Bug 34188: DBRev 23.06.00.072
[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 use Encode qw( encode_utf8 );
38 # Koha modules
39 use C4::Context;
40 use C4::Installer;
41 use Koha::Database;
42 use Koha;
43 use Koha::DateUtils qw( dt_from_string output_pref );
44 use Koha::Caches;
45
46 use MARC::Record;
47 use MARC::File::XML ( BinaryEncoding => 'utf8' );
48
49 use File::Path qw[remove_tree]; # perl core module
50
51 # FIXME - The user might be installing a new database, so can't rely
52 # on /etc/koha.conf anyway.
53
54 my (
55     $sth,
56     $query,
57     $table,
58     $type,
59 );
60
61 my $schema = Koha::Database->new()->schema();
62
63 my ( $silent, $force );
64 GetOptions(
65     's'     => \$silent,
66     'force' => \$force,
67 );
68 my $dbh = C4::Context->dbh;
69 $|=1; # flushes output
70
71 local $dbh->{RaiseError} = 0;
72
73 # Flush memcached before we begin
74 Koha::Caches->get_instance('config')->flush_all;
75 Koha::Caches->get_instance('sysprefs')->flush_all;
76
77 # Record the version we are coming from
78 my $original_version = C4::Context->preference("Version");
79
80 # Deal with virtualshelves
81 my $DBversion = "3.00.00.001";
82 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
83     # update virtualshelves table to
84     #
85     $dbh->do("ALTER TABLE `bookshelf` RENAME `virtualshelves`");
86     $dbh->do("ALTER TABLE `shelfcontents` RENAME `virtualshelfcontents`");
87     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD `biblionumber` INT( 11 ) NOT NULL default '0' AFTER shelfnumber");
88     $dbh->do("UPDATE `virtualshelfcontents` SET biblionumber=(SELECT biblionumber FROM items WHERE items.itemnumber=virtualshelfcontents.itemnumber)");
89     # drop all foreign keys : otherwise, we can't drop itemnumber field.
90     DropAllForeignKeys('virtualshelfcontents');
91     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD KEY biblionumber (biblionumber)");
92     # create the new foreign keys (on biblionumber)
93     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD CONSTRAINT `virtualshelfcontents_ibfk_1` FOREIGN KEY (`shelfnumber`) REFERENCES `virtualshelves` (`shelfnumber`) ON DELETE CASCADE ON UPDATE CASCADE");
94     # re-create the foreign key on virtualshelf
95     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD CONSTRAINT `shelfcontents_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE");
96     $dbh->do("ALTER TABLE `virtualshelfcontents` DROP `itemnumber`");
97     print "Upgrade to $DBversion done (virtualshelves)\n";
98     SetVersion ($DBversion);
99 }
100
101
102 $DBversion = "3.00.00.002";
103 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
104     $dbh->do("DROP TABLE sessions");
105     $dbh->do("CREATE TABLE `sessions` (
106   `id` varchar(32) NOT NULL,
107   `a_session` text NOT NULL,
108   UNIQUE KEY `id` (`id`)
109 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
110     print "Upgrade to $DBversion done (sessions uses CGI::session, new table structure for sessions)\n";
111     SetVersion ($DBversion);
112 }
113
114
115 $DBversion = "3.00.00.003";
116 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
117     if (C4::Context->preference("opaclanguages") eq "fr") {
118         $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')");
119     } else {
120         $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')");
121     }
122     print "Upgrade to $DBversion done (adding ReservesNeedReturns systempref, in circulation)\n";
123     SetVersion ($DBversion);
124 }
125
126
127 $DBversion = "3.00.00.004";
128 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
129     $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')");
130     print "Upgrade to $DBversion done (adding DebugLevel systempref, in 'Admin' tab)\n";
131     SetVersion ($DBversion);
132 }
133
134 $DBversion = "3.00.00.005";
135 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
136     $dbh->do("CREATE TABLE `tags` (
137                     `entry` varchar(255) NOT NULL default '',
138                     `weight` bigint(20) NOT NULL default 0,
139                     PRIMARY KEY  (`entry`)
140                     ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
141                 ");
142         $dbh->do("CREATE TABLE `nozebra` (
143                 `server` varchar(20)     NOT NULL,
144                 `indexname` varchar(40)  NOT NULL,
145                 `value` varchar(250)     NOT NULL,
146                 `biblionumbers` longtext NOT NULL,
147                 KEY `indexname` (`server`,`indexname`),
148                 KEY `value` (`server`,`value`))
149                 ENGINE=InnoDB DEFAULT CHARSET=utf8;
150                 ");
151     print "Upgrade to $DBversion done (adding tags and nozebra tables )\n";
152     SetVersion ($DBversion);
153 }
154
155 $DBversion = "3.00.00.006";
156 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
157     sanitize_zero_date('issues', 'issuedate');
158     print "Upgrade to $DBversion done (filled issues.issuedate with timestamp)\n";
159     SetVersion ($DBversion);
160 }
161
162 $DBversion = "3.00.00.007";
163 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
164     $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')");
165     print "Upgrade to $DBversion done (set SessionStorage variable)\n";
166     SetVersion ($DBversion);
167 }
168
169 $DBversion = "3.00.00.008";
170 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
171     $dbh->do("ALTER TABLE `biblio` ADD `datecreated` DATE NOT NULL AFTER `timestamp` ;");
172     $dbh->do("UPDATE biblio SET datecreated=timestamp");
173     print "Upgrade to $DBversion done (biblio creation date)\n";
174     SetVersion ($DBversion);
175 }
176
177 $DBversion = "3.00.00.009";
178 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
179
180     # Create backups of call number columns
181     # in case default migration needs to be customized
182     #
183     # UPGRADE NOTE: temp_upg_biblioitems_call_num should be dropped
184     #               after call numbers have been transformed to the new structure
185     #
186     # Not bothering to do the same with deletedbiblioitems -- assume
187     # default is good enough.
188     $dbh->do("CREATE TABLE `temp_upg_biblioitems_call_num` AS
189               SELECT `biblioitemnumber`, `biblionumber`,
190                      `classification`, `dewey`, `subclass`,
191                      `lcsort`, `ccode`
192               FROM `biblioitems`");
193
194     # biblioitems changes
195     $dbh->do("ALTER TABLE `biblioitems` CHANGE COLUMN `volumeddesc` `volumedesc` TEXT,
196                                     ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
197                                     ADD `cn_class` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
198                                     ADD `cn_item` VARCHAR(10) DEFAULT NULL AFTER `cn_class`,
199                                     ADD `cn_suffix` VARCHAR(10) DEFAULT NULL AFTER `cn_item`,
200                                     ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_suffix`,
201                                     ADD `totalissues` INT(10) AFTER `cn_sort`");
202
203     # default mapping of call number columns:
204     #   cn_class = concatentation of classification + dewey,
205     #              trimmed to fit -- assumes that most users do not
206     #              populate both classification and dewey in a single record
207     #   cn_item  = subclass
208     #   cn_source = left null
209     #   cn_sort = lcsort
210     #
211     # After upgrade, cn_sort will have to be set based on whatever
212     # default call number scheme user sets as a preference.  Misc
213     # script will be added at some point to do that.
214     #
215     $dbh->do("UPDATE `biblioitems`
216               SET cn_class = SUBSTR(TRIM(CONCAT_WS(' ', `classification`, `dewey`)), 1, 30),
217                     cn_item = subclass,
218                     `cn_sort` = `lcsort`
219             ");
220
221     # Now drop the old call number columns
222     $dbh->do("ALTER TABLE `biblioitems` DROP COLUMN `classification`,
223                                         DROP COLUMN `dewey`,
224                                         DROP COLUMN `subclass`,
225                                         DROP COLUMN `lcsort`,
226                                         DROP COLUMN `ccode`");
227
228     # deletedbiblio changes
229     $dbh->do("ALTER TABLE `deletedbiblio` ALTER COLUMN `frameworkcode` SET DEFAULT '',
230                                         DROP COLUMN `marc`,
231                                         ADD `datecreated` DATE NOT NULL AFTER `timestamp`");
232     $dbh->do("UPDATE deletedbiblio SET datecreated = timestamp");
233
234     # deletedbiblioitems changes
235     $dbh->do("ALTER TABLE `deletedbiblioitems`
236                         MODIFY `publicationyear` TEXT,
237                         CHANGE `volumeddesc` `volumedesc` TEXT,
238                         MODIFY `collectiontitle` MEDIUMTEXT DEFAULT NULL AFTER `volumedesc`,
239                         MODIFY `collectionissn` TEXT DEFAULT NULL AFTER `collectiontitle`,
240                         MODIFY `collectionvolume` MEDIUMTEXT DEFAULT NULL AFTER `collectionissn`,
241                         MODIFY `editionstatement` TEXT DEFAULT NULL AFTER `collectionvolume`,
242                         MODIFY `editionresponsibility` TEXT DEFAULT NULL AFTER `editionstatement`,
243                         MODIFY `place` VARCHAR(255) DEFAULT NULL AFTER `size`,
244                         MODIFY `marc` LONGBLOB,
245                         ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `url`,
246                         ADD `cn_class` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
247                         ADD `cn_item` VARCHAR(10) DEFAULT NULL AFTER `cn_class`,
248                         ADD `cn_suffix` VARCHAR(10) DEFAULT NULL AFTER `cn_item`,
249                         ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_suffix`,
250                         ADD `totalissues` INT(10) AFTER `cn_sort`,
251                         ADD `marcxml` LONGTEXT NOT NULL AFTER `totalissues`,
252                         ADD KEY `isbn` (`isbn`),
253                         ADD KEY `publishercode` (`publishercode`)
254                     ");
255
256     $dbh->do("UPDATE `deletedbiblioitems`
257                 SET `cn_class` = SUBSTR(TRIM(CONCAT_WS(' ', `classification`, `dewey`)), 1, 30),
258                `cn_item` = `subclass`,
259                 `cn_sort` = `lcsort`
260             ");
261     $dbh->do("ALTER TABLE `deletedbiblioitems`
262                         DROP COLUMN `classification`,
263                         DROP COLUMN `dewey`,
264                         DROP COLUMN `subclass`,
265                         DROP COLUMN `lcsort`,
266                         DROP COLUMN `ccode`
267             ");
268
269     # deleteditems changes
270     $dbh->do("ALTER TABLE `deleteditems`
271                         MODIFY `barcode` VARCHAR(20) DEFAULT NULL,
272                         MODIFY `price` DECIMAL(8,2) DEFAULT NULL,
273                         MODIFY `replacementprice` DECIMAL(8,2) DEFAULT NULL,
274                         DROP `bulk`,
275                         MODIFY `itemcallnumber` VARCHAR(30) DEFAULT NULL AFTER `wthdrawn`,
276                         MODIFY `holdingbranch` VARCHAR(10) DEFAULT NULL,
277                         DROP `interim`,
278                         MODIFY `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP AFTER `paidfor`,
279                         DROP `cutterextra`,
280                         ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `onloan`,
281                         ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
282                         ADD `ccode` VARCHAR(10) DEFAULT NULL AFTER `cn_sort`,
283                         ADD `materials` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
284                         ADD `uri` VARCHAR(255) DEFAULT NULL AFTER `materials`,
285                         MODIFY `marc` LONGBLOB AFTER `uri`,
286                         DROP KEY `barcode`,
287                         DROP KEY `itembarcodeidx`,
288                         DROP KEY `itembinoidx`,
289                         DROP KEY `itembibnoidx`,
290                         ADD UNIQUE KEY `delitembarcodeidx` (`barcode`),
291                         ADD KEY `delitembinoidx` (`biblioitemnumber`),
292                         ADD KEY `delitembibnoidx` (`biblionumber`),
293                         ADD KEY `delhomebranch` (`homebranch`),
294                         ADD KEY `delholdingbranch` (`holdingbranch`)");
295     $dbh->do("UPDATE deleteditems SET `ccode` = `itype`");
296     $dbh->do("ALTER TABLE deleteditems DROP `itype`");
297     $dbh->do("UPDATE `deleteditems` SET `cn_sort` = `itemcallnumber`");
298
299     # items changes
300     $dbh->do("ALTER TABLE `items` ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `onloan`,
301                                 ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
302                                 ADD `ccode` VARCHAR(10) DEFAULT NULL AFTER `cn_sort`,
303                                 ADD `materials` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
304                                 ADD `uri` VARCHAR(255) DEFAULT NULL AFTER `materials`
305             ");
306     $dbh->do("ALTER TABLE `items`
307                         DROP KEY `itembarcodeidx`,
308                         ADD UNIQUE KEY `itembarcodeidx` (`barcode`)");
309
310     # map items.itype to items.ccode and
311     # set cn_sort to itemcallnumber -- as with biblioitems.cn_sort,
312     # will have to be subsequently updated per user's default
313     # classification scheme
314     $dbh->do("UPDATE `items` SET `cn_sort` = `itemcallnumber`,
315                             `ccode` = `itype`");
316
317     $dbh->do("ALTER TABLE `items` DROP `cutterextra`,
318                                 DROP `itype`");
319
320     print "Upgrade to $DBversion done (major changes to biblio, biblioitems, items, and deleted* versions of same\n";
321     SetVersion ($DBversion);
322 }
323
324 $DBversion = "3.00.00.010";
325 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
326     $dbh->do("CREATE INDEX `userid` ON borrowers (`userid`) ");
327     print "Upgrade to $DBversion done (userid index added)\n";
328     SetVersion ($DBversion);
329 }
330
331 $DBversion = "3.00.00.011";
332 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
333     $dbh->do("ALTER TABLE `branchcategories` CHANGE `categorycode` `categorycode` varchar(10) ");
334     $dbh->do("ALTER TABLE `branchcategories` CHANGE `categoryname` `categoryname` varchar(32) ");
335     $dbh->do("ALTER TABLE `branchcategories` ADD COLUMN `categorytype` varchar(16) ");
336     $dbh->do("UPDATE `branchcategories` SET `categorytype` = 'properties'");
337     $dbh->do("ALTER TABLE `branchrelations` CHANGE `categorycode` `categorycode` varchar(10) ");
338     print "Upgrade to $DBversion done (added branchcategory type)\n";
339     SetVersion ($DBversion);
340 }
341
342 $DBversion = "3.00.00.012";
343 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
344     $dbh->do("CREATE TABLE `class_sort_rules` (
345                                `class_sort_rule` varchar(10) NOT NULL default '',
346                                `description` mediumtext,
347                                `sort_routine` varchar(30) NOT NULL default '',
348                                PRIMARY KEY (`class_sort_rule`),
349                                UNIQUE KEY `class_sort_rule_idx` (`class_sort_rule`)
350                              ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
351     $dbh->do("CREATE TABLE `class_sources` (
352                                `cn_source` varchar(10) NOT NULL default '',
353                                `description` mediumtext,
354                                `used` tinyint(4) NOT NULL default 0,
355                                `class_sort_rule` varchar(10) NOT NULL default '',
356                                PRIMARY KEY (`cn_source`),
357                                UNIQUE KEY `cn_source_idx` (`cn_source`),
358                                KEY `used_idx` (`used`),
359                                CONSTRAINT `class_source_ibfk_1` FOREIGN KEY (`class_sort_rule`)
360                                           REFERENCES `class_sort_rules` (`class_sort_rule`)
361                              ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
362     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type)
363               VALUES('DefaultClassificationSource','ddc',
364                      'Default classification scheme used by the collection. E.g., Dewey, LCC, etc.', NULL,'free')");
365     $dbh->do("INSERT INTO `class_sort_rules` (`class_sort_rule`, `description`, `sort_routine`) VALUES
366                                ('dewey', 'Default filing rules for DDC', 'Dewey'),
367                                ('lcc', 'Default filing rules for LCC', 'LCC'),
368                                ('generic', 'Generic call number filing rules', 'Generic')");
369     $dbh->do("INSERT INTO `class_sources` (`cn_source`, `description`, `used`, `class_sort_rule`) VALUES
370                             ('ddc', 'Dewey Decimal Classification', 1, 'dewey'),
371                             ('lcc', 'Library of Congress Classification', 1, 'lcc'),
372                             ('udc', 'Universal Decimal Classification', 0, 'generic'),
373                             ('sudocs', 'SuDoc Classification (U.S. GPO)', 0, 'generic'),
374                             ('z', 'Other/Generic Classification Scheme', 0, 'generic')");
375     print "Upgrade to $DBversion done (classification sources added)\n";
376     SetVersion ($DBversion);
377 }
378
379 $DBversion = "3.00.00.013";
380 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
381     $dbh->do("CREATE TABLE `import_batches` (
382               `import_batch_id` int(11) NOT NULL auto_increment,
383               `template_id` int(11) default NULL,
384               `branchcode` varchar(10) default NULL,
385               `num_biblios` int(11) NOT NULL default 0,
386               `num_items` int(11) NOT NULL default 0,
387               `upload_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
388               `overlay_action` enum('replace', 'create_new', 'use_template') NOT NULL default 'create_new',
389               `import_status` enum('staging', 'staged', 'importing', 'imported', 'reverting', 'reverted', 'cleaned') NOT NULL default 'staging',
390               `batch_type` enum('batch', 'z3950') NOT NULL default 'batch',
391               `file_name` varchar(100),
392               `comments` mediumtext,
393               PRIMARY KEY (`import_batch_id`),
394               KEY `branchcode` (`branchcode`)
395               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
396     $dbh->do("CREATE TABLE `import_records` (
397               `import_record_id` int(11) NOT NULL auto_increment,
398               `import_batch_id` int(11) NOT NULL,
399               `branchcode` varchar(10) default NULL,
400               `record_sequence` int(11) NOT NULL default 0,
401               `upload_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
402               `import_date` DATE default NULL,
403               `marc` longblob NOT NULL,
404               `marcxml` longtext NOT NULL,
405               `marcxml_old` longtext NOT NULL,
406               `record_type` enum('biblio', 'auth', 'holdings') NOT NULL default 'biblio',
407               `overlay_status` enum('no_match', 'auto_match', 'manual_match', 'match_applied') NOT NULL default 'no_match',
408               `status` enum('error', 'staged', 'imported', 'reverted', 'items_reverted') NOT NULL default 'staged',
409               `import_error` mediumtext,
410               `encoding` varchar(40) NOT NULL default '',
411               `z3950random` varchar(40) default NULL,
412               PRIMARY KEY (`import_record_id`),
413               CONSTRAINT `import_records_ifbk_1` FOREIGN KEY (`import_batch_id`)
414                           REFERENCES `import_batches` (`import_batch_id`) ON DELETE CASCADE ON UPDATE CASCADE,
415               KEY `branchcode` (`branchcode`),
416               KEY `batch_sequence` (`import_batch_id`, `record_sequence`)
417               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
418     $dbh->do("CREATE TABLE `import_record_matches` (
419               `import_record_id` int(11) NOT NULL,
420               `candidate_match_id` int(11) NOT NULL,
421               `score` int(11) NOT NULL default 0,
422               CONSTRAINT `import_record_matches_ibfk_1` FOREIGN KEY (`import_record_id`)
423                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
424               KEY `record_score` (`import_record_id`, `score`)
425               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
426     $dbh->do("CREATE TABLE `import_biblios` (
427               `import_record_id` int(11) NOT NULL,
428               `matched_biblionumber` int(11) default NULL,
429               `control_number` varchar(25) default NULL,
430               `original_source` varchar(25) default NULL,
431               `title` varchar(128) default NULL,
432               `author` varchar(80) default NULL,
433               `isbn` varchar(14) default NULL,
434               `issn` varchar(9) default NULL,
435               `has_items` tinyint(1) NOT NULL default 0,
436               CONSTRAINT `import_biblios_ibfk_1` FOREIGN KEY (`import_record_id`)
437                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
438               KEY `matched_biblionumber` (`matched_biblionumber`),
439               KEY `title` (`title`),
440               KEY `isbn` (`isbn`)
441               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
442     $dbh->do("CREATE TABLE `import_items` (
443               `import_items_id` int(11) NOT NULL auto_increment,
444               `import_record_id` int(11) NOT NULL,
445               `itemnumber` int(11) default NULL,
446               `branchcode` varchar(10) default NULL,
447               `status` enum('error', 'staged', 'imported', 'reverted') NOT NULL default 'staged',
448               `marcxml` longtext NOT NULL,
449               `import_error` mediumtext,
450               PRIMARY KEY (`import_items_id`),
451               CONSTRAINT `import_items_ibfk_1` FOREIGN KEY (`import_record_id`)
452                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
453               KEY `itemnumber` (`itemnumber`),
454               KEY `branchcode` (`branchcode`)
455               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
456
457     $dbh->do("INSERT INTO `import_batches`
458                 (`overlay_action`, `import_status`, `batch_type`, `file_name`)
459               SELECT distinct 'create_new', 'staged', 'z3950', `file`
460               FROM   `marc_breeding`");
461
462     $dbh->do("INSERT INTO `import_records`
463                 (`import_batch_id`, `import_record_id`, `record_sequence`, `marc`, `record_type`, `status`,
464                 `encoding`, `z3950random`, `marcxml`, `marcxml_old`)
465               SELECT `import_batch_id`, `id`, 1, `marc`, 'biblio', 'staged', `encoding`, `z3950random`, '', ''
466               FROM `marc_breeding`
467               JOIN `import_batches` ON (`file_name` = `file`)");
468
469     $dbh->do("INSERT INTO `import_biblios`
470                 (`import_record_id`, `title`, `author`, `isbn`)
471               SELECT `import_record_id`, `title`, `author`, `isbn`
472               FROM   `marc_breeding`
473               JOIN   `import_records` ON (`import_record_id` = `id`)");
474
475     $dbh->do("UPDATE `import_batches`
476               SET `num_biblios` = (
477               SELECT COUNT(*)
478               FROM `import_records`
479               WHERE `import_batch_id` = `import_batches`.`import_batch_id`
480               )");
481
482     $dbh->do("DROP TABLE `marc_breeding`");
483
484     print "Upgrade to $DBversion done (import_batches et al. added)\n";
485     SetVersion ($DBversion);
486 }
487
488 $DBversion = "3.00.00.014";
489 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
490     $dbh->do("ALTER TABLE subscription ADD lastbranch VARCHAR(4)");
491     print "Upgrade to $DBversion done (userid index added)\n";
492     SetVersion ($DBversion);
493 }
494
495 $DBversion = "3.00.00.015";
496 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
497     $dbh->do("CREATE TABLE `saved_sql` (
498            `id` int(11) NOT NULL auto_increment,
499            `borrowernumber` int(11) default NULL,
500            `date_created` datetime default NULL,
501            `last_modified` datetime default NULL,
502            `savedsql` text,
503            `last_run` datetime default NULL,
504            `report_name` varchar(255) default NULL,
505            `type` varchar(255) default NULL,
506            `notes` text,
507            PRIMARY KEY  (`id`),
508            KEY boridx (`borrowernumber`)
509         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
510     $dbh->do("CREATE TABLE `saved_reports` (
511            `id` int(11) NOT NULL auto_increment,
512            `report_id` int(11) default NULL,
513            `report` longtext,
514            `date_run` datetime default NULL,
515            PRIMARY KEY  (`id`)
516         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
517     print "Upgrade to $DBversion done (saved_sql and saved_reports added)\n";
518     SetVersion ($DBversion);
519 }
520
521 $DBversion = "3.00.00.016";
522 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
523     $dbh->do(" CREATE TABLE reports_dictionary (
524           id int(11) NOT NULL auto_increment,
525           name varchar(255) default NULL,
526           description text,
527           date_created datetime default NULL,
528           date_modified datetime default NULL,
529           saved_sql text,
530           area int(11) default NULL,
531           PRIMARY KEY  (id)
532         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
533     print "Upgrade to $DBversion done (reports_dictionary) added)\n";
534     SetVersion ($DBversion);
535 }
536
537 $DBversion = "3.00.00.017";
538 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
539     $dbh->do("ALTER TABLE action_logs DROP PRIMARY KEY");
540     $dbh->do("ALTER TABLE action_logs ADD KEY  timestamp (timestamp,user)");
541     $dbh->do("ALTER TABLE action_logs ADD action_id INT(11) NOT NULL FIRST");
542     $dbh->do("UPDATE action_logs SET action_id = if (\@a, \@a:=\@a+1, \@a:=1)");
543     $dbh->do("ALTER TABLE action_logs MODIFY action_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY");
544     print "Upgrade to $DBversion done (added column to action_logs)\n";
545     SetVersion ($DBversion);
546 }
547
548 $DBversion = "3.00.00.018";
549 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
550     $dbh->do("ALTER TABLE `zebraqueue`
551                     ADD `done` INT NOT NULL DEFAULT '0',
552                     ADD `time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ;
553             ");
554     print "Upgrade to $DBversion done (adding timestamp and done columns to zebraque table to improve problem tracking) added)\n";
555     SetVersion ($DBversion);
556 }
557
558 $DBversion = "3.00.00.019";
559 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
560     $dbh->do("ALTER TABLE biblio MODIFY biblionumber INT(11) NOT NULL AUTO_INCREMENT");
561     $dbh->do("ALTER TABLE biblioitems MODIFY biblioitemnumber INT(11) NOT NULL AUTO_INCREMENT");
562     $dbh->do("ALTER TABLE items MODIFY itemnumber INT(11) NOT NULL AUTO_INCREMENT");
563     print "Upgrade to $DBversion done (made bib/item PKs auto_increment)\n";
564     SetVersion ($DBversion);
565 }
566
567 $DBversion = "3.00.00.020";
568 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
569     $dbh->do("ALTER TABLE deleteditems
570               DROP KEY `delitembarcodeidx`,
571               ADD KEY `delitembarcodeidx` (`barcode`)");
572     print "Upgrade to $DBversion done (dropped uniqueness of key on deleteditems.barcode)\n";
573     SetVersion ($DBversion);
574 }
575
576 $DBversion = "3.00.00.021";
577 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
578     $dbh->do("ALTER TABLE items CHANGE homebranch homebranch VARCHAR(10)");
579     $dbh->do("ALTER TABLE deleteditems CHANGE homebranch homebranch VARCHAR(10)");
580     $dbh->do("ALTER TABLE statistics CHANGE branch branch VARCHAR(10)");
581     $dbh->do("ALTER TABLE subscription CHANGE lastbranch lastbranch VARCHAR(10)");
582     print "Upgrade to $DBversion done (extended missed branchcode columns to 10 chars)\n";
583     SetVersion ($DBversion);
584 }
585
586 $DBversion = "3.00.00.022";
587 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
588     $dbh->do("ALTER TABLE items
589                 ADD `damaged` tinyint(1) default NULL AFTER notforloan");
590     $dbh->do("ALTER TABLE deleteditems
591                 ADD `damaged` tinyint(1) default NULL AFTER notforloan");
592     print "Upgrade to $DBversion done (adding damaged column to items table)\n";
593     SetVersion ($DBversion);
594 }
595
596 $DBversion = "3.00.00.023";
597 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
598      $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
599          VALUES ('yuipath','http://yui.yahooapis.com/2.3.1/build','Insert the path to YUI libraries','','free')");
600     print "Upgrade to $DBversion done (adding new system preference for controlling YUI path)\n";
601     SetVersion ($DBversion);
602 }
603 $DBversion = "3.00.00.024";
604 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
605     $dbh->do("ALTER TABLE biblioitems CHANGE  itemtype itemtype VARCHAR(10)");
606     print "Upgrade to $DBversion done (changing itemtype to (10))\n";
607     SetVersion ($DBversion);
608 }
609
610 $DBversion = "3.00.00.025";
611 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
612     $dbh->do("ALTER TABLE items ADD COLUMN itype VARCHAR(10)");
613     $dbh->do("ALTER TABLE deleteditems ADD COLUMN itype VARCHAR(10) AFTER uri");
614     if(C4::Context->preference('item-level_itypes')){
615         $dbh->do('update items,biblioitems set items.itype=biblioitems.itemtype where items.biblionumber=biblioitems.biblionumber and itype is null');
616     }
617     print "Upgrade to $DBversion done (reintroduce items.itype - fill from itemtype)\n ";
618     SetVersion ($DBversion);
619 }
620
621 $DBversion = "3.00.00.026";
622 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
623     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
624        VALUES ('HomeOrHoldingBranch','homebranch','homebranch|holdingbranch','With independent branches turned on this decides whether to check the items holdingbranch or homebranch at circulatilon','choice')");
625     print "Upgrade to $DBversion done (adding new system preference for choosing whether homebranch or holdingbranch is checked in circulation)\n";
626     SetVersion ($DBversion);
627 }
628
629 $DBversion = "3.00.00.027";
630 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
631     $dbh->do("CREATE TABLE `marc_matchers` (
632                 `matcher_id` int(11) NOT NULL auto_increment,
633                 `code` varchar(10) NOT NULL default '',
634                 `description` varchar(255) NOT NULL default '',
635                 `record_type` varchar(10) NOT NULL default 'biblio',
636                 `threshold` int(11) NOT NULL default 0,
637                 PRIMARY KEY (`matcher_id`),
638                 KEY `code` (`code`),
639                 KEY `record_type` (`record_type`)
640               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
641     $dbh->do("CREATE TABLE `matchpoints` (
642                 `matcher_id` int(11) NOT NULL,
643                 `matchpoint_id` int(11) NOT NULL auto_increment,
644                 `search_index` varchar(30) NOT NULL default '',
645                 `score` int(11) NOT NULL default 0,
646                 PRIMARY KEY (`matchpoint_id`),
647                 CONSTRAINT `matchpoints_ifbk_1` FOREIGN KEY (`matcher_id`)
648                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE
649               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
650     $dbh->do("CREATE TABLE `matchpoint_components` (
651                 `matchpoint_id` int(11) NOT NULL,
652                 `matchpoint_component_id` int(11) NOT NULL auto_increment,
653                 sequence int(11) NOT NULL default 0,
654                 tag varchar(3) NOT NULL default '',
655                 subfields varchar(40) NOT NULL default '',
656                 offset int(4) NOT NULL default 0,
657                 length int(4) NOT NULL default 0,
658                 PRIMARY KEY (`matchpoint_component_id`),
659                 KEY `by_sequence` (`matchpoint_id`, `sequence`),
660                 CONSTRAINT `matchpoint_components_ifbk_1` FOREIGN KEY (`matchpoint_id`)
661                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
662               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
663     $dbh->do("CREATE TABLE `matchpoint_component_norms` (
664                 `matchpoint_component_id` int(11) NOT NULL,
665                 `sequence`  int(11) NOT NULL default 0,
666                 `norm_routine` varchar(50) NOT NULL default '',
667                 KEY `matchpoint_component_norms` (`matchpoint_component_id`, `sequence`),
668                 CONSTRAINT `matchpoint_component_norms_ifbk_1` FOREIGN KEY (`matchpoint_component_id`)
669                            REFERENCES `matchpoint_components` (`matchpoint_component_id`) ON DELETE CASCADE ON UPDATE CASCADE
670               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
671     $dbh->do("CREATE TABLE `matcher_matchpoints` (
672                 `matcher_id` int(11) NOT NULL,
673                 `matchpoint_id` int(11) NOT NULL,
674                 CONSTRAINT `matcher_matchpoints_ifbk_1` FOREIGN KEY (`matcher_id`)
675                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE,
676                 CONSTRAINT `matcher_matchpoints_ifbk_2` FOREIGN KEY (`matchpoint_id`)
677                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
678               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
679     $dbh->do("CREATE TABLE `matchchecks` (
680                 `matcher_id` int(11) NOT NULL,
681                 `matchcheck_id` int(11) NOT NULL auto_increment,
682                 `source_matchpoint_id` int(11) NOT NULL,
683                 `target_matchpoint_id` int(11) NOT NULL,
684                 PRIMARY KEY (`matchcheck_id`),
685                 CONSTRAINT `matcher_matchchecks_ifbk_1` FOREIGN KEY (`matcher_id`)
686                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE,
687                 CONSTRAINT `matcher_matchchecks_ifbk_2` FOREIGN KEY (`source_matchpoint_id`)
688                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE,
689                 CONSTRAINT `matcher_matchchecks_ifbk_3` FOREIGN KEY (`target_matchpoint_id`)
690                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
691               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
692     print "Upgrade to $DBversion done (added C4::Matcher serialization tables)\n ";
693     SetVersion ($DBversion);
694 }
695
696 $DBversion = "3.00.00.028";
697 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
698     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
699        VALUES ('canreservefromotherbranches','1','','With Independent branches on, can a user from one library reserve an item from another library','YesNo')");
700     print "Upgrade to $DBversion done (adding new system preference for changing reserve/holds behaviour with independent branches)\n";
701     SetVersion ($DBversion);
702 }
703
704
705 $DBversion = "3.00.00.029";
706 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
707     $dbh->do("ALTER TABLE `import_batches` ADD `matcher_id` int(11) NULL AFTER `import_batch_id`");
708     print "Upgrade to $DBversion done (adding matcher_id to import_batches)\n";
709     SetVersion ($DBversion);
710 }
711
712 $DBversion = "3.00.00.030";
713 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
714     $dbh->do("
715 CREATE TABLE services_throttle (
716   service_type varchar(10) NOT NULL default '',
717   service_count varchar(45) default NULL,
718   PRIMARY KEY  (service_type)
719 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
720 ");
721     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
722        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')");
723  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
724        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')");
725  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
726        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')");
727  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
728        VALUES ('XISBNDailyLimit',499,'','The xISBN Web service is free for non-commercial use when usage does not exceed 500 requests per day','free')");
729  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
730        VALUES ('PINESISBN',0,'','Use with FRBRizeEditions. If ON, Koha will use PINES OISBN web service in the Editions tab on the detail pages.','YesNo')");
731  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
732        VALUES ('ThingISBN',0,'','Use with FRBRizeEditions. If ON, Koha will use the ThingISBN web service in the Editions tab on the detail pages.','YesNo')");
733     print "Upgrade to $DBversion done (adding services throttle table and sysprefs for xISBN)\n";
734     SetVersion ($DBversion);
735 }
736
737 $DBversion = "3.00.00.031";
738 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
739
740 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryStemming',1,'If ON, enables query stemming',NULL,'YesNo')");
741 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryFuzzy',1,'If ON, enables fuzzy option for searches',NULL,'YesNo')");
742 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryWeightFields',1,'If ON, enables field weighting',NULL,'YesNo')");
743 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('WebBasedSelfCheck',0,'If ON, enables the web-based self-check system',NULL,'YesNo')");
744 $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')");
745 $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')");
746 $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')");
747 $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')");
748 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('defaultSortOrder',NULL,'Specify the default sort order','asc|dsc|az|za','Choice')");
749 $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')");
750 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACdefaultSortOrder',NULL,'Specify the default sort order','asc|dsc|za|az','Choice')");
751 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('staffClientBaseURL','','Specify the base URL of the staff client',NULL,'free')");
752 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('minPasswordLength',3,'Specify the minimum length of a patron/staff password',NULL,'free')");
753 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('noItemTypeImages',0,'If ON, disables item-type images',NULL,'YesNo')");
754 $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')");
755 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('holdCancelLength','','Specify how many days before a hold is canceled',NULL,'free')");
756 $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')");
757 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('finesMode','test','Choose the fines mode, test or production','test|production','Choice')");
758 $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')");
759 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('itemBarcodeInputFilter','','If set, allows specification of a item barcode input filter','cuecat','Choice')");
760 $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')");
761 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('URLLinkText','','Text to display as the link anchor in the OPAC',NULL,'free')");
762 $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')");
763 $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')");
764 $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')");
765 $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')");
766 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACUserCSS',0,'Add CSS to be included in the OPAC',NULL,'free')");
767
768     print "Upgrade to $DBversion done (adding additional system preference)\n";
769     SetVersion ($DBversion);
770 }
771
772 $DBversion = "3.00.00.032";
773 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
774     $dbh->do("UPDATE `marc_subfield_structure` SET `kohafield` = 'items.wthdrawn' WHERE `kohafield` = 'items.withdrawn'");
775     print "Upgrade to $DBversion done (fixed MARC framework references to items.withdrawn)\n";
776     SetVersion ($DBversion);
777 }
778
779 $DBversion = "3.00.00.033";
780 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
781     $dbh->do("INSERT INTO `userflags` VALUES(17,'staffaccess','Modify login / permissions for staff users',0)");
782     print "Upgrade to $DBversion done (Adding permissions flag for staff member access modification.  )\n";
783     SetVersion ($DBversion);
784 }
785
786 $DBversion = "3.00.00.034";
787 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
788     $dbh->do("ALTER TABLE `virtualshelves` ADD COLUMN `sortfield` VARCHAR(16) ");
789     print "Upgrade to $DBversion done (Adding sortfield for Virtual Shelves.  )\n";
790     SetVersion ($DBversion);
791 }
792
793 $DBversion = "3.00.00.035";
794 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
795     $dbh->do("UPDATE marc_subfield_structure
796               SET authorised_value = 'cn_source'
797               WHERE kohafield IN ('items.cn_source', 'biblioitems.cn_source')
798               AND (authorised_value is NULL OR authorised_value = '')");
799     print "Upgrade to $DBversion done (MARC frameworks: make classification source a drop-down)\n";
800     SetVersion ($DBversion);
801 }
802
803 $DBversion = "3.00.00.036";
804 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
805     $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');");
806     print "Upgrade to $DBversion done (OPACItemsResultsDisplay systempreference added)\n";
807     SetVersion ($DBversion);
808 }
809
810 $DBversion = "3.00.00.037";
811 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
812     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactfirstname` varchar(255)");
813     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactsurname` varchar(255)");
814     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress1` varchar(255)");
815     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress2` varchar(255)");
816     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress3` varchar(255)");
817     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactzipcode` varchar(50)");
818     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactphone` varchar(50)");
819     print "Upgrade to $DBversion done (Adding Alternative Contact Person information to borrowers table)\n";
820     SetVersion ($DBversion);
821 }
822
823 $DBversion = "3.00.00.038";
824 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
825     $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'");
826     $dbh->do("DELETE FROM `systempreferences` WHERE variable='hideBiblioNumber'");
827     print "Upgrade to $DBversion done ('alter finesMode systempreference, remove superfluous syspref.')\n";
828     SetVersion ($DBversion);
829 }
830
831 $DBversion = "3.00.00.039";
832 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
833     $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')");
834     $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')");
835     $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')");
836     # $dbh->do("DELETE FROM `systempreferences` WHERE variable='HomeOrHoldingBranch'"); # Bug #2752
837     print "Upgrade to $DBversion done ('add circ sysprefs CircControl, finesCalendar, and uppercasesurnames, and delete HomeOrHoldingBranch.')\n";
838     SetVersion ($DBversion);
839 }
840
841 $DBversion = "3.00.00.040";
842 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
843         $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')");
844         $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')");
845         print "Upgrade to $DBversion done ('add circ sysprefs todaysIssuesDefaultSortOrder and previousIssuesDefaultSortOrder.')\n";
846     SetVersion ($DBversion);
847 }
848
849
850 $DBversion = "3.00.00.041";
851 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
852     # Strictly speaking it is not necessary to explicitly change
853     # NULL values to 0, because the ALTER TABLE statement will do that.
854     # However, setting them first avoids a warning.
855     $dbh->do("UPDATE items SET notforloan = 0 WHERE notforloan IS NULL");
856     $dbh->do("UPDATE items SET damaged = 0 WHERE damaged IS NULL");
857     $dbh->do("UPDATE items SET itemlost = 0 WHERE itemlost IS NULL");
858     $dbh->do("UPDATE items SET wthdrawn = 0 WHERE wthdrawn IS NULL");
859     $dbh->do("ALTER TABLE items
860                 MODIFY notforloan tinyint(1) NOT NULL default 0,
861                 MODIFY damaged    tinyint(1) NOT NULL default 0,
862                 MODIFY itemlost   tinyint(1) NOT NULL default 0,
863                 MODIFY wthdrawn   tinyint(1) NOT NULL default 0");
864     $dbh->do("UPDATE deleteditems SET notforloan = 0 WHERE notforloan IS NULL");
865     $dbh->do("UPDATE deleteditems SET damaged = 0 WHERE damaged IS NULL");
866     $dbh->do("UPDATE deleteditems SET itemlost = 0 WHERE itemlost IS NULL");
867     $dbh->do("UPDATE deleteditems SET wthdrawn = 0 WHERE wthdrawn IS NULL");
868     $dbh->do("ALTER TABLE deleteditems
869                 MODIFY notforloan tinyint(1) NOT NULL default 0,
870                 MODIFY damaged    tinyint(1) NOT NULL default 0,
871                 MODIFY itemlost   tinyint(1) NOT NULL default 0,
872                 MODIFY wthdrawn   tinyint(1) NOT NULL default 0");
873         print "Upgrade to $DBversion done (disallow NULL in several item status columns)\n";
874     SetVersion ($DBversion);
875 }
876
877 $DBversion = "3.00.00.04";
878 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
879     $dbh->do("ALTER TABLE aqbooksellers CHANGE name name mediumtext NOT NULL");
880         print "Upgrade to $DBversion done (disallow NULL in aqbooksellers.name; part of fix for bug 1251)\n";
881     SetVersion ($DBversion);
882 }
883
884 $DBversion = "3.00.00.043";
885 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
886     $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");
887         print "Upgrade to $DBversion done (currency table: add symbol and timestamp columns)\n";
888     SetVersion ($DBversion);
889 }
890
891 $DBversion = "3.00.00.044";
892 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
893     $dbh->do("ALTER TABLE deletedborrowers
894   ADD `altcontactfirstname` varchar(255) default NULL,
895   ADD `altcontactsurname` varchar(255) default NULL,
896   ADD `altcontactaddress1` varchar(255) default NULL,
897   ADD `altcontactaddress2` varchar(255) default NULL,
898   ADD `altcontactaddress3` varchar(255) default NULL,
899   ADD `altcontactzipcode` varchar(50) default NULL,
900   ADD `altcontactphone` varchar(50) default NULL
901   ");
902   $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES
903 ('OPACBaseURL',NULL,'Specify the Base URL of the OPAC, e.g., opac.mylibrary.com, the http:// will be added automatically by Koha.',NULL,'Free'),
904 ('language','en','Set the default language in the staff client.',NULL,'Languages'),
905 ('QueryAutoTruncate',1,'If ON, query truncation is enabled by default',NULL,'YesNo'),
906 ('QueryRemoveStopwords',0,'If ON, stopwords listed in the Administration area will be removed from queries',NULL,'YesNo')
907   ");
908         print "Upgrade to $DBversion done (syncing deletedborrowers table with borrowers table)\n";
909     SetVersion ($DBversion);
910 }
911
912 #-- http://www.w3.org/International/articles/language-tags/
913
914 #-- RFC4646
915 $DBversion = "3.00.00.045";
916 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
917     $dbh->do("
918 CREATE TABLE language_subtag_registry (
919         subtag varchar(25),
920         type varchar(25), -- language-script-region-variant-extension-privateuse
921         description varchar(25), -- only one of the possible descriptions for ease of reference, see language_descriptions for the complete list
922         added date,
923         KEY `subtag` (`subtag`)
924 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
925
926 #-- TODO: add suppress_scripts
927 #-- this maps three letter codes defined in iso639.2 back to their
928 #-- two letter equivilents in rfc4646 (LOC maintains iso639+)
929  $dbh->do("CREATE TABLE language_rfc4646_to_iso639 (
930         rfc4646_subtag varchar(25),
931         iso639_2_code varchar(25),
932         KEY `rfc4646_subtag` (`rfc4646_subtag`)
933 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
934
935  $dbh->do("CREATE TABLE language_descriptions (
936         subtag varchar(25),
937         type varchar(25),
938         lang varchar(25),
939         description varchar(255),
940         KEY `lang` (`lang`)
941 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
942
943 #-- bi-directional support, keyed by script subcode
944  $dbh->do("CREATE TABLE language_script_bidi (
945         rfc4646_subtag varchar(25), -- script subtag, Arab, Hebr, etc.
946         bidi varchar(3), -- rtl ltr
947         KEY `rfc4646_subtag` (`rfc4646_subtag`)
948 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
949
950 #-- BIDI Stuff, Arabic and Hebrew
951  $dbh->do("INSERT INTO language_script_bidi(rfc4646_subtag,bidi)
952 VALUES( 'Arab', 'rtl')");
953  $dbh->do("INSERT INTO language_script_bidi(rfc4646_subtag,bidi)
954 VALUES( 'Hebr', 'rtl')");
955
956 #-- TODO: need to map language subtags to script subtags for detection
957 #-- of bidi when script is not specified (like ar, he)
958  $dbh->do("CREATE TABLE language_script_mapping (
959         language_subtag varchar(25),
960         script_subtag varchar(25),
961         KEY `language_subtag` (`language_subtag`)
962 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
963
964 #-- Default mappings between script and language subcodes
965  $dbh->do("INSERT INTO language_script_mapping(language_subtag,script_subtag)
966 VALUES( 'ar', 'Arab')");
967  $dbh->do("INSERT INTO language_script_mapping(language_subtag,script_subtag)
968 VALUES( 'he', 'Hebr')");
969
970         print "Upgrade to $DBversion done (adding language subtag registry and basic BiDi support NOTE: You should import the subtag registry SQL)\n";
971     SetVersion ($DBversion);
972 }
973
974 $DBversion = "3.00.00.046";
975 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
976     $dbh->do("ALTER TABLE `subscription` CHANGE `numberlength` `numberlength` int(11) default '0' ,
977                  CHANGE `weeklength` `weeklength` int(11) default '0'");
978     $dbh->do("CREATE TABLE `serialitems` (`serialid` int(11) NOT NULL, `itemnumber` int(11) NOT NULL, UNIQUE KEY `serialididx` (`serialid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
979     $dbh->do("INSERT INTO `serialitems` SELECT `serialid`,`itemnumber` from serial where NOT ISNULL(itemnumber) && itemnumber <> '' && itemnumber NOT LIKE '%,%'");
980         print "Upgrade to $DBversion done (Add serialitems table to link serial issues to items. )\n";
981     SetVersion ($DBversion);
982 }
983
984 $DBversion = "3.00.00.047";
985 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
986     $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');");
987         print "Upgrade to $DBversion done ( Added OpacRenewalAllowed syspref )\n";
988     SetVersion ($DBversion);
989 }
990
991 $DBversion = "3.00.00.048";
992 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
993     $dbh->do("ALTER TABLE `items` ADD `more_subfields_xml` longtext default NULL AFTER `itype`");
994         print "Upgrade to $DBversion done (added items.more_subfields_xml)\n";
995     SetVersion ($DBversion);
996 }
997
998 $DBversion = "3.00.00.049";
999 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1000         $dbh->do("ALTER TABLE `z3950servers` ADD `encoding` text default NULL AFTER type ");
1001         print "Upgrade to $DBversion done ( Added encoding field to z3950servers table )\n";
1002     SetVersion ($DBversion);
1003 }
1004
1005 $DBversion = "3.00.00.050";
1006 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1007     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacHighlightedWords','0','If Set, query matched terms are highlighted in OPAC',NULL,'YesNo');");
1008         print "Upgrade to $DBversion done ( Added OpacHighlightedWords syspref )\n";
1009     SetVersion ($DBversion);
1010 }
1011
1012 $DBversion = "3.00.00.051";
1013 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1014     $dbh->do("UPDATE systempreferences SET explanation = 'Define the current theme for the OPAC interface.' WHERE variable = 'opacthemes';");
1015         print "Upgrade to $DBversion done ( Corrected opacthemes explanation. )\n";
1016     SetVersion ($DBversion);
1017 }
1018
1019 $DBversion = "3.00.00.052";
1020 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1021     $dbh->do("ALTER TABLE `deleteditems` ADD `more_subfields_xml` LONGTEXT DEFAULT NULL AFTER `itype`");
1022         print "Upgrade to $DBversion done ( Adding missing column to deleteditems table. )\n";
1023     SetVersion ($DBversion);
1024 }
1025
1026 $DBversion = "3.00.00.053";
1027 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1028     $dbh->do("CREATE TABLE `printers_profile` (
1029             `prof_id` int(4) NOT NULL auto_increment,
1030             `printername` varchar(40) NOT NULL,
1031             `tmpl_id` int(4) NOT NULL,
1032             `paper_bin` varchar(20) NOT NULL,
1033             `offset_horz` float default NULL,
1034             `offset_vert` float default NULL,
1035             `creep_horz` float default NULL,
1036             `creep_vert` float default NULL,
1037             `unit` char(20) NOT NULL default 'POINT',
1038             PRIMARY KEY  (`prof_id`),
1039             UNIQUE KEY `printername` (`printername`,`tmpl_id`,`paper_bin`),
1040             CONSTRAINT `printers_profile_pnfk_1` FOREIGN KEY (`tmpl_id`) REFERENCES `labels_templates` (`tmpl_id`) ON DELETE CASCADE ON UPDATE CASCADE
1041             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1042     $dbh->do("CREATE TABLE `labels_profile` (
1043             `tmpl_id` int(4) NOT NULL,
1044             `prof_id` int(4) NOT NULL,
1045             UNIQUE KEY `tmpl_id` (`tmpl_id`),
1046             UNIQUE KEY `prof_id` (`prof_id`)
1047             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1048     print "Upgrade to $DBversion done ( Printer Profile tables added )\n";
1049     SetVersion ($DBversion);
1050 }
1051
1052 $DBversion = "3.00.00.054";
1053 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1054     $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';");
1055         print "Upgrade to $DBversion done ( Added another barcode autogeneration sequence to barcode.pl. )\n";
1056     SetVersion ($DBversion);
1057 }
1058
1059 $DBversion = "3.00.00.055";
1060 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1061     $dbh->do("ALTER TABLE `zebraqueue` ADD KEY `zebraqueue_lookup` (`server`, `biblio_auth_number`, `operation`, `done`)");
1062         print "Upgrade to $DBversion done ( Added index on zebraqueue. )\n";
1063     SetVersion ($DBversion);
1064 }
1065 $DBversion = "3.00.00.056";
1066 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1067     if (C4::Context->preference("marcflavour") eq 'UNIMARC') {
1068         $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) ");
1069     } else {
1070         $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) ");
1071     }
1072     $dbh->do("ALTER TABLE `items` ADD `enumchron` VARCHAR(80) DEFAULT NULL;");
1073     print "Upgrade to $DBversion done ( Added item.enumchron column, and framework map to 952h )\n";
1074     SetVersion ($DBversion);
1075 }
1076
1077 $DBversion = "3.00.00.057";
1078 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1079     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH','0','if ON, OAI-PMH server is enabled',NULL,'YesNo');");
1080     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH:archiveID','KOHA-OAI-TEST','OAI-PMH archive identification',NULL,'Free');");
1081     $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');");
1082     $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');");
1083     $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');");
1084     SetVersion ($DBversion);
1085 }
1086
1087 $DBversion = "3.00.00.058";
1088 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1089     $dbh->do("ALTER TABLE `opac_news`
1090                 CHANGE `lang` `lang` VARCHAR( 25 )
1091                 CHARACTER SET utf8
1092                 COLLATE utf8_general_ci
1093                 NOT NULL default ''");
1094         print "Upgrade to $DBversion done ( lang field in opac_news made longer )\n";
1095     SetVersion ($DBversion);
1096 }
1097
1098 $DBversion = "3.00.00.059";
1099 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1100
1101     $dbh->do("CREATE TABLE IF NOT EXISTS `labels_templates` (
1102             `tmpl_id` int(4) NOT NULL auto_increment,
1103             `tmpl_code` char(100)  default '',
1104             `tmpl_desc` char(100) default '',
1105             `page_width` float default '0',
1106             `page_height` float default '0',
1107             `label_width` float default '0',
1108             `label_height` float default '0',
1109             `topmargin` float default '0',
1110             `leftmargin` float default '0',
1111             `cols` int(2) default '0',
1112             `rows` int(2) default '0',
1113             `colgap` float default '0',
1114             `rowgap` float default '0',
1115             `active` int(1) default NULL,
1116             `units` char(20)  default 'PX',
1117             `fontsize` int(4) NOT NULL default '3',
1118             PRIMARY KEY  (`tmpl_id`)
1119             ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1120     $dbh->do("CREATE TABLE  IF NOT EXISTS `printers_profile` (
1121             `prof_id` int(4) NOT NULL auto_increment,
1122             `printername` varchar(40) NOT NULL,
1123             `tmpl_id` int(4) NOT NULL,
1124             `paper_bin` varchar(20) NOT NULL,
1125             `offset_horz` float default NULL,
1126             `offset_vert` float default NULL,
1127             `creep_horz` float default NULL,
1128             `creep_vert` float default NULL,
1129             `unit` char(20) NOT NULL default 'POINT',
1130             PRIMARY KEY  (`prof_id`),
1131             UNIQUE KEY `printername` (`printername`,`tmpl_id`,`paper_bin`),
1132             CONSTRAINT `printers_profile_pnfk_1` FOREIGN KEY (`tmpl_id`) REFERENCES `labels_templates` (`tmpl_id`) ON DELETE CASCADE ON UPDATE CASCADE
1133             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1134     print "Upgrade to $DBversion done ( Added labels_templates table if it did not exist. )\n";
1135     SetVersion ($DBversion);
1136 }
1137
1138 $DBversion = "3.00.00.060";
1139 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1140     $dbh->do("CREATE TABLE IF NOT EXISTS `patronimage` (
1141             `cardnumber` varchar(16) NOT NULL,
1142             `mimetype` varchar(15) NOT NULL,
1143             `imagefile` mediumblob NOT NULL,
1144             PRIMARY KEY  (`cardnumber`),
1145             CONSTRAINT `patronimage_fk1` FOREIGN KEY (`cardnumber`) REFERENCES `borrowers` (`cardnumber`) ON DELETE CASCADE ON UPDATE CASCADE
1146             ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1147         print "Upgrade to $DBversion done ( Added patronimage table. )\n";
1148     SetVersion ($DBversion);
1149 }
1150
1151 $DBversion = "3.00.00.061";
1152 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1153     $dbh->do("ALTER TABLE labels_templates ADD COLUMN font char(10) NOT NULL DEFAULT 'TR';");
1154         print "Upgrade to $DBversion done ( Added font column to labels_templates )\n";
1155     SetVersion ($DBversion);
1156 }
1157
1158 $DBversion = "3.00.00.062";
1159 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1160     $dbh->do("CREATE TABLE `old_issues` (
1161                 `borrowernumber` int(11) default NULL,
1162                 `itemnumber` int(11) default NULL,
1163                 `date_due` date default NULL,
1164                 `branchcode` varchar(10) default NULL,
1165                 `issuingbranch` varchar(18) default NULL,
1166                 `returndate` date default NULL,
1167                 `lastreneweddate` date default NULL,
1168                 `return` varchar(4) default NULL,
1169                 `renewals` tinyint(4) default NULL,
1170                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1171                 `issuedate` date default NULL,
1172                 KEY `old_issuesborridx` (`borrowernumber`),
1173                 KEY `old_issuesitemidx` (`itemnumber`),
1174                 KEY `old_bordate` (`borrowernumber`,`timestamp`),
1175                 CONSTRAINT `old_issues_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1176                     ON DELETE SET NULL ON UPDATE SET NULL,
1177                 CONSTRAINT `old_issues_ibfk_2` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`)
1178                     ON DELETE SET NULL ON UPDATE SET NULL
1179                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1180     $dbh->do("CREATE TABLE `old_reserves` (
1181                 `borrowernumber` int(11) default NULL,
1182                 `reservedate` date default NULL,
1183                 `biblionumber` int(11) default NULL,
1184                 `constrainttype` varchar(1) default NULL,
1185                 `branchcode` varchar(10) default NULL,
1186                 `notificationdate` date default NULL,
1187                 `reminderdate` date default NULL,
1188                 `cancellationdate` date default NULL,
1189                 `reservenotes` mediumtext,
1190                 `priority` smallint(6) default NULL,
1191                 `found` varchar(1) default NULL,
1192                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1193                 `itemnumber` int(11) default NULL,
1194                 `waitingdate` date default NULL,
1195                 KEY `old_reserves_borrowernumber` (`borrowernumber`),
1196                 KEY `old_reserves_biblionumber` (`biblionumber`),
1197                 KEY `old_reserves_itemnumber` (`itemnumber`),
1198                 KEY `old_reserves_branchcode` (`branchcode`),
1199                 CONSTRAINT `old_reserves_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1200                     ON DELETE SET NULL ON UPDATE SET NULL,
1201                 CONSTRAINT `old_reserves_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`)
1202                     ON DELETE SET NULL ON UPDATE SET NULL,
1203                 CONSTRAINT `old_reserves_ibfk_3` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`)
1204                     ON DELETE SET NULL ON UPDATE SET NULL
1205                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1206
1207     # move closed transactions to old_* tables
1208     $dbh->do("INSERT INTO old_issues SELECT * FROM issues WHERE returndate IS NOT NULL");
1209     $dbh->do("DELETE FROM issues WHERE returndate IS NOT NULL");
1210     $dbh->do("INSERT INTO old_reserves SELECT * FROM reserves WHERE cancellationdate IS NOT NULL OR found = 'F'");
1211     $dbh->do("DELETE FROM reserves WHERE cancellationdate IS NOT NULL OR found = 'F'");
1212
1213         print "Upgrade to $DBversion done ( Added old_issues and old_reserves tables )\n";
1214     SetVersion ($DBversion);
1215 }
1216
1217 $DBversion = "3.00.00.063";
1218 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1219     $dbh->do("ALTER TABLE deleteditems
1220                 CHANGE COLUMN booksellerid booksellerid MEDIUMTEXT DEFAULT NULL,
1221                 ADD COLUMN enumchron VARCHAR(80) DEFAULT NULL AFTER more_subfields_xml,
1222                 ADD COLUMN copynumber SMALLINT(6) DEFAULT NULL AFTER enumchron;");
1223     $dbh->do("ALTER TABLE items
1224                 CHANGE COLUMN booksellerid booksellerid MEDIUMTEXT,
1225                 ADD COLUMN copynumber SMALLINT(6) DEFAULT NULL AFTER enumchron;");
1226         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";
1227     SetVersion ($DBversion);
1228 }
1229
1230 $DBversion = "3.00.00.064";
1231 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1232     $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');");
1233     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AWSAccessKeyID','','See:  http://aws.amazon.com','','free');");
1234     $dbh->do("DELETE FROM `systempreferences` WHERE variable='AmazonDevKey';");
1235     $dbh->do("DELETE FROM `systempreferences` WHERE variable='XISBNAmazonSimilarItems';");
1236     $dbh->do("DELETE FROM `systempreferences` WHERE variable='OPACXISBNAmazonSimilarItems';");
1237     print "Upgrade to $DBversion done (IMPORTANT: Upgrading to Amazon.com Associates Web Service 4.0 ) \n";
1238     SetVersion ($DBversion);
1239 }
1240
1241 $DBversion = "3.00.00.065";
1242 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1243     $dbh->do("CREATE TABLE `patroncards` (
1244                 `cardid` int(11) NOT NULL auto_increment,
1245                 `batch_id` varchar(10) NOT NULL default '1',
1246                 `borrowernumber` int(11) NOT NULL,
1247                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1248                 PRIMARY KEY  (`cardid`),
1249                 KEY `patroncards_ibfk_1` (`borrowernumber`),
1250                 CONSTRAINT `patroncards_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE
1251                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1252     print "Upgrade to $DBversion done (Adding patroncards table for patroncards generation feature. ) \n";
1253     SetVersion ($DBversion);
1254 }
1255
1256 $DBversion = "3.00.00.066";
1257 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1258     $dbh->do("ALTER TABLE `virtualshelfcontents` MODIFY `dateadded` timestamp NOT NULL
1259 DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP;
1260 ");
1261     print "Upgrade to $DBversion done (fix for bug 1873: virtualshelfcontents dateadded column empty. ) \n";
1262     SetVersion ($DBversion);
1263 }
1264
1265 $DBversion = "3.00.00.067";
1266 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1267     $dbh->do("UPDATE systempreferences SET explanation = 'Enable patron images for the Staff Client', type = 'YesNo' WHERE variable = 'patronimages'");
1268     print "Upgrade to $DBversion done (Updating patronimages syspref to reflect current kohastructure.sql. ) \n";
1269     SetVersion ($DBversion);
1270 }
1271
1272 $DBversion = "3.00.00.068";
1273 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1274     $dbh->do("CREATE TABLE `permissions` (
1275                 `module_bit` int(11) NOT NULL DEFAULT 0,
1276                 `code` varchar(30) DEFAULT NULL,
1277                 `description` varchar(255) DEFAULT NULL,
1278                 PRIMARY KEY  (`module_bit`, `code`),
1279                 CONSTRAINT `permissions_ibfk_1` FOREIGN KEY (`module_bit`) REFERENCES `userflags` (`bit`)
1280                     ON DELETE CASCADE ON UPDATE CASCADE
1281               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1282     $dbh->do("CREATE TABLE `user_permissions` (
1283                 `borrowernumber` int(11) NOT NULL DEFAULT 0,
1284                 `module_bit` int(11) NOT NULL DEFAULT 0,
1285                 `code` varchar(30) DEFAULT NULL,
1286                 CONSTRAINT `user_permissions_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1287                     ON DELETE CASCADE ON UPDATE CASCADE,
1288                 CONSTRAINT `user_permissions_ibfk_2` FOREIGN KEY (`module_bit`, `code`)
1289                     REFERENCES `permissions` (`module_bit`, `code`)
1290                     ON DELETE CASCADE ON UPDATE CASCADE
1291               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1292
1293     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
1294     (13, 'edit_news', 'Write news for the OPAC and staff interfaces'),
1295     (13, 'label_creator', 'Create printable labels and barcodes from catalog and patron data'),
1296     (13, 'edit_calendar', 'Define days when the library is closed'),
1297     (13, 'moderate_comments', 'Moderate patron comments'),
1298     (13, 'edit_notices', 'Define notices'),
1299     (13, 'edit_notice_status_triggers', 'Set notice/status triggers for overdue items'),
1300     (13, 'view_system_logs', 'Browse the system logs'),
1301     (13, 'inventory', 'Perform inventory (stocktaking) of your catalogue'),
1302     (13, 'stage_marc_import', 'Stage MARC records into the reservoir'),
1303     (13, 'manage_staged_marc', 'Managed staged MARC records, including completing and reversing imports'),
1304     (13, 'export_catalog', 'Export bibliographic and holdings data'),
1305     (13, 'import_patrons', 'Import patron data'),
1306     (13, 'delete_anonymize_patrons', 'Delete old borrowers and anonymize circulation history (deletes borrower reading history)'),
1307     (13, 'batch_upload_patron_images', 'Upload patron images in batch or one at a time'),
1308     (13, 'schedule_tasks', 'Schedule tasks to run')");
1309
1310     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('GranularPermissions','0','Use detailed staff user permissions',NULL,'YesNo')");
1311
1312     print "Upgrade to $DBversion done (adding permissions and user_permissions tables and GranularPermissions syspref) \n";
1313     SetVersion ($DBversion);
1314 }
1315 $DBversion = "3.00.00.069";
1316 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1317     $dbh->do("ALTER TABLE labels_conf CHANGE COLUMN class classification int(1) DEFAULT NULL;");
1318         print "Upgrade to $DBversion done ( Correcting columname in labels_conf )\n";
1319     SetVersion ($DBversion);
1320 }
1321
1322 $DBversion = "3.00.00.070";
1323 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1324     $sth = $dbh->prepare("SELECT value FROM systempreferences WHERE variable='yuipath'");
1325     $sth->execute;
1326     my ($value) = $sth->fetchrow;
1327     $value =~ s/2.3.1/2.5.1/;
1328     $dbh->do("UPDATE systempreferences SET value='$value' WHERE variable='yuipath';");
1329         print "Update yuipath syspref to 2.5.1 if necessary\n";
1330     SetVersion ($DBversion);
1331 }
1332
1333 $DBversion = "3.00.00.071";
1334 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1335     $dbh->do(" ALTER TABLE `subscription` ADD `serialsadditems` TINYINT( 1 ) NOT NULL DEFAULT '0';");
1336     # fill the new field with the previous systempreference value, then drop the syspref
1337     my $sth = $dbh->prepare("SELECT value FROM systempreferences WHERE variable='serialsadditems'");
1338     $sth->execute;
1339     my ($serialsadditems) = $sth->fetchrow();
1340     $dbh->do("UPDATE subscription SET serialsadditems=$serialsadditems");
1341     $dbh->do("DELETE FROM systempreferences WHERE variable='serialsadditems'");
1342     print "Upgrade to $DBversion done ( moving serialsadditems from syspref to subscription )\n";
1343     SetVersion ($DBversion);
1344 }
1345
1346 $DBversion = "3.00.00.072";
1347 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1348     $dbh->do("ALTER TABLE labels_conf ADD COLUMN formatstring mediumtext DEFAULT NULL AFTER printingtype");
1349         print "Upgrade to $DBversion done ( Adding format string to labels generator. )\n";
1350     SetVersion ($DBversion);
1351 }
1352
1353 $DBversion = "3.00.00.073";
1354 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1355         $dbh->do("DROP TABLE IF EXISTS `tags_all`;");
1356         $dbh->do(q#
1357         CREATE TABLE `tags_all` (
1358           `tag_id`         int(11) NOT NULL auto_increment,
1359           `borrowernumber` int(11) NOT NULL,
1360           `biblionumber`   int(11) NOT NULL,
1361           `term`      varchar(255) NOT NULL,
1362           `language`       int(4) default NULL,
1363           `date_created` datetime  NOT NULL,
1364           PRIMARY KEY  (`tag_id`),
1365           KEY `tags_borrowers_fk_1` (`borrowernumber`),
1366           KEY `tags_biblionumber_fk_1` (`biblionumber`),
1367           CONSTRAINT `tags_borrowers_fk_1` FOREIGN KEY (`borrowernumber`)
1368                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1369           CONSTRAINT `tags_biblionumber_fk_1` FOREIGN KEY (`biblionumber`)
1370                 REFERENCES `biblio`     (`biblionumber`)  ON DELETE CASCADE ON UPDATE CASCADE
1371         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1372         #);
1373         $dbh->do("DROP TABLE IF EXISTS `tags_approval`;");
1374         $dbh->do(q#
1375         CREATE TABLE `tags_approval` (
1376           `term`   varchar(255) NOT NULL,
1377           `approved`     int(1) NOT NULL default '0',
1378           `date_approved` datetime       default NULL,
1379           `approved_by` int(11)          default NULL,
1380           `weight_total` int(9) NOT NULL default '1',
1381           PRIMARY KEY  (`term`),
1382           KEY `tags_approval_borrowers_fk_1` (`approved_by`),
1383           CONSTRAINT `tags_approval_borrowers_fk_1` FOREIGN KEY (`approved_by`)
1384                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE
1385         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1386         #);
1387         $dbh->do("DROP TABLE IF EXISTS `tags_index`;");
1388         $dbh->do(q#
1389         CREATE TABLE `tags_index` (
1390           `term`    varchar(255) NOT NULL,
1391           `biblionumber` int(11) NOT NULL,
1392           `weight`        int(9) NOT NULL default '1',
1393           PRIMARY KEY  (`term`,`biblionumber`),
1394           KEY `tags_index_biblionumber_fk_1` (`biblionumber`),
1395           CONSTRAINT `tags_index_term_fk_1` FOREIGN KEY (`term`)
1396                 REFERENCES `tags_approval` (`term`)  ON DELETE CASCADE ON UPDATE CASCADE,
1397           CONSTRAINT `tags_index_biblionumber_fk_1` FOREIGN KEY (`biblionumber`)
1398                 REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
1399         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1400         #);
1401         $dbh->do(q#
1402         INSERT INTO `systempreferences` VALUES
1403                 ('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=',''),
1404                 ('BakerTaylorEnabled','0','','Enable or disable all Baker & Taylor features.','YesNo'),
1405                 ('BakerTaylorPassword','','','Baker & Taylor Password for Content Cafe (external content)','Textarea'),
1406                 ('BakerTaylorUsername','','','Baker & Taylor Username for Content Cafe (external content)','Textarea'),
1407                 ('TagsEnabled','1','','Enables or disables all tagging features.  This is the main switch for tags.','YesNo'),
1408                 ('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.',''),
1409                 ('TagsInputOnDetail','1','','Allow users to input tags from the detail page.',         'YesNo'),
1410                 ('TagsInputOnList',  '0','','Allow users to input tags from the search results list.', 'YesNo'),
1411                 ('TagsModeration',  NULL,'','Require tags from patrons to be approved before becoming visible.','YesNo'),
1412                 ('TagsShowOnDetail','10','','Number of tags to display on detail page.  0 is off.',        'Integer'),
1413                 ('TagsShowOnList',   '6','','Number of tags to display on search results list.  0 is off.','Integer')
1414         #);
1415         print "Upgrade to $DBversion done (Baker/Taylor,Tags: sysprefs and tables (tags_all, tags_index, tags_approval)) \n";
1416         SetVersion ($DBversion);
1417 }
1418
1419 $DBversion = "3.00.00.074";
1420 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1421     $dbh->do( q(update itemtypes set imageurl = concat( 'npl/', imageurl )
1422                   where imageurl not like 'http%'
1423                     and imageurl is not NULL
1424                     and imageurl != '') );
1425     print "Upgrade to $DBversion done (updating imagetype.imageurls to reflect new icon locations.)\n";
1426     SetVersion ($DBversion);
1427 }
1428
1429 $DBversion = "3.00.00.075";
1430 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1431     $dbh->do( q(alter table authorised_values add imageurl varchar(200) default NULL) );
1432     print "Upgrade to $DBversion done (adding imageurl field to authorised_values table)\n";
1433     SetVersion ($DBversion);
1434 }
1435
1436 $DBversion = "3.00.00.076";
1437 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1438     $dbh->do("ALTER TABLE import_batches
1439               ADD COLUMN nomatch_action enum('create_new', 'ignore') NOT NULL default 'create_new' AFTER overlay_action");
1440     $dbh->do("ALTER TABLE import_batches
1441               ADD COLUMN item_action enum('always_add', 'add_only_for_matches', 'add_only_for_new', 'ignore')
1442                   NOT NULL default 'always_add' AFTER nomatch_action");
1443     $dbh->do("ALTER TABLE import_batches
1444               MODIFY overlay_action  enum('replace', 'create_new', 'use_template', 'ignore')
1445                   NOT NULL default 'create_new'");
1446     $dbh->do("ALTER TABLE import_records
1447               MODIFY status  enum('error', 'staged', 'imported', 'reverted', 'items_reverted',
1448                                   'ignored') NOT NULL default 'staged'");
1449     $dbh->do("ALTER TABLE import_items
1450               MODIFY status enum('error', 'staged', 'imported', 'reverted', 'ignored') NOT NULL default 'staged'");
1451
1452         print "Upgrade to $DBversion done (changes to import_batches and import_records)\n";
1453         SetVersion ($DBversion);
1454 }
1455
1456 $DBversion = "3.00.00.077";
1457 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1458     # drop these tables only if they exist and none of them are empty
1459     # these tables are not defined in the packaged 2.2.9, but since it is believed
1460     # that at least one library may be using them in a post-2.2.9 but pre-3.0 Koha,
1461     # some care is taken.
1462     my ($print_error) = $dbh->{PrintError};
1463     $dbh->{PrintError} = 0;
1464     my ($raise_error) = $dbh->{RaiseError};
1465     $dbh->{RaiseError} = 1;
1466
1467     my $count = 0;
1468     my $do_drop = 1;
1469     eval { $count = $dbh->do("SELECT 1 FROM categorytable"); };
1470     if ($count > 0) {
1471         $do_drop = 0;
1472     }
1473     eval { $count = $dbh->do("SELECT 1 FROM mediatypetable"); };
1474     if ($count > 0) {
1475         $do_drop = 0;
1476     }
1477     eval { $count = $dbh->do("SELECT 1 FROM subcategorytable"); };
1478     if ($count > 0) {
1479         $do_drop = 0;
1480     }
1481
1482     if ($do_drop) {
1483         $dbh->do("DROP TABLE IF EXISTS `categorytable`");
1484         $dbh->do("DROP TABLE IF EXISTS `mediatypetable`");
1485         $dbh->do("DROP TABLE IF EXISTS `subcategorytable`");
1486     }
1487
1488     $dbh->{PrintError} = $print_error;
1489     $dbh->{RaiseError} = $raise_error;
1490         print "Upgrade to $DBversion done (drop categorytable, subcategorytable, and mediatypetable)\n";
1491         SetVersion ($DBversion);
1492 }
1493
1494 $DBversion = "3.00.00.078";
1495 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1496     my ($print_error) = $dbh->{PrintError};
1497     $dbh->{PrintError} = 0;
1498
1499     unless ($dbh->do("SELECT 1 FROM browser")) {
1500         $dbh->{PrintError} = $print_error;
1501         $dbh->do("CREATE TABLE `browser` (
1502                     `level` int(11) NOT NULL,
1503                     `classification` varchar(20) NOT NULL,
1504                     `description` varchar(255) NOT NULL,
1505                     `number` bigint(20) NOT NULL,
1506                     `endnode` tinyint(4) NOT NULL
1507                   ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1508     }
1509     $dbh->{PrintError} = $print_error;
1510         print "Upgrade to $DBversion done (add browser table if not already present)\n";
1511         SetVersion ($DBversion);
1512 }
1513
1514 $DBversion = "3.00.00.079";
1515 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1516  my ($print_error) = $dbh->{PrintError};
1517     $dbh->{PrintError} = 0;
1518
1519     $dbh->do("INSERT INTO `systempreferences` (variable, value,options,type, explanation)VALUES
1520         ('AddPatronLists','categorycode','categorycode|category_type','Choice','Allow user to choose what list to pick up from when adding patrons')");
1521     print "Upgrade to $DBversion done (add browser table if not already present)\n";
1522         SetVersion ($DBversion);
1523 }
1524
1525 $DBversion = "3.00.00.080";
1526 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1527     $dbh->do("ALTER TABLE subscription CHANGE monthlength monthlength int(11) default '0'");
1528     $dbh->do("ALTER TABLE deleteditems MODIFY marc LONGBLOB AFTER copynumber");
1529     $dbh->do("ALTER TABLE aqbooksellers CHANGE name name mediumtext NOT NULL");
1530         print "Upgrade to $DBversion done (catch up on DB schema changes since alpha and beta)\n";
1531         SetVersion ($DBversion);
1532 }
1533
1534 $DBversion = "3.00.00.081";
1535 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1536     $dbh->do("CREATE TABLE `borrower_attribute_types` (
1537                 `code` varchar(10) NOT NULL,
1538                 `description` varchar(255) NOT NULL,
1539                 `repeatable` tinyint(1) NOT NULL default 0,
1540                 `unique_id` tinyint(1) NOT NULL default 0,
1541                 `opac_display` tinyint(1) NOT NULL default 0,
1542                 `password_allowed` tinyint(1) NOT NULL default 0,
1543                 `staff_searchable` tinyint(1) NOT NULL default 0,
1544                 `authorised_value_category` varchar(10) default NULL,
1545                 PRIMARY KEY  (`code`)
1546               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1547     $dbh->do("CREATE TABLE `borrower_attributes` (
1548                 `borrowernumber` int(11) NOT NULL,
1549                 `code` varchar(10) NOT NULL,
1550                 `attribute` varchar(30) default NULL,
1551                 `password` varchar(30) default NULL,
1552                 KEY `borrowernumber` (`borrowernumber`),
1553                 KEY `code_attribute` (`code`, `attribute`),
1554                 CONSTRAINT `borrower_attributes_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1555                     ON DELETE CASCADE ON UPDATE CASCADE,
1556                 CONSTRAINT `borrower_attributes_ibfk_2` FOREIGN KEY (`code`) REFERENCES `borrower_attribute_types` (`code`)
1557                     ON DELETE CASCADE ON UPDATE CASCADE
1558             ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1559     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('ExtendedPatronAttributes','0','Use extended patron IDs and attributes',NULL,'YesNo')");
1560     print "Upgrade to $DBversion done (added borrower_attributes and  borrower_attribute_types)\n";
1561  SetVersion ($DBversion);
1562 }
1563
1564 $DBversion = "3.00.00.082";
1565 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1566     $dbh->do( q(alter table accountlines add column lastincrement decimal(28,6) default NULL) );
1567     print "Upgrade to $DBversion done (adding lastincrement column to accountlines table)\n";
1568     SetVersion ($DBversion);
1569 }
1570
1571 $DBversion = "3.00.00.083";
1572 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1573     $dbh->do( qq(UPDATE systempreferences SET value='local' where variable='yuipath' and value like "%/intranet-tmpl/prog/%"));
1574     print "Upgrade to $DBversion done (Changing yuipath behaviour in managing a local value)\n";
1575     SetVersion ($DBversion);
1576 }
1577 $DBversion = "3.00.00.084";
1578     if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1579     $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')");
1580     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('GoogleJackets','0','if ON, displays jacket covers from Google Books API',NULL,'YesNo')");
1581     print "Upgrade to $DBversion done (add new sysprefs)\n";
1582     SetVersion ($DBversion);
1583 }
1584
1585 $DBversion = "3.00.00.085";
1586 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1587     if (C4::Context->preference("marcflavour") eq 'MARC21') {
1588         $dbh->do("UPDATE marc_subfield_structure SET tab = 0 WHERE tab =  9 AND tagfield = '037'");
1589         $dbh->do("UPDATE marc_subfield_structure SET tab = 1 WHERE tab =  6 AND tagfield in ('100', '110', '111', '130')");
1590         $dbh->do("UPDATE marc_subfield_structure SET tab = 2 WHERE tab =  6 AND tagfield in ('240', '243')");
1591         $dbh->do("UPDATE marc_subfield_structure SET tab = 4 WHERE tab =  6 AND tagfield in ('400', '410', '411', '440')");
1592         $dbh->do("UPDATE marc_subfield_structure SET tab = 5 WHERE tab =  9 AND tagfield = '584'");
1593         $dbh->do("UPDATE marc_subfield_structure SET tab = 7 WHERE tab = -6 AND tagfield = '760'");
1594     }
1595     print "Upgrade to $DBversion done (move editing tab of various MARC21 subfields)\n";
1596     SetVersion ($DBversion);
1597 }
1598
1599 $DBversion = "3.00.00.086";
1600 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1601         $dbh->do(
1602         "CREATE TABLE `tmp_holdsqueue` (
1603         `biblionumber` int(11) default NULL,
1604         `itemnumber` int(11) default NULL,
1605         `barcode` varchar(20) default NULL,
1606         `surname` mediumtext NOT NULL,
1607         `firstname` text,
1608         `phone` text,
1609         `borrowernumber` int(11) NOT NULL,
1610         `cardnumber` varchar(16) default NULL,
1611         `reservedate` date default NULL,
1612         `title` mediumtext,
1613         `itemcallnumber` varchar(30) default NULL,
1614         `holdingbranch` varchar(10) default NULL,
1615         `pickbranch` varchar(10) default NULL,
1616         `notes` text
1617         ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1618
1619         $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')");
1620         $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')");
1621
1622         print "Upgrade to $DBversion done (Table structure for table `tmp_holdsqueue`)\n";
1623         SetVersion ($DBversion);
1624 }
1625
1626 $DBversion = "3.00.00.087";
1627 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1628     $dbh->do("INSERT INTO `systempreferences` VALUES ('AutoEmailOpacUser','0','','Sends notification emails containing new account details to patrons - when account is created.','YesNo')" );
1629     $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')");
1630     print "Upgrade to $DBversion done (added 2 new 'AutoEmailOpacUser' sysprefs)\n";
1631     SetVersion ($DBversion);
1632 }
1633
1634 $DBversion = "3.00.00.088";
1635 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1636         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('OPACShelfBrowser','1','','Enable/disable Shelf Browser on item details page','YesNo')");
1637         $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')");
1638         $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')");
1639         $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')");
1640         print "Upgrade to $DBversion done (added 2 new 'AutoEmailOpacUser' sysprefs)\n";
1641     SetVersion ($DBversion);
1642 }
1643
1644 $DBversion = "3.00.00.089";
1645 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1646         $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')");
1647         print "Upgrade to $DBversion done (added new AdvancedSearchTypes syspref)\n";
1648     SetVersion ($DBversion);
1649 }
1650
1651 $DBversion = "3.00.00.090";
1652 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1653     $dbh->do("
1654         CREATE TABLE `branch_borrower_circ_rules` (
1655           `branchcode` VARCHAR(10) NOT NULL,
1656           `categorycode` VARCHAR(10) NOT NULL,
1657           `maxissueqty` int(4) default NULL,
1658           PRIMARY KEY (`categorycode`, `branchcode`),
1659           CONSTRAINT `branch_borrower_circ_rules_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
1660             ON DELETE CASCADE ON UPDATE CASCADE,
1661           CONSTRAINT `branch_borrower_circ_rules_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`)
1662             ON DELETE CASCADE ON UPDATE CASCADE
1663         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1664     ");
1665     $dbh->do("
1666         CREATE TABLE `default_borrower_circ_rules` (
1667           `categorycode` VARCHAR(10) NOT NULL,
1668           `maxissueqty` int(4) default NULL,
1669           PRIMARY KEY (`categorycode`),
1670           CONSTRAINT `borrower_borrower_circ_rules_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
1671             ON DELETE CASCADE ON UPDATE CASCADE
1672         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1673     ");
1674     $dbh->do("
1675         CREATE TABLE `default_branch_circ_rules` (
1676           `branchcode` VARCHAR(10) NOT NULL,
1677           `maxissueqty` int(4) default NULL,
1678           PRIMARY KEY (`branchcode`),
1679           CONSTRAINT `default_branch_circ_rules_ibfk_1` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`)
1680             ON DELETE CASCADE ON UPDATE CASCADE
1681         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1682     ");
1683     $dbh->do("
1684         CREATE TABLE `default_circ_rules` (
1685             `singleton` enum('singleton') NOT NULL default 'singleton',
1686             `maxissueqty` int(4) default NULL,
1687             PRIMARY KEY (`singleton`)
1688         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1689     ");
1690     print "Upgrade to $DBversion done (added several circ rules tables)\n";
1691     SetVersion ($DBversion);
1692 }
1693
1694
1695 $DBversion = "3.00.00.091";
1696 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1697     $dbh->do(<<'END_SQL');
1698 ALTER TABLE borrowers
1699 ADD `smsalertnumber` varchar(50) default NULL
1700 END_SQL
1701
1702     $dbh->do(<<'END_SQL');
1703 CREATE TABLE `message_attributes` (
1704   `message_attribute_id` int(11) NOT NULL auto_increment,
1705   `message_name` varchar(20) NOT NULL default '',
1706   `takes_days` tinyint(1) NOT NULL default '0',
1707   PRIMARY KEY  (`message_attribute_id`),
1708   UNIQUE KEY `message_name` (`message_name`)
1709 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1710 END_SQL
1711
1712     $dbh->do(<<'END_SQL');
1713 CREATE TABLE `message_transport_types` (
1714   `message_transport_type` varchar(20) NOT NULL,
1715   PRIMARY KEY  (`message_transport_type`)
1716 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1717 END_SQL
1718
1719     $dbh->do(<<'END_SQL');
1720 CREATE TABLE `message_transports` (
1721   `message_attribute_id` int(11) NOT NULL,
1722   `message_transport_type` varchar(20) NOT NULL,
1723   `is_digest` tinyint(1) NOT NULL default '0',
1724   `letter_module` varchar(20) NOT NULL default '',
1725   `letter_code` varchar(20) NOT NULL default '',
1726   PRIMARY KEY  (`message_attribute_id`,`message_transport_type`,`is_digest`),
1727   KEY `message_transport_type` (`message_transport_type`),
1728   KEY `letter_module` (`letter_module`,`letter_code`),
1729   CONSTRAINT `message_transports_ibfk_1` FOREIGN KEY (`message_attribute_id`) REFERENCES `message_attributes` (`message_attribute_id`) ON DELETE CASCADE ON UPDATE CASCADE,
1730   CONSTRAINT `message_transports_ibfk_2` FOREIGN KEY (`message_transport_type`) REFERENCES `message_transport_types` (`message_transport_type`) ON DELETE CASCADE ON UPDATE CASCADE,
1731   CONSTRAINT `message_transports_ibfk_3` FOREIGN KEY (`letter_module`, `letter_code`) REFERENCES `letter` (`module`, `code`) ON DELETE CASCADE ON UPDATE CASCADE
1732 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1733 END_SQL
1734
1735     $dbh->do(<<'END_SQL');
1736 CREATE TABLE `borrower_message_preferences` (
1737   `borrower_message_preference_id` int(11) NOT NULL auto_increment,
1738   `borrowernumber` int(11) NOT NULL default '0',
1739   `message_attribute_id` int(11) default '0',
1740   `days_in_advance` int(11) default '0',
1741   `wants_digets` tinyint(1) NOT NULL default '0',
1742   PRIMARY KEY  (`borrower_message_preference_id`),
1743   KEY `borrowernumber` (`borrowernumber`),
1744   KEY `message_attribute_id` (`message_attribute_id`),
1745   CONSTRAINT `borrower_message_preferences_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1746   CONSTRAINT `borrower_message_preferences_ibfk_2` FOREIGN KEY (`message_attribute_id`) REFERENCES `message_attributes` (`message_attribute_id`) ON DELETE CASCADE ON UPDATE CASCADE
1747 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1748 END_SQL
1749
1750     $dbh->do(<<'END_SQL');
1751 CREATE TABLE `borrower_message_transport_preferences` (
1752   `borrower_message_preference_id` int(11) NOT NULL default '0',
1753   `message_transport_type` varchar(20) NOT NULL default '0',
1754   PRIMARY KEY  (`borrower_message_preference_id`,`message_transport_type`),
1755   KEY `message_transport_type` (`message_transport_type`),
1756   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,
1757   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
1758 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1759 END_SQL
1760
1761     $dbh->do(<<'END_SQL');
1762 CREATE TABLE `message_queue` (
1763   `message_id` int(11) NOT NULL auto_increment,
1764   `borrowernumber` int(11) NOT NULL,
1765   `subject` text,
1766   `content` text,
1767   `message_transport_type` varchar(20) NOT NULL,
1768   `status` enum('sent','pending','failed','deleted') NOT NULL default 'pending',
1769   `time_queued` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1770   KEY `message_id` (`message_id`),
1771   KEY `borrowernumber` (`borrowernumber`),
1772   KEY `message_transport_type` (`message_transport_type`),
1773   CONSTRAINT `messageq_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1774   CONSTRAINT `messageq_ibfk_2` FOREIGN KEY (`message_transport_type`) REFERENCES `message_transport_types` (`message_transport_type`) ON DELETE RESTRICT ON UPDATE CASCADE
1775 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1776 END_SQL
1777
1778     $dbh->do(<<'END_SQL');
1779 INSERT INTO `systempreferences`
1780   (variable,value,explanation,options,type)
1781 VALUES
1782 ('EnhancedMessagingPreferences',0,'If ON, allows patrons to select to receive additional messages about items due or nearly due.','','YesNo')
1783 END_SQL
1784
1785     $dbh->do( <<'END_SQL');
1786 INSERT INTO `letter`
1787 (module, code, name, title, content)
1788 VALUES
1789 ('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>>'),
1790 ('circulation','DUEDGST','Item Due Reminder (Digest)','Item Due Reminder','You have <<count>> items due'),
1791 ('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>>'),
1792 ('circulation','PREDUEDGST','Advance Notice of Item Due (Digest)','Advance Notice of Item Due','You have <<count>> items due soon'),
1793 ('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.');
1794 END_SQL
1795
1796     my @sql_scripts = (
1797         'installer/data/mysql/en/mandatory/message_transport_types.sql',
1798         'installer/data/mysql/en/optional/sample_notices_message_attributes.sql',
1799         'installer/data/mysql/en/optional/sample_notices_message_transports.sql',
1800     );
1801
1802     my $installer = C4::Installer->new();
1803     foreach my $script ( @sql_scripts ) {
1804         my $full_path = $installer->get_file_path_from_name($script);
1805         my $error = $installer->load_sql($full_path);
1806         warn $error if $error;
1807     }
1808
1809     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";
1810     SetVersion ($DBversion);
1811 }
1812
1813 $DBversion = "3.00.00.092";
1814 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1815     $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')");
1816     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES('AllowHoldsOnDamagedItems', '1', '', 'Allow hold requests to be placed on damaged items', 'YesNo')");
1817         print "Upgrade to $DBversion done (added new AllowOnShelfHolds syspref)\n";
1818     SetVersion ($DBversion);
1819 }
1820
1821 $DBversion = "3.00.00.093";
1822 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1823     $dbh->do("ALTER TABLE `items` MODIFY COLUMN `copynumber` VARCHAR(32) DEFAULT NULL");
1824     $dbh->do("ALTER TABLE `deleteditems` MODIFY COLUMN `copynumber` VARCHAR(32) DEFAULT NULL");
1825         print "Upgrade to $DBversion done (Change data type of items.copynumber to allow free text)\n";
1826     SetVersion ($DBversion);
1827 }
1828
1829 $DBversion = "3.00.00.094";
1830 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1831     $dbh->do("ALTER TABLE `marc_subfield_structure` MODIFY `tagsubfield` VARCHAR(1) NOT NULL DEFAULT '' COLLATE utf8_bin");
1832         print "Upgrade to $DBversion done (Change Collation of marc_subfield_structure to allow mixed case in subfield labels.)\n";
1833     SetVersion ($DBversion);
1834 }
1835
1836 $DBversion = "3.00.00.095";
1837 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1838     if (C4::Context->preference("marcflavour") eq 'MARC21') {
1839         $dbh->do("UPDATE marc_subfield_structure SET authtypecode = 'MEETI_NAME' WHERE authtypecode = 'Meeting Name'");
1840         $dbh->do("UPDATE marc_subfield_structure SET authtypecode = 'CORPO_NAME' WHERE authtypecode = 'CORP0_NAME'");
1841     }
1842         print "Upgrade to $DBversion done (fix invalid authority types in MARC21 frameworks [bug 2254])\n";
1843     SetVersion ($DBversion);
1844 }
1845
1846 $DBversion = "3.00.00.096";
1847 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1848     $sth = $dbh->prepare("SHOW COLUMNS FROM borrower_message_preferences LIKE 'wants_digets'");
1849     $sth->execute();
1850     if (my $row = $sth->fetchrow_hashref) {
1851         $dbh->do("ALTER TABLE borrower_message_preferences CHANGE wants_digets wants_digest tinyint(1) NOT NULL default 0");
1852     }
1853         print "Upgrade to $DBversion done (fix name borrower_message_preferences.wants_digest)\n";
1854     SetVersion ($DBversion);
1855 }
1856
1857 $DBversion = '3.00.00.097';
1858 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1859
1860     $dbh->do('ALTER TABLE message_queue ADD to_address   mediumtext default NULL');
1861     $dbh->do('ALTER TABLE message_queue ADD from_address mediumtext default NULL');
1862     $dbh->do('ALTER TABLE message_queue ADD content_type text');
1863     $dbh->do('ALTER TABLE message_queue CHANGE borrowernumber borrowernumber int(11) default NULL');
1864
1865     print "Upgrade to $DBversion done (updating 4 fields in message_queue table)\n";
1866     SetVersion($DBversion);
1867 }
1868
1869 $DBversion = '3.00.00.098';
1870 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1871
1872     $dbh->do(q(DELETE FROM message_transport_types WHERE message_transport_type = 'rss'));
1873     $dbh->do(q(DELETE FROM message_transports WHERE message_transport_type = 'rss'));
1874
1875     print "Upgrade to $DBversion done (removing unused RSS message_transport_type)\n";
1876     SetVersion($DBversion);
1877 }
1878
1879 $DBversion = '3.00.00.099';
1880 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1881     $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')");
1882     print "Upgrade to $DBversion done (Adding OpacSuppression syspref)\n";
1883     SetVersion($DBversion);
1884 }
1885
1886 $DBversion = '3.00.00.100';
1887 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1888         $dbh->do('ALTER TABLE virtualshelves ADD COLUMN lastmodified timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP');
1889     print "Upgrade to $DBversion done (Adding lastmodified column to virtualshelves)\n";
1890     SetVersion($DBversion);
1891 }
1892
1893 $DBversion = '3.00.00.101';
1894 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1895         $dbh->do('ALTER TABLE `overduerules` CHANGE `categorycode` `categorycode` VARCHAR(10) NOT NULL');
1896         $dbh->do('ALTER TABLE `deletedborrowers` CHANGE `categorycode` `categorycode` VARCHAR(10) NOT NULL');
1897     print "Upgrade to $DBversion done (Updating columnd definitions for patron category codes in notice/statsu triggers and deletedborrowers tables.)\n";
1898     SetVersion($DBversion);
1899 }
1900
1901 $DBversion = '3.00.00.102';
1902 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1903         $dbh->do('ALTER TABLE serialitems MODIFY `serialid` int(11) NOT NULL AFTER itemnumber' );
1904         $dbh->do('ALTER TABLE serialitems DROP KEY serialididx' );
1905         $dbh->do('ALTER TABLE serialitems ADD CONSTRAINT UNIQUE KEY serialitemsidx (itemnumber)' );
1906         # before setting constraint, delete any unvalid data
1907         $dbh->do('DELETE from serialitems WHERE serialid not in (SELECT serial.serialid FROM serial)');
1908         $dbh->do('ALTER TABLE serialitems ADD CONSTRAINT serialitems_sfk_1 FOREIGN KEY (serialid) REFERENCES serial (serialid) ON DELETE CASCADE ON UPDATE CASCADE' );
1909     print "Upgrade to $DBversion done (Updating serialitems table to allow for multiple items per serial fixing kohabug 2380)\n";
1910     SetVersion($DBversion);
1911 }
1912
1913 $DBversion = "3.00.00.103";
1914 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1915     $dbh->do("DELETE FROM systempreferences WHERE variable='serialsadditems'");
1916     print "Upgrade to $DBversion done ( Verifying the removal of serialsadditems from syspref fixing kohabug 2219)\n";
1917     SetVersion ($DBversion);
1918 }
1919
1920 $DBversion = "3.00.00.104";
1921 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1922     $dbh->do("DELETE FROM systempreferences WHERE variable='noOPACHolds'");
1923     print "Upgrade to $DBversion done (remove superseded 'noOPACHolds' system preference per bug 2413)\n";
1924     SetVersion ($DBversion);
1925 }
1926
1927 $DBversion = '3.00.00.105';
1928 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
1929
1930     # it is possible that this syspref is already defined since the feature was added some time ago.
1931     unless ( $dbh->do(q(SELECT variable FROM systempreferences WHERE variable = 'SMSSendDriver')) ) {
1932         $dbh->do(<<'END_SQL');
1933 INSERT INTO `systempreferences`
1934   (variable,value,explanation,options,type)
1935 VALUES
1936 ('SMSSendDriver','','Sets which SMS::Send driver is used to send SMS messages.','','free')
1937 END_SQL
1938     }
1939     print "Upgrade to $DBversion done (added SMSSendDriver system preference)\n";
1940     SetVersion($DBversion);
1941 }
1942
1943 $DBversion = "3.00.00.106";
1944 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1945     $dbh->do("DELETE FROM systempreferences WHERE variable='noOPACHolds'");
1946
1947 # db revision 105 didn't apply correctly, so we're rolling this into 106
1948         $dbh->do("INSERT INTO `systempreferences`
1949    (variable,value,explanation,options,type)
1950         VALUES
1951         ('SMSSendDriver','','Sets which SMS::Send driver is used to send SMS messages.','','free')");
1952
1953     print "Upgrade to $DBversion done (remove default '0000-00-00' in subscriptionhistory.enddate field)\n";
1954     $dbh->do("ALTER TABLE `subscriptionhistory` CHANGE `enddate` `enddate` DATE NULL DEFAULT NULL ");
1955
1956     sanitize_zero_date('subscriptionhistory', 'enddate');
1957
1958     SetVersion ($DBversion);
1959 }
1960
1961 $DBversion = '3.00.00.107';
1962 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1963     $dbh->do(<<'END_SQL');
1964 UPDATE systempreferences
1965   SET explanation = CONCAT( explanation, '. WARNING: this feature is very resource consuming on collections with large numbers of items.' )
1966   WHERE variable = 'OPACShelfBrowser'
1967     AND explanation NOT LIKE '%WARNING%'
1968 END_SQL
1969     $dbh->do(<<'END_SQL');
1970 UPDATE systempreferences
1971   SET explanation = CONCAT( explanation, '. WARNING: this feature is very resource consuming.' )
1972   WHERE variable = 'CataloguingLog'
1973     AND explanation NOT LIKE '%WARNING%'
1974 END_SQL
1975     $dbh->do(<<'END_SQL');
1976 UPDATE systempreferences
1977   SET explanation = CONCAT( explanation, '. WARNING: using NoZebra on even modest sized collections is very slow.' )
1978   WHERE variable = 'NoZebra'
1979     AND explanation NOT LIKE '%WARNING%'
1980 END_SQL
1981     print "Upgrade to $DBversion done (warning added to OPACShelfBrowser system preference)\n";
1982     SetVersion ($DBversion);
1983 }
1984
1985 $DBversion = '3.01.00.000';
1986 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1987     print "Upgrade to $DBversion done (start of 3.1)\n";
1988     SetVersion ($DBversion);
1989 }
1990
1991 $DBversion = '3.01.00.001';
1992 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1993     $dbh->do("
1994         CREATE TABLE hold_fill_targets (
1995             `borrowernumber` int(11) NOT NULL,
1996             `biblionumber` int(11) NOT NULL,
1997             `itemnumber` int(11) NOT NULL,
1998             `source_branchcode`  varchar(10) default NULL,
1999             `item_level_request` tinyint(4) NOT NULL default 0,
2000             PRIMARY KEY `itemnumber` (`itemnumber`),
2001             KEY `bib_branch` (`biblionumber`, `source_branchcode`),
2002             CONSTRAINT `hold_fill_targets_ibfk_1` FOREIGN KEY (`borrowernumber`)
2003                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
2004             CONSTRAINT `hold_fill_targets_ibfk_2` FOREIGN KEY (`biblionumber`)
2005                 REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
2006             CONSTRAINT `hold_fill_targets_ibfk_3` FOREIGN KEY (`itemnumber`)
2007                 REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
2008             CONSTRAINT `hold_fill_targets_ibfk_4` FOREIGN KEY (`source_branchcode`)
2009                 REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
2010         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2011     ");
2012     $dbh->do("
2013         ALTER TABLE tmp_holdsqueue
2014             ADD item_level_request tinyint(4) NOT NULL default 0
2015     ");
2016
2017     print "Upgrade to $DBversion done (add hold_fill_targets table and a column to tmp_holdsqueue)\n";
2018     SetVersion($DBversion);
2019 }
2020
2021 $DBversion = '3.01.00.002';
2022 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2023     # use statistics where available
2024     $dbh->do("
2025         ALTER TABLE statistics ADD KEY  tmp_stats (type, itemnumber, borrowernumber)
2026     ");
2027     $dbh->do("
2028         UPDATE issues iss
2029         SET issuedate = (
2030             SELECT max(datetime)
2031             FROM statistics
2032             WHERE type = 'issue'
2033             AND itemnumber = iss.itemnumber
2034             AND borrowernumber = iss.borrowernumber
2035         )
2036         WHERE issuedate IS NULL;
2037     ");
2038     $dbh->do("ALTER TABLE statistics DROP KEY tmp_stats");
2039
2040     # default to last renewal date
2041     $dbh->do("
2042         UPDATE issues
2043         SET issuedate = lastreneweddate
2044         WHERE issuedate IS NULL
2045         and lastreneweddate IS NOT NULL
2046     ");
2047
2048     my $num_bad_issuedates = $dbh->selectrow_array("SELECT COUNT(*) FROM issues WHERE issuedate IS NULL");
2049     if ($num_bad_issuedates > 0) {
2050         print STDERR "After the upgrade to $DBversion, there are still $num_bad_issuedates loan(s) with a NULL (blank) loan date. ",
2051                      "Please check the issues table in your database.";
2052     }
2053     print "Upgrade to $DBversion done (bug 2582: set null issues.issuedate to lastreneweddate)\n";
2054     SetVersion($DBversion);
2055 }
2056
2057 $DBversion = "3.01.00.003";
2058 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2059     $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')");
2060     print "Upgrade to $DBversion done (add new syspref)\n";
2061     SetVersion ($DBversion);
2062 }
2063
2064 $DBversion = '3.01.00.004';
2065 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2066     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACDisplayRequestPriority','0','Show patrons the priority level on holds in the OPAC','','YesNo')");
2067     print "Upgrade to $DBversion done (added OPACDisplayRequestPriority system preference)\n";
2068     SetVersion ($DBversion);
2069 }
2070
2071 $DBversion = '3.01.00.005';
2072 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2073     $dbh->do("
2074         INSERT INTO `letter` (module, code, name, title, content)
2075         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>>')
2076     ");
2077     $dbh->do("INSERT INTO `message_attributes` (message_attribute_id, message_name, takes_days) values(4, 'Hold Filled', 0)");
2078     $dbh->do("INSERT INTO `message_transports` (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) values(4, 'sms', 0, 'reserves', 'HOLD')");
2079     $dbh->do("INSERT INTO `message_transports` (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) values(4, 'email', 0, 'reserves', 'HOLD')");
2080     print "Upgrade to $DBversion done (Add letter for holds notifications)\n";
2081     SetVersion ($DBversion);
2082 }
2083
2084 $DBversion = '3.01.00.006';
2085 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2086     $dbh->do("ALTER TABLE `biblioitems` ADD KEY issn (issn)");
2087     print "Upgrade to $DBversion done (add index on biblioitems.issn)\n";
2088     SetVersion ($DBversion);
2089 }
2090
2091 $DBversion = "3.01.00.007";
2092 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2093     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='intranetmainUserblock'");
2094     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='intranetuserjs'");
2095     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='opacheader'");
2096     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='OpacMainUserBlock'");
2097     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='OpacNav'");
2098     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='opacuserjs'");
2099     $dbh->do("UPDATE `systempreferences` SET options='30|10', type='Textarea' WHERE variable='OAI-PMH:Set'");
2100     $dbh->do("UPDATE `systempreferences` SET options='50' WHERE variable='intranetstylesheet'");
2101     $dbh->do("UPDATE `systempreferences` SET options='50' WHERE variable='intranetcolorstylesheet'");
2102     $dbh->do("UPDATE `systempreferences` SET options='10' WHERE variable='globalDueDate'");
2103     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='numSearchResults'");
2104     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='OPACnumSearchResults'");
2105     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='ReservesMaxPickupDelay'");
2106     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='TransfersMaxDaysWarning'");
2107     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='StaticHoldsQueueWeight'");
2108     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='holdCancelLength'");
2109     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='XISBNDailyLimit'");
2110     $dbh->do("UPDATE `systempreferences` SET type='Float' WHERE variable='gist'");
2111     $dbh->do("UPDATE `systempreferences` SET type='Free' WHERE variable='BakerTaylorUsername'");
2112     $dbh->do("UPDATE `systempreferences` SET type='Free' WHERE variable='BakerTaylorPassword'");
2113     $dbh->do("UPDATE `systempreferences` SET type='Textarea', options='70|10' WHERE variable='ISBD'");
2114     $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'");
2115     print "Upgrade to $DBversion done (fix display of many sysprefs)\n";
2116     SetVersion ($DBversion);
2117 }
2118
2119 $DBversion = '3.01.00.008';
2120 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2121
2122     $dbh->do("CREATE TABLE branch_transfer_limits (
2123                           limitId int(8) NOT NULL auto_increment,
2124                           toBranch varchar(4) NOT NULL,
2125                           fromBranch varchar(4) NOT NULL,
2126                           itemtype varchar(4) NOT NULL,
2127                           PRIMARY KEY  (limitId)
2128                           ) ENGINE=InnoDB DEFAULT CHARSET=utf8"
2129                         );
2130
2131     $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')");
2132
2133     print "Upgrade to $DBversion done (added branch_transfer_limits table and UseBranchTransferLimits system preference)\n";
2134     SetVersion ($DBversion);
2135 }
2136
2137 $DBversion = "3.01.00.009";
2138 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2139     $dbh->do("ALTER TABLE permissions MODIFY `code` varchar(64) DEFAULT NULL");
2140     $dbh->do("ALTER TABLE user_permissions MODIFY `code` varchar(64) DEFAULT NULL");
2141     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'circulate_remaining_permissions', 'Remaining circulation permissions')");
2142     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'override_renewals', 'Override blocked renewals')");
2143     print "Upgrade to $DBversion done (added subpermissions for circulate permission)\n";
2144 }
2145
2146 $DBversion = '3.01.00.010';
2147 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2148     $dbh->do("ALTER TABLE `borrower_attributes` MODIFY COLUMN `attribute` VARCHAR(64) DEFAULT NULL");
2149     $dbh->do("ALTER TABLE `borrower_attributes` MODIFY COLUMN `password` VARCHAR(64) DEFAULT NULL");
2150     print "Upgrade to $DBversion done (bug 2687: increase length of borrower attribute fields)\n";
2151     SetVersion ($DBversion);
2152 }
2153
2154 $DBversion = '3.01.00.011';
2155 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2156
2157     # Yes, the old value was ^M terminated.
2158     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);";
2159
2160     my $intranetuserjs = C4::Context->preference('intranetuserjs');
2161     if ($intranetuserjs  and  $intranetuserjs eq $bad_value) {
2162         my $sql = <<'END_SQL';
2163 UPDATE systempreferences
2164 SET value = ''
2165 WHERE variable = 'intranetuserjs'
2166 END_SQL
2167         $dbh->do($sql);
2168     }
2169     print "Upgrade to $DBversion done (removed bogus intranetuserjs syspref)\n";
2170     SetVersion($DBversion);
2171 }
2172
2173 $DBversion = "3.01.00.012";
2174 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2175     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowHoldPolicyOverride', '0', 'Allow staff to override hold policies when placing holds',NULL,'YesNo')");
2176     $dbh->do("
2177         CREATE TABLE `branch_item_rules` (
2178           `branchcode` varchar(10) NOT NULL,
2179           `itemtype` varchar(10) NOT NULL,
2180           `holdallowed` tinyint(1) default NULL,
2181           PRIMARY KEY  (`itemtype`,`branchcode`),
2182           KEY `branch_item_rules_ibfk_2` (`branchcode`),
2183           CONSTRAINT `branch_item_rules_ibfk_1` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE,
2184           CONSTRAINT `branch_item_rules_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
2185         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2186     ");
2187     $dbh->do("
2188         CREATE TABLE `default_branch_item_rules` (
2189           `itemtype` varchar(10) NOT NULL,
2190           `holdallowed` tinyint(1) default NULL,
2191           PRIMARY KEY  (`itemtype`),
2192           CONSTRAINT `default_branch_item_rules_ibfk_1` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE
2193         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2194     ");
2195     $dbh->do("
2196         ALTER TABLE default_branch_circ_rules
2197             ADD COLUMN holdallowed tinyint(1) NULL
2198     ");
2199     $dbh->do("
2200         ALTER TABLE default_circ_rules
2201             ADD COLUMN holdallowed tinyint(1) NULL
2202     ");
2203     print "Upgrade to $DBversion done (Add tables and system preferences for holds policies)\n";
2204     SetVersion ($DBversion);
2205 }
2206
2207 $DBversion = '3.01.00.013';
2208 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2209     $dbh->do("
2210         CREATE TABLE item_circulation_alert_preferences (
2211             id           int(11) AUTO_INCREMENT,
2212             branchcode   varchar(10) NOT NULL,
2213             categorycode varchar(10) NOT NULL,
2214             item_type    varchar(10) NOT NULL,
2215             notification varchar(16) NOT NULL,
2216             PRIMARY KEY (id),
2217             KEY (branchcode, categorycode, item_type, notification)
2218         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2219     ");
2220
2221     $dbh->do(q{ ALTER TABLE `message_queue` ADD metadata text DEFAULT NULL           AFTER content;  });
2222     $dbh->do(q{ ALTER TABLE `message_queue` ADD letter_code varchar(64) DEFAULT NULL AFTER metadata; });
2223
2224     $dbh->do(q{
2225         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
2226         ('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.');
2227     });
2228     $dbh->do(q{
2229         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
2230         ('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>>.');
2231     });
2232
2233     $dbh->do(q{INSERT INTO message_attributes (message_attribute_id, message_name, takes_days) VALUES (5, 'Item Check-in', 0);});
2234     $dbh->do(q{INSERT INTO message_attributes (message_attribute_id, message_name, takes_days) VALUES (6, 'Item Checkout', 0);});
2235
2236     $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');});
2237     $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');});
2238     $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');});
2239     $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');});
2240
2241     print "Upgrade to $DBversion done (data for Email Checkout Slips project)\n";
2242          SetVersion ($DBversion);
2243 }
2244
2245 $DBversion = "3.01.00.014";
2246 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2247     $dbh->do("ALTER TABLE `branch_transfer_limits` CHANGE `itemtype` `itemtype` VARCHAR( 4 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL");
2248     $dbh->do("ALTER TABLE `branch_transfer_limits` ADD `ccode` VARCHAR( 10 ) NULL ;");
2249     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2250     VALUES (
2251     'BranchTransferLimitsType', 'ccode', 'itemtype|ccode', 'When using branch transfer limits, choose whether to limit by itemtype or collection code.', 'Choice'
2252     );");
2253
2254     print "Upgrade to $DBversion done ( Updated table for Branch Transfer Limits)\n";
2255     SetVersion ($DBversion);
2256 }
2257
2258 $DBversion = '3.01.00.015';
2259 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2260     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsClientCode', '0', 'Client Code for using Syndetics Solutions content','','free')");
2261
2262     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsEnabled', '0', 'Turn on Syndetics Enhanced Content','','YesNo')");
2263
2264     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsCoverImages', '0', 'Display Cover Images from Syndetics','','YesNo')");
2265
2266     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsTOC', '0', 'Display Table of Content information from Syndetics','','YesNo')");
2267
2268     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsSummary', '0', 'Display Summary Information from Syndetics','','YesNo')");
2269
2270     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsEditions', '0', 'Display Editions from Syndetics','','YesNo')");
2271
2272     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsExcerpt', '0', 'Display Excerpts and first chapters on OPAC from Syndetics','','YesNo')");
2273
2274     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsReviews', '0', 'Display Reviews on OPAC from Syndetics','','YesNo')");
2275
2276     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsAuthorNotes', '0', 'Display Notes about the Author on OPAC from Syndetics','','YesNo')");
2277
2278     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsAwards', '0', 'Display Awards on OPAC from Syndetics','','YesNo')");
2279
2280     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsSeries', '0', 'Display Series information on OPAC from Syndetics','','YesNo')");
2281
2282     $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')");
2283
2284     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAmazonCoverImages', '0', 'Display cover images on OPAC from Amazon Web Services','','YesNo')");
2285
2286     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AmazonCoverImages', '0', 'Display Cover Images in Staff Client from Amazon Web Services','','YesNo')");
2287
2288     $dbh->do("UPDATE systempreferences SET variable='AmazonEnabled' WHERE variable = 'AmazonContent'");
2289
2290     $dbh->do("UPDATE systempreferences SET variable='OPACAmazonEnabled' WHERE variable = 'OPACAmazonContent'");
2291
2292     print "Upgrade to $DBversion done (added Syndetics Enhanced Content system preferences)\n";
2293     SetVersion ($DBversion);
2294 }
2295
2296 $DBversion = "3.01.00.016";
2297 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2298     $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')");
2299     print "Upgrade to $DBversion done (Added Babeltheque syspref)\n";
2300     SetVersion ($DBversion);
2301 }
2302
2303 $DBversion = "3.01.00.017";
2304 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2305     $dbh->do("ALTER TABLE `subscription` ADD `staffdisplaycount` VARCHAR(10) NULL;");
2306     $dbh->do("ALTER TABLE `subscription` ADD `opacdisplaycount` VARCHAR(10) NULL;");
2307     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2308     VALUES (
2309     'StaffSerialIssueDisplayCount', '3', '', 'Number of serial issues to display per subscription in the Staff client', 'Integer'
2310     );");
2311         $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2312     VALUES (
2313     'OPACSerialIssueDisplayCount', '3', '', 'Number of serial issues to display per subscription in the OPAC', 'Integer'
2314     );");
2315
2316     print "Upgrade to $DBversion done ( Updated table for Serials Display)\n";
2317     SetVersion ($DBversion);
2318 }
2319
2320 $DBversion = "3.01.00.018";
2321 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2322     $dbh->do("ALTER TABLE deletedborrowers ADD `smsalertnumber` varchar(50) default NULL");
2323     print "Upgrade to $DBversion done (added deletedborrowers.smsalertnumber, missed in 3.00.00.091)\n";
2324     SetVersion ($DBversion);
2325 }
2326
2327 $DBversion = "3.01.00.019";
2328 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2329         $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')");
2330     print "Upgrade to $DBversion done (adding OPACShowCheckoutName systempref)\n";
2331     SetVersion ($DBversion);
2332 }
2333
2334 $DBversion = "3.01.00.020";
2335 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2336     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesID','','See:http://librarything.com/forlibraries/','','free')");
2337     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesEnabled','0','Enable or Disable Library Thing for Libraries Features','','YesNo')");
2338     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesTabbedView','0','Put LibraryThingForLibraries Content in Tabs.','','YesNo')");
2339     print "Upgrade to $DBversion done (adding LibraryThing for Libraries sysprefs)\n";
2340     SetVersion ($DBversion);
2341 }
2342
2343 $DBversion = "3.01.00.021";
2344 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2345     my $enable_reviews = C4::Context->preference('OPACAmazonEnabled') ? '1' : '0';
2346     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAmazonReviews', '$enable_reviews', 'Display Amazon readers reviews on OPAC','','YesNo')");
2347     print "Upgrade to $DBversion done (adding OPACAmazonReviews syspref)\n";
2348     SetVersion ($DBversion);
2349 }
2350
2351 $DBversion = '3.01.00.022';
2352 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2353     $dbh->do("ALTER TABLE `labels_conf` MODIFY COLUMN `formatstring` mediumtext DEFAULT NULL");
2354     print "Upgrade to $DBversion done (bug 2945: increase size of labels_conf.formatstring)\n";
2355     SetVersion ($DBversion);
2356 }
2357
2358 $DBversion = '3.01.00.023';
2359 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2360     $dbh->do("ALTER TABLE biblioitems        MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2361     $dbh->do("ALTER TABLE deletedbiblioitems MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2362     $dbh->do("ALTER TABLE import_biblios     MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2363     $dbh->do("ALTER TABLE suggestions        MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2364     print "Upgrade to $DBversion done (bug 2765: increase width of isbn column in several tables)\n";
2365     SetVersion ($DBversion);
2366 }
2367
2368 $DBversion = "3.01.00.024";
2369 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2370     $dbh->do("ALTER TABLE labels MODIFY COLUMN batch_id int(10) NOT NULL default 1;");
2371     print "Upgrade to $DBversion done (change labels.batch_id from varchar to int)\n";
2372     SetVersion ($DBversion);
2373 }
2374
2375 $DBversion = '3.01.00.025';
2376 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2377     $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')");
2378
2379     print "Upgrade to $DBversion done (added ceilingDueDate system preference)\n";
2380     SetVersion ($DBversion);
2381 }
2382
2383 $DBversion = '3.01.00.026';
2384 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2385     $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')");
2386
2387     print "Upgrade to $DBversion done (added numReturnedItemsToShow system preference)\n";
2388     SetVersion ($DBversion);
2389 }
2390
2391 $DBversion = '3.01.00.027';
2392 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2393     $dbh->do("ALTER TABLE zebraqueue CHANGE `biblio_auth_number` `biblio_auth_number` bigint(20) unsigned NOT NULL default 0");
2394     print "Upgrade to $DBversion done (Increased size of zebraqueue biblio_auth_number to address bug 3148.)\n";
2395     SetVersion ($DBversion);
2396 }
2397
2398 $DBversion = '3.01.00.028';
2399 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2400     my $enable_reviews = C4::Context->preference('AmazonEnabled') ? '1' : '0';
2401     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AmazonReviews', '$enable_reviews', 'Display Amazon reviews on staff interface','','YesNo')");
2402     print "Upgrade to $DBversion done (added AmazonReviews)\n";
2403     SetVersion ($DBversion);
2404 }
2405
2406 $DBversion = '3.01.00.029';
2407 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2408     $dbh->do(q( UPDATE language_rfc4646_to_iso639
2409                 SET iso639_2_code = 'spa'
2410                 WHERE rfc4646_subtag = 'es'
2411                 AND   iso639_2_code = 'rus' )
2412             );
2413     print "Upgrade to $DBversion done (fixed bug 2599: using Spanish search limit retrieves Russian results)\n";
2414     SetVersion ($DBversion);
2415 }
2416
2417 $DBversion = "3.01.00.030";
2418 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2419     $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')");
2420     print "Upgrade to $DBversion done (added AllowNotForLoanOverride system preference)\n";
2421     SetVersion ($DBversion);
2422 }
2423
2424 $DBversion = "3.01.00.031";
2425 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2426     $dbh->do("ALTER TABLE branch_transfer_limits
2427               MODIFY toBranch   varchar(10) NOT NULL,
2428               MODIFY fromBranch varchar(10) NOT NULL,
2429               MODIFY itemtype   varchar(10) NULL");
2430     print "Upgrade to $DBversion done (fix column widths in branch_transfer_limits)\n";
2431     SetVersion ($DBversion);
2432 }
2433
2434 $DBversion = "3.01.00.032";
2435 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2436     $dbh->do(<<ENDOFRENEWAL);
2437 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');
2438 ENDOFRENEWAL
2439     print "Upgrade to $DBversion done (Change the field)\n";
2440     SetVersion ($DBversion);
2441 }
2442
2443 $DBversion = "3.01.00.033";
2444 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2445     $dbh->do(q/
2446         ALTER TABLE borrower_message_preferences
2447         MODIFY borrowernumber int(11) default NULL,
2448         ADD    categorycode varchar(10) default NULL AFTER borrowernumber,
2449         ADD KEY `categorycode` (`categorycode`),
2450         ADD CONSTRAINT `borrower_message_preferences_ibfk_3`
2451                        FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
2452                        ON DELETE CASCADE ON UPDATE CASCADE
2453     /);
2454     print "Upgrade to $DBversion done (DB changes to allow patron category defaults for messaging preferences)\n";
2455     SetVersion ($DBversion);
2456 }
2457
2458 $DBversion = "3.01.00.034";
2459 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2460     $dbh->do("ALTER TABLE `subscription` ADD COLUMN `graceperiod` INT(11) NOT NULL default '0';");
2461     print "Upgrade to $DBversion done (Adding graceperiod column to subscription table)\n";
2462     SetVersion ($DBversion);
2463 }
2464
2465 $DBversion = '3.01.00.035';
2466 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2467     $dbh->do(q{ ALTER TABLE `subscription` ADD location varchar(80) NULL DEFAULT '' AFTER callnumber; });
2468    print "Upgrade to $DBversion done (Adding location to subscription table)\n";
2469     SetVersion ($DBversion);
2470 }
2471
2472 $DBversion = '3.01.00.036';
2473 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2474     $dbh->do("UPDATE systempreferences SET explanation = 'Choose the default detail view in the staff interface; choose between normal, labeled_marc, marc or isbd'
2475               WHERE variable = 'IntranetBiblioDefaultView'
2476               AND   explanation = 'IntranetBiblioDefaultView'");
2477     $dbh->do("UPDATE systempreferences SET type = 'Choice', options = 'normal|marc|isbd|labeled_marc'
2478               WHERE variable = 'IntranetBiblioDefaultView'");
2479     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewISBD','1','Allow display of ISBD view of bibiographic records','','YesNo')");
2480     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewLabeledMARC','0','Allow display of labeled MARC view of bibiographic records','','YesNo')");
2481     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewMARC','1','Allow display of MARC view of bibiographic records','','YesNo')");
2482     print "Upgrade to $DBversion done (new viewISBD, viewLabeledMARC, viewMARC sysprefs and tweak IntranetBiblioDefaultView)\n";
2483     SetVersion ($DBversion);
2484 }
2485
2486 $DBversion = '3.01.00.037';
2487 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2488     $dbh->do('ALTER TABLE authorised_values ADD KEY `lib` (`lib`)');
2489     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('FilterBeforeOverdueReport','0','Do not run overdue report until filter selected','','YesNo')");
2490     SetVersion ($DBversion);
2491     print "Upgrade to $DBversion done (added FilterBeforeOverdueReport syspref and new index on authorised_values)\n";
2492 }
2493
2494 $DBversion = "3.01.00.038";
2495 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2496     # update branches table
2497     #
2498     $dbh->do("ALTER TABLE branches ADD `branchzip` varchar(25) default NULL AFTER `branchaddress3`");
2499     $dbh->do("ALTER TABLE branches ADD `branchcity` mediumtext AFTER `branchzip`");
2500     $dbh->do("ALTER TABLE branches ADD `branchcountry` text AFTER `branchcity`");
2501     $dbh->do("ALTER TABLE branches ADD `branchurl` mediumtext AFTER `branchemail`");
2502     $dbh->do("ALTER TABLE branches ADD `branchnotes` mediumtext AFTER `branchprinter`");
2503     print "Upgrade to $DBversion done (add ZIP, city, country, URL, and notes column to branches)\n";
2504     SetVersion ($DBversion);
2505 }
2506
2507 $DBversion = '3.01.00.039';
2508 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2509     $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')");
2510     $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')");
2511     SetVersion ($DBversion);
2512     print "Upgrade to $DBversion done (added SpineLabelFormat and SpineLabelAutoPrint sysprefs)\n";
2513 }
2514
2515 $DBversion = '3.01.00.040';
2516 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2517     $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')");
2518     $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')");
2519     SetVersion ($DBversion);
2520     print "Upgrade to $DBversion done (AllowHoldDateInFuture and OPACAllowHoldDateInFuture sysprefs)\n";
2521 }
2522
2523 $DBversion = '3.01.00.041';
2524 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2525     $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')");
2526     SetVersion ($DBversion);
2527     print "Upgrade to $DBversion done (added AWSPrivateKey syspref - note that if you use enhanced content from Amazon, this should be set right away.)\n";
2528 }
2529
2530 $DBversion = '3.01.00.042';
2531 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2532     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACFineNoRenewals','99999','Fine Limit above which user canmot renew books via OPAC','','Integer')");
2533     SetVersion ($DBversion);
2534     print "Upgrade to $DBversion done (added OPACFineNoRenewals syspref)\n";
2535 }
2536
2537 $DBversion = '3.01.00.043';
2538 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2539     $dbh->do('ALTER TABLE items ADD COLUMN permanent_location VARCHAR(80) DEFAULT NULL AFTER location');
2540     $dbh->do('UPDATE items SET permanent_location = location');
2541     $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 )', '')");
2542     $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')");
2543     $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')");
2544     SetVersion ($DBversion);
2545     print "Upgrade to $DBversion done (amended Item added NewItemsDefaultLocation, InProcessingToShelvingCart, ReturnToShelvingCart sysprefs)\n";
2546 }
2547
2548 $DBversion = '3.01.00.044';
2549 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2550     $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')");
2551     SetVersion ($DBversion);
2552     print "Upgrade to $DBversion done (added DisplayClearScreenButton system preference)\n";
2553 }
2554
2555 $DBversion = '3.01.00.045';
2556 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2557     $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')");
2558     SetVersion ($DBversion);
2559     print "Upgrade to $DBversion done (added a preference to hide the patrons name in the staff catalog)\n";
2560 }
2561
2562 $DBversion = "3.01.00.046";
2563 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2564     # update borrowers table
2565     #
2566     $dbh->do("ALTER TABLE borrowers ADD `country` text AFTER zipcode");
2567     $dbh->do("ALTER TABLE borrowers ADD `B_country` text AFTER B_zipcode");
2568     $dbh->do("ALTER TABLE deletedborrowers ADD `country` text AFTER zipcode");
2569     $dbh->do("ALTER TABLE deletedborrowers ADD `B_country` text AFTER B_zipcode");
2570     print "Upgrade to $DBversion done (add country and B_country to borrowers)\n";
2571     SetVersion ($DBversion);
2572 }
2573
2574 $DBversion = '3.01.00.047';
2575 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2576     $dbh->do("ALTER TABLE items MODIFY itemcallnumber varchar(255);");
2577     $dbh->do("ALTER TABLE deleteditems MODIFY itemcallnumber varchar(255);");
2578     $dbh->do("ALTER TABLE tmp_holdsqueue MODIFY itemcallnumber varchar(255);");
2579     SetVersion ($DBversion);
2580     print " Upgrade to $DBversion done (bug 2761: change max length of itemcallnumber to 255 from 30)\n";
2581 }
2582
2583 $DBversion = '3.01.00.048';
2584 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2585     $dbh->do("UPDATE userflags SET flagdesc='View Catalog (Librarian Interface)' WHERE bit=2;");
2586     $dbh->do("UPDATE userflags SET flagdesc='Edit Catalog (Modify bibliographic/holdings data)' WHERE bit=9;");
2587     $dbh->do("UPDATE userflags SET flagdesc='Allow to edit authorities' WHERE bit=14;");
2588     $dbh->do("UPDATE userflags SET flagdesc='Allow to access to the reports module' WHERE bit=16;");
2589     $dbh->do("UPDATE userflags SET flagdesc='Allow to manage serials subscriptions' WHERE bit=15;");
2590     SetVersion ($DBversion);
2591     print " Upgrade to $DBversion done (bug 2611: fix spelling/capitalization in permission flag descriptions)\n";
2592 }
2593
2594 $DBversion = '3.01.00.049';
2595 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2596     $dbh->do("UPDATE permissions SET description = 'Perform inventory (stocktaking) of your catalog' WHERE code = 'inventory';");
2597      SetVersion ($DBversion);
2598     print "Upgrade to $DBversion done (bug 2611: changed catalogue to catalog per the standard)\n";
2599 }
2600
2601 $DBversion = '3.01.00.050';
2602 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2603     $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');");
2604     SetVersion ($DBversion);
2605     print "Upgrade to $DBversion done (bug 1934: Add OPACSearchForTitleIn syspref)\n";
2606 }
2607
2608 $DBversion = '3.01.00.051';
2609 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2610     $dbh->do("UPDATE systempreferences SET explanation='Fine limit above which user cannot renew books via OPAC' WHERE variable='OPACFineNoRenewals';");
2611     $dbh->do("UPDATE systempreferences SET explanation='If set to ON, a clear screen button will appear on the circulation page.' WHERE variable='DisplayClearScreenButton';");
2612     SetVersion ($DBversion);
2613     print "Upgrade to $DBversion done (fixed typos in new sysprefs)\n";
2614 }
2615
2616 $DBversion = '3.01.00.052';
2617 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2618     $dbh->do('ALTER TABLE deleteditems ADD COLUMN permanent_location VARCHAR(80) DEFAULT NULL AFTER location');
2619     SetVersion ($DBversion);
2620     print "Upgrade to $DBversion done (bug 3481: add permanent_location column to deleteditems)\n";
2621 }
2622
2623 $DBversion = '3.01.00.053';
2624 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2625     my $upgrade_script = C4::Context->config("intranetdir") . "/installer/data/mysql/labels_upgrade.pl";
2626     system("perl $upgrade_script");
2627     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";
2628     SetVersion ($DBversion);
2629 }
2630
2631 $DBversion = '3.01.00.054';
2632 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2633     $dbh->do("ALTER TABLE borrowers ADD `B_address2` text AFTER B_address");
2634     $dbh->do("ALTER TABLE borrowers ADD `altcontactcountry` text AFTER altcontactzipcode");
2635     $dbh->do("ALTER TABLE deletedborrowers ADD `B_address2` text AFTER B_address");
2636     $dbh->do("ALTER TABLE deletedborrowers ADD `altcontactcountry` text AFTER altcontactzipcode");
2637     SetVersion ($DBversion);
2638     print "Upgrade to $DBversion done (bug 1600, bug 3454: add altcontactcountry and B_address2 to borrowers and deletedborrowers)\n";
2639 }
2640
2641 $DBversion = '3.01.00.055';
2642 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2643     $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'|);
2644     SetVersion ($DBversion);
2645     print "Upgrade to $DBversion done (changed OPACSearchForTitleIn per requests in bug 1934)\n";
2646 }
2647
2648 $DBversion = '3.01.00.056';
2649 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2650     $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');");
2651     SetVersion ($DBversion);
2652     print "Upgrade to $DBversion done (Bug 1172 : Add OPACPatronDetails syspref)\n";
2653 }
2654
2655 $DBversion = '3.01.00.057';
2656 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2657     $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');");
2658     SetVersion ($DBversion);
2659     print "Upgrade to $DBversion done (Bug 2576 : Add OPACFinesTab syspref)\n";
2660 }
2661
2662 $DBversion = '3.01.00.058';
2663 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2664     $dbh->do("ALTER TABLE `language_subtag_registry` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2665     $dbh->do("ALTER TABLE `language_rfc4646_to_iso639` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2666     $dbh->do("ALTER TABLE `language_descriptions` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2667     SetVersion ($DBversion);
2668     print "Upgrade to $DBversion done (Added primary keys to language tables)\n";
2669 }
2670
2671 $DBversion = '3.01.00.059';
2672 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2673     $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')");
2674     SetVersion ($DBversion);
2675     print "Upgrade to $DBversion done (added DisplayOPACiconsXSLT sysprefs)\n";
2676 }
2677
2678 $DBversion = '3.01.00.060';
2679 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2680     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowAllMessageDeletion','0','Allow any Library to delete any message','','YesNo');");
2681     $dbh->do('DROP TABLE IF EXISTS messages');
2682     $dbh->do("CREATE TABLE messages ( `message_id` int(11) NOT NULL auto_increment,
2683         `borrowernumber` int(11) NOT NULL,
2684         `branchcode` varchar(4) default NULL,
2685         `message_type` varchar(1) NOT NULL,
2686         `message` text NOT NULL,
2687         `message_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
2688         PRIMARY KEY (`message_id`)
2689         ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
2690
2691         print "Upgrade to $DBversion done ( Added AllowAllMessageDeletion syspref and messages table )\n";
2692     SetVersion ($DBversion);
2693 }
2694
2695 $DBversion = '3.01.00.061';
2696 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2697     $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')");
2698         print "Upgrade to $DBversion done ( Added ShowPatronImageInWebBasedSelfCheck system preference )\n";
2699     SetVersion ($DBversion);
2700 }
2701
2702 $DBversion = "3.01.00.062";
2703 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2704     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'manage_csv_profiles', 'Manage CSV export profiles')");
2705     $dbh->do(q/
2706         CREATE TABLE `export_format` (
2707           `export_format_id` int(11) NOT NULL auto_increment,
2708           `profile` varchar(255) NOT NULL,
2709           `description` mediumtext NOT NULL,
2710           `marcfields` mediumtext NOT NULL,
2711           PRIMARY KEY  (`export_format_id`)
2712         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Used for CSV export';
2713     /);
2714     print "Upgrade to $DBversion done (added csv export profiles)\n";
2715 }
2716
2717 $DBversion = "3.01.00.063";
2718 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2719     $dbh->do("
2720         CREATE TABLE `fieldmapping` (
2721           `id` int(11) NOT NULL auto_increment,
2722           `field` varchar(255) NOT NULL,
2723           `frameworkcode` char(4) NOT NULL default '',
2724           `fieldcode` char(3) NOT NULL,
2725           `subfieldcode` char(1) NOT NULL,
2726           PRIMARY KEY  (`id`)
2727         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2728              ");
2729     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";
2730 }
2731
2732 $DBversion = '3.01.00.065';
2733 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2734     $dbh->do('ALTER TABLE issuingrules ADD COLUMN `renewalsallowed` smallint(6) NOT NULL default "0" AFTER `issuelength`;');
2735     $sth = $dbh->prepare("SELECT itemtype, renewalsallowed FROM itemtypes");
2736     $sth->execute();
2737
2738     my $sthupd = $dbh->prepare("UPDATE issuingrules SET renewalsallowed = ? WHERE itemtype = ?");
2739
2740     while(my $row = $sth->fetchrow_hashref){
2741         $sthupd->execute($row->{renewalsallowed}, $row->{itemtype});
2742     }
2743
2744     $dbh->do('ALTER TABLE itemtypes DROP COLUMN `renewalsallowed`;');
2745
2746     SetVersion ($DBversion);
2747     print "Upgrade to $DBversion done (Moving allowed renewals from itemtypes to issuingrule)\n";
2748 }
2749
2750 $DBversion = '3.01.00.066';
2751 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2752     $dbh->do('ALTER TABLE issuingrules ADD COLUMN `reservesallowed` smallint(6) NOT NULL default "0" AFTER `renewalsallowed`;');
2753
2754     my $maxreserves = C4::Context->preference('maxreserves');
2755     $sth = $dbh->prepare('UPDATE issuingrules SET reservesallowed = ?;');
2756     $sth->execute($maxreserves);
2757
2758     $dbh->do('DELETE FROM systempreferences WHERE variable = "maxreserves";');
2759
2760     $dbh->do("INSERT INTO systempreferences (variable,value, options, explanation, type) VALUES('ReservesControlBranch','PatronLibrary','ItemHomeLibrary|PatronLibrary','Branch checked for members reservations rights','Choice')");
2761
2762     SetVersion ($DBversion);
2763     print "Upgrade to $DBversion done (Moving max allowed reserves from system preference to issuingrule)\n";
2764 }
2765
2766 $DBversion = "3.01.00.067";
2767 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2768     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'batchmod', 'Perform batch modification of items')");
2769     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'batchdel', 'Perform batch deletion of items')");
2770     print "Upgrade to $DBversion done (added permissions for batch modification and deletion)\n";
2771     SetVersion ($DBversion);
2772 }
2773
2774 $DBversion = "3.01.00.068";
2775 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2776         $dbh->do("ALTER TABLE issuingrules ADD COLUMN `finedays` int(11) default NULL AFTER `fine` ");
2777         print "Upgrade to $DBversion done (Adding finedays in issuingrules table)\n";
2778     SetVersion ($DBversion);
2779 }
2780
2781
2782 $DBversion = "3.01.00.069";
2783 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2784         $dbh->do("INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('EnableOpacSearchHistory', '1', '', 'Enable or disable opac search history', 'YesNo')");
2785
2786         my $create = <<SEARCHHIST;
2787 CREATE TABLE IF NOT EXISTS `search_history` (
2788   `userid` int(11) NOT NULL,
2789   `sessionid` varchar(32) NOT NULL,
2790   `query_desc` varchar(255) NOT NULL,
2791   `query_cgi` varchar(255) NOT NULL,
2792   `total` int(11) NOT NULL,
2793   `time` timestamp NOT NULL default CURRENT_TIMESTAMP,
2794   KEY `userid` (`userid`),
2795   KEY `sessionid` (`sessionid`)
2796 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Opac search history results';
2797 SEARCHHIST
2798         $dbh->do($create);
2799
2800         print "Upgrade to $DBversion done (added OPAC search history preference and table)\n";
2801 }
2802
2803 $DBversion = "3.01.00.070";
2804 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2805         $dbh->do("ALTER TABLE authorised_values ADD COLUMN `lib_opac` VARCHAR(80) default NULL AFTER `lib`");
2806         print "Upgrade to $DBversion done (Added a lib_opac field in authorised_values table)\n";
2807 }
2808
2809 $DBversion = "3.01.00.071";
2810 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2811         $dbh->do("ALTER TABLE `subscription` ADD `enddate` date default NULL");
2812         $dbh->do("ALTER TABLE subscriptionhistory CHANGE enddate histenddate DATE default NULL");
2813         print "Upgrade to $DBversion done ( Adding enddate to subscription)\n";
2814 }
2815
2816 # Acquisitions update
2817
2818 $DBversion = "3.01.00.072";
2819 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2820     $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')");
2821     # create a new syspref for the 'Mr anonymous' patron
2822     $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,'')");
2823     # fill AnonymousPatron with AnonymousSuggestion value (copy)
2824     my $sth=$dbh->prepare("SELECT value FROM systempreferences WHERE variable='AnonSuggestions'");
2825     $sth->execute;
2826     my ($value) = $sth->fetchrow() || 0;
2827     $dbh->do("UPDATE systempreferences SET value='$value' WHERE variable='AnonymousPatron'");
2828     # set AnonymousSuggestion do YesNo
2829     # 1st, set the value (1/True if it had a borrowernumber)
2830     $dbh->do("UPDATE systempreferences SET value=1 WHERE variable='AnonSuggestions' AND value>0");
2831     # 2nd, change the type to Choice
2832     $dbh->do("UPDATE systempreferences SET type='YesNo' WHERE variable='AnonSuggestions'");
2833         # borrower reading record privacy : 0 : forever, 1 : laws, 2 : don't keep at all
2834     $dbh->do("ALTER TABLE `borrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
2835     print "Upgrade to $DBversion done (add new syspref and column in borrowers)\n";
2836     SetVersion ($DBversion);
2837 }
2838
2839 $DBversion = '3.01.00.073';
2840 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2841     $dbh->do('SET FOREIGN_KEY_CHECKS=0 ');
2842     $dbh->do(<<'END_SQL');
2843 CREATE TABLE IF NOT EXISTS `aqcontract` (
2844   `contractnumber` int(11) NOT NULL auto_increment,
2845   `contractstartdate` date default NULL,
2846   `contractenddate` date default NULL,
2847   `contractname` varchar(50) default NULL,
2848   `contractdescription` mediumtext,
2849   `booksellerid` int(11) not NULL,
2850     PRIMARY KEY  (`contractnumber`),
2851         CONSTRAINT `booksellerid_fk1` FOREIGN KEY (`booksellerid`)
2852         REFERENCES `aqbooksellers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
2853 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
2854 END_SQL
2855     $dbh->do('SET FOREIGN_KEY_CHECKS=1 ');
2856     print "Upgrade to $DBversion done (adding aqcontract table)\n";
2857     SetVersion ($DBversion);
2858 }
2859
2860 $DBversion = '3.01.00.074';
2861 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2862     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `basketname` varchar(50) default NULL AFTER `basketno`");
2863     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `note` mediumtext AFTER `basketname`");
2864     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `booksellernote` mediumtext AFTER `note`");
2865     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `contractnumber` int(11) AFTER `booksellernote`");
2866     $dbh->do("ALTER TABLE `aqbasket` ADD FOREIGN KEY (`contractnumber`) REFERENCES `aqcontract` (`contractnumber`)");
2867     print "Upgrade to $DBversion done (edit aqbasket table done)\n";
2868     SetVersion ($DBversion);
2869 }
2870
2871 $DBversion = '3.01.00.075';
2872 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2873     $dbh->do("ALTER TABLE `aqorders` ADD COLUMN `uncertainprice` tinyint(1)");
2874
2875     print "Upgrade to $DBversion done (adding uncertainprices)\n";
2876     SetVersion ($DBversion);
2877 }
2878
2879 $DBversion = '3.01.00.076';
2880 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2881     $dbh->do('SET FOREIGN_KEY_CHECKS=0 ');
2882     $dbh->do("CREATE TABLE IF NOT EXISTS `aqbasketgroups` (
2883                          `id` int(11) NOT NULL auto_increment,
2884                          `name` varchar(50) default NULL,
2885                          `closed` tinyint(1) default NULL,
2886                          `booksellerid` int(11) NOT NULL,
2887                          PRIMARY KEY (`id`),
2888                          KEY `booksellerid` (`booksellerid`),
2889                          CONSTRAINT `aqbasketgroups_ibfk_1` FOREIGN KEY (`booksellerid`) REFERENCES `aqbooksellers` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
2890                          ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
2891     $dbh->do("ALTER TABLE aqbasket ADD COLUMN `basketgroupid` int(11)");
2892     $dbh->do("ALTER TABLE aqbasket ADD FOREIGN KEY (`basketgroupid`) REFERENCES `aqbasketgroups` (`id`) ON UPDATE CASCADE ON DELETE SET NULL");
2893     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('pdfformat','pdfformat::layout2pages','Controls what script is used for printing (basketgroups)','','free')");
2894     $dbh->do('SET FOREIGN_KEY_CHECKS=1 ');
2895     print "Upgrade to $DBversion done (adding basketgroups)\n";
2896     SetVersion ($DBversion);
2897 }
2898 $DBversion = '3.01.00.077';
2899 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2900
2901     $dbh->do("SET FOREIGN_KEY_CHECKS=0 ");
2902     # create a mapping table holding the info we need to match orders to budgets
2903     $dbh->do('DROP TABLE IF EXISTS fundmapping');
2904     $dbh->do(
2905         q|CREATE TABLE fundmapping AS
2906         SELECT aqorderbreakdown.ordernumber, branchcode, bookfundid, budgetdate, entrydate
2907         FROM aqorderbreakdown JOIN aqorders ON aqorderbreakdown.ordernumber = aqorders.ordernumber|);
2908     # match the new type of the corresponding field
2909     $dbh->do('ALTER TABLE fundmapping modify column bookfundid varchar(30)');
2910     # System did not ensure budgetdate was valid historically
2911     sanitize_zero_date('fundmapping', 'budgetdate');
2912     $dbh->do(q|UPDATE fundmapping SET budgetdate = entrydate WHERE budgetdate IS NULL|);
2913     # We save the map in fundmapping in case you need later processing
2914     $dbh->do(q|ALTER TABLE fundmapping add column aqbudgetid integer|);
2915     # these can speed processing up
2916     $dbh->do(q|CREATE INDEX fundmaporder ON fundmapping (ordernumber)|);
2917     $dbh->do(q|CREATE INDEX fundmapid ON fundmapping (bookfundid)|);
2918
2919     $dbh->do("DROP TABLE IF EXISTS `aqbudgetperiods` ");
2920
2921     $dbh->do(qq|
2922                     CREATE TABLE `aqbudgetperiods` (
2923                     `budget_period_id` int(11) NOT NULL auto_increment,
2924                     `budget_period_startdate` date NOT NULL,
2925                     `budget_period_enddate` date NOT NULL,
2926                     `budget_period_active` tinyint(1) default '0',
2927                     `budget_period_description` mediumtext,
2928                     `budget_period_locked` tinyint(1) default NULL,
2929                     `sort1_authcat` varchar(10) default NULL,
2930                     `sort2_authcat` varchar(10) default NULL,
2931                     PRIMARY KEY  (`budget_period_id`)
2932                     ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 |);
2933
2934    $dbh->do(<<ADDPERIODS);
2935 INSERT INTO aqbudgetperiods (budget_period_startdate,budget_period_enddate,budget_period_active,budget_period_description,budget_period_locked)
2936 SELECT DISTINCT startdate, enddate, NOW() BETWEEN startdate and enddate, concat(startdate," ",enddate),NOT NOW() BETWEEN startdate AND enddate from aqbudget
2937 ADDPERIODS
2938 # SORRY , NO AQBUDGET/AQBOOKFUND -> AQBUDGETS IMPORT JUST YET,
2939 # BUT A NEW CLEAN AQBUDGETS TABLE CREATE FOR NOW..
2940 # DROP TABLE IF EXISTS `aqbudget`;
2941 #CREATE TABLE `aqbudget` (
2942 #  `bookfundid` varchar(10) NOT NULL default ',
2943 #    `startdate` date NOT NULL default 0,
2944 #         `enddate` date default NULL,
2945 #           `budgetamount` decimal(13,2) default NULL,
2946 #                 `aqbudgetid` tinyint(4) NOT NULL auto_increment,
2947 #                   `branchcode` varchar(10) default NULL,
2948     DropAllForeignKeys('aqbudget');
2949   #$dbh->do("drop table aqbudget;");
2950
2951
2952     my $maxbudgetid = $dbh->selectcol_arrayref(<<IDsBUDGET);
2953 SELECT MAX(aqbudgetid) from aqbudget
2954 IDsBUDGET
2955
2956 $$maxbudgetid[0] = 0 if !$$maxbudgetid[0];
2957
2958     $dbh->do(<<BUDGETAUTOINCREMENT);
2959 ALTER TABLE aqbudget AUTO_INCREMENT=$$maxbudgetid[0]
2960 BUDGETAUTOINCREMENT
2961
2962     $dbh->do(<<BUDGETNAME);
2963 ALTER TABLE aqbudget RENAME `aqbudgets`
2964 BUDGETNAME
2965
2966     $dbh->do(<<BUDGETS);
2967 ALTER TABLE `aqbudgets`
2968    CHANGE  COLUMN aqbudgetid `budget_id` int(11) NOT NULL AUTO_INCREMENT,
2969    CHANGE  COLUMN branchcode `budget_branchcode` varchar(10) default NULL,
2970    CHANGE  COLUMN budgetamount `budget_amount` decimal(28,6) NOT NULL default '0.00',
2971    CHANGE  COLUMN bookfundid   `budget_code` varchar(30) default NULL,
2972    ADD     COLUMN `budget_parent_id` int(11) default NULL,
2973    ADD     COLUMN `budget_name` varchar(80) default NULL,
2974    ADD     COLUMN `budget_encumb` decimal(28,6) default '0.00',
2975    ADD     COLUMN `budget_expend` decimal(28,6) default '0.00',
2976    ADD     COLUMN `budget_notes` mediumtext,
2977    ADD     COLUMN `budget_description` mediumtext,
2978    ADD     COLUMN `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
2979    ADD     COLUMN `budget_amount_sublevel`  decimal(28,6) AFTER `budget_amount`,
2980    ADD     COLUMN `budget_period_id` int(11) default NULL,
2981    ADD     COLUMN `sort1_authcat` varchar(80) default NULL,
2982    ADD     COLUMN `sort2_authcat` varchar(80) default NULL,
2983    ADD     COLUMN `budget_owner_id` int(11) default NULL,
2984    ADD     COLUMN `budget_permission` int(1) default '0';
2985 BUDGETS
2986
2987     $dbh->do(<<BUDGETCONSTRAINTS);
2988 ALTER TABLE `aqbudgets`
2989    ADD CONSTRAINT `aqbudgets_ifbk_1` FOREIGN KEY (`budget_period_id`) REFERENCES `aqbudgetperiods` (`budget_period_id`) ON DELETE CASCADE ON UPDATE CASCADE
2990 BUDGETCONSTRAINTS
2991 #    $dbh->do(<<BUDGETPKDROP);
2992 #ALTER TABLE `aqbudgets`
2993 #   DROP PRIMARY KEY
2994 #BUDGETPKDROP
2995 #    $dbh->do(<<BUDGETPKADD);
2996 #ALTER TABLE `aqbudgets`
2997 #   ADD PRIMARY KEY budget_id
2998 #BUDGETPKADD
2999
3000
3001         my $query_period= $dbh->prepare(qq|SELECT budget_period_id from aqbudgetperiods where budget_period_startdate=? and budget_period_enddate=?|);
3002         my $query_bookfund= $dbh->prepare(qq|SELECT * from aqbookfund where bookfundid=?|);
3003         my $selectbudgets=$dbh->prepare(qq|SELECT * from aqbudgets|);
3004         my $updatebudgets=$dbh->prepare(qq|UPDATE aqbudgets SET budget_period_id= ? , budget_name=?, budget_branchcode=? where budget_id=?|);
3005         $selectbudgets->execute;
3006         while (my $databudget=$selectbudgets->fetchrow_hashref){
3007                 $query_period->execute ($$databudget{startdate},$$databudget{enddate});
3008                 my ($budgetperiodid)=$query_period->fetchrow;
3009                 $query_bookfund->execute ($$databudget{budget_code});
3010                 my $databf=$query_bookfund->fetchrow_hashref;
3011                 my $branchcode=$$databudget{budget_branchcode}||$$databf{branchcode};
3012                 $updatebudgets->execute($budgetperiodid,$$databf{bookfundname},$branchcode,$$databudget{budget_id});
3013         }
3014     $dbh->do(<<BUDGETDROPDATES);
3015 ALTER TABLE `aqbudgets`
3016    DROP startdate,
3017    DROP enddate
3018 BUDGETDROPDATES
3019
3020
3021     $dbh->do("DROP TABLE IF EXISTS `aqbudgets_planning` ");
3022     $dbh->do("CREATE TABLE  `aqbudgets_planning` (
3023                     `plan_id` int(11) NOT NULL auto_increment,
3024                     `budget_id` int(11) NOT NULL,
3025                     `budget_period_id` int(11) NOT NULL,
3026                     `estimated_amount` decimal(28,6) default NULL,
3027                     `authcat` varchar(30) NOT NULL,
3028                     `authvalue` varchar(30) NOT NULL,
3029                                         `display` tinyint(1) DEFAULT 1,
3030                         PRIMARY KEY  (`plan_id`),
3031                         CONSTRAINT `aqbudgets_planning_ifbk_1` FOREIGN KEY (`budget_id`) REFERENCES `aqbudgets` (`budget_id`) ON DELETE CASCADE ON UPDATE CASCADE
3032                         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
3033
3034     $dbh->do("ALTER TABLE `aqorders`
3035                     ADD COLUMN `budget_id` tinyint(4) NOT NULL,
3036                     ADD COLUMN `budgetgroup_id` int(11) NOT NULL,
3037                     ADD COLUMN  `sort1_authcat` varchar(10) default NULL,
3038                     ADD COLUMN  `sort2_authcat` varchar(10) default NULL" );
3039                 # We need to map the orders to the budgets
3040                 # For Historic reasons this is more complex than it should be on occasions
3041                 my $budg_arr = $dbh->selectall_arrayref(
3042                     q|SELECT aqbudgets.budget_id, aqbudgets.budget_code, aqbudgetperiods.budget_period_startdate,
3043                     aqbudgetperiods.budget_period_enddate
3044                     FROM aqbudgets JOIN aqbudgetperiods ON aqbudgets.budget_period_id = aqbudgetperiods.budget_period_id
3045                     ORDER BY budget_code, budget_period_startdate|, { Slice => {} });
3046                 # We arbitarily order on start date, this means if you have overlapping periods the order will be
3047                 # linked to the latest matching budget YMMV
3048                 my $b_sth = $dbh->prepare(
3049                     'UPDATE fundmapping set aqbudgetid = ? where bookfundid =? AND budgetdate >= ? AND budgetdate <= ?');
3050                 for my $b ( @{$budg_arr}) {
3051                     $b_sth->execute($b->{budget_id}, $b->{budget_code}, $b->{budget_period_startdate}, $b->{budget_period_enddate});
3052                 }
3053                 # move the budgetids to aqorders
3054                 $dbh->do(q|UPDATE aqorders, fundmapping SET aqorders.budget_id = fundmapping.aqbudgetid
3055                     WHERE aqorders.ordernumber = fundmapping.ordernumber AND fundmapping.aqbudgetid IS NOT NULL|);
3056                 # NB fundmapping is left as an accontants trail also if you have budgetids that werent set
3057                 # you can decide what to do with them
3058
3059      $dbh->do(
3060          q|UPDATE aqorders, aqbudgets SET aqorders.budgetgroup_id = aqbudgets.budget_period_id
3061          WHERE aqorders.budget_id = aqbudgets.budget_id|);
3062                 # cannot do until aqorderbreakdown removed
3063 #    $dbh->do("DROP TABLE aqbookfund ");
3064 #    $dbh->do("ALTER TABLE aqorders  ADD FOREIGN KEY (`budget_id`) REFERENCES `aqbudgets` (`budget_id`) ON UPDATE CASCADE  " ); ????
3065     $dbh->do("SET FOREIGN_KEY_CHECKS=1 ");
3066
3067     print "Upgrade to $DBversion done (Adding new aqbudgetperiods, aqbudgets and aqbudget_planning tables  )\n";
3068     SetVersion ($DBversion);
3069 }
3070
3071
3072
3073 $DBversion = '3.01.00.078';
3074 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3075     $dbh->do("ALTER TABLE aqbudgetperiods ADD COLUMN budget_period_total decimal(28,6)");
3076     print "Upgrade to $DBversion done (adds 'budget_period_total' column to aqbudgetperiods table)\n";
3077     SetVersion($DBversion);
3078 }
3079
3080
3081 $DBversion = '3.01.00.079';
3082 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3083     $dbh->do("ALTER TABLE currency ADD COLUMN active  tinyint(1)");
3084
3085     print "Upgrade to $DBversion done (adds 'active' column to currencies table)\n";
3086     SetVersion($DBversion);
3087 }
3088
3089 $DBversion = '3.01.00.080';
3090 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3091     $dbh->do(<<BUDG_PERM );
3092 INSERT INTO permissions (module_bit, code, description) VALUES
3093             (11, 'vendors_manage', 'Manage vendors'),
3094             (11, 'contracts_manage', 'Manage contracts'),
3095             (11, 'period_manage', 'Manage periods'),
3096             (11, 'budget_manage', 'Manage budgets'),
3097             (11, 'budget_modify', "Modify budget (can't create lines but can modify existing ones)"),
3098             (11, 'planning_manage', 'Manage budget plannings'),
3099             (11, 'order_manage', 'Manage orders & basket'),
3100             (11, 'group_manage', 'Manage orders & basketgroups'),
3101             (11, 'order_receive', 'Manage orders & basket'),
3102             (11, 'budget_add_del', "Add and delete budgets (but can't modify budgets)");
3103 BUDG_PERM
3104
3105     print "Upgrade to $DBversion done (adds permissions for the acquisitions module)\n";
3106     SetVersion($DBversion);
3107 }
3108
3109
3110 $DBversion = '3.01.00.081';
3111 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3112     $dbh->do("ALTER TABLE aqbooksellers ADD COLUMN `gstrate` decimal(6,4) default NULL");
3113     if (my $gist=C4::Context->preference("gist")){
3114                 my $sql=$dbh->prepare("UPDATE aqbooksellers set `gstrate`=? ");
3115         $sql->execute($gist) ;
3116         }
3117     print "Upgrade to $DBversion done (added per-supplier gstrate setting)\n";
3118     SetVersion($DBversion);
3119 }
3120
3121 $DBversion = "3.01.00.082";
3122 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3123     if (C4::Context->preference("opaclanguages") eq "fr") {
3124         $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')#);
3125     } else {
3126         $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')");
3127     }
3128     print "Upgrade to $DBversion done (adding ReservesNeedReturns systempref, in circulation)\n";
3129     SetVersion ($DBversion);
3130 }
3131
3132 $DBversion = "3.01.00.083";
3133 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3134     $dbh->do(qq|
3135  CREATE TABLE `aqorders_items` (
3136   `ordernumber` int(11) NOT NULL,
3137   `itemnumber` int(11) NOT NULL,
3138   `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
3139   PRIMARY KEY  (`itemnumber`),
3140   KEY `ordernumber` (`ordernumber`)
3141 ) ENGINE=InnoDB DEFAULT CHARSET=utf8   |
3142     );
3143
3144     $dbh->do(qq| DROP TABLE aqorderbreakdown |);
3145     $dbh->do('DROP TABLE aqbookfund');
3146     print "Upgrade to $DBversion done (New aqorders_items table for acqui)\n";
3147     SetVersion ($DBversion);
3148 }
3149
3150 $DBversion = "3.01.00.084";
3151 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3152     $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')  #);
3153
3154     print "Upgrade to $DBversion done (CurrencyFormat syspref added)\n";
3155     SetVersion ($DBversion);
3156 }
3157
3158 $DBversion = "3.01.00.085";
3159 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3160     $dbh->do("ALTER table aqorders drop column title");
3161     $dbh->do("ALTER TABLE `aqorders` CHANGE `budget_id` `budget_id` INT( 11 ) NOT NULL");
3162     print "Upgrade to $DBversion done update budget_id size that should not be a tinyint\n";
3163     SetVersion ($DBversion);
3164 }
3165
3166 $DBversion = "3.01.00.086";
3167 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3168     $dbh->do(<<SUGGESTIONS);
3169 ALTER table suggestions
3170     ADD budgetid INT(11),
3171     ADD branchcode VARCHAR(10) default NULL,
3172     ADD acceptedby INT(11) default NULL,
3173     ADD accepteddate date default NULL,
3174     ADD suggesteddate date default NULL,
3175     ADD manageddate date default NULL,
3176     ADD rejectedby INT(11) default NULL,
3177     ADD rejecteddate date default NULL,
3178     ADD collectiontitle text default NULL,
3179     ADD itemtype VARCHAR(30) default NULL
3180     ;
3181 SUGGESTIONS
3182     print "Upgrade to $DBversion done (Suggestions)\n";
3183     SetVersion ($DBversion);
3184 }
3185
3186 $DBversion = "3.01.00.087";
3187 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3188     $dbh->do("ALTER table aqbudgets drop column budget_amount_sublevel;");
3189     print "Upgrade to $DBversion done (Drop column budget_amount_sublevel from aqbudgets)\n";
3190     SetVersion ($DBversion);
3191 }
3192
3193 $DBversion = "3.01.00.088";
3194 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3195     $dbh->do(  qq# INSERT INTO `systempreferences` VALUES ('intranetbookbag','1','','If ON, enables display of Cart feature in the intranet','YesNo')  #);
3196
3197     print "Upgrade to $DBversion done (intranetbookbag syspref added)\n";
3198     SetVersion ($DBversion);
3199 }
3200
3201 $DBversion = "3.01.00.090";
3202 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3203 $dbh->do("
3204        INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3205                 (16, 'execute_reports', 'Execute SQL reports'),
3206                 (16, 'create_reports', 'Create SQL Reports')
3207         ");
3208
3209     print "Upgrade to $DBversion done (granular permissions for guided reports added)\n";
3210     SetVersion ($DBversion);
3211 }
3212
3213 $DBversion = "3.01.00.091";
3214 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3215 $dbh->do("
3216         UPDATE `systempreferences` SET `options` = 'holdings|serialcollection|subscriptions'
3217         WHERE `systempreferences`.`variable` = 'opacSerialDefaultTab' LIMIT 1
3218         ");
3219
3220     print "Upgrade to $DBversion done (opac-detail default tag updated)\n";
3221     SetVersion ($DBversion);
3222 }
3223
3224 $DBversion = "3.01.00.092";
3225 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3226     if (C4::Context->preference("opaclanguages") =~ /fr/) {
3227         $dbh->do(qq{
3228 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');
3229         });
3230         }else{
3231         $dbh->do(qq{
3232 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');
3233         });
3234         }
3235     print "Upgrade to $DBversion done (Added RoutingListAddReserves syspref)\n";
3236     SetVersion ($DBversion);
3237 }
3238
3239 $DBversion = "3.01.00.093";
3240 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3241         $dbh->do(qq{
3242         ALTER TABLE biblioitems ADD INDEX issn_idx (issn);
3243         });
3244     print "Upgrade to $DBversion done (added index to ISSN)\n";
3245     SetVersion ($DBversion);
3246 }
3247
3248 $DBversion = "3.01.00.094";
3249 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3250         $dbh->do(qq{
3251         ALTER TABLE aqbasketgroups ADD deliveryplace VARCHAR(10) default NULL, ADD deliverycomment VARCHAR(255) default NULL;
3252         });
3253
3254     print "Upgrade to $DBversion done (adding deliveryplace deliverycomment to basketgroups)\n";
3255     SetVersion ($DBversion);
3256 }
3257
3258 $DBversion = "3.01.00.095";
3259 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3260         $dbh->do(qq{
3261         ALTER TABLE items ADD stocknumber VARCHAR(32) DEFAULT NULL COMMENT "stores the inventory number";
3262         });
3263         $dbh->do(qq{
3264         ALTER TABLE items ADD UNIQUE INDEX itemsstocknumberidx (stocknumber);
3265         });
3266         $dbh->do(qq{
3267         ALTER TABLE deleteditems ADD stocknumber VARCHAR(32) DEFAULT NULL COMMENT "stores the inventory number of deleted items";
3268         });
3269         $dbh->do(qq{
3270         ALTER TABLE deleteditems ADD UNIQUE INDEX deleteditemsstocknumberidx (stocknumber);
3271         });
3272         if (C4::Context->preference('marcflavour') eq 'UNIMARC'){
3273                 $dbh->do(qq{
3274         INSERT IGNORE INTO marc_subfield_structure (frameworkcode,tagfield, tagsubfield, tab, repeatable, mandatory,kohafield)
3275         SELECT DISTINCT (frameworkcode),995,"j",10,0,0,"items.stocknumber" from biblio_framework ;
3276                 });
3277                 #Previously, copynumber was used as stocknumber
3278                 $dbh->do(qq{
3279         UPDATE items set stocknumber=copynumber;
3280                 });
3281                 $dbh->do(qq{
3282         UPDATE items set copynumber=NULL;
3283                 });
3284         }
3285     print "Upgrade to $DBversion done (stocknumber field added)\n";
3286     SetVersion ($DBversion);
3287 }
3288
3289 $DBversion = "3.01.00.096";
3290 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3291     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OrderPdfTemplate','','Uploads a PDF template to use for printing baskets','NULL','Upload')");
3292     $dbh->do("UPDATE systempreferences SET variable='OrderPdfFormat' WHERE variable='pdfformat'");
3293     print "Upgrade to $DBversion done (PDF orders system preferences added and updated)\n";
3294     SetVersion ($DBversion);
3295 }
3296
3297 $DBversion = "3.01.00.097";
3298 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3299         $dbh->do(qq{
3300         ALTER TABLE aqbasketgroups ADD billingplace VARCHAR(10) NOT NULL AFTER deliverycomment;
3301         });
3302
3303     print "Upgrade to $DBversion done (Adding billingplace to aqbasketgroups)\n";
3304     SetVersion ($DBversion);
3305 }
3306
3307 $DBversion = "3.01.00.098";
3308 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3309         $dbh->do(qq{
3310         ALTER TABLE auth_subfield_structure MODIFY frameworkcode VARCHAR(10) NULL;
3311         });
3312
3313     print "Upgrade to $DBversion done (changing frameworkcode length in auth_subfield_structure)\n";
3314     SetVersion ($DBversion);
3315 }
3316
3317 $DBversion = "3.01.00.099";
3318 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3319         $dbh->do(qq{
3320                 INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3321                 (9, 'edit_catalogue', 'Edit catalogue'),
3322                 (9, 'fast_cataloging', 'Fast cataloging')
3323         });
3324
3325     print "Upgrade to $DBversion done (granular permissions for cataloging added)\n";
3326     SetVersion ($DBversion);
3327 }
3328
3329 $DBversion = "3.01.00.100";
3330 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3331         $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')");
3332         print "Upgrade to $DBversion done (added CAS authentication system preferences)\n";
3333     SetVersion ($DBversion);
3334 }
3335
3336 $DBversion = "3.01.00.101";
3337 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3338         $dbh->do(
3339         "INSERT INTO systempreferences
3340            (variable, value, options, explanation, type)
3341          VALUES (
3342             'OverdueNoticeBcc', '', '',
3343             'Email address to Bcc outgoing notices sent by email',
3344             'free')
3345          ");
3346         print "Upgrade to $DBversion done (added OverdueNoticeBcc system preferences)\n";
3347     SetVersion ($DBversion);
3348 }
3349 $DBversion = "3.01.00.102";
3350 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3351     $dbh->do(
3352     "UPDATE permissions set description = 'Edit catalog (Modify bibliographic/holdings data)' where module_bit = 9 and code = 'edit_catalogue'"
3353     );
3354         print "Upgrade to $DBversion done (fixed spelling error in edit_catalogue permission)\n";
3355     SetVersion ($DBversion);
3356 }
3357
3358 $DBversion = "3.01.00.103";
3359 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3360         $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES (13, 'moderate_tags', 'Moderate patron tags')");
3361         print "Upgrade to $DBversion done (adding patron permissions for tags tool)\n";
3362     SetVersion ($DBversion);
3363 }
3364
3365 $DBversion = "3.01.00.104";
3366 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3367
3368     my ($maninv_count, $borrnotes_count);
3369     eval { $maninv_count = $dbh->do("SELECT 1 FROM authorised_values WHERE category='MANUAL_INV'"); };
3370     if ($maninv_count == 0) {
3371         $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('MANUAL_INV','Copier Fees','.25')");
3372     }
3373     eval { $borrnotes_count = $dbh->do("SELECT 1 FROM authorised_values WHERE category='BOR_NOTES'"); };
3374     if ($borrnotes_count == 0) {
3375         $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('BOR_NOTES','ADDR','Address Notes')");
3376     }
3377
3378     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('LOC','CART','Book Cart')");
3379     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('LOC','PROC','Processing Center')");
3380
3381         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";
3382         SetVersion ($DBversion);
3383 }
3384
3385
3386 $DBversion = "3.01.00.105";
3387 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3388     $dbh->do("
3389       CREATE TABLE `collections` (
3390         `colId` int(11) NOT NULL auto_increment,
3391         `colTitle` varchar(100) NOT NULL default '',
3392         `colDesc` text NOT NULL,
3393         `colBranchcode` varchar(4) default NULL COMMENT 'branchcode for branch where item should be held.',
3394         PRIMARY KEY  (`colId`)
3395       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3396     ");
3397
3398     $dbh->do("
3399       CREATE TABLE `collections_tracking` (
3400         `ctId` int(11) NOT NULL auto_increment,
3401         `colId` int(11) NOT NULL default '0' COMMENT 'collections.colId',
3402         `itemnumber` int(11) NOT NULL default '0' COMMENT 'items.itemnumber',
3403         PRIMARY KEY  (`ctId`)
3404       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3405     ");
3406     $dbh->do("
3407         INSERT INTO permissions (module_bit, code, description)
3408         VALUES ( 13, 'rotating_collections', 'Manage Rotating collections')" );
3409         print "Upgrade to $DBversion done (added collection and collection_tracking tables for rotating collections functionality)\n";
3410     SetVersion ($DBversion);
3411 }
3412 $DBversion = "3.01.00.106";
3413 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3414         $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' )");
3415         print "Upgrade to $DBversion done (added OpacAddMastheadLibraryPulldown system preferences)\n";
3416     SetVersion ($DBversion);
3417 }
3418
3419 $DBversion = '3.01.00.107';
3420 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3421     my $upgrade_script = C4::Context->config("intranetdir") . "/installer/data/mysql/patroncards_upgrade.pl";
3422     system("perl $upgrade_script");
3423     print "Upgrade to $DBversion done (Migrated labels and patroncards tables and data to new schema.)\n";
3424     SetVersion ($DBversion);
3425 }
3426
3427 $DBversion = '3.01.00.108';
3428 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3429         $dbh->do(qq{
3430     ALTER TABLE `export_format` ADD `csv_separator` VARCHAR( 2 ) NOT NULL AFTER `marcfields` ,
3431     ADD `field_separator` VARCHAR( 2 ) NOT NULL AFTER `csv_separator` ,
3432     ADD `subfield_separator` VARCHAR( 2 ) NOT NULL AFTER `field_separator`
3433     });
3434         print "Upgrade to $DBversion done (added separators for csv export)\n";
3435     SetVersion ($DBversion);
3436 }
3437
3438 $DBversion = "3.01.00.109";
3439 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3440         $dbh->do(qq{
3441         ALTER TABLE `export_format` ADD `encoding` VARCHAR(255) NOT NULL AFTER `subfield_separator`
3442         });
3443         print "Upgrade to $DBversion done (added encoding for csv export)\n";
3444     SetVersion ($DBversion);
3445 }
3446
3447 $DBversion = '3.01.00.110';
3448 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3449     $dbh->do('ALTER TABLE `categories` ADD COLUMN `enrolmentperioddate` DATE NULL DEFAULT NULL AFTER `enrolmentperiod`');
3450     print "Upgrade to $DBversion done (Add enrolment period date support)\n";
3451     SetVersion ($DBversion);
3452 }
3453
3454 $DBversion = '3.01.00.111';
3455 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3456     print "Upgrade to $DBversion done (mark DBrev for 3.2-alpha release)\n";
3457     SetVersion ($DBversion);
3458 }
3459
3460 $DBversion = '3.01.00.112';
3461 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3462         $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');");
3463         print "Upgrade to $DBversion done ( added Show Spine Label Printer on Bib Items Details preferences )\n";
3464     SetVersion ($DBversion);
3465 }
3466
3467 $DBversion = '3.01.00.113';
3468 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3469     my $value = C4::Context->preference("XSLTResultsDisplay");
3470     $dbh->do(
3471         "INSERT INTO systempreferences (variable,value,type)
3472          VALUES('OPACXSLTResultsDisplay',?,'YesNo')", {}, $value ? 1 : 0);
3473     $value = C4::Context->preference("XSLTDetailsDisplay");
3474     $dbh->do(
3475         "INSERT INTO systempreferences (variable,value,type)
3476          VALUES('OPACXSLTDetailsDisplay',?,'YesNo')", {}, $value ? 1 : 0);
3477     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";
3478     SetVersion ($DBversion);
3479 }
3480
3481 $DBversion = '3.01.00.114';
3482 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3483     $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')");
3484     $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')");
3485     $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')");
3486         print "Upgrade to $DBversion done ( Added AutoSelfCheckAllowed, AutoSelfCheckID, and AutoShelfCheckPass system preference )\n";
3487     SetVersion ($DBversion);
3488 }
3489
3490 $DBversion = '3.01.00.115';
3491 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3492     $dbh->do('UPDATE aqorders SET quantityreceived = 0 WHERE quantityreceived IS NULL');
3493     $dbh->do('ALTER TABLE aqorders MODIFY COLUMN quantityreceived smallint(6) NOT NULL DEFAULT 0');
3494         print "Upgrade to $DBversion done ( Default aqorders.quantityreceived to 0 )\n";
3495     SetVersion ($DBversion);
3496 }
3497
3498 $DBversion = '3.01.00.116';
3499 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3500         if (C4::Context->preference('OrderPdfFormat') eq 'pdfformat::example'){
3501                 $dbh->do("UPDATE `systempreferences` set value='pdfformat::layout2pages' WHERE variable='OrderPdfFormat'");
3502         }
3503         print "Upgrade to $DBversion done (corrected default OrderPdfFormat value if still set wrong )\n";
3504     SetVersion ($DBversion);
3505 }
3506
3507 $DBversion = '3.01.00.117';
3508 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3509     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'por' WHERE rfc4646_subtag='pt' ");
3510     print "Upgrade to $DBversion done (corrected ISO 639-2 language code for Portuguese)\n";
3511     SetVersion ($DBversion);
3512 }
3513
3514 $DBversion = '3.01.00.118';
3515 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3516     my ($count) = $dbh->selectrow_array("SELECT count(*) FROM information_schema.columns
3517                                          WHERE table_name = 'aqbudgets_planning'
3518                                          AND column_name = 'display'");
3519     if ($count < 1) {
3520         $dbh->do("ALTER TABLE aqbudgets_planning ADD COLUMN display tinyint(1) DEFAULT 1");
3521     }
3522     print "Upgrade to $DBversion done (bug 4203: add display column to aqbudgets_planning if missing)\n";
3523     SetVersion ($DBversion);
3524 }
3525
3526 $DBversion = '3.01.00.119';
3527 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3528     eval{require Locale::Currency::Format};
3529     if (!$@) {
3530         print "Upgrade to $DBversion done (Locale::Currency::Format installed.)\n";
3531         SetVersion ($DBversion);
3532     }
3533     else {
3534         print "Upgrade to $DBversion done.\n";
3535         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";
3536         SetVersion ($DBversion);
3537     }
3538 }
3539
3540 $DBversion = '3.01.00.120';
3541 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3542     $dbh->do(q{
3543 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');
3544 });
3545     print "Upgrade to $DBversion done (bug 1080: add soundon system preference for circulation sounds)\n";
3546     SetVersion ($DBversion);
3547 }
3548
3549 $DBversion = '3.01.00.121';
3550 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3551     $dbh->do("ALTER TABLE `reserves` ADD `expirationdate` DATE DEFAULT NULL");
3552     $dbh->do("ALTER TABLE `reserves` ADD `lowestPriority` tinyint(1) NOT NULL");
3553     $dbh->do("ALTER TABLE `old_reserves` ADD `expirationdate` DATE DEFAULT NULL");
3554     $dbh->do("ALTER TABLE `old_reserves` ADD `lowestPriority` tinyint(1) NOT NULL");
3555     print "Upgrade to $DBversion done ( Added Additional Fields to Reserves tables )\n";
3556     SetVersion ($DBversion);
3557 }
3558
3559 $DBversion = '3.01.00.122';
3560 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3561     $dbh->do(q{
3562       INSERT INTO systempreferences (variable,value,explanation,options,type)
3563       VALUES ('OAI-PMH:ConfFile', '', 'If empty, Koha OAI Server operates in normal mode, otherwise it operates in extended mode.','','File');
3564 });
3565     print "Upgrade to $DBversion done. — Add a new system preference OAI-PMF:ConfFile\n";
3566     SetVersion ($DBversion);
3567 }
3568
3569 $DBversion = "3.01.00.123";
3570 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3571     $dbh->do("INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3572         (6, 'place_holds', 'Place holds for patrons')");
3573     $dbh->do("INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3574         (6, 'modify_holds_priority', 'Modify holds priority')");
3575     $dbh->do("UPDATE `userflags` SET `flagdesc` = 'Place and modify holds for patrons' WHERE `flag` = 'reserveforothers'");
3576     print "Upgrade to $DBversion done (Add granular permission for holds modification and update description of reserveforothers permission)\n";
3577     SetVersion ($DBversion);
3578 }
3579
3580 $DBversion = '3.01.00.124';
3581 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3582     $dbh->do("
3583         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>>).');
3584     ");
3585     print "Upgrade to $DBversion done (bug 3242: add HOLDPLACED letter template, which is used when emailLibrarianWhenHoldIsPlaced is enabled)\n";
3586     SetVersion ($DBversion);
3587 }
3588
3589 $DBversion = '3.01.00.125';
3590 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3591     $dbh->do("
3592         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' );
3593     ");
3594     $dbh->do("
3595         INSERT INTO message_transport_types (message_transport_type) values ('print');
3596     ");
3597     print "Upgrade to $DBversion done (bug 3482: Printable hold and overdue notices)\n";
3598     SetVersion ($DBversion);
3599 }
3600
3601 $DBversion = "3.01.00.126";
3602 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3603         $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')");
3604         $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')");
3605
3606     print "Upgrade to $DBversion done (Adding ILS-DI updates and ILS-DI:AuthorizedIPs)\n";
3607     SetVersion ($DBversion);
3608 }
3609
3610 $DBversion = '3.01.00.127';
3611 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3612     $dbh->do("ALTER TABLE messages CHANGE branchcode branchcode varchar(10);");
3613     print "Upgrade to $DBversion done (bug 4190: messages in patron account did not work with branchcodes > 4)\n";
3614     SetVersion ($DBversion);
3615 }
3616
3617 $DBversion = '3.01.00.128';
3618 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3619     $dbh->do('CREATE INDEX budget_id ON aqorders (budget_id );');
3620     print "Upgrade to $DBversion done (bug 4331: index orders by budget_id)\n";
3621     SetVersion ($DBversion);
3622 }
3623
3624 $DBversion = "3.01.00.129";
3625 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3626         $dbh->do("UPDATE `permissions` SET `code` = 'items_batchdel' WHERE `permissions`.`module_bit` =13 AND `permissions`.`code` = 'batchdel' LIMIT 1 ;");
3627         $dbh->do("UPDATE `permissions` SET `code` = 'items_batchmod' WHERE `permissions`.`module_bit` =13 AND `permissions`.`code` = 'batchmod' LIMIT 1 ;");
3628         print "Upgrade to $DBversion done (Change permissions names for item batch modification / deletion)\n";
3629
3630     SetVersion ($DBversion);
3631 }
3632
3633 $DBversion = "3.01.00.130";
3634 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3635     sanitize_zero_date('reserves', 'expirationdate');
3636     print "Upgrade to $DBversion done (change reserves.expirationdate values of 0000-00-00 to NULL (bug 1532)\n";
3637     SetVersion ($DBversion);
3638 }
3639
3640 $DBversion = "3.01.00.131";
3641 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3642         $dbh->do(q{
3643 INSERT IGNORE INTO message_transport_types (message_transport_type) VALUES ('print'),('feed');
3644     });
3645     print "Upgrade to $DBversion done (adding print and feed message transport types)\n";
3646     SetVersion ($DBversion);
3647 }
3648
3649 $DBversion = "3.01.00.132";
3650 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3651         $dbh->do(q{
3652     ALTER TABLE language_descriptions ADD INDEX subtag_type_lang (subtag, type, lang);
3653     });
3654     print "Upgrade to $DBversion done (Adding index to language_descriptions table)\n";
3655     SetVersion ($DBversion);
3656 }
3657
3658 $DBversion = '3.01.00.133';
3659 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3660     $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')");
3661     print "Upgrade to $DBversion done (bug 4405: added OverduesBlockCirc syspref to control whether circulation is blocked if a borrower has overdues)\n";
3662     SetVersion ($DBversion);
3663 }
3664
3665 $DBversion = '3.01.00.134';
3666 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3667     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('DisplayMultiPlaceHold','1','Display the ability to place multiple holds or not','','YesNo')");
3668     print "Upgrade to $DBversion done (adding syspref DisplayMultiPlaceHold to control whether multiple holds can be placed from the search results page)\n";
3669     SetVersion ($DBversion);
3670 }
3671
3672 $DBversion = '3.01.00.135';
3673 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3674     $dbh->do("
3675         INSERT INTO `letter` (module, code, name, title, content) VALUES
3676 ('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')
3677 ");
3678     print "Upgrade to $DBversion done (bug 4377: added HOLD_PRINT message template)\n";
3679     SetVersion ($DBversion);
3680 }
3681
3682 $DBversion = '3.01.00.136';
3683 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3684     $dbh->do(qq{
3685 INSERT INTO permissions (module_bit, code, description) VALUES
3686    ( 9, 'edit_items', 'Edit Items');});
3687     print "Upgrade to $DBversion done (Adding a new permission to edit items)\n";
3688     SetVersion ($DBversion);
3689 }
3690
3691 $DBversion = "3.01.00.137";
3692 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3693         $dbh->do("
3694           INSERT INTO permissions (module_bit, code, description) VALUES
3695           (15, 'check_expiration', 'Check the expiration of a serial'),
3696           (15, 'claim_serials', 'Claim missing serials'),
3697           (15, 'create_subscription', 'Create a new subscription'),
3698           (15, 'delete_subscription', 'Delete an existing subscription'),
3699           (15, 'edit_subscription', 'Edit an existing subscription'),
3700           (15, 'receive_serials', 'Serials receiving'),
3701           (15, 'renew_subscription', 'Renew a subscription'),
3702           (15, 'routing', 'Routing');
3703                  ");
3704     print "Upgrade to $DBversion done (adding granular permissions for serials)\n";
3705     SetVersion ($DBversion);
3706 }
3707
3708 $DBversion = "3.01.00.138";
3709 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3710     $dbh->do("DELETE FROM systempreferences WHERE variable = 'GranularPermissions'");
3711     print "Upgrade to $DBversion done (bug 4896: removing GranularPermissions syspref; use of granular permissions is now the default)\n";
3712     SetVersion ($DBversion);
3713 }
3714
3715 $DBversion = '3.01.00.139';
3716 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3717     $dbh->do("ALTER TABLE message_attributes CHANGE message_name message_name varchar(40);");
3718     print "Upgrade to $DBversion done (bug 3682: change message_name from varchar(20) to varchar(40))\n";
3719     SetVersion ($DBversion);
3720 }
3721
3722 $DBversion = '3.01.00.140';
3723 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3724     $dbh->do("UPDATE systempreferences SET value = '0' WHERE variable = 'TagsModeration' AND value is NULL");
3725     print "Upgrade to $DBversion done (bug 4312 TagsModeration changed from NULL to 0)\n";
3726     SetVersion ($DBversion);
3727 }
3728
3729 $DBversion = '3.01.00.141';
3730 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3731     $dbh->do(qq{DELETE FROM message_attributes WHERE message_attribute_id=3;});
3732     $dbh->do(qq{DELETE FROM letter WHERE code='EVENT' AND title='Upcoming Library Event';});
3733     print "Upgrade to $DBversion done Remove upcoming events messaging option (bug 2434)\n";
3734     SetVersion ($DBversion);
3735 }
3736
3737 $DBversion = '3.01.00.142';
3738 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3739     $dbh->do(qq{DELETE FROM message_transports WHERE message_attribute_id=3;});
3740     print "Upgrade to $DBversion done (Remove upcoming events messaging option part 2 (bug 2434))\n";
3741     SetVersion ($DBversion);
3742 }
3743
3744 $DBversion = '3.01.00.143';
3745 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3746     $dbh->do(qq{CREATE INDEX auth_value_idx ON authorised_values (authorised_value)});
3747     $dbh->do(qq{CREATE INDEX auth_val_cat_idx ON borrower_attribute_types (authorised_value_category)});
3748     print "Upgrade to $DBversion done (Create index on authorised_values and borrower_attribute_types (bug 4139))\n";
3749     SetVersion ($DBversion);
3750 }
3751
3752 $DBversion = '3.01.00.144';
3753 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3754     $dbh->do(qq{UPDATE systempreferences SET value='normal' where value='default' and variable='IntranetBiblioDefaultView'});
3755     print "Upgrade to $DBversion done (Update the 'default' to 'normal' for the IntranetBiblioDefaultView syspref (bug 5007))\n";
3756     SetVersion ($DBversion);
3757 }
3758
3759 $DBversion = "3.01.00.145";
3760 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3761     $dbh->do("ALTER TABLE borrowers ADD KEY `guarantorid` (guarantorid);");
3762     print "Upgrade to $DBversion done (Add index on guarantorid)\n";
3763     SetVersion ($DBversion);
3764 }
3765
3766 $DBversion = '3.01.00.999';
3767 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3768     print "Upgrade to $DBversion done (3.2.0 release candidate)\n";
3769     SetVersion ($DBversion);
3770 }
3771
3772 $DBversion = "3.02.00.000";
3773 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3774     my $value = $dbh->selectrow_array("SELECT value FROM systempreferences WHERE variable = 'HomeOrHoldingBranch'");
3775     $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');");
3776     print "Upgrade to $DBversion done (Add HomeOrHoldingBranchReturn system preference)\n";
3777     SetVersion ($DBversion);
3778 }
3779
3780 $DBversion = "3.02.00.001";
3781 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3782     $dbh->do(q{DELETE FROM systempreferences WHERE variable IN (
3783                 'holdCancelLength',
3784                 'PINESISBN',
3785                 'sortbynonfiling',
3786                 'TemplateEncoding',
3787                 'OPACSubscriptionDisplay',
3788                 'OPACDisplayExtendedSubInfo',
3789                 'OAI-PMH:Set',
3790                 'OAI-PMH:Subset',
3791                 'libraryAddress',
3792                 'kohaspsuggest',
3793                 'OrderPdfTemplate',
3794                 'marc',
3795                 'acquisitions',
3796                 'MIME')
3797                }
3798     );
3799     print "Upgrade to $DBversion done (bug 3756: remove disused system preferences)\n";
3800     SetVersion ($DBversion);
3801 }
3802
3803 $DBversion = "3.02.00.002";
3804 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3805     $dbh->do(q{DELETE FROM systempreferences WHERE variable = 'OpacPrivacy'});
3806     print "Upgrade to $DBversion done (bug 3881: remove unused OpacPrivacy system preference)\n";
3807     SetVersion ($DBversion);
3808 }
3809
3810 $DBversion = "3.02.00.003";
3811 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3812     $dbh->do(q{UPDATE systempreferences SET variable = 'ILS-DI:AuthorizedIPs' WHERE variable = 'ILS-DI:Authorized_IPs'});
3813     print "Upgrade to $DBversion done (correct ILS-DI:AuthorizedIPs)\n";
3814     SetVersion ($DBversion);
3815 }
3816
3817 $DBversion = "3.02.00.004";
3818 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3819     print "Upgrade to $DBversion done (3.2.0 general release)\n";
3820     SetVersion ($DBversion);
3821 }
3822 # This is the point where 3.2.x and master diverged, we can use $original_version to make sure we don't
3823
3824 # apply updates that have already been done
3825
3826 $DBversion = "3.03.00.001";
3827 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.005")) {
3828     $dbh->do("DELETE FROM subscriptionroutinglist WHERE borrowernumber IS NULL;");
3829     $dbh->do("ALTER TABLE subscriptionroutinglist MODIFY COLUMN `borrowernumber` int(11) NOT NULL;");
3830     $dbh->do("DELETE FROM subscriptionroutinglist WHERE subscriptionid IS NULL;");
3831     $dbh->do("ALTER TABLE subscriptionroutinglist MODIFY COLUMN `subscriptionid` int(11) NOT NULL;");
3832     $dbh->do("CREATE TEMPORARY TABLE del_subscriptionroutinglist
3833               SELECT s1.routingid FROM subscriptionroutinglist s1
3834               WHERE EXISTS (SELECT * FROM subscriptionroutinglist s2
3835                             WHERE s2.borrowernumber = s1.borrowernumber
3836                             AND   s2.subscriptionid = s1.subscriptionid
3837                             AND   s2.routingid < s1.routingid);");
3838     $dbh->do("DELETE FROM subscriptionroutinglist
3839               WHERE routingid IN (SELECT routingid FROM del_subscriptionroutinglist);");
3840     $dbh->do("ALTER TABLE subscriptionroutinglist ADD UNIQUE (subscriptionid, borrowernumber);");
3841     $dbh->do("ALTER TABLE subscriptionroutinglist
3842                 ADD CONSTRAINT `subscriptionroutinglist_ibfk_1` FOREIGN KEY (`borrowernumber`)
3843                 REFERENCES `borrowers` (`borrowernumber`)
3844                 ON DELETE CASCADE ON UPDATE CASCADE");
3845     $dbh->do("ALTER TABLE subscriptionroutinglist
3846                 ADD CONSTRAINT `subscriptionroutinglist_ibfk_2` FOREIGN KEY (`subscriptionid`)
3847                 REFERENCES `subscription` (`subscriptionid`)
3848                 ON DELETE CASCADE ON UPDATE CASCADE");
3849     print "Upgrade to $DBversion done (Make subscriptionroutinglist more strict)\n";
3850     SetVersion ($DBversion);
3851 }
3852
3853 $DBversion = '3.03.00.002';
3854 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.006")) {
3855     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='arm' WHERE rfc4646_subtag='hy';");
3856     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='eng' WHERE rfc4646_subtag='en';");
3857     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'fi','fin');");
3858     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='fre' WHERE rfc4646_subtag='fr';");
3859     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'lo','lao');");
3860     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='ita' WHERE rfc4646_subtag='it';");
3861     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'sr','srp');");
3862     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'tet','tet');");
3863     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'ur','urd');");
3864
3865     print "Upgrade to $DBversion done (Correct language mappings)\n";
3866     SetVersion ($DBversion);
3867 }
3868
3869 $DBversion = '3.03.00.003';
3870 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.007")) {
3871     $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');");
3872     print "Upgrade to $DBversion done (Add UseTablesortForCirc syspref)\n";
3873     SetVersion ($DBversion);
3874 }
3875
3876 $DBversion = '3.03.00.004';
3877 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.001")) {
3878     my $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'ACCEPTED');
3879     $dbh->do(q/
3880 INSERT INTO `letter`
3881 (module, code, name, title, content)
3882 VALUES
3883 ('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>>')
3884 /) unless $count > 0;
3885     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'AVAILABLE');
3886     $dbh->do(q/
3887 INSERT INTO `letter`
3888 (module, code, name, title, content)
3889 VALUES
3890 ('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>>')
3891 /) unless $count > 0;
3892     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'ORDERED');
3893     $dbh->do(q/
3894 INSERT INTO `letter`
3895 (module, code, name, title, content)
3896 VALUES
3897 ('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>>')
3898 /) unless $count > 0;
3899     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'REJECTED');
3900     $dbh->do(q/
3901 INSERT INTO `letter`
3902 (module, code, name, title, content)
3903 VALUES
3904 ('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>>')
3905 /) unless $count > 0;
3906     print "Upgrade to $DBversion done (bug 5127: add default templates for suggestion status change notifications)\n";
3907     SetVersion ($DBversion);
3908 };
3909
3910 $DBversion = '3.03.00.005';
3911 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3912     $dbh->do("update `systempreferences` set options='whitespace|T-prefix|cuecat|libsuite8' where variable='itemBarcodeInputFilter'");
3913     print "Upgrade to $DBversion done (Add itemBarcodeInputFilter choice libsuite8)\n";
3914 }
3915
3916 $DBversion = '3.03.00.006';
3917 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.002")) {
3918     $dbh->do("ALTER TABLE deletedborrowers ADD `privacy` int(11) AFTER smsalertnumber;");
3919     $dbh->do("ALTER TABLE deletedborrowers CHANGE `cardnumber` `cardnumber` varchar(16);");
3920     print "Upgrade to $DBversion done (Fix differences between borrowers and deletedborrowers)\n";
3921     SetVersion ($DBversion);
3922 }
3923
3924 $DBversion = '3.03.00.007';
3925 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3926     $dbh->do("ALTER table suggestions ADD quantity SMALLINT(6) default NULL,
3927                 ADD currency VARCHAR(3) default NULL,
3928                 ADD price DECIMAL(28,6) default NULL,
3929                 ADD total DECIMAL(28,6) default NULL;
3930                 ");
3931     print "Upgrade to $DBversion done (Added acq related columns to suggestions)\n";
3932     SetVersion ($DBversion);
3933 }
3934
3935 $DBversion = '3.03.00.008';
3936 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3937     $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')");
3938     print "Upgrade to $DBversion done (adding syspref OPACNoResultsFound to control what displays when no results are found for a search in the OPAC.)\n";
3939     SetVersion ($DBversion);
3940 }
3941
3942 $DBversion = '3.03.00.009';
3943 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.003")) {
3944     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('IntranetUserCSS','','Add CSS to be included in the Intranet',NULL,'free')");
3945     print "Upgrade to $DBversion done (Add IntranetUserCSS syspref)\n";
3946     SetVersion ($DBversion);
3947 }
3948
3949 $DBversion = "3.03.00.010";
3950 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.02.001")) {
3951     $dbh->do("UPDATE `marc_subfield_structure` SET liblibrarian = 'Distance from earth' WHERE liblibrarian = 'Distrance from earth' AND tagfield = '034' AND tagsubfield = 'r';");
3952     $dbh->do("UPDATE `marc_subfield_structure` SET libopac = 'Distance from earth' WHERE libopac = 'Distrance from earth' AND tagfield = '034' AND tagsubfield = 'r';");
3953     print "Upgrade to $DBversion done (Fix misspelled 034r subfield in MARC21 Frameworks)\n";
3954     SetVersion ($DBversion);
3955 }
3956
3957 $DBversion = "3.03.00.011";
3958 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3959     $dbh->do("UPDATE aqbooksellers SET gstrate=NULL WHERE gstrate=0.0");
3960     print "Upgrade to $DBversion done (Bug 5186: allow GST rate to be set to 0)\n";
3961     SetVersion ($DBversion);
3962 }
3963
3964 $DBversion = "3.03.00.012";
3965 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3966    $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')");
3967    print "Upgrade to $DBversion done (Bug 2142: maxItemsInSearchResults syspref resurrected)\n";
3968    SetVersion ($DBversion);
3969 }
3970
3971 $DBversion = "3.03.00.013";
3972 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3973     $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')");
3974     print "Upgrade to $DBversion done (added 'OpacPublic' syspref)\n";
3975    SetVersion ($DBversion);
3976 }
3977
3978 $DBversion = "3.03.00.014";
3979 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3980     $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')");
3981     $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')");
3982     $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')");
3983     print "Upgrade to $DBversion done (Add flexible shelf browser constraints)\n";
3984     SetVersion ($DBversion);
3985 }
3986
3987 $DBversion = "3.03.00.015";
3988 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3989     if ( C4::Context->preference("marcflavour") eq "MARC21" ) {
3990         my $sth = $dbh->prepare(
3991 "INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`,
3992                              `tab`, `authorised_value`, `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`)
3993                              VALUES ( ?, '9', '9 (RLIN)', '9 (RLIN)', 0, 0, '', 6, '', '', '', 0, -5, '', '', '', NULL)"
3994         );
3995         $sth->execute('648');
3996         $sth->execute('654');
3997         $sth->execute('655');
3998         $sth->execute('656');
3999         $sth->execute('657');
4000         $sth->execute('658');
4001         $sth->execute('662');
4002         $sth->finish;
4003         print
4004 "Upgrade to $DBversion done (Bug 5619: Add subfield 9 to marc21 648,654,655,656,657,658,662)\n";
4005     }
4006     SetVersion($DBversion);
4007 }
4008
4009 $DBversion = '3.03.00.016';
4010 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4011     # reimplement OpacPrivacy system preference
4012     $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')");
4013     $dbh->do("ALTER TABLE `borrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
4014     $dbh->do("ALTER TABLE `deletedborrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
4015     print "Upgrade to $DBversion done (OpacPrivacy reimplementation)\n";
4016     SetVersion($DBversion);
4017 };
4018
4019 $DBversion = '3.03.00.017';
4020 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.001")) {
4021     $dbh->do("ALTER TABLE  `currency` CHANGE `rate` `rate` FLOAT( 15, 5 ) NULL DEFAULT NULL;");
4022     print "Upgrade to $DBversion done (Enable currency rates >= 100)\n";
4023     SetVersion ($DBversion);
4024 }
4025
4026 $DBversion = '3.03.00.018';
4027 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.002")) {
4028     $dbh->do( q|update language_descriptions set description = 'Nederlands' where lang = 'nl' and subtag = 'nl'|);
4029     $dbh->do( q|update language_descriptions set description = 'Dansk' where lang = 'da' and subtag = 'da'|);
4030     print "Upgrade to $DBversion done (Correct language descriptions)\n";
4031     SetVersion ($DBversion);
4032 }
4033
4034 $DBversion = '3.03.00.019';
4035 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.003")) {
4036     # Fix bokmål
4037     $dbh->do("UPDATE language_subtag_registry SET description = 'Norwegian bokm&#229;l' WHERE subtag = 'nb';");
4038     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'nb','nob');");
4039     $dbh->do("UPDATE language_descriptions SET description = 'Norsk bokm&#229;l' WHERE subtag = 'nb' AND lang = 'nb';");
4040     $dbh->do("UPDATE language_descriptions SET description = 'Norwegian bokm&#229;l' WHERE subtag = 'nb' AND lang = 'en';");
4041     $dbh->do("UPDATE language_descriptions SET description = 'Norvégien bokm&#229;l' WHERE subtag = 'nb' AND lang = 'fr';");
4042     # Add nynorsk
4043     $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'nn', 'language', 'Norwegian nynorsk','2011-02-14' )");
4044     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'nn','nno')");
4045     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'nb', 'Norsk nynorsk')");
4046     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'nn', 'Norsk nynorsk')");
4047     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'en', 'Norwegian nynorsk')");
4048     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'fr', 'Norvégien nynorsk')");
4049     print "Upgrade to $DBversion done (Correct language descriptions for Norwegian)\n";
4050     SetVersion ($DBversion);
4051 }
4052
4053 $DBversion = '3.03.00.020';
4054 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4055     $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')");
4056     $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')");
4057     print "Upgrade to $DBversion done (Bug 5811: Add sysprefs controlling overriding fines)\n";
4058     SetVersion($DBversion);
4059 };
4060
4061 $DBversion = '3.03.00.021';
4062 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.001")) {
4063     $dbh->do("ALTER TABLE items MODIFY enumchron TEXT");
4064     $dbh->do("ALTER TABLE deleteditems MODIFY enumchron TEXT");
4065     print "Upgrade to $DBversion done (bug 5642: longer serial enumeration)\n";
4066     SetVersion ($DBversion);
4067 }
4068
4069 $DBversion = '3.03.00.022';
4070 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4071     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('AuthoritiesLog','0','If ON, log edit/create/delete actions on authorities.','','YesNo');");
4072     print "Upgrade to $DBversion done (Add AuthoritiesLog syspref)\n";
4073     SetVersion ($DBversion);
4074 }
4075
4076 # due to a mismatch in kohastructure.sql some koha will have missing columns in aqbasketgroup
4077 # this attempts to fix that
4078 $DBversion = '3.03.00.023';
4079 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.002")) {
4080     my $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'billingplace'");
4081     $sth->execute;
4082     $dbh->do("ALTER TABLE aqbasketgroups ADD billingplace VARCHAR(10)") if ! $sth->fetchrow_hashref;
4083     $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'deliveryplace'");
4084     $sth->execute;
4085     $dbh->do("ALTER TABLE aqbasketgroups ADD deliveryplace VARCHAR(10)") if ! $sth->fetchrow_hashref;
4086     $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'deliverycomment'");
4087     $sth->execute;
4088     $dbh->do("ALTER TABLE aqbasketgroups ADD deliverycomment VARCHAR(255)") if ! $sth->fetchrow_hashref;
4089     print "Upgrade to $DBversion done (Reconcile aqbasketgroups)\n";
4090     SetVersion ($DBversion);
4091 }
4092
4093 $DBversion = '3.03.00.024';
4094 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4095     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('TraceCompleteSubfields','0','Force subject tracings to only match complete subfields.','0','YesNo')");
4096     $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')");
4097     print "Upgrade to $DBversion done (Add syspref to force whole-subfield matching on subject tracings)\n";
4098     SetVersion($DBversion);
4099 };
4100
4101 $DBversion = "3.03.00.025";
4102 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4103     $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')");
4104     print "Upgrade to $DBversion done (Add syspref to control if user can choose pickup branch for holds)\n";
4105     SetVersion ($DBversion);
4106 }
4107
4108 $DBversion = '3.03.00.026';
4109 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.003")) {
4110     $dbh->do("UPDATE `message_attributes` SET message_name='Item Due' WHERE message_attribute_id=1 AND message_name LIKE 'Item DUE'");
4111         print "Upgrade to $DBversion done ( fix capitalization in message type )\n";
4112     SetVersion ($DBversion);
4113 }
4114
4115 $DBversion = '3.03.00.027';
4116 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4117     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('displayFacetCount', '0', NULL, NULL, 'YesNo')");
4118     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('maxRecordsForFacets', '20', NULL, NULL, 'Integer')");
4119     print "Upgrade to $DBversion done (Preferences for facet count)\n";
4120     SetVersion ($DBversion);
4121 }
4122
4123 $DBversion = "3.03.00.028";
4124 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4125     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('FacetLabelTruncationLength', 20, 'Truncate facets length to','','free')");
4126     print "Upgrade to $DBversion done (Add FacetLabelTruncationLength syspref to control facets displayed length)\n";
4127     SetVersion ($DBversion);
4128 }
4129
4130 $DBversion = "3.03.00.029";
4131 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4132     $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')");
4133     print "Upgrade to $DBversion done (Add syspref to control if user can choose branch when making purchase suggestion)\n";
4134     SetVersion ($DBversion);
4135 }
4136
4137 $DBversion = "3.03.00.030";
4138 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4139     $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')");
4140     $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')");
4141     print "Upgrade to $DBversion done (Add sysprefs to control custom favicons)\n";
4142     SetVersion ($DBversion);
4143 }
4144
4145 $DBversion = "3.03.00.031";
4146 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4147     $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');");
4148     print "Upgrade to $DBversion done (Add syspref FineNotifyAtCheckin)\n";
4149     SetVersion ($DBversion);
4150 }
4151
4152 $DBversion = '3.03.00.032';
4153 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4154     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('TraceSubjectSubdivisions', 1, 'Create searches on all subdivisions for subject tracings.','1','YesNo')");
4155     print "Upgrade to $DBversion done ( include subdivisions when generating subject tracing searches )\n";
4156 }
4157
4158
4159 $DBversion = '3.03.00.033';
4160 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4161     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('StaffAuthorisedValueImages', '1', '', NULL, 'YesNo')");
4162     print "Upgrade to $DBversion done (System pref StaffAuthorisedValueImages)\n";
4163     SetVersion ($DBversion);
4164 }
4165
4166 $DBversion = '3.03.00.034';
4167 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4168     $dbh->do("ALTER TABLE `categories` ADD `hidelostitems` tinyint(1) NOT NULL default '0' AFTER `reservefee`");
4169     print "Upgrade to $DBversion done (Add hidelostitems preference to borrower categories)\n";
4170     SetVersion ($DBversion);
4171 }
4172
4173 $DBversion = '3.03.00.035';
4174 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4175     $dbh->do("ALTER TABLE `issuingrules` ADD hardduedate date default NULL AFTER issuelength");
4176     $dbh->do("ALTER TABLE `issuingrules` ADD hardduedatecompare tinyint NOT NULL default 0 AFTER hardduedate");
4177     my $duedate;
4178     if (C4::Context->preference("globalDueDate")) {
4179       $duedate = eval { output_pref( { dt => dt_from_string( C4::Context->preference("globalDueDate") ), dateonly => 1, dateformat => 'iso' } ); };
4180       $dbh->do("UPDATE `issuingrules` SET hardduedate = '$duedate', hardduedatecompare = 0");
4181     } elsif (C4::Context->preference("ceilingDueDate")) {
4182       $duedate = eval { output_pref( { dt => dt_from_string( C4::Context->preference("ceilingDueDate") ), dateonly => 1, dateformat => 'iso' } ); };
4183       $dbh->do("UPDATE `issuingrules` SET hardduedate = '$duedate', hardduedatecompare = -1");
4184     }
4185     $dbh->do("DELETE FROM `systempreferences` WHERE variable = 'globalDueDate' OR variable = 'ceilingDueDate'");
4186     print "Upgrade to $DBversion done (Move global and ceiling due dates to Circ Rules level)\n";
4187     SetVersion ($DBversion);
4188 }
4189
4190 $DBversion = '3.03.00.036';
4191 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4192     $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')");
4193     print "Upgrade to $DBversion done ( Make COinS optional in OPAC search results )\n";
4194     SetVersion ($DBversion);
4195 }
4196
4197 $DBversion = '3.03.00.037';
4198 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4199     $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')");
4200     $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')");
4201     print "Upgrade to $DBversion done (Add 'Display856uAsImage' and 'OPACDisplay856uAsImage' syspref)\n";
4202     SetVersion ($DBversion);
4203 }
4204
4205 $DBversion = '3.03.00.038';
4206 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4207     $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')");
4208     $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')");
4209     $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')");
4210     print "Upgrade to $DBversion done ( Add Self-checkout by Login system preferences )\n";
4211 }
4212
4213 $DBversion = "3.03.00.039";
4214 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4215     $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');");
4216     print "Upgrade to $DBversion done (Add syspref ShowReviewer)\n";
4217 }
4218
4219 $DBversion = "3.03.00.040";
4220 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4221     $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');");
4222     print "Upgrade to $DBversion done (Add syspref UseControlNumber)\n";
4223 }
4224
4225 $DBversion = "3.03.00.041";
4226 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4227     $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')");
4228     $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')");
4229     print "Upgrade to $DBversion done (Add sysprefs to control alternate holdings information display)\n";
4230     SetVersion ($DBversion);
4231 }
4232
4233 $DBversion = '3.03.00.042';
4234 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4235     stocknumber_checker();
4236     print "Upgrade to $DBversion done (5860 Index itemstocknumber)\n";
4237     SetVersion ($DBversion);
4238 }
4239
4240 sub stocknumber_checker { #code reused later on
4241   my @row;
4242   #drop the obsolete itemSStocknumber idx if it exists
4243   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemsstocknumberidx'");
4244   $dbh->do("ALTER TABLE `items` DROP INDEX `itemsstocknumberidx`;") if @row;
4245
4246   #check itemstocknumber idx; remove it if it is unique
4247   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemstocknumberidx' AND non_unique=0");
4248   $dbh->do("ALTER TABLE `items` DROP INDEX `itemstocknumberidx`;") if @row;
4249
4250   #add itemstocknumber index non-unique IF it still not exists
4251   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemstocknumberidx'");
4252   $dbh->do("ALTER TABLE items ADD INDEX itemstocknumberidx (stocknumber);") unless @row;
4253 }
4254
4255 $DBversion = "3.03.00.043";
4256 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4257
4258     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib,lib_opac) VALUES ('YES_NO','0','No','No')");
4259     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib,lib_opac) VALUES ('YES_NO','1','Yes','Yes')");
4260
4261         print "Upgrade to $DBversion done ( add generic boolean YES_NO authorised_values pair )\n";
4262         SetVersion ($DBversion);
4263 }
4264
4265 $DBversion = '3.03.00.044';
4266 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4267     $dbh->do("ALTER TABLE `aqbasketgroups` ADD `freedeliveryplace` TEXT NULL AFTER `deliveryplace`;");
4268     print "Upgrade to $DBversion done (adding freedeliveryplace to basketgroups)\n";
4269 }
4270
4271 $DBversion = '3.03.00.045';
4272 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4273     #Remove obsolete columns from aqbooksellers if needed
4274     my $a = $dbh->selectall_hashref('SHOW columns from aqbooksellers','Field');
4275     my $sqldrop="ALTER TABLE aqbooksellers DROP COLUMN ";
4276     foreach(qw/deliverydays followupdays followupscancel invoicedisc nocalc specialty/) {
4277       $dbh->do($sqldrop.$_) if exists $a->{$_};
4278     }
4279     #Remove obsolete column from aqbudgets if needed
4280     #The correct column is budget_notes
4281     $a = $dbh->selectall_hashref('SHOW columns from aqbudgets','Field');
4282     if(exists $a->{budget_description}) {
4283       $dbh->do("ALTER TABLE aqbudgets DROP COLUMN budget_description");
4284     }
4285     print "Upgrade to $DBversion done (Remove obsolete columns from aqbooksellers and aqbudgets if needed)\n";
4286     SetVersion ($DBversion);
4287 }
4288
4289 $DBversion = "3.03.00.046";
4290 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4291     $dbh->do("ALTER TABLE overduerules ALTER delay1 SET DEFAULT NULL, ALTER delay2 SET DEFAULT NULL, ALTER delay3 SET DEFAULT NULL");
4292     print "Upgrade to $DBversion done (Setting NULL default value for delayn columns in table overduerules)\n";
4293     SetVersion($DBversion);
4294 }
4295
4296 $DBversion = '3.03.00.047';
4297 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4298     $dbh->do("ALTER TABLE borrowers ADD `state` mediumtext AFTER city;");
4299     $dbh->do("ALTER TABLE borrowers ADD `B_state` mediumtext AFTER B_city;");
4300     $dbh->do("ALTER TABLE borrowers ADD `altcontactstate` mediumtext AFTER altcontactaddress3;");
4301     $dbh->do("ALTER TABLE deletedborrowers ADD `state` mediumtext AFTER city;");
4302     $dbh->do("ALTER TABLE deletedborrowers ADD `B_state` mediumtext AFTER B_city;");
4303     $dbh->do("ALTER TABLE deletedborrowers ADD `altcontactstate` mediumtext AFTER altcontactaddress3;");
4304     print "Upgrade to $DBversion done (Add state field to patron's addresses)\n";
4305 }
4306
4307 $DBversion = '3.03.00.048';
4308 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4309     $dbh->do("ALTER TABLE branches ADD `branchstate` mediumtext AFTER `branchcity`;");
4310     print "Upgrade to $DBversion done (Add state to branch address)\n";
4311     SetVersion ($DBversion);
4312 }
4313
4314 $DBversion = '3.03.00.049';
4315 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4316     $dbh->do("ALTER TABLE `accountlines` ADD `note` text NULL default NULL");
4317     $dbh->do("ALTER TABLE `accountlines` ADD `manager_id` int( 11 ) NULL ");
4318     print "Upgrade to $DBversion done (adding note and manager_id fields in accountlines table)\n";
4319     SetVersion($DBversion);
4320 }
4321
4322 $DBversion = "3.03.00.050";
4323 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4324     $dbh->do("
4325         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');
4326         ");
4327     print "Upgrade to $DBversion done (Adding OpacHiddenItems syspref)\n";
4328     SetVersion($DBversion);
4329 }
4330
4331 $DBversion = "3.03.00.051";
4332 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4333     print "Upgrade to $DBversion done (Remove spaces and dashes from message_attribute names)\n";
4334     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Due' WHERE message_name='Item Due'");
4335     $dbh->do("UPDATE message_attributes SET message_name = 'Advance_Notice' WHERE message_name='Advance Notice'");
4336     $dbh->do("UPDATE message_attributes SET message_name = 'Hold_Filled' WHERE message_name='Hold Filled'");
4337     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Check_in' WHERE message_name='Item Check-in'");
4338     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Checkout' WHERE message_name='Item Checkout'");
4339     SetVersion ($DBversion);
4340 }
4341
4342 $DBversion = "3.03.00.052";
4343 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4344     $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');");
4345     print "Upgrade to $DBversion done (Add syspref WaitingNotifyAtCheckin)\n";
4346     SetVersion ($DBversion);
4347 }
4348
4349 $DBversion = "3.04.00.000";
4350 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4351     print "Upgrade to $DBversion done Koha 3.4.0 release \n";
4352     SetVersion ($DBversion);
4353 }
4354
4355 $DBversion = "3.05.00.001";
4356 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4357     $dbh->do(qq{
4358     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');
4359     });
4360     print "Upgrade to $DBversion done (Adds New System preference numSearchRSSResults)\n";
4361     SetVersion($DBversion);
4362 }
4363
4364 $DBversion = '3.05.00.002';
4365 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4366     #follow up fix 5860: some installs already past 3.3.0.42
4367     stocknumber_checker();
4368     print "Upgrade to $DBversion done (Fix for stocknumber index)\n";
4369     SetVersion ($DBversion);
4370 }
4371
4372 $DBversion = "3.05.00.003";
4373 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4374     $dbh->do(qq{
4375     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');
4376     });
4377     print "Upgrade to $DBversion done (Adds New System preference OpacRenewalBranch)\n";
4378     SetVersion($DBversion);
4379 }
4380
4381 $DBversion = "3.05.00.004";
4382 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4383     $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');");
4384     print "Upgrade to $DBversion done (Add syspref ShowReviewerPhoto)\n";
4385     SetVersion($DBversion);
4386 }
4387
4388 $DBversion = "3.05.00.005";
4389 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4390     $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');");
4391     print "Upgrade to $DBversion done (Adds pref BasketConfirmations)\n";
4392     SetVersion($DBversion);
4393 }
4394
4395 $DBversion = "3.05.00.006";
4396 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4397     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('MARCAuthorityControlField008', '|| aca||aabn           | a|a     d', NULL, NULL, 'Textarea')");
4398     print "Upgrade to $DBversion done (Add syspref MARCAuthorityControlField008)\n";
4399     SetVersion ($DBversion);
4400 }
4401
4402 $DBversion = "3.05.00.007";
4403 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4404     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpenLibraryCovers',0,'If ON Openlibrary book covers will be show',NULL,'YesNo');");
4405     print "Upgrade to $DBversion done (Add syspref OpenLibraryCovers)\n";
4406     SetVersion($DBversion);
4407 }
4408
4409 $DBversion = "3.05.00.008";
4410 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4411     $dbh->do("ALTER TABLE `cities` ADD `city_state` VARCHAR( 100 ) NULL DEFAULT NULL AFTER  `city_name`;");
4412     $dbh->do("ALTER TABLE `cities` ADD `city_country` VARCHAR( 100 ) NULL DEFAULT NULL AFTER  `city_zipcode`;");
4413     print "Add state and country to cities table corresponding to new columns in borrowers\n";
4414     SetVersion($DBversion);
4415 }
4416
4417 $DBversion = "3.05.00.009";
4418 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4419     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4420               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE borrowernumber IS NULL");
4421     $dbh->do("DELETE FROM issues WHERE borrowernumber IS NULL");
4422
4423     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4424               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE itemnumber IS NULL");
4425     $dbh->do("DELETE FROM issues WHERE itemnumber IS NULL");
4426
4427     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4428               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)");
4429     $dbh->do("DELETE FROM issues WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowernumber = issues.borrowernumber)");
4430
4431     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4432               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)");
4433     $dbh->do("DELETE FROM issues WHERE NOT EXISTS (SELECT * FROM items WHERE itemnumber = issues.itemnumber)");
4434
4435     $dbh->do("ALTER TABLE issues DROP FOREIGN KEY `issues_ibfk_1`");
4436     $dbh->do("ALTER TABLE issues DROP FOREIGN KEY `issues_ibfk_2`");
4437     $dbh->do("ALTER TABLE issues ALTER COLUMN borrowernumber DROP DEFAULT");
4438     $dbh->do("ALTER TABLE issues ALTER COLUMN itemnumber DROP DEFAULT");
4439     $dbh->do("ALTER TABLE issues MODIFY COLUMN borrowernumber int(11) NOT NULL");
4440     $dbh->do("ALTER TABLE issues MODIFY COLUMN itemnumber int(11) NOT NULL");
4441     $dbh->do("ALTER TABLE issues DROP KEY `issuesitemidx`");
4442     $dbh->do("ALTER TABLE issues ADD PRIMARY KEY (`itemnumber`)");
4443     $dbh->do("ALTER TABLE issues ADD CONSTRAINT `issues_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE RESTRICT ON UPDATE CASCADE");
4444     $dbh->do("ALTER TABLE issues ADD CONSTRAINT `issues_ibfk_2` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE RESTRICT ON UPDATE CASCADE");
4445
4446     print "Upgrade to $DBversion done (issues referential integrity)\n";
4447     SetVersion ($DBversion);
4448 }
4449
4450 $DBversion = "3.05.00.010";
4451 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4452     $dbh->do("CREATE INDEX priorityfoundidx ON reserves (priority,found)");
4453     print "Create an index on reserves to speed up holds awaiting pickup report bug 5866\n";
4454     SetVersion($DBversion);
4455 }
4456
4457
4458 $DBversion = "3.05.00.011";
4459 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4460     $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')");
4461     print "Upgrade to $DBversion done (add OPACResultsSidebar syspref (enh 6165))\n";
4462     SetVersion($DBversion);
4463 }
4464
4465 $DBversion = "3.05.00.012";
4466 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4467     $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')");
4468     print "Upgrade to $DBversion done (add RecordLocalUseOnReturn syspref (enh 6403))\n";
4469     SetVersion($DBversion);
4470 }
4471
4472 $DBversion = "3.05.00.013";
4473 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4474     $dbh->do(qq|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OpacKohaUrl','0',"Show 'Powered by Koha' text on OPAC footer.",NULL,NULL)|);
4475     print "Upgrade to $DBversion done (Add syspref 'OpacKohaUrl')\n";
4476     SetVersion($DBversion);
4477 }
4478
4479 $DBversion = "3.05.00.014";
4480 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4481     $dbh->do("ALTER TABLE `borrowers` MODIFY `userid` VARCHAR(75)");
4482     print "Modified userid column length into 75 in borrowers\n";
4483     SetVersion($DBversion);
4484 }
4485
4486 $DBversion = "3.05.00.015";
4487 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4488     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectEnabled',0,'Enable Novelist Select content.  Requires Novelist Profile and Password',NULL,'YesNo')");
4489     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectProfile',NULL,'Novelist Select user Password',NULL,'free')");
4490     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectPassword',NULL,'Enable Novelist user Profile',NULL,'free')");
4491     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectView','tab','Where to display Novelist Select content','tab|above|below|right','Choice')");
4492     print "Upgrade to $DBversion done (Add support for EBSCO's NoveList Select (enh 6902))\n";
4493     SetVersion($DBversion);
4494 }
4495
4496 $DBversion = '3.05.00.016';
4497 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4498     $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');");
4499     print "Upgrade to $DBversion done (Add EasyAnalyticalRecords syspref)\n";
4500     SetVersion ($DBversion);
4501 }
4502
4503 $DBversion = '3.05.00.017';
4504 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4505     if (C4::Context->preference("marcflavour") eq 'MARC21' ||
4506         C4::Context->preference("marcflavour") eq 'NORMARC'){
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 ('773', '0', 'Host Biblionumber', 'Host Biblionumber', 0, 0, NULL, 7, NULL, NULL, '', NULL, -6, '', '', '', NULL)");
4508         $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)");
4509         print "Upgrade to $DBversion done (Add 773 subfield 9 and 0 to default framework)\n";
4510         SetVersion ($DBversion);
4511     } elsif (C4::Context->preference("marcflavour") eq 'UNIMARC'){
4512         $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)");
4513         print "Upgrade to $DBversion done (Add 461 subfield 9 to default framework)\n";
4514         SetVersion ($DBversion);
4515     }
4516 }
4517
4518 $DBversion = "3.05.00.018";
4519 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4520     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacNavBottom','','Links after OpacNav links','70|10','Textarea')");
4521     print "Upgrade to $DBversion done (add OpacNavBottom syspref (enh 6825): if appropriate, you can split OpacNav into OpacNav and OpacNavBottom)\n";
4522     SetVersion($DBversion);
4523 }
4524
4525 $DBversion = "3.05.00.019";
4526 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4527     $dbh->do("UPDATE itemtypes SET imageurl = 'vokal/Book.png' WHERE imageurl = 'vokal/BOOK.png'");
4528     $dbh->do("UPDATE itemtypes SET imageurl = 'vokal/Book-32px.png' WHERE imageurl = 'vokal/BOOK-32px.png'");
4529     $dbh->do("UPDATE authorised_values SET imageurl = 'vokal/Book.png' WHERE imageurl = 'vokal/BOOK.png'");
4530     $dbh->do("UPDATE authorised_values SET imageurl = 'vokal/Book-32px.png' WHERE imageurl = 'vokal/BOOK-32px.png'");
4531     print "Upgrade to $DBversion done (remove duplicate VOKAL Book icons, bug 6862)\n";
4532     SetVersion($DBversion);
4533 }
4534
4535 $DBversion = "3.05.00.020";
4536 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4537     $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')");
4538     print "Upgrade to $DBversion done (Add syspref AcqViewBaskets)\n";
4539     SetVersion($DBversion);
4540 }
4541
4542 $DBversion = "3.05.00.021";
4543 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4544     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN display_checkout TINYINT(1) NOT NULL DEFAULT '0';");
4545     print "Upgrade to $DBversion done (Added a display_checkout field in borrower_attribute_types table)\n";
4546     SetVersion($DBversion);
4547 }
4548
4549 $DBversion = "3.05.00.022";
4550 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4551     $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");
4552     print "Upgrade to $DBversion done (6094: Fixing ModAuthority problems, add a need_merge_authorities table)\n";
4553     SetVersion($DBversion);
4554 }
4555
4556 $DBversion = "3.05.00.023";
4557 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4558     $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');");
4559     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";
4560     SetVersion($DBversion);
4561 }
4562
4563 $DBversion = "3.06.00.000";
4564 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4565     print "Upgrade to $DBversion done Koha 3.6.0 release \n";
4566     SetVersion ($DBversion);
4567 }
4568
4569 $DBversion = "3.07.00.001";
4570 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4571     my $borrowers = $dbh->selectcol_arrayref( "SELECT borrowernumber from borrowers where debarred =1;", { Columns => [1] } );
4572     $dbh->do("ALTER TABLE borrowers MODIFY debarred DATE DEFAULT NULL;");
4573     $dbh->do( "UPDATE borrowers set debarred='9999-12-31' where borrowernumber IN (" . join( ",", @$borrowers ) . ");" ) if ($borrowers and scalar(@$borrowers)>0);
4574     $dbh->do("ALTER TABLE borrowers ADD COLUMN debarredcomment VARCHAR(255) DEFAULT NULL AFTER debarred;");
4575     $dbh->do("ALTER TABLE deletedborrowers MODIFY debarred DATE DEFAULT NULL;");
4576     $dbh->do("ALTER TABLE deletedborrowers ADD COLUMN debarredcomment VARCHAR(255) DEFAULT NULL AFTER debarred;");
4577     print "Upgrade done (Change borrowers.debarred into Date )\n";
4578     SetVersion($DBversion);
4579 }
4580
4581 $DBversion = "3.07.00.002";
4582 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4583     sanitize_zero_date('borrowers', 'debarred');
4584     print "Setting NULL to debarred where 0000-00-00 is stored (bug 7272)\n";
4585     SetVersion($DBversion);
4586 }
4587
4588 $DBversion = "3.07.00.003";
4589 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4590     $dbh->do(" UPDATE `message_attributes` SET message_name='Item_Due' WHERE message_name='Item_DUE'");
4591     print "Updating message_name in message_attributes\n";
4592     SetVersion($DBversion);
4593 }
4594
4595 $DBversion = "3.07.00.004";
4596 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4597     $dbh->do("ALTER TABLE  `suggestions` ADD  `patronreason` TEXT NULL AFTER  `reason`");
4598     print "Upgrade to $DBversion done (Add column to suggestions table to store patrons' reasons for submitting a suggestion. )\n";
4599     SetVersion($DBversion);
4600 }
4601
4602 $DBversion = "3.07.00.005";
4603 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4604     $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')");
4605     print "Upgrade to $DBversion done (BorrowerUnwantedField syspref)\n";
4606     SetVersion ($DBversion);
4607 }
4608
4609 $DBversion = "3.07.00.006";
4610 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4611     $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');");
4612     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";
4613     SetVersion($DBversion);
4614 }
4615
4616 $DBversion = "3.07.00.007";
4617 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4618     $dbh->do("ALTER TABLE items MODIFY materials text;");
4619     print "Upgrade to $DBversion done alter items.material from varchar(10) to text \n";
4620     SetVersion($DBversion);
4621 }
4622
4623 $DBversion = '3.07.00.008';
4624 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4625     if (C4::Context->preference("marcflavour") eq 'MARC21') {
4626         if (C4::Context->preference("opaclanguages") eq "de") {
4627             $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, '');");
4628         } else {
4629             $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, '');");
4630         }
4631     }
4632     print "Upgrade to $DBversion done (add MARC21 field 545 to framework)\n";
4633     SetVersion ($DBversion);
4634 }
4635
4636 $DBversion = "3.07.00.009";
4637 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4638     $dbh->do("ALTER TABLE `aqorders` ADD COLUMN `claims_count` INT(11)  DEFAULT 0, ADD COLUMN `claimed_date` DATE  DEFAULT NULL AFTER `claims_count`");
4639     print "Upgrade to $DBversion done (Add claims_count and claimed_date fields in aqorders table)\n";
4640     SetVersion($DBversion);
4641 }
4642
4643 $DBversion = "3.07.00.010";
4644 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4645     $dbh->do(
4646         q|CREATE TABLE `biblioimages` (
4647           `imagenumber` int(11) NOT NULL AUTO_INCREMENT,
4648           `biblionumber` int(11) NOT NULL,
4649           `mimetype` varchar(15) NOT NULL,
4650           `imagefile` mediumblob NOT NULL,
4651           `thumbnail` mediumblob NOT NULL,
4652           PRIMARY KEY (`imagenumber`),
4653           CONSTRAINT `bibliocoverimage_fk1` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
4654           ) ENGINE=InnoDB DEFAULT CHARSET=utf8|
4655     );
4656     $dbh->do(
4657         q|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OPACLocalCoverImages','0','Display local cover images on OPAC search and details pages.','1','YesNo')|
4658         );
4659     $dbh->do(
4660         q|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('LocalCoverImages','0','Display local cover images on intranet search and details pages.','1','YesNo')|
4661         );
4662     $dbh->do(
4663         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')|
4664     );
4665     $dbh->do(
4666         q|INSERT INTO permissions (module_bit, code, description) VALUES (13, 'upload_local_cover_images', 'Upload local cover images')|
4667     );
4668     print "Upgrade to $DBversion done (Added support for local cover images)\n";
4669     SetVersion($DBversion);
4670 }
4671
4672 $DBversion = "3.07.00.011";
4673 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4674     $dbh->do(<<ENDOFRENEWAL);
4675     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');
4676 ENDOFRENEWAL
4677     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";
4678     SetVersion($DBversion);
4679 }
4680
4681 $DBversion = "3.07.00.012";
4682 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4683     $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')");
4684     print "Upgrade to $DBversion add 'AllowItemsOnHoldCheckout' syspref \n";
4685     SetVersion ($DBversion);
4686 }
4687
4688 $DBversion = "3.07.00.013";
4689 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4690     $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');");
4691     print "Upgrade to $DBversion done (Bug 7345: Add system preference OpacExportOptions.)\n";
4692     SetVersion ($DBversion);
4693 }
4694
4695 $DBversion = "3.07.00.014";
4696 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4697     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";
4698     SetVersion($DBversion);
4699 }
4700
4701 $DBversion = "3.07.00.015";
4702 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4703     my $sth = $dbh->prepare(q|
4704         SELECT COUNT(*) FROM marc_subfield_structure where kohafield="biblioitems.editionstatement"
4705         |);
4706     $sth->execute;
4707     my $already_exists = $sth->fetchrow;
4708     if ( not $already_exists ) {
4709         my $field = C4::Context->preference("marcflavour") eq "UNIMARC" ? "205" : "250";
4710         my $subfield = "a";
4711         my $sth = $dbh->prepare( q|
4712             UPDATE marc_subfield_structure SET kohafield = "biblioitems.editionstatement"
4713             WHERE tagfield = ? AND tagsubfield = ?
4714         |);
4715         $sth->execute( $field, $subfield );
4716         print "Upgrade to $DBversion done (Added a mapping for biblioitems.editionstatement.)\n";
4717     } else {
4718         print "Upgrade to $DBversion done (Added a mapping for biblioitems.editionstatement (already exists, nothing to do).)\n";
4719     }
4720     SetVersion($DBversion);
4721 }
4722
4723 $DBversion = "3.07.00.016";
4724 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4725     $dbh->do("ALTER TABLE items ADD KEY `itemcallnumber` (itemcallnumber)");
4726     print "Upgrade to $DBversion done (Added index on items.itemcallnumber)\n";
4727     SetVersion($DBversion);
4728 }
4729
4730 $DBversion = "3.07.00.017";
4731 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4732     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('TransferWhenCancelAllWaitingHolds','0','Transfer items when cancelling all waiting holds',NULL,'YesNo')");
4733     print "Upgrade to $DBversion done (Add sysprefs to control transfer when cancel all waiting holds)\n";
4734     SetVersion ($DBversion);
4735 }
4736
4737 $DBversion = "3.07.00.018";
4738 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4739     $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;");
4740     print "Upgrade to $DBversion done ( adding offline operations table )\n";
4741     SetVersion($DBversion);
4742 }
4743
4744 $DBversion = "3.07.00.019";
4745 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4746     $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");
4747     $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");
4748     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";
4749     SetVersion($DBversion);
4750 }
4751
4752 $DBversion = "3.07.00.020";
4753 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4754     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OPACpatronimages',0,'Enable patron images in the OPAC',NULL,'YesNo');");
4755     print "Upgrade to $DBversion done (Bug 3516: Add the option to show patron images in the OPAC.)\n";
4756     SetVersion($DBversion);
4757 }
4758
4759 $DBversion = "3.07.00.021";
4760 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4761     $dbh->do(
4762     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('LinkerModule','Default','Chooses which linker module to use (see documentation).','Default|FirstMatchLastMatch','Choice');"
4763     );
4764     $dbh->do(
4765     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('LinkerOptions','','A pipe-separated list of options for the linker.','','free');"
4766     );
4767     $dbh->do(
4768     "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');"
4769     );
4770     $dbh->do(
4771     "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');"
4772     );
4773     $dbh->do(
4774     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AutoCreateAuthorities',0,'Automatically create authorities that do not exist when cataloging records.',NULL,'YesNo');"
4775     );
4776     $dbh->do(
4777     "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');"
4778     );
4779     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";
4780     SetVersion($DBversion);
4781 }
4782
4783 $DBversion = "3.07.00.022";
4784 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4785     $dbh->do("DELETE FROM reviews WHERE biblionumber NOT IN (SELECT biblionumber from biblio)");
4786     $dbh->do("UPDATE reviews SET borrowernumber = NULL WHERE borrowernumber NOT IN (SELECT borrowernumber FROM borrowers)");
4787     $dbh->do("ALTER TABLE reviews ADD CONSTRAINT reviews_ibfk_2 FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE");
4788     $dbh->do("ALTER TABLE reviews ADD CONSTRAINT reviews_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber ) ON UPDATE CASCADE ON DELETE SET NULL");
4789     print "Upgrade to $DBversion done (Bug 7493 - Add constraint linking OPAC comment biblionumber to biblio, OPAC comment borrowernumber to borrowers.)\n";
4790     SetVersion($DBversion);
4791 }
4792
4793 $DBversion = "3.07.00.023";
4794 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4795     $dbh->do("ALTER TABLE `message_transports` DROP FOREIGN KEY `message_transports_ibfk_3`");
4796     $dbh->do("ALTER TABLE `letter` DROP PRIMARY KEY");
4797     $dbh->do("ALTER TABLE `letter` ADD `branchcode` varchar(10) default NULL AFTER `code`");
4798     $dbh->do("ALTER TABLE `letter` ADD PRIMARY KEY  (`module`,`code`, `branchcode`)");
4799     $dbh->do("ALTER TABLE `message_transports` ADD `branchcode` varchar(10) NOT NULL default ''");
4800     $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");
4801     $dbh->do("ALTER TABLE `letter` ADD `is_html` tinyint(1) default 0 AFTER `name`");
4802
4803     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4804               VALUES ('circulation','ISSUESLIP','Issue Slip','Issue Slip', '<h3><<branches.branchname>></h3>
4805 Checked out to <<borrowers.title>> <<borrowers.firstname>> <<borrowers.initials>> <<borrowers.surname>> <br />
4806 (<<borrowers.cardnumber>>) <br />
4807
4808 <<today>><br />
4809
4810 <h4>Checked Out</h4>
4811 <checkedout>
4812 <p>
4813 <<biblio.title>> <br />
4814 Barcode: <<items.barcode>><br />
4815 Date due: <<issues.date_due>><br />
4816 </p>
4817 </checkedout>
4818
4819 <h4>Overdues</h4>
4820 <overdue>
4821 <p>
4822 <<biblio.title>> <br />
4823 Barcode: <<items.barcode>><br />
4824 Date due: <<issues.date_due>><br />
4825 </p>
4826 </overdue>
4827
4828 <hr>
4829
4830 <h4 style=\"text-align: center; font-style:italic;\">News</h4>
4831 <news>
4832 <div class=\"newsitem\">
4833 <h5 style=\"margin-bottom: 1px; margin-top: 1px\"><b><<opac_news.title>></b></h5>
4834 <p style=\"margin-bottom: 1px; margin-top: 1px\"><<opac_news.new>></p>
4835 <p class=\"newsfooter\" style=\"font-size: 8pt; font-style:italic; margin-bottom: 1px; margin-top: 1px\">Posted on <<opac_news.timestamp>></p>
4836 <hr />
4837 </div>
4838 </news>', 1)");
4839     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4840               VALUES ('circulation','ISSUEQSLIP','Issue Quick Slip','Issue Quick Slip', '<h3><<branches.branchname>></h3>
4841 Checked out to <<borrowers.title>> <<borrowers.firstname>> <<borrowers.initials>> <<borrowers.surname>> <br />
4842 (<<borrowers.cardnumber>>) <br />
4843
4844 <<today>><br />
4845
4846 <h4>Checked Out Today</h4>
4847 <checkedout>
4848 <p>
4849 <<biblio.title>> <br />
4850 Barcode: <<items.barcode>><br />
4851 Date due: <<issues.date_due>><br />
4852 </p>
4853 </checkedout>', 1)");
4854     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4855               VALUES ('circulation','RESERVESLIP','Reserve Slip','Reserve Slip', '<h5>Date: <<today>></h5>
4856
4857 <h3> Transfer to/Hold in <<branches.branchname>></h3>
4858
4859 <h3><<borrowers.surname>>, <<borrowers.firstname>></h3>
4860
4861 <ul>
4862     <li><<borrowers.cardnumber>></li>
4863     <li><<borrowers.phone>></li>
4864     <li> <<borrowers.address>><br />
4865          <<borrowers.address2>><br />
4866          <<borrowers.city >>  <<borrowers.zipcode>>
4867     </li>
4868     <li><<borrowers.email>></li>
4869 </ul>
4870 <br />
4871 <h3>ITEM ON HOLD</h3>
4872 <h4><<biblio.title>></h4>
4873 <h5><<biblio.author>></h5>
4874 <ul>
4875    <li><<items.barcode>></li>
4876    <li><<items.itemcallnumber>></li>
4877    <li><<reserves.waitingdate>></li>
4878 </ul>
4879 <p>Notes:
4880 <pre><<reserves.reservenotes>></pre>
4881 </p>', 1)");
4882     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4883               VALUES ('circulation','TRANSFERSLIP','Transfer Slip','Transfer Slip', '<h5>Date: <<today>></h5>
4884 <h3>Transfer to <<branches.branchname>></h3>
4885
4886 <h3>ITEM</h3>
4887 <h4><<biblio.title>></h4>
4888 <h5><<biblio.author>></h5>
4889 <ul>
4890    <li><<items.barcode>></li>
4891    <li><<items.itemcallnumber>></li>
4892 </ul>', 1)");
4893
4894     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('NoticeCSS','','Notices CSS url.',NULL,'free')");
4895     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('SlipCSS','','Slips CSS url.',NULL,'free')");
4896
4897     $dbh->do("UPDATE `letter` SET content = replace(content, '<<title>>', '<<biblio.title>>') WHERE code = 'HOLDPLACED'");
4898
4899     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";
4900     SetVersion($DBversion);
4901 }
4902
4903 $DBversion = "3.07.00.024";
4904 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4905     $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')");
4906     $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')");
4907     print "Upgrade to $DBversion done (Added system preference ExpireReservesMaxPickUpDelay, system preference ExpireReservesMaxPickUpDelayCharge, add reseves.charge_if_expired)\n";
4908 }
4909
4910 $DBversion = "3.07.00.025";
4911 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4912     if (TableExists('bibliocoverimage')) {
4913         $dbh->do( q|DROP TABLE bibliocoverimage;| );
4914         $dbh->do(
4915             q|CREATE TABLE biblioimages (
4916               imagenumber int(11) NOT NULL AUTO_INCREMENT,
4917               biblionumber int(11) NOT NULL,
4918               mimetype varchar(15) NOT NULL,
4919               imagefile mediumblob NOT NULL,
4920               thumbnail mediumblob NOT NULL,
4921               PRIMARY KEY (imagenumber),
4922               CONSTRAINT bibliocoverimage_fk1 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
4923               ) ENGINE=InnoDB DEFAULT CHARSET=utf8;|
4924         );
4925     }
4926     print "Upgrade to $DBversion done (Correct table name for local cover images if needed. )\n";
4927     SetVersion($DBversion);
4928 }
4929
4930 $DBversion = "3.07.00.026";
4931 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4932     $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');");
4933     print "Upgrade to $DBversion done (Add syspref CalendarFirstDayOfWeek used to select the first day of week to use in the calendar. )\n";
4934     SetVersion($DBversion);
4935 }
4936
4937 $DBversion = "3.07.00.027";
4938 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4939     $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');});
4940     print "Upgrade to $DBversion done (Added system preference RoutingListNote for adding a general note to all routing lists.)\n";
4941     SetVersion($DBversion);
4942 }
4943
4944 $DBversion = "3.07.00.028";
4945 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4946     $dbh->do(qq{
4947     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');
4948     });
4949     print "Upgrade to $DBversion done (Bug 6296 New System preference AllowPKIAuth)\n";
4950 }
4951
4952 $DBversion = "3.07.00.029";
4953 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4954     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_descriptions`;});
4955     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_mappings`;});
4956     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_biblios`;});
4957     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets`;});
4958
4959     $dbh->do(q{
4960         CREATE TABLE `oai_sets` (
4961           `id` int(11) NOT NULL auto_increment,
4962           `spec` varchar(80) NOT NULL UNIQUE,
4963           `name` varchar(80) NOT NULL,
4964           PRIMARY KEY (`id`)
4965         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4966     });
4967
4968     $dbh->do(q{
4969         CREATE TABLE `oai_sets_descriptions` (
4970           `set_id` int(11) NOT NULL,
4971           `description` varchar(255) NOT NULL,
4972           CONSTRAINT `oai_sets_descriptions_ibfk_1` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4973         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4974     });
4975
4976     $dbh->do(q{
4977         CREATE TABLE `oai_sets_mappings` (
4978           `set_id` int(11) NOT NULL,
4979           `marcfield` char(3) NOT NULL,
4980           `marcsubfield` char(1) NOT NULL,
4981           `marcvalue` varchar(80) NOT NULL,
4982           CONSTRAINT `oai_sets_mappings_ibfk_1` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4983         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4984     });
4985
4986     $dbh->do(q{
4987         CREATE TABLE `oai_sets_biblios` (
4988           `biblionumber` int(11) NOT NULL,
4989           `set_id` int(11) NOT NULL,
4990           PRIMARY KEY (`biblionumber`, `set_id`),
4991           CONSTRAINT `oai_sets_biblios_ibfk_1` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
4992           CONSTRAINT `oai_sets_biblios_ibfk_2` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4993         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4994     });
4995
4996     $dbh->do(q{
4997         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');
4998     });
4999
5000     print "Upgrade to $DBversion done (Atomic update for OAI-PMH sets management)\n";
5001     SetVersion($DBversion);
5002 }
5003
5004 $DBversion = "3.07.00.030";
5005 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5006     $dbh->do("ALTER TABLE default_circ_rules ADD
5007             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5008     $dbh->do("ALTER TABLE branch_item_rules ADD
5009             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5010     $dbh->do("ALTER TABLE default_branch_circ_rules ADD
5011             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5012     $dbh->do("ALTER TABLE default_branch_item_rules ADD
5013             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5014     # set the default rule to the current value of HomeOrHoldingBranchReturn (default to 'homebranch' if need be)
5015     my $homeorholdingbranchreturn = C4::Context->preference('HomeOrHoldingBranchReturn') || 'homebranch';
5016     $dbh->do("UPDATE default_circ_rules SET returnbranch = '$homeorholdingbranchreturn'");
5017     print "Upgrade to $DBversion done (Atomic update for OAI-PMH sets management)\n";
5018     SetVersion($DBversion);
5019 }
5020
5021 $DBversion = "3.07.00.031";
5022 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5023     $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')");
5024     print "Upgrade to $DBversion done (Add syspref to tell Koha if ICU indexing is in use for Zebra or not.)\n";
5025     SetVersion ($DBversion);
5026 }
5027
5028 $DBversion = "3.07.00.032";
5029 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5030     $dbh->do("ALTER TABLE virtualshelves MODIFY COLUMN owner int"); #should have been int already (fk to borrowers)
5031     $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
5032     $dbh->do("DELETE FROM virtualshelves WHERE owner IS NULL and category=1"); #delete private lists without owner (cascades to shelfcontents)
5033     $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");
5034     $dbh->do("UPDATE virtualshelves SET allow_add=0, allow_delete_own=1, allow_delete_other=0 WHERE category=1");
5035     $dbh->do("UPDATE virtualshelves SET allow_add=0, allow_delete_own=1, allow_delete_other=0 WHERE category=2");
5036     $dbh->do("UPDATE virtualshelves SET allow_add=1, allow_delete_own=1, allow_delete_other=1 WHERE category=3");
5037     $dbh->do("UPDATE virtualshelves SET category=2 WHERE category=3");
5038
5039     $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");
5040     $dbh->do("UPDATE virtualshelfcontents co LEFT JOIN virtualshelves sh USING (shelfnumber) SET co.borrowernumber=sh.owner");
5041
5042     $dbh->do("CREATE TABLE virtualshelfshares
5043     (id int AUTO_INCREMENT PRIMARY KEY, shelfnumber int NOT NULL,
5044     borrowernumber int, invitekey varchar(10), sharedate datetime,
5045     CONSTRAINT `virtualshelfshares_ibfk_1` FOREIGN KEY (`shelfnumber`) REFERENCES `virtualshelves` (`shelfnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
5046         CONSTRAINT `virtualshelfshares_ibfk_2` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE SET NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8");
5047
5048     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacAllowPublicListCreation',1,'If set, allows opac users to create public lists',NULL,'YesNo');");
5049     $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');");
5050
5051     print "Upgrade to $DBversion done (BZ7310: Improving list permissions)\n";
5052     SetVersion($DBversion);
5053 }
5054
5055 $DBversion = "3.07.00.033";
5056 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5057     $dbh->do("ALTER TABLE branches ADD opac_info text;");
5058     print "Upgrade to $DBversion done add opac_info to branches \n";
5059     SetVersion($DBversion);
5060 }
5061
5062 $DBversion = "3.07.00.034";
5063 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5064     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN category_code VARCHAR(10) NULL DEFAULT NULL AFTER `display_checkout`");
5065     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN class VARCHAR(255)  NOT NULL DEFAULT '' AFTER `category_code`");
5066     $dbh->do("ALTER TABLE borrower_attribute_types ADD CONSTRAINT category_code_fk FOREIGN KEY (category_code) REFERENCES categories(categorycode)");
5067     print "Upgrade to $DBversion done (New fields category_code and class in borrower_attribute_types table)\n";
5068     SetVersion($DBversion);
5069 }
5070
5071 $DBversion = "3.07.00.035";
5072 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5073     $dbh->do("ALTER TABLE issues CHANGE date_due date_due datetime");
5074     $dbh->do("UPDATE issues SET date_due = CONCAT(SUBSTR(date_due,1,11),'23:59:00')");
5075     $dbh->do("ALTER TABLE issues CHANGE returndate returndate datetime");
5076     $dbh->do("ALTER TABLE issues CHANGE lastreneweddate lastreneweddate datetime");
5077     $dbh->do("ALTER TABLE issues CHANGE issuedate issuedate datetime");
5078     $dbh->do("ALTER TABLE old_issues CHANGE date_due date_due datetime");
5079     $dbh->do("ALTER TABLE old_issues CHANGE returndate returndate datetime");
5080     $dbh->do("ALTER TABLE old_issues CHANGE lastreneweddate lastreneweddate datetime");
5081     $dbh->do("ALTER TABLE old_issues CHANGE issuedate issuedate datetime");
5082     $dbh->do("UPDATE accountlines SET description = CONCAT(description,' 23:59') WHERE accounttype='F' OR accounttype='FU'"); #BUG-8253
5083     print "Upgrade to $DBversion done (Setting up issues and accountlines tables for hourly loans)\n";
5084     SetVersion($DBversion);
5085 }
5086
5087 $DBversion = "3.07.00.036";
5088 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5089     $dbh->do(qq{
5090        ALTER TABLE z3950servers ADD timeout INT( 11 ) NOT NULL DEFAULT '0' AFTER syntax;
5091     });
5092     print "Upgrade to $DBversion done (New timeout field in z3950servers)\n";
5093 }
5094
5095 $DBversion = "3.07.00.037";
5096 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5097     $dbh->do("
5098        ALTER TABLE  `marc_subfield_structure` ADD  `maxlength` INT( 4 ) NOT NULL DEFAULT  '9999';
5099        ");
5100        $dbh->do("
5101        UPDATE `marc_subfield_structure` SET maxlength=24 WHERE tagfield='000';
5102        ");
5103        $dbh->do("
5104        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='MARC21','40','9999') WHERE tagfield='008';
5105        ");
5106        $dbh->do("
5107        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='NORMARC','40','9999') WHERE tagfield='008';
5108        ");
5109        $dbh->do("
5110        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='UNIMARC','36','9999') WHERE tagfield='100';
5111        ");
5112     print "Upgrade to $DBversion done (Add new field maxlength to marc_subfield_structure)\n";
5113     SetVersion($DBversion);
5114 }
5115
5116 $DBversion = "3.07.00.038";
5117 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5118     $dbh->do(qq{
5119         INSERT INTO systempreferences(variable,value,explanation,options,type)
5120         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')
5121     });
5122     print "Upgrade to $DBversion done (Added system preference 'UniqueItemFields')\n";
5123     SetVersion($DBversion);
5124 }
5125
5126 $DBversion = "3.07.00.039";
5127 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5128     $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')} );
5129     $dbh->do( qq{CREATE TABLE IF NOT EXISTS social_data
5130       ( isbn VARCHAR(30),
5131         num_critics INT,
5132         num_critics_pro INT,
5133         num_quotations INT,
5134         num_videos INT,
5135         score_avg DECIMAL(5,2),
5136         num_scores INT,
5137         PRIMARY KEY  (isbn)
5138       ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5139     } );
5140     $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')} );
5141     print "Upgrade to $DBversion done (added syspref and table for babeltheque (Babeltheque_url_js, babeltheque))\n";
5142     SetVersion($DBversion);
5143 }
5144
5145 $DBversion = "3.07.00.040";
5146 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5147     $dbh->do( qq{INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('SocialNetworks','0','Enable/Disable social networks links in opac detail','','YesNo')} );
5148     print "Upgrade to $DBversion done (added syspref SocialNetworks, to display facebook/ggl+ and other buttons)\n";
5149     SetVersion($DBversion);
5150 }
5151
5152
5153
5154 $DBversion = "3.07.00.041";
5155 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5156     $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')");
5157     print "Upgrade to $DBversion done (Add system preference SubscriptionDuplicateDroppedInput)\n";
5158     SetVersion($DBversion);
5159 }
5160
5161 $DBversion = "3.07.00.042";
5162 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5163     $dbh->do("ALTER TABLE reserves ADD suspend BOOLEAN NOT NULL DEFAULT 0");
5164     $dbh->do("ALTER TABLE old_reserves ADD suspend BOOLEAN NOT NULL DEFAULT 0");
5165
5166     $dbh->do("ALTER TABLE reserves ADD suspend_until DATETIME NULL DEFAULT NULL");
5167     $dbh->do("ALTER TABLE old_reserves ADD suspend_until DATETIME NULL DEFAULT NULL");
5168
5169     $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')");
5170
5171     print "Upgrade to $DBversion done (Add suspend fields to reserves table, add syspref AutoResumeSuspendedHolds)\n";
5172     SetVersion ($DBversion);
5173 }
5174
5175 $DBversion = "3.07.00.043";
5176 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5177     my $countXSLTDetailsDisplay = 0;
5178     my $valueXSLTDetailsDisplay = "";
5179     my $valueXSLTResultsDisplay = "";
5180     my $valueOPACXSLTDetailsDisplay = "";
5181     my $valueOPACXSLTResultsDisplay = "";
5182     #the line below test if database comes from a BibLibre's branch
5183     $countXSLTDetailsDisplay = $dbh->do('SELECT 1 FROM systempreferences WHERE variable="IntranetXSLTDetailsDisplay"');
5184     if ($countXSLTDetailsDisplay > 0)
5185     {
5186         #the two lines below will only be used to update the databases from the BibLibre's branch. They will not affect the others
5187         $dbh->do(q|UPDATE systempreferences SET variable="XSLTDetailsDisplay" WHERE variable="IntranetXSLTDetailsDisplay"|);
5188         $dbh->do(q|UPDATE systempreferences SET variable="XSLTResultsDisplay" WHERE variable="IntranetXSLTResultsDisplay"|);
5189     }
5190     else
5191     {
5192         $valueXSLTDetailsDisplay = "default" if (C4::Context->preference("XSLTDetailsDisplay"));
5193         $valueXSLTResultsDisplay = "default" if (C4::Context->preference("XSLTResultsDisplay"));
5194         $valueOPACXSLTDetailsDisplay = "default" if (C4::Context->preference("OPACXSLTDetailsDisplay"));
5195         $valueOPACXSLTResultsDisplay = "default" if (C4::Context->preference("OPACXSLTResultsDisplay"));
5196         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueXSLTDetailsDisplay\" WHERE variable='XSLTDetailsDisplay'");
5197         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueXSLTResultsDisplay\" WHERE variable='XSLTResultsDisplay'");
5198         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueOPACXSLTDetailsDisplay\" WHERE variable='OPACXSLTDetailsDisplay'");
5199         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueOPACXSLTResultsDisplay\" WHERE variable='OPACXSLTResultsDisplay'");
5200     }
5201     print "Upgrade to $DBversion done (XSLT systempreference takes a path to file rather than YesNo)\n";
5202     SetVersion($DBversion);
5203 }
5204
5205 $DBversion = "3.07.00.044";
5206 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5207     $dbh->do("ALTER TABLE aqbooksellers ADD deliverytime INT DEFAULT NULL");
5208     print "Upgrade to $DBversion done (Add deliverytime field in aqbooksellers table)";
5209     SetVersion($DBversion);
5210 }
5211
5212 $DBversion = "3.07.00.045";
5213 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5214     $dbh->do("ALTER TABLE import_batches MODIFY COLUMN batch_type ENUM('batch','z3950','webservice') NOT NULL default 'batch'");
5215     print "Upgrade to $DBversion done (Add 'webservice' to batch_type enum)\n";
5216     SetVersion ($DBversion);
5217 }
5218
5219 $DBversion = "3.07.00.046";
5220 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5221     $dbh->do("ALTER TABLE issuingrules ADD COLUMN lengthunit varchar(10) DEFAULT 'days' AFTER issuelength");
5222     print "Upgrade to $DBversion done (Setting up issues tables for hourly loans (lengthunit fix))\n";
5223     SetVersion($DBversion);
5224 }
5225
5226 $DBversion = "3.07.00.047";
5227 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5228     $dbh->do("CREATE INDEX items_location ON items(location)");
5229     $dbh->do("CREATE INDEX items_ccode ON items(ccode)");
5230     print "Upgrade to $DBversion done (items_location and items_ccode indexes added for ShelfBrowser)\n";
5231     SetVersion($DBversion);
5232 }
5233
5234 $DBversion = "3.07.00.048";
5235 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5236     $dbh->do(
5237         q | CREATE TABLE ratings (
5238   borrowernumber int(11) NOT NULL,
5239   biblionumber int(11) NOT NULL,
5240   rating_value tinyint(1) NOT NULL,
5241   timestamp timestamp NOT NULL default CURRENT_TIMESTAMP,
5242   PRIMARY KEY  (borrowernumber,biblionumber),
5243   CONSTRAINT ratings_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE,
5244   CONSTRAINT ratings_ibfk_2 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
5245 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
5246     );
5247
5248     $dbh->do(
5249 q /INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OpacStarRatings','disable',NULL,'disable|all|details','Choice') /
5250     );
5251
5252     print
5253 "Upgrade to $DBversion done (Add 'ratings' table and 'OpacStarRatings' syspref)\n";
5254     SetVersion($DBversion);
5255 }
5256
5257 $DBversion = "3.07.00.049";
5258 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5259     $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')");
5260     print "Upgrade to $DBversion done (Add system preference OpacBrowseResults ))\n";
5261     SetVersion($DBversion);
5262 }
5263
5264 $DBversion = "3.08.00.000";
5265 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5266     print "Upgrade to $DBversion done\n";
5267     SetVersion($DBversion);
5268 }
5269
5270 $DBversion = "3.09.00.001";
5271 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5272     $dbh->do("ALTER TABLE borrower_attribute_types MODIFY category_code VARCHAR( 1 ) NULL DEFAULT NULL");
5273     print "Upgrade to $DBversion done. (Bug 8002: Update patron attribute types table to allow NULL category_code)\n";
5274     SetVersion($DBversion);
5275 }
5276
5277 $DBversion = "3.09.00.002";
5278 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5279     $dbh->do("ALTER TABLE saved_sql
5280         ADD (
5281             cache_expiry INT NOT NULL DEFAULT 300,
5282             public BOOLEAN NOT NULL DEFAULT FALSE
5283         );
5284     ");
5285     print "Upgrade to $DBversion done (Added cache_expiry and public fields in
5286 saved_reports table.)\n";
5287     SetVersion($DBversion);
5288 }
5289
5290 $DBversion = "3.09.00.003";
5291 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5292     $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');");
5293     print "Upgrade to $DBversion done (Added SvcMaxReportRows syspref)\n";
5294     SetVersion($DBversion);
5295 }
5296
5297 $DBversion = "3.09.00.004";
5298 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5299     $dbh->do("INSERT IGNORE INTO permissions (module_bit, code, description) VALUES('13', 'edit_patrons', 'Perform batch modifivation of patrons')");
5300     print "Upgrade to $DBversion done (Adds permissions flag for access to the patron modifications tool)\n";
5301     SetVersion($DBversion);
5302 }
5303
5304 $DBversion = "3.09.00.005";
5305 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5306     unless (TableExists('quotes')) {
5307         $dbh->do( qq{
5308             CREATE TABLE `quotes` (
5309               `id` int(11) NOT NULL AUTO_INCREMENT,
5310               `source` text DEFAULT NULL,
5311               `text` mediumtext NOT NULL,
5312               `timestamp` datetime NOT NULL,
5313               PRIMARY KEY (`id`)
5314             ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5315         });
5316     }
5317     $dbh->do( qq{
5318         INSERT IGNORE INTO permissions VALUES (13, "edit_quotes","Edit quotes for quote-of-the-day feature");
5319     });
5320     $dbh->do( qq{
5321         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');
5322     });
5323     print "Upgrade to $DBversion done (Adding Quote of the Day Option.)\n";
5324     SetVersion($DBversion);
5325 }
5326
5327 $DBversion = "3.09.00.006";
5328 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5329     $dbh->do("UPDATE systempreferences SET
5330                 variable = 'OPACShowHoldQueueDetails',
5331                 value = CASE value WHEN '1' THEN 'priority' ELSE 'none' END,
5332                 options = 'none|priority|holds|holds_priority',
5333                 explanation = 'Show holds details in OPAC',
5334                 type = 'Choice'
5335               WHERE variable = 'OPACDisplayRequestPriority'");
5336     print "Upgrade to $DBversion done (Changed system preference OPACDisplayRequestPriority -> OPACShowHoldQueueDetails)\n";
5337     SetVersion($DBversion);
5338 }
5339
5340 $DBversion = "3.09.00.007";
5341 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5342     unless(C4::Context->preference('ReservesControlBranch')){
5343         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('ReservesControlBranch','PatronLibrary','ItemHomeLibrary|PatronLibrary','Branch checked for members reservations rights.','Choice')");
5344     }
5345     print "Upgrade to $DBversion done (Insert ReservesControlBranch systempreference into systempreferences table )\n";
5346     SetVersion($DBversion);
5347 }
5348
5349 $DBversion = "3.09.00.008";
5350 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5351     $dbh->do("ALTER TABLE sessions ADD PRIMARY KEY (id);");
5352     $dbh->do("ALTER TABLE sessions DROP INDEX `id`;");
5353     print "Upgrade to $DBversion done (redefine the field id as PRIMARY KEY of sessions)\n";
5354     SetVersion($DBversion);
5355 }
5356
5357 $DBversion = "3.09.00.009";
5358 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5359     $dbh->do("ALTER TABLE branches ADD PRIMARY KEY (branchcode);");
5360     $dbh->do("ALTER TABLE branches DROP INDEX branchcode;");
5361     print "Upgrade to $DBversion done (redefine the field branchcode as PRIMARY KEY of branches)\n";
5362     SetVersion ($DBversion);
5363 }
5364
5365 $DBversion = "3.09.00.010";
5366 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5367     $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')");
5368     print "Upgrade to $DBversion done (Add system preference issuelostitem ))\n";
5369     SetVersion($DBversion);
5370 }
5371
5372 $DBversion = "3.09.00.011";
5373 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5374     $dbh->do("ALTER TABLE `biblioitems` ADD `ean` VARCHAR( 13 ) NULL AFTER issn");
5375     $dbh->do("CREATE INDEX `ean` ON biblioitems (`ean`) ");
5376     $dbh->do("ALTER TABLE `deletedbiblioitems` ADD `ean` VARCHAR( 13 ) NULL AFTER issn");
5377     if (C4::Context->preference("marcflavour") eq 'UNIMARC') {
5378          $dbh->do("UPDATE marc_subfield_structure SET kohafield='biblioitems.ean' WHERE tagfield='073' and tagsubfield='a'");
5379     }
5380     print "Upgrade to $DBversion done (Adding ean in biblioitems and deletedbiblioitems)\n";
5381     print "If you have records with ean, please run misc/batchRebuildBiblioTables.pl to populate bibliotems.ean\n" if (C4::Context->preference("marcflavour") eq 'UNIMARC');
5382     SetVersion($DBversion);
5383 }
5384
5385 $DBversion = "3.09.00.012";
5386 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5387     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('SuspendHoldsIntranet', '1', NULL , 'Allow holds to be suspended from the intranet.', 'YesNo')");
5388     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('SuspendHoldsOpac', '1', NULL , 'Allow holds to be suspended from the OPAC.', 'YesNo')");
5389     print "Upgrade to $DBversion done (Add system preference OpacBrowseResults ))\n";
5390     SetVersion($DBversion);
5391 }
5392
5393 $DBversion ="3.09.00.013";
5394 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5395     $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');");
5396     print "Upgrade to $DBversion done (Add system preference DefaultLanguageField008))\n";
5397     SetVersion($DBversion);
5398 }
5399
5400 $DBversion ="3.09.00.014";
5401 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5402     # add phone message transport type
5403     $dbh->do("INSERT INTO message_transport_types (message_transport_type) VALUES ('phone')");
5404
5405     # adds HOLD_PHONE and PREDUE_PHONE letters (as placeholders)
5406     $dbh->do("INSERT INTO letter (module, code, name, title, content) VALUES
5407               ('reserves', 'HOLD_PHONE', 'Item Available for Pick-up (phone notice)', 'Item Available for Pick-up (phone notice)', 'Your item is available for pickup'),
5408               ('circulation', 'PREDUE_PHONE', 'Advance Notice of Item Due (phone notice)', 'Advance Notice of Item Due (phone notice)', 'Your item is due soon'),
5409               ('circulation', 'OVERDUE_PHONE', 'Overdue Notice (phone notice)', 'Overdue Notice (phone notice)', 'Your item is overdue')
5410               ");
5411
5412     # add phone notifications to patron message preferences options
5413     $dbh->do("INSERT INTO message_transports
5414              (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) VALUES
5415              (4, 'phone', 0, 'reserves', 'HOLD_PHONE'),
5416              (2, 'phone', 0, 'circulation', 'PREDUE_PHONE')
5417              ");
5418
5419     # add TalkingTechItivaPhoneNotification syspref
5420     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('TalkingTechItivaPhoneNotification',0,'If ON, enables Talking Tech I-tiva phone notifications',NULL,'YesNo');");
5421
5422     print "Upgrade done (Support for Talking Tech i-tiva phone notification system)\n";
5423     SetVersion($DBversion);
5424 }
5425
5426 $DBversion = "3.09.00.015";
5427 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5428     $dbh->do(qq{
5429         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')
5430     });
5431     print "Upgrade to $DBversion done (Add System preference StatisticsFields)\n";
5432     SetVersion($DBversion);
5433 }
5434
5435 $DBversion = "3.09.00.016";
5436 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5437     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACShowBarcode','0','Show items barcode in holding tab','','YesNo')");
5438     print "Upgrade to $DBversion done (Add syspref OPACShowBarcode)\n";
5439     SetVersion ($DBversion);
5440 }
5441
5442 $DBversion = "3.09.00.017";
5443 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5444     $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');");
5445     print "Upgrade to $DBversion done (Add customizable OpacNavRight region to the OPAC main page)\n";
5446     SetVersion ($DBversion);
5447 }
5448
5449 $DBversion = "3.09.00.018";
5450 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5451     $dbh->do("DROP TABLE IF EXISTS aqbudgetborrowers");
5452     $dbh->do("
5453         CREATE TABLE aqbudgetborrowers (
5454           budget_id int(11) NOT NULL,
5455           borrowernumber int(11) NOT NULL,
5456           PRIMARY KEY (budget_id, borrowernumber),
5457           CONSTRAINT aqbudgetborrowers_ibfk_1 FOREIGN KEY (budget_id)
5458             REFERENCES aqbudgets (budget_id)
5459             ON DELETE CASCADE ON UPDATE CASCADE,
5460           CONSTRAINT aqbudgetborrowers_ibfk_2 FOREIGN KEY (borrowernumber)
5461             REFERENCES borrowers (borrowernumber)
5462             ON DELETE CASCADE ON UPDATE CASCADE
5463         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
5464     ");
5465     $dbh->do("
5466         INSERT INTO permissions (module_bit, code, description)
5467         VALUES (11, 'budget_manage_all', 'Manage all budgets')
5468     ");
5469     print "Upgrade to $DBversion done (Add aqbudgetborrowers table)\n";
5470     SetVersion($DBversion);
5471 }
5472
5473 $DBversion = "3.09.00.019";
5474 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5475     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('OPACShowUnusedAuthorities','1','','Show authorities that are not being used in the OPAC.','YesNo')");
5476     print "Upgrade to $DBversion done (Add OPACShowUnusedAuthorities system preference)\n";
5477     SetVersion ($DBversion);
5478 }
5479
5480 $DBversion = "3.09.00.020";
5481 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5482     $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')");
5483     $dbh->do("
5484 CREATE TABLE IF NOT EXISTS borrower_files (
5485   file_id int(11) NOT NULL AUTO_INCREMENT,
5486   borrowernumber int(11) NOT NULL,
5487   file_name varchar(255) NOT NULL,
5488   file_type varchar(255) NOT NULL,
5489   file_description varchar(255) DEFAULT NULL,
5490   file_content longblob NOT NULL,
5491   date_uploaded timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
5492   PRIMARY KEY (file_id),
5493   KEY borrowernumber (borrowernumber)
5494 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
5495     ");
5496     $dbh->do("ALTER TABLE borrower_files ADD CONSTRAINT borrower_files_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE");
5497
5498     print "Upgrade to $DBversion done (Added borrow_files table, EnableBorrowerFiles syspref)\n";
5499     SetVersion($DBversion);
5500 }
5501
5502 $DBversion = "3.09.00.021";
5503 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5504     $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');");
5505     print "Upgrade to $DBversion done (Add syspref UpdateTotalIssuesOnCirc)\n";
5506     SetVersion($DBversion);
5507 }
5508
5509 $DBversion = "3.09.00.022";
5510 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5511     $dbh->do("ALTER TABLE search_history MODIFY COLUMN query_cgi text NOT NULL");
5512     print "Upgrade to $DBversion done (Change search_history.query_cgi type to text. bug 5981)\n";
5513     SetVersion($DBversion);
5514 }
5515
5516 $DBversion = "3.09.00.023";
5517 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5518     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('SearchEngine','Zebra','Solr|Zebra','Search Engine','Choice')");
5519     print "Upgrade to $DBversion done (Add system preference SearchEngine )\n";
5520     SetVersion($DBversion);
5521 }
5522
5523 $DBversion ="3.09.00.024";
5524 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5525     $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')");
5526     print "Upgrade to $DBversion done (Add system preference IntranetSlipPrinterJS))\n";
5527     SetVersion($DBversion);
5528 }
5529
5530 $DBversion = "3.09.00.025";
5531 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5532     $dbh->do('START TRANSACTION');
5533     $dbh->do('CREATE TABLE tmp_reserves AS SELECT * FROM old_reserves LIMIT 0');
5534     $dbh->do('ALTER TABLE tmp_reserves ADD reserve_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
5535     $dbh->do("
5536         INSERT INTO tmp_reserves (
5537           borrowernumber, reservedate, biblionumber,
5538           constrainttype, branchcode, notificationdate,
5539           reminderdate, cancellationdate, reservenotes,
5540           priority, found, timestamp, itemnumber,
5541           waitingdate, expirationdate, lowestPriority,
5542           suspend, suspend_until
5543         ) SELECT
5544           borrowernumber, reservedate, biblionumber,
5545           constrainttype, branchcode, notificationdate,
5546           reminderdate, cancellationdate, reservenotes,
5547           priority, found, timestamp, itemnumber,
5548           waitingdate, expirationdate, lowestPriority,
5549           suspend, suspend_until
5550         FROM old_reserves ORDER BY reservedate
5551     ");
5552     $dbh->do('SET @ai = ( SELECT MAX( reserve_id ) FROM tmp_reserves )');
5553     $dbh->do('TRUNCATE old_reserves');
5554     $dbh->do('ALTER TABLE old_reserves ADD reserve_id INT( 11 ) NOT NULL PRIMARY KEY FIRST');
5555     $dbh->do('INSERT INTO old_reserves SELECT * FROM tmp_reserves WHERE reserve_id <= @ai');
5556     $dbh->do("
5557         INSERT INTO tmp_reserves (
5558           borrowernumber, reservedate, biblionumber,
5559           constrainttype, branchcode, notificationdate,
5560           reminderdate, cancellationdate, reservenotes,
5561           priority, found, timestamp, itemnumber,
5562           waitingdate, expirationdate, lowestPriority,
5563           suspend, suspend_until
5564         ) SELECT
5565           borrowernumber, reservedate, biblionumber,
5566           constrainttype, branchcode, notificationdate,
5567           reminderdate, cancellationdate, reservenotes,
5568           priority, found, timestamp, itemnumber,
5569           waitingdate, expirationdate, lowestPriority,
5570           suspend, suspend_until
5571         FROM reserves ORDER BY reservedate
5572     ");
5573     $dbh->do('TRUNCATE reserves');
5574     $dbh->do('ALTER TABLE reserves ADD reserve_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
5575     $dbh->do('INSERT INTO reserves SELECT * FROM tmp_reserves WHERE reserve_id > COALESCE(@ai, 0)');
5576     $dbh->do('DROP TABLE tmp_reserves');
5577     $dbh->do('COMMIT');
5578
5579     my $sth = $dbh->prepare("
5580         SELECT COUNT( * ) AS count
5581         FROM information_schema.COLUMNS
5582         WHERE COLUMN_NAME =  'reserve_id'
5583         AND (
5584           TABLE_NAME LIKE  'reserves'
5585           OR
5586           TABLE_NAME LIKE  'old_reserves'
5587         )
5588     ");
5589     $sth->execute();
5590     my $row = $sth->fetchrow_hashref();
5591     die("Failed to add reserve_id to reserves tables, please refresh the page to try again.") unless ( $row->{'count'} );
5592
5593     print "Upgrade to $DBversion done (add reserve_id to reserves & old_reserves tables)\n";
5594     SetVersion($DBversion);
5595 }
5596
5597 $DBversion = "3.09.00.026";
5598 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5599     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
5600         ( 3, 'parameters_remaining_permissions', 'Remaining system parameters permissions'),
5601         ( 3, 'manage_circ_rules', 'manage circulation rules')");
5602     $dbh->do("INSERT INTO user_permissions (borrowernumber, module_bit, code)
5603         SELECT borrowernumber, 3, 'parameters_remaining_permissions'
5604         FROM borrowers WHERE flags & (1 << 3)");
5605     # Give new subpermissions to all users that have 'parameters' permission flag (bit 3) set
5606     # see userflags table
5607     $dbh->do("INSERT INTO user_permissions (borrowernumber, module_bit, code)
5608         SELECT borrowernumber, 3, 'manage_circ_rules'
5609         FROM borrowers WHERE flags & (1 << 3)");
5610     print "Upgrade to $DBversion done (Added parameters subpermissions)\n";
5611     SetVersion($DBversion);
5612 }
5613
5614 $DBversion = '3.09.00.027';
5615 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5616     $dbh->do("ALTER TABLE issuingrules ADD overduefinescap decimal(28,6) DEFAULT NULL");
5617     my $maxfine = C4::Context->preference('MaxFine');
5618     if ($maxfine && $maxfine < 900) { # an arbitrary value that tells us it's not "some huge value"
5619       $dbh->do("UPDATE issuingrules SET overduefinescap=?",undef,$maxfine);
5620       $dbh->do("UPDATE systempreferences SET value = NULL WHERE variable = 'MaxFine'");
5621     }
5622     $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'");
5623     print "Upgrade to $DBversion done (Bug 7420 add overduefinescap to circulation matrix)\n";
5624     SetVersion ($DBversion);
5625 }
5626
5627 $DBversion = "3.09.00.028";
5628 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5629     unless ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) {
5630         my %referencetypes = (  '00' => 'PERSO_NAME',
5631                                 '10' => 'CORPO_NAME',
5632                                 '11' => 'MEETI_NAME',
5633                                 '30' => 'UNIF_TITLE',
5634                                 '48' => 'CHRON_TERM',
5635                                 '50' => 'TOPIC_TERM',
5636                                 '51' => 'GEOGR_NAME',
5637                                 '55' => 'GENRE/FORM'
5638                 );
5639         my $query = q{SELECT DISTINCT authtypecode, tagfield
5640                     FROM auth_subfield_structure
5641                     WHERE (tagfield BETWEEN '400' AND '455' OR
5642                     tagfield BETWEEN '500' and '555') AND tagsubfield='a' AND
5643                     frameworkcode = '' AND ROW(authtypecode, tagfield) NOT IN
5644                     (SELECT authtypecode, tagfield FROM auth_subfield_structure
5645                     WHERE tagsubfield ='9' )};
5646         $sth = $dbh->prepare($query);
5647         $sth->execute;
5648         my $sth2 = $dbh->prepare(q{INSERT INTO auth_subfield_structure
5649                 (authtypecode, tagfield, tagsubfield, liblibrarian, libopac,
5650                  repeatable, mandatory, tab, authorised_value, value_builder,
5651                  seealso, isurl, hidden, linkid, kohafield, frameworkcode)
5652                 VALUES (?, ?, '9', '9 (RLIN)', '9 (RLIN)', 0, 0, ?, NULL, NULL,
5653                     NULL, 0, 1, '', '', '')});
5654         my $sth3 = $dbh->prepare(q{UPDATE auth_subfield_structure SET
5655                                     frameworkcode = ? WHERE authtypecode = ? AND
5656                                     tagfield = ? AND tagsubfield = 'a'});
5657         while (my $row = $sth->fetchrow_arrayref()) {
5658             my ($authtypecode, $field) = @$row;
5659             $sth2->execute($authtypecode, $field, substr($field, 0, 1));
5660             my $authtypemarker = substr $field, 1, 2;
5661             if ($authtypemarker && $referencetypes{$authtypemarker}) {
5662                 $sth3->execute($referencetypes{$authtypemarker}, $authtypecode, $field);
5663             }
5664         }
5665     }
5666
5667     print "Upgrade to $DBversion done (Add thesaurus links for MARC21/NORMARC)\n";
5668     SetVersion($DBversion);
5669 }
5670
5671 $DBversion = "3.09.00.029"; # FIXME
5672 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5673     $dbh->do("UPDATE systempreferences SET options=concat(options,'|EAN13') WHERE variable='itemBarcodeInputFilter' AND options NOT LIKE '%EAN13%'");
5674     print "Upgrade to $DBversion done (Add itemBarcodeInputFilter choice EAN13)\n";
5675
5676     $dbh->do("UPDATE systempreferences SET options = concat(options,'|EAN13'), explanation = concat(explanation,'; EAN13 - incremental') WHERE variable = 'autoBarcode' AND options NOT LIKE '%EAN13%'");
5677     print "Upgrade to $DBversion done ( Added EAN13 barcode autogeneration sequence )\n";
5678     SetVersion($DBversion);
5679 }
5680
5681 $DBversion ="3.09.00.030";
5682 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5683     my $query = "SELECT value FROM systempreferences WHERE variable='opacstylesheet'";
5684     my $remote= $dbh->selectrow_arrayref($query);
5685     $dbh->do("DELETE from systempreferences WHERE variable='opacstylesheet'");
5686     if($remote && $remote->[0]) {
5687         $query="UPDATE systempreferences SET value=? WHERE variable='opaclayoutstylesheet'";
5688         $dbh->do($query,undef,$remote->[0]);
5689         print "NOTE: The URL of your remote opac css file has been moved to preference opaclayoutstylesheet.\n";
5690     }
5691     print "Upgrade to $DBversion done (BZ 8263: Make OPAC stylesheet preferences more consistent)\n";
5692     SetVersion($DBversion);
5693 }
5694
5695 $DBversion = "3.09.00.031";
5696 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5697     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonReviews'");
5698     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonSimilarItems'");
5699     $dbh->do("DELETE FROM systempreferences WHERE variable='AWSAccessKeyID'");
5700     $dbh->do("DELETE FROM systempreferences WHERE variable='AWSPrivateKey'");
5701     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonReviews'");
5702     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonSimilarItems'");
5703     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonEnabled'");
5704     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonEnabled'");
5705     print "Upgrade to $DBversion done ('Remove preferences controlling broken Amazon features (Bug 8679')\n";
5706     SetVersion ($DBversion);
5707 }
5708
5709 $DBversion = "3.09.00.032";
5710 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5711     $dbh->do("UPDATE systempreferences SET value = 'call_number' WHERE variable = 'defaultSortField' AND value = 'callnumber'");
5712     $dbh->do("UPDATE systempreferences SET value = 'call_number' WHERE variable = 'OPACdefaultSortField' AND value = 'callnumber'");
5713     print "Upgrade to $DBversion done (Bug 8657 - Default sort by call number does not work. Correcting system preference value.)\n";
5714     SetVersion ($DBversion);
5715 }
5716
5717
5718 $DBversion = '3.09.00.033';
5719 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5720    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacSuppressionByIPRange','','Restrict the suppression to IP adresses outside of the IP range','','free');");
5721    print "Upgrade to $DBversion done (Add OpacSuppressionByIPRange syspref)\n";
5722    SetVersion ($DBversion);
5723 }
5724
5725 $DBversion ="3.09.00.034";
5726 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5727     $dbh->do("UPDATE auth_subfield_structure SET frameworkcode = 'PERSO_NAME' WHERE frameworkcode = 'PERSO_CODE'");
5728     $dbh->do("UPDATE auth_subfield_structure SET frameworkcode = 'CORPO_NAME' WHERE frameworkcode = 'ORGO_CODE'");
5729     print "Upgrade to $DBversion done (Bug 8207: correct typo in authority types)\n";
5730     SetVersion ($DBversion);
5731 }
5732
5733 $DBversion = "3.09.00.035";
5734 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5735     $dbh->do("
5736     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');
5737     ");
5738     $dbh->do(
5739     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SubfieldsToUseWhenPrefill','','Define a list of subfields to use when prefilling items (separated by space)','','Free');
5740     ");
5741     print "Upgrade to $DBversion done (Adding PrefillItem and SubfieldsToUseWhenPrefill sysprefs)\n";
5742     SetVersion ($DBversion);
5743 }
5744
5745 $DBversion = "3.09.00.036";
5746 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5747     # biblioitems changes
5748     $dbh->do("ALTER TABLE biblioitems ADD COLUMN agerestriction VARCHAR(255) DEFAULT NULL AFTER cn_sort");
5749     $dbh->do("ALTER TABLE deletedbiblioitems ADD COLUMN agerestriction VARCHAR(255) DEFAULT NULL AFTER cn_sort");
5750     # preferences changes
5751     $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')");
5752     $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')");
5753
5754     print "Upgrade to $DBversion done (Add colum agerestriction to biblioitems and deletedbiblioitems, add system preferences AgeRestrictionMarker and AgeRestrictionOverride)\n";
5755    SetVersion ($DBversion);
5756 }
5757
5758 $DBversion = "3.09.00.037";
5759 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5760     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('UseTransportCostMatrix',0,'Use Transport Cost Matrix when filling holds','','YesNo')");
5761
5762  $dbh->do("CREATE TABLE `transport_cost` (
5763               `frombranch` varchar(10) NOT NULL,
5764               `tobranch` varchar(10) NOT NULL,
5765               `cost` decimal(6,2) NOT NULL,
5766               `disable_transfer` tinyint(1) NOT NULL DEFAULT 0,
5767               CHECK ( `frombranch` <> `tobranch` ), -- a dud check, mysql does not support that
5768               PRIMARY KEY (`frombranch`, `tobranch`),
5769               CONSTRAINT `transport_cost_ibfk_1` FOREIGN KEY (`frombranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
5770               CONSTRAINT `transport_cost_ibfk_2` FOREIGN KEY (`tobranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
5771           ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
5772
5773     print "Upgrade to $DBversion done (creating `transport_cost` table; adding UseTransportCostMatrix systempref, in circulation)\n";
5774     SetVersion($DBversion);
5775 }
5776
5777 $DBversion ="3.09.00.038";
5778 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5779     $dbh->do("ALTER TABLE borrower_attributes CHANGE  attribute  attribute VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
5780     print "Upgrade to $DBversion done (Increase the maximum size of a borrower attribute value)\n";
5781     SetVersion($DBversion);
5782 }
5783
5784 $DBversion ="3.09.00.039";
5785 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5786     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,type) VALUES('DidYouMeanFromAuthorities','0','Suggest searches based on authority file.','YesNo');");
5787     print "Upgrade to $DBversion done (Add system preference DidYouMeanFromAuthorities)\n";
5788     SetVersion($DBversion);
5789 }
5790
5791 $DBversion = "3.09.00.040";
5792 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5793     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('IncludeSeeFromInSearches','0','','Include see-from references in searches.','YesNo');");
5794     print "Upgrade to $DBversion done (Add IncludeSeeFromInSearches system preference)\n";
5795     SetVersion ($DBversion);
5796 }
5797
5798 $DBversion = "3.09.00.041";
5799 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5800     $dbh->do(qq{
5801         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ExportRemoveFields','','List of fields for non export in circulation.pl (separated by a space)','','');
5802     });
5803     print "Upgrade to $DBversion done (Add system preference ExportRemoveFields)\n";
5804     SetVersion($DBversion);
5805 }
5806
5807 $DBversion = "3.09.00.042";
5808 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5809     $dbh->do(qq{
5810         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ExportWithCsvProfile','','Set a profile name for CSV export','','');
5811     });
5812     print "Upgrade to $DBversion done (Adds New System preference ExportWithCsvProfile)\n";
5813     SetVersion($DBversion)
5814 }
5815
5816 $DBversion = "3.09.00.043";
5817 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5818     $dbh->do("
5819         ALTER TABLE aqorders
5820         ADD parent_ordernumber int(11) DEFAULT NULL
5821     ");
5822     $dbh->do("
5823         UPDATE aqorders
5824         SET parent_ordernumber = ordernumber;
5825     ");
5826     print "Upgrade to $DBversion done (Adding parent_ordernumber in aqorders)\n";
5827     SetVersion($DBversion);
5828 }
5829
5830 $DBversion = '3.09.00.044';
5831 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5832     $dbh->do("ALTER TABLE statistics ADD COLUMN ccode VARCHAR ( 10 ) NULL AFTER associatedborrower");
5833     $dbh->do("UPDATE statistics SET statistics.ccode = ( SELECT items.ccode FROM items WHERE statistics.itemnumber = items.itemnumber )");
5834     $dbh->do("UPDATE statistics SET statistics.ccode = (
5835               SELECT deleteditems.ccode FROM deleteditems
5836                   WHERE statistics.itemnumber = deleteditems.itemnumber
5837               ) WHERE statistics.ccode IS NULL");
5838     print "Upgrade done ( Added Collection Code to Statistics table. )\n";
5839     SetVersion ($DBversion);
5840 }
5841
5842 $DBversion = "3.09.00.045";
5843 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5844     $dbh->do("ALTER TABLE borrower_attribute_types MODIFY category_code VARCHAR( 10 ) NULL DEFAULT NULL");
5845     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.";
5846     SetVersion($DBversion);
5847 }
5848
5849 $DBversion = "3.09.00.046";
5850 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5851     $dbh->do("ALTER TABLE `accountlines` ADD `accountlines_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;");
5852     print "Upgrade to $DBversion done (adding accountlines_id field in accountlines table)\n";
5853     SetVersion($DBversion);
5854 }
5855
5856 $DBversion = "3.09.00.047";
5857 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5858     # to preserve default behaviour as best as possible, set this new preference differently depending on whether IndependantBranches is set or not
5859     my $prefvalue = 'anywhere';
5860     if (C4::Context->preference("IndependantBranches")) { $prefvalue = 'homeorholdingbranch';}
5861     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowReturnToBranch', '$prefvalue', 'Where an item may be returned', 'anywhere|homebranch|holdingbranch|homeorholdingbranch', 'Choice');");
5862
5863     print "Upgrade to $DBversion done: adding AllowReturnToBranch syspref (bug 6151)";
5864     SetVersion($DBversion);
5865 }
5866
5867 $DBversion = "3.09.00.048";
5868 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5869     $dbh->do("ALTER TABLE authorised_values MODIFY lib varchar(200)");
5870     $dbh->do("ALTER TABLE authorised_values MODIFY lib_opac varchar(200)");
5871
5872     print "Upgrade to $DBversion done (Raise the length of Authorised Values descriptions)\n";
5873     SetVersion($DBversion);
5874 }
5875
5876 $DBversion ="3.09.00.049";
5877 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5878     $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');");
5879     $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');");
5880     $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');");
5881     $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');");
5882     print "Upgrade to $DBversion done (Add OPACMobileUserCSS, OpacMainUserBlockMobile, OpacShowLibrariesPulldownMobile and OpacShowFiltersPulldownMobile sysprefs)\n";
5883     SetVersion($DBversion);
5884 }
5885
5886 $DBversion = "3.09.00.050";
5887 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5888     $dbh->do("ALTER TABLE authorised_values MODIFY category varchar(16) NOT NULL DEFAULT '';");
5889     $dbh->do("INSERT INTO authorised_values (category, authorised_value, lib) VALUES
5890               ('REPORT_GROUP', 'CIRC', 'Circulation'),
5891               ('REPORT_GROUP', 'CAT', 'Catalog'),
5892               ('REPORT_GROUP', 'PAT', 'Patrons'),
5893               ('REPORT_GROUP', 'ACQ', 'Acquisitions'),
5894               ('REPORT_GROUP', 'ACC', 'Accounts');");
5895
5896     $dbh->do("ALTER TABLE reports_dictionary ADD report_area varchar(6) DEFAULT NULL;");
5897     $dbh->do("UPDATE reports_dictionary SET report_area = CASE area
5898                   WHEN 1 THEN 'CIRC'
5899                   WHEN 2 THEN 'CAT'
5900                   WHEN 3 THEN 'PAT'
5901                   WHEN 4 THEN 'ACQ'
5902                   WHEN 5 THEN 'ACC'
5903                   END;");
5904     $dbh->do("ALTER TABLE reports_dictionary DROP area;");
5905     $dbh->do("ALTER TABLE reports_dictionary ADD KEY dictionary_area_idx (report_area);");
5906
5907     $dbh->do("ALTER TABLE saved_sql ADD report_area varchar(6) DEFAULT NULL;");
5908     $dbh->do("ALTER TABLE saved_sql ADD report_group varchar(80) DEFAULT NULL;");
5909     $dbh->do("ALTER TABLE saved_sql ADD report_subgroup varchar(80) DEFAULT NULL;");
5910     $dbh->do("ALTER TABLE saved_sql ADD KEY sql_area_group_idx (report_group, report_subgroup);");
5911
5912     print "Upgrade to $DBversion done saved_sql new fields report_group and report_area; authorised_values.category 16 char \n";
5913     SetVersion($DBversion);
5914 }
5915
5916 $DBversion = "3.09.00.051";
5917 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5918     $dbh->do("
5919         CREATE TABLE aqinvoices (
5920           invoiceid int(11) NOT NULL AUTO_INCREMENT,
5921           invoicenumber mediumtext NOT NULL,
5922           booksellerid int(11) NOT NULL,
5923           shipmentdate date default NULL,
5924           billingdate date default NULL,
5925           closedate date default NULL,
5926           shipmentcost decimal(28,6) default NULL,
5927           shipmentcost_budgetid int(11) default NULL,
5928           PRIMARY KEY (invoiceid),
5929           CONSTRAINT aqinvoices_fk_aqbooksellerid FOREIGN KEY (booksellerid) REFERENCES aqbooksellers (id) ON DELETE CASCADE ON UPDATE CASCADE,
5930           CONSTRAINT aqinvoices_fk_shipmentcost_budgetid FOREIGN KEY (shipmentcost_budgetid) REFERENCES aqbudgets (budget_id) ON DELETE SET NULL ON UPDATE CASCADE
5931         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5932     ");
5933
5934     # Fill this new table with existing invoices
5935     my $sth = $dbh->prepare("
5936         SELECT aqorders.booksellerinvoicenumber AS invoicenumber, aqbasket.booksellerid, aqorders.datereceived
5937         FROM aqorders
5938           LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
5939         WHERE aqorders.booksellerinvoicenumber IS NOT NULL
5940           AND aqorders.booksellerinvoicenumber != ''
5941         GROUP BY aqorders.booksellerinvoicenumber
5942     ");
5943     $sth->execute;
5944     my $results = $sth->fetchall_arrayref({});
5945     $sth = $dbh->prepare("
5946         INSERT INTO aqinvoices (invoicenumber, booksellerid, shipmentdate) VALUES (?,?,?)
5947     ");
5948     foreach(@$results) {
5949         $sth->execute($_->{invoicenumber}, $_->{booksellerid}, $_->{datereceived});
5950     }
5951
5952     # Add the column in aqorders, fill it with correct value
5953     # and then drop booksellerinvoicenumber column
5954     $dbh->do("
5955         ALTER TABLE aqorders
5956         ADD COLUMN invoiceid int(11) default NULL AFTER booksellerinvoicenumber,
5957         ADD CONSTRAINT aqorders_ibfk_3 FOREIGN KEY (invoiceid) REFERENCES aqinvoices (invoiceid) ON DELETE SET NULL ON UPDATE CASCADE
5958     ");
5959
5960     $dbh->do("
5961         UPDATE aqorders, aqinvoices
5962         SET aqorders.invoiceid = aqinvoices.invoiceid
5963         WHERE aqorders.booksellerinvoicenumber = aqinvoices.invoicenumber
5964     ");
5965
5966     $dbh->do("
5967         ALTER TABLE aqorders
5968         DROP COLUMN booksellerinvoicenumber
5969     ");
5970
5971     print "Upgrade to $DBversion done (Add aqinvoices table) \n";
5972     SetVersion ($DBversion);
5973 }
5974
5975 $DBversion = "3.09.00.052";
5976 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5977     $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');");
5978     $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');");
5979     $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');");
5980     print "Upgrade to $DBversion done (Add systempreferences to decrease loan length on high demand items decreaseLoanHighHolds, decreaseLoanHighHoldsValue and decreaseLoanHighHoldsDuration) \n";
5981     SetVersion ($DBversion);
5982 }
5983
5984 $DBversion = "3.09.00.053";
5985 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5986     $dbh->do(
5987     q|CREATE TABLE `import_auths` (
5988         import_record_id int(11) NOT NULL,
5989         matched_authid int(11) default NULL,
5990         control_number varchar(25) default NULL,
5991         authorized_heading varchar(128) default NULL,
5992         original_source varchar(25) default NULL,
5993         CONSTRAINT import_auths_ibfk_1 FOREIGN KEY (import_record_id)
5994         REFERENCES import_records (import_record_id) ON DELETE CASCADE ON UPDATE CASCADE,
5995         KEY matched_authid (matched_authid)
5996         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;|
5997     );
5998     $dbh->do("ALTER TABLE import_batches
5999                 CHANGE COLUMN num_biblios num_records int(11) NOT NULL default 0,
6000                 ADD COLUMN record_type enum('biblio', 'auth', 'holdings') NOT NULL default 'biblio'");
6001     $dbh->do("UPDATE import_batches SET record_type='auth' WHERE import_batch_id IN
6002                 (SELECT import_batch_id FROM import_records WHERE record_type='auth')");
6003
6004     print "Upgrade to $DBversion done (Added support for staging authorities)\n";
6005     SetVersion ($DBversion);
6006 }
6007
6008 $DBversion = "3.09.00.054";
6009 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6010     $dbh->do("ALTER TABLE aqorders CHANGE COLUMN gst gstrate DECIMAL(6,4)  DEFAULT NULL");
6011     print "Upgrade to $DBversion done (Change column name in aqorders gst --> gstrate)\n";
6012     SetVersion($DBversion);
6013 }
6014
6015 $DBversion = "3.09.00.055";
6016 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6017     $dbh->do("ALTER TABLE aqorders ADD discount float(6,4) DEFAULT NULL AFTER gstrate");
6018     print "Upgrade to $DBversion done (Add discount field in aqorders table)\n";
6019     SetVersion($DBversion);
6020 }
6021
6022 $DBversion ="3.09.00.056";
6023 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6024     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('AuthDisplayHierarchy','0','Display authority hierarchies','','YesNo')");
6025     print "Upgrade to $DBversion done (Add system preference AuthDisplayHierarchy)\n";
6026     SetVersion($DBversion);
6027 }
6028
6029 $DBversion = "3.09.00.057";
6030 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6031     $dbh->do("ALTER TABLE aqbasket ADD deliveryplace VARCHAR(10) default NULL AFTER basketgroupid;");
6032     $dbh->do("ALTER TABLE aqbasket ADD billingplace VARCHAR(10) default NULL AFTER deliveryplace;");
6033     print "Upgrade to $DBversion done (Bug 5356: Added billingplace, deliveryplace to the aqbasket table)\n";
6034     SetVersion($DBversion);
6035 }
6036
6037 $DBversion ="3.09.00.058";
6038 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6039     $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');");
6040     $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');");
6041     print "Upgrade to $DBversion done (Add Did You Mean? configuration)\n";
6042     SetVersion($DBversion);
6043 }
6044
6045 $DBversion ="3.09.00.059";
6046 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6047     $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');");
6048     print "Upgrade to $DBversion done (Add system preference BlockReturnOfWithdrawnItems)\n";
6049     SetVersion($DBversion);
6050 }
6051
6052 $DBversion = "3.09.00.060";
6053 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6054     $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')");
6055     print "Upgrade to $DBversion done (Added HoldsToPullStartDate syspref)\n";
6056     SetVersion($DBversion);
6057 }
6058
6059 $DBversion = "3.09.00.061";
6060 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6061     $dbh->do("UPDATE systempreferences set value=0 WHERE variable='OPACItemsResultsDisplay' AND value='statuses'");
6062     $dbh->do("UPDATE systempreferences set value=1 WHERE variable='OPACItemsResultsDisplay' AND value='itemdetails'");
6063     $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'");
6064     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";
6065     SetVersion ($DBversion);
6066 }
6067
6068 $DBversion = "3.09.00.062";
6069 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6070    $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='NoZebra'");
6071    $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='QueryRemoveStopwords'");
6072    print "Upgrade to $DBversion done (Disable obsolete NoZebra and QueryRemoveStopwords sysprefs)\n";
6073    SetVersion ($DBversion);
6074 }
6075
6076 $DBversion = "3.09.00.063";
6077 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6078     my $gst_booksellers = $dbh->selectcol_arrayref("SELECT DISTINCT(gstrate) FROM aqbooksellers");
6079     my $gist_syspref = C4::Context->preference("gist");
6080     # remove the undef values and construct and array with the syspref and the supplier values
6081     my @gstrates = map { defined $_ ? $_ : () } @$gst_booksellers;
6082     push @gstrates, split ('\|', $gist_syspref);
6083     # we want to compare integer (or float)
6084     $_ = $_ + 0 for @gstrates;
6085     use List::MoreUtils qw/uniq/;
6086     # remove duplicate values
6087     @gstrates = uniq sort @gstrates;
6088     my $new_syspref_value = join '|', @gstrates;
6089     # update the syspref with the new values
6090     my $sth = $dbh->prepare("UPDATE systempreferences set value=? WHERE variable='gist'");
6091     $sth->execute( $new_syspref_value );
6092
6093     print "Upgrade to $DBversion done (Bug 8832, Set the syspref gist with the existing values)\n";
6094     SetVersion ($DBversion);
6095 }
6096
6097 $DBversion = "3.09.00.064";
6098 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6099    $dbh->do('ALTER TABLE items ADD coded_location_qualifier varchar(10) default NULL AFTER itemcallnumber');
6100    print "Upgrade to $DBversion done (Bug 6428: Added coded_location_qualifier to the items table)\n";
6101    SetVersion ($DBversion);
6102 }
6103
6104 $DBversion = "3.09.00.065";
6105 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6106    $dbh->do('ALTER TABLE deleteditems ADD coded_location_qualifier varchar(10) default NULL AFTER itemcallnumber');
6107    print "Upgrade to $DBversion done (Bug 6428: Added coded_location_qualifier to the deleteditems table)\n";
6108    SetVersion ($DBversion);
6109 }
6110
6111 $DBversion = "3.09.00.066";
6112 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6113    $dbh->do("DELETE FROM systempreferences WHERE variable='DidYouMeanFromAuthorities'");
6114    print "Upgrade to $DBversion done (Bug 9107: remove DidYouMeanFromAuthorities syspref)\n";
6115    SetVersion ($DBversion);
6116 }
6117
6118 $DBversion = "3.09.00.067";
6119 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6120    $dbh->do("ALTER TABLE statistics CHANGE COLUMN ccode ccode varchar(10) NULL");
6121    print "Upgrade to $DBversion done (Bug 9064: statistics.ccode potentially wrongly defined)\n";
6122    SetVersion ($DBversion);
6123 }
6124
6125 $DBversion = "3.10.00.00";
6126 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6127    print "Upgrade to $DBversion done (release tag)\n";
6128    SetVersion ($DBversion);
6129 }
6130
6131 $DBversion = "3.11.00.001";
6132 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6133     $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')");
6134     print "Upgrade to $DBversion done (Bug 2832 - Add alphabet syspref)\n";
6135 }
6136
6137 $DBversion = "3.11.00.002";
6138 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6139     $dbh->do(q{
6140         DELETE from aqorders_items where ordernumber NOT IN (SELECT ordernumber FROM aqorders);
6141     });
6142     $dbh->do(q{
6143         ALTER TABLE aqorders_items
6144         ADD CONSTRAINT aqorders_items_ibfk_1 FOREIGN KEY (ordernumber) REFERENCES aqorders (ordernumber)
6145         ON DELETE CASCADE ON UPDATE CASCADE;
6146     });
6147     print "Upgrade to $DBversion done (Bug 9030: Add constraint on aqorders_items.ordernumber)\n";
6148     SetVersion ($DBversion);
6149 }
6150
6151 $DBversion = "3.11.00.003";
6152 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6153     $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')");
6154     print "Upgrade to $DBversion done (Bug 7189: Add system preference RefundLostItemFeeOnReturn)\n";
6155     SetVersion($DBversion);
6156 }
6157
6158 $DBversion = "3.11.00.004";
6159 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6160     $dbh->do(qq{
6161         ALTER TABLE subscription ADD COLUMN closed INT(1) NOT NULL DEFAULT 0 AFTER enddate;
6162     });
6163
6164     print "Upgrade to $DBversion done (Bug 8782: Add field subscription.closed)\n";
6165     SetVersion($DBversion);
6166 }
6167
6168 $DBversion = "3.11.00.005";
6169 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6170     $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;});
6171
6172     $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;});
6173
6174     $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;});
6175
6176     print "Upgrade to $DBversion done (Bug 7919: Display of values depending on the connexion library)\n";
6177     SetVersion($DBversion);
6178 }
6179
6180 $DBversion = "3.11.00.006";
6181 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6182     $dbh->do(q{
6183         UPDATE virtualshelves SET sortfield="copyrightdate" where sortfield="year";
6184     });
6185     print "Upgrade to $DBversion done (Bug 9167: Update the virtualshelves.sortfield column with 'copyrightdate' if needed)\n";
6186     SetVersion($DBversion);
6187 }
6188
6189 $DBversion = "3.11.00.007";
6190 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6191     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ar', 'language', 'de', 'Arabisch')");
6192     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hy', 'language', 'de', 'Armenisch')");
6193     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'bg', 'language', 'de', 'Bulgarisch')");
6194     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'zh', 'language', 'de', 'Chinesisch')");
6195     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'cs', 'language', 'de', 'Tschechisch')");
6196     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'da', 'language', 'de', 'Dänisch')");
6197     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nl', 'language', 'de', 'Niederländisch')");
6198     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'en', 'language', 'de', 'Englisch')");
6199     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fi', 'language', 'de', 'Finnisch')");
6200     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fr', 'language', 'de', 'Französisch')");
6201     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'lo', 'language', 'fr', 'Laotien')");
6202     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'lo', 'language', 'de', 'Laotisch')");
6203     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'el', 'language', 'de', 'Griechisch (Nach 1453)')");
6204     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'he', 'language', 'de', 'Hebräisch')");
6205     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hi', 'language', 'de', 'Hindi')");
6206     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hu', 'language', 'de', 'Ungarisch')");
6207     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'id', 'language', 'de', 'Indonesisch')");
6208     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'it', 'language', 'de', 'Italienisch')");
6209     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ja', 'language', 'de', 'Japanisch')");
6210     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ko', 'language', 'de', 'Koreanisch')");
6211     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'la', 'language', 'de', 'Latein')");
6212     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'gl', 'language', 'fr', 'Galicien')");
6213     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'gl', 'language', 'de', 'Galizisch')");
6214     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nb', 'language', 'de', 'Norwegisch bokm&#229;l')");
6215     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nn', 'language', 'de', 'Norwegisch nynorsk')");
6216     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fa', 'language', 'de', 'Persisch')");
6217     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'pl', 'language', 'de', 'Polnisch')");
6218     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'pt', 'language', 'de', 'Portugiesisch')");
6219     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ro', 'language', 'de', 'Rumänisch')");
6220     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ru', 'language', 'de', 'Russisch')");
6221     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sr', 'language', 'fr', 'Serbe')");
6222     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sr', 'language', 'de', 'Serbisch')");
6223     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'es', 'language', 'de', 'Spanisch')");
6224     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sv', 'language', 'de', 'Schwedisch')");
6225     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tet', 'language', 'fr', 'Tétoum')");
6226     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tet', 'language', 'de', 'Tetum')");
6227     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'th', 'language', 'de', 'Thailändisch')");
6228     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tr', 'language', 'de', 'Türkisch')");
6229     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'uk', 'language', 'de', 'Ukrainisch')");
6230     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ur', 'language', 'fr', 'Ourdou')");
6231     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ur', 'language', 'de', 'Urdu')");
6232     print "Upgrade to $DBversion done (Bug 9056: add German and a couple of French translations to language_descriptions)\n";
6233     SetVersion ($DBversion);
6234 }
6235
6236 $DBversion = "3.11.00.008";
6237 if (CheckVersion($DBversion)) {
6238     $dbh->do("
6239         CREATE TABLE IF NOT EXISTS `borrower_modifications` (
6240           `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6241           `verification_token` varchar(255) NOT NULL DEFAULT '',
6242           `borrowernumber` int(11) NOT NULL DEFAULT '0',
6243           `cardnumber` varchar(16) DEFAULT NULL,
6244           `surname` mediumtext,
6245           `firstname` text,
6246           `title` mediumtext,
6247           `othernames` mediumtext,
6248           `initials` text,
6249           `streetnumber` varchar(10) DEFAULT NULL,
6250           `streettype` varchar(50) DEFAULT NULL,
6251           `address` mediumtext,
6252           `address2` text,
6253           `city` mediumtext,
6254           `state` text,
6255           `zipcode` varchar(25) DEFAULT NULL,
6256           `country` text,
6257           `email` mediumtext,
6258           `phone` text,
6259           `mobile` varchar(50) DEFAULT NULL,
6260           `fax` mediumtext,
6261           `emailpro` text,
6262           `phonepro` text,
6263           `B_streetnumber` varchar(10) DEFAULT NULL,
6264           `B_streettype` varchar(50) DEFAULT NULL,
6265           `B_address` varchar(100) DEFAULT NULL,
6266           `B_address2` text,
6267           `B_city` mediumtext,
6268           `B_state` text,
6269           `B_zipcode` varchar(25) DEFAULT NULL,
6270           `B_country` text,
6271           `B_email` text,
6272           `B_phone` mediumtext,
6273           `dateofbirth` date DEFAULT NULL,
6274           `branchcode` varchar(10) DEFAULT NULL,
6275           `categorycode` varchar(10) DEFAULT NULL,
6276           `dateenrolled` date DEFAULT NULL,
6277           `dateexpiry` date DEFAULT NULL,
6278           `gonenoaddress` tinyint(1) DEFAULT NULL,
6279           `lost` tinyint(1) DEFAULT NULL,
6280           `debarred` date DEFAULT NULL,
6281           `debarredcomment` varchar(255) DEFAULT NULL,
6282           `contactname` mediumtext,
6283           `contactfirstname` text,
6284           `contacttitle` text,
6285           `guarantorid` int(11) DEFAULT NULL,
6286           `borrowernotes` mediumtext,
6287           `relationship` varchar(100) DEFAULT NULL,
6288           `ethnicity` varchar(50) DEFAULT NULL,
6289           `ethnotes` varchar(255) DEFAULT NULL,
6290           `sex` varchar(1) DEFAULT NULL,
6291           `password` varchar(30) DEFAULT NULL,
6292           `flags` int(11) DEFAULT NULL,
6293           `userid` varchar(75) DEFAULT NULL,
6294           `opacnote` mediumtext,
6295           `contactnote` varchar(255) DEFAULT NULL,
6296           `sort1` varchar(80) DEFAULT NULL,
6297           `sort2` varchar(80) DEFAULT NULL,
6298           `altcontactfirstname` varchar(255) DEFAULT NULL,
6299           `altcontactsurname` varchar(255) DEFAULT NULL,
6300           `altcontactaddress1` varchar(255) DEFAULT NULL,
6301           `altcontactaddress2` varchar(255) DEFAULT NULL,
6302           `altcontactaddress3` varchar(255) DEFAULT NULL,
6303           `altcontactstate` text,
6304           `altcontactzipcode` varchar(50) DEFAULT NULL,
6305           `altcontactcountry` text,
6306           `altcontactphone` varchar(50) DEFAULT NULL,
6307           `smsalertnumber` varchar(50) DEFAULT NULL,
6308           `privacy` int(11) DEFAULT NULL,
6309           PRIMARY KEY (`verification_token`,`borrowernumber`),
6310           KEY `verification_token` (`verification_token`),
6311           KEY `borrowernumber` (`borrowernumber`)
6312         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6313 ");
6314
6315     $dbh->do("
6316         INSERT INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES
6317         ('PatronSelfRegistration', '0', NULL, 'If enabled, patrons will be able to register themselves via the OPAC.', 'YesNo'),
6318         ('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'),
6319         ('PatronSelfRegistrationDefaultCategory', '', '', 'A patron registered via the OPAC will receive a borrower category code set in this system preference.', 'free'),
6320         ('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'),
6321         ('PatronSelfRegistrationBorrowerMandatoryField',  'surname|firstname', NULL ,  'Choose the mandatory fields for a patron''s account, when registering via the OPAC.',  'free'),
6322         ('PatronSelfRegistrationBorrowerUnwantedField',  '', NULL ,  'Name the fields you don''t want to display when registering a new patron via the OPAC.',  'free');
6323     ");
6324
6325     $dbh->do("
6326     INSERT INTO  letter ( `module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content` )
6327     VALUES ( 'members', 'OPAC_REG_VERIFY', '', 'Opac Self-Registration Verification Email', '1', 'Verify Your Account', 'Hello!
6328
6329     Your library account has been created. Please verify your email address by clicking this link to complete the signup process:
6330
6331     http://<<OPACBaseURL>>/cgi-bin/koha/opac-registration-verify.pl?token=<<borrower_modifications.verification_token>>
6332
6333     If you did not initiate this request, you may safely ignore this one-time message. The request will expire shortly.'
6334     )");
6335
6336     print "Upgrade to $DBversion done (Bug 7067: Add Patron Self Registration)\n";
6337     SetVersion ($DBversion);
6338 }
6339
6340 $DBversion = "3.11.00.009";
6341 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6342     $dbh->do("
6343         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
6344         ('SeparateHoldings', '0', 'Separate current branch holdings from other holdings', NULL, 'YesNo'),
6345         ('SeparateHoldingsBranch', 'homebranch', 'Branch used to separate holdings', 'homebranch|holdingbranch', 'Choice'),
6346         ('OpacSeparateHoldings', '0', 'Separate current branch holdings from other holdings (OPAC)', NULL, 'YesNo'),
6347         ('OpacSeparateHoldingsBranch', 'homebranch', 'Branch used to separate holdings (OPAC)', 'homebranch|holdingbranch', 'Choice')
6348     ");
6349
6350     print "Upgrade to $DBversion done (Bug 7674: Add systempreferences SeparateHoldings, SeparateHoldingsBranch, OpacSeparateHoldings and OpacSeparateHoldingsBranch) \n";
6351     SetVersion ($DBversion);
6352 }
6353
6354 $DBversion = "3.11.00.010";
6355 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6356     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('RenewalSendNotice', '0', '', NULL, 'YesNo')");
6357     $dbh->do(q{
6358         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
6359         ('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>>.');
6360     });
6361     print "Upgrade to $DBversion done (Bug 9151 - Renewal notice according to patron alert preferences)\n";
6362     SetVersion($DBversion);
6363 }
6364
6365 $DBversion = "3.11.00.011";
6366 if ( CheckVersion($DBversion) ) {
6367    $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');");
6368    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('HTML5MediaExtensions','webm|ogg|ogv|oga|vtt','Media file extensions','','free');");
6369    print "Upgrade to $DBversion done (Bug 8377: Add HTML5MediaEnabled and HTML5MediaExtensions sysprefs)\n";
6370    SetVersion ($DBversion);
6371 }
6372
6373 $DBversion = "3.11.00.012";
6374 if ( CheckVersion($DBversion) ) {
6375     $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')");
6376     print "Upgrade to $DBversion done (Bug 9206: Only allow place holds in records that the patron don't have in his possession)\n";
6377     SetVersion($DBversion);
6378 }
6379
6380 $DBversion = "3.11.00.013";
6381 if ( CheckVersion($DBversion) ) {
6382     $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')");
6383     print "Upgrade to $DBversion done (Bug 9162 - Add a system preference to set which notes fields appears on title notes/description separator)\n";
6384     SetVersion($DBversion);
6385 }
6386
6387 $DBversion = "3.11.00.014";
6388 if ( CheckVersion($DBversion) ) {
6389    $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' )");
6390    $dbh->do("INSERT INTO systempreferences ( variable, value, explanation, type ) VALUES ( 'SCOUserJS', '', 'Define custom javascript for inclusion in the SCO module', 'free' )");
6391    print "Upgrade to $DBversion done (Bug 9009: Add SCOUserCSS and SCOUserJS sysprefs)\n";
6392 }
6393
6394 $DBversion = "3.11.00.015";
6395 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6396     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('RentalsInNoissuesCharge', '1', 'Rental charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
6397     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('ManInvInNoissuesCharge', '1', 'MANUAL_INV charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
6398     print "Upgrade to $DBversion done (Add sysprefs RentalsInNoissuesCharge and ManInvInNoissuesCharge.)\n";
6399     SetVersion($DBversion);
6400 }
6401
6402 $DBversion = "3.11.00.016";
6403 if ( CheckVersion($DBversion) ) {
6404    $dbh->do(q{
6405         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";
6406         });
6407    $dbh->do(q{
6408         UPDATE userflags SET flagdesc="Edit Authorities" where flagdesc="Allow to edit authorities";
6409         });
6410    $dbh->do(q{
6411         UPDATE userflags SET flagdesc="Allow access to the reports module" where flagdesc="Allow to access to the reports module";
6412         });
6413    $dbh->do(q{
6414         UPDATE userflags SET flagdesc="Set library management parameters (deprecated)" where flagdesc="Set library management parameters";
6415         });
6416    $dbh->do(q{
6417         UPDATE userflags SET flagdesc="Manage serial subscriptions" where flagdesc="Allow to manage serials subscriptions";
6418         });
6419    $dbh->do(q{
6420         UPDATE userflags SET flagdesc="Manage patrons fines and fees" where flagdesc="Update borrower charges";
6421         });
6422    $dbh->do(q{
6423         UPDATE userflags SET flagdesc="Check out and check in items" where flagdesc="Circulate books";
6424         });
6425    $dbh->do(q{
6426         UPDATE userflags SET flagdesc="Manage Koha system settings (Administration panel)" where flagdesc="Set Koha system parameters";
6427         });
6428    $dbh->do(q{
6429         UPDATE userflags SET flagdesc="Add or modify patrons" where flagdesc="Add or modify borrowers";
6430         });
6431    $dbh->do(q{
6432         UPDATE userflags SET flagdesc="Use all tools (expand for granular tools permissions)" where flagdesc="Use tools (export, import, barcodes)";
6433         });
6434    $dbh->do(q{
6435         UPDATE userflags SET flagdesc="Allow staff members to modify permissions for other staff members" where flagdesc="Set user permissions";
6436         });
6437    $dbh->do(q{
6438         UPDATE permissions SET description="Perform batch modification of patrons" where description="Perform batch modifivation of patrons";
6439         });
6440
6441    print "Upgrade to $DBversion done (Bug 9382 (updated with bug 9745) - refresh permission descriptions to make more sense)\n";
6442    SetVersion ($DBversion);
6443 }
6444
6445 $DBversion ="3.11.00.017";
6446 if ( CheckVersion($DBversion) ) {
6447     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksReviews','0','Display book review snippets from IDreamBooks.com','','YesNo');");
6448     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksReadometer','0','Display Readometer from IDreamBooks.com','','YesNo');");
6449     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksResults','0','Display IDreamBooks.com rating in search results','','YesNo');");
6450     print "Upgrade to $DBversion done (Add IDreamBooks enhanced content)\n";
6451     SetVersion($DBversion);
6452 }
6453
6454 $DBversion = "3.11.00.018";
6455 if ( CheckVersion($DBversion) ) {
6456    $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')");
6457    $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')");
6458    print "Upgrade to $DBversion done (Bug 9395: Problem with callnumber and standard number search in OPAC and Staff Client)\n";
6459    SetVersion ($DBversion);
6460 }
6461
6462 $DBversion = "3.11.00.019";
6463 if ( CheckVersion($DBversion) ) {
6464     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('UNIMARCAuthorityField100', 'afrey50      ba0', NULL, NULL, 'Textarea')");
6465     print "Upgrade to $DBversion done (Bug 9145 - Add syspref UNIMARCAuthorityField100)\n";
6466     SetVersion ($DBversion);
6467 }
6468
6469 $DBversion = "3.11.00.020";
6470 if ( CheckVersion($DBversion) ) {
6471     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UNIMARCField100Language', 'fre','UNIMARC field 100 default language',NULL,'short')");
6472     print "Upgrade to $DBversion done (Bug 8347 - Koha forces UNIMARC 100 field code language to 'fre')\n";
6473     SetVersion($DBversion);
6474 }
6475
6476 $DBversion ="3.11.00.021";
6477 if ( CheckVersion($DBversion) ) {
6478     $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');");
6479     print "Upgrade to $DBversion done (Bug 5888 - Subject search pop-up for the OPAC)\n";
6480     SetVersion($DBversion);
6481 }
6482
6483 $DBversion = "3.11.00.022";
6484 if ( CheckVersion($DBversion) ) {
6485     $dbh->do(
6486 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('Persona',0,'Use Mozilla Persona for login','','YesNo')"
6487     );
6488     print "Upgrade to $DBversion done (Bug 9587 - Allow login via Persona)\n";
6489     SetVersion($DBversion);
6490 }
6491
6492 $DBversion = "3.11.00.023";
6493 if ( CheckVersion($DBversion) ) {
6494     $dbh->do("UPDATE z3950servers SET host = 'lx2.loc.gov', port = 210, db = 'LCDB', syntax = 'USMARC', encoding = 'utf8' WHERE name = 'LIBRARY OF CONGRESS'");
6495     print "Upgrade to $DBversion done (Bug 9520 - Update default LOC Z39.50 target)\n";
6496     SetVersion($DBversion);
6497 }
6498
6499 $DBversion = "3.11.00.024";
6500 if ( CheckVersion($DBversion) ) {
6501     $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');");
6502     print "Upgrade to $DBversion done (Bug 5079: Add OpacItemLocation syspref)\n";
6503     SetVersion ($DBversion);
6504 }
6505
6506 $DBversion = "3.11.00.025";
6507 if ( CheckVersion($DBversion) ) {
6508     $dbh->do(
6509         "CREATE TABLE linktracker (
6510   id int(11) NOT NULL AUTO_INCREMENT,
6511   biblionumber int(11) DEFAULT NULL,
6512   itemnumber int(11) DEFAULT NULL,
6513   borrowernumber int(11) DEFAULT NULL,
6514   url text,
6515   timeclicked datetime DEFAULT NULL,
6516   PRIMARY KEY (id),
6517   KEY bibidx (biblionumber),
6518   KEY itemidx (itemnumber),
6519   KEY borridx (borrowernumber),
6520   KEY dateidx (timeclicked)
6521     ) ENGINE=InnoDB DEFAULT CHARSET=utf8;"
6522     );
6523     $dbh->do( "
6524   INSERT INTO systempreferences (variable,value,explanation,options,type)
6525   VALUES('TrackClicks','0','Track links clicked',NULL,'Integer')" );
6526     print
6527 "Upgrade to $DBversion done (Adds feature Bug 8917, the ability to track links clicked)\n";
6528     SetVersion($DBversion);
6529 }
6530
6531 $DBversion = "3.11.00.026";
6532 if ( CheckVersion($DBversion) ) {
6533     $dbh->do(qq{
6534         ALTER TABLE import_records ADD INDEX batch_id_record_type ( import_batch_id, record_type );
6535     });
6536     print "Upgrade to $DBversion done (Bug 9207: Add new index batch_id_record_type to import_records)\n";
6537     SetVersion($DBversion);
6538 }
6539
6540 $DBversion = "3.11.00.027";
6541 if ( CheckVersion($DBversion) ) {
6542     $dbh->do(q{
6543         INSERT INTO permissions ( module_bit, code, description )
6544         VALUES  ( '1', 'overdues_report', 'Execute overdue items report' )
6545     });
6546     # add new permission for users with all report permissions and circulation remaining permission
6547     $dbh->do(q{
6548         INSERT INTO user_permissions (borrowernumber, module_bit, code)
6549         SELECT user_permissions.borrowernumber, 1, 'overdues_report'
6550         FROM user_permissions
6551         LEFT JOIN borrowers USING(borrowernumber)
6552         WHERE borrowers.flags & (1 << 16)
6553         AND user_permissions.code = 'circulate_remaining_permissions'
6554     });
6555     print "Upgrade to $DBversion done ( Add circ permission overdues_report )\n";
6556     SetVersion($DBversion);
6557 }
6558
6559 $DBversion = "3.11.00.028";
6560 if ( CheckVersion($DBversion) ) {
6561     $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'    );");
6562     print "Upgrade to $DBversion done (Bug 9756 - Patron self registration missing the system preference PatronSelfRegistrationAdditionalInstructions)\n";
6563     SetVersion($DBversion);
6564 }
6565
6566 $DBversion = "3.11.00.029";
6567 if (CheckVersion($DBversion)) {
6568     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UseQueryParser', '0', 'If enabled, try to use QueryParser for queries.', NULL, 'YesNo')");
6569     print "Upgrade to $DBversion done (Bug 9239: Make it possible for Koha to use QueryParser)\n";
6570     SetVersion ($DBversion);
6571 }
6572
6573 $DBversion = "3.11.00.030";
6574 if ( CheckVersion($DBversion) ) {
6575     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('FinesIncludeGracePeriod','1','If enabled, fines calculations will include the grace period.',NULL,'YesNo');");
6576     print "Upgrade to $DBversion done (Add system preference FinesIncludeGracePeriod)\n";
6577     SetVersion($DBversion);
6578 }
6579
6580 $DBversion = "3.11.00.100";
6581 if ( CheckVersion($DBversion) ) {
6582     print "Upgrade to $DBversion done (3.12-alpha release)\n";
6583     SetVersion ($DBversion);
6584 }
6585
6586 $DBversion = "3.11.00.101";
6587 if ( CheckVersion($DBversion) ) {
6588    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('UNIMARCAuthorsFacetsSeparator',', ', 'UNIMARC authors facets separator', NULL, 'short')");
6589    print "Upgrade to $DBversion done (Bug 9341: Problem with UNIMARC authors facets)\n";
6590    SetVersion ($DBversion);
6591 }
6592
6593 $DBversion = "3.11.00.102";
6594 if ( CheckVersion($DBversion) ) {
6595     $dbh->do(q{
6596         DELETE FROM systempreferences WHERE variable='NoZebra'
6597     });
6598     $dbh->do(q{
6599         DELETE FROM systempreferences WHERE variable='QueryRemoveStopwords'
6600     });
6601     print "Upgrade to $DBversion done (Remove deprecated NoZebra and QueryRemoveStopwords sysprefs)\n";
6602     SetVersion($DBversion);
6603 }
6604
6605 $DBversion = "3.11.00.103";
6606 if ( CheckVersion($DBversion) ) {
6607     $dbh->do("DELETE FROM systempreferences WHERE variable = 'insecure';");
6608     print "Upgrade to $DBversion done (Bug 9827 - Remove 'insecure' system preference)\n";
6609     SetVersion($DBversion);
6610 }
6611
6612 $DBversion = "3.11.00.104";
6613 if ( CheckVersion($DBversion) ) {
6614     print "Upgrade to $DBversion done (3.12-alpha2 release)\n";
6615     SetVersion ($DBversion);
6616 }
6617
6618 $DBversion = "3.11.00.105";
6619 if ( CheckVersion($DBversion) ) {
6620     if ( C4::Context->preference("marcflavour") eq 'MARC21' ) {
6621         $sth = $dbh->prepare(
6622 "SELECT frameworkcode FROM marc_tag_structure WHERE tagfield = '029'"
6623         );
6624         $sth->execute;
6625         my $frameworkcodes = $sth->fetchall_hashref('frameworkcode');
6626
6627         for my $frameworkcode ( keys %$frameworkcodes ) {
6628             $dbh->do( "
6629     INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian,
6630     libopac, repeatable, mandatory, kohafield, tab, authorised_value, authtypecode,
6631     value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
6632     ('029', 'a', 'OCLC library identifier', 'OCLC library identifier', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6633     ('029', 'b', 'System control number', 'System control number', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6634     ('029', 'c', 'OAI set name', 'OAI set name', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6635     ('029', 't', 'Content type identifier', 'Content type identifier', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL)
6636    " );
6637         }
6638
6639         for my $tag ( '863', '864', '865' ) {
6640             $sth = $dbh->prepare(
6641 "SELECT frameworkcode FROM marc_tag_structure WHERE tagfield = '$tag'"
6642             );
6643             $sth->execute;
6644             my $frameworkcodes = $sth->fetchall_hashref('frameworkcode');
6645
6646             for my $frameworkcode ( keys %$frameworkcodes ) {
6647                 $dbh->do( "
6648      INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian,
6649      libopac, repeatable, mandatory, kohafield, tab, authorised_value, authtypecode,
6650      value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
6651      ('$tag', '6', 'Linkage', 'Linkage', 0, 0, '', 8, '', '', '', NULL, 5, '$frameworkcode', '', '', NULL),
6652      ('$tag', '8', 'Field link and sequence number', 'Field link and sequence number', 0, 0, '', 8, '', '', '', NULL, 5, '$frameworkcode', '', '', NULL),
6653      ('$tag', 'a', 'First level of enumeration', 'First level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6654      ('$tag', 'b', 'Second level of enumeration', 'Second level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6655      ('$tag', 'c', 'Third level of enumeration', 'Third level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6656      ('$tag', 'd', 'Fourth level of enumeration', 'Fourth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6657      ('$tag', 'e', 'Fifth level of enumeration', 'Fifth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6658      ('$tag', 'f', 'Sixth level of enumeration', 'Sixth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6659      ('$tag', 'g', 'Alternative numbering scheme, first level of enumeration', 'Alternative numbering scheme, first level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6660      ('$tag', 'h', 'Alternative numbering scheme, second level of enumeration', 'Alternative numbering scheme, second level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6661      ('$tag', 'i', 'First level of chronology', 'First level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6662      ('$tag', 'j', 'Second level of chronology', 'Second level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6663      ('$tag', 'k', 'Third level of chronology', 'Third level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6664      ('$tag', 'l', 'Fourth level of chronology', 'Fourth level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6665      ('$tag', 'm', 'Alternative numbering scheme, chronology', 'Alternative numbering scheme, chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6666      ('$tag', 'n', 'Converted Gregorian year', 'Converted Gregorian year', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6667      ('$tag', 'o', 'Type of unit', 'Type of unit', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6668      ('$tag', 'p', 'Piece designation', 'Piece designation', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6669      ('$tag', 'q', 'Piece physical condition', 'Piece physical condition', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6670      ('$tag', 's', 'Copyright article-fee code', 'Copyright article-fee code', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6671      ('$tag', 't', 'Copy number', 'Copy number', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6672      ('$tag', 'v', 'Issuing date', 'Issuing date', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6673      ('$tag', 'w', 'Break indicator', 'Break indicator', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6674      ('$tag', 'x', 'Nonpublic note', 'Nonpublic note', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6675      ('$tag', 'z', 'Public note', 'Public note', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL)
6676     " );
6677             }
6678         }
6679     }
6680     print "Upgrade to $DBversion done (Bug 9353: Missing subfields on MARC21 frameworks)\n";
6681     SetVersion($DBversion);
6682 }
6683
6684
6685 $DBversion = "3.11.00.106";
6686 if ( CheckVersion($DBversion) ) {
6687     $dbh->do("INSERT INTO userflags (bit, flag, flagdesc, defaulton) VALUES ('19', 'plugins', 'Koha plugins', '0')");
6688     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
6689               ('19', 'manage', 'Manage plugins ( install / uninstall )'),
6690               ('19', 'tool', 'Use tool plugins'),
6691               ('19', 'report', 'Use report plugins'),
6692               ('19', 'configure', 'Configure plugins')
6693             ");
6694     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UseKohaPlugins','0','Enable or disable the ability to use Koha Plugins.','','YesNo')");
6695
6696     $dbh->do("
6697         CREATE TABLE IF NOT EXISTS plugin_data (
6698             plugin_class varchar(255) NOT NULL,
6699             plugin_key varchar(255) NOT NULL,
6700             plugin_value text,
6701             PRIMARY KEY (plugin_class,plugin_key)
6702         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6703     ");
6704
6705     print "Upgrade to $DBversion done (Bug 7804: Added plugin system.)\n";
6706     SetVersion($DBversion);
6707 }
6708
6709 $DBversion = "3.11.00.107";
6710 if ( CheckVersion($DBversion) ) {
6711    $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('TimeFormat','24hr','12hr|24hr','Defines the global time format for visual output.','Choice')");
6712    print "Upgrade to $DBversion done (Bug 9014: Add syspref TimeFormat)\n";
6713    SetVersion ($DBversion);
6714 }
6715
6716 $DBversion = "3.11.00.108";
6717 if ( CheckVersion($DBversion) ) {
6718     $dbh->do("ALTER TABLE action_logs CHANGE timestamp timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;");
6719     $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');");
6720     $dbh->do("ALTER TABLE action_logs CHANGE timestamp timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;");
6721     print "Upgrade to $DBversion done (Bug 7241: Fix on circulation logs)\n";
6722     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";
6723     SetVersion($DBversion);
6724 }
6725
6726 $DBversion = "3.11.00.109";
6727 if ( CheckVersion($DBversion) ) {
6728    $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');");
6729    print "Upgrade to $DBversion done (Bug 9403: Add DisplayIconsXSLT)\n";
6730    SetVersion ($DBversion);
6731 }
6732
6733 $DBversion = "3.11.00.110";
6734 if ( CheckVersion($DBversion) ) {
6735     $dbh->do("ALTER TABLE pending_offline_operations CHANGE barcode barcode VARCHAR( 20 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
6736     $dbh->do("ALTER TABLE pending_offline_operations ADD amount DECIMAL( 28, 6 ) NULL DEFAULT NULL");
6737     print "Upgrade to $DBversion done (Bug 8220 - Allow koc uploads to go to process queue)\n";
6738     SetVersion ($DBversion);
6739 }
6740
6741 $DBversion = "3.11.00.111";
6742 if ( CheckVersion($DBversion) ) {
6743     my $sth = $dbh->prepare("
6744         SELECT module, code, branchcode, content
6745         FROM letter
6746         WHERE content LIKE '%<fine>%'
6747     ");
6748     $sth->execute;
6749     my $sth_update = $dbh->prepare("UPDATE letter SET content = ? WHERE module = ? AND code = ? AND branchcode = ?");
6750     while(my $row = $sth->fetchrow_hashref){
6751         $row->{content} =~ s/<fine>\w+<\/fine>/<<items.fine>>/;
6752         $sth_update->execute($row->{content}, $row->{module}, $row->{code}, $row->{branchcode});
6753     }
6754     print "Upgrade to $DBversion done (use new <<items.fine>> syntax in notices)\n";
6755     SetVersion($DBversion);
6756 }
6757
6758 $DBversion = "3.11.00.112";
6759 if ( CheckVersion($DBversion) ) {
6760     $dbh->do(qq{
6761         ALTER TABLE issuingrules ADD COLUMN renewalperiod int(4) DEFAULT NULL AFTER renewalsallowed
6762     });
6763     $dbh->do(qq{
6764         UPDATE issuingrules SET renewalperiod = issuelength
6765     });
6766     print "Upgrade to $DBversion done (Bug 8365: Add colum issuingrules.renewalperiod)\n";
6767     SetVersion ($DBversion);
6768 }
6769
6770 $DBversion = "3.11.00.113";
6771 if ( CheckVersion($DBversion) ) {
6772     $dbh->do(q{
6773         ALTER TABLE branchcategories ADD show_in_pulldown BOOLEAN NOT NULL DEFAULT '0',
6774         ADD INDEX ( show_in_pulldown )
6775     });
6776     print "Upgrade to $DBversion done (Bug 9257 - Add groups to normal search pulldown)\n";
6777     SetVersion ($DBversion);
6778 }
6779
6780 $DBversion = "3.11.00.115";
6781 if ( CheckVersion($DBversion) ) {
6782     $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')");
6783     $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')");
6784     print "Upgrade to $DBversion done (Bug 7740: Add syspref HighlightOwnItemsOnOPAC)\n";
6785     SetVersion ($DBversion);
6786 }
6787
6788 $DBversion = "3.11.00.116";
6789 if ( CheckVersion($DBversion) ) {
6790     $dbh->do(q{ALTER TABLE aqorders DROP COLUMN serialid;});
6791     $dbh->do(q{ALTER TABLE aqorders DROP COLUMN subscription;});
6792     $dbh->do(q{ALTER TABLE aqorders ADD COLUMN subscriptionid INT(11) DEFAULT NULL;});
6793     $dbh->do(q{ALTER TABLE aqorders ADD CONSTRAINT aqorders_subscriptionid FOREIGN KEY (subscriptionid) REFERENCES subscription (subscriptionid) ON DELETE CASCADE ON UPDATE CASCADE;});
6794     $dbh->do(q{ALTER TABLE subscription ADD COLUMN reneweddate DATE DEFAULT NULL;});
6795     print "Upgrade to $DBversion done (Bug 5343: table aqorders: DROP serialid and subscription fields and ADD subscriptionid, table subscription: ADD reneweddate)\n";
6796     SetVersion ($DBversion);
6797 }
6798
6799 $DBversion = "3.11.00.200";
6800 if ( CheckVersion($DBversion) ) {
6801     print "Upgrade to $DBversion done (3.12-beta1 release)\n";
6802     SetVersion ($DBversion);
6803 }
6804
6805 $DBversion = "3.11.00.201";
6806 if ( CheckVersion($DBversion) ) {
6807     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'BIBSYS' AND host LIKE 'z3950.bibsys.no'");
6808     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'NORBOK' AND host LIKE 'z3950.nb.no'");
6809     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'SAMBOK' AND host LIKE 'z3950.nb.no'");
6810     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'DEICHMAN' AND host like 'z3950.deich.folkebibl.no'");
6811     print "Upgrade to $DBversion done (Bug 9498 - Update encoding for Norwegian sample Z39.50 servers)\n";
6812     SetVersion($DBversion);
6813 }
6814
6815 $DBversion = "3.11.00.202";
6816 if ( CheckVersion($DBversion) ) {
6817    $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ca', 'language', 'Catalan','2013-01-12' )");
6818    $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'ca','cat')");
6819    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'es', 'Catalán')");
6820    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'en', 'Catalan')");
6821    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'fr', 'Catalan')");
6822    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'ca', 'Català')");
6823    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'de', 'Katalanisch')");
6824    print "Upgrade to $DBversion done (Bug 9381: Add Catalan laguage)\n";
6825    SetVersion ($DBversion);
6826 }
6827
6828 $DBversion = "3.11.00.203";
6829 if ( CheckVersion($DBversion) ) {
6830     $dbh->do(q{ALTER TABLE suggestions CHANGE COLUMN title title VARCHAR(255) DEFAULT NULL;});
6831     print "Upgrade to $DBversion done (Bug 2046 - increasing title column length for suggestions)\n";
6832     SetVersion ($DBversion);
6833 }
6834
6835 $DBversion = "3.11.00.300";
6836 if ( CheckVersion($DBversion) ) {
6837     print "Upgrade to $DBversion done (3.12-beta3 release)\n";
6838     SetVersion ($DBversion);
6839 }
6840
6841 $DBversion = "3.11.00.301";
6842 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6843     #issues
6844     $dbh->do(q{
6845         ALTER TABLE `issues`
6846             ADD KEY `itemnumber_idx` (`itemnumber`),
6847             ADD KEY `branchcode_idx` (`branchcode`),
6848             ADD KEY `issuingbranch_idx` (`issuingbranch`)
6849     });
6850     $dbh->do(q{
6851         ALTER TABLE `old_issues`
6852             ADD KEY `branchcode_idx` (`branchcode`),
6853             ADD KEY `issuingbranch_idx` (`issuingbranch`)
6854     });
6855     #items
6856     $dbh->do(q{
6857         ALTER TABLE `items` ADD KEY `itype_idx` (`itype`)
6858     });
6859     $dbh->do(q{
6860         ALTER TABLE `deleteditems` ADD KEY `itype_idx` (`itype`)
6861     });
6862     # biblioitems
6863     $dbh->do(q{
6864         ALTER TABLE `biblioitems` ADD KEY `itemtype_idx` (`itemtype`)
6865     });
6866     $dbh->do(q{
6867         ALTER TABLE `deletedbiblioitems` ADD KEY `itemtype_idx` (`itemtype`)
6868     });
6869     # statistics
6870     $dbh->do(q{
6871         ALTER TABLE `statistics`
6872             ADD KEY `branch_idx` (`branch`),
6873             ADD KEY `proccode_idx` (`proccode`),
6874             ADD KEY `type_idx` (`type`),
6875             ADD KEY `usercode_idx` (`usercode`),
6876             ADD KEY `itemnumber_idx` (`itemnumber`),
6877             ADD KEY `itemtype_idx` (`itemtype`),
6878             ADD KEY `borrowernumber_idx` (`borrowernumber`),
6879             ADD KEY `associatedborrower_idx` (`associatedborrower`),
6880             ADD KEY `ccode_idx` (`ccode`)
6881     });
6882
6883     print "Upgrade to $DBversion done (Bug 9681: Add some database indexes)\n";
6884     SetVersion($DBversion);
6885 }
6886
6887 $DBversion = "3.12.00.000";
6888 if ( CheckVersion($DBversion) ) {
6889     print "Upgrade to $DBversion done (3.12.0 release)\n";
6890     SetVersion ($DBversion);
6891 }
6892
6893 $DBversion = '3.13.00.000';
6894 if ( CheckVersion($DBversion) ) {
6895     print "Upgrade to $DBversion done (start the journey to Koha Pi)\n";
6896     SetVersion ($DBversion);
6897 }
6898
6899 $DBversion = "3.13.00.001";
6900 if ( CheckVersion($DBversion) ) {
6901     $dbh->do("INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('UseCourseReserves', '0', NULL, 'Enable the course reserves feature.', 'YesNo')");
6902     $dbh->do("INSERT INTO userflags (bit,flag,flagdesc,defaulton) VALUES ('18','coursereserves','Course Reserves','0')");
6903     $dbh->do("
6904 CREATE TABLE `courses` (
6905   `course_id` int(11) NOT NULL AUTO_INCREMENT,
6906   `department` varchar(20) DEFAULT NULL,
6907   `course_number` varchar(255) DEFAULT NULL,
6908   `section` varchar(255) DEFAULT NULL,
6909   `course_name` varchar(255) DEFAULT NULL,
6910   `term` varchar(20) DEFAULT NULL,
6911   `staff_note` mediumtext,
6912   `public_note` mediumtext,
6913   `students_count` varchar(20) DEFAULT NULL,
6914   `enabled` enum('yes','no') NOT NULL DEFAULT 'yes',
6915   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6916    PRIMARY KEY (`course_id`)
6917 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6918     ");
6919
6920     $dbh->do("
6921 CREATE TABLE `course_instructors` (
6922   `course_id` int(11) NOT NULL,
6923   `borrowernumber` int(11) NOT NULL,
6924   PRIMARY KEY (`course_id`,`borrowernumber`),
6925   KEY `borrowernumber` (`borrowernumber`)
6926 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6927     ");
6928
6929     $dbh->do("
6930 ALTER TABLE `course_instructors`
6931   ADD CONSTRAINT `course_instructors_ibfk_2` FOREIGN KEY (`course_id`) REFERENCES `courses` (`course_id`),
6932   ADD CONSTRAINT `course_instructors_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE;
6933     ");
6934
6935     $dbh->do("
6936 CREATE TABLE `course_items` (
6937   `ci_id` int(11) NOT NULL AUTO_INCREMENT,
6938   `itemnumber` int(11) NOT NULL,
6939   `itype` varchar(10) DEFAULT NULL,
6940   `ccode` varchar(10) DEFAULT NULL,
6941   `holdingbranch` varchar(10) DEFAULT NULL,
6942   `location` varchar(80) DEFAULT NULL,
6943   `enabled` enum('yes','no') NOT NULL DEFAULT 'no',
6944   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6945    PRIMARY KEY (`ci_id`),
6946    UNIQUE KEY `itemnumber` (`itemnumber`),
6947    KEY `holdingbranch` (`holdingbranch`)
6948 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6949     ");
6950
6951     $dbh->do("
6952 ALTER TABLE `course_items`
6953   ADD CONSTRAINT `course_items_ibfk_2` FOREIGN KEY (`holdingbranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
6954   ADD CONSTRAINT `course_items_ibfk_1` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE;
6955 ");
6956
6957     $dbh->do("
6958 CREATE TABLE `course_reserves` (
6959   `cr_id` int(11) NOT NULL AUTO_INCREMENT,
6960   `course_id` int(11) NOT NULL,
6961   `ci_id` int(11) NOT NULL,
6962   `staff_note` mediumtext,
6963   `public_note` mediumtext,
6964   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6965    PRIMARY KEY (`cr_id`),
6966    UNIQUE KEY `pseudo_key` (`course_id`,`ci_id`),
6967    KEY `course_id` (`course_id`)
6968 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6969 ");
6970
6971     $dbh->do("
6972 ALTER TABLE `course_reserves`
6973   ADD CONSTRAINT `course_reserves_ibfk_1` FOREIGN KEY (`course_id`) REFERENCES `courses` (`course_id`);
6974     ");
6975
6976     $dbh->do("
6977 INSERT INTO permissions (module_bit, code, description) VALUES
6978   (18, 'manage_courses', 'Add, edit and delete courses'),
6979   (18, 'add_reserves', 'Add course reserves'),
6980   (18, 'delete_reserves', 'Remove course reserves')
6981 ;
6982     ");
6983
6984
6985     print "Upgrade to $DBversion done (Add Course Reserves ( system preference UseCourseReserves ))\n";
6986     SetVersion($DBversion);
6987 }
6988
6989 $DBversion = "3.13.00.002";
6990 if ( CheckVersion($DBversion) ) {
6991    $dbh->do("UPDATE systempreferences SET variable = 'IndependentBranches' WHERE variable = 'IndependantBranches'");
6992    print "Upgrade to $DBversion done (Bug 10080 - Change system pref IndependantBranches to IndependentBranches)\n";
6993    SetVersion ($DBversion);
6994 }
6995
6996 $DBversion = '3.13.00.003';
6997 if ( CheckVersion($DBversion) ) {
6998     $dbh->do("ALTER TABLE serial DROP itemnumber");
6999     print "Upgrade to $DBversion done (Bug 7718 - Remove itemnumber column from serials table)\n";
7000     SetVersion($DBversion);
7001 }
7002
7003 $DBversion = "3.13.00.004";
7004 if(CheckVersion($DBversion)) {
7005     $dbh->do(
7006 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacShowHoldNotes',0,'Show hold notes on OPAC','','YesNo')"
7007     );
7008     print "Upgrade to $DBversion done (Bug 9722: Allow users to add notes when placing a hold in OPAC)\n";
7009     SetVersion($DBversion);
7010 }
7011
7012 $DBversion = "3.13.00.005";
7013 if(CheckVersion($DBversion)) {
7014     my $intra= C4::Context->preference("intranetstylesheet");
7015     #if this pref is not blank or starting with http, https or / [root], then
7016     #add an additional / to the front
7017     if($intra && $intra !~ /^(\/|https?)/) {
7018         $dbh->do("UPDATE systempreferences SET value=? WHERE variable=?",
7019             undef,('/'.$intra,"intranetstylesheet"));
7020         print "WARNING: Your system preference intranetstylesheet has been prefixed with a slash to make it an absolute path.\n";
7021     }
7022     print "Upgrade to $DBversion done (Bug 10052: Make intranetstylesheet and intranetcolorstylesheet behave exactly like their opac counterparts)\n";
7023     SetVersion ($DBversion);
7024 }
7025
7026 $DBversion = "3.13.00.006";
7027 if ( CheckVersion($DBversion) ) {
7028     $dbh->do(q{
7029         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
7030         VALUES ('CalculateFinesOnReturn','1','Switch to control if overdue fines are calculated on return or not', '', 'YesNo')
7031     });
7032     print "Upgrade to $DBversion done (Bug 10120: Fines on item return controlled by a systempreference)\n";
7033     SetVersion($DBversion);
7034 }
7035
7036 $DBversion = "3.13.00.007";
7037 if ( CheckVersion($DBversion) ) {
7038     $dbh->do("UPDATE systempreferences SET variable='OpacHoldNotes' WHERE variable='OpacShowHoldNotes'");
7039     print "Upgrade to $DBversion done (Bug 10343: Rename OpacShowHoldNotes to OpacHoldNotes)\n";
7040     SetVersion($DBversion);
7041 }
7042
7043 $DBversion = "3.13.00.008";
7044 if ( CheckVersion($DBversion) ) {
7045     $dbh->do("
7046 CREATE TABLE IF NOT EXISTS borrower_files (
7047   file_id int(11) NOT NULL AUTO_INCREMENT,
7048   borrowernumber int(11) NOT NULL,
7049   file_name varchar(255) NOT NULL,
7050   file_type varchar(255) NOT NULL,
7051   file_description varchar(255) DEFAULT NULL,
7052   file_content longblob NOT NULL,
7053   date_uploaded timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
7054   PRIMARY KEY (file_id),
7055   KEY borrowernumber (borrowernumber),
7056   CONSTRAINT borrower_files_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
7057 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7058     ");
7059     print "Upgrade to $DBversion done (Bug 10443: make sure borrower_files table exists)\n";
7060     SetVersion($DBversion);
7061 }
7062
7063 $DBversion = "3.13.00.009";
7064 if ( CheckVersion($DBversion) ) {
7065     $dbh->do("ALTER TABLE aqorders DROP COLUMN biblioitemnumber");
7066     print "Upgrade to $DBversion done (Bug 9987 - Drop column aqorders.biblioitemnumber)\n";
7067     SetVersion($DBversion);
7068 }
7069
7070 $DBversion = "3.13.00.010";
7071 if ( CheckVersion($DBversion) ) {
7072     $dbh->do(
7073         q{
7074 INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AcqWarnOnDuplicateInvoice','0','Warn librarians when they try to create a duplicate invoice', '', 'YesNo');
7075 }
7076     );
7077     print
7078 "Upgrade to $DBversion done (Bug 10366 - Add system preference to enabling warning librarian when invoice is duplicated)\n";
7079     SetVersion($DBversion);
7080 }
7081
7082 $DBversion = "3.13.00.011";
7083 if ( CheckVersion($DBversion) ) {
7084     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='ita' WHERE rfc4646_subtag='it'");
7085     print "Upgrade to $DBversion done (Bug 9519: Wrong language code for Italian in the advanced search language limitations)\n";
7086     SetVersion($DBversion);
7087 }
7088
7089 $DBversion = "3.13.00.012";
7090 if ( CheckVersion($DBversion) ) {
7091     $dbh->do("ALTER TABLE issuingrules MODIFY COLUMN overduefinescap decimal(28,6) DEFAULT NULL;");
7092     print "Upgrade to $DBversion done (Bug 10490: Correct datatype for overduefinescap in issuingrules)\n";
7093     SetVersion($DBversion);
7094 }
7095
7096 $DBversion ="3.13.00.013";
7097 if ( CheckVersion($DBversion) ) {
7098     $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');");
7099     print "Upgrade to $DBversion done (Bug 9576: add AllowTooManyOverride syspref to enable or disable issue limit confirmation)\n";
7100     SetVersion($DBversion);
7101 }
7102
7103 $DBversion = "3.13.00.014";
7104 if ( CheckVersion($DBversion) ) {
7105     $dbh->do("ALTER TABLE courses MODIFY COLUMN department varchar(80) DEFAULT NULL;");
7106     $dbh->do("ALTER TABLE courses MODIFY COLUMN term       varchar(80) DEFAULT NULL;");
7107     print "Upgrade to $DBversion done (Bug 10604: correct width of courses.department and courses.term)\n";
7108     SetVersion($DBversion);
7109 }
7110
7111 $DBversion = "3.13.00.015";
7112 if ( CheckVersion($DBversion) ) {
7113     $dbh->do(
7114 "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')"
7115     );
7116     print "Upgrade to $DBversion done (Bug 7494: Add itemBarcodeFallbackSearch syspref)\n";
7117     SetVersion($DBversion);
7118 }
7119
7120 $DBversion = "3.13.00.016";
7121 if ( CheckVersion($DBversion) ) {
7122     $dbh->do(q{
7123         ALTER TABLE items CHANGE wthdrawn withdrawn TINYINT( 1 ) NOT NULL DEFAULT  '0'
7124     });
7125
7126     $dbh->do(q{
7127         ALTER TABLE deleteditems CHANGE wthdrawn withdrawn TINYINT( 1 ) NOT NULL DEFAULT  '0'
7128     });
7129
7130     $dbh->do(q{
7131         UPDATE saved_sql SET savedsql = REPLACE(savedsql, 'wthdrawn', 'withdrawn')
7132     });
7133
7134     $dbh->do(q{
7135         UPDATE marc_subfield_structure SET kohafield = 'items.withdrawn' WHERE kohafield = 'items.wthdrawn'
7136     });
7137
7138     print "Upgrade to $DBversion done (Bug 10550 - Fix database typo wthdrawn)\n";
7139     SetVersion($DBversion);
7140 }
7141
7142 $DBversion = "3.13.00.017";
7143 if ( CheckVersion($DBversion) ) {
7144     $dbh->do(
7145 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveClientKey','','Client key for OverDrive integration','30','Free')"
7146     );
7147     $dbh->do(
7148 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveClientSecret','','Client key for OverDrive integration','30','YesNo')"
7149     );
7150     $dbh->do(
7151 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveLibraryID','','Library ID for OverDrive integration','','Integer')"
7152     );
7153     print "Upgrade to $DBversion done (Bug 10320 - Show results from library's OverDrive collection in OPAC search)\n";
7154     SetVersion($DBversion);
7155 }
7156
7157 $DBversion = "3.13.00.018";
7158 if ( CheckVersion($DBversion) ) {
7159     $dbh->do(qq{DROP TABLE IF EXISTS aqorders_transfers;});
7160     $dbh->do(qq{
7161         CREATE TABLE aqorders_transfers (
7162           ordernumber_from int(11) NULL,
7163           ordernumber_to int(11) NULL,
7164           timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
7165           UNIQUE KEY ordernumber_from (ordernumber_from),
7166           UNIQUE KEY ordernumber_to (ordernumber_to),
7167           CONSTRAINT aqorders_transfers_ordernumber_from FOREIGN KEY (ordernumber_from) REFERENCES aqorders (ordernumber) ON DELETE SET NULL ON UPDATE CASCADE,
7168           CONSTRAINT aqorders_transfers_ordernumber_to FOREIGN KEY (ordernumber_to) REFERENCES aqorders (ordernumber) ON DELETE SET NULL ON UPDATE CASCADE
7169         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7170     });
7171     print "Upgrade to $DBversion done (Bug 5349: Add aqorders_transfers table)\n";
7172     SetVersion($DBversion);
7173 }
7174
7175 $DBversion = "3.13.00.019";
7176 if ( CheckVersion($DBversion) ) {
7177     $dbh->do("ALTER TABLE itemtypes ADD COLUMN checkinmsg VARCHAR(255) AFTER summary;");
7178     $dbh->do("ALTER TABLE itemtypes ADD COLUMN checkinmsgtype CHAR(16) DEFAULT 'message' NOT NULL AFTER checkinmsg;");
7179     print "Upgrade to $DBversion done (Bug 10513 - Light up a warning/message when returning a chosen item type)\n";
7180     SetVersion($DBversion);
7181 }
7182
7183 $DBversion = "3.13.00.020";
7184 if ( CheckVersion($DBversion) ) {
7185     $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')");
7186     $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')");
7187     print "Upgrade to $DBversion done (Bug 7639: system preferences to forgive fines on lost items)\n";
7188     SetVersion($DBversion);
7189 }
7190
7191 $DBversion ="3.13.00.021";
7192 if ( CheckVersion($DBversion) ) {
7193     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ConfirmFutureHolds','0','Number of days for confirming future holds','','Integer');");
7194     print "Upgrade to $DBversion done (Bug 9761: Add ConfirmFutureHolds pref)\n";
7195     SetVersion($DBversion);
7196 }
7197
7198 $DBversion = "3.13.00.022";
7199 if ( CheckVersion($DBversion) ) {
7200     $dbh->do("DELETE from auth_tag_structure WHERE tagfield IN ('68a','68b')");
7201     $dbh->do("DELETE from auth_subfield_structure WHERE tagfield IN ('68a','68b')");
7202     print "Upgrade to $DBversion done (Bug 10687 - Delete erroneous tags 68a and 68b on default MARC21 auth framework)\n";
7203     SetVersion($DBversion);
7204 }
7205
7206 $DBversion = "3.13.00.023";
7207 if ( CheckVersion($DBversion) ) {
7208     $dbh->do("ALTER TABLE borrowers CHANGE password password VARCHAR(60);");
7209     print "Upgrade to $DBversion done (Bug 9611 upgrading password storage system)\n";
7210     SetVersion($DBversion);
7211 }
7212
7213 $DBversion = "3.13.00.024";
7214 if ( CheckVersion($DBversion) ) {
7215     $dbh->do(q{ALTER TABLE z3950servers ADD COLUMN recordtype VARCHAR(45) NOT NULL DEFAULT 'biblio' AFTER description;});
7216     print "Upgrade to $DBversion done (Bug 10096 - Add a Z39.50 interface for authority searching)\n";
7217 }
7218
7219 $DBversion = "3.13.00.025";
7220 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
7221    $dbh->do("ALTER TABLE oai_sets_mappings ADD COLUMN operator varchar(8) NOT NULL default 'equal' AFTER marcsubfield;");
7222    print "Upgrade to $DBversion done (Bug 9295: OAI notequal: add operator column to OAI mappings table)\n";
7223    SetVersion ($DBversion);
7224 }
7225
7226 $DBversion = "3.13.00.026";
7227 if ( CheckVersion($DBversion) ) {
7228     $dbh->do(q|
7229         ALTER TABLE auth_subfield_structure ADD COLUMN defaultvalue TEXT DEFAULT NULL AFTER frameworkcode
7230     |);
7231     print "Upgrade to $DBversion done (Bug 10602: Add the column auth_subfield_structure.defaultvalue)\n";
7232     SetVersion($DBversion);
7233 }
7234
7235 $DBversion = "3.13.00.027";
7236 if ( CheckVersion($DBversion) ) {
7237     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('AllowOfflineCirculation','0','','If on, enables HTML5 offline circulation functionality.','YesNo')");
7238     print "Upgrade to $DBversion done (Bug 10240: Add syspref AllowOfflineCirculation)\n";
7239     SetVersion ($DBversion);
7240 }
7241
7242 $DBversion = "3.13.00.028";
7243 if ( CheckVersion($DBversion) ) {
7244     $dbh->do(q{
7245         ALTER TABLE export_format ADD type VARCHAR(255) DEFAULT 'marc' AFTER encoding
7246     });
7247     $dbh->do(q{
7248         ALTER TABLE export_format CHANGE marcfields content mediumtext NOT NULL
7249     });
7250     print "Upgrade to $DBversion done (Bug 10853: Add new field export_format.type and rename export_format.marcfields with export_format.content)\n";
7251     SetVersion($DBversion);
7252 }
7253
7254 $DBversion = "3.13.00.029";
7255 if ( CheckVersion($DBversion) ) {
7256     $dbh->do(q{
7257         INSERT IGNORE INTO export_format( profile, description, content, csv_separator, type )
7258         VALUES ( "issues to claim", "Default CSV export for serial issue claims",
7259                 "SUPPLIER=aqbooksellers.name|TITLE=subscription.title|ISSUE NUMBER=serial.serialseq|LATE SINCE=serial.planneddate",
7260                 ",", "sql" )
7261     });
7262     print "Upgrade to $DBversion done (Bug 10854: Add the default CSV profile for claiming issues)\n";
7263     SetVersion($DBversion);
7264 }
7265
7266 $DBversion = "3.13.00.030";
7267 if ( CheckVersion($DBversion) ) {
7268     $dbh->do(qq{
7269         DELETE FROM patronimage WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowers.cardnumber = patronimage.cardnumber)
7270     });
7271
7272     $dbh->do(qq{
7273         ALTER TABLE patronimage ADD borrowernumber INT( 11 ) NULL FIRST
7274     });
7275
7276     $dbh->{AutoCommit} = 0;
7277     $dbh->{RaiseError} = 1;
7278
7279     eval {
7280         $dbh->do(qq{
7281             UPDATE patronimage LEFT JOIN borrowers USING ( cardnumber ) SET patronimage.borrowernumber = borrowers.borrowernumber
7282         });
7283         $dbh->commit();
7284     };
7285
7286     if ($@) {
7287         print "Upgrade to $DBversion done (Bug 10636 - patronimage should have borrowernumber as PK, not cardnumber) failed! Transaction aborted because $@\n";
7288         eval { $dbh->rollback };
7289     }
7290     else {
7291         $dbh->do(qq{
7292             ALTER TABLE patronimage DROP FOREIGN KEY patronimage_fk1
7293         });
7294         $dbh->do(qq{
7295             ALTER TABLE patronimage DROP PRIMARY KEY, ADD PRIMARY KEY( borrowernumber )
7296         });
7297         $dbh->do(qq{
7298             ALTER TABLE patronimage DROP cardnumber
7299         });
7300         $dbh->do(qq{
7301             ALTER TABLE patronimage ADD FOREIGN KEY ( borrowernumber ) REFERENCES borrowers ( borrowernumber ) ON DELETE CASCADE ON UPDATE CASCADE
7302         });
7303
7304         print "Upgrade to $DBversion done (Bug 10636 - patronimage should have borrowernumber as PK, not cardnumber)\n";
7305         SetVersion($DBversion);
7306     }
7307
7308     $dbh->{AutoCommit} = 1;
7309     $dbh->{RaiseError} = 0;
7310 }
7311
7312 $DBversion = "3.13.00.031";
7313 if ( CheckVersion($DBversion) ) {
7314
7315     $dbh->do(q{
7316         CREATE TABLE IF NOT EXISTS `patron_lists` (
7317           patron_list_id int(11) NOT NULL AUTO_INCREMENT,
7318           name varchar(255) CHARACTER SET utf8 NOT NULL,
7319           owner int(11) NOT NULL,
7320           PRIMARY KEY (patron_list_id),
7321           KEY owner (owner)
7322         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7323     });
7324
7325     $dbh->do(q{
7326         ALTER TABLE `patron_lists`
7327           ADD CONSTRAINT patron_lists_ibfk_1 FOREIGN KEY (`owner`) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE;
7328     });
7329
7330     $dbh->do(q{
7331         CREATE TABLE patron_list_patrons (
7332           patron_list_patron_id int(11) NOT NULL AUTO_INCREMENT,
7333           patron_list_id int(11) NOT NULL,
7334           borrowernumber int(11) NOT NULL,
7335           PRIMARY KEY (patron_list_patron_id),
7336           KEY patron_list_id (patron_list_id),
7337           KEY borrowernumber (borrowernumber)
7338         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7339     });
7340
7341     $dbh->do(q{
7342         ALTER TABLE `patron_list_patrons`
7343           ADD CONSTRAINT patron_list_patrons_ibfk_1 FOREIGN KEY (patron_list_id) REFERENCES patron_lists (patron_list_id) ON DELETE CASCADE ON UPDATE CASCADE,
7344           ADD CONSTRAINT patron_list_patrons_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE;
7345     });
7346
7347     $dbh->do(q{
7348         INSERT INTO permissions (module_bit, code, description) VALUES
7349         (13, 'manage_patron_lists', 'Add, edit and delete patron lists and their contents')
7350     });
7351
7352     print "Upgrade to $DBversion done (Bug 10565 - Add a 'Patron List' feature for storing and manipulating collections of patrons)\n";
7353     SetVersion($DBversion);
7354 }
7355
7356 $DBversion = "3.13.00.032";
7357 if ( CheckVersion($DBversion) ) {
7358     $dbh->do("ALTER TABLE aqorders ADD COLUMN orderstatus varchar(16) DEFAULT 'new' AFTER parent_ordernumber");
7359     $dbh->do("UPDATE aqorders SET orderstatus='ordered' WHERE basketno IN (SELECT basketno FROM aqbasket WHERE closedate IS NOT NULL)");
7360     $dbh->do(q{
7361         UPDATE aqorders SET orderstatus='partial'
7362         WHERE quantity > quantityreceived
7363         AND quantityreceived > 0
7364         AND ordernumber IN (
7365             SELECT parent_ordernumber
7366             FROM (
7367                 SELECT DISTINCT(parent_ordernumber)
7368                 FROM aqorders
7369                 WHERE ordernumber != parent_ordernumber
7370             ) AS aq
7371         )
7372         AND basketno IN (SELECT basketno FROM aqbasket WHERE closedate IS NOT NULL)
7373     });
7374     $dbh->do("UPDATE aqorders SET orderstatus='complete' WHERE quantity=quantityreceived");
7375     $dbh->do("UPDATE aqorders SET orderstatus='cancelled' WHERE datecancellationprinted IS NOT NULL");
7376     print "Upgrade to $DBversion done (Bug 5336: Add the new column aqorders.orderstatus)\n";
7377     SetVersion($DBversion);
7378 }
7379
7380 $DBversion = "3.13.00.033";
7381 if ( CheckVersion($DBversion) ) {
7382     $dbh->do(qq|
7383         DROP TABLE IF EXISTS subscription_frequencies
7384     |);
7385     $dbh->do(qq|
7386         CREATE TABLE subscription_frequencies (
7387             id INTEGER NOT NULL AUTO_INCREMENT,
7388             description TEXT NOT NULL,
7389             displayorder INT DEFAULT NULL,
7390             unit ENUM('day','week','month','year') DEFAULT NULL,
7391             unitsperissue INTEGER NOT NULL DEFAULT '1',
7392             issuesperunit INTEGER NOT NULL DEFAULT '1',
7393             PRIMARY KEY (id)
7394         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
7395     |);
7396
7397     $dbh->do(qq|
7398         DROP TABLE IF EXISTS subscription_numberpatterns
7399     |);
7400     $dbh->do(qq|
7401         CREATE TABLE subscription_numberpatterns (
7402             id INTEGER NOT NULL AUTO_INCREMENT,
7403             label VARCHAR(255) NOT NULL,
7404             displayorder INTEGER DEFAULT NULL,
7405             description TEXT NOT NULL,
7406             numberingmethod VARCHAR(255) NOT NULL,
7407             label1 VARCHAR(255) DEFAULT NULL,
7408             add1 INTEGER DEFAULT NULL,
7409             every1 INTEGER DEFAULT NULL,
7410             whenmorethan1 INTEGER DEFAULT NULL,
7411             setto1 INTEGER DEFAULT NULL,
7412             numbering1 VARCHAR(255) DEFAULT NULL,
7413             label2 VARCHAR(255) DEFAULT NULL,
7414             add2 INTEGER DEFAULT NULL,
7415             every2 INTEGER DEFAULT NULL,
7416             whenmorethan2 INTEGER DEFAULT NULL,
7417             setto2 INTEGER DEFAULT NULL,
7418             numbering2 VARCHAR(255) DEFAULT NULL,
7419             label3 VARCHAR(255) DEFAULT NULL,
7420             add3 INTEGER DEFAULT NULL,
7421             every3 INTEGER DEFAULT NULL,
7422             whenmorethan3 INTEGER DEFAULT NULL,
7423             setto3 INTEGER DEFAULT NULL,
7424             numbering3 VARCHAR(255) DEFAULT NULL,
7425             PRIMARY KEY (id)
7426         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
7427     |);
7428
7429     $dbh->do(qq|
7430         INSERT INTO subscription_frequencies (description, unit, unitsperissue, issuesperunit, displayorder)
7431         VALUES
7432             ('2/day', 'day', 1, 2, 1),
7433             ('1/day', 'day', 1, 1, 2),
7434             ('3/week', 'week', 1, 3, 3),
7435             ('1/week', 'week', 1, 1, 4),
7436             ('1/2 weeks', 'week', 2, 1, 5),
7437             ('1/3 weeks', 'week', 3, 1, 6),
7438             ('1/month', 'month', 1, 1, 7),
7439             ('1/2 months', 'month', 2, 1, 8),
7440             ('1/3 months', 'month', 3, 1, 9),
7441             ('2/year', 'month', 6, 1, 10),
7442             ('1/year', 'year', 1, 1, 11),
7443             ('1/2 year', 'year', 2, 1, 12),
7444             ('Irregular', NULL, 1, 1, 13)
7445     |);
7446
7447     # Used to link existing subscription to newly created frequencies
7448     my $frequencies_mapping = {     # keys are old frequency numbers, values are the new ones
7449         1 => 2,     # daily (n/week)
7450         2 => 4,     # 1/week
7451         3 => 5,     # 1/2 weeks
7452         4 => 6,     # 1/3 weeks
7453         5 => 7,     # 1/month
7454         6 => 8,     # 1/2 months (6/year)
7455         7 => 9,     # 1/3 months (1/quarter)
7456         8 => 9,    # 1/quarter (seasonal)
7457         9 => 10,    # 2/year
7458         10 => 11,   # 1/year
7459         11 => 12,   # 1/2 years
7460         12 => 1,    # 2/day
7461         16 => 13,   # Without periodicity
7462         32 => 13,   # Irregular
7463         48 => 13    # Unknown
7464     };
7465
7466     $dbh->do(qq|
7467         INSERT INTO subscription_numberpatterns
7468             (label, displayorder, description, numberingmethod,
7469             label1, add1, every1, whenmorethan1, setto1, numbering1,
7470             label2, add2, every2, whenmorethan2, setto2, numbering2,
7471             label3, add3, every3, whenmorethan3, setto3, numbering3)
7472         VALUES
7473             ('Number', 1, 'Simple Numbering method', 'No.{X}',
7474             'Number', 1, 1, 99999, 1, NULL,
7475             NULL, NULL, NULL, NULL, NULL, NULL,
7476             NULL, NULL, NULL, NULL, NULL, NULL),
7477
7478             ('Volume, Number, Issue', 2, 'Volume Number Issue 1', 'Vol.{X}, Number {Y}, Issue {Z}',
7479             'Volume', 1, 48, 99999, 1, NULL,
7480             'Number', 1, 4, 12, 1, NULL,
7481             'Issue', 1, 1, 4, 1, NULL),
7482
7483             ('Volume, Number', 3, 'Volume Number 1', 'Vol {X}, No {Y}',
7484             'Volume', 1, 12, 99999, 1, NULL,
7485             'Number', 1, 1, 12, 1, NULL,
7486             NULL, NULL, NULL, NULL, NULL, NULL),
7487
7488             ('Seasonal', 4, 'Season Year', '{X} {Y}',
7489             'Season', 1, 1, 3, 0, 'season',
7490             'Year', 1, 4, 99999, 1, NULL,
7491             NULL, NULL, NULL, NULL, NULL, NULL)
7492     |);
7493
7494     $dbh->do(qq|
7495         ALTER TABLE subscription
7496         MODIFY COLUMN numberpattern INTEGER DEFAULT NULL,
7497         MODIFY COLUMN periodicity INTEGER DEFAULT NULL
7498     |);
7499
7500     # Update existing subscriptions
7501
7502     my $query = qq|
7503         SELECT subscriptionid, periodicity, numberingmethod,
7504             add1, every1, whenmorethan1, setto1,
7505             add2, every2, whenmorethan2, setto2,
7506             add3, every3, whenmorethan3, setto3
7507         FROM subscription
7508         ORDER BY subscriptionid
7509     |;
7510     my $sth = $dbh->prepare($query);
7511     $sth->execute;
7512     my $insert_numberpatterns_sth = $dbh->prepare(qq|
7513         INSERT INTO subscription_numberpatterns
7514              (label, displayorder, description, numberingmethod,
7515             label1, add1, every1, whenmorethan1, setto1, numbering1,
7516             label2, add2, every2, whenmorethan2, setto2, numbering2,
7517             label3, add3, every3, whenmorethan3, setto3, numbering3)
7518         VALUES
7519             (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
7520     |);
7521     my $check_numberpatterns_sth = $dbh->prepare(qq|
7522         SELECT * FROM subscription_numberpatterns
7523         WHERE (add1 = ? OR (add1 IS NULL AND ? IS NULL)) AND (add2 = ? OR (add2 IS NULL AND ? IS NULL))
7524         AND (add3 = ? OR (add3 IS NULL AND ? IS NULL)) AND (every1 = ? OR (every1 IS NULL AND ? IS NULL))
7525         AND (every2 = ? OR (every2 IS NULL AND ? IS NULL)) AND (every3 = ? OR (every3 IS NULL AND ? IS NULL))
7526         AND (whenmorethan1 = ? OR (whenmorethan1 IS NULL AND ? IS NULL)) AND (whenmorethan2 = ? OR (whenmorethan2 IS NULL AND ? IS NULL))
7527         AND (whenmorethan3 = ? OR (whenmorethan3 IS NULL AND ? IS NULL)) AND (setto1 = ? OR (setto1 IS NULL AND ? IS NULL))
7528         AND (setto2 = ? OR (setto2 IS NULL AND ? IS NULL)) AND (setto3 = ? OR (setto3 IS NULL AND ? IS NULL))
7529         AND (numberingmethod = ? OR (numberingmethod IS NULL AND ? IS NULL))
7530         LIMIT 1
7531     |);
7532     my $update_subscription_sth = $dbh->prepare(qq|
7533         UPDATE subscription
7534         SET numberpattern = ?,
7535             periodicity = ?
7536         WHERE subscriptionid = ?
7537     |);
7538
7539     my $i = 1;
7540     while(my $sub = $sth->fetchrow_hashref) {
7541         $check_numberpatterns_sth->execute(
7542             $sub->{add1}, $sub->{add1}, $sub->{add2}, $sub->{add2}, $sub->{add3}, $sub->{add3},
7543             $sub->{every1}, $sub->{every1}, $sub->{every2}, $sub->{every2}, $sub->{every3}, $sub->{every3},
7544             $sub->{whenmorethan1}, $sub->{whenmorethan1}, $sub->{whenmorethan2}, $sub->{whenmorethan2},
7545             $sub->{whenmorethan3}, $sub->{whenmorethan3}, $sub->{setto1}, $sub->{setto1}, $sub->{setto2},
7546             $sub->{setto2}, $sub->{setto3}, $sub->{setto3}, $sub->{numberingmethod}, $sub->{numberingmethod}
7547         );
7548         my $p = $check_numberpatterns_sth->fetchrow_hashref;
7549         if (defined $p) {
7550             # Pattern already exists, link to it
7551             $update_subscription_sth->execute($p->{id},
7552                 $frequencies_mapping->{$sub->{periodicity}},
7553                 $sub->{subscriptionid});
7554         } else {
7555             # Create a new numbering pattern for this subscription
7556             my $ok = $insert_numberpatterns_sth->execute(
7557                 "Backup pattern $i", 4+$i, "Automatically created pattern by updatedatabase", $sub->{numberingmethod},
7558                 "X", $sub->{add1}, $sub->{every1}, $sub->{whenmorethan1}, $sub->{setto1}, undef,
7559                 "Y", $sub->{add2}, $sub->{every2}, $sub->{whenmorethan2}, $sub->{setto2}, undef,
7560                 "Z", $sub->{add3}, $sub->{every3}, $sub->{whenmorethan3}, $sub->{setto3}, undef
7561             );
7562             if($ok) {
7563                 my $id = $dbh->last_insert_id(undef, undef, 'subscription_numberpatterns', undef);
7564                 # Link to subscription_numberpatterns and subscription_frequencies
7565                 $update_subscription_sth->execute($id,
7566                     $frequencies_mapping->{$sub->{periodicity}},
7567                     $sub->{subscriptionid});
7568             }
7569             $i++;
7570         }
7571     }
7572
7573     # Remove now useless columns
7574     $dbh->do(qq|
7575         ALTER TABLE subscription
7576         DROP COLUMN numberingmethod,
7577         DROP COLUMN add1,
7578         DROP COLUMN every1,
7579         DROP COLUMN whenmorethan1,
7580         DROP COLUMN setto1,
7581         DROP COLUMN add2,
7582         DROP COLUMN every2,
7583         DROP COLUMN whenmorethan2,
7584         DROP COLUMN setto2,
7585         DROP COLUMN add3,
7586         DROP COLUMN every3,
7587         DROP COLUMN whenmorethan3,
7588         DROP COLUMN setto3,
7589         DROP COLUMN dow,
7590         DROP COLUMN issuesatonce,
7591         DROP COLUMN hemisphere,
7592         ADD COLUMN countissuesperunit INTEGER NOT NULL DEFAULT 1 AFTER periodicity,
7593         ADD COLUMN skip_serialseq BOOLEAN NOT NULL DEFAULT 0 AFTER irregularity,
7594         ADD COLUMN locale VARCHAR(80) DEFAULT NULL AFTER numberpattern,
7595         ADD CONSTRAINT subscription_ibfk_1 FOREIGN KEY (periodicity) REFERENCES subscription_frequencies (id) ON DELETE SET NULL ON UPDATE CASCADE,
7596         ADD CONSTRAINT subscription_ibfk_2 FOREIGN KEY (numberpattern) REFERENCES subscription_numberpatterns (id) ON DELETE SET NULL ON UPDATE CASCADE
7597     |);
7598
7599     # Set firstacquidate if not already set (firstacquidate is now mandatory)
7600     my $get_first_planneddate_sth = $dbh->prepare(qq|
7601         SELECT planneddate
7602         FROM serial
7603         WHERE subscriptionid = ?
7604         ORDER BY serialid
7605         LIMIT 1
7606     |);
7607     my $update_firstacquidate_sth = $dbh->prepare(qq|
7608         UPDATE subscription
7609         SET firstacquidate = ?
7610         WHERE subscriptionid = ?
7611     |);
7612
7613     sanitize_zero_date('subscription', 'firstacquidate');
7614     my $get_subscriptions_sth = $dbh->prepare(qq|
7615         SELECT subscriptionid, startdate
7616         FROM subscription
7617         WHERE firstacquidate IS NULL
7618           OR firstacquidate = '0000-00-00'
7619     |);
7620     $get_subscriptions_sth->execute;
7621     while ( my ($subscriptionid, $startdate) = $get_subscriptions_sth->fetchrow ) {
7622         # Try to get the planned date of the first serial
7623         $get_first_planneddate_sth->execute($subscriptionid);
7624         my ($first_planneddate) = $get_first_planneddate_sth->fetchrow;
7625         if ($first_planneddate and $first_planneddate =~ /^\d{4}-\d{2}-\d{2}$/) {
7626             $update_firstacquidate_sth->execute($first_planneddate, $subscriptionid);
7627         } else {
7628             # Defaults to subscription start date
7629             $update_firstacquidate_sth->execute($startdate, $subscriptionid);
7630         }
7631     }
7632
7633     print "Upgrade to $DBversion done (Bug 7688: add subscription_frequencies and subscription_numberpatterns tables)\n";
7634     SetVersion($DBversion);
7635 }
7636
7637 $DBversion = "3.13.00.034";
7638 if ( CheckVersion($DBversion) ) {
7639     $dbh->do("
7640         ALTER TABLE `import_batches`
7641         CHANGE `item_action` `item_action`
7642           ENUM( 'always_add', 'add_only_for_matches', 'add_only_for_new', 'ignore', 'replace' )
7643           NOT NULL DEFAULT 'always_add'
7644     ");
7645     print "Upgrade to $DBversion done (Bug 7131 - way to overlay items in in marc import)\n";
7646     SetVersion($DBversion);
7647 }
7648
7649 $DBversion ="3.13.00.035";
7650 if ( CheckVersion($DBversion) ) {
7651     $dbh->do(q{
7652 CREATE TABLE borrower_debarments (
7653   borrower_debarment_id int(11) NOT NULL AUTO_INCREMENT,
7654   borrowernumber int(11) NOT NULL,
7655   expiration date DEFAULT NULL,
7656   `type` enum('SUSPENSION','OVERDUES','MANUAL') NOT NULL DEFAULT 'MANUAL',
7657   `comment` text,
7658   manager_id int(11) DEFAULT NULL,
7659   created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
7660   updated timestamp NULL DEFAULT NULL,
7661   PRIMARY KEY (borrower_debarment_id),
7662   KEY borrowernumber (borrowernumber) ,
7663   CONSTRAINT `borrower_debarments_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
7664     ON DELETE CASCADE ON UPDATE CASCADE
7665 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7666     });
7667
7668     # debarments with end date
7669     $dbh->do(q{
7670 INSERT INTO borrower_debarments ( borrowernumber, expiration, comment ) SELECT borrowernumber, debarred, debarredcomment FROM borrowers WHERE debarred IS NOT NULL AND debarred <> '9999-12-31'
7671     });
7672     # debarments with no end date
7673     $dbh->do(q{
7674 INSERT INTO borrower_debarments ( borrowernumber, comment ) SELECT borrowernumber, debarredcomment FROM borrowers WHERE debarred = '9999-12-31'
7675     });
7676
7677     $dbh->do(q{
7678 INSERT IGNORE INTO systempreferences (variable,value,explanation,type) VALUES
7679 ('AutoRemoveOverduesRestrictions','0','Defines whether an OVERDUES debarment should be lifted automatically if all overdue items are returned by the patron.','YesNo')
7680     });
7681
7682     print "Upgrade to $DBversion done (Bug 2720 - Overdues which debar automatically should undebar automatically when returned)\n";
7683     SetVersion($DBversion);
7684 }
7685
7686 $DBversion = "3.13.00.036";
7687 if ( CheckVersion($DBversion) ) {
7688     $dbh->do(qq{
7689         INSERT INTO systempreferences (variable, value, explanation, options, type)
7690         VALUES ('StaffDetailItemSelection', '1', 'Enable item selection in record detail page', NULL, 'YesNo')
7691     });
7692     print "Upgrade to $DBversion done (Add system preference StaffDetailItemSelection)\n";
7693     SetVersion($DBversion);
7694 }
7695
7696 $DBversion = "3.13.00.037";
7697 if ( CheckVersion($DBversion) ) {
7698     #add phone if it is not there already (explains the ignore option)
7699     $dbh->do("
7700 INSERT IGNORE INTO message_transport_types (message_transport_type) values ('phone');
7701     ");
7702     print "Upgrade to $DBversion done (Bug 10572: Add phone to message_transport_types table for new installs)\n";
7703     SetVersion($DBversion);
7704 }
7705
7706 $DBversion = "3.13.00.038";
7707 if ( CheckVersion($DBversion) ) {
7708     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES(15, 'superserials', 'Manage subscriptions from any branch (only applies when IndependentBranches is used)')");
7709     print "Upgrade to $DBversion done (Bug 8435: Add superserials permission)\n";
7710     SetVersion($DBversion);
7711 }
7712
7713 $DBversion = "3.13.00.039";
7714 if ( CheckVersion($DBversion) ) {
7715     $dbh->do("
7716         ALTER TABLE aqbasket ADD branch varchar(10) default NULL
7717     ");
7718     $dbh->do("
7719         ALTER TABLE aqbasket
7720         ADD CONSTRAINT aqbasket_ibfk_4 FOREIGN KEY (branch)
7721             REFERENCES branches (branchcode)
7722             ON UPDATE CASCADE ON DELETE SET NULL
7723     ");
7724     $dbh->do("
7725         DROP TABLE IF EXISTS aqbasketusers
7726     ");
7727     $dbh->do("
7728         CREATE TABLE aqbasketusers (
7729             basketno int(11) NOT NULL,
7730             borrowernumber int(11) NOT NULL,
7731             PRIMARY KEY (basketno,borrowernumber),
7732             CONSTRAINT aqbasketusers_ibfk_1 FOREIGN KEY (basketno) REFERENCES aqbasket (basketno) ON DELETE CASCADE ON UPDATE CASCADE,
7733             CONSTRAINT aqbasketusers_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
7734         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7735     ");
7736     $dbh->do("
7737         INSERT INTO permissions (module_bit, code, description)
7738         VALUES (11, 'order_manage_all', 'Manage all orders and baskets, regardless of restrictions on them')
7739     ");
7740
7741     print "Upgrade to $DBversion done (Add branch and users list to baskets. "
7742         . "New permission order_manage_all)\n";
7743     SetVersion($DBversion);
7744 }
7745
7746 $DBversion = "3.13.00.040";
7747 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
7748     $dbh->do("CREATE TABLE IF NOT EXISTS marc_modification_templates (
7749               template_id int(11) NOT NULL auto_increment,
7750               name text NOT NULL,
7751               PRIMARY KEY  (template_id)
7752               ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;"
7753     );
7754
7755     $dbh->do("
7756       CREATE TABLE IF NOT EXISTS marc_modification_template_actions (
7757       mmta_id int(11) NOT NULL auto_increment,
7758       template_id int(11) NOT NULL,
7759       ordering int(3) NOT NULL,
7760       action enum('delete_field','update_field','move_field','copy_field') NOT NULL,
7761       field_number smallint(6) NOT NULL default '0',
7762       from_field varchar(3) NOT NULL,
7763       from_subfield varchar(1) NULL,
7764       field_value varchar(100) default NULL,
7765       to_field varchar(3) default NULL,
7766       to_subfield varchar(1) default NULL,
7767       to_regex_search text,
7768       to_regex_replace text,
7769       to_regex_modifiers varchar(8) default '',
7770       conditional enum('if','unless') default NULL,
7771       conditional_field varchar(3) default NULL,
7772       conditional_subfield varchar(1) default NULL,
7773       conditional_comparison enum('exists','not_exists','equals','not_equals') default NULL,
7774       conditional_value text,
7775       conditional_regex tinyint(1) NOT NULL default '0',
7776       description text,
7777       PRIMARY KEY  (mmta_id),
7778       CONSTRAINT `mmta_ibfk_1` FOREIGN KEY (`template_id`) REFERENCES `marc_modification_templates` (`template_id`) ON DELETE CASCADE ON UPDATE CASCADE
7779       ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7780     ");
7781
7782     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('13', 'marc_modification_templates', 'Manage marc modification templates')");
7783
7784     print "Upgrade to $DBversion done ( Bug 8015: Added tables for MARC Modification Framework )\n";
7785     SetVersion($DBversion);
7786 }
7787
7788 $DBversion = "3.13.00.041";
7789 if(CheckVersion($DBversion)) {
7790     $dbh->do(q{
7791         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');
7792     });
7793     print "Upgrade to $DBversion done (Bug 10986: Added AcqItemSetSubfieldsWhenReceived syspref)\n";
7794     SetVersion($DBversion);
7795 }
7796
7797 $DBversion = "3.13.00.042";
7798 if(CheckVersion($DBversion)) {
7799     print "Upgrade to $DBversion done (Koha 3.14 beta)\n";
7800     SetVersion($DBversion);
7801 }
7802
7803 $DBversion = "3.13.00.043";
7804 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
7805     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('SearchEngine','Zebra','Solr|Zebra','Search Engine','Choice')");
7806     print "Upgrade to $DBversion done (Bug 11196: Add system preference SearchEngine if missing )\n";
7807     SetVersion($DBversion);
7808 }
7809
7810 $DBversion = "3.14.00.000";
7811 if ( CheckVersion($DBversion) ) {
7812     print "Upgrade to $DBversion done (3.14.0 release)\n";
7813     SetVersion ($DBversion);
7814 }
7815
7816 $DBversion = '3.15.00.000';
7817 if ( CheckVersion($DBversion) ) {
7818     print "Upgrade to $DBversion done (the road goes ever on)\n";
7819     SetVersion ($DBversion);
7820 }
7821
7822 $DBversion = "3.15.00.001";
7823 if ( CheckVersion($DBversion) ) {
7824     $dbh->do("UPDATE systempreferences SET value='clear' where variable = 'CircAutoPrintQuickSlip' and value = '0'");
7825     $dbh->do("UPDATE systempreferences SET value='qslip' where variable = 'CircAutoPrintQuickSlip' and value = '1'");
7826     $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'");
7827     print "Upgrade to $DBversion done (Bug 11040: Add option to print full slip when checking out a null barcode)\n";
7828     SetVersion($DBversion);
7829 }
7830
7831 $DBversion = "3.15.00.002";
7832 if(CheckVersion($DBversion)) {
7833     $dbh->do("ALTER TABLE deleteditems MODIFY materials text;");
7834     print "Upgrade to $DBversion done (Bug 11275: alter deleteditems.materials from varchar(10) to text)\n";
7835     SetVersion($DBversion);
7836 }
7837
7838 $DBversion = "3.15.00.003";
7839 if ( CheckVersion($DBversion) ) {
7840     $dbh->do(q{
7841         UPDATE accountlines
7842         SET description = ''
7843         WHERE description IN (
7844             ' New Card',
7845             ' Fine',
7846             ' Sundry',
7847             'Writeoff',
7848             ' Account Management fee',
7849             'Payment,thanks', 'Payment,thanks - ',
7850             ' Lost Item'
7851         )
7852     });
7853     print "Upgrade to $DBversion done (Bug 2546: Update fine descriptions)\n";
7854     SetVersion($DBversion);
7855 }
7856
7857 $DBversion = "3.15.00.004";
7858 if ( CheckVersion($DBversion) ) {
7859     if ( C4::Context->preference("marcflavour") eq 'MARC21' ) {
7860         $dbh->do(qq{
7861             INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian, libopac, repeatable, mandatory,
7862             kohafield, tab, authorised_value, authtypecode, value_builder, isurl, hidden, frameworkcode, seealso, link,
7863             defaultvalue) VALUES
7864             ('015', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7865             ('020', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7866             ('024', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7867             ('027', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7868             ('800', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7869             ('810', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7870             ('811', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7871             ('830', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL);
7872         });
7873         $dbh->do(qq{
7874             INSERT IGNORE INTO auth_subfield_structure (authtypecode, tagfield, tagsubfield, liblibrarian, libopac, repeatable,
7875             mandatory, tab, authorised_value, value_builder, seealso, isurl, hidden, linkid, kohafield, frameworkcode) VALUES
7876             ('', '020', 'q', 'Qualifying information', 'Qualifying information', 1, 0, 0, NULL, NULL, NULL, 0, 0, '', '', ''),
7877             ('', '024', 'q', 'Qualifying information', 'Qualifying information', 1, 0, 0, NULL, NULL, NULL, 0, 0, '', '', '');
7878         });
7879     }
7880     print "Upgrade to $DBversion done (Bug 10970 - Update MARC21 frameworks to Update Nr. 17 - DB update)\n";
7881     SetVersion($DBversion);
7882 }
7883
7884 $DBversion = "3.15.00.005";
7885 if ( CheckVersion($DBversion) ) {
7886    $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('AcquisitionDetails', '1', '', 'Hide/Show acquisition details on the biblio detail page.', 'YesNo');");
7887    print "Upgrade to $DBversion done (Bug 8230: Add AcquisitionDetails system preference)\n";
7888    SetVersion ($DBversion);
7889 }
7890
7891 $DBversion = "3.15.00.006";
7892 if(CheckVersion($DBversion)) {
7893     $dbh->do(q{
7894         ALTER TABLE `borrowers`
7895         ADD KEY `surname_idx` (`surname`(255)),
7896         ADD KEY `firstname_idx` (`firstname`(255)),
7897         ADD KEY `othernames_idx` (`othernames`(255))
7898     });
7899     print "Upgrade to $DBversion done (Bug 11249 - Add DB indexes on borrower names)\n";
7900     SetVersion($DBversion);
7901 }
7902
7903 $DBversion = "3.15.00.007";
7904 if ( CheckVersion($DBversion) ) {
7905    $dbh->do("ALTER TABLE items ADD itemlost_on DATETIME NULL AFTER itemlost");
7906    $dbh->do("ALTER TABLE items ADD withdrawn_on DATETIME NULL AFTER withdrawn");
7907    $dbh->do("ALTER TABLE deleteditems ADD itemlost_on DATETIME NULL AFTER itemlost");
7908    $dbh->do("ALTER TABLE deleteditems ADD withdrawn_on DATETIME NULL AFTER withdrawn");
7909    print "Upgrade to $DBversion done (Bug 9673 - Track when items are marked as lost or withdrawn)\n";
7910    SetVersion ($DBversion);
7911 }
7912
7913 $DBversion = "3.15.00.008";
7914 if ( CheckVersion($DBversion) ) {
7915     $dbh->do(q{
7916         ALTER TABLE collections_tracking CHANGE ctId collections_tracking_id integer(11) NOT NULL auto_increment;
7917     });
7918     print "Upgrade to $DBversion done (Bug 11384) - change name of collections_tracker.ctId column)\n";
7919    SetVersion ($DBversion);
7920 }
7921
7922 $DBversion = "3.15.00.009";
7923 if ( CheckVersion($DBversion) ) {
7924     $dbh->do(q{
7925         ALTER TABLE suggestions MODIFY suggesteddate DATE NOT NULL
7926     });
7927     print "Upgrade to $DBversion done (Bug 11391) - drop default value on suggestions.suggesteddate column)\n";
7928    SetVersion ($DBversion);
7929 }
7930
7931 $DBversion = "3.15.00.010";
7932 if(CheckVersion($DBversion)) {
7933     $dbh->do("ALTER TABLE deleteditems DROP COLUMN marc");
7934     print "Upgrade to $DBversion done (Bug 6331: remove obsolete column in deleteditems.marc)\n";
7935     SetVersion ($DBversion);
7936 }
7937
7938 $DBversion = "3.15.00.011";
7939 if(CheckVersion($DBversion)) {
7940     $dbh->do("UPDATE marc_subfield_structure SET maxlength=9999 WHERE maxlength IS NULL OR maxlength=0;");
7941     print "Upgrade to $DBversion done (Bug 8018: set 9999 as default max length for subfields)\n";
7942     SetVersion ($DBversion);
7943 }
7944
7945 $DBversion = "3.15.00.012";
7946 if ( CheckVersion($DBversion) ) {
7947     $dbh->do(q{
7948         INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'force_checkout', 'Force checkout if a limitation exists')
7949     });
7950     $dbh->do(q{
7951         INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'manage_restrictions', 'Manage restrictions for accounts')
7952     });
7953     $dbh->do(q{
7954         INSERT INTO user_permissions (borrowernumber, module_bit, code)
7955             SELECT user_permissions.borrowernumber, 1, 'force_checkout'
7956             FROM user_permissions
7957             LEFT JOIN borrowers USING(borrowernumber)
7958             WHERE borrowers.flags & (1 << 1)
7959     });
7960     $dbh->do(q{
7961         INSERT INTO user_permissions (borrowernumber, module_bit, code)
7962             SELECT user_permissions.borrowernumber, 1, 'manage_restrictions'
7963             FROM user_permissions
7964             LEFT JOIN borrowers USING(borrowernumber)
7965             WHERE borrowers.flags & (1 << 1)
7966     });
7967
7968     print "Upgrade to $DBversion done (Bug 10863 - Add permissions force_checkout and manage_restrictions)\n";
7969     SetVersion($DBversion);
7970 }
7971
7972 $DBversion = "3.15.00.013";
7973 if(CheckVersion($DBversion)) {
7974     $dbh->do(q{
7975         UPDATE systempreferences
7976         SET explanation = 'Upon receiving items, update their subfields if they were created when placing an order (e.g. o=5|a="foo bar")'
7977         WHERE variable = "AcqItemSetSubfieldsWhenReceived"
7978     });
7979
7980     $dbh->do(q{
7981         UPDATE systempreferences
7982         SET value = ''
7983         WHERE variable = "AcqItemSetSubfieldsWhenReceived"
7984             AND value = "0"
7985     });
7986     print "Upgrade to $DBversion done (Bug 11237: Update explanation and default value for AcqItemSetSubfieldsWhenReceived syspref)\n";
7987     SetVersion($DBversion);
7988 }
7989
7990 $DBversion = "3.15.00.014";
7991 if (CheckVersion($DBversion)) {
7992     $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');");
7993     print "Upgrade to $DBversion done (Bug 11415: add system preference for automatic self checkout receipt printing)\n";
7994     SetVersion($DBversion);
7995 }
7996
7997 $DBversion = "3.15.00.015";
7998 if (CheckVersion($DBversion)) {
7999     $dbh->do("INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
8000         ('OpacSuggestionManagedBy',1,'','Show the name of the staff member who managed a suggestion in OPAC','YesNo');");
8001     print "Upgrade to $DBversion done (Bug 10907: Add OpacSuggestionManagedBy system preference)\n";
8002     SetVersion($DBversion);
8003 }
8004
8005 $DBversion = "3.15.00.016";
8006 if (CheckVersion($DBversion)) {
8007     $dbh->do("ALTER TABLE biblioitems CHANGE url url TEXT NULL DEFAULT NULL");
8008     $dbh->do("ALTER TABLE deletedbiblioitems CHANGE url url TEXT NULL DEFAULT NULL");
8009     print "Upgrade to $DBversion done (Bug 11268 - Biblioitems URL field is too small for some URLs)\n";
8010     SetVersion($DBversion);
8011 }
8012
8013 $DBversion = "3.15.00.017";
8014 if(CheckVersion($DBversion)) {
8015     $dbh->do(q{
8016         UPDATE systempreferences
8017         SET explanation = 'Define the contents of UNIMARC authority control field 100 position 08-35'
8018         WHERE variable = "UNIMARCAuthorityField100"
8019     });
8020     $dbh->do(q{
8021         UPDATE systempreferences
8022         SET explanation = 'Define the contents of MARC21 authority control field 008 position 06-39'
8023         WHERE variable = "MARCAuthorityControlField008"
8024     });
8025     $dbh->do(q{
8026         UPDATE systempreferences
8027         SET explanation = 'Define MARC Organization Code for MARC21 records - http://www.loc.gov/marc/organizations/orgshome.html'
8028         WHERE variable = "MARCOrgCode"
8029     });
8030     print "Upgrade to $DBversion done (Bug 11611 - fix possible confusion between UNIMARC and MARC21 in some sysprefs)\n";
8031     SetVersion($DBversion);
8032 }
8033
8034 $DBversion = "3.15.00.018";
8035 if ( CheckVersion($DBversion) ) {
8036     $dbh->{AutoCommit} = 0;
8037     $dbh->{RaiseError} = 1;
8038
8039     eval {
8040         $dbh->selectcol_arrayref(q|SELECT COUNT(*) FROM roadtype|);
8041     };
8042     unless ( $@ ) {
8043         my $av_added = $dbh->do(q|
8044             INSERT INTO authorised_values(category, authorised_value, lib, lib_opac)
8045                 SELECT 'ROADTYPE', roadtypeid, road_type, road_type
8046                 FROM roadtype;
8047         |);
8048
8049         my $rt_deleted = $dbh->do(q|
8050             DELETE FROM roadtype
8051         |);
8052
8053         if ( $av_added == $rt_deleted or $rt_deleted eq "0E0" ) {
8054             $dbh->do(q|
8055                 DROP TABLE roadtype;
8056             |);
8057             $dbh->commit;
8058             print "Upgrade to $DBversion done (Bug 7372: Move road types from the roadtype table to the ROADTYPE authorised values)\n";
8059             SetVersion($DBversion);
8060         } else {
8061             print "Upgrade to $DBversion failed (Bug 7372: Move road types from the roadtype table to the ROADTYPE authorised values.\nTransaction aborted because $@\n)";
8062             $dbh->rollback;
8063         }
8064     }
8065     $dbh->{AutoCommit} = 1;
8066     $dbh->{RaiseError} = 0;
8067 }
8068
8069 $DBversion = "3.15.00.019";
8070 if ( CheckVersion($DBversion) ) {
8071     $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')");
8072     print "Upgrade to $DBversion done (Bug 11256: Add system preference OpacMaxItemsToDisplay)\n";
8073     SetVersion($DBversion);
8074 }
8075
8076 $DBversion = "3.15.00.020";
8077 if ( CheckVersion($DBversion) ) {
8078     $dbh->do(q|
8079         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')
8080     |);
8081     print "Upgrade to $DBversion done (Bug 11343: Add system preference MaxItemsForBatch )\n";
8082     SetVersion($DBversion);
8083 }
8084
8085 $DBversion = "3.15.00.021";
8086 if(CheckVersion($DBversion)) {
8087     $dbh->do(q{
8088         ALTER TABLE `action_logs`
8089             DROP KEY timestamp,
8090             ADD KEY `timestamp_idx` (`timestamp`),
8091             ADD KEY `user_idx` (`user`),
8092             ADD KEY `module_idx` (`module`(255)),
8093             ADD KEY `action_idx` (`action`(255)),
8094             ADD KEY `object_idx` (`object`),
8095             ADD KEY `info_idx` (`info`(255))
8096     });
8097     print "Upgrade to $DBversion done (Bug 3445: Add indexes to action_logs table)\n";
8098     SetVersion($DBversion);
8099 }
8100
8101 $DBversion = "3.15.00.022";
8102 if (CheckVersion($DBversion)) {
8103     $dbh->do(q|
8104         DELETE FROM systempreferences WHERE variable= "memberofinstitution"
8105     |);
8106     print "Upgrade to $DBversion done (Bug 11751: Remove memberofinstitytion system preference)\n";
8107     SetVersion($DBversion);
8108 }
8109
8110 $DBversion = "3.15.00.023";
8111 if ( CheckVersion($DBversion) ) {
8112    $dbh->do("
8113        INSERT INTO systempreferences (variable,value,options,explanation,type)
8114        VALUES('CardnumberLength', '', '', 'Set a length for card numbers.', 'Free');
8115     ");
8116    print "Upgrade to $DBversion done (Bug 10861: Add CardnumberLength syspref)\n";
8117    SetVersion ($DBversion);
8118 }
8119
8120 $DBversion = "3.15.00.024";
8121 if ( CheckVersion($DBversion) ) {
8122     $dbh->do(q{
8123         DELETE FROM systempreferences WHERE variable = 'NoZebraIndexes'
8124     });
8125     print "Upgrade to $DBversion done (Bug 10012 - remove last vestiges of NoZebra)\n";
8126     SetVersion($DBversion);
8127 }
8128
8129 $DBversion = "3.15.00.025";
8130 if ( CheckVersion($DBversion) ) {
8131     $dbh->do(q{
8132         DROP TABLE aqorderdelivery;
8133     });
8134     print "Upgrade to $DBversion done (Bug 11928 - remove unused table)\n";
8135     SetVersion($DBversion);
8136 }
8137
8138 $DBversion = "3.15.00.026";
8139 if ( CheckVersion($DBversion) ) {
8140     $dbh->do(q{
8141         UPDATE language_descriptions SET description = 'Հայերեն' WHERE subtag = 'hy' AND lang = 'hy';
8142     });
8143     print "Upgrade to $DBversion done (Bug 11973 - Fix Armenian language description)\n";
8144     SetVersion($DBversion);
8145 }
8146
8147 $DBversion = "3.15.00.027";
8148 if (CheckVersion($DBversion)) {
8149     $dbh->do(q{
8150         ALTER TABLE opac_news ADD branchcode varchar(10) DEFAULT NULL
8151                                   AFTER idnew,
8152                               ADD CONSTRAINT opac_news_branchcode_ibfk
8153                                   FOREIGN KEY (branchcode)
8154                                   REFERENCES branches (branchcode)
8155                                   ON DELETE CASCADE ON UPDATE CASCADE;
8156     });
8157     print "Upgrade to $DBversion done (Bug 7567: Add branchcode to opac_news)\n";
8158     SetVersion($DBversion);
8159 }
8160
8161 $DBversion = "3.15.00.028";
8162 if(CheckVersion($DBversion)) {
8163     $dbh->do(q{
8164         ALTER TABLE issuingrules ADD norenewalbefore int(4) default NULL AFTER renewalperiod
8165     });
8166     print "Upgrade to $DBversion done (Bug 7413: Allow OPAC renewal x days before due date)\n";
8167     SetVersion($DBversion);
8168 }
8169
8170 $DBversion = "3.15.00.029";
8171 if ( CheckVersion($DBversion) ) {
8172     $dbh->do(q{
8173         UPDATE borrower_debarments SET expiration = NULL WHERE expiration = '9999-12-31'
8174     });
8175     print "Upgrade to $DBversion done (Bug 11846 - correct borrower_debarments with expiration 9999-12-31)\n";
8176     SetVersion($DBversion);
8177 }
8178
8179 $DBversion = "3.15.00.030";
8180 if(CheckVersion($DBversion)) {
8181     $dbh->do(q|
8182         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')
8183     |);
8184     print "Upgrade to $DBversion done (Bug 12052: Add OPACMySummaryNote syspref)\n";
8185     SetVersion($DBversion);
8186 }
8187
8188 $DBversion = "3.15.00.031";
8189 if ( CheckVersion($DBversion) ) {
8190    $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('10', 'writeoff', 'Write off fines and fees')");
8191    $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('10', 'remaining_permissions', 'Remaining permissions for managing fines and fees')");
8192    print "Upgrade to $DBversion done (Bug 9448 - Add separate permission for writing off fees)\n";
8193    SetVersion ($DBversion);
8194 }
8195
8196 $DBversion = "3.15.00.032";
8197 if ( CheckVersion($DBversion) ) {
8198     $dbh->do("ALTER TABLE aqorders CHANGE notes order_internalnote MEDIUMTEXT;");
8199     $dbh->do("ALTER TABLE aqorders ADD COLUMN order_vendornote MEDIUMTEXT AFTER order_internalnote;");
8200     print "Upgrade to $DBversion done (Bug 9416 - In each order, add a new note made for the vendor)\n";
8201    SetVersion ($DBversion);
8202 }
8203
8204 $DBversion = "3.15.00.033";
8205 if ( CheckVersion($DBversion) ) {
8206     $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')");
8207     print "Upgrade to $DBversion done (Bug 10951: Add NoLoginInstructions pref)\n";
8208     SetVersion($DBversion);
8209 }
8210
8211 $DBversion = "3.15.00.034";
8212 if ( CheckVersion($DBversion) ) {
8213     $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')");
8214     print "Upgrade to $DBversion done (Bug 10986: system preferences to limit languages in advanced search )\n";
8215     SetVersion ($DBversion);
8216 }
8217
8218 $DBversion = "3.15.00.035";
8219 if ( CheckVersion($DBversion) ) {
8220     #insert a notice for sharing a list and accepting a share
8221     $dbh->do("
8222 INSERT INTO letter (module, code, branchcode, name, is_html, title, content)
8223 VALUES ( 'members', 'SHARE_INVITE', '', 'Invitation for sharing a list', '0', 'Share list <<listname>>', 'Dear patron,
8224
8225 One of our patrons, <<borrowers.firstname>> <<borrowers.surname>>, invites you to share a list <<listname>> in our library catalog.
8226
8227 To access this shared list, please click on the following URL or copy-and-paste it into your browser address bar.
8228
8229 <<shareurl>>
8230
8231 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.
8232
8233 Thank you.
8234
8235 Your library.'
8236     )");
8237     $dbh->do("
8238 INSERT INTO letter (module, code, branchcode, name, is_html, title, content)
8239 VALUES ( 'members', 'SHARE_ACCEPT', '', 'Notification about an accepted share', '0', 'Share on list <<listname>> accepted', 'Dear patron,
8240
8241 We want to inform you that <<borrowers.firstname>> <<borrowers.surname>> accepted your invitation to share your list <<listname>> in our library catalog.
8242
8243 Thank you.
8244
8245 Your library.'
8246     )");
8247     print "Upgrade to $DBversion done (Bug 9032: Share a list)\n";
8248     SetVersion($DBversion);
8249 }
8250
8251 $DBversion = "3.15.00.036";
8252 if ( CheckVersion($DBversion) ) {
8253     $dbh->do(q{
8254         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
8255         VALUES('AllowMultipleIssuesOnABiblio',1,'Allow/Don\'t allow patrons to check out multiple items from one biblio','','YesNo')
8256     });
8257
8258     print "Upgrade to $DBversion done (Bug 10859 - Add system preference AllowMultipleIssuesOnABiblio)\n";
8259     SetVersion($DBversion);
8260 }
8261
8262 $DBversion = "3.15.00.037";
8263 if(CheckVersion($DBversion)) {
8264     $dbh->do(q{
8265         ALTER TABLE itemtypes ADD sip_media_type VARCHAR( 3 ) DEFAULT NULL AFTER checkinmsgtype
8266     });
8267     $dbh->do(q{
8268         INSERT INTO authorised_values (category, authorised_value, lib) VALUES
8269          ('SIP_MEDIA_TYPE', '000', 'Other'),
8270          ('SIP_MEDIA_TYPE', '001', 'Book'),
8271          ('SIP_MEDIA_TYPE', '002', 'Magazine'),
8272          ('SIP_MEDIA_TYPE', '003', 'Bound journal'),
8273          ('SIP_MEDIA_TYPE', '004', 'Audio tape'),
8274          ('SIP_MEDIA_TYPE', '005', 'Video tape'),
8275          ('SIP_MEDIA_TYPE', '006', 'CD/CDROM'),
8276          ('SIP_MEDIA_TYPE', '007', 'Diskette'),
8277          ('SIP_MEDIA_TYPE', '008', 'Book with diskette'),
8278          ('SIP_MEDIA_TYPE', '009', 'Book with CD'),
8279          ('SIP_MEDIA_TYPE', '010', 'Book with audio tape')
8280     });
8281     print "Upgrade to $DBversion done (Bug 11351 - Add support for SIP2 media type)\n";
8282     SetVersion($DBversion);
8283 }
8284
8285 $DBversion = '3.15.00.038';
8286 if ( CheckVersion($DBversion) ) {
8287     $dbh->do(q{
8288         INSERT INTO  systempreferences (
8289             variable,
8290             value,
8291             options,
8292             explanation,
8293             type
8294             )
8295         VALUES (
8296             'DisplayLibraryFacets',  'holding',  'home|holding|both',  'Defines which library facets to display.',  'Choice'
8297         );
8298     });
8299     print "Upgrade to $DBversion done (Bug 11334 - Add facet for home library)\n";
8300     SetVersion ($DBversion);
8301 }
8302
8303 $DBversion = "3.15.00.039";
8304 if ( CheckVersion($DBversion) ) {
8305
8306     $dbh->do( q{
8307         ALTER TABLE letter ADD COLUMN message_transport_type VARCHAR(20) NOT NULL DEFAULT 'email' AFTER content
8308     } );
8309
8310     $dbh->do( q{
8311         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
8312     } );
8313
8314     $dbh->do( q{
8315         ALTER TABLE letter DROP PRIMARY KEY, ADD PRIMARY KEY (`module`,`code`,`branchcode`, message_transport_type);
8316     } );
8317
8318     $dbh->do( q{
8319         CREATE TABLE overduerules_transport_types(
8320             id INT(11) NOT NULL AUTO_INCREMENT,
8321             branchcode varchar(10) NOT NULL DEFAULT '',
8322             categorycode VARCHAR(10) NOT NULL DEFAULT '',
8323             letternumber INT(1) NOT NULL DEFAULT 1,
8324             message_transport_type VARCHAR(20) NOT NULL DEFAULT 'email',
8325             PRIMARY KEY (id),
8326             CONSTRAINT overduerules_fk FOREIGN KEY (branchcode, categorycode) REFERENCES overduerules (branchcode, categorycode) ON DELETE CASCADE ON UPDATE CASCADE,
8327             CONSTRAINT mtt_fk FOREIGN KEY (message_transport_type) REFERENCES message_transport_types (message_transport_type) ON DELETE CASCADE ON UPDATE CASCADE
8328         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
8329     } );
8330
8331     my $sth = $dbh->prepare( q{
8332         SELECT * FROM overduerules;
8333     } );
8334
8335     $sth->execute;
8336     my $sth_insert_mtt = $dbh->prepare( q{
8337         INSERT INTO overduerules_transport_types (branchcode, categorycode, letternumber, message_transport_type) VALUES ( ?, ?, ?, ? )
8338     } );
8339     while ( my $row = $sth->fetchrow_hashref ) {
8340         my $branchcode = $row->{branchcode};
8341         my $categorycode = $row->{categorycode};
8342         for my $letternumber ( 1 .. 3 ) {
8343             next unless $row->{"letter$letternumber"};
8344             $sth_insert_mtt->execute(
8345                 $branchcode, $categorycode, $letternumber, 'email'
8346             );
8347         }
8348     }
8349
8350     print "Upgrade done (Bug 9016: Adds multi transport types management for notices)\n";
8351     SetVersion($DBversion);
8352 }
8353
8354 $DBversion = "3.15.00.040";
8355 if ( CheckVersion($DBversion) ) {
8356     $dbh->do(q|
8357         UPDATE message_transports SET letter_code='HOLD' WHERE letter_code='HOLD_PHONE' OR letter_code='HOLD_PRINT'
8358     |);
8359     $dbh->do(q|
8360         UPDATE letter SET code='HOLD', message_transport_type='print' WHERE code='HOLD_PRINT'
8361     |);
8362     $dbh->do(q|
8363         UPDATE letter SET code='HOLD', message_transport_type='phone' WHERE code='HOLD_PHONE'
8364     |);
8365     print "Upgrade to $DBversion done (Bug 10845: Multi transport types for holds)\n";
8366     SetVersion($DBversion);
8367 }
8368
8369 $DBversion = "3.15.00.041";
8370 if ( CheckVersion($DBversion) ) {
8371     my ( $name ) = $dbh->selectrow_array(q|
8372         SELECT name FROM letter WHERE code="HOLD"
8373     |);
8374     $dbh->do(q|
8375         UPDATE letter
8376         SET code="HOLD",
8377             message_transport_type="phone",
8378             name= ?
8379         WHERE code="HOLD_PHONE"
8380     |, {}, $name);
8381
8382     ( $name ) = $dbh->selectrow_array(q|
8383         SELECT name FROM letter WHERE code="PREDUE"
8384     |);
8385     $dbh->do(q|
8386         UPDATE letter
8387         SET code="PREDUE",
8388             message_transport_type="phone",
8389             name= ?
8390         WHERE code="PREDUE_PHONE"
8391     |, {}, $name);
8392
8393     ( $name ) = $dbh->selectrow_array(q|
8394         SELECT name FROM letter WHERE code="OVERDUE"
8395     |);
8396     $dbh->do(q|
8397         UPDATE letter
8398         SET code="OVERDUE",
8399             message_transport_type="phone",
8400             name= ?
8401         WHERE code="OVERDUE_PHONE"
8402     |, {}, $name);
8403
8404     print "Upgrade to $DBversion done (Bug 11867: Update letters *_PHONE)\n";
8405     SetVersion($DBversion);
8406 }
8407
8408 $DBversion = "3.15.00.042";
8409 if ( CheckVersion($DBversion) ) {
8410     $dbh->do(q{
8411         INSERT INTO systempreferences
8412             (variable,value,explanation,options,type)
8413         VALUES
8414             ('SpecifyReturnDate',0,'Define whether to display \"Specify Return Date\" form in Circulation','','YesNo')
8415     });
8416     print "Upgrade to $DBversion done (Bug 10694 - Allow arbitrary backdating of returns)\n";
8417     SetVersion($DBversion);
8418 }
8419
8420 $DBversion = "3.15.00.043";
8421 if ( CheckVersion($DBversion) ) {
8422     $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')");
8423    print "Upgrade to $DBversion done (Bug 7180: Added MarcFieldsToOrder syspref)\n";
8424    SetVersion ($DBversion);
8425 }
8426
8427 $DBversion = "3.15.00.044";
8428 if ( CheckVersion($DBversion) ) {
8429     $dbh->do("ALTER TABLE currency ADD isocode VARCHAR(5) default NULL AFTER symbol;");
8430     print "Upgrade to $DBversion done (Added isocode to the currency table)\n";
8431     SetVersion($DBversion);
8432 }
8433
8434 $DBversion = "3.15.00.045";
8435 if ( CheckVersion($DBversion) ) {
8436     $dbh->do("
8437         INSERT INTO systempreferences (variable,value,explanation,options,type)
8438         VALUES (
8439             'BlockExpiredPatronOpacActions',
8440             '0',
8441             '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',
8442             NULL,
8443             'YesNo'
8444         )
8445     ");
8446     $dbh->do("ALTER TABLE `categories` ADD COLUMN `BlockExpiredPatronOpacActions` TINYINT(1) DEFAULT -1 NOT NULL AFTER category_type");
8447     print "Upgraded to $DBversion done (Bug 6739 - expired patrons not blocked from opac actions)\n";
8448     SetVersion ($DBversion);
8449 }
8450
8451 $DBversion = "3.15.00.046";
8452 if ( CheckVersion($DBversion) ) {
8453     $dbh->do(q|
8454         ALTER TABLE search_history ADD COLUMN type VARCHAR(16) NOT NULL DEFAULT 'biblio' AFTER query_cgi
8455     |);
8456     print "Upgrade to $DBversion done (Bug 10807 - Add db field search_history.type)\n";
8457     SetVersion($DBversion);
8458 }
8459
8460 $DBversion = "3.15.00.047";
8461 if ( CheckVersion($DBversion) ) {
8462     $dbh->do(q|
8463         INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('EnableSearchHistory','0','','Enable or disable search history','YesNo')
8464     |);
8465     print "Upgrade to $DBversion done (Bug 10862: Add EnableSearchHistory syspref)\n";
8466     SetVersion($DBversion);
8467 }
8468
8469 $DBversion = "3.15.00.048";
8470 if ( CheckVersion($DBversion) ) {
8471     $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')");
8472     $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')");
8473     print "Upgrade to $DBversion done (Bug 10195: Records hidden with OpacSuppression can still be accessed)\n";
8474     SetVersion($DBversion);
8475 }
8476
8477 $DBversion = "3.15.00.049";
8478 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
8479     $dbh->do("ALTER TABLE biblioitems DROP INDEX isbn");
8480     $dbh->do("ALTER TABLE biblioitems DROP INDEX issn");
8481     $dbh->do("ALTER TABLE biblioitems DROP INDEX issn_idx");
8482     $dbh->do("ALTER TABLE biblioitems
8483               CHANGE isbn isbn MEDIUMTEXT NULL DEFAULT NULL,
8484               CHANGE issn issn MEDIUMTEXT NULL DEFAULT NULL
8485     ");
8486     $dbh->do("ALTER TABLE biblioitems
8487               ADD INDEX isbn ( isbn ( 255 ) ),
8488               ADD INDEX issn ( issn ( 255 ) )
8489     ");
8490
8491     $dbh->do("ALTER TABLE deletedbiblioitems DROP INDEX isbn");
8492     $dbh->do("ALTER TABLE deletedbiblioitems
8493               CHANGE isbn isbn MEDIUMTEXT NULL DEFAULT NULL,
8494               CHANGE issn issn MEDIUMTEXT NULL DEFAULT NULL
8495     ");
8496     $dbh->do("ALTER TABLE deletedbiblioitems
8497               ADD INDEX isbn ( isbn ( 255 ) )
8498     ");
8499
8500     print "Upgrade to $DBversion done (Bug 5377 - Biblioitems isbn and issn fields too small for multiple ISBN and ISSN)\n";
8501     SetVersion($DBversion);
8502 }
8503
8504 $DBversion = "3.15.00.050";
8505 if ( CheckVersion($DBversion) ) {
8506     $dbh->do("
8507         INSERT INTO systempreferences (
8508             variable,
8509             value,
8510             explanation,
8511             type
8512         ) VALUES (
8513             'AggressiveMatchOnISBN',
8514             '0',
8515             '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',
8516             'YesNo'
8517         )
8518     ");
8519
8520     print "Upgrade to $DBversion done (Bug 10500 - Improve isbn matching when importing records)\n";
8521     SetVersion($DBversion);
8522 }
8523
8524 $DBversion = "3.15.00.051";
8525 if ( CheckVersion($DBversion) ) {
8526     print "Upgrade to $DBversion done (Koha 3.16 beta)\n";
8527     SetVersion($DBversion);
8528 }
8529
8530 $DBversion = "3.15.00.052";
8531 if ( CheckVersion($DBversion) ) {
8532     print "Upgrade to $DBversion done (Koha 3.16 RC)\n";
8533     SetVersion($DBversion);
8534 }
8535
8536 $DBversion = "3.16.00.000";
8537 if ( CheckVersion($DBversion) ) {
8538     print "Upgrade to $DBversion done (3.16.0 release)\n";
8539     SetVersion ($DBversion);
8540 }
8541
8542 $DBversion = '3.17.00.000';
8543 if ( CheckVersion($DBversion) ) {
8544     print "Upgrade to $DBversion done (there is no time to rest on our laurels)\n";
8545     SetVersion ($DBversion);
8546 }
8547
8548 $DBversion = '3.17.00.001';
8549 if ( CheckVersion($DBversion) ) {
8550    $dbh->do("UPDATE systempreferences SET variable = 'AuthoritySeparator' WHERE variable = 'authoritysep'");
8551    print "Upgrade to $DBversion done (Bug 10330 - Rename system preference authoritysep to AuthoritySeparator)\n";
8552    SetVersion ($DBversion);
8553 }
8554
8555 $DBversion = "3.17.00.002";
8556 if (CheckVersion($DBversion)) {
8557     $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')");
8558     $dbh->do("
8559 CREATE TABLE IF NOT EXISTS `misc_files` (
8560   `file_id` int(11) NOT NULL AUTO_INCREMENT,
8561   `table_tag` varchar(255) NOT NULL,
8562   `record_id` int(11) NOT NULL,
8563   `file_name` varchar(255) NOT NULL,
8564   `file_type` varchar(255) NOT NULL,
8565   `file_description` varchar(255) DEFAULT NULL,
8566   `file_content` longblob NOT NULL, -- file content
8567   `date_uploaded` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
8568   PRIMARY KEY (`file_id`),
8569   KEY `table_tag` (`table_tag`),
8570   KEY `record_id` (`record_id`)
8571 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
8572     ");
8573     print "Upgrade to $DBversion done (Bug 3050 - Add an option to upload scanned invoices)\n";
8574     SetVersion($DBversion);
8575 }
8576
8577 $DBversion = "3.17.00.003";
8578 if (CheckVersion($DBversion)) {
8579     $dbh->do("UPDATE systempreferences SET type = 'Choice', options = '0|1|force' WHERE variable = 'OPACItemHolds'");
8580     print "Upgrade to $DBversion done (Bug 7825 - Changed OPACItemHolds syspref to Choice)\n";
8581     SetVersion($DBversion);
8582 }
8583
8584 $DBversion = "3.17.00.004";
8585 if (CheckVersion($DBversion)) {
8586     $dbh->do("ALTER TABLE categories ADD default_privacy ENUM( 'default', 'never', 'forever' ) NOT NULL DEFAULT 'default' AFTER category_type");
8587     print "Upgrade to $DBversion done (Bug 6254 - can't set patron privacy by default)\n";
8588     SetVersion($DBversion);
8589 }
8590
8591 $DBversion = "3.17.00.005";
8592 if (CheckVersion($DBversion)) {
8593     $dbh->do(q|
8594         ALTER TABLE issuingrules
8595         ADD maxsuspensiondays INT(11) DEFAULT NULL AFTER finedays;
8596     |);
8597     print "Upgrade to $DBversion done (Bug 12230: Add new issuing rule maxsuspensiondays)\n";
8598     SetVersion($DBversion);
8599 }
8600
8601 $DBversion = "3.17.00.006";
8602 if ( CheckVersion($DBversion) ) {
8603     $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')");
8604     $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')");
8605     print "Upgrade to $DBversion done (Bug 7720 - Ambiguity in OPAC Details location.)\n";
8606     SetVersion($DBversion);
8607 }
8608
8609 $DBversion = "3.17.00.007";
8610 if (CheckVersion($DBversion)) {
8611     $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');");
8612     print "Upgrade to $DBversion done (Bug 11629 - Add ability to update not for loan status on checkin)\n";
8613     SetVersion($DBversion);
8614 }
8615
8616 $DBversion = "3.17.00.008";
8617 if ( CheckVersion($DBversion) ) {
8618     $dbh->do(q|
8619         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('OPACAcquisitionDetails','0', '','Show the acquisition details at the OPAC','YesNo')
8620     |);
8621     print "Upgrade to $DBversion done (Bug 11169 - Add OPACAcquisitionDetails syspref)\n";
8622     SetVersion($DBversion);
8623 }
8624
8625 $DBversion = "3.17.00.009";
8626 if ( CheckVersion($DBversion) ) {
8627     $dbh->do(q{
8628         DELETE FROM systempreferences WHERE variable = 'UseTablesortForCirc'
8629     });
8630
8631     print "Upgrade to $DBversion done (Bug 11703 - Remove UseTablesortForCirc syspref)\n";
8632     SetVersion($DBversion);
8633 }
8634
8635 $DBversion = "3.17.00.010";
8636 if ( CheckVersion($DBversion) ) {
8637     $dbh->do("DELETE FROM systempreferences WHERE variable='opacsmallimage'");
8638     print "Upgrade to $DBversion done (Bug 11347 - PROG/CCSR deprecation: Remove opacsmallimage system preference)\n";
8639     SetVersion($DBversion);
8640 }
8641
8642 $DBversion = "3.17.00.011";
8643 if ( CheckVersion($DBversion) ) {
8644     $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'hr', 'language', 'Croatian','2014-07-24' )");
8645     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'hr','hrv')");
8646     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'hr', 'Hrvatski')");
8647     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'en', 'Croatian')");
8648     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'fr', 'Croate')");
8649     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'de', 'Kroatisch')");
8650     print "Upgrade to $DBversion done (Bug 12649: Add Croatian language)\n";
8651     SetVersion ($DBversion);
8652 }
8653
8654 $DBversion = "3.17.00.012";
8655 if ( CheckVersion($DBversion) ) {
8656     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacShowFiltersPulldownMobile'");
8657     print "Upgrade to $DBversion done ( Bug 12512 - PROG/CCSR deprecation: Remove OpacShowFiltersPulldownMobile system preference )\n";
8658     SetVersion ($DBversion);
8659 }
8660
8661 $DBversion = "3.17.00.013";
8662 if ( CheckVersion($DBversion) ) {
8663     $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')");
8664     print "Upgrade to $DBversion done (Re-add system preference maxreserves)\n";
8665     SetVersion ($DBversion);
8666 }
8667
8668 $DBversion = '3.17.00.014';
8669 if ( CheckVersion($DBversion) ) {
8670     $dbh->do("
8671         INSERT INTO systempreferences (variable,value,explanation,type) VALUES
8672         ('OverdueNoticeCalendar',0,'Take calendar into consideration when working out sending overdue notices','YesNo')
8673     ");
8674     print "Upgrade to $DBversion done (Bug 12529 - Adding a syspref to allow the overdue notices to consider the calendar when generating notices)\n";
8675     SetVersion($DBversion);
8676 }
8677
8678 $DBversion = "3.17.00.015";
8679 if ( CheckVersion($DBversion) ) {
8680     $dbh->do(q{
8681         CREATE TABLE IF NOT EXISTS columns_settings (
8682             module varchar(255) NOT NULL,
8683             page varchar(255) NOT NULL,
8684             tablename varchar(255) NOT NULL,
8685             columnname varchar(255) NOT NULL,
8686             cannot_be_toggled int(1) NOT NULL DEFAULT 0,
8687             is_hidden int(1) NOT NULL DEFAULT 0,
8688             PRIMARY KEY(module, page, tablename, columnname)
8689         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
8690     });
8691     print "Upgrade to $DBversion done (Bug 10212 - Create new table columns_settings)\n";
8692     SetVersion ($DBversion);
8693 }
8694
8695 $DBversion = "3.17.00.016";
8696 if ( CheckVersion($DBversion) ) {
8697     $dbh->do("CREATE TABLE aqcontacts (
8698         id int(11) NOT NULL auto_increment,
8699         name varchar(100) default NULL,
8700         position varchar(100) default NULL,
8701         phone varchar(100) default NULL,
8702         altphone varchar(100) default NULL,
8703         fax varchar(100) default NULL,
8704         email varchar(100) default NULL,
8705         notes mediumtext,
8706         claimacquisition BOOLEAN NOT NULL DEFAULT 0,
8707         claimissues BOOLEAN NOT NULL DEFAULT 0,
8708         acqprimary BOOLEAN NOT NULL DEFAULT 0,
8709         serialsprimary BOOLEAN NOT NULL DEFAULT 0,
8710         booksellerid int(11) not NULL,
8711         PRIMARY KEY  (id),
8712         CONSTRAINT booksellerid_aqcontacts_fk FOREIGN KEY (booksellerid)
8713             REFERENCES aqbooksellers (id) ON DELETE CASCADE ON UPDATE CASCADE
8714         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;");
8715     $dbh->do("INSERT INTO aqcontacts (name, position, phone, altphone, fax,
8716             email, notes, booksellerid, claimacquisition, claimissues, acqprimary, serialsprimary)
8717         SELECT contact, contpos, contphone, contaltphone, contfax, contemail,
8718             contnotes, id, 1, 1, 1, 1 FROM aqbooksellers;");
8719     $dbh->do("ALTER TABLE aqbooksellers DROP COLUMN contact,
8720         DROP COLUMN contpos, DROP COLUMN contphone,
8721         DROP COLUMN contaltphone, DROP COLUMN contfax,
8722         DROP COLUMN contemail, DROP COLUMN contnotes;");
8723     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contact>>', '<<aqcontacts.name>>')");
8724     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contpos>>', '<<aqcontacts.position>>')");
8725     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contphone>>', '<<aqcontacts.phone>>')");
8726     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contaltphone>>', '<<aqcontacts.altphone>>')");
8727     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contfax>>', '<<aqcontacts.contfax>>')");
8728     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contemail>>', '<<aqcontacts.contemail>>')");
8729     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contnotes>>', '<<aqcontacts.contnotes>>')");
8730     print "Upgrade to $DBversion done (Bug 10402: Move bookseller contacts to separate table)\n";
8731     SetVersion($DBversion);
8732 }
8733
8734 $DBversion = "3.17.00.017";
8735 if ( CheckVersion($DBversion) ) {
8736     # Correct invalid recordtypes (should be very exceptional)
8737     $dbh->do(q{
8738         UPDATE z3950servers set recordtype='biblio' WHERE recordtype NOT IN ('authority','biblio')
8739     });
8740     # Correct invalid server types (should also be very exceptional)
8741     $dbh->do(q{
8742         UPDATE z3950servers set type='zed' WHERE type <> 'zed'
8743     });
8744     # Adjust table
8745     $dbh->do(q{
8746         ALTER TABLE z3950servers
8747         DROP COLUMN icon,
8748         DROP COLUMN description,
8749         DROP COLUMN position,
8750         MODIFY COLUMN id int NOT NULL AUTO_INCREMENT FIRST,
8751         MODIFY COLUMN recordtype enum('authority','biblio') NOT NULL DEFAULT 'biblio',
8752         CHANGE COLUMN name servername mediumtext NOT NULL,
8753         CHANGE COLUMN type servertype enum('zed','sru') NOT NULL DEFAULT 'zed',
8754         ADD COLUMN sru_options varchar(255) default NULL,
8755         ADD COLUMN sru_fields mediumtext default NULL,
8756         ADD COLUMN add_xslt mediumtext default NULL
8757     });
8758     print "Upgrade to $DBversion done (Bug 6536: Z3950 improvements)\n";
8759     SetVersion ($DBversion);
8760 }
8761
8762 $DBversion = "3.17.00.018";
8763 if ( CheckVersion($DBversion) ) {
8764     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('HoldsInNoissuesCharge', '0', 'Hold charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
8765     print "Upgrade to $DBversion done (Bug 12205: Add HoldsInNoissuesCharge systempreference)\n";
8766     SetVersion($DBversion);
8767 }
8768
8769 $DBversion = "3.17.00.019";
8770 if ( CheckVersion($DBversion) ) {
8771     $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')"
8772     );
8773     print "Upgrade to $DBversion done (Bug 6149: Operator highlighted in search results)\n";
8774     SetVersion($DBversion);
8775 }
8776
8777 $DBversion = "3.17.00.020";
8778 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
8779     $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')");
8780     print "Upgrade to $DBversion done (Bug 8735 - Expire holds waiting only on days the library is open)\n";
8781     SetVersion ($DBversion);
8782 }
8783
8784 $DBversion = "3.17.00.021";
8785 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
8786     my $pref = C4::Context->preference('HomeOrHoldingBranch');
8787     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
8788        VALUES ('StaffSearchResultsDisplayBranch', ?,'homebranch|holdingbranch','Controls the display of the home or holding branch for staff search results','choice')", undef, $pref);
8789     print "Upgrade to $DBversion done (Bug 12582 - Control of branch displayed in search results linked to HomeOrHoldingBranch)\n";
8790     SetVersion ($DBversion);
8791 }
8792
8793 $DBversion = '3.17.00.022';
8794 if ( CheckVersion($DBversion) ) {
8795     my @temp= $dbh->selectrow_array(qq|
8796         SELECT count(*)
8797         FROM marc_subfield_structure
8798         WHERE kohafield='permanent_location' OR kohafield='items.permanent_location'
8799     |);
8800     print "Upgrade to $DBversion done (Bug 7817: Check for permanent_location)\n";
8801     if( $temp[0] ) {
8802         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";
8803     }
8804     SetVersion($DBversion);
8805 }
8806
8807 $DBversion = "3.17.00.023";
8808 if ( CheckVersion($DBversion) ) {
8809     $dbh->do(q{
8810         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')
8811     });
8812     print "Upgrade to $DBversion done (Bug 11169 - Add AcqItemSetSubfieldsWhenReceiptIsCancelled syspref)\n";
8813     SetVersion($DBversion);
8814 }
8815
8816 $DBversion = "3.17.00.024";
8817 if(CheckVersion($DBversion)) {
8818     $dbh->do(q{
8819         ALTER TABLE issues ADD auto_renew BOOLEAN default FALSE AFTER renewals
8820     });
8821     $dbh->do(q{
8822         ALTER TABLE old_issues ADD auto_renew BOOLEAN default FALSE AFTER renewals
8823     });
8824     $dbh->do(q{
8825         ALTER TABLE issuingrules ADD auto_renew BOOLEAN default FALSE AFTER norenewalbefore
8826     });
8827     print "Upgrade to $DBversion done (Bug 11577: [ENH] Automatic renewal feature)\n";
8828     SetVersion($DBversion);
8829 }
8830
8831 $DBversion = '3.17.00.025';
8832 if ( CheckVersion($DBversion) ) {
8833     $dbh->do(qq{
8834         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')
8835     });
8836     print "Upgrade to $DBversion done (Bug 12728: Checked syspref StatisticsFields)\n";
8837 }
8838
8839 $DBversion = "3.17.00.026";
8840 if ( CheckVersion($DBversion) ) {
8841     if ( C4::Context->preference('marcflavour') eq 'MARC21' ) {
8842         $dbh->do("UPDATE marc_subfield_structure SET liblibrarian = 'Encoded bitrate', libopac = 'Encoded bitrate' WHERE tagfield = '347' AND tagsubfield = 'f'");
8843         $dbh->do("UPDATE marc_subfield_structure SET repeatable = 1 WHERE tagfield IN ('110','111','610','611','710','711','810','811') AND tagsubfield = 'c'");
8844         $dbh->do("UPDATE auth_subfield_structure SET repeatable = 1 WHERE tagfield IN ('110','111','410','411','510','511','710','711') AND tagsubfield = 'c'");
8845         print "Upgrade to $DBversion done (Bug 12435 - Update MARC21 frameworks to Update No. 18 (April 2014))\n";
8846     }
8847     SetVersion($DBversion);
8848 }
8849
8850 $DBversion = "3.17.00.027";
8851 if ( CheckVersion($DBversion) ) {
8852     $dbh->do(q{
8853         DELETE FROM systempreferences WHERE variable = 'SearchEngine'
8854     });
8855     print "Upgrade to $DBversion done (Bug 12538 - Remove SearchEngine syspref)\n";
8856     SetVersion($DBversion);
8857 }
8858
8859 $DBversion = "3.17.00.028";
8860 if ( CheckVersion($DBversion) ) {
8861     $dbh->do(q{
8862         INSERT INTO systempreferences (variable,value) VALUES('OpacCustomSearch','');
8863     });
8864     print "Upgrade to $DBversion done (Bug 12296 - search box replaceable with a system preference)\n";
8865     SetVersion($DBversion);
8866 }
8867
8868 $DBversion = "3.17.00.029";
8869 if ( CheckVersion($DBversion) ) {
8870     $dbh->do("ALTER TABLE  `items` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8871     $dbh->do("ALTER TABLE  `deleteditems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8872     $dbh->do("ALTER TABLE  `biblioitems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8873     $dbh->do("ALTER TABLE  `deletedbiblioitems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8874     print "Upgrade to $DBversion done (Bug 12424 - ddc sorting of call numbers truncates long Cutter parts)\n";
8875     SetVersion ($DBversion);
8876 }
8877
8878 $DBversion = "3.17.00.030";
8879 if ( CheckVersion($DBversion) ) {
8880     $dbh->do(
8881         q{
8882        INSERT INTO systempreferences (variable, value, options, explanation, type )
8883        VALUES
8884         ('UsageStatsCountry', '', NULL, 'The country where your library is located, to be shown on the Hea Koha community website', 'Choice'),
8885         ('UsageStatsID', '', NULL, 'This preference is part of Koha but it should not be deleted or updated manually.',  'Free'),
8886         ('UsageStatsLastUpdateTime', '', NULL, 'This preference is part of Koha but it should not be deleted or updated manually.', 'Free'),
8887         ('UsageStatsLibraryName', '', NULL, 'The library name to be shown on Hea Koha community website', 'Free'),
8888         ('UsageStatsLibraryType', 'public', 'public|university', 'The library type to be shown on the Hea Koha community website', 'Choice'),
8889         ('UsageStatsLibraryUrl', '', NULL, 'The library URL to be shown on Hea Koha community website', 'Free'),
8890         ('UsageStats', 0, NULL, 'Share anonymous usage data on the Hea Koha community website.', 'YesNo')
8891     });
8892     print "Upgrade to $DBversion done (Bug 11926: Add UsageStats systempreferences (HEA))\n";
8893     SetVersion ($DBversion);
8894 }
8895
8896 $DBversion = "3.17.00.031";
8897 if ( CheckVersion($DBversion) ) {
8898    $dbh->do("ALTER TABLE saved_sql CHANGE report_name report_name VARCHAR( 255 ) NOT NULL DEFAULT '' ");
8899    print "Upgrade to $DBversion done (Bug 2969: Report Name should be mandatory for saved reports)\n";
8900    SetVersion ($DBversion);
8901 }
8902
8903 $DBversion = "3.17.00.032";
8904 if ( CheckVersion($DBversion) ) {
8905     $dbh->do(
8906 "INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('ReplytoDefault',  '',  NULL,  'The default email address to be set as replyto.',  'Free')"
8907     );
8908     $dbh->do(
8909 "INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('ReturnpathDefault',  '',  NULL,  'The default email address to be set as return-path',  'Free')"
8910     );
8911     $dbh->do("ALTER TABLE branches ADD branchreplyto mediumtext AFTER branchemail");
8912     $dbh->do("ALTER TABLE branches ADD branchreturnpath mediumtext AFTER branchreplyto");
8913     print "Upgrade to $DBversion done (Bug 9530: Adding replyto and returnpath addresses.)\n";
8914     SetVersion($DBversion);
8915 }
8916
8917 $DBversion = "3.17.00.033";
8918 if ( CheckVersion($DBversion) ) {
8919     $dbh->do(q{
8920         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
8921         VALUES('FacetMaxCount', '20','Specify the max facet count for each category',NULL,'Integer')
8922     });
8923     print "Upgrade to $DBversion done (Bug 13088 - Allow the user to specify a max amount of facets to show)\n";
8924     SetVersion($DBversion);
8925 }
8926
8927 $DBversion = "3.17.00.034";
8928 if ( CheckVersion($DBversion) ) {
8929     $dbh->do(q|
8930         ALTER TABLE aqorders DROP COLUMN cancelledby;
8931     |);
8932
8933     print "Upgrade to $DBversion done (Bug 11007 - DROP column aqorders.cancelledby)\n";
8934     SetVersion($DBversion);
8935 }
8936
8937 $DBversion = "3.17.00.035";
8938 if ( CheckVersion($DBversion) ) {
8939     $dbh->do(q|
8940         ALTER TABLE serial ADD COLUMN claims_count INT(11) DEFAULT 0 after claimdate
8941     |);
8942     $dbh->do(q|
8943         UPDATE serial
8944         SET claims_count = 1
8945         WHERE claimdate IS NOT NULL
8946     |);
8947     print "Upgrade to $DBversion done (Bug 5342: Add claims_count field in serial table)\n";
8948     SetVersion($DBversion);
8949 }
8950
8951 $DBversion = "3.17.00.036";
8952 if ( CheckVersion($DBversion) ) {
8953     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacShowLibrariesPulldownMobile'");
8954     print "Upgrade to $DBversion done ( Bug 12513 - PROG/CCSR deprecation: Remove OpacShowLibrariesPulldownMobile system preference )\n";
8955     SetVersion ($DBversion);
8956 }
8957
8958 $DBversion = "3.17.00.037";
8959 if ( CheckVersion($DBversion) ) {
8960     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacMainUserBlockMobile'");
8961     print "Upgrade to $DBversion done ( Bug 12246 - PROG/CCSR deprecation: Remove OpacMainUserBlockMobile system preference )\n";
8962     SetVersion ($DBversion);
8963 }
8964
8965 $DBversion = "3.17.00.038";
8966 if ( CheckVersion($DBversion) ) {
8967     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACMobileUserCSS'");
8968     print "Upgrade to $DBversion done ( Bug 12245 - PROG/CCSR deprecation: Remove OPACMobileUserCSS system preference )\n";
8969     SetVersion ($DBversion);
8970 }
8971
8972 $DBversion = "3.17.00.039";
8973 if ( CheckVersion($DBversion) ) {
8974     $dbh->do("INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES
8975     ('OPACFallback', 'prog', 'bootstrap|prog', 'Define the fallback theme for the OPAC interface.', 'Themes')");
8976     print "Upgrade to $DBversion done (Bug 12539 - PROG/CCSR deprecation: Remove hardcoded theme from C4/Templates.pm)\n";
8977     SetVersion ($DBversion);
8978 }
8979
8980 $DBversion = "3.17.00.040";
8981 if ( CheckVersion($DBversion) ) {
8982     my $opac_theme = C4::Context->preference( 'opacthemes' );
8983     if ( !defined $opac_theme || $opac_theme eq 'prog' || $opac_theme eq 'ccsr' ) {
8984         $dbh->do("UPDATE systempreferences SET value='bootstrap' WHERE variable='opacthemes'");
8985     }
8986     print "Upgrade to $DBversion done (Bug 12223: 'prog' and 'ccsr' themes removed)\n";
8987     SetVersion($DBversion);
8988 }
8989
8990 $DBversion = "3.17.00.041";
8991 if ( CheckVersion($DBversion) ) {
8992     print "Upgrade to $DBversion done (Bug 11346: Deprecate the 'prog' and 'CCSR' themes)\n";
8993     SetVersion($DBversion);
8994 }
8995
8996 $DBversion = "3.17.00.042";
8997 if ( CheckVersion($DBversion) ) {
8998     $dbh->do("DELETE FROM systempreferences WHERE variable='yuipath'");
8999     print "Upgrade to $DBversion done (Bug 12494: Remove yuipath system preference)\n";
9000     SetVersion ($DBversion);
9001 }
9002
9003 $DBversion = "3.17.00.043";
9004 if ( CheckVersion($DBversion) ) {
9005     $dbh->do("
9006         ALTER TABLE aqorders
9007         ADD COLUMN cancellationreason TEXT DEFAULT NULL AFTER datecancellationprinted
9008     ");
9009     print "Upgrade to $DBversion done (Bug 7162: Add aqorders.cancellationreason)\n";
9010     SetVersion ($DBversion);
9011 }
9012
9013 $DBversion = "3.17.00.044";
9014 if ( CheckVersion($DBversion) ) {
9015     $dbh->do(q{
9016         INSERT IGNORE INTO systempreferences
9017             (variable,value,explanation,options,type)
9018             VALUES('OnSiteCheckouts','0','Enable/Disable the on-site checkouts feature','','YesNo');
9019     });
9020     $dbh->do(q{
9021         INSERT IGNORE INTO systempreferences
9022             (variable,value,explanation,options,type)
9023             VALUES('OnSiteCheckoutsForce','0','Enable/Disable the on-site for all cases (Even if a user is debarred, etc.)','','YesNo');
9024     });
9025     $dbh->do(q{
9026         ALTER TABLE issues ADD COLUMN onsite_checkout INT(1) NOT NULL DEFAULT 0 AFTER issuedate;
9027     });
9028     $dbh->do(q{
9029         ALTER TABLE old_issues ADD COLUMN onsite_checkout INT(1) NOT NULL DEFAULT 0 AFTER issuedate;
9030     });
9031     print "Upgrade to $DBversion done (Bug 10860: Add new system preference OnSiteCheckouts + fields [old_]issues.onsite_checkout)\n";
9032     SetVersion($DBversion);
9033 }
9034
9035 $DBversion = "3.17.00.045";
9036 if ( CheckVersion($DBversion) ) {
9037     $dbh->do(q{
9038         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
9039         ('LocalHoldsPriority',  '0', NULL,  'Enables the LocalHoldsPriority feature',  'YesNo'),
9040         ('LocalHoldsPriorityItemControl',  'holdingbranch',  'holdingbranch|homebranch',  'decides if the feature operates using the item''s home or holding library.',  'Choice'),
9041         ('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')
9042     });
9043     print "Upgrade to $DBversion done (Bug 11126 - Make the holds system optionally give precedence to local holds)\n";
9044     SetVersion($DBversion);
9045 }
9046
9047 $DBversion = "3.17.00.046";
9048 if ( CheckVersion($DBversion) ) {
9049     $dbh->do(q{
9050         CREATE TABLE IF NOT EXISTS items_search_fields (
9051           name VARCHAR(255) NOT NULL,
9052           label VARCHAR(255) NOT NULL,
9053           tagfield CHAR(3) NOT NULL,
9054           tagsubfield CHAR(1) NULL DEFAULT NULL,
9055           authorised_values_category VARCHAR(16) NULL DEFAULT NULL,
9056           PRIMARY KEY(name),
9057           CONSTRAINT items_search_fields_authorised_values_category
9058             FOREIGN KEY (authorised_values_category) REFERENCES authorised_values (category)
9059             ON DELETE SET NULL ON UPDATE CASCADE
9060         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
9061     });
9062     print "Upgrade to $DBversion done (Bug 11425: Add items_search_fields table)\n";
9063     SetVersion($DBversion);
9064 }
9065
9066 $DBversion = "3.17.00.047";
9067 if ( CheckVersion($DBversion) ) {
9068     $dbh->do(q{
9069         ALTER TABLE collections
9070             CHANGE colBranchcode colBranchcode VARCHAR( 10 ) NULL DEFAULT NULL,
9071             ADD INDEX ( colBranchcode ),
9072             ADD CONSTRAINT collections_ibfk_1 FOREIGN KEY (colBranchcode) REFERENCES branches (branchcode) ON DELETE CASCADE ON UPDATE CASCADE
9073     });
9074     print "Upgrade to $DBversion done (Bug 8836 - Resurrect Rotating Collections)\n";
9075     SetVersion($DBversion);
9076 }
9077
9078 $DBversion = "3.17.00.048";
9079 if ( CheckVersion($DBversion) ) {
9080     $dbh->do(q|
9081         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')
9082     |);
9083     print "Upgrade to $DBversion done (Bug 12448 - Add RentalFeesCheckoutConfirmation syspref)\n";
9084     SetVersion($DBversion);
9085 }
9086
9087 $DBversion = "3.17.00.049";
9088 if ( CheckVersion($DBversion) ) {
9089     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'am', 'language', 'Amharic','2014-10-29')");
9090     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'am','amh')");
9091     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'am', 'language', 'am', 'አማርኛ')");
9092     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'am', 'language', 'en', 'Amharic')");
9093
9094     $dbh->do("UPDATE language_descriptions SET description = 'لعربية' WHERE subtag = 'ar' AND type = 'language' AND lang = 'ar'");
9095
9096     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'az', 'language', 'Azerbaijani','2014-10-30')");
9097     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'az','aze')");
9098     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'az', 'language', 'az', 'Azərbaycan dili')");
9099     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'az', 'language', 'en', 'Azerbaijani')");
9100
9101     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'be', 'language', 'Byelorussian','2014-10-30')");
9102     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'be','bel')");
9103     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'be', 'language', 'be', 'Беларуская мова')");
9104     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'be', 'language', 'en', 'Byelorussian')");
9105
9106     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'bn', 'language', 'Bengali','2014-10-30')");
9107     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'bn','ben')");
9108     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'bn', 'language', 'bn', 'বাংলা')");
9109     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'bn', 'language', 'en', 'Bengali')");
9110
9111     $dbh->do("UPDATE language_descriptions SET description = 'Български' WHERE subtag = 'bg' AND type = 'language' AND lang = 'bg'");
9112     $dbh->do("UPDATE language_descriptions SET description = 'Ceština' WHERE subtag = 'cs' AND type = 'language' AND lang = 'cs'");
9113     $dbh->do("UPDATE language_descriptions SET description = 'Ελληνικά' WHERE subtag = 'el' AND type = 'language' AND lang = 'el'");
9114     $dbh->do("UPDATE language_descriptions SET description = 'Español' WHERE subtag = 'es' AND type = 'language' AND lang = 'es'");
9115
9116     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'eu', 'language', 'Basque','2014-10-30')");
9117     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'eu','eus')");
9118     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'eu', 'language', 'eu', 'Euskera')");
9119     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'eu', 'language', 'en', 'Basque')");
9120
9121     $dbh->do("UPDATE language_descriptions SET description = 'فارسى' WHERE subtag = 'fa' AND type = 'language' AND lang = 'fa'");
9122     $dbh->do("UPDATE language_descriptions SET description = 'Suomi' WHERE subtag = 'fi' AND type = 'language' AND lang = 'fi'");
9123
9124     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'fo', 'language', 'Faroese','2014-10-30')");
9125     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'fo','fao')");
9126     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'fo', 'language', 'fo', 'Føroyskt')");
9127     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'fo', 'language', 'en', 'Faroese')");
9128
9129     $dbh->do("UPDATE language_descriptions SET description = 'Français' WHERE subtag = 'fr' AND type = 'language' AND lang = 'fr'");
9130     $dbh->do("UPDATE language_descriptions SET description = 'עִבְרִית' WHERE subtag = 'he' AND type = 'language' AND lang = 'he'");
9131     $dbh->do("UPDATE language_descriptions SET description = 'हिन्दी' WHERE subtag = 'hi' AND type = 'language' AND lang = 'hi'");
9132
9133     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'is', 'language', 'Icelandic','2014-10-30')");
9134     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'is','ice')");
9135     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'is', 'language', 'is', 'Íslenska')");
9136     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'is', 'language', 'en', 'Icelandic')");
9137
9138     $dbh->do("UPDATE language_descriptions SET description = '日本語' WHERE subtag = 'ja' AND type = 'language' AND lang = 'ja'");
9139
9140     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ka', 'language', 'Kannada','2014-10-30')");
9141     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ka','kan')");
9142     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'ka', 'ಕನ್ನಡ')");
9143     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'en', 'Kannada')");
9144
9145     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'km', 'language', 'Khmer','2014-10-30')");
9146     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'km','khm')");
9147     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'km', 'language', 'km', 'ភាសាខ្មែរ')");
9148     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'km', 'language', 'en', 'Khmer')");
9149
9150     $dbh->do("UPDATE language_descriptions SET description = '한국어' WHERE subtag = 'ko' AND type = 'language' AND lang = 'ko'");
9151
9152     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ku', 'language', 'Kurdish','2014-05-13')");
9153     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ku','kur')");
9154     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'ku', 'کوردی')");
9155     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'en', 'Kurdish')");
9156     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'fr', 'Kurde')");
9157     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'de', 'Kurdisch')");
9158     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'es', 'Kurdo')");
9159
9160     $dbh->do("UPDATE language_descriptions SET description = 'ພາສາລາວ' WHERE subtag = 'lo' AND type = 'language' AND lang = 'lo'");
9161
9162     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mi', 'language', 'Maori','2014-10-30')");
9163     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mi','mri')");
9164     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mi', 'language', 'mi', 'Te Reo Māori')");
9165     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mi', 'language', 'en', 'Maori')");
9166
9167     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mn', 'language', 'Mongolian','2014-10-30')");
9168     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mn','mon')");
9169     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mn', 'language', 'mn', 'Mонгол')");
9170     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mn', 'language', 'en', 'Mongolian')");
9171
9172     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mr', 'language', 'Marathi','2014-10-30')");
9173     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mr','mar')");
9174     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mr', 'language', 'mr', 'मराठी')");
9175     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mr', 'language', 'en', 'Marathi')");
9176
9177     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ms', 'language', 'Malay','2014-10-30')");
9178     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ms','may')");
9179     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ms', 'language', 'ms', 'Bahasa melayu')");
9180     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ms', 'language', 'en', 'Malay')");
9181
9182     $dbh->do("UPDATE language_descriptions SET description = 'Norsk bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'nb'");
9183     $dbh->do("UPDATE language_descriptions SET description = 'Norwegian bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'en'");
9184     $dbh->do("UPDATE language_descriptions SET description = 'Norvégien bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'fr'");
9185     $dbh->do("UPDATE language_descriptions SET description = 'Norwegisch bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'de'");
9186
9187     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ne', 'language', 'Nepali','2014-10-30')");
9188     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ne','nep')");
9189     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)VALUES ( 'ne', 'language', 'ne', 'नेपाली')");
9190     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ne', 'language', 'en', 'Nepali')");
9191
9192     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'pbr', 'language', 'Pangwa','2014-10-30')");
9193     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'pbr','pbr')");
9194     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'pbr', 'language', 'pbr', 'Ekipangwa')");
9195     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'pbr', 'language', 'en', 'Pangwa')");
9196
9197     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'prs', 'language', 'Dari','2014-10-30')");
9198     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'prs','prs')");
9199     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'prs', 'language', 'prs', 'درى')");
9200     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'prs', 'language', 'en', 'Dari')");
9201
9202     $dbh->do("UPDATE language_descriptions SET description = 'Português' WHERE subtag = 'pt' AND type = 'language' AND lang = 'pt'");
9203     $dbh->do("UPDATE language_descriptions SET description = 'Român' WHERE subtag = 'ro' AND type = 'language' AND lang = 'ro'");
9204     $dbh->do("UPDATE language_descriptions SET description = 'Русский' WHERE subtag = 'ru' AND type = 'language' AND lang = 'ru'");
9205
9206     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'rw', 'language', 'Kinyarwanda','2014-10-30')");
9207     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'rw','kin')");
9208     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'rw', 'language', 'rw', 'Ikinyarwanda')");
9209     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'rw', 'language', 'en', 'Kinyarwanda')");
9210
9211     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sd', 'language', 'Sindhi','2014-10-30')");
9212     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sd','snd')");
9213     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sd', 'language', 'sd', 'سنڌي')");
9214     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sd', 'language', 'en', 'Sindhi')");
9215
9216     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sk', 'language', 'Slovak','2014-10-30')");
9217     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sk','slk')");
9218     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sk', 'language', 'sk', 'Slovenčina')");
9219     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sk', 'language', 'en', 'Slovak')");
9220
9221     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sl', 'language', 'Slovene','2014-10-30')");
9222     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sl','slv')");
9223     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sl', 'language', 'sl', 'Slovenščina')");
9224     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sl', 'language', 'en', 'Slovene')");
9225
9226     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sq', 'language', 'Albanian','2014-10-30')");
9227     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sq','sqi')");
9228     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sq', 'language', 'sq', 'Shqip')");
9229     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sq', 'language', 'en', 'Albanian')");
9230
9231     $dbh->do("UPDATE language_descriptions SET description = 'Cрпски' WHERE subtag = 'sr' AND type = 'language' AND lang = 'sr'");
9232
9233     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sw', 'language', 'Swahili','2014-10-30')");
9234     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sw','swa')");
9235     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sw', 'language', 'sw', 'Kiswahili')");
9236     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sw', 'language', 'en', 'Swahili')");
9237
9238     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ta', 'language', 'Tamil','2014-10-30')");
9239     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ta','tam')");
9240     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ta', 'language', 'ta', 'தமிழ்')");
9241     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ta', 'language', 'en', 'Tamil')");
9242
9243     $dbh->do("UPDATE language_descriptions SET description = 'Tetun' WHERE subtag = 'tet' AND type = 'language' AND lang = 'tet'");
9244     $dbh->do("UPDATE language_descriptions SET description = 'ภาษาไทย' WHERE subtag = 'th' AND type = 'language' AND lang = 'th'");
9245
9246     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'tl', 'language', 'Tagalog','2014-10-30')");
9247     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'tl','tgl')");
9248     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'tl', 'language', 'tl', 'Tagalog')");
9249     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'tl', 'language', 'en', 'Tagalog')");
9250
9251     $dbh->do("UPDATE language_descriptions SET description = 'Türkçe' WHERE subtag = 'tr' AND type = 'language' AND lang = 'tr'");
9252     $dbh->do("UPDATE language_descriptions SET description = 'Українська' WHERE subtag = 'uk' AND type = 'language' AND lang = 'uk'");
9253     $dbh->do("UPDATE language_descriptions SET description = 'اردو' WHERE subtag = 'ur' AND type = 'language' AND lang = 'ur'");
9254
9255     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'vi', 'language', 'Vietnamese','2014-10-30')");
9256     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'vi','vie')");
9257     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'vi', 'language', 'vi', '㗂越')");
9258     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'vi', 'language', 'en', 'Vietnamese')");
9259
9260     $dbh->do("UPDATE language_descriptions SET description = '中文' WHERE subtag = 'zh' AND type = 'language' AND lang = 'zh'");
9261     $dbh->do("UPDATE language_descriptions SET description = '' WHERE subtag = 'Arab,script' AND type = 'Arab' AND lang = 'العربية'");
9262
9263     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Armn', 'script', 'Armenian','2014-10-30')");
9264     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Armn', 'script', 'Armn', 'Հայոց այբուբեն')");
9265     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Armn', 'script', 'en', 'Armenian')");
9266
9267     $dbh->do("UPDATE language_descriptions SET description = 'Кирилица' WHERE subtag = 'Cyrl' AND type = 'script' AND lang = 'Cyrl'");
9268
9269     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Ethi', 'script', 'Ethiopic','2014-10-30')");
9270     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Ethi', 'script', 'Ethi', 'ግዕዝ')");
9271     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Ethi', 'script', 'en', 'Ethiopic')");
9272
9273     $dbh->do("UPDATE language_descriptions SET description = 'Ελληνικό αλφάβητο' WHERE subtag = 'Grek' AND type = 'script' AND lang = 'Grek'");
9274     $dbh->do("UPDATE language_descriptions SET description = '简体字' WHERE subtag = 'Hans' AND type = 'script' AND lang = 'Hans'");
9275     $dbh->do("UPDATE language_descriptions SET description = '繁體字' WHERE subtag = 'Hant' AND type = 'script' AND lang = 'Hant'");
9276     $dbh->do("UPDATE language_descriptions SET description = 'אָלֶף־בֵּית עִבְרִי' WHERE subtag = 'Hebr' AND type = 'script' AND lang = 'Hebr'");
9277
9278     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Jpan', 'script', 'Japanese','2014-10-30')");
9279     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Jpan', 'script', 'Jpan', '漢字')");
9280     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Jpan', 'script', 'en', 'Japanese')");
9281
9282     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Knda', 'script', 'Kannada','2014-10-30')");
9283     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Knda', 'script', 'Knda', 'ಕನ್ನಡ ಲಿಪಿ')");
9284     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Knda', 'script', 'en', 'Kannada')");
9285
9286     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Kore', 'script', 'Korean','2014-10-30')");
9287     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Kore', 'script', 'Kore', '한글')");
9288     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Kore', 'script', 'en', 'Korean')");
9289
9290     $dbh->do("UPDATE language_descriptions SET description = 'ອັກສອນລາວ' WHERE subtag = 'Laoo' AND type = 'script' AND lang = 'Laoo'");
9291
9292     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'AL', 'region', 'Albania','2014-10-30')");
9293     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AL', 'region', 'en', 'Albania')");
9294     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AL', 'region', 'sq', 'Shqipërisë')");
9295
9296     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'AZ', 'region', 'Azerbaijan','2014-10-30')");
9297     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AZ', 'region', 'en', 'Azerbaijan')");
9298     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AZ', 'region', 'az', 'Azərbaycan')");
9299
9300     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BE', 'region', 'Belgium','2014-10-30')");
9301     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BE', 'region', 'en', 'Belgium')");
9302     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BE', 'region', 'nl', 'België')");
9303
9304     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BR', 'region', 'Brazil','2014-10-30')");
9305     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BR', 'region', 'en', 'Brazil')");
9306     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BR', 'region', 'pt', 'Brasil')");
9307
9308     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BY', 'region', 'Belarus','2014-10-30')");
9309     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BY', 'region', 'en', 'Belarus')");
9310     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BY', 'region', 'be', 'Беларусь')");
9311
9312     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CA', 'region', 'fr', 'Canada')");
9313
9314     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CH', 'region', 'Switzerland','2014-10-30')");
9315     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CH', 'region', 'en', 'Switzerland')");
9316     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CH', 'region', 'de', 'Schweiz')");
9317
9318     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CN', 'region', 'China','2014-10-30')");
9319     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CN', 'region', 'en', 'China')");
9320     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CN', 'region', 'zh', '中国')");
9321
9322     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CZ', 'region', 'Czech Republic','2014-10-30')");
9323     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CZ', 'region', 'en', 'Czech Republic')");
9324     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CZ', 'region', 'cs', 'Česká republika')");
9325
9326     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'DE', 'region', 'Germany','2014-10-30')");
9327     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DE', 'region', 'en', 'Germany')");
9328     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DE', 'region', 'de', 'Deutschland')");
9329
9330     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DK', 'region', 'en', 'Denmark')");
9331
9332     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ES', 'region', 'Spain','2014-10-30')");
9333     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ES', 'region', 'en', 'Spain')");
9334     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ES', 'region', 'es', 'España')");
9335
9336     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'FI', 'region', 'Finland','2014-10-30')");
9337     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FI', 'region', 'en', 'Finland')");
9338     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FI', 'region', 'fi', 'Suomi')");
9339
9340     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'FO', 'region', 'Faroe Islands','2014-10-30')");
9341     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FO', 'region', 'en', 'Faroe Islands')");
9342     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FO', 'region', 'fo', 'Føroyar')");
9343
9344     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'GR', 'region', 'Greece','2014-10-30')");
9345     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'GR', 'region', 'en', 'Greece')");
9346     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'GR', 'region', 'el', 'Ελλάδα')");
9347
9348     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'HR', 'region', 'Croatia','2014-10-30')");
9349     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HR', 'region', 'en', 'Croatia')");
9350     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HR', 'region', 'hr', 'Hrvatska')");
9351
9352     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'HU', 'region', 'Hungary','2014-10-30')");
9353     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HU', 'region', 'en', 'Hungary')");
9354     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HU', 'region', 'hu', 'Magyarország')");
9355
9356     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ID', 'region', 'Indonesia','2014-10-30')");
9357     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ID', 'region', 'en', 'Indonesia')");
9358     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ID', 'region', 'id', 'Indonesia')");
9359
9360     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'IS', 'region', 'Iceland','2014-10-30')");
9361     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IS', 'region', 'en', 'Iceland')");
9362     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IS', 'region', 'is', 'Ísland')");
9363
9364     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'IT', 'region', 'Italy','2014-10-30')");
9365     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IT', 'region', 'en', 'Italy')");
9366     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IT', 'region', 'it', 'Italia')");
9367
9368     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'JP', 'region', 'Japan','2014-10-30')");
9369     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'JP', 'region', 'en', 'Japan')");
9370     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'JP', 'region', 'ja', '日本')");
9371
9372     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KE', 'region', 'Kenya','2014-10-30')");
9373     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KE', 'region', 'en', 'Kenya')");
9374     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KE', 'region', 'rw', 'Kenya')");
9375
9376     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KH', 'region', 'Cambodia','2014-10-30')");
9377     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KH', 'region', 'en', 'Cambodia')");
9378     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KH', 'region', 'km', 'កម្ពុជា')");
9379
9380     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KP', 'region', 'North Korea','2014-10-30')");
9381     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KP', 'region', 'en', 'North Korea')");
9382     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KP', 'region', 'ko', '조선민주주의인민공화국')");
9383
9384     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'LK', 'region', 'Sri Lanka','2014-10-30')");
9385     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'LK', 'region', 'en', 'Sri Lanka')");
9386     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'LK', 'region', 'ta', 'இலங்கை')");
9387
9388     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'MY', 'region', 'Malaysia','2014-10-30')");
9389     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'MY', 'region', 'en', 'Malaysia')");
9390     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'MY', 'region', 'ms', 'Malaysia')");
9391
9392     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NE', 'region', 'Niger','2014-10-30')");
9393     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NE', 'region', 'en', 'Niger')");
9394     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NE', 'region', 'ne', 'Niger')");
9395
9396     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NL', 'region', 'Netherlands','2014-10-30')");
9397     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NL', 'region', 'en', 'Netherlands')");
9398     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NL', 'region', 'nl', 'Nederland')");
9399
9400     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NO', 'region', 'Norway','2014-10-30')");
9401     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'en', 'Norway')");
9402     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'ne', 'Noreg')");
9403     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'nn', 'Noreg')");
9404
9405     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PH', 'region', 'Philippines','2014-10-30')");
9406     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PH', 'region', 'en', 'Philippines')");
9407     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PH', 'region', 'tl', 'Pilipinas')");
9408
9409     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PK', 'region', 'Pakistan','2014-10-30')");
9410     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PK', 'region', 'en', 'Pakistan')");
9411     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PK', 'region', 'sd', 'پاكستان')");
9412
9413     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PL', 'region', 'Poland','2014-10-30')");
9414     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PL', 'region', 'en', 'Poland')");
9415     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PL', 'region', 'pl', 'Polska')");
9416
9417     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PT', 'region', 'Portugal','2014-10-30')");
9418     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PT', 'region', 'en', 'Portugal')");
9419     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PT', 'region', 'pt', 'Portugal')");
9420
9421     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RO', 'region', 'Romania','2014-10-30')");
9422     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RO', 'region', 'en', 'Romania')");
9423     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RO', 'region', 'ro', 'România')");
9424
9425     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RU', 'region', 'Russia','2014-10-30')");
9426     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RU', 'region', 'en', 'Russia')");
9427     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RU', 'region', 'ru', 'Россия')");
9428
9429     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RW', 'region', 'Rwanda','2014-10-30')");
9430     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RW', 'region', 'en', 'Rwanda')");
9431     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RW', 'region', 'rw', 'Rwanda')");
9432
9433     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SE', 'region', 'Sweden','2014-10-30')");
9434     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SE', 'region', 'en', 'Sweden')");
9435     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SE', 'region', 'sv', 'Sverige')");
9436
9437     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SI', 'region', 'Slovenia','2014-10-30')");
9438     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SI', 'region', 'en', 'Slovenia')");
9439     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SI', 'region', 'sl', 'Slovenija')");
9440
9441     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SK', 'region', 'Slovakia','2014-10-30')");
9442     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SK', 'region', 'en', 'Slovakia')");
9443     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SK', 'region', 'sk', 'Slovensko')");
9444
9445     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TH', 'region', 'Thailand','2014-10-30')");
9446     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TH', 'region', 'en', 'Thailand')");
9447     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TH', 'region', 'th', 'ประเทศไทย')");
9448
9449     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TR', 'region', 'Turkey','2014-10-30')");
9450     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TR', 'region', 'en', 'Turkey')");
9451     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TR', 'region', 'tr', 'Türkiye')");
9452
9453     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TW', 'region', 'Taiwan','2014-10-30')");
9454     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TW', 'region', 'en', 'Taiwan')");
9455     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TW', 'region', 'zh', '台灣')");
9456
9457     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'UA', 'region', 'Ukraine','2014-10-30')");
9458     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'UA', 'region', 'en', 'Ukraine')");
9459     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'UA', 'region', 'uk', 'Україна')");
9460
9461     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'VN', 'region', 'Vietnam','2014-10-30')");
9462     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'VN', 'region', 'en', 'Vietnam')");
9463     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'VN', 'region', 'vi', 'Việt Nam')");
9464
9465     print "Upgrade to $DBversion done (Bug 12250: Update descriptions for languages, scripts and regions)\n";
9466     SetVersion($DBversion);
9467 }
9468
9469 $DBversion = "3.17.00.050";
9470 if ( CheckVersion($DBversion) ) {
9471     $dbh->do(q|
9472         INSERT INTO permissions (module_bit, code, description) VALUES
9473           (13, 'records_batchdel', 'Perform batch deletion of records (bibliographic or authority)')
9474     |);
9475     print "Upgrade to $DBversion done (Bug 12403: Add permission tools_records_batchdelitem)\n";
9476     SetVersion($DBversion);
9477 }
9478
9479 $DBversion = "3.17.00.051";
9480 if ( CheckVersion($DBversion) ) {
9481     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('GoogleIndicTransliteration','0','','GoogleIndicTransliteration on the OPAC.','YesNo')");
9482     print "Upgrade to $DBversion done (Bug 13211: Added system preferences GoogleIndicTransliteration on the OPAC)\n";
9483     SetVersion($DBversion);
9484 }
9485
9486 $DBversion = "3.17.00.052";
9487 if ( CheckVersion($DBversion) ) {
9488     $dbh->do(q{
9489         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');
9490     });
9491
9492     $dbh->do(q{
9493         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');
9494    });
9495    print "Upgrade to $DBversion done (Bug 9043: Add system preference OpacAdvSearchOptions and OpacAdvSearchMoreOptions)\n";
9496    SetVersion ($DBversion);
9497 }
9498
9499 $DBversion = "3.17.00.053";
9500 if ( CheckVersion($DBversion) ) {
9501     $dbh->do(q{
9502         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)');
9503     });
9504
9505     $dbh->do(q{
9506         INSERT INTO permissions (module_bit, code, description) VALUES ('9', 'delete_all_items', 'Delete all items at once');
9507     });
9508
9509     $dbh->do(q{
9510         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)');
9511     });
9512
9513     # The delete_all_items permission should be added to users having the edit_items permission.
9514     $dbh->do(q{
9515         INSERT INTO user_permissions (borrowernumber, module_bit, code) SELECT borrowernumber, module_bit, "delete_all_items" FROM user_permissions WHERE code="edit_items";
9516     });
9517
9518     # Add 2 new prefs
9519     $dbh->do(q{
9520         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');
9521     });
9522
9523     $dbh->do(q{
9524         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');
9525     });
9526
9527     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";
9528     SetVersion($DBversion);
9529 }
9530
9531 $DBversion = "3.17.00.054";
9532 if (CheckVersion($DBversion)) {
9533     $dbh->do(q{
9534         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
9535         ('AllowRenewalIfOtherItemsAvailable','0',NULL,'If enabled, allow a patron to renew an item with unfilled holds if other available items can fill that hold.','YesNo')
9536     });
9537     print "Upgrade to $DBversion done (Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds)\n";
9538     SetVersion($DBversion);
9539 }
9540
9541 $DBversion = "3.17.00.055";
9542 if ( CheckVersion($DBversion) ) {
9543     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBEnable', '0', NULL, 'Enable communication with the Norwegian national patron database.', 'YesNo')");
9544     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBEndpoint', '', NULL, 'Which NL endpoint to use.', 'Free')");
9545     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBUsername', '', NULL, 'Username for communication with the Norwegian national patron database.', 'Free')");
9546     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBPassword', '', NULL, 'Password for communication with the Norwegian national patron database.', 'Free')");
9547     $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')");
9548     $dbh->do("
9549 CREATE TABLE borrower_sync (
9550     borrowersyncid int(11) NOT NULL AUTO_INCREMENT,
9551     borrowernumber int(11) NOT NULL,
9552     synctype varchar(32) NOT NULL,
9553     sync tinyint(1) NOT NULL DEFAULT '0',
9554     syncstatus varchar(10) DEFAULT NULL,
9555     lastsync varchar(50) DEFAULT NULL,
9556     hashed_pin varchar(64) DEFAULT NULL,
9557     PRIMARY KEY (borrowersyncid),
9558     KEY borrowernumber (borrowernumber),
9559     CONSTRAINT borrower_sync_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
9560 ) ENGINE=InnoDB DEFAULT CHARSET=utf8"
9561 );
9562     print "Upgrade to $DBversion done (Bug 11401 - Add support for Norwegian national library card)\n";
9563     SetVersion($DBversion);
9564 }
9565
9566 $DBversion = "3.17.00.056";
9567 if ( CheckVersion($DBversion) ) {
9568     $dbh->do(q{
9569         UPDATE systempreferences SET value = 'pubdate,itemtype,language,sorting,location' WHERE variable='OpacAdvSearchOptions'
9570     });
9571
9572     $dbh->do(q{
9573         UPDATE systempreferences SET value = 'pubdate,itemtype,language,subtype,sorting,location' WHERE variable='OpacAdvSearchMoreOptions'
9574     });
9575
9576     print "Upgrade to $DBversion done (Bug 9043 - Update the values for OpacAdvSearchOptions and OpacAdvSearchOptions)\n";
9577     SetVersion($DBversion);
9578 }
9579
9580 $DBversion = "3.17.00.057";
9581 if ( CheckVersion($DBversion) ) {
9582     print "Upgrade to $DBversion done (Koha 3.18 beta)\n";
9583     SetVersion ($DBversion);
9584 }
9585
9586 $DBversion = "3.17.00.058";
9587 if( CheckVersion($DBversion) ){
9588     $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')");
9589     $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')");
9590     $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')");
9591     print "Upgrade to $DBversion done (Bug 8337: System preferences for longoverdue cron)\n";
9592     SetVersion($DBversion);
9593 }
9594
9595 $DBversion = "3.17.00.059";
9596 if ( CheckVersion($DBversion) ) {
9597     $dbh->do(q{
9598         UPDATE permissions SET description = "Add and delete budgets (but can't modifiy budgets)" WHERE description = "Add and delete budgets (but cant modify budgets)";
9599     });
9600     print "Upgrade to $DBversion done (Bug 10749: Fix typo in budget_add_del permission description)\n";
9601     SetVersion ($DBversion);
9602 }
9603
9604 $DBversion = "3.17.00.060";
9605 if ( CheckVersion($DBversion) ) {
9606     my $count_l = $dbh->selectcol_arrayref(q|
9607         SELECT COUNT(*) FROM letter WHERE message_transport_type='feed'
9608     |);
9609     my $count_mq = $dbh->selectcol_arrayref(q|
9610         SELECT COUNT(*) FROM message_queue WHERE message_transport_type='feed'
9611     |);
9612     my $count_ott = $dbh->selectcol_arrayref(q|
9613         SELECT COUNT(*) FROM overduerules_transport_types WHERE message_transport_type='feed'
9614     |);
9615     my $count_mt = $dbh->selectcol_arrayref(q|
9616         SELECT COUNT(*) FROM message_transports WHERE message_transport_type='feed'
9617     |);
9618     my $count_bmtp = $dbh->selectcol_arrayref(q|
9619         SELECT COUNT(*) FROM borrower_message_transport_preferences WHERE message_transport_type='feed'
9620     |);
9621
9622     my $deleted = 0;
9623     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 ) {
9624         $deleted = $dbh->do(q|
9625             DELETE FROM message_transport_types where message_transport_type='feed'
9626         |);
9627         $deleted = $deleted ne '0E0' ? 1 : 0;
9628     }
9629
9630     print "Upgrade to $DBversion done (Bug 12298: Delete the 'feed' message transport type " . ($deleted ? '(deleted!)' : '(not deleted)') . ")\n";
9631     SetVersion($DBversion);
9632 }
9633
9634 $DBversion = "3.18.00.000";
9635 if ( CheckVersion($DBversion) ) {
9636     print "Upgrade to $DBversion done (3.18.0 release)\n";
9637     SetVersion($DBversion);
9638 }
9639
9640 $DBversion = "3.19.00.000";
9641 if ( CheckVersion($DBversion) ) {
9642     print "Upgrade to $DBversion done (there's life after 3.18)\n";
9643     SetVersion ($DBversion);
9644 }
9645
9646 $DBversion = "3.19.00.001";
9647 if ( CheckVersion($DBversion) ) {
9648     $dbh->do("
9649         UPDATE systempreferences
9650         SET options = 'public|school|academic|research|private|societyAssociation|corporate|government|religiousOrg|subscription'
9651         WHERE variable = 'UsageStatsLibraryType'
9652     ");
9653     if ( C4::Context->preference("UsageStatsLibraryType") eq "university" ) {
9654         C4::Context->set_preference("UsageStatsLibraryType", "academic")
9655     }
9656     print "Upgrade to $DBversion done (Bug 13436: Add more options to UsageStatsLibraryType)\n";
9657     SetVersion ($DBversion);
9658 }
9659
9660 $DBversion = "3.19.00.002";
9661 if ( CheckVersion($DBversion) ) {
9662     $dbh->do(q|
9663         UPDATE suggestions SET branchcode="" WHERE branchcode="__ANY__"
9664     |);
9665     print "upgrade to $DBversion done (Bug 10753: replace __ANY__ with empty string in suggestions.branchcode)\n";
9666     SetVersion ($DBversion);
9667 }
9668
9669 $DBversion = "3.19.00.003";
9670 if ( CheckVersion($DBversion) ) {
9671     my ($count) = $dbh->selectrow_array("SELECT COUNT(*) FROM borrowers GROUP BY userid HAVING COUNT(userid) > 1");
9672
9673     if ( $count ) {
9674         print "Upgrade to $DBversion done (Bug 1861 - Unique patrons logins not (totally) enforced) FAILED!\n";
9675         print "Your database has users with duplicate user logins. Please have your administrator deduplicate your user logins.\n";
9676         print "Afterward, your Koha administrator should execute the following database query: ALTER TABLE borrowers DROP INDEX userid, ADD UNIQUE userid (userid)";
9677     } else {
9678         $dbh->do(q{
9679             ALTER TABLE borrowers
9680                 DROP INDEX userid ,
9681                 ADD UNIQUE userid (userid)
9682         });
9683         print "Upgrade to $DBversion done (Bug 1861: Unique patrons logins not (totally) enforced)\n";
9684     }
9685     SetVersion ($DBversion);
9686 }
9687
9688 $DBversion = "3.19.00.004";
9689 if ( CheckVersion($DBversion) ) {
9690     my $pref_value = C4::Context->preference('OpacExportOptions');
9691     $pref_value =~ s/\|/,/g; # multiple is separated by ,
9692     $dbh->do(q{
9693         UPDATE systempreferences
9694             SET value = ?,
9695                 type = 'multiple'
9696         WHERE variable = 'OpacExportOptions'
9697     }, {}, $pref_value );
9698     print "Upgrade to $DBversion done (Bug 13346: OpacExportOptions is now multiple)\n";
9699     SetVersion ($DBversion);
9700 }
9701
9702 $DBversion = "3.19.00.005";
9703 if(CheckVersion($DBversion)) {
9704     $dbh->do(q{
9705         ALTER TABLE authorised_values MODIFY COLUMN category VARCHAR(32) NOT NULL DEFAULT ''
9706     });
9707
9708     $dbh->do(q{
9709         ALTER TABLE borrower_attribute_types MODIFY COLUMN authorised_value_category VARCHAR(32) DEFAULT NULL
9710     });
9711
9712     print "Upgrade to $DBversion done (Bug 13379: Modify authorised_values.category to varchar(32))\n";
9713     SetVersion($DBversion);
9714 }
9715
9716 $DBversion = "3.19.00.006";
9717 if ( CheckVersion($DBversion) ) {
9718     $dbh->do(q|SET foreign_key_checks = 0|);
9719     my $sth = $dbh->table_info( '','','','TABLE' );
9720     my ( $cat, $schema, $name, $type, $remarks );
9721     while ( ( $cat, $schema, $name, $type, $remarks ) = $sth->fetchrow_array ) {
9722         my $table_sth = $dbh->prepare(qq|SHOW CREATE TABLE $name|);
9723         $table_sth->execute;
9724         my @table = $table_sth->fetchrow_array;
9725         unless ( $table[1] =~ /COLLATE=utf8mb4_unicode_ci/ ) { #catches utf8mb4 collated tables
9726             if ( $name eq 'marc_subfield_structure' ) {
9727                 $dbh->do(q|
9728                     ALTER TABLE marc_subfield_structure
9729                     MODIFY COLUMN tagfield varchar(3) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9730                     MODIFY COLUMN tagsubfield varchar(1) COLLATE utf8_bin NOT NULL DEFAULT '',
9731                     MODIFY COLUMN liblibrarian varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9732                     MODIFY COLUMN libopac varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9733                     MODIFY COLUMN kohafield varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
9734                     MODIFY COLUMN authorised_value varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
9735                     MODIFY COLUMN authtypecode varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
9736                     MODIFY COLUMN value_builder varchar(80) COLLATE utf8_unicode_ci DEFAULT NULL,
9737                     MODIFY COLUMN frameworkcode varchar(4) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9738                     MODIFY COLUMN seealso varchar(1100) COLLATE utf8_unicode_ci DEFAULT NULL,
9739                     MODIFY COLUMN link varchar(80) COLLATE utf8_unicode_ci DEFAULT NULL
9740                 |);
9741                 $dbh->do(qq|ALTER TABLE $name CHARACTER SET utf8 COLLATE utf8_unicode_ci|);
9742             }
9743             else {
9744                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci|);
9745             }
9746         }
9747     }
9748     $dbh->do(q|SET foreign_key_checks = 1|);;
9749
9750     print "Upgrade to $DBversion done (Bug 11944: Convert DB tables to utf8_unicode_ci)\n";
9751     SetVersion($DBversion);
9752 }
9753
9754 $DBversion = "3.19.00.007";
9755 if ( CheckVersion($DBversion) ) {
9756     my $orphan_budgets = $dbh->selectall_arrayref(q|
9757         SELECT budget_id, budget_name, budget_code
9758         FROM aqbudgets
9759         WHERE   budget_parent_id IS NOT NULL
9760             AND budget_parent_id NOT IN (
9761                 SELECT DISTINCT budget_id FROM aqbudgets
9762             )
9763     |, { Slice => {} } );
9764
9765     if ( @$orphan_budgets ) {
9766         for my $b ( @$orphan_budgets ) {
9767             print "Fund $b->{budget_name} (code:$b->{budget_code}, id:$b->{budget_id}) does not have a parent, it may cause problem\n";
9768         }
9769         print "Upgrade to $DBversion done (Bug 12905: Check budget integrity: FAIL)\n";
9770     } else {
9771         print "Upgrade to $DBversion done (Bug 12905: Check budget integrity: OK)\n";
9772     }
9773     SetVersion ($DBversion);
9774 }
9775
9776 $DBversion = "3.19.00.008";
9777 if ( CheckVersion($DBversion) ) {
9778     my $number_of_orders_not_linked = $dbh->selectcol_arrayref(q|
9779         SELECT COUNT(*)
9780         FROM aqorders o
9781         WHERE NOT EXISTS (
9782             SELECT NULL
9783             FROM aqbudgets b
9784             WHERE b.budget_id = o.budget_id
9785         );
9786     |);
9787
9788     if ( $number_of_orders_not_linked->[0] > 0 ) {
9789         $dbh->do(q|
9790             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)
9791         |);
9792         my $budget_period_id = $dbh->last_insert_id( undef, undef, 'aqbudgetperiods', undef );
9793         $dbh->do(qq|
9794             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 );
9795         |);
9796         my $budget_id = $dbh->last_insert_id( undef, undef, 'aqbudgets', undef );
9797         $dbh->do(qq|
9798             UPDATE aqorders o
9799             SET budget_id = $budget_id
9800             WHERE NOT EXISTS (
9801                 SELECT NULL
9802                 FROM aqbudgets b
9803                 WHERE b.budget_id = o.budget_id
9804             )
9805         |);
9806     }
9807
9808     $dbh->do(q|
9809         ALTER TABLE aqorders
9810         ADD CONSTRAINT aqorders_budget_id_fk FOREIGN KEY (budget_id) REFERENCES aqbudgets(budget_id) ON DELETE CASCADE ON UPDATE CASCADE
9811     |);
9812
9813     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";
9814     SetVersion($DBversion);
9815 }
9816
9817 $DBversion = "3.19.00.009";
9818 if ( CheckVersion($DBversion) ) {
9819     $dbh->do(q|
9820         UPDATE suggestions s SET s.budgetid = NULL
9821         WHERE NOT EXISTS (
9822             SELECT NULL
9823             FROM aqbudgets b
9824             WHERE b.budget_id = s.budgetid
9825         );
9826     |);
9827
9828     $dbh->do(q|
9829         ALTER TABLE suggestions
9830         ADD CONSTRAINT suggestions_budget_id_fk FOREIGN KEY (budgetid) REFERENCES aqbudgets(budget_id) ON DELETE SET NULL ON UPDATE CASCADE
9831     |);
9832
9833     print "Upgrade to $DBversion done (Bug 13007: Add new foreign key suggestions.budgetid)\n";
9834     SetVersion($DBversion);
9835 }
9836
9837 $DBversion = "3.19.00.010";
9838 if ( CheckVersion($DBversion) ) {
9839     $dbh->do(q|
9840         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
9841         VALUES('SessionRestrictionByIP','1','Check for Change in  Remote IP address for Session Security. Disable when remote ip address changes frequently.','','YesNo')
9842     |);
9843     print "Upgrade to $DBversion done (Bug 5511: SessionRestrictionByIP)\n";
9844     SetVersion ($DBversion);
9845 }
9846
9847 $DBversion = "3.19.00.011";
9848 if ( CheckVersion($DBversion) ) {
9849     $dbh->do(q|
9850         INSERT INTO userflags (bit, flag, flagdesc, defaulton) VALUES
9851         (20, 'lists', 'Lists', 0)
9852     |);
9853     $dbh->do(q|
9854         INSERT INTO permissions (module_bit, code, description) VALUES
9855         (20, 'delete_public_lists', 'Delete public lists')
9856     |);
9857     print "Upgrade to $DBversion done (Bug 13417: Add permission to delete public lists)\n";
9858     SetVersion ($DBversion);
9859 }
9860
9861 $DBversion = "3.19.00.012";
9862 if(CheckVersion($DBversion)) {
9863     $dbh->do(q{
9864         ALTER TABLE biblioitems MODIFY COLUMN marcxml longtext
9865     });
9866
9867     $dbh->do(q{
9868         ALTER TABLE deletedbiblioitems MODIFY COLUMN marcxml longtext
9869     });
9870
9871     print "Upgrade to $DBversion done (Bug 13523 Remove NOT NULL restriction on field marcxml due to mysql STRICT_TRANS_TABLES)\n";
9872     SetVersion ($DBversion);
9873 }
9874
9875 $DBversion = "3.19.00.013";
9876 if ( CheckVersion($DBversion) ) {
9877     $dbh->do(q|
9878         INSERT INTO permissions (module_bit, code, description) VALUES
9879           (13, 'records_batchmod', 'Perform batch modification of records (biblios or authorities)')
9880     |);
9881     print "Upgrade to $DBversion done (Bug 11395: Add permission tools_records_batchmod)\n";
9882     SetVersion($DBversion);
9883 }
9884
9885 $DBversion = "3.19.00.014";
9886 if ( CheckVersion($DBversion) ) {
9887     $dbh->do(q|
9888         CREATE TABLE aqorder_users (
9889             ordernumber int(11) NOT NULL,
9890             borrowernumber int(11) NOT NULL,
9891             PRIMARY KEY (ordernumber, borrowernumber),
9892             CONSTRAINT aqorder_users_ibfk_1 FOREIGN KEY (ordernumber) REFERENCES aqorders (ordernumber) ON DELETE CASCADE ON UPDATE CASCADE,
9893             CONSTRAINT aqorder_users_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
9894         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
9895     |);
9896
9897     $dbh->do(q|
9898         INSERT INTO letter(module, code, branchcode, name, title, content, message_transport_type)
9899         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')
9900     |);
9901     print "Upgrade to $DBversion done (Bug 12648: Add letter ACQ_NOTIF_ON_RECEIV )\n";
9902     SetVersion ($DBversion);
9903 }
9904
9905 $DBversion = "3.19.00.015";
9906 if ( CheckVersion($DBversion) ) {
9907     $dbh->do(q|
9908         ALTER TABLE search_history ADD COLUMN id INT(11) NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY(id);
9909     |);
9910     print "Upgrade to $DBversion done (Bug 11430: Add primary key for search_history)\n";
9911     SetVersion ($DBversion);
9912 }
9913
9914 $DBversion = "3.19.00.016";
9915 if(CheckVersion($DBversion)) {
9916     my @order_cancellation_reason = $dbh->selectrow_array("SELECT count(*) FROM authorised_values WHERE category='ORDER_CANCELLATION_REASON'");
9917     if ($order_cancellation_reason[0] == 0) {
9918         $dbh->do(q{
9919             INSERT INTO authorised_values (category, authorised_value, lib) VALUES
9920              ('ORDER_CANCELLATION_REASON', 0, 'No reason provided'),
9921              ('ORDER_CANCELLATION_REASON', 1, 'Out of stock'),
9922              ('ORDER_CANCELLATION_REASON', 2, 'Restocking')
9923         });
9924
9925         my $already_existing_reasons = $dbh->selectcol_arrayref(q{
9926             SELECT DISTINCT( cancellationreason )
9927             FROM aqorders;
9928         }, { Slice => {} });
9929
9930         my $update_orders_sth = $dbh->prepare(q{
9931             UPDATE aqorders
9932             SET cancellationreason = ?
9933             WHERE cancellationreason = ?
9934         });
9935
9936         my $insert_av_sth = $dbh->prepare(q{
9937             INSERT INTO authorised_values (category, authorised_value, lib) VALUES
9938              ('ORDER_CANCELLATION_REASON', ?, ?)
9939         });
9940         my $i = 3;
9941         for my $reason ( @$already_existing_reasons ) {
9942             next unless $reason;
9943             $insert_av_sth->execute( $i, $reason );
9944             $update_orders_sth->execute( $i, $reason );
9945             $i++;
9946         }
9947         print "Upgrade to $DBversion done (Bug 13380: Add the ORDER_CANCELLATION_REASON authorised value)\n";
9948     }
9949     else {
9950         print "Upgrade to $DBversion done (Bug 13380: ORDER_CANCELLATION_REASON authorised value already existed from earlier update!)\n";
9951     }
9952
9953     SetVersion($DBversion);
9954 }
9955
9956 $DBversion = '3.19.00.017';
9957 if ( CheckVersion($DBversion) ) {
9958     # First create the column
9959     $dbh->do("ALTER TABLE issuingrules ADD onshelfholds tinyint(1) default 0 NOT NULL");
9960     # Now update the column
9961     if (C4::Context->preference("AllowOnShelfHolds")){
9962         # Pref is on, set allow for all rules
9963         $dbh->do("UPDATE issuingrules SET onshelfholds=1");
9964     } else {
9965         # If the preference is not set, leave off
9966         $dbh->do("UPDATE issuingrules SET onshelfholds=0");
9967     }
9968     # Remove from the systempreferences table
9969     $dbh->do("DELETE FROM systempreferences WHERE variable = 'AllowOnShelfHolds'");
9970
9971     # First create the column
9972     $dbh->do("ALTER TABLE issuingrules ADD opacitemholds char(1) DEFAULT 'N' NOT NULL");
9973     # Now update the column
9974     my $opacitemholds = C4::Context->preference("OPACItemHolds") || '';
9975     if (lc ($opacitemholds) eq 'force') {
9976         $opacitemholds = 'F';
9977     }
9978     else {
9979         $opacitemholds = $opacitemholds ? 'Y' : 'N';
9980     }
9981     # Set allow for all rules
9982     $dbh->do("UPDATE issuingrules SET opacitemholds='$opacitemholds'");
9983
9984     # Remove from the systempreferences table
9985     $dbh->do("DELETE FROM systempreferences WHERE variable = 'OPACItemHolds'");
9986
9987     print "Upgrade to $DBversion done (Bug 5786: Move AllowOnShelfHolds to circulation matrix; Move OPACItemHolds system preference to circulation matrix)\n";
9988     SetVersion ($DBversion);
9989 }
9990
9991
9992 $DBversion = "3.19.00.018";
9993 if ( CheckVersion($DBversion) ) {
9994     $dbh->do(q|
9995         UPDATE systempreferences set variable="OpacAdditionalStylesheet" WHERE variable="opaccolorstylesheet"
9996     |);
9997     print "Upgrade to $DBversion done (Bug 10328: Rename opaccolorstylesheet to OpacAdditionalStylesheet\n";
9998     SetVersion ($DBversion);
9999 }
10000
10001 $DBversion = "3.19.00.019";
10002 if ( CheckVersion($DBversion) ) {
10003     $dbh->do(q{
10004         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
10005         VALUES('Coce','0', 'If on, enables cover retrieval from the configured Coce server', NULL, 'YesNo')
10006     });
10007     $dbh->do(q{
10008         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
10009         VALUES('CoceHost', NULL, 'Coce server URL', NULL,'Free')
10010     });
10011     $dbh->do(q{
10012         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
10013         VALUES('CoceProviders', NULL, 'Coce providers', 'aws,gb,ol', 'multiple')
10014     });
10015     print "Upgrade to $DBversion done (Bug 9580: Cover image from Coce, a remote image URL cache)\n";
10016     SetVersion($DBversion);
10017 }
10018
10019 $DBversion = "3.19.00.020";
10020 if ( CheckVersion($DBversion) ) {
10021     $dbh->do(q|
10022         ALTER TABLE aqorders DROP COLUMN supplierreference;
10023     |);
10024
10025     print "Upgrade to $DBversion done (Bug 11008: DROP column aqorders.supplierreference)\n";
10026     SetVersion($DBversion);
10027 }
10028
10029 $DBversion = "3.19.00.021";
10030 if ( CheckVersion($DBversion) ) {
10031     $dbh->do(q|
10032         ALTER TABLE issues DROP COLUMN issuingbranch
10033     |);
10034     $dbh->do(q|
10035         ALTER TABLE old_issues DROP COLUMN issuingbranch
10036     |);
10037     print "Upgrade to $DBversion done (Bug 2806: Remove issuingbranch columns)\n";
10038     SetVersion ($DBversion);
10039 }
10040
10041 $DBversion = '3.19.00.022';
10042 if ( CheckVersion($DBversion) ) {
10043     $dbh->do(q{
10044         ALTER TABLE suggestions DROP COLUMN mailoverseeing;
10045     });
10046     print "Upgrade to $DBversion done (Bug 13006: Drop column suggestion.mailoverseeing)\n";
10047     SetVersion($DBversion);
10048 }
10049
10050 $DBversion = "3.19.00.023";
10051 if ( CheckVersion($DBversion) ) {
10052     $dbh->do(q|
10053         DELETE FROM systempreferences where variable = 'AddPatronLists'
10054     |);
10055     print "Upgrade to $DBversion done (Bug 13497: Remove the AddPatronLists system preferences)\n";
10056     SetVersion ($DBversion);
10057 }
10058
10059 $DBversion = "3.19.00.024";
10060 if ( CheckVersion($DBversion) ) {
10061     $dbh->do(qq|DROP table patroncards;|);
10062     print "Upgrade to $DBversion done (Bug 13539: Remove table patroncards from database as it's no longer in use)\n";
10063     SetVersion ($DBversion);
10064 }
10065
10066 $DBversion = "3.19.00.025";
10067 if ( CheckVersion($DBversion) ) {
10068     $dbh->do(q|
10069         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
10070         ('SearchWithISBNVariations','0',NULL,'If enabled, search on all variations of the ISBN','YesNo')
10071     |);
10072     print "Upgrade to $DBversion done (Bug 13528: Add the SearchWithISBNVariations syspref)\n";
10073     SetVersion ($DBversion);
10074 }
10075
10076 $DBversion = "3.19.00.026";
10077 if( CheckVersion($DBversion) ) {
10078     if ( C4::Context->preference('marcflavour') eq 'MARC21' ) {
10079     $dbh->do(q{
10080         INSERT IGNORE INTO auth_tag_structure (authtypecode, tagfield, liblibrarian, libopac, repeatable, mandatory, authorised_value) VALUES
10081         ('', '388', 'TIME PERIOD OF CREATION', 'TIME PERIOD OF CREATION', 1, 0, NULL);
10082     });
10083
10084     $dbh->do(q{
10085         INSERT IGNORE INTO auth_subfield_structure (authtypecode, tagfield, tagsubfield, liblibrarian, libopac, repeatable,
10086         mandatory, tab, authorised_value, value_builder, seealso, isurl, hidden, linkid, kohafield, frameworkcode) VALUES
10087         ('', '388', '0', 'Authority record control number or standard number', 'Authority record control number or standard number', 1, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10088         ('', '388', '2', 'Source of term', 'Source of term', 0, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10089         ('', '388', '3', 'Materials specified', 'Materials specified', 0, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10090         ('', '388', '6', 'Linkage', 'Linkage', 0, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10091         ('', '388', '8', 'Field link and sequence number', 'Field link and sequence number', 1, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10092         ('', '388', 'a', 'Time period of creation term', 'Time period of creation term', 1, 0, 3, NULL, NULL, NULL, 0, 0, '', '', '');
10093     });
10094
10095     $dbh->do(q{
10096         UPDATE IGNORE auth_subfield_structure SET repeatable = 1 WHERE tagsubfield = 'g' AND tagfield IN
10097         ('100','110','111','130','400','410','411','430','500','510','511','530','700','710','730');
10098     });
10099
10100     $dbh->do(q{
10101         INSERT IGNORE INTO auth_subfield_structure (authtypecode, tagfield, tagsubfield, liblibrarian, libopac, repeatable,
10102         mandatory, tab, authorised_value, value_builder, seealso, isurl, hidden, linkid, kohafield, frameworkcode) VALUES
10103         ('', '150', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 1, NULL, NULL, NULL, 0, 0, '', '', ''),
10104         ('', '151', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 1, NULL, NULL, NULL, 0, 0, '', '', ''),
10105         ('', '450', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 4, NULL, NULL, NULL, 0, 0, '', '', ''),
10106         ('', '451', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 4, NULL, NULL, NULL, 0, 0, '', '', ''),
10107         ('', '550', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 5, NULL, NULL, NULL, 0, 0, '', '', ''),
10108         ('', '551', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 5, NULL, NULL, NULL, 0, 0, '', '', ''),
10109         ('', '750', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10110         ('', '751', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10111         ('', '748', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10112         ('', '755', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10113         ('', '780', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10114         ('', '781', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10115         ('', '782', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10116         ('', '785', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10117         ('', '710', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10118         ('', '730', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10119         ('', '748', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10120         ('', '750', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10121         ('', '751', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10122         ('', '755', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10123         ('', '762', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10124         ('', '780', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10125         ('', '781', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10126         ('', '782', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10127         ('', '785', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10128         ('', '788', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', '');
10129     });
10130
10131     $dbh->do(q{
10132         UPDATE IGNORE auth_subfield_structure SET liblibrarian = 'Relationship information', libopac = 'Relationship information'
10133         WHERE tagsubfield = 'i' AND tagfield IN ('700','710','730','750','751','762');
10134     });
10135
10136     $dbh->do(q{
10137         UPDATE IGNORE auth_subfield_structure SET liblibrarian = 'Relationship code', libopac = 'Relationship code'
10138         WHERE tagsubfield = '4' AND tagfield IN ('700','710');
10139     });
10140
10141     $dbh->do(q{
10142         INSERT IGNORE INTO marc_tag_structure (tagfield, liblibrarian, libopac, repeatable, mandatory, authorised_value, frameworkcode) VALUES
10143         ('370', 'ASSOCIATED PLACE', 'ASSOCIATED PLACE', 1, 0, NULL, ''),
10144         ('388', 'TIME PERIOD OF CREATION', 'TIME PERIOD OF CREATION', 1, 0, NULL, '');
10145     });
10146
10147     $dbh->do(q{
10148         INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian, libopac, repeatable, mandatory,
10149         kohafield, tab, authorised_value, authtypecode, value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
10150         ('370', '0', 'Authority record control number or standard number', 'Authority record control number or standard number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10151         ('370', '2', 'Source of term', 'Source of term', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10152         ('370', '6', 'Linkage', 'Linkage', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10153         ('370', '8', 'Field link and sequence number', 'Field link and sequence number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10154         ('370', 'c', 'Associated country', 'Associated country', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10155         ('370', 'f', 'Other associated place', 'Other associated place', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10156         ('370', 'g', 'Place of origin of work', 'Place of origin of work', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10157         ('370', 's', 'Start period', 'Start period', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10158         ('370', 't', 'End period', 'End period', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10159         ('370', 'u', 'Uniform Resource Identifier', 'Uniform Resource Identifier', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10160         ('370', 'v', 'Source of information', 'Source of information', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10161         ('377', 'l', 'Language term', 'Language term', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10162         ('382', 's', 'Total number of performers', 'Total number of performers', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10163         ('388', '0', 'Authority record control number or standard number', 'Authority record control number or standard number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10164         ('388', '2', 'Source of term', 'Source of term', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10165         ('388', '3', ' Materials specified', ' Materials specified', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10166         ('388', '6', ' Linkage', ' Linkage', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10167         ('388', '8', 'Field link and sequence number', 'Field link and sequence number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10168         ('388', 'a', 'Time period of creation term', 'Time period of creation term', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10169         ('650', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, '', 6, '', '', '', 0, -1, '', '', '', NULL),
10170         ('651', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, '', 6, '', '', '', 0, -1, '', '', '', NULL);
10171     });
10172
10173     $dbh->do(q{
10174         UPDATE IGNORE marc_subfield_structure SET repeatable = 1 WHERE tagsubfield = 'g' AND
10175         tagfield IN ('100','110','111','130','240','243','246','247','600','610','611','630','700','710','711','730','800','810','811','830');
10176     });
10177     }
10178
10179     print "Upgrade to $DBversion done (Bug 13322: Update MARC21 frameworks to Update No. 19 - October 2014)\n";
10180     SetVersion($DBversion);
10181 }
10182
10183 $DBversion = '3.19.00.027';
10184 if ( CheckVersion($DBversion) ) {
10185     $dbh->do("ALTER TABLE items ADD COLUMN itemnotes_nonpublic MEDIUMTEXT AFTER itemnotes");
10186     $dbh->do("ALTER TABLE deleteditems ADD COLUMN itemnotes_nonpublic MEDIUMTEXT AFTER itemnotes");
10187     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";
10188     SetVersion($DBversion);
10189 }
10190
10191 $DBversion = "3.19.00.028";
10192 if( CheckVersion($DBversion) ) {
10193     eval {
10194         local $dbh->{PrintError} = 0;
10195         $dbh->do(q{
10196             ALTER TABLE issues DROP PRIMARY KEY
10197         });
10198     };
10199
10200     $dbh->do(q{
10201         ALTER TABLE old_issues ADD issue_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10202     });
10203
10204     $dbh->do(q{
10205         ALTER TABLE old_issues CHANGE issue_id issue_id INT( 11 ) NOT NULL
10206     });
10207
10208     $dbh->do(q{
10209         ALTER TABLE issues ADD issue_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10210     });
10211
10212     $dbh->do(q{
10213         UPDATE issues SET issue_id = issue_id + ( SELECT COUNT(*) FROM old_issues ) ORDER BY issue_id DESC
10214     });
10215
10216     my $max_issue_id = $schema->resultset('Issue')->get_column('issue_id')->max();
10217     if ($max_issue_id) {
10218         $max_issue_id++;
10219         $dbh->do(qq{
10220             ALTER TABLE issues AUTO_INCREMENT = $max_issue_id
10221         });
10222     }
10223
10224     print "Upgrade to $DBversion done (Bug 13790: Add unique id issue_id to issues and oldissues tables)\n";
10225     SetVersion($DBversion);
10226 }
10227
10228 $DBversion = "3.19.00.029";
10229 if ( CheckVersion($DBversion) ) {
10230     $dbh->do(q|
10231          ALTER TABLE sessions CHANGE COLUMN a_session a_session MEDIUMTEXT
10232     |);
10233     print "Upgrade to $DBversion done (Bug 13606: Upgrade sessions.a_session to MEDIUMTEXT)\n";
10234     SetVersion($DBversion);
10235 }
10236
10237 $DBversion = "3.19.00.030";
10238 if ( CheckVersion($DBversion) ) {
10239     $dbh->do(q|
10240 UPDATE language_subtag_registry SET subtag = 'kn' WHERE subtag = 'ka' AND description = 'Kannada';
10241     |);
10242     $dbh->do(q|
10243 UPDATE language_rfc4646_to_iso639 SET rfc4646_subtag = 'kn' WHERE rfc4646_subtag = 'ka' AND iso639_2_code = 'kan';
10244     |);
10245     $dbh->do(q|
10246 UPDATE language_descriptions SET subtag = 'kn', lang = 'kn' WHERE subtag = 'ka' AND lang = 'ka' AND description = 'ಕನ್ನಡ';
10247     |);
10248     $dbh->do(q|
10249 UPDATE language_descriptions SET subtag = 'kn' WHERE subtag = 'ka' AND description = 'Kannada';
10250     |);
10251     $dbh->do(q|
10252 INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ka', 'language', 'Georgian','2015-04-20');
10253     |);
10254     $dbh->do(q|
10255 DELETE FROM language_subtag_registry
10256        WHERE NOT id IN
10257          (SELECT id FROM
10258            (SELECT MIN(id) as id,subtag,type,description,added
10259             FROM language_subtag_registry
10260             GROUP BY subtag,type,description,added)
10261            AS subtable);
10262     |);
10263     $dbh->do(q|
10264 INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ka', 'geo');
10265     |);
10266     $dbh->do(q|
10267 DELETE FROM language_rfc4646_to_iso639
10268        WHERE NOT id IN
10269          (SELECT id FROM
10270            (SELECT MIN(id) as id,rfc4646_subtag,iso639_2_code
10271             FROM language_rfc4646_to_iso639
10272             GROUP BY rfc4646_subtag,iso639_2_code)
10273            AS subtable);
10274     |);
10275     $dbh->do(q|
10276 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'ka', 'ქართული');
10277     |);
10278     $dbh->do(q|
10279 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'en', 'Georgian');
10280     |);
10281     $dbh->do(q|
10282 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'fr', 'Géorgien');
10283     |);
10284     $dbh->do(q|
10285 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'de', 'Georgisch');
10286     |);
10287     $dbh->do(q|
10288 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'es', 'Georgiano');
10289     |);
10290     $dbh->do(q|
10291 DELETE FROM language_descriptions
10292        WHERE NOT id IN
10293          (SELECT id FROM
10294            (SELECT MIN(id) as id,subtag,type,lang,description
10295             FROM language_descriptions GROUP BY subtag,type,lang,description)
10296            AS subtable);
10297     |);
10298     print "Upgrade to $DBversion done (Bug 14030: Add Georgian language and fix Kannada language code)\n";
10299     SetVersion($DBversion);
10300 }
10301
10302 $DBversion = "3.19.00.031";
10303 if ( CheckVersion($DBversion) ) {
10304     $dbh->do(q{
10305         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10306         VALUES('IdRef','0','Disable/enable the IdRef webservice from the OPAC detail page.',NULL,'YesNo')
10307     });
10308     print "Upgrade to $DBversion done (Bug 8992: Add system preference IdRef))\n";
10309     SetVersion($DBversion);
10310 }
10311
10312 $DBversion = "3.19.00.032";
10313 if ( CheckVersion($DBversion) ) {
10314     $dbh->do(q|
10315         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10316         VALUES('AddressFormat','us','Choose format to display postal addresses','','Choice')
10317     |);
10318     print "Upgrade to $DBversion done (Bug 4041: Address Format as a I18N/L10N system preference\n";
10319     SetVersion ($DBversion);
10320 }
10321
10322 $DBversion = "3.19.00.033";
10323 if ( CheckVersion($DBversion) ) {
10324     $dbh->do(q|
10325         ALTER TABLE auth_header
10326         CHANGE COLUMN datemodified modification_time TIMESTAMP NOT NULL default CURRENT_TIMESTAMP
10327     |);
10328     $dbh->do(q|
10329         ALTER TABLE auth_header
10330         CHANGE COLUMN modification_time modification_time TIMESTAMP NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP
10331     |);
10332     print "Upgrade to $DBversion done (Bug 11165: Update auth_header.datemodified when updated)\n";
10333     SetVersion ($DBversion);
10334 }
10335
10336 $DBversion = "3.19.00.034";
10337 if ( CheckVersion($DBversion) ) {
10338     $dbh->do(q|
10339         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10340         VALUES('CardnumberLength', '', '', 'Set a length for card numbers.', 'Free')
10341     |);
10342     print "Upgrade to $DBversion done (Bug 13984: CardnumberLength syspref missing on some setups\n";
10343     SetVersion ($DBversion);
10344 }
10345
10346 $DBversion = "3.19.00.035";
10347 if ( CheckVersion($DBversion) ) {
10348     $dbh->do(q|
10349         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('useDischarge','','Allows librarians to discharge borrowers and borrowers to request a discharge','','YesNo')
10350     |);
10351     $dbh->do(q|
10352         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.')
10353     |);
10354
10355     $dbh->do(q|
10356         ALTER TABLE borrower_debarments CHANGE type type ENUM('SUSPENSION','OVERDUES','MANUAL','DISCHARGE') NOT NULL DEFAULT 'MANUAL'
10357     |);
10358
10359     $dbh->do(q|
10360         CREATE TABLE discharges (
10361           borrower int(11) DEFAULT NULL,
10362           needed timestamp NULL DEFAULT NULL,
10363           validated timestamp NULL DEFAULT NULL,
10364           KEY borrower_discharges_ibfk1 (borrower),
10365           CONSTRAINT borrower_discharges_ibfk1 FOREIGN KEY (borrower) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
10366         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
10367     |);
10368
10369     print "Upgrade to $DBversion done (Bug 8007: Add System Preferences useDischarge, the discharge notice and the new table discharges)\n";
10370     SetVersion($DBversion);
10371 }
10372
10373 $DBversion = "3.19.00.036";
10374 if ( CheckVersion($DBversion) ) {
10375     $dbh->do(q|
10376         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10377         VALUES ('CronjobLog','0',NULL,'If ON, log information from cron jobs.','YesNo')
10378     |);
10379     print "Upgrade to $DBversion done (Bug 13889: Add cron jobs information to system log)\n";
10380     SetVersion ($DBversion);
10381 }
10382
10383 $DBversion = "3.19.00.037";
10384 if ( CheckVersion($DBversion) ) {
10385     $dbh->do(q|
10386         ALTER TABLE marc_subfield_structure
10387         MODIFY COLUMN tagsubfield varchar(1) COLLATE utf8_bin NOT NULL DEFAULT ''
10388     |);
10389     print "Upgrade to $DBversion done (Bug 13810: Change collate for tagsubfield (utf8_bin))\n";
10390     SetVersion ($DBversion);
10391 }
10392
10393 $DBversion = "3.19.00.038";
10394 if ( CheckVersion($DBversion) ) {
10395     $dbh->do(q|
10396         ALTER TABLE virtualshelves
10397         ADD COLUMN created_on DATETIME NOT NULL AFTER lastmodified
10398     |);
10399     # Set created_on = lastmodified
10400     # I would say it's better than 0000-00-00
10401     # Set modified to the existing value (do not get the current ts!)
10402     $dbh->do(q|
10403         UPDATE virtualshelves
10404         SET created_on = lastmodified, lastmodified = lastmodified
10405     |);
10406     print "Upgrade to $DBversion done (Bug 13421: Add DB field virtualshelves.created_on)\n";
10407     SetVersion ($DBversion);
10408 }
10409
10410 $DBversion = "3.19.00.039";
10411 if ( CheckVersion($DBversion) ) {
10412     print "Upgrade to $DBversion done (Koha 3.20 beta)\n";
10413     SetVersion ($DBversion);
10414 }
10415
10416 $DBversion = "3.19.00.040";
10417 if ( CheckVersion($DBversion) ) {
10418     $dbh->do(q|
10419         ALTER TABLE aqorders DROP COLUMN totalamount
10420     |);
10421     print "Upgrade to $DBversion done (Bug 11006: Drop column aqorders.totalamount)\n";
10422     SetVersion ($DBversion);
10423 }
10424
10425 $DBversion = "3.19.00.041";
10426 if ( CheckVersion($DBversion) ) {
10427     unless ( index_exists( 'suggestions', 'status' ) ) {
10428         $dbh->do(q|
10429             ALTER TABLE suggestions ADD KEY status (STATUS)
10430         |);
10431     }
10432     unless ( index_exists( 'suggestions', 'biblionumber' ) ) {
10433         $dbh->do(q|
10434             ALTER TABLE suggestions ADD KEY biblionumber (biblionumber)
10435         |);
10436     }
10437     unless ( index_exists( 'suggestions', 'branchcode' ) ) {
10438         $dbh->do(q|
10439             ALTER TABLE suggestions ADD KEY branchcode (branchcode)
10440         |);
10441     }
10442     print "Upgrade to $DBversion done (Bug 14132: suggestions table is missing indexes)\n";
10443     SetVersion ($DBversion);
10444 }
10445
10446 $DBversion = "3.19.00.042";
10447 if ( CheckVersion($DBversion) ) {
10448     $dbh->do(q{
10449         DELETE ass.*
10450         FROM auth_subfield_structure AS ass
10451         LEFT JOIN auth_types USING(authtypecode)
10452         WHERE auth_types.authtypecode IS NULL
10453     });
10454
10455     unless ( foreign_key_exists( 'auth_subfield_structure', 'auth_subfield_structure_ibfk_1' ) ) {
10456         $dbh->do(q{
10457             ALTER TABLE auth_subfield_structure
10458             ADD CONSTRAINT auth_subfield_structure_ibfk_1
10459             FOREIGN KEY (authtypecode) REFERENCES auth_types(authtypecode)
10460             ON DELETE CASCADE ON UPDATE CASCADE
10461         });
10462     }
10463
10464     print "Upgrade to $DBversion done (Bug 8480: Add foreign key on auth_subfield_structure.authtypecode)\n";
10465     SetVersion($DBversion);
10466 }
10467
10468 $DBversion = "3.19.00.043";
10469 if ( CheckVersion($DBversion) ) {
10470     $dbh->do(q|
10471         INSERT IGNORE INTO authorised_values (category, authorised_value, lib) VALUES
10472         ('REPORT_GROUP', 'SER', 'Serials')
10473     |);
10474
10475     print "Upgrade to $DBversion done (Bug 5338: Add Serial to the report groups if does not exist)\n";
10476     SetVersion ($DBversion);
10477 }
10478
10479 $DBversion = "3.20.00.000";
10480 if ( CheckVersion($DBversion) ) {
10481     print "Upgrade to $DBversion done (Koha 3.20)\n";
10482     SetVersion ($DBversion);
10483 }
10484
10485 $DBversion = "3.21.00.000";
10486 if ( CheckVersion($DBversion) ) {
10487     print "Upgrade to $DBversion done (El tiempo vuela, un nuevo ciclo comienza.)\n";
10488     SetVersion ($DBversion);
10489 }
10490
10491 $DBversion = "3.21.00.001";
10492 if ( CheckVersion($DBversion) ) {
10493     $dbh->do(q|
10494         UPDATE systempreferences SET variable='IntranetUserJS' where variable='intranetuserjs'
10495     |);
10496     print "Upgrade to $DBversion done (Bug 12160: Rename intranetuserjs to IntranetUserJS)\n";
10497     SetVersion ($DBversion);
10498 }
10499
10500 $DBversion = "3.21.00.002";
10501 if ( CheckVersion($DBversion) ) {
10502     $dbh->do(q|
10503         UPDATE systempreferences SET variable='OPACUserJS' where variable='opacuserjs'
10504     |);
10505     print "Upgrade to $DBversion done (Bug 12160: Rename opacuserjs to OPACUserJS)\n";
10506     SetVersion ($DBversion);
10507 }
10508
10509 $DBversion = "3.21.00.003";
10510 if ( CheckVersion($DBversion) ) {
10511     $dbh->do(q|
10512         INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added)
10513         VALUES ( 'IN', 'region', 'India','2015-05-28');
10514     |);
10515     $dbh->do(q|
10516         INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)
10517         VALUES ( 'IN', 'region', 'en', 'India');
10518     |);
10519     $dbh->do(q|
10520         INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)
10521         VALUES ( 'IN', 'region', 'bn', 'ভারত');
10522     |);
10523     print "Upgrade to $DBversion done (Bug 14285: Add new region India)\n";
10524     SetVersion ($DBversion);
10525 }
10526
10527 $DBversion = '3.21.00.004';
10528 if ( CheckVersion($DBversion) ) {
10529     my $OPACBaseURL = C4::Context->preference('OPACBaseURL');
10530     if (defined($OPACBaseURL) && substr($OPACBaseURL,0,4) ne "http") {
10531         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.};
10532         $OPACBaseURL = 'http://' . $OPACBaseURL;
10533         my $sth_OPACBaseURL = $dbh->prepare( q{
10534             UPDATE systempreferences SET value=?,explanation=?
10535             WHERE variable='OPACBaseURL'; } );
10536         $sth_OPACBaseURL->execute($OPACBaseURL,$explanation);
10537     }
10538     if (defined($OPACBaseURL)) {
10539         $dbh->do( q{ UPDATE letter
10540                      SET content=replace(content,
10541                                          'http://<<OPACBaseURL>>',
10542                                          '<<OPACBaseURL>>')
10543                      WHERE content LIKE "%http://<<OPACBaseURL>>%"; } );
10544     }
10545
10546     print "Upgrade to $DBversion done (Bug 5010: Fix OPACBaseURL to include protocol)\n";
10547     SetVersion($DBversion);
10548 }
10549
10550 $DBversion = "3.21.00.005";
10551 if ( CheckVersion($DBversion) ) {
10552     $dbh->do(q|
10553         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10554         VALUES ('ReportsLog','0',NULL,'If ON, log information about reports.','YesNo')
10555     |);
10556     print "Upgrade to $DBversion done (Bug 14024: Add reports to action logs)\n";
10557     SetVersion ($DBversion);
10558 }
10559
10560 $DBversion = "3.21.00.006";
10561 if ( CheckVersion($DBversion) ) {
10562     # Remove the borrow permission flag (bit 7)
10563     $dbh->do(q|
10564         UPDATE borrowers
10565         SET flags = flags - ( flags & (1<<7) )
10566         WHERE flags IS NOT NULL
10567             AND flags > 0
10568     |);
10569     $dbh->do(q|
10570         DELETE FROM userflags WHERE bit=7;
10571     |);
10572     print "Upgrade to $DBversion done (Bug 7976: Remove the 'borrow' permission)\n";
10573     SetVersion($DBversion);
10574 }
10575
10576 $DBversion = "3.21.00.007";
10577 if ( CheckVersion($DBversion) ) {
10578     unless ( index_exists( 'aqbasket', 'authorisedby' ) ) {
10579         $dbh->do(q|
10580             ALTER TABLE aqbasket
10581                 ADD KEY authorisedby (authorisedby)
10582         |);
10583     }
10584     unless ( index_exists( 'aqbooksellers', 'name' ) ) {
10585         $dbh->do(q|
10586             ALTER TABLE aqbooksellers
10587                 ADD KEY name (name(255))
10588         |);
10589     }
10590     unless ( index_exists( 'aqbudgets', 'budget_parent_id' ) ) {
10591         $dbh->do(q|
10592             ALTER TABLE aqbudgets
10593                 ADD KEY budget_parent_id (budget_parent_id)|);
10594         }
10595     unless ( index_exists( 'aqbudgets', 'budget_code' ) ) {
10596         $dbh->do(q|
10597             ALTER TABLE aqbudgets
10598                 ADD KEY budget_code (budget_code)|);
10599     }
10600     unless ( index_exists( 'aqbudgets', 'budget_branchcode' ) ) {
10601         $dbh->do(q|
10602             ALTER TABLE aqbudgets
10603                 ADD KEY budget_branchcode (budget_branchcode)|);
10604     }
10605     unless ( index_exists( 'aqbudgets', 'budget_period_id' ) ) {
10606         $dbh->do(q|
10607             ALTER TABLE aqbudgets
10608                 ADD KEY budget_period_id (budget_period_id)|);
10609     }
10610     unless ( index_exists( 'aqbudgets', 'budget_owner_id' ) ) {
10611         $dbh->do(q|
10612             ALTER TABLE aqbudgets
10613                 ADD KEY budget_owner_id (budget_owner_id)|);
10614     }
10615     unless ( index_exists( 'aqbudgets_planning', 'budget_period_id' ) ) {
10616         $dbh->do(q|
10617             ALTER TABLE aqbudgets_planning
10618                 ADD KEY budget_period_id (budget_period_id)|);
10619     }
10620     unless ( index_exists( 'aqorders', 'parent_ordernumber' ) ) {
10621         $dbh->do(q|
10622             ALTER TABLE aqorders
10623                 ADD KEY parent_ordernumber (parent_ordernumber)|);
10624     }
10625     unless ( index_exists( 'aqorders', 'orderstatus' ) ) {
10626         $dbh->do(q|
10627             ALTER TABLE aqorders
10628                 ADD KEY orderstatus (orderstatus)|);
10629     }
10630     print "Upgrade to $DBversion done (Bug 14053: Acquisition db tables are missing indexes)\n";
10631     SetVersion ($DBversion);
10632 }
10633
10634 $DBversion = "3.21.00.008";
10635 if ( CheckVersion($DBversion) ) {
10636     $dbh->do(q{
10637         DELETE IGNORE FROM systempreferences
10638         WHERE variable = 'HomeOrHoldingBranchReturn';
10639     });
10640     print "Upgrade to $DBversion done (Bug 7981: Transfer message on return. HomeOrHoldingBranchReturn syspref removed in favour of circulation rules.)\n";
10641     SetVersion($DBversion);
10642 }
10643
10644 $DBversion = "3.21.00.009";
10645 if ( CheckVersion($DBversion) ) {
10646
10647     sanitize_zero_date('aqorders', 'datecancellationprinted');
10648
10649     $dbh->do(q|
10650         UPDATE aqorders SET orderstatus='cancelled'
10651         WHERE (datecancellationprinted IS NOT NULL)
10652     |);
10653
10654     print "Upgrade to $DBversion done (Bug 13993: Correct orderstatus for transferred orders)\n";
10655     SetVersion($DBversion);
10656 }
10657
10658 $DBversion = "3.21.00.010";
10659 if ( CheckVersion($DBversion) ) {
10660     $dbh->do(q|
10661         ALTER TABLE message_queue
10662             DROP message_id
10663     |);
10664     $dbh->do(q|
10665         ALTER TABLE message_queue
10666             ADD message_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10667     |);
10668     print "Upgrade to $DBversion done (Bug 7793: redefine the field message_id as PRIMARY KEY of message_queue)\n";
10669     SetVersion ($DBversion);
10670 }
10671
10672 $DBversion = "3.21.00.011";
10673 if ( CheckVersion($DBversion) ) {
10674     $dbh->do(q{
10675         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10676         VALUES ('OpacLangSelectorMode','footer','top|both|footer','Select the location to display the language selector','Choice')
10677     });
10678     print "Upgrade to $DBversion done (Bug 14252: Make the OPAC language switcher available in the masthead navbar, footer, or both)\n";
10679     SetVersion ($DBversion);
10680 }
10681
10682 $DBversion = "3.21.00.012";
10683 if ( CheckVersion($DBversion) ) {
10684     $dbh->do(q|
10685         INSERT INTO letter (module, code, name, title, content, message_transport_type)
10686         VALUES
10687         ('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')
10688     |);
10689     print "Upgrade to $DBversion done (Bug 13014: Add the TO_PROCESS letter code)\n";
10690     SetVersion($DBversion);
10691 }
10692
10693 $DBversion = "3.21.00.013";
10694 if ( CheckVersion($DBversion) ) {
10695     my $msg;
10696     if ( C4::Context->preference('OPACPrivacy') ) {
10697         if ( my $anonymous_patron = C4::Context->preference('AnonymousPatron') ) {
10698             my $anonymous_patron_exists = $dbh->selectcol_arrayref(q|
10699                 SELECT COUNT(*)
10700                 FROM borrowers
10701                 WHERE borrowernumber=?
10702             |, {}, $anonymous_patron);
10703             unless ( $anonymous_patron_exists->[0] ) {
10704                 $msg = "Configuration WARNING: OPACPrivacy is set but AnonymousPatron is not linked to an existing patron";
10705             }
10706         }
10707         else {
10708             $msg = "Configuration WARNING: OPACPrivacy is set but AnonymousPatron is not";
10709         }
10710     }
10711     else {
10712         my $patrons_have_required_anonymity = $dbh->selectcol_arrayref(q|
10713             SELECT COUNT(*)
10714             FROM borrowers
10715             WHERE privacy = 2
10716         |, {} );
10717         if ( $patrons_have_required_anonymity->[0] ) {
10718             $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.";
10719         }
10720     }
10721
10722     $msg //= "Privacy is correctly set";
10723     print "Upgrade to $DBversion done (Bug 9942: $msg)\n";
10724     SetVersion ($DBversion);
10725 }
10726
10727 $DBversion = "3.21.00.014";
10728 if ( CheckVersion($DBversion) ) {
10729     $dbh->do(q{
10730         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10731         VALUES ('OAI-PMH:DeletedRecord','persistent','Koha\'s deletedbiblio table will never be deleted (persistent) or might be deleted (transient)','transient|persistent','Choice')
10732     });
10733
10734     if ( foreign_key_exists( 'oai_sets_biblios', 'oai_sets_biblios_ibfk_1' ) ) {
10735         $dbh->do(q|
10736             ALTER TABLE oai_sets_biblios DROP FOREIGN KEY oai_sets_biblios_ibfk_1
10737         |);
10738     }
10739     print "Upgrade to $DBversion done (Bug 3206: OAI repository deleted record support)\n";
10740     SetVersion ($DBversion);
10741 }
10742
10743 $DBversion = "3.21.00.015";
10744 if ( CheckVersion($DBversion) ) {
10745     $dbh->do(q{
10746         UPDATE systempreferences SET value='0' WHERE variable='CalendarFirstDayOfWeek' AND value='Sunday';
10747     });
10748     $dbh->do(q{
10749         UPDATE systempreferences SET value='1' WHERE variable='CalendarFirstDayOfWeek' AND value='Monday';
10750     });
10751     $dbh->do(q{
10752         UPDATE systempreferences SET options='0|1|2|3|4|5|6' WHERE variable='CalendarFirstDayOfWeek';
10753     });
10754
10755     print "Upgrade to $DBversion done (Bug 12137: Extend functionality of CalendarFirstDayOfWeek to be any day)\n";
10756     SetVersion($DBversion);
10757 }
10758
10759 $DBversion = "3.21.00.016";
10760 if ( CheckVersion($DBversion) ) {
10761     my $rs = $schema->resultset('Systempreference');
10762     $rs->find_or_create(
10763         {
10764             variable => 'DumpTemplateVarsIntranet',
10765             value    => 0,
10766             explanation => 'If enabled, dump all Template Toolkit variable to a comment in the html source for the staff intranet.',
10767             type => 'YesNo',
10768         }
10769     );
10770     $rs->find_or_create(
10771         {
10772             variable => 'DumpTemplateVarsOpac',
10773             value    => 0,
10774             explanation => 'If enabled, dump all Template Toolkit variable to a comment in the html source for the opac.',
10775             type => 'YesNo',
10776         }
10777     );
10778     print "Upgrade to $DBversion done (Bug 13948: Add ability to dump template toolkit variables to html comment)\n";
10779     SetVersion($DBversion);
10780 }
10781
10782 $DBversion = "3.21.00.017";
10783 if ( CheckVersion($DBversion) ) {
10784     $dbh->do("
10785         CREATE TABLE uploaded_files (
10786             id int(11) NOT NULL AUTO_INCREMENT,
10787             hashvalue CHAR(40) NOT NULL,
10788             filename TEXT NOT NULL,
10789             dir TEXT NOT NULL,
10790             filesize int(11),
10791             dtcreated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
10792             categorycode tinytext,
10793             owner int(11),
10794             PRIMARY KEY (id)
10795         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
10796     ");
10797
10798     print "Upgrade to $DBversion done (Bug 6874: New cataloging plugin upload.pl)\n";
10799     print "This plugin comes with a new config variable (upload_path) and a new table (uploaded_files)\n";
10800     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";
10801     SetVersion($DBversion);
10802 }
10803
10804 $DBversion = "3.21.00.018";
10805 if ( CheckVersion($DBversion) ) {
10806     $dbh->do(q{
10807         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10808         VALUES
10809             ('RestrictedPageLocalIPs','',NULL,'Beginning of IP addresses considered as local (comma separated ex: \"127.0.0,127.0.2\")','Free'),
10810             ('RestrictedPageContent','',NULL,'HTML content of the restricted page','TextArea'),
10811             ('RestrictedPageTitle','',NULL,'Title of the restricted page (breadcrumb and header)','Free')
10812     });
10813     print "Upgrade to $DBversion done (Bug 13485: Add a page to display links to restricted sites)\n";
10814     SetVersion ($DBversion);
10815 }
10816
10817 $DBversion = "3.21.00.019";
10818 if ( CheckVersion($DBversion) ) {
10819     if ( column_exists( 'reserves', 'constrainttype' ) ) {
10820         $dbh->do(q{
10821             ALTER TABLE reserves DROP constrainttype
10822         });
10823         $dbh->do(q{
10824             ALTER TABLE old_reserves DROP constrainttype
10825         });
10826     }
10827     $dbh->do(q{
10828         DROP TABLE IF EXISTS reserveconstraints
10829     });
10830     print "Upgrade to $DBversion done (Bug 9809: Get rid of reserveconstraints)\n";
10831     SetVersion ($DBversion);
10832 }
10833
10834 $DBversion = "3.21.00.020";
10835 if ( CheckVersion($DBversion) ) {
10836     $dbh->do(q{
10837         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`)
10838         VALUES ('FeeOnChangePatronCategory','1','','If set, when a patron changes to a category with enrolment fee, a fee is charged','YesNo')
10839     });
10840     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";
10841     SetVersion($DBversion);
10842 }
10843
10844 $DBversion = "3.21.00.021";
10845 if ( CheckVersion($DBversion) ) {
10846     $dbh->do(q{
10847         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10848         VALUES ('UseWYSIWYGinSystemPreferences','0','','Show WYSIWYG editor when editing certain HTML system preferences.','YesNo')
10849     });
10850     print "Upgrade to $DBversion done (Bug 11584: Add wysiwyg editor to system preferences dealing with HTML)\n";
10851     SetVersion($DBversion);
10852 }
10853
10854 $DBversion = "3.21.00.022";
10855 if ( CheckVersion($DBversion) ) {
10856     $dbh->do(q{
10857         DELETE cr.*
10858         FROM course_reserves AS cr
10859         LEFT JOIN course_items USING(ci_id)
10860         WHERE course_items.ci_id IS NULL
10861     });
10862
10863     my ($print_error) = $dbh->{PrintError};
10864     $dbh->{RaiseError} = 0;
10865     $dbh->{PrintError} = 0;
10866     if ( foreign_key_exists('course_reserves', 'course_reserves_ibfk_2') ) {
10867         $dbh->do(q{ALTER TABLE course_reserves DROP FOREIGN KEY course_reserves_ibfk_2});
10868         $dbh->do(q{ALTER TABLE course_reserves DROP INDEX course_reserves_ibfk_2});
10869     }
10870     $dbh->{PrintError} = $print_error;
10871
10872     $dbh->do(q{
10873         ALTER TABLE course_reserves
10874             ADD CONSTRAINT course_reserves_ibfk_2
10875                 FOREIGN KEY (ci_id) REFERENCES course_items (ci_id)
10876                 ON DELETE CASCADE ON UPDATE CASCADE
10877     });
10878     print "Upgrade to $DBversion done (Bug 14205: Deleting an Item/Record does not remove link to course reserve)\n";
10879     SetVersion($DBversion);
10880 }
10881
10882 $DBversion = "3.21.00.023";
10883 if ( CheckVersion($DBversion) ) {
10884
10885     sanitize_zero_date('borrowers', 'debarred');
10886     sanitize_zero_date('borrowers', 'dateexpiry');
10887     sanitize_zero_date('borrowers', 'dateofbirth');
10888     sanitize_zero_date('borrowers', 'dateenrolled');
10889
10890     print "Upgrade to $DBversion done (Bug 14717: Prevent 0000-00-00 dates in patron data)\n";
10891     SetVersion($DBversion);
10892 }
10893
10894 $DBversion = "3.21.00.024";
10895 if ( CheckVersion($DBversion) ) {
10896     $dbh->do(q{
10897         ALTER TABLE marc_modification_template_actions
10898         MODIFY COLUMN action
10899             ENUM('delete_field','update_field','move_field','copy_field','copy_and_replace_field')
10900             NOT NULL
10901     });
10902     print "Upgrade to $DBversion done (Bug 14098: Regression in Marc Modification Templates)\n";
10903     SetVersion($DBversion);
10904 }
10905
10906 $DBversion = "3.21.00.025";
10907 if ( CheckVersion($DBversion) ) {
10908     $dbh->do(q{
10909         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10910         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')
10911     });
10912     $dbh->do(q{
10913         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10914         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')
10915     });
10916     print "Upgrade to $DBversion done (Bug 12357: Enhancements to RIS and BibTeX exporting)\n";
10917     SetVersion($DBversion);
10918 }
10919
10920 $DBversion = "3.21.00.026";
10921 if ( CheckVersion($DBversion) ) {
10922     $dbh->do(q{
10923         UPDATE matchpoints
10924         SET search_index='issn'
10925         WHERE matcher_id IN (SELECT matcher_id FROM marc_matchers WHERE code = 'ISSN')
10926     });
10927     print "Upgrade to $DBversion done (Bug 14472: Wrong ISSN search index in record matching rules)\n";
10928     SetVersion($DBversion);
10929 }
10930
10931 $DBversion = "3.21.00.027";
10932 if ( CheckVersion($DBversion) ) {
10933     $dbh->do(q|
10934         INSERT IGNORE INTO permissions (module_bit, code, description)
10935         VALUES (1, 'self_checkout', 'Perform self checkout at the OPAC. It should be used for the patron matching the AutoSelfCheckID')
10936     |);
10937
10938     my $AutoSelfCheckID = C4::Context->preference('AutoSelfCheckID');
10939
10940     $dbh->do(q|
10941         UPDATE borrowers
10942         SET flags=0
10943         WHERE userid=?
10944     |, undef, $AutoSelfCheckID);
10945
10946     $dbh->do(q|
10947         DELETE FROM user_permissions
10948         WHERE borrowernumber=(SELECT borrowernumber FROM borrowers WHERE userid=?)
10949     |, undef, $AutoSelfCheckID);
10950
10951     $dbh->do(q|
10952         INSERT INTO user_permissions(borrowernumber, module_bit, code)
10953         SELECT borrowernumber, 1, 'self_checkout' FROM borrowers WHERE userid=?
10954     |, undef, $AutoSelfCheckID);
10955     print "Upgrade to $DBversion done (Bug 14298: AutoSelfCheckID user should only be able to access SCO)\n";
10956     SetVersion($DBversion);
10957 }
10958
10959 $DBversion = "3.21.00.028";
10960 if ( CheckVersion($DBversion) ) {
10961     unless ( column_exists('uploaded_files', 'public') ) {
10962         $dbh->do(q{
10963             ALTER TABLE uploaded_files
10964                 ADD COLUMN public tinyint,
10965                 ADD COLUMN permanent tinyint
10966         });
10967         $dbh->do(q{
10968             UPDATE uploaded_files SET public=1, permanent=1
10969         });
10970         $dbh->do(q{
10971             ALTER TABLE uploaded_files
10972                 CHANGE COLUMN categorycode uploadcategorycode tinytext
10973         });
10974     }
10975     print "Upgrade to $DBversion done (Bug 14321: Merge UploadedFile and UploadedFiles into Koha::Upload)\n";
10976     SetVersion($DBversion);
10977 }
10978
10979 $DBversion = "3.21.00.029";
10980 if ( CheckVersion($DBversion) ) {
10981     unless ( column_exists('discharges', 'discharge_id') ) {
10982         $dbh->do(q{
10983             ALTER TABLE discharges
10984                 ADD COLUMN discharge_id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10985         });
10986     }
10987     print "Upgrade to $DBversion done (Bug 14368: Add discharges history)\n";
10988     SetVersion($DBversion);
10989 }
10990
10991 $DBversion = "3.21.00.030";
10992 if ( CheckVersion($DBversion) ) {
10993     $dbh->do(q{
10994         UPDATE marc_subfield_structure
10995         SET value_builder='marc21_leader.pl'
10996         WHERE value_builder='marc21_leader_book.pl'
10997     });
10998     $dbh->do(q{
10999         UPDATE marc_subfield_structure
11000         SET value_builder='marc21_leader.pl'
11001         WHERE value_builder='marc21_leader_computerfile.pl'
11002     });
11003     $dbh->do(q{
11004         UPDATE marc_subfield_structure
11005         SET value_builder='marc21_leader.pl'
11006         WHERE value_builder='marc21_leader_video.pl'
11007     });
11008     print "Upgrade to $DBversion done (Bug 14201: Remove unused code or template from some MARC21 leader plugins )\n";
11009     SetVersion($DBversion);
11010 }
11011
11012 $DBversion = "3.21.00.031";
11013 if ( CheckVersion($DBversion) ) {
11014     $dbh->do(q{
11015         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
11016         VALUES
11017             ('SMSSendPassword', '', '', 'Password used to send SMS messages', 'free'),
11018             ('SMSSendUsername', '', '', 'Username/Login used to send SMS messages', 'free')
11019     });
11020     print "Upgrade to $DBversion done (Bug 14820: SMSSendUsername and SMSSendPassword are not listed in the system preferences)\n";
11021     SetVersion($DBversion);
11022 }
11023
11024 $DBversion = "3.21.00.032";
11025 if ( CheckVersion($DBversion) ) {
11026     $dbh->do(q{
11027         CREATE TABLE additional_fields (
11028             id int(11) NOT NULL AUTO_INCREMENT,
11029             tablename varchar(255) NOT NULL DEFAULT '',
11030             name varchar(255) NOT NULL DEFAULT '',
11031             authorised_value_category varchar(16) NOT NULL DEFAULT '',
11032             marcfield varchar(16) NOT NULL DEFAULT '',
11033             searchable tinyint(1) NOT NULL DEFAULT '0',
11034             PRIMARY KEY (id),
11035             UNIQUE KEY fields_uniq (tablename,name)
11036         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
11037     });
11038     $dbh->do(q{
11039         CREATE TABLE additional_field_values (
11040             id int(11) NOT NULL AUTO_INCREMENT,
11041             field_id int(11) NOT NULL,
11042             record_id int(11) NOT NULL,
11043             value varchar(255) NOT NULL DEFAULT '',
11044             PRIMARY KEY (id),
11045             UNIQUE KEY field_record (field_id,record_id),
11046             CONSTRAINT afv_fk FOREIGN KEY (field_id) REFERENCES additional_fields (id) ON DELETE CASCADE ON UPDATE CASCADE
11047         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
11048     });
11049     print "Upgrade to $DBversion done (Bug 10855: Additional fields for subscriptions)\n";
11050     SetVersion($DBversion);
11051 }
11052
11053 $DBversion = "3.21.00.033";
11054 if ( CheckVersion($DBversion) ) {
11055
11056     my $done = 0;
11057     my $count_ethnicity = $dbh->selectrow_arrayref(q|
11058         SELECT COUNT(*) FROM ethnicity
11059     |);
11060     my $count_borrower_modifications = $dbh->selectrow_arrayref(q|
11061         SELECT COUNT(*)
11062         FROM borrower_modifications
11063         WHERE ethnicity IS NOT NULL
11064             OR ethnotes IS NOT NULL
11065     |);
11066     my $count_borrowers = $dbh->selectrow_arrayref(q|
11067         SELECT COUNT(*)
11068         FROM borrowers
11069         WHERE ethnicity IS NOT NULL
11070             OR ethnotes IS NOT NULL
11071     |);
11072     # We don't care about the ethnicity of the deleted borrowers, right?
11073     if ( $count_ethnicity->[0] == 0
11074             and $count_borrower_modifications->[0] == 0
11075             and $count_borrowers->[0] == 0
11076     ) {
11077         $dbh->do(q|
11078             DROP TABLE ethnicity
11079         |);
11080         $dbh->do(q|
11081             ALTER TABLE borrower_modifications
11082             DROP COLUMN ethnicity,
11083             DROP COLUMN ethnotes
11084         |);
11085         $dbh->do(q|
11086             ALTER TABLE borrowers
11087             DROP COLUMN ethnicity,
11088             DROP COLUMN ethnotes
11089         |);
11090         $dbh->do(q|
11091             ALTER TABLE deletedborrowers
11092             DROP COLUMN ethnicity,
11093             DROP COLUMN ethnotes
11094         |);
11095         $done = 1;
11096     }
11097     if ( $done ) {
11098         print "Upgrade to $DBversion done (Bug 10020: Drop table ethnicity and columns ethnicity and ethnotes)\n";
11099     }
11100     else {
11101         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";
11102     }
11103
11104     SetVersion ($DBversion);
11105 }
11106
11107 $DBversion = "3.21.00.034";
11108 if ( CheckVersion($DBversion) ) {
11109     $dbh->do(q{
11110         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11111         VALUES('MembershipExpiryDaysNotice',NULL,'Send an account expiration notice that a patron''s card is about to expire after',NULL,'Integer')
11112     });
11113     $dbh->do(q{
11114         INSERT IGNORE INTO letter (module, code, branchcode, name, title, content, message_transport_type)
11115         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')
11116     });
11117     print "Upgrade to $DBversion done (Bug 6810: Send membership expiry reminder notices)\n";
11118     SetVersion($DBversion);
11119 }
11120
11121 $DBversion = "3.21.00.035";
11122 if ( CheckVersion($DBversion) ) {
11123     $dbh->do(q|
11124         ALTER TABLE branch_borrower_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11125     |);
11126     $dbh->do(q|
11127         UPDATE branch_borrower_circ_rules SET maxonsiteissueqty = maxissueqty;
11128     |);
11129     $dbh->do(q|
11130         ALTER TABLE default_borrower_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11131     |);
11132     $dbh->do(q|
11133         UPDATE default_borrower_circ_rules SET maxonsiteissueqty = maxissueqty;
11134     |);
11135     $dbh->do(q|
11136         ALTER TABLE default_branch_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11137     |);
11138     $dbh->do(q|
11139         UPDATE default_branch_circ_rules SET maxonsiteissueqty = maxissueqty;
11140     |);
11141     $dbh->do(q|
11142         ALTER TABLE default_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11143     |);
11144     $dbh->do(q|
11145         UPDATE default_circ_rules SET maxonsiteissueqty = maxissueqty;
11146     |);
11147     $dbh->do(q|
11148         ALTER TABLE issuingrules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11149     |);
11150     $dbh->do(q|
11151         UPDATE issuingrules SET maxonsiteissueqty = maxissueqty;
11152     |);
11153     $dbh->do(q|
11154         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11155         VALUES ('ConsiderOnSiteCheckoutsAsNormalCheckouts','1',NULL,'Consider on-site checkouts as normal checkouts','YesNo');
11156     |);
11157
11158     print "Upgrade to $DBversion done (Bug 14045: Add DB fields maxonsiteissueqty and pref ConsiderOnSiteCheckoutsAsNormalCheckouts)\n";
11159     SetVersion ($DBversion);
11160 }
11161
11162 $DBversion = "3.21.00.036";
11163 if ( CheckVersion($DBversion) ) {
11164    $dbh->do(q{
11165         ALTER TABLE authorised_values_branches
11166         DROP FOREIGN KEY authorised_values_branches_ibfk_1,
11167         DROP FOREIGN KEY authorised_values_branches_ibfk_2
11168     });
11169     $dbh->do(q{
11170         ALTER TABLE authorised_values_branches
11171         MODIFY av_id INT( 11 ) NOT NULL,
11172         MODIFY branchcode VARCHAR( 10 ) NOT NULL,
11173         ADD FOREIGN KEY (`av_id`) REFERENCES `authorised_values` (`id`) ON DELETE CASCADE,
11174         ADD FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE
11175    });
11176    print "Upgrade to $DBversion done (Bug 10363: There is no package for authorised values)\n";
11177    SetVersion($DBversion);
11178 }
11179
11180 $DBversion = "3.21.00.037";
11181 if ( CheckVersion($DBversion) ) {
11182    $dbh->do(q{
11183        INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11184        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')
11185    });
11186    $dbh->do(q{
11187        INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11188        VALUES ('RestrictionBlockRenewing','0','If patron is restricted, should renewal be allowed or blocked',NULL,'YesNo')
11189     });
11190    print "Upgrade to $DBversion done (Bug 8236: Prevent renewing if overdue or restriction)\n";
11191    SetVersion($DBversion);
11192 }
11193
11194 $DBversion = "3.21.00.038";
11195 if ( CheckVersion($DBversion) ) {
11196     $dbh->do(q|
11197         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11198         VALUES ('BatchCheckouts','0','','Enable or disable batch checkouts','YesNo')
11199     |);
11200     $dbh->do(q|
11201         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11202         VALUES ('BatchCheckoutsValidCategories','',NULL,'Patron categories allowed to checkout in a batch','Free')
11203     |);
11204     print "Upgrade to $DBversion done (Bug 11759: Add the batch checkout feature)\n";
11205     SetVersion($DBversion);
11206 }
11207
11208 $DBversion = "3.21.00.039";
11209 if ( CheckVersion($DBversion) ) {
11210     $dbh->do(q|
11211         ALTER TABLE creator_layouts ADD COLUMN oblique_title INT(1) NULL DEFAULT 1 AFTER guidebox
11212     |);
11213     print "Upgrade to $DBversion done (Bug 12194: Add column oblique_title to layouts)\n";
11214     SetVersion($DBversion);
11215 }
11216
11217 $DBversion = "3.21.00.040";
11218 if ( CheckVersion($DBversion) ) {
11219     $dbh->do(q{
11220         ALTER TABLE itemtypes
11221             ADD hideinopac TINYINT(1) NOT NULL DEFAULT 0
11222               AFTER sip_media_type,
11223             ADD searchcategory VARCHAR(80) DEFAULT NULL
11224               AFTER hideinopac;
11225     });
11226     print "Upgrade to $DBversion done (Bug 10937: Option to hide and group itemtypes from advanced search)\n";
11227     SetVersion($DBversion);
11228 }
11229
11230 $DBversion = "3.21.00.041";
11231 if ( CheckVersion($DBversion) ) {
11232     $dbh->do(q|
11233         ALTER TABLE issuingrules
11234             ADD chargeperiod_charge_at BOOLEAN NOT NULL DEFAULT  '0' AFTER chargeperiod
11235     |);
11236     print "Upgrade to $DBversion done (Bug 13590: Add ability to charge fines at start of charge period)\n";
11237     SetVersion($DBversion);
11238 }
11239
11240 $DBversion = "3.21.00.042";
11241 if ( CheckVersion($DBversion) ) {
11242     $dbh->do(q|
11243         ALTER TABLE items_search_fields
11244             MODIFY COLUMN authorised_values_category VARCHAR(32) DEFAULT NULL
11245     |);
11246     print "Upgrade to $DBversion done (Bug 15069: items_search_fields.authorised_values_category is still a varchar(32))\n";
11247     SetVersion($DBversion);
11248 }
11249
11250 $DBversion = "3.21.00.043";
11251 if ( CheckVersion($DBversion) ) {
11252     $dbh->do(q|
11253         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11254         VALUES ('EnableAdvancedCatalogingEditor','0','','Enable the Rancor advanced cataloging editor','YesNo')
11255     |);
11256     print "Upgrade to $DBversion done (Bug 11559: Professional cataloger's interface)\n";
11257     SetVersion($DBversion);
11258 }
11259
11260 $DBversion = "3.21.00.044";
11261 if ( CheckVersion($DBversion) ) {
11262     $dbh->do(q|
11263         CREATE TABLE localization (
11264             localization_id int(11) NOT NULL AUTO_INCREMENT,
11265             entity varchar(16) COLLATE utf8_unicode_ci NOT NULL,
11266             code varchar(64) COLLATE utf8_unicode_ci NOT NULL,
11267             lang varchar(25) COLLATE utf8_unicode_ci NOT NULL,
11268             translation text COLLATE utf8_unicode_ci,
11269             PRIMARY KEY (localization_id),
11270             UNIQUE KEY entity_code_lang (entity,code,lang)
11271         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
11272     |);
11273     print "Upgrade to $DBversion done (Bug 14100: Generic solution for language overlay)\n";
11274     SetVersion($DBversion);
11275 }
11276
11277 $DBversion = "3.21.00.045";
11278 if ( CheckVersion($DBversion) ) {
11279     $dbh->do(q|
11280         ALTER TABLE opac_news
11281             ADD borrowernumber int(11) default NULL
11282                 AFTER number
11283     |);
11284     $dbh->do(q|
11285         ALTER TABLE opac_news
11286             ADD CONSTRAINT borrowernumber_fk
11287                 FOREIGN KEY (borrowernumber)
11288                 REFERENCES borrowers (borrowernumber)
11289                 ON DELETE SET NULL ON UPDATE CASCADE
11290     |);
11291     print "Upgrade to $DBversion done (Bug 14246: (newsauthor) Add borrowernumber to koha_news)\n";
11292     SetVersion($DBversion);
11293 }
11294
11295 $DBversion = "3.21.00.046";
11296 if ( CheckVersion($DBversion) ) {
11297     $dbh->do(q{
11298         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11299         VALUES ('NewsAuthorDisplay','none','none|opac|staff|both','Display the author name for news items.','Choice')
11300     });
11301     print "Upgrade to $DBversion done (Bug 14247: (newsauthor) System preference for news author display)\n";
11302     SetVersion($DBversion);
11303 }
11304
11305 $DBversion = "3.21.00.047";
11306 if(CheckVersion($DBversion)) {
11307     $dbh->do(q{
11308         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11309         VALUES ('IndependentBranchesPatronModifications','0','Show only modification request for the logged in branch','','YesNo')
11310     });
11311     print "Upgrade to $DBversion done (Bug 10904: Limit patron update request management by branch)\n";
11312     SetVersion($DBversion);
11313 }
11314
11315 $DBversion = '3.21.00.048';
11316 if ( CheckVersion($DBversion) ) {
11317     my $create_table_issues = @{ $dbh->selectall_arrayref(q|SHOW CREATE TABLE issues|) }[0]->[1];
11318     if ($create_table_issues !~ m|UNIQUE KEY.*itemnumber| ) {
11319         $dbh->do(q|ALTER TABLE issues ADD CONSTRAINT UNIQUE KEY (itemnumber)|);
11320     }
11321     print "Upgrade to $DBversion done (Bug 14978: Make sure issues.itemnumber is a unique key)\n";
11322     SetVersion($DBversion);
11323 }
11324
11325 $DBversion = "3.21.00.049";
11326 if ( CheckVersion($DBversion) ) {
11327     $dbh->do(q{UPDATE systempreferences SET variable = 'AudioAlerts' WHERE variable = 'soundon'});
11328
11329     $dbh->do(q{
11330         CREATE TABLE audio_alerts (
11331             id int(11) NOT NULL AUTO_INCREMENT,
11332             precedence smallint(5) unsigned NOT NULL,
11333             selector varchar(255) NOT NULL,
11334             sound varchar(255) NOT NULL,
11335             PRIMARY KEY (id),
11336             KEY precedence (precedence)
11337         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
11338     });
11339
11340     $dbh->do(q{
11341         INSERT IGNORE INTO audio_alerts VALUES
11342         (1, 1, '.audio-alert-action', 'opening.ogg'),
11343         (2, 2, '.audio-alert-warning', 'critical.ogg'),
11344         (3, 3, '.audio-alert-success', 'beep.ogg');
11345     });
11346
11347     print "Upgrade to $DBversion done (Bug 11431: Add additional sound options for warnings)\n";
11348     SetVersion($DBversion);
11349 }
11350
11351 $DBversion = "3.21.00.050";
11352 if(CheckVersion($DBversion)) {
11353     $dbh->do(q{
11354         INSERT INTO letter ( module, code, branchcode, name, is_html, title, content, message_transport_type )
11355         VALUES ( 'circulation', 'OVERDUES_SLIP', '', 'Overdues Slip', '0', 'OVERDUES_SLIP', 'The following item(s) is/are currently overdue:
11356
11357 <item>"<<biblio.title>>" by <<biblio.author>>, <<items.itemcallnumber>>, Barcode: <<items.barcode>> Fine: <<items.fine>></item>
11358 ', 'print' )
11359     });
11360     print "Upgrade to $DBversion done (Bug 12933: Add ability to print overdue slip from staff intranet)\n";
11361     SetVersion($DBversion);
11362 }
11363
11364 $DBversion = "3.21.00.051";
11365 if ( CheckVersion($DBversion) ) {
11366     $dbh->do(q{
11367         ALTER TABLE virtualshelves
11368             CHANGE COLUMN sortfield sortfield VARCHAR(16) DEFAULT 'title'
11369     });
11370     $dbh->do(q{
11371         UPDATE virtualshelves
11372         SET sortfield='title'
11373             WHERE sortfield IS NULL;
11374     });
11375     print "Upgrade to $DBversion done (Bug 14544: Move the list related code to Koha::Virtualshelves)\n";
11376     SetVersion($DBversion);
11377 }
11378
11379 $DBversion = "3.21.00.052";
11380 if ( CheckVersion($DBversion) ) {
11381     $dbh->do(q{
11382         ALTER TABLE serial
11383             ADD COLUMN publisheddatetext VARCHAR(100) DEFAULT NULL AFTER publisheddate
11384     });
11385     print "Upgrade to $DBversion done (Bug 8296: Add descriptive (text) published date field for serials)\n";
11386     SetVersion($DBversion);
11387 }
11388
11389 $DBversion = "3.21.00.053";
11390 if ( CheckVersion($DBversion) ) {
11391     my $query = q{ SELECT * FROM itemtypes ORDER BY description };
11392     my $sth   = C4::Context->dbh->prepare($query);
11393     $sth->execute;
11394     my $suggestion_formats = $sth->fetchall_arrayref( {} );
11395
11396     foreach my $format (@$suggestion_formats) {
11397         $dbh->do(
11398             q|
11399             INSERT IGNORE INTO authorised_values (category, authorised_value, lib, lib_opac, imageurl)
11400             VALUES (?, ?, ?, ?, ?)
11401         |, {},
11402             'SUGGEST_FORMAT', $format->{itemtype}, $format->{description}, $format->{description},
11403             $format->{imageurl}
11404         );
11405     }
11406     print "Upgrade to $DBversion done (Bug 9468: create new SUGGEST_FORMAT authorised_value list)\n";
11407     SetVersion($DBversion);
11408 }
11409
11410 $DBversion = "3.21.00.054";
11411 if(CheckVersion($DBversion)) {
11412     $dbh->do(q{
11413         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11414         VALUES('MergeReportFields','','Displayed fields for deleted MARC records after merge',NULL,'Free')
11415     });
11416     print "Upgrade to $DBversion done (Bug 8064: Merge several biblio records)\n";
11417     SetVersion($DBversion);
11418 }
11419
11420 $DBversion = "3.21.00.055";
11421 if ( CheckVersion($DBversion) ) {
11422     print "Upgrade to $DBversion done (Koha 3.22 beta)\n";
11423     SetVersion($DBversion);
11424 }
11425
11426 $DBversion = "3.21.00.056";
11427 if(CheckVersion($DBversion)) {
11428     $dbh->do(q{
11429         UPDATE systempreferences
11430         SET
11431             options='metric|us|iso|dmydot',
11432             explanation='Define global date format (us mm/dd/yyyy, metric dd/mm/yyy, ISO yyyy-mm-dd, DMY separated by dots dd.mm.yyyy)'
11433         WHERE variable='dateformat'
11434     });
11435     print "Upgrade to $DBversion done (Bug 12072: New dateformat dd.mm.yyyy)\n";
11436     SetVersion($DBversion);
11437 }
11438
11439 $DBversion = "3.22.00.000";
11440 if ( CheckVersion($DBversion) ) {
11441     print "Upgrade to $DBversion done (Koha 3.22)\n";
11442     SetVersion($DBversion);
11443 }
11444
11445 $DBversion = "3.23.00.000";
11446 if ( CheckVersion($DBversion) ) {
11447     print "Upgrade to $DBversion done (The year of the monkey will be here soon.)\n";
11448     SetVersion ($DBversion);
11449 }
11450
11451 $DBversion = "3.23.00.001";
11452 if(CheckVersion($DBversion)) {
11453     $dbh->do(q{
11454         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11455         VALUES (
11456             'DefaultToLoggedInLibraryCircRules',  '0', NULL ,  'If enabled, circ rules editor will default to the logged in library''s rules, rather than the ''all libraries'' rules.',  'YesNo'
11457         ), (
11458             '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'
11459         )
11460     });
11461
11462     print "Upgrade to $DBversion done (Bug 11625 - Add pref DefaultToLoggedInLibraryCircRules and DefaultToLoggedInLibraryNoticesSlips)\n";
11463     SetVersion($DBversion);
11464 }
11465
11466 $DBversion = "3.23.00.002";
11467 if(CheckVersion($DBversion)) {
11468     $dbh->do(q{
11469         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11470         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')
11471     });
11472
11473     print "Upgrade to $DBversion done (Bug 11747 - add pref DefaultToLoggedInLibraryOverdueTriggers)\n";
11474     SetVersion($DBversion);
11475 }
11476
11477 $DBversion = "3.23.00.003";
11478 if(CheckVersion($DBversion)) {
11479     $dbh->do(q{
11480         UPDATE letter SET name = "Hold Slip" WHERE name = "Reserve Slip"
11481     });
11482     $dbh->do(q{
11483         UPDATE letter SET title = "Hold Slip" WHERE title = "Reserve Slip";
11484     });
11485
11486     print "Upgrade to $DBversion done (Bug 8085 - Rename 'Reserve slip' to 'Hold slip')\n";
11487     SetVersion($DBversion);
11488 }
11489
11490 $DBversion = "3.23.00.004";
11491 if ( CheckVersion($DBversion) ) {
11492     $dbh->do(q{
11493         DROP TABLE IF EXISTS `stopwords`;
11494     });
11495     print "Upgrade to $DBversion done (Bug 9819 - stopwords related code should be removed)\n";
11496     SetVersion($DBversion);
11497 }
11498
11499 $DBversion = "3.23.00.005";
11500 if ( CheckVersion($DBversion) ) {
11501     $dbh->do(q{
11502         UPDATE permissions SET description = 'Manage circulation rules' WHERE description = 'manage circulation rules'
11503     });
11504     $dbh->do(q{
11505         UPDATE permissions SET description = 'Manage staged MARC records, including completing and reversing imports' WHERE description = 'Managed staged MARC records, including completing and reversing imports'
11506     });
11507     print "Upgrade to $DBversion done (Bug 11569 - Typo in userpermissions.sql)\n";
11508     SetVersion($DBversion);
11509 }
11510 $DBversion = "3.23.00.006";
11511 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
11512    $dbh->do("
11513        ALTER TABLE serial
11514         ADD serialseq_x VARCHAR( 100 ) NULL DEFAULT NULL AFTER serialseq,
11515         ADD serialseq_y VARCHAR( 100 ) NULL DEFAULT NULL AFTER serialseq_x,
11516         ADD serialseq_z VARCHAR( 100 ) NULL DEFAULT NULL AFTER serialseq_y
11517    ");
11518
11519     my $sth = $dbh->prepare("SELECT * FROM subscription");
11520     $sth->execute();
11521
11522     my $sth2 = $dbh->prepare("SELECT * FROM subscription_numberpatterns WHERE id = ?");
11523
11524     my $sth3 = $dbh->prepare("UPDATE serial SET serialseq_x = ?, serialseq_y = ?, serialseq_z = ? WHERE serialid = ?");
11525
11526     foreach my $subscription ( $sth->fetchrow_hashref() ) {
11527         next if !defined($subscription);
11528         $sth2->execute( $subscription->{numberpattern} );
11529         my $number_pattern = $sth2->fetchrow_hashref();
11530
11531         my $numbering_method = $number_pattern->{numberingmethod};
11532         # Get all the data between the enumeration values, we need
11533         # to split each enumeration string based on these values.
11534         my @splits = split( /\{[XYZ]\}/, $numbering_method );
11535         # Get the order in which the X Y and Z values are used
11536         my %indexes;
11537         foreach my $i (qw(X Y Z)) {
11538             $indexes{$i} = index( $numbering_method, "{$i}" );
11539             delete $indexes{$i} if $indexes{$i} == -1;
11540         }
11541         my @indexes = sort { $indexes{$a} <=> $indexes{$b} } keys(%indexes);
11542
11543         my @serials = @{
11544             $dbh->selectall_arrayref(
11545                 "SELECT * FROM serial WHERE subscriptionid = $subscription->{subscriptionid}",
11546                 { Slice => {} }
11547             )
11548         };
11549
11550         foreach my $serial (@serials) {
11551             my $serialseq = $serial->{serialseq};
11552             my %enumeration_data;
11553
11554             ## We cannot split on multiple values at once,
11555             ## so let's replace each of those values with __SPLIT__
11556             if (@splits) {
11557                 for my $split_item (@splits) {
11558                     my $quoted_split = quotemeta($split_item);
11559                     $serialseq =~ s/$quoted_split/__SPLIT__/;
11560                 }
11561                 (
11562                     undef,
11563                     $enumeration_data{ $indexes[0] // q{} },
11564                     $enumeration_data{ $indexes[1] // q{} },
11565                     $enumeration_data{ $indexes[2] // q{} }
11566                 ) = split( /__SPLIT__/, $serialseq );
11567             }
11568             else
11569             {    ## Nothing to split on means the only thing in serialseq is a single placeholder e.g. {X}
11570                 $enumeration_data{ $indexes[0] } = $serialseq;
11571             }
11572
11573             $sth3->execute(
11574                     $enumeration_data{'X'},
11575                     $enumeration_data{'Y'},
11576                     $enumeration_data{'Z'},
11577                     $serial->{serialid},
11578             );
11579         }
11580     }
11581
11582     print "Upgrade to $DBversion done ( Bug 8956 - Split serials enumeration data into separate fields )\n";
11583     SetVersion($DBversion);
11584 }
11585
11586 $DBversion = "3.23.00.007";
11587 if ( CheckVersion($DBversion) ) {
11588     $dbh->do("SET FOREIGN_KEY_CHECKS=0");
11589     $dbh->do("ALTER TABLE overduerules RENAME old_overduerules");
11590     $dbh->do("CREATE TABLE overduerules (
11591         `overduerules_id` int(11) NOT NULL AUTO_INCREMENT,
11592         `branchcode` varchar(10) NOT NULL DEFAULT '',
11593         `categorycode` varchar(10) NOT NULL DEFAULT '',
11594         `delay1` int(4) DEFAULT NULL,
11595         `letter1` varchar(20) DEFAULT NULL,
11596         `debarred1` varchar(1) DEFAULT '0',
11597         `delay2` int(4) DEFAULT NULL,
11598         `debarred2` varchar(1) DEFAULT '0',
11599         `letter2` varchar(20) DEFAULT NULL,
11600         `delay3` int(4) DEFAULT NULL,
11601         `letter3` varchar(20) DEFAULT NULL,
11602         `debarred3` int(1) DEFAULT '0',
11603         PRIMARY KEY (`overduerules_id`),
11604         UNIQUE KEY `overduerules_branch_cat` (`branchcode`,`categorycode`)
11605         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
11606     $dbh->do("INSERT INTO overduerules(branchcode, categorycode, delay1, letter1, debarred1, delay2, debarred2, letter2, delay3, letter3, debarred3) SELECT * FROM old_overduerules");
11607     $dbh->do("DROP TABLE old_overduerules");
11608     $dbh->do("ALTER TABLE overduerules_transport_types
11609               ADD COLUMN overduerules_id int(11) NOT NULL");
11610     my $mtts = $dbh->selectall_arrayref("SELECT * FROM overduerules_transport_types", { Slice => {} });
11611     $dbh->do("DELETE FROM overduerules_transport_types");
11612     $dbh->do("ALTER TABLE overduerules_transport_types
11613               DROP FOREIGN KEY overduerules_fk,
11614               ADD FOREIGN KEY overduerules_transport_types_fk (overduerules_id) REFERENCES overduerules (overduerules_id) ON DELETE CASCADE ON UPDATE CASCADE,
11615               DROP COLUMN branchcode,
11616               DROP COLUMN categorycode");
11617     my $s = $dbh->prepare("INSERT INTO overduerules_transport_types (overduerules_id, id, letternumber, message_transport_type) "
11618                          ." VALUES((SELECT overduerules_id FROM overduerules WHERE branchcode = ? AND categorycode = ?),?,?,?)");
11619     foreach my $mtt(@$mtts){
11620         $s->execute($mtt->{branchcode}, $mtt->{categorycode}, $mtt->{id}, $mtt->{letternumber}, $mtt->{message_transport_type} );
11621     }
11622     $dbh->do("SET FOREIGN_KEY_CHECKS=1");
11623
11624     print "Upgrade to $DBversion done (Bug 13624 - Remove columns branchcode, categorytype from table overduerules_transport_types)\n";
11625     SetVersion($DBversion);
11626 }
11627
11628 $DBversion = "3.23.00.008";
11629 if ( CheckVersion($DBversion) ) {
11630
11631     $dbh->do(q{ALTER TABLE borrowers ADD privacy_guarantor_checkouts BOOLEAN NOT NULL DEFAULT '0' AFTER privacy});
11632
11633     $dbh->do(q{ALTER TABLE deletedborrowers ADD privacy_guarantor_checkouts BOOLEAN NOT NULL DEFAULT '0' AFTER privacy});
11634
11635     $dbh->do(q{
11636         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type )
11637         VALUES (
11638             'AllowStaffToSetCheckoutsVisibilityForGuarantor',  '0', NULL,
11639             'If enabled, library staff can set a patron''s checkouts to be visible to linked patrons from the opac.',  'YesNo'
11640         ), (
11641             'AllowPatronToSetCheckoutsVisibilityForGuarantor',  '0', NULL,
11642             'If enabled, the patron can set checkouts to be visible to  his or her guarantor',  'YesNo'
11643         )
11644     });
11645
11646     print "Upgrade to $DBversion done (Bug 9303 - relative's checkouts in the opac)\n";
11647     SetVersion($DBversion);
11648 }
11649
11650 $DBversion = "3.23.00.009";
11651 if ( CheckVersion($DBversion) ) {
11652     $dbh->do(q{
11653         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type ) VALUES
11654         ( 'EnablePayPalOpacPayments',  '0', NULL ,  'Enables the ability to pay fees and fines from  the OPAC via PayPal',  'YesNo' ),
11655         ( 'PayPalChargeDescription',  'Koha fee payment', NULL ,  'This preference defines what the user will see the charge listed as in PayPal',  'Free' ),
11656         ( 'PayPalPwd',  '', NULL ,  'Your PayPal API password',  'Free' ),
11657         ( 'PayPalSandboxMode',  '1', NULL ,  'If enabled, the system will use PayPal''s sandbox server for testing, rather than the production server.',  'YesNo' ),
11658         ( 'PayPalSignature',  '', NULL ,  'Your PayPal API signature',  'Free' ),
11659         ( 'PayPalUser',  '', NULL ,  'Your PayPal API username ( email address )',  'Free' )
11660     });
11661
11662     print "Upgrade to $DBversion done (Bug 11622 - Add ability to pay fees and fines from OPAC via PayPal)\n";
11663     SetVersion($DBversion);
11664 }
11665
11666 $DBversion = "3.23.00.010";
11667 if ( CheckVersion($DBversion) ) {
11668     $dbh->do(q{
11669         ALTER TABLE issuingrules ADD cap_fine_to_replacement_price BOOLEAN NOT NULL DEFAULT '0' AFTER overduefinescap
11670     });
11671
11672     print "Upgrade to $DBversion done (Bug 9129 - Add the ability to set the maximum fine for an item to its replacement price)\n";
11673     SetVersion($DBversion);
11674 }
11675
11676 $DBversion = "3.23.00.011";
11677 if ( CheckVersion($DBversion) ) {
11678     $dbh->do(q{
11679         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES ('HoldFeeMode','not_always','always|not_always','Set the hold fee mode','Choice')
11680     });
11681
11682     print "Upgrade to $DBversion done (Bug 13592 - Hold fee not being applied on placing a hold)\n";
11683     SetVersion($DBversion);
11684 }
11685
11686 $DBversion = "3.23.00.012";
11687 if ( CheckVersion($DBversion) ) {
11688     $dbh->do(q{
11689         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')
11690     });
11691
11692     print "Upgrade to $DBversion done (Bug 15380 - Move the authority types related code to Koha::Authority::Type[s] - part 1)\n";
11693     SetVersion($DBversion);
11694 }
11695
11696 $DBversion = "3.23.00.013";
11697 if ( CheckVersion($DBversion) ) {
11698     $dbh->do(q{
11699         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')
11700     });
11701     $dbh->do(q{
11702         CREATE TABLE IF NOT EXISTS `items_last_borrower` (
11703   `id` int(11) NOT NULL AUTO_INCREMENT,
11704   `itemnumber` int(11) NOT NULL,
11705   `borrowernumber` int(11) NOT NULL,
11706   `created_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
11707   PRIMARY KEY (`id`),
11708   UNIQUE KEY `itemnumber` (`itemnumber`),
11709   KEY `borrowernumber` (`borrowernumber`),
11710   CONSTRAINT `items_last_borrower_ibfk_2` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
11711   CONSTRAINT `items_last_borrower_ibfk_1` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE
11712 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
11713     });
11714
11715     print "Upgrade to $DBversion done (Bug 14945 - Add the ability to store the last patron to return an item)\n";
11716     SetVersion($DBversion);
11717
11718 }
11719
11720 $DBversion = "3.23.00.014";
11721 if ( CheckVersion($DBversion) ) {
11722     $dbh->do(q{
11723         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
11724 VALUES ('ClaimsBccCopy','0','','Bcc the ClaimAcquisition and ClaimIssues alerts','YesNo')
11725     });
11726
11727     print "Upgrade to $DBversion done (Bug 10076 - Add Bcc syspref for claimacquisition and clamissues)\n";
11728     SetVersion($DBversion);
11729 }
11730
11731 $DBversion = "3.23.00.015";
11732 if ( CheckVersion($DBversion) ) {
11733     $dbh->do(q{
11734         UPDATE letter SET code = "HOLD_SLIP" WHERE code = "RESERVESLIP";
11735     });
11736
11737     print "Upgrade to $DBversion done (Bug 15443 - Re-code RESERVESLIP as HOLD_SLIP)\n";
11738     SetVersion($DBversion);
11739 }
11740
11741 $DBversion = "3.23.00.016";
11742 if ( CheckVersion($DBversion) ) {
11743     $dbh->do(q{
11744     INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
11745     VALUES ('OpacResetPassword',  '0','','Shows the ''Forgot your password?'' link in the OPAC','YesNo');
11746 });
11747     $dbh->do(q{
11748     CREATE TABLE IF NOT EXISTS borrower_password_recovery (
11749       borrowernumber int(11) NOT NULL,
11750       uuid varchar(128) NOT NULL,
11751       valid_until timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
11752       PRIMARY KEY (borrowernumber),
11753       KEY borrowernumber (borrowernumber)
11754     ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
11755 });
11756     $dbh->do(q{
11757     INSERT IGNORE INTO `letter` (module, code, branchcode, name, is_html, title, content, message_transport_type)
11758     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');
11759
11760     });
11761
11762     print "Upgrade to $DBversion done (Bug 8753 - Add forgot password link to OPAC)\n";
11763     SetVersion($DBversion);
11764 }
11765
11766 $DBversion = "3.23.00.017";
11767 if ( CheckVersion($DBversion) ) {
11768
11769 $dbh->do(q{
11770     DELETE FROM uploaded_files
11771     WHERE COALESCE(permanent,0)=0 AND dir='koha_upload'
11772 });
11773
11774 my $tmp = C4::Context->temporary_directory . '/koha_upload';
11775 remove_tree( $tmp ) if -d $tmp;
11776
11777     print "Upgrade to $DBversion done (Bug 14893 - Separate temporary storage per instance in Upload.pm)\n";
11778     SetVersion($DBversion);
11779
11780 }
11781
11782 $DBversion = "3.23.00.018";
11783 if ( CheckVersion($DBversion) ) {
11784     $dbh->do(q{
11785         UPDATE systempreferences SET value="0" where type="YesNo" and value="";
11786     });
11787
11788     print "Upgrade to $DBversion done (Bug 15446 - Fix systempreferences rows where type=YesNo and value='')\n";
11789     SetVersion($DBversion);
11790 }
11791
11792 $DBversion = "3.23.00.019";
11793 if ( CheckVersion($DBversion) ) {
11794     $dbh->do(q{
11795         UPDATE `authorised_values` SET `lib`='Non-fiction' WHERE `lib`='Non Fiction';
11796     });
11797
11798     print "Upgrade to $DBversion done (Bug 15411 - Change Non Fiction to Non-fiction in authorised_values)\n";
11799     SetVersion($DBversion);
11800 }
11801
11802 $DBversion = "3.23.00.020";
11803 if ( CheckVersion($DBversion) ) {
11804     $dbh->do(q{
11805         CREATE TABLE  sms_providers (
11806            id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
11807            name VARCHAR( 255 ) NOT NULL ,
11808            domain VARCHAR( 255 ) NOT NULL ,
11809            UNIQUE (
11810                name
11811            )
11812         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
11813     });
11814
11815     $dbh->do(q{
11816         ALTER TABLE borrowers ADD sms_provider_id INT( 11 ) NULL DEFAULT NULL AFTER smsalertnumber;
11817     });
11818     $dbh->do(q{
11819         ALTER TABLE borrowers ADD FOREIGN KEY ( sms_provider_id ) REFERENCES sms_providers ( id ) ON UPDATE CASCADE ON DELETE SET NULL;
11820     });
11821     $dbh->do(q{
11822         ALTER TABLE deletedborrowers ADD sms_provider_id INT( 11 ) NULL DEFAULT NULL AFTER smsalertnumber;
11823     });
11824
11825     print "Upgrade to $DBversion done (Bug 9021 - Add SMS via email as an alternative to SMS services via SMS::Send drivers)\n";
11826     SetVersion($DBversion);
11827 }
11828
11829 $DBversion = "3.23.00.021";
11830 if ( CheckVersion($DBversion) ) {
11831     $dbh->do(q{
11832         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES ('ShowAllCheckins', '0', '', 'Show all checkins', 'YesNo');
11833     });
11834
11835     print "Upgrade to $DBversion done (Bug 15736 - Add a preference to control whether all items should be shown in checked-in items list)\n";
11836     SetVersion($DBversion);
11837 }
11838
11839 $DBversion = "3.23.00.022";
11840 if ( CheckVersion($DBversion) ) {
11841     $dbh->do(q{ ALTER TABLE tags_all MODIFY COLUMN borrowernumber INT(11) });
11842     $dbh->do(q{ ALTER TABLE tags_all drop FOREIGN KEY tags_borrowers_fk_1 });
11843     $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 });
11844     $dbh->do(q{ ALTER TABLE tags_approval DROP FOREIGN KEY tags_approval_borrowers_fk_1 });
11845     $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 });
11846
11847     print "Upgrade to $DBversion done (Bug 13534 - Deleting staff patron will delete tags approved by this patron)\n";
11848     SetVersion($DBversion);
11849 }
11850
11851 $DBversion = "3.23.00.023";
11852 if ( CheckVersion($DBversion) ) {
11853     $dbh->do(q{
11854         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11855         VALUES('OpenLibrarySearch','0','If Yes Open Library search results will show in OPAC',NULL,'YesNo');
11856     });
11857
11858     print "Upgrade to $DBversion done (Bug 6624 - Allow Koha to use the new read API from OpenLibrary)\n";
11859     SetVersion($DBversion);
11860 }
11861
11862 $DBversion = "3.23.00.024";
11863 if ( CheckVersion($DBversion) ) {
11864     $dbh->do(q{
11865         ALTER TABLE deletedborrowers MODIFY COLUMN userid VARCHAR(75) DEFAULT NULL;
11866     });
11867
11868     $dbh->do(q{
11869         ALTER TABLE deletedborrowers MODIFY COLUMN password VARCHAR(60) DEFAULT NULL;
11870     });
11871
11872     print "Upgrade to $DBversion done (Bug 15517 - Tables borrowers and deletedborrowers differ again)\n";
11873     SetVersion($DBversion);
11874 }
11875
11876 $DBversion = "3.23.00.025";
11877 if ( CheckVersion($DBversion) ) {
11878     $dbh->do(q{
11879         DROP TABLE IF EXISTS nozebra;
11880     });
11881
11882     print "Upgrade to $DBversion done (Bug 15526 - Drop nozebra database table)\n";
11883     SetVersion($DBversion);
11884 }
11885
11886 $DBversion = "3.23.00.026";
11887 if ( CheckVersion($DBversion) ) {
11888     $dbh->do(q{
11889         UPDATE systempreferences SET value = CONCAT_WS('|', IF(value='', NULL, value), "password") WHERE variable="PatronSelfRegistrationBorrowerUnwantedField" AND value NOT LIKE "%password%";
11890     });
11891
11892     print "Upgrade to $DBversion done (Bug 15343 - Allow patrons to choose their own password on self registration)\n";
11893     SetVersion($DBversion);
11894 }
11895
11896 $DBversion = "3.23.00.027";
11897 if ( CheckVersion($DBversion) ) {
11898     my ( $db_value ) = $dbh->selectrow_array(q|SELECT count(*) FROM branches|);
11899     my $pref_value = C4::Context->preference("singleBranchMode") || 0;
11900     if ( $db_value > 1 and $pref_value == 1 ) {
11901         warn "WARNING: You have more than 1 libraries in your branches tables but the singleBranchMode system preference is on.\n";
11902         warn "This configuration does not make sense. The system preference is going to be deleted,\n";
11903         warn "and this parameter will be based on the number of libraries defined.\n";
11904     }
11905     $dbh->do(q|DELETE FROM systempreferences WHERE variable="singleBranchMode"|);
11906
11907     print "Upgrade to $DBversion done (Bug 4941 - Can't set branch in staff client when singleBranchMode is enabled)\n";
11908     SetVersion($DBversion);
11909 }
11910
11911 $DBversion = "3.23.00.028";
11912 if ( CheckVersion($DBversion) ) {
11913     $dbh->do(q{
11914         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';
11915     });
11916
11917     print "Upgrade to $DBversion done (Bug 14658 - Split PatronSelfRegistrationBorrowerUnwantedField into two preferences for creating and editing)\n";
11918     SetVersion($DBversion);
11919 }
11920
11921 $DBversion = "3.23.00.029";
11922 if ( CheckVersion($DBversion) ) {
11923
11924     # move marc21_field_003.pl 040c and 040d to marc21_orgcode.pl
11925     $dbh->do(q{
11926         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' );
11927     });
11928     $dbh->do(q{
11929         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' );
11930     });
11931
11932     print "Upgrade to $DBversion done (Bug 14199 - Unify all organization code plugins)\n";
11933     SetVersion($DBversion);
11934 }
11935
11936 $DBversion = "3.23.00.030";
11937 if(CheckVersion($DBversion)) {
11938     $dbh->do(q{
11939         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
11940         VALUES ('OpacMaintenanceNotice','','','A user-defined block of HTML to appear on screen when OpacMaintenace is enabled','Textarea')
11941     });
11942
11943     print "Upgrade to $DBversion done (Bug 15311: Let libraries set text to display when OpacMaintenance = on)\n";
11944     SetVersion($DBversion);
11945 }
11946
11947 $DBversion = "3.23.00.031";
11948 if(CheckVersion($DBversion)) {
11949     $dbh->do(q{
11950         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11951         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')
11952     });
11953
11954     print "Upgrade to $DBversion done (Bug 14395 - Two different ways to calculate 'No renewal before')\n";
11955     SetVersion($DBversion);
11956 }
11957
11958 $DBversion = "3.23.00.032";
11959 if ( CheckVersion($DBversion) ) {
11960     $dbh->do(q{
11961    -- Add issue_id to accountlines table
11962     ALTER TABLE accountlines ADD issue_id INT(11) NULL DEFAULT NULL AFTER accountlines_id;
11963     });
11964
11965 ## Close out any accruing fines with no current issue
11966     $dbh->do(q{
11967     UPDATE accountlines LEFT JOIN issues USING ( itemnumber, borrowernumber ) SET accounttype = 'F' WHERE accounttype = 'FU' and issues.issue_id IS NULL;
11968     });
11969
11970 ## Close out any extra not really accruing fines, keep only the latest accring fine
11971     $dbh->do(q{
11972     UPDATE accountlines a1
11973     LEFT JOIN (SELECT MAX(accountlines_id) AS keeper,
11974                       borrowernumber,
11975                       itemnumber
11976                FROM   accountlines
11977                WHERE  accounttype = 'FU'
11978                GROUP BY borrowernumber, itemnumber
11979               ) a2 USING ( borrowernumber, itemnumber )
11980     SET    a1.accounttype = 'F'
11981     WHERE  a1.accounttype = 'FU'
11982     AND  a1.accountlines_id != a2.keeper;
11983     });
11984
11985 ## Update the unclosed fines to add the current issue_id to them
11986     $dbh->do(q{
11987     UPDATE accountlines LEFT JOIN issues USING ( itemnumber ) SET accountlines.issue_id = issues.issue_id WHERE accounttype = 'FU'; 
11988     });
11989
11990     print "Upgrade to $DBversion done (Bug 15675 - Add issue_id column to accountlines and use it for updating fines)\n";
11991     SetVersion($DBversion);
11992 }
11993
11994 $DBversion = "3.23.00.033";
11995 if ( CheckVersion($DBversion) ) {
11996     $dbh->do(q{
11997     UPDATE systempreferences SET value = CONCAT_WS('|', IF(value = '', NULL, value), 'cardnumber') WHERE variable = 'PatronSelfRegistrationBorrowerUnwantedField' AND value NOT LIKE '%cardnumber%';
11998     });
11999
12000     $dbh->do(q{
12001     UPDATE systempreferences SET value = CONCAT_WS('|', IF(value = '', NULL, value), 'categorycode') WHERE variable = 'PatronSelfRegistrationBorrowerUnwantedField' AND value NOT LIKE '%categorycode%';
12002     });
12003
12004     print "Upgrade to $DBversion done (Bug 14659 - Allow patrons to enter card number and patron category on OPAC registration page)\n";
12005     SetVersion($DBversion);
12006 }
12007
12008 $DBversion = "3.23.00.034";
12009 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12010     $dbh->do(q{
12011         ALTER TABLE `items` ADD `new` VARCHAR(32) NULL AFTER `stocknumber`;
12012     });
12013     $dbh->do(q{
12014         ALTER TABLE `deleteditems` ADD `new` VARCHAR(32) NULL AFTER `stocknumber`;
12015     });
12016     print "Upgrade to $DBversion done (Bug 11023: Adds field 'new' in items and deleteditems tables)\n";
12017     SetVersion($DBversion);
12018 }
12019
12020 $DBversion = "3.23.00.035";
12021 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12022     $dbh->do(q{
12023         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('HTML5MediaYouTube',0,'Embed|Don\'t embed','YouTube links as videos','YesNo');
12024     });
12025     print "Upgrade to $DBversion done (Bug 14168 - enhance streaming cataloging to include youtube)\n";
12026
12027     SetVersion($DBversion);
12028     }
12029
12030 $DBversion = "3.23.00.036";
12031 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12032     $dbh->do(q{
12033     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');
12034     });
12035     print "Upgrade to $DBversion done (Bug 12803 - Add ability to skip closed libraries when generating the holds queue)\n";
12036     SetVersion($DBversion);
12037     }
12038
12039 $DBversion = "3.23.00.037";
12040 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12041 ## Add the new currency.archived column
12042     $dbh->do(q{
12043     ALTER TABLE currency ADD column archived tinyint(1) DEFAULT 0;
12044     });
12045 ## Set currency=NULL if empty (just in case)
12046     $dbh->do(q{
12047     UPDATE aqorders SET currency=NULL WHERE currency="";
12048     });
12049 ## Insert the missing currency and mark them as archived before adding the FK
12050     $dbh->do(q{
12051     INSERT INTO currency(currency, archived) SELECT distinct currency, 1 FROM aqorders WHERE currency NOT IN (SELECT currency FROM currency);
12052     });
12053 ## Correct the field length in aqorders before adding FK too
12054     $dbh->do(q{ ALTER TABLE aqorders MODIFY COLUMN currency varchar(10) default NULL; });
12055 ## And finally add the FK
12056     $dbh->do(q{
12057     ALTER TABLE aqorders ADD FOREIGN KEY (currency) REFERENCES currency(currency) ON DELETE SET NULL ON UPDATE SET null;
12058     });
12059
12060     print "Upgrade to $DBversion done (Bug 15084 - Move the currency related code to Koha::Acquisition::Currenc[y|ies])\n";
12061     SetVersion($DBversion);
12062 }
12063
12064 $DBversion = "3.23.00.038";
12065 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12066     $dbh->do(q{
12067     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');
12068     });
12069     print "Upgrade to $DBversion done (Bug 14694 - Make decreaseloanHighHolds more flexible)\n";
12070     SetVersion($DBversion);
12071 }
12072
12073 $DBversion = "3.23.00.039";
12074 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12075
12076     $dbh->do(q{
12077     ALTER TABLE suggestions
12078     MODIFY COLUMN currency varchar(10) default NULL;
12079     });
12080     $dbh->do(q{
12081     ALTER TABLE aqbooksellers
12082     MODIFY COLUMN currency varchar(10) default NULL;
12083     });
12084     print "Upgrade to $DBversion done (Bug 15084 - Move the currency related code to Koha::Acquisition::Currenc[y|ies])\n";
12085     SetVersion($DBversion);
12086 }
12087
12088
12089 $DBversion = "3.23.00.040";
12090 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12091
12092     my $c = $dbh->selectrow_array('SELECT COUNT(*) FROM systempreferences WHERE variable="intranetcolorstylesheet" AND value="blue.css"');
12093
12094     if ( $c ) {
12095         print "WARNING: You are using a stylesheeet which has been removed from the Koha codebase.\n";
12096         print "Update your intranetcolorstylesheet.\n";
12097     }
12098     print "Upgrade to $DBversion done (Bug 16019 - Check intranetcolorstylesheet for blue.css)\n";
12099     SetVersion($DBversion);
12100 }
12101
12102 $DBversion = "3.23.00.041";
12103 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12104
12105     my $dbh = C4::Context->dbh;
12106     my ($print_error) = $dbh->{PrintError};
12107     $dbh->{RaiseError} = 0;
12108     $dbh->{PrintError} = 0;
12109     $dbh->do("ALTER TABLE overduerules_transport_types ADD COLUMN letternumber INT(1) NOT NULL DEFAULT 1 AFTER id");
12110     $dbh->{PrintError} = $print_error;
12111
12112     print "Upgrade to $DBversion done (Bug 16007: Make sure overduerules_transport_types.letternumber exists)\n";
12113     SetVersion($DBversion);
12114 }
12115
12116 $DBversion = "3.23.00.042";
12117 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12118
12119     $dbh->do(q{
12120             ALTER TABLE items CHANGE new new_status VARCHAR(32) NULL;
12121             });
12122     $dbh->do(q{
12123             ALTER TABLE deleteditems CHANGE new new_status VARCHAR(32) NULL;
12124             });
12125     $dbh->do(q{
12126             UPDATE systempreferences SET value=REPLACE(value, '"items.new"', '"items.new_status"') WHERE variable="automatic_item_modification_by_age_configuration";
12127             });
12128
12129     print "Upgrade to $DBversion done (Bug 16004 - Replace items.new with items.new_status)\n";
12130     SetVersion($DBversion);
12131 }
12132
12133 $DBversion = "3.23.00.043";
12134 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12135     $dbh->do(q{
12136             UPDATE systempreferences SET value="" WHERE value IS NULL;
12137             });
12138
12139     print "Upgrade to $DBversion done (Bug 16070 - Empty (undef) system preferences may cause some issues in combination with memcache)\n";
12140     SetVersion($DBversion);
12141 }
12142
12143 $DBversion = "3.23.00.044";
12144 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12145     $dbh->do(q{
12146             INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
12147             ('GoogleOpenIDConnect', '0', NULL, 'if ON, allows the use of Google OpenID Connect for login', 'YesNo'),
12148             ('GoogleOAuth2ClientID', '', NULL, 'Client ID for the web app registered with Google', 'Free'),
12149             ('GoogleOAuth2ClientSecret', '', NULL, 'Client Secret for the web app registered with Google', 'Free'),
12150             ('GoogleOpenIDConnectDomain', '', NULL, 'Restrict OpenID Connect to this domain (or subdomains of this domain). Leave blank for all Google domains', 'Free');
12151             });
12152
12153     print "Upgrade to $DBversion done (Bug 10988 - Allow login via Google OAuth2 (OpenID Connect))\n";
12154     SetVersion($DBversion);
12155 }
12156
12157 $DBversion = "3.23.00.045";
12158 if ( CheckVersion($DBversion) ) {
12159 ## Holds details for vendors supplying goods by EDI
12160    $dbh->do(q{
12161            CREATE TABLE IF NOT EXISTS vendor_edi_accounts (
12162                    id INT(11) NOT NULL auto_increment,
12163                    description TEXT NOT NULL,
12164                    host VARCHAR(40),
12165                    username VARCHAR(40),
12166                    password VARCHAR(40),
12167                    last_activity DATE,
12168                    vendor_id INT(11) REFERENCES aqbooksellers( id ),
12169                    download_directory TEXT,
12170                    upload_directory TEXT,
12171                    san VARCHAR(20),
12172                    id_code_qualifier VARCHAR(3) default '14',
12173                    transport VARCHAR(6) default 'FTP',
12174                    quotes_enabled TINYINT(1) not null default 0,
12175                    invoices_enabled TINYINT(1) not null default 0,
12176                    orders_enabled TINYINT(1) not null default 0,
12177                    responses_enabled TINYINT(1) not null default 0,
12178                    auto_orders TINYINT(1) not null default 0,
12179                    shipment_budget INTEGER(11) REFERENCES aqbudgets( budget_id ),
12180                    PRIMARY KEY  (id),
12181                    KEY vendorid (vendor_id),
12182                    KEY shipmentbudget (shipment_budget),
12183                    CONSTRAINT vfk_vendor_id FOREIGN KEY ( vendor_id ) REFERENCES aqbooksellers ( id ),
12184                    CONSTRAINT vfk_shipment_budget FOREIGN KEY ( shipment_budget ) REFERENCES aqbudgets ( budget_id )
12185                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
12186    });
12187
12188 ## Hold the actual edifact messages with links to associated baskets
12189    $dbh->do(q{
12190            CREATE TABLE IF NOT EXISTS edifact_messages (
12191                    id INT(11) NOT NULL auto_increment,
12192                    message_type VARCHAR(10) NOT NULL,
12193                    transfer_date DATE,
12194                    vendor_id INT(11) REFERENCES aqbooksellers( id ),
12195                    edi_acct  INTEGER REFERENCES vendor_edi_accounts( id ),
12196                    status TEXT,
12197                    basketno INT(11) REFERENCES aqbasket( basketno),
12198                    raw_msg MEDIUMTEXT,
12199                    filename TEXT,
12200                    deleted BOOLEAN NOT NULL DEFAULT 0,
12201                    PRIMARY KEY  (id),
12202                    KEY vendorid ( vendor_id),
12203                    KEY ediacct (edi_acct),
12204                    KEY basketno ( basketno),
12205                    CONSTRAINT emfk_vendor FOREIGN KEY ( vendor_id ) REFERENCES aqbooksellers ( id ),
12206                    CONSTRAINT emfk_edi_acct FOREIGN KEY ( edi_acct ) REFERENCES vendor_edi_accounts ( id ),
12207                    CONSTRAINT emfk_basketno FOREIGN KEY ( basketno ) REFERENCES aqbasket ( basketno )
12208                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
12209             });
12210
12211 ## invoices link back to the edifact message it was generated from
12212    $dbh->do(q{
12213            ALTER TABLE aqinvoices ADD COLUMN message_id INT(11) REFERENCES edifact_messages( id );
12214            });
12215
12216 ## clean up link on deletes
12217    $dbh->do(q{
12218            ALTER TABLE aqinvoices ADD CONSTRAINT edifact_msg_fk FOREIGN KEY ( message_id ) REFERENCES edifact_messages ( id ) ON DELETE SET NULL;
12219            });
12220
12221 ## Hold the supplier ids from quotes for ordering
12222 ## although this is an EAN-13 article number the standard says 35 characters ???
12223    $dbh->do(q{
12224            ALTER TABLE aqorders ADD COLUMN line_item_id VARCHAR(35);
12225            });
12226
12227 ## The suppliers unique reference usually a quotation line number ('QLI')
12228 ## Otherwise Suppliers unique orderline reference ('SLI')
12229    $dbh->do(q{
12230            ALTER TABLE aqorders ADD COLUMN suppliers_reference_number VARCHAR(35);
12231            });
12232    $dbh->do(q{
12233            ALTER TABLE aqorders ADD COLUMN suppliers_reference_qualifier VARCHAR(3);
12234            });
12235    $dbh->do(q{
12236            ALTER TABLE aqorders ADD COLUMN suppliers_report text;
12237            });
12238
12239 ## hold the EAN/SAN used in ordering
12240    $dbh->do(q{
12241            CREATE TABLE IF NOT EXISTS edifact_ean (
12242                    ee_id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
12243                    description VARCHAR(128) NULL DEFAULT NULL,
12244                    branchcode VARCHAR(10) NOT NULL REFERENCES branches (branchcode),
12245                    ean VARCHAR(15) NOT NULL,
12246                    id_code_qualifier VARCHAR(3) NOT NULL DEFAULT '14',
12247                    CONSTRAINT efk_branchcode FOREIGN KEY ( branchcode ) REFERENCES branches ( branchcode )
12248                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
12249            });
12250
12251 ## Add a permission for managing EDI
12252    $dbh->do(q{
12253            INSERT INTO permissions (module_bit, code, description) values (11, 'edi_manage', 'Manage EDIFACT transmissions');
12254            });
12255
12256    print "Upgrade to $DBversion done (Bug 7736 - Edifact QUOTE and ORDER functionality))\n";
12257    SetVersion($DBversion);
12258 }
12259
12260 $DBversion = "3.23.00.046";
12261 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12262
12263     $dbh->do(q{
12264     ALTER TABLE vendor_edi_accounts ADD COLUMN plugin VARCHAR(256) NOT NULL DEFAULT "";
12265     });
12266
12267     print "Upgrade to $DBversion done (Bug 15630 - Make Edifact module pluggable))\n";
12268     SetVersion($DBversion);
12269 }
12270
12271 $DBversion = "3.23.00.047";
12272 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12273
12274     $dbh->do(q{
12275          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');
12276          });
12277     $dbh->do(q{
12278          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');
12279          });
12280
12281     print "Upgrade to $DBversion done (Bug 15008 - Add custom HTML areas to circulation and reports home pages)\n";
12282     SetVersion($DBversion);
12283 }
12284
12285 $DBversion = "3.23.00.048";
12286 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12287     $dbh->do(q{
12288     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';
12289     });
12290
12291     print "Upgrade to $DBversion done (Bug 5979 - Add separate OPACISBD system preference)\n";
12292     SetVersion($DBversion);
12293 }
12294
12295
12296
12297 $DBversion = "3.23.00.049";
12298 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12299 my $dbh = C4::Context->dbh;
12300 my ( $column_has_been_used ) = $dbh->selectrow_array(q|
12301             SELECT COUNT(*)
12302                 FROM borrower_attributes
12303                     WHERE password IS NOT NULL
12304                     |);
12305
12306 if ( $column_has_been_used ) {
12307         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.|;
12308 } else {
12309         $dbh->do(q|
12310         ALTER TABLE borrower_attribute_types DROP column password_allowed
12311         |);
12312         $dbh->do(q|
12313         ALTER TABLE borrower_attributes DROP column password;
12314         |);
12315     }
12316     print "Upgrade to $DBversion done (Bug 12267 - Allow password option in Patron Attribute non functional)\n";
12317         SetVersion($DBversion);
12318 }
12319
12320
12321 $DBversion = "3.23.00.050";
12322 if ( CheckVersion($DBversion) ) {
12323
12324     $dbh->do(q|INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
12325                     VALUES('SearchEngine','Zebra','Choose Search Engine','','Choice')|);
12326
12327
12328     $dbh->do(q|DROP TABLE IF EXISTS search_marc_to_field|);
12329     $dbh->do(q|DROP TABLE IF EXISTS search_marc_map|);
12330     $dbh->do(q|DROP TABLE IF EXISTS search_field|);
12331
12332 # This specifies the fields that will be stored in the search engine.
12333  $dbh->do(q|
12334          CREATE TABLE `search_field` (
12335              `id` int(11) NOT NULL AUTO_INCREMENT, 
12336              `name` varchar(255) NOT NULL COMMENT 'the name of the field as it will be stored in the search engine',
12337              `label` varchar(255) NOT NULL COMMENT 'the human readable name of the field, for display', 
12338              `type` ENUM('', 'string', 'date', 'number', 'boolean', 'sum') NOT NULL COMMENT 'what type of data this holds, relevant when storing it in the search engine',
12339              PRIMARY KEY (`id`),
12340              UNIQUE KEY (`name`)
12341              ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
12342          |);
12343 # This contains a MARC field specifier for a given index, marc type, and marc
12344 # field.
12345 $dbh->do(q|
12346         CREATE TABLE `search_marc_map` (
12347             id int(11) NOT NULL AUTO_INCREMENT,
12348             index_name ENUM('biblios','authorities') NOT NULL COMMENT 'what storage index this map is for',
12349             marc_type ENUM('marc21', 'unimarc', 'normarc') NOT NULL COMMENT 'what MARC type this map is for',
12350             marc_field VARCHAR(255) NOT NULL COMMENT 'the MARC specifier for this field',
12351             PRIMARY KEY(`id`),
12352             unique key( index_name, marc_field, marc_type),
12353             INDEX (`index_name`)
12354             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
12355         |);
12356
12357 # This joins the two search tables together. We can have any combination:
12358 # one marc field could have many search fields (maybe you want one value
12359 # to go to 'author' and 'corporate-author) and many marc fields could go
12360 # to one search field (e.g. all the various author fields going into
12361 # 'author'.)
12362 #
12363 # a note about the sort field:
12364 # * if all the entries for a mapping are 'null', nothing special is done with that mapping.
12365 # * if any of the entries are not null, then a __sort field is created in ES for this mapping. In this case:
12366 #   * any mapping with sort == false WILL NOT get copied into a __sort field
12367 #   * any mapping with sort == true or is null WILL get copied into a __sort field
12368 #   * any sorts on the field name will be applied to $fieldname.'__sort' instead.
12369 # this means that we can have search for author that includes 1xx, 245$c, and 7xx, but the sort only applies to 1xx.
12370
12371 $dbh->do(q|
12372         CREATE TABLE `search_marc_to_field` (
12373             search_marc_map_id int(11) NOT NULL,
12374             search_field_id int(11) NOT NULL,
12375             facet boolean DEFAULT FALSE COMMENT 'true if a facet field should be generated for this',
12376             suggestible boolean DEFAULT FALSE COMMENT 'true if this field can be used to generate suggestions for browse',
12377             sort boolean DEFAULT NULL COMMENT 'true/false creates special sort handling, null doesn''t',
12378             PRIMARY KEY(search_marc_map_id, search_field_id),
12379             FOREIGN KEY(search_marc_map_id) REFERENCES search_marc_map(id) ON DELETE CASCADE ON UPDATE CASCADE,
12380             FOREIGN KEY(search_field_id) REFERENCES search_field(id) ON DELETE CASCADE ON UPDATE CASCADE
12381             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
12382         |);
12383
12384     print "WARNING: If you plan to use Elasticsearch you should go to 'Home › Administration › Search engine configuration' and reset the mappings\n";
12385     print "Upgrade to $DBversion done (Bug 12478 - Elasticsearch support for Koha)\n";
12386     SetVersion($DBversion);
12387 }
12388
12389
12390 $DBversion = "3.23.00.051";
12391 if ( CheckVersion($DBversion) ) {
12392 $dbh->do(q{
12393         ALTER TABLE edifact_messages
12394         DROP FOREIGN KEY emfk_vendor,
12395         DROP FOREIGN KEY emfk_edi_acct,
12396         DROP FOREIGN KEY emfk_basketno;
12397         });
12398
12399 $dbh->do(q{
12400         ALTER TABLE edifact_messages
12401         ADD CONSTRAINT emfk_vendor FOREIGN KEY ( vendor_id ) REFERENCES aqbooksellers ( id ) ON DELETE CASCADE ON UPDATE CASCADE,
12402         ADD CONSTRAINT emfk_edi_acct FOREIGN KEY ( edi_acct ) REFERENCES vendor_edi_accounts ( id ) ON DELETE CASCADE ON UPDATE CASCADE,
12403         ADD CONSTRAINT emfk_basketno FOREIGN KEY ( basketno ) REFERENCES aqbasket ( basketno ) ON DELETE CASCADE ON UPDATE CASCADE;
12404         });
12405
12406     print "Upgrade to $DBversion done (Bug 16354 - Fix FK constraints for edifact_messages table)\n";
12407     SetVersion($DBversion);
12408 }
12409
12410
12411 $DBversion = "3.23.00.052";
12412 if ( CheckVersion($DBversion) ) {
12413 ## Insert permission
12414
12415     $dbh->do(q{
12416         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
12417         (13, 'upload_general_files', 'Upload any file'),
12418         (13, 'upload_manage', 'Manage uploaded files');
12419         });
12420 ## Update user_permissions for current users (check count in uploaded_files)
12421 ## Note 9 == edit_catalogue and 13 == tools
12422 ## We do not insert if someone is superlibrarian, does not have edit_catalogue,
12423 ## or already has all tools
12424
12425         $dbh->do(q{
12426                 INSERT IGNORE INTO user_permissions (borrowernumber, module_bit, code)
12427                 SELECT borrowernumber, 13, 'upload_general_files'
12428                 FROM borrowers bo
12429                 WHERE flags<>1 AND flags & POW(2,13) = 0 AND
12430                 ( flags & POW(2,9) > 0 OR 
12431                   (SELECT COUNT(*) FROM user_permissions
12432                    WHERE borrowernumber=bo.borrowernumber AND module_bit=9 ) > 0 )
12433                 AND ( SELECT COUNT(*) FROM uploaded_files ) > 0
12434                 });
12435
12436     print "Upgrade to $DBversion done (Bug 14686 - New menu option and permission for file uploading)\n";
12437     SetVersion($DBversion);
12438 }
12439
12440 $DBversion = "3.23.00.053";
12441 if ( CheckVersion($DBversion) ) {
12442     my $letters = $dbh->selectall_arrayref(
12443         q|
12444         SELECT code, name
12445         FROM letter
12446         WHERE message_transport_type="email"
12447         |, { Slice => {} }
12448     );
12449     for my $letter (@$letters) {
12450         $dbh->do(
12451             q|
12452                 UPDATE letter
12453                 SET name = ?
12454                 WHERE code = ?
12455                 AND message_transport_type <> "email"
12456                 |, undef, $letter->{name}, $letter->{code}
12457         );
12458     }
12459
12460     print "Upgrade to $DBversion done (Bug 16217 - Notice' names may have diverged)\n";
12461     SetVersion($DBversion);
12462 }
12463
12464 $DBversion = "3.23.00.054";
12465 if ( CheckVersion($DBversion) ) {
12466     $dbh->do(q{
12467         ALTER TABLE branch_item_rules ADD COLUMN hold_fulfillment_policy ENUM('any', 'homebranch', 'holdingbranch') NOT NULL DEFAULT 'any' AFTER holdallowed;
12468     });
12469     $dbh->do(q{
12470         ALTER TABLE default_branch_circ_rules ADD COLUMN hold_fulfillment_policy ENUM('any', 'homebranch', 'holdingbranch') NOT NULL DEFAULT 'any' AFTER holdallowed;
12471     });
12472     $dbh->do(q{
12473         ALTER TABLE default_branch_item_rules ADD COLUMN hold_fulfillment_policy ENUM('any', 'homebranch', 'holdingbranch') NOT NULL DEFAULT 'any' AFTER holdallowed;
12474     });
12475     $dbh->do(q{
12476         ALTER TABLE default_circ_rules ADD COLUMN hold_fulfillment_policy ENUM('any', 'homebranch', 'holdingbranch') NOT NULL DEFAULT 'any' AFTER holdallowed;
12477     });
12478
12479     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";
12480     SetVersion($DBversion);
12481 }
12482
12483 $DBversion = "3.23.00.055";
12484 if ( CheckVersion($DBversion) ) {
12485     $dbh->do(q{
12486         ALTER TABLE reserves ADD COLUMN itemtype VARCHAR(10) NULL DEFAULT NULL AFTER suspend_until;
12487     });
12488     $dbh->do(q{
12489         ALTER TABLE reserves ADD KEY `itemtype` (`itemtype`);
12490     });
12491     $dbh->do(q{
12492         ALTER TABLE reserves ADD CONSTRAINT `reserves_ibfk_5` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE;
12493     });
12494     $dbh->do(q{
12495         ALTER TABLE old_reserves ADD COLUMN itemtype VARCHAR(10) NULL DEFAULT NULL AFTER suspend_until;
12496     });
12497     $dbh->do(q{
12498         ALTER TABLE old_reserves ADD KEY `itemtype` (`itemtype`);
12499     });
12500     $dbh->do(q{
12501         ALTER TABLE old_reserves ADD CONSTRAINT `old_reserves_ibfk_4` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE;
12502     });
12503
12504     $dbh->do(q{
12505         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
12506         ('AllowHoldItemTypeSelection','0','','If enabled, patrons and staff will be able to select the itemtype when placing a hold','YesNo');
12507     });
12508
12509     print "Upgrade to $DBversion done (Bug 15533 - Allow patrons and librarians to select itemtype when placing hold)\n";
12510     SetVersion($DBversion);
12511 }
12512
12513 $DBversion = "3.23.00.056";
12514 if ( CheckVersion($DBversion) ) {
12515     $dbh->do(q{
12516         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
12517         ('NoIssuesChargeGuarantees','','','Define maximum amount withstanding before check outs are blocked','Integer');
12518     });
12519
12520     print "Upgrade to $DBversion done (Bug 14577 - Allow restriction of checkouts based on fines of guarantor/guarantee)\n";
12521     SetVersion($DBversion);
12522 }
12523
12524 $DBversion = "3.23.00.057";
12525 if ( CheckVersion($DBversion) ) {
12526     $dbh->do(q{
12527         ALTER TABLE aqbasket ADD COLUMN is_standing TINYINT(1) NOT NULL DEFAULT 0 AFTER branch;
12528     });
12529
12530     print "Upgrade to $DBversion done (Bug 15531 - Add support for standing orders)\n";
12531     SetVersion($DBversion);
12532 }
12533
12534 $DBversion = "3.23.00.058";
12535 if ( CheckVersion($DBversion) ) {
12536
12537     my ($count_imageurl) = $dbh->selectrow_array(q|
12538         SELECT COUNT(*)
12539         FROM authorised_values
12540         WHERE imageurl IS NOT NULL
12541             AND imageurl <> ""
12542     |);
12543
12544     unless ($count_imageurl) {
12545         if (   C4::Context->preference('AuthorisedValueImages')
12546             or C4::Context->preference('StaffAuthorisedValueImages') )
12547         {
12548             $dbh->do(q|
12549                 UPDATE systempreferences
12550                 SET value = 0
12551                 WHERE variable = "AuthorisedValueImages"
12552                    or variable = "StaffAuthorisedValueImages"
12553             |);
12554             warn "The system preferences AuthorisedValueImages and StaffAuthorisedValueImages have been turned off\n";
12555             warn "authorised_values.imageurl is not populated, that means you are not using this feature\n";
12556         }
12557     }
12558     else {
12559         warn "At least one authorised value has an icon defined (imageurl)\n";
12560         warn "The system preference AuthorisedValueImages or StaffAuthorisedValueImages could be turned off if you are not aware of this feature\n";
12561     }
12562
12563     print "Upgrade to $DBversion done (Bug 16041 - StaffAuthorisedValueImages & AuthorisedValueImages preferences - impact on search performance)\n";
12564     SetVersion($DBversion);
12565 }
12566
12567 $DBversion = "3.23.00.059";
12568 if ( CheckVersion($DBversion) ) {
12569     $dbh->do(q{
12570         DELETE FROM systempreferences WHERE variable="AuthorisedValueImages" OR variable="StaffAuthorisedValueImages";
12571     });
12572
12573     print "Upgrade to $DBversion done (Bug 16167 - Remove prefs to drive authorised value images)\n";
12574     SetVersion($DBversion);
12575 }
12576
12577 $DBversion = "3.23.00.060";
12578 if ( CheckVersion($DBversion) ) {
12579     $dbh->do(q{
12580         INSERT IGNORE INTO systempreferences ( value, variable, options, explanation,type )
12581         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';
12582     });
12583
12584     print "Upgrade to $DBversion done (Bug 12528 - Enable staff to deny message setting access to patrons on the OPAC)\n";
12585     SetVersion($DBversion);
12586 }
12587
12588 $DBversion = "3.23.00.061";
12589 if ( CheckVersion($DBversion) ) {
12590     my ( $cnt ) = $dbh->selectrow_array( q|
12591         SELECT COUNT(*) FROM items it
12592         LEFT JOIN biblio bi ON bi.biblionumber=it.biblionumber
12593         LEFT JOIN biblioitems bii USING (biblioitemnumber)
12594         WHERE bi.biblionumber IS NULL
12595     |);
12596     if( $cnt ) {
12597         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";
12598     } else {
12599         # now add FK
12600         $dbh->do( q|
12601             ALTER TABLE items
12602             ADD FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
12603         |);
12604         print "Upgrade to $DBversion done (Bug 16170 - Add FK for biblionumber in items)\n";
12605     }
12606     SetVersion($DBversion);
12607 }
12608
12609 $DBversion = "3.23.00.062";
12610 if ( CheckVersion($DBversion) ) {
12611     $dbh->do( q|
12612             ALTER TABLE aqorders DROP COLUMN budgetgroup_id;
12613             |);
12614     print "Upgrade to $DBversion done (Bug 16414 - aqorders.budgetgroup_id has never been used and can be removed)\n";
12615 SetVersion($DBversion);
12616 }
12617
12618 $DBversion = "3.23.00.063";
12619 if ( CheckVersion($DBversion) ) {
12620     $dbh->do(q{
12621         UPDATE letter SET branchcode='' WHERE branchcode IS NULL;
12622     });
12623     $dbh->do(q{
12624         ALTER TABLE letter MODIFY COLUMN branchcode varchar(10) NOT NULL DEFAULT ''
12625     });
12626     $dbh->do(q{
12627         ALTER TABLE permissions MODIFY COLUMN code varchar(64) NOT NULL DEFAULT '';
12628     });
12629     print "Upgrade to $DBversion done (Bug 16402: Fix DB structure to work on MySQL 5.7)\n";
12630     SetVersion($DBversion);
12631 }
12632
12633 $DBversion = "3.23.00.064";
12634 if ( CheckVersion($DBversion) ) {
12635     $dbh->do(q{
12636         ALTER TABLE creator_layouts MODIFY layout_name char(25) NOT NULL DEFAULT 'DEFAULT';
12637     });
12638     print "Upgrade to $DBversion done (Bug 15086 - Creators layout and template sql has warnings)\n";
12639     SetVersion($DBversion);
12640 }
12641
12642 $DBversion = "16.05.00.000";
12643 if ( CheckVersion($DBversion) ) {
12644     print "Upgrade to $DBversion done (Koha 16.05)\n";
12645     SetVersion($DBversion);
12646 }
12647
12648 $DBversion = "16.06.00.000";
12649 if ( CheckVersion($DBversion) ) {
12650     print "Upgrade to $DBversion done (Koha 16.06 - starting a new dev line at KohaCon16 in Thessaloniki, Greece! Koha is great!)\n";
12651     SetVersion($DBversion);
12652 }
12653
12654 $DBversion = "16.06.00.001";
12655 if ( CheckVersion($DBversion) ) {
12656     $dbh->do(q{
12657         UPDATE accountlines SET accounttype='HE', description=itemnumber WHERE (description REGEXP '^Hold waiting too long [0-9]+') AND accounttype='F';
12658     });
12659
12660     print "Upgrade to $DBversion done (Bug 16200 - 'Hold waiting too long' fee has a translation problem)\n";
12661     SetVersion($DBversion);
12662 }
12663
12664 $DBversion = "16.06.00.002";
12665 if ( CheckVersion($DBversion) ) {
12666     unless ( column_exists('borrowers', 'updated_on') ) {
12667         $dbh->do(q{
12668             ALTER TABLE borrowers
12669                 ADD COLUMN updated_on timestamp NULL DEFAULT CURRENT_TIMESTAMP
12670                 ON UPDATE CURRENT_TIMESTAMP
12671                 AFTER privacy_guarantor_checkouts;
12672         });
12673         $dbh->do(q{
12674             ALTER TABLE deletedborrowers
12675                 ADD COLUMN updated_on timestamp NULL DEFAULT CURRENT_TIMESTAMP
12676                 ON UPDATE CURRENT_TIMESTAMP
12677                 AFTER privacy_guarantor_checkouts;
12678         });
12679     }
12680
12681     print "Upgrade to $DBversion done (Bug 10459 - borrowers should have a timestamp)\n";
12682     SetVersion($DBversion);
12683 }
12684
12685 $DBversion = "16.06.00.003";
12686 if ( CheckVersion($DBversion) ) {
12687     $dbh->do(q{
12688         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
12689         SELECT 'MaxItemsToProcessForBatchMod', value, NULL, 'Process up to a given number of items in a single item modification batch.', 'Integer' FROM systempreferences WHERE variable='MaxItemsForBatch';
12690     });
12691     $dbh->do(q{
12692         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
12693         SELECT 'MaxItemsToDisplayForBatchDel', value, NULL, 'Display up to a given number of items in a single item deletionbatch.', 'Integer' FROM systempreferences WHERE variable='MaxItemsForBatch';
12694     });
12695     $dbh->do(q{
12696         DELETE FROM systempreferences WHERE variable="MaxItemsForBatch";
12697     });
12698
12699     print "Upgrade to $DBversion done (Bug 11490 - MaxItemsForBatch should be split into two new prefs)\n";
12700     SetVersion($DBversion);
12701 }
12702
12703 $DBversion = '16.06.00.004';
12704 if ( CheckVersion($DBversion) ) {
12705     $dbh->do(q{
12706         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
12707          SELECT 'OPACXSLTListsDisplay', COALESCE(value,''), '', 'Enable XSLT stylesheet control over lists pages display on OPAC', 'Free'
12708          FROM systempreferences WHERE variable='OPACXSLTResultsDisplay';
12709     });
12710
12711     $dbh->do(q{
12712         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
12713          SELECT 'XSLTListsDisplay', COALESCE(value,''), '', 'Enable XSLT stylesheet control over lists pages display on intranet', 'Free'
12714          FROM systempreferences WHERE variable='XSLTResultsDisplay';
12715     });
12716
12717     print "Upgrade to $DBversion done (Bug 15485: Allow choosing different XSLTs for lists)\n";
12718     SetVersion($DBversion);
12719 }
12720
12721 $DBversion = '16.06.00.005';
12722 if ( CheckVersion($DBversion) ) {
12723     $dbh->do(q{
12724         UPDATE `systempreferences` set options = 'US|FR|CH' where variable = 'CurrencyFormat';
12725     });
12726
12727     print "Upgrade to $DBversion done (Bug 16768 - Add official number format for Switzerland: 1'234'567.89)\n";
12728     SetVersion($DBversion);
12729 }
12730
12731 $DBversion = "16.06.00.006";
12732 if ( CheckVersion($DBversion) ) {
12733     $dbh->do(q{
12734         CREATE TABLE `refund_lost_item_fee_rules` (
12735           `branchcode` varchar(10) NOT NULL default '',
12736           `refund` tinyint(1) NOT NULL default 0,
12737           PRIMARY KEY  (`branchcode`)
12738         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
12739     });
12740     $dbh->do(q{
12741         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
12742         VALUES( 'RefundLostOnReturnControl',
12743                 'CheckinLibrary',
12744                 'If a lost item is returned, choose which branch to pick rules for refunding.',
12745                 'CheckinLibrary|PatronLibrary|ItemHomeBranch|ItemHoldingbranch',
12746                 'Choice')
12747     });
12748     # Pick the old syspref as the default rule
12749     $dbh->do(q{
12750         INSERT INTO refund_lost_item_fee_rules (branchcode,refund)
12751             SELECT '*', COALESCE(value,'1') FROM systempreferences WHERE variable='RefundLostItemFeeOnReturn'
12752     });
12753     # Delete the old syspref
12754     $dbh->do(q{
12755         DELETE IGNORE FROM systempreferences
12756         WHERE variable='RefundLostItemFeeOnReturn'
12757     });
12758
12759     print "Upgrade to $DBversion done (Bug 14048: Change RefundLostItemFeeOnReturn to be branch specific)\n";
12760     SetVersion($DBversion);
12761 }
12762
12763 $DBversion = '16.06.00.007';
12764 if ( CheckVersion($DBversion) ) {
12765     $dbh->do(q{
12766         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) 
12767         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');
12768     });
12769
12770     print "Upgrade to $DBversion done (Bug 3534 - Patron quick add form)\n";
12771     SetVersion($DBversion);
12772 }
12773
12774 $DBversion = '16.06.00.008';
12775 if ( CheckVersion($DBversion) ) {
12776     $dbh->do(q{
12777         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
12778         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');
12779     });
12780     $dbh->do(q{
12781         ALTER TABLE categories
12782         ADD COLUMN `checkprevcheckout` varchar(7) NOT NULL default 'inherit'
12783         AFTER `default_privacy`;
12784     });
12785     $dbh->do(q{
12786         ALTER TABLE borrowers
12787         ADD COLUMN `checkprevcheckout` varchar(7) NOT NULL default 'inherit'
12788         AFTER `privacy_guarantor_checkouts`;
12789     });
12790     $dbh->do(q{
12791         ALTER TABLE deletedborrowers
12792         ADD COLUMN `checkprevcheckout` varchar(7) NOT NULL default 'inherit'
12793         AFTER `privacy_guarantor_checkouts`;
12794     });
12795
12796     print "Upgrade to $DBversion done (Bug 6906 - show 'Borrower has previously issued \$ITEM' alert on checkout)\n";
12797     SetVersion($DBversion);
12798 }
12799
12800 $DBversion = '16.06.00.009';
12801 if ( CheckVersion($DBversion) ) {
12802     $dbh->do(q{
12803         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) 
12804         VALUES ('IntranetCatalogSearchPulldown','0',NULL,'Show a search field pulldown for \"Search the catalog\" boxes. ','YesNo');
12805     });
12806
12807     print "Upgrade to $DBversion done (Bug 14902 - Add qualifier menu to staff side 'Search the Catalog')\n";
12808     SetVersion($DBversion);
12809 }
12810
12811 $DBversion = '16.06.00.010';
12812 if ( CheckVersion($DBversion) ) {
12813     $dbh->do(q{
12814         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
12815         VALUES ('MaxOpenSuggestions','',NULL,'Limit the number of open suggestions a patron can have at once, unlimited if blank','Integer')
12816     });
12817
12818     print "Upgrade to $DBversion done (Bug 15128 - Add ability to limit the number of open purchase suggestions a patron can make)\n";
12819     SetVersion($DBversion);
12820 }
12821
12822 $DBversion = '16.06.00.011';
12823 if ( CheckVersion($DBversion) ) {
12824     $dbh->do(q{
12825         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
12826         ('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'),
12827         ('NovelistSelectStaffView','tab','tab|above|below','Where to display Novelist Select content','Choice');
12828     });
12829
12830     print "Upgrade to $DBversion done (Bug 11606 - Novelist Select in Staff Client)\n";
12831     SetVersion($DBversion);
12832 }
12833
12834 $DBversion = '16.06.00.012';
12835 if ( CheckVersion($DBversion) ) {
12836     $dbh->do(q{
12837         ALTER TABLE virtualshelves MODIFY COLUMN created_on DATETIME not NULL;
12838     });
12839
12840     print "Upgrade to $DBversion done (Bug 16573 - Web installer fails to load structure and sample data on MySQL 5.7)\n";
12841     SetVersion($DBversion);
12842 }
12843
12844 $DBversion = '16.06.00.013';
12845 if ( CheckVersion($DBversion) ) {
12846     $dbh->do(q{
12847         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES
12848         ('OPACResultsLibrary', 'homebranch', 'homebranch|holdingbranch', 'Defines whether the OPAC displays the holding or home branch in search results when using XSLT', 'Choice');
12849     });
12850
12851     print "Upgrade to $DBversion done (Bug 7441 - Search results showing wrong branch)\n";
12852     SetVersion($DBversion);
12853 }
12854
12855 $DBversion = "16.06.00.014";
12856 if ( CheckVersion($DBversion) ) {
12857     $dbh->do(q{
12858         ALTER TABLE `action_logs` ADD COLUMN `interface` VARCHAR(30) DEFAULT NULL AFTER `info`;
12859     });
12860
12861     $dbh->do(q{
12862         ALTER TABLE `action_logs` ADD KEY `interface` (`interface`);
12863     });
12864
12865     print "Upgrade to $DBversion done (Bug 16829: action_logs should have an 'interface' column)\n";
12866     SetVersion($DBversion);
12867 }
12868
12869 $DBversion = "16.06.00.015";
12870 if ( CheckVersion($DBversion) ) {
12871     $dbh->do(q{
12872         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type ) VALUES
12873         ('HoldsLog','0',NULL,'If ON, log create/cancel/suspend/resume actions on holds.','YesNo');
12874     });
12875
12876     print "Upgrade to $DBversion done (Bug 14642: Add logging of hold modifications)\n";
12877     SetVersion($DBversion);
12878 }
12879
12880 $DBversion = "16.06.00.016";
12881 if ( CheckVersion($DBversion) ) {
12882     $dbh->do(q{
12883         update marc_subfield_structure set defaultvalue=REPLACE(defaultvalue, 'YYYY', '<<YYYY>>') where defaultvalue like "%YYYY%" and defaultvalue not like "%<<YYYY>>%";
12884     });
12885     $dbh->do(q{
12886         update marc_subfield_structure set defaultvalue=REPLACE(defaultvalue, 'MM', '<<MM>>') where defaultvalue like "%MM%" and defaultvalue not like "%<<MM>>%";
12887     });
12888     $dbh->do(q{
12889         update marc_subfield_structure set defaultvalue=REPLACE(defaultvalue, 'DD', '<<DD>>') where defaultvalue like "%DD%" and defaultvalue not like "%<<DD>>%";
12890     });
12891     $dbh->do(q{
12892         update marc_subfield_structure set defaultvalue=REPLACE(defaultvalue, 'user', '<<USER>>') where defaultvalue like "%user%" and defaultvalue not like "%<<USER>>%";
12893     });
12894
12895     print "Upgrade to $DBversion done (Bug 7045 - Default-value substitution inconsistent)\n";
12896     SetVersion($DBversion);
12897 }
12898
12899 $DBversion = "16.06.00.017";
12900 if ( CheckVersion($DBversion) ) {
12901     $dbh->do(q{
12902         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');
12903     });
12904
12905     print "Upgrade to $DBversion done (Bug 10848 - Allow configuration of mandatory/required fields on the suggestion form in OPAC)\n";
12906     SetVersion($DBversion);
12907 }
12908
12909 $DBversion = "16.06.00.018";
12910 if ( CheckVersion($DBversion) ) {
12911     $dbh->do(q{
12912         ALTER TABLE issuingrules ADD COLUMN holds_per_record SMALLINT(6) NOT NULL DEFAULT 1 AFTER reservesallowed;
12913     });
12914
12915     print "Upgrade to $DBversion done (Bug 14695 - Add ability to place multiple item holds on a given record per patron)\n";
12916     SetVersion($DBversion);
12917 }
12918
12919 $DBversion = "16.06.00.019";
12920 if ( CheckVersion($DBversion) ) {
12921     $dbh->do(q{
12922         ALTER TABLE reviews CHANGE COLUMN approved approved tinyint(4) DEFAULT 0;
12923     });
12924     $dbh->do(q{
12925         UPDATE reviews SET approved=0 WHERE approved IS NULL;
12926     });
12927
12928     print "Upgrade to $DBversion done (Bug 15839 - Move the reviews related code to Koha::Reviews)\n";
12929     SetVersion($DBversion);
12930 }
12931
12932 $DBversion = "16.06.00.020";
12933 if ( CheckVersion($DBversion) ) {
12934     $dbh->do(q{
12935         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('SwitchOnSiteCheckouts', '0', 'Automatically switch an on-site checkout to a normal checkout', NULL, 'YesNo');
12936     });
12937
12938     print "Upgrade to $DBversion done (Bug 16272 - Transform checkout from on-site checkout to regular checkout)\n";
12939     SetVersion($DBversion);
12940 }
12941
12942 $DBversion = "16.06.00.021";
12943 if ( CheckVersion($DBversion) ) {
12944     $dbh->do(q{
12945         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');
12946     });
12947
12948     print "Upgrade to $DBversion done (Bug 16275 - Prevent patron self registration if the email already filled in borrowers.email)\n";
12949     SetVersion($DBversion);
12950 }
12951
12952 $DBversion = "16.06.00.022";
12953 if ( CheckVersion($DBversion) ) {
12954     $dbh->do(q{
12955         INSERT IGNORE INTO `permissions`
12956         (module_bit, code,             description) VALUES
12957         (16,         'delete_reports', 'Delete SQL reports');
12958     });
12959     $dbh->do(q{
12960         INSERT IGNORE INTO user_permissions
12961         (borrowernumber,      module_bit,code)
12962         SELECT borrowernumber,module_bit,'delete_reports'
12963             FROM user_permissions
12964             WHERE module_bit=16 AND code='create_reports';
12965     });
12966
12967     print "Upgrade to $DBversion done (Bug 16978 - Add delete reports user permission)\n";
12968     SetVersion($DBversion);
12969 }
12970
12971 $DBversion = "16.06.00.023";
12972 if ( CheckVersion($DBversion) ) {
12973     my $pref = C4::Context->preference('timeout');
12974     if( !$pref || $pref eq '12000000' ) {
12975         # update if pref is null or equals old default value
12976         $dbh->do(q|
12977             UPDATE systempreferences SET value = '1d', type = 'Free'
12978             WHERE variable = 'timeout'
12979         |);
12980         print "Upgrade to $DBversion done (Bug 17187)\nNote: Pref value for timeout has been adjusted.\n";
12981     } else {
12982         # only update pref type
12983         $dbh->do(q|
12984             UPDATE systempreferences SET type = 'Free'
12985             WHERE variable = 'timeout'
12986         |);
12987         print "Upgrade to $DBversion done (Bug 17187)\nNote: Pref value for timeout has not been adjusted.\n";
12988     }
12989     SetVersion($DBversion);
12990 }
12991
12992 $DBversion = "16.06.00.024";
12993 if ( CheckVersion($DBversion) ) {
12994     $dbh->do(q{
12995         UPDATE language_descriptions SET description = 'Română' WHERE subtag = 'ro' AND type = 'language' AND lang = 'ro';
12996     });
12997
12998     print "Upgrade to $DBversion done (Bug 16311 - Advanced search language limit typo for Romanian)\n";
12999     SetVersion($DBversion);
13000 }
13001
13002 $DBversion = "16.06.00.025";
13003 if ( CheckVersion($DBversion) ) {
13004     $dbh->do(q{
13005         ALTER TABLE `subscription` ADD `itemtype` VARCHAR( 10 ) NULL AFTER reneweddate, ADD `previousitemtype` VARCHAR( 10 ) NULL AFTER itemtype;
13006     });
13007     $dbh->do(q{
13008         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
13009         ('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');
13010     });
13011
13012     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";
13013     SetVersion($DBversion);
13014 }
13015
13016 $DBversion = "16.06.00.026";
13017 if ( CheckVersion($DBversion) ) {
13018     $dbh->do(q{
13019         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('PatronSelfRegistrationLibraryList', '', 'Only display libraries listed. If empty, all libraries are displayed.', NULL, 'Free');
13020     });
13021
13022     print "Upgrade to $DBversion done (Bug 16274 - Make the selfregistration branchcode selection configurable)\n";
13023     SetVersion($DBversion);
13024 }
13025
13026 $DBversion = "16.06.00.027";
13027 if ( CheckVersion($DBversion) ) {
13028     unless ( column_exists('borrowers', 'lastseen') ) {
13029         $dbh->do(q{
13030             ALTER TABLE borrowers ADD COLUMN lastseen datetime default NULL AFTER updated_on;
13031         });
13032         $dbh->do(q{
13033             ALTER TABLE deletedborrowers ADD COLUMN lastseen datetime default NULL AFTER updated_on;
13034         });
13035     }
13036     $dbh->do(q{
13037         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');
13038     });
13039
13040     print "Upgrade to $DBversion done (Bug 16276: Add a new pref TrackLastPatronActivity and new column borrowers.lastseen)\n";
13041     SetVersion($DBversion);
13042 }
13043
13044 $DBversion = '16.06.00.028';
13045 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
13046     {
13047         print "Attempting upgrade to $DBversion (Bug 17135) ...\n";
13048         my $maintenance_script = C4::Context->config("intranetdir") . "/installer/data/mysql/fix_unclosed_nonaccruing_fines_bug17135.pl";
13049         system("perl $maintenance_script --confirm");
13050
13051         print "Upgrade to $DBversion done (Bug 17135 - Fine for the previous overdue may get overwritten by the next one)\n";
13052
13053         unless ($original_version < TransformToNum("3.23.00.032")) { ## Bug 15675
13054             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";
13055             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";
13056         }
13057         SetVersion ($DBversion);
13058     }
13059 }
13060
13061 $DBversion = "16.06.00.029";
13062 if ( CheckVersion($DBversion) ) {
13063     $dbh->do(q{
13064         UPDATE systempreferences SET type="Choice" WHERE variable="UsageStatsLibraryType";
13065     });
13066     $dbh->do(q{
13067         UPDATE systempreferences SET value="Canada" WHERE variable="UsageStatsCountry" AND value="CANADA";
13068     });
13069     $dbh->do(q{
13070         UPDATE systempreferences SET value="Czech Republic" WHERE variable="UsageStatsCountry" AND value="CZ";
13071     });
13072     $dbh->do(q{
13073         UPDATE systempreferences SET value="United Kingdom" WHERE variable="UsageStatsCountry" AND (value="England" OR value="UK");
13074     });
13075     $dbh->do(q{
13076         UPDATE systempreferences SET value="Spain" WHERE variable="UsageStatsCountry" AND value="España";
13077     });
13078     $dbh->do(q{
13079         UPDATE systempreferences SET value="Greece" WHERE variable="UsageStatsCountry" AND value="GR";
13080     });
13081     $dbh->do(q{
13082         UPDATE systempreferences SET value="Ireland" WHERE variable="UsageStatsCountry" AND value="Irelanbd";
13083     });
13084     $dbh->do(q{
13085         UPDATE systempreferences SET value="Mexico" WHERE variable="UsageStatsCountry" AND value="México";
13086     });
13087     $dbh->do(q{
13088         UPDATE systempreferences SET value="Peru" WHERE variable="UsageStatsCountry" AND value="Perú";
13089     });
13090     $dbh->do(q{
13091         UPDATE systempreferences SET value="Dominican Rep." WHERE variable="UsageStatsCountry" AND value="República Dominicana";
13092     });
13093     $dbh->do(q{
13094         UPDATE systempreferences SET value="Trinidad & Tob." WHERE variable="UsageStatsCountry" AND value="Trinidad";
13095     });
13096     $dbh->do(q{
13097         UPDATE systempreferences SET value="Turkey" WHERE variable="UsageStatsCountry" AND value="Türkiye";
13098     });
13099     $dbh->do(q{
13100         UPDATE systempreferences SET value="USA" WHERE variable="UsageStatsCountry" AND (value="United States" OR value="United States of America" OR value="US");
13101     });
13102     $dbh->do(q{
13103         UPDATE systempreferences SET value="Zimbabwe" WHERE variable="UsageStatsCountry" AND value="Zimbabbwe";
13104     });
13105
13106     print "Upgrade to $DBversion done (Bug 14707 - Change UsageStatsCountry from free text to a dropdown list)\n";
13107     SetVersion($DBversion);
13108 }
13109
13110 $DBversion = "16.06.00.030";
13111 if ( CheckVersion($DBversion) ) {
13112     $dbh->do(q{
13113         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
13114         ('OPACHoldingsDefaultSortField','first_column','first_column|homebranch|holdingbranch','Default sort field for the holdings table at the OPAC','choice');
13115     });
13116
13117     print "Upgrade to $DBversion done (Bug 16552 - Add the ability to change the default holdings sort)\n";
13118     SetVersion($DBversion);
13119 }
13120
13121 $DBversion = "16.06.00.031";
13122 if ( CheckVersion($DBversion) ) {
13123     $dbh->do(q{
13124         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');
13125     });
13126
13127     print "Upgrade to $DBversion done (Bug 16273 - Prevent selfregistration from printing the borrower password and filling the logging form)\n";
13128     SetVersion($DBversion);
13129 }
13130
13131 $DBversion = "16.06.00.032";
13132 if ( CheckVersion($DBversion) ) {
13133     $dbh->do(q{
13134         UPDATE marc_subfield_structure SET authorised_value="WITHDRAWN" WHERE authorised_value="WTHDRAWN";
13135     });
13136
13137     print "Upgrade to $DBversion done (Bug 17357 - WTHDRAWN is still used in installer files)\n";
13138     SetVersion($DBversion);
13139 }
13140
13141
13142 $DBversion = "16.06.00.033";
13143 if ( CheckVersion($DBversion) ) {
13144     $dbh->do(q{
13145         CREATE TABLE authorised_value_categories (
13146         category_name VARCHAR(32) NOT NULL,
13147         primary key (category_name)
13148         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13149         });
13150 ## Add authorised value categories
13151     $dbh->do(q{
13152     INSERT INTO authorised_value_categories (category_name )
13153     SELECT DISTINCT category FROM authorised_values;
13154     });
13155     
13156 ## Add special categories
13157     $dbh->do(q{
13158     INSERT IGNORE INTO authorised_value_categories( category_name )
13159     VALUES
13160     ('Asort1'),
13161     ('Asort2'),
13162     ('Bsort1'),
13163     ('Bsort2'),
13164     ('SUGGEST'),
13165     ('DAMAGED'),
13166     ('LOST'),
13167     ('REPORT_GROUP'),
13168     ('REPORT_SUBGROUP'),
13169     ('DEPARTMENT'),
13170     ('TERM'),
13171     ('SUGGEST_STATUS'),
13172     ('ITEMTYPECAT');
13173     });
13174
13175 ## Add very special categories
13176     $dbh->do(q{
13177     INSERT IGNORE INTO authorised_value_categories( category_name )
13178     VALUES
13179     ('branches'),
13180     ('itemtypes'),
13181     ('cn_source');
13182     });
13183
13184     $dbh->do(q{
13185     INSERT IGNORE INTO authorised_value_categories( category_name )
13186     VALUES
13187     ('WITHDRAWN'),
13188     ('RESTRICTED'),
13189     ('NOT_LOAN'),
13190     ('CCODE'),
13191     ('LOC'),
13192     ('STACK');
13193     });
13194
13195 ## Update the FK
13196     $dbh->do(q{
13197     ALTER TABLE items_search_fields
13198     DROP FOREIGN KEY items_search_fields_authorised_values_category;
13199     });
13200
13201     $dbh->do(q{
13202     ALTER TABLE items_search_fields
13203     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;
13204     });
13205
13206     $dbh->do(q{
13207     ALTER TABLE authorised_values
13208     ADD CONSTRAINT `authorised_values_authorised_values_category` FOREIGN KEY (`category`) REFERENCES `authorised_value_categories` (`category_name`) ON DELETE CASCADE ON UPDATE CASCADE;
13209     });
13210
13211     $dbh->do(q{
13212             INSERT IGNORE INTO authorised_value_categories( category_name ) SELECT DISTINCT(authorised_value) FROM marc_subfield_structure;
13213             });
13214
13215     $dbh->do(q{
13216             UPDATE marc_subfield_structure SET authorised_value = NULL WHERE authorised_value = '';
13217             });
13218
13219     # 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)
13220     my $table_sth = $dbh->prepare(qq|SHOW CREATE TABLE marc_subfield_structure|);
13221     $table_sth->execute;
13222     my @table = $table_sth->fetchrow_array;
13223     if ( $table[1] !~ /COLLATE=utf8_unicode_ci/ and $table[1] !~ /COLLATE=utf8mb4_unicode_ci/ ) { #catches utf8mb4 collated tables
13224         $dbh->do(qq|ALTER TABLE marc_subfield_structure CHARACTER SET utf8 COLLATE utf8_unicode_ci|);
13225     }
13226     $dbh->do(q{
13227             ALTER TABLE marc_subfield_structure
13228             MODIFY COLUMN authorised_value VARCHAR(32) DEFAULT NULL,
13229             ADD CONSTRAINT marc_subfield_structure_ibfk_1 FOREIGN KEY (authorised_value) REFERENCES authorised_value_categories (category_name) ON UPDATE CASCADE ON DELETE SET NULL;
13230             });
13231
13232       print "Upgrade to $DBversion done (Bug 17216 - Add a new table to store authorized value categories)\n";
13233       SetVersion($DBversion);
13234 }
13235
13236 $DBversion = "16.06.00.034";
13237 if ( CheckVersion($DBversion) ) {
13238     $dbh->do(q{
13239         ALTER TABLE biblioitems DROP COLUMN marc;
13240     });
13241     $dbh->do(q{
13242         ALTER TABLE deletedbiblioitems DROP COLUMN marc;
13243     });
13244
13245     print "Upgrade to $DBversion done (Bug 10455 - remove redundant 'biblioitems.marc' field)\n";
13246     SetVersion($DBversion);
13247 }
13248
13249 $DBversion = '16.06.00.035';
13250 if ( CheckVersion($DBversion) ) {
13251     $dbh->do(q{
13252         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
13253          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'
13254          FROM systempreferences WHERE variable='AllowItemsOnHoldCheckout';
13255     });
13256
13257     print "Upgrade to $DBversion done (Bug 15131: Give SCO separate control for AllowItemsOnHoldCheckout)\n";
13258     SetVersion($DBversion);
13259 }
13260
13261 $DBversion = '16.06.00.036';
13262 if ( CheckVersion($DBversion) ) {
13263     $dbh->do(q{
13264         CREATE TABLE IF NOT EXISTS `housebound_profile` (
13265           `borrowernumber` int(11) NOT NULL, -- Number of the borrower associated with this profile.
13266           `day` text NOT NULL,  -- The preferred day of the week for delivery.
13267           `frequency` text NOT NULL, -- The Authorised_Value definining the pattern for delivery.
13268           `fav_itemtypes` text default NULL, -- Free text describing preferred itemtypes.
13269           `fav_subjects` text default NULL, -- Free text describing preferred subjects.
13270           `fav_authors` text default NULL, -- Free text describing preferred authors.
13271           `referral` text default NULL, -- Free text indicating how the borrower was added to the service.
13272           `notes` text default NULL, -- Free text for additional notes.
13273           PRIMARY KEY  (`borrowernumber`),
13274           CONSTRAINT `housebound_profile_bnfk`
13275             FOREIGN KEY (`borrowernumber`)
13276             REFERENCES `borrowers` (`borrowernumber`)
13277             ON UPDATE CASCADE ON DELETE CASCADE
13278         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13279     });
13280     $dbh->do(q{
13281         CREATE TABLE IF NOT EXISTS `housebound_visit` (
13282           `id` int(11) NOT NULL auto_increment, -- ID of the visit.
13283           `borrowernumber` int(11) NOT NULL, -- Number of the borrower, & the profile, linked to this visit.
13284           `appointment_date` date default NULL, -- Date of visit.
13285           `day_segment` varchar(10),  -- Rough time frame: 'morning', 'afternoon' 'evening'
13286           `chooser_brwnumber` int(11) default NULL, -- Number of the borrower to choose items  for delivery.
13287           `deliverer_brwnumber` int(11) default NULL, -- Number of the borrower to deliver items.
13288           PRIMARY KEY  (`id`),
13289           CONSTRAINT `houseboundvisit_bnfk`
13290             FOREIGN KEY (`borrowernumber`)
13291             REFERENCES `housebound_profile` (`borrowernumber`)
13292             ON UPDATE CASCADE ON DELETE CASCADE,
13293           CONSTRAINT `houseboundvisit_bnfk_1`
13294             FOREIGN KEY (`chooser_brwnumber`)
13295             REFERENCES `borrowers` (`borrowernumber`)
13296             ON UPDATE CASCADE ON DELETE CASCADE,
13297           CONSTRAINT `houseboundvisit_bnfk_2`
13298             FOREIGN KEY (`deliverer_brwnumber`)
13299             REFERENCES `borrowers` (`borrowernumber`)
13300             ON UPDATE CASCADE ON DELETE CASCADE
13301         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13302     });
13303     $dbh->do(q{
13304         CREATE TABLE IF NOT EXISTS `housebound_role` (
13305           `borrowernumber_id` int(11) NOT NULL, -- borrowernumber link
13306           `housebound_chooser` tinyint(1) NOT NULL DEFAULT 0, -- set to 1 to indicate this patron is a housebound chooser volunteer
13307           `housebound_deliverer` tinyint(1) NOT NULL DEFAULT 0, -- set to 1 to indicate this patron is a housebound deliverer volunteer
13308           PRIMARY KEY (`borrowernumber_id`),
13309           CONSTRAINT `houseboundrole_bnfk`
13310             FOREIGN KEY (`borrowernumber_id`)
13311             REFERENCES `borrowers` (`borrowernumber`)
13312             ON UPDATE CASCADE ON DELETE CASCADE
13313         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13314     });
13315     $dbh->do(q{
13316         INSERT IGNORE INTO systempreferences
13317                (variable,value,options,explanation,type) VALUES
13318                ('HouseboundModule',0,'',
13319                'If ON, enable housebound module functionality.','YesNo');
13320     });
13321     $dbh->do(q{
13322         INSERT IGNORE INTO authorised_value_categories( category_name ) VALUES
13323             ('HSBND_FREQ');
13324     });
13325     $dbh->do(q{
13326         INSERT IGNORE INTO authorised_values (category, authorised_value, lib) VALUES
13327                ('HSBND_FREQ','EW','Every week');
13328     });
13329
13330     print "Upgrade to $DBversion done (Bug 5670 - Housebound Readers Module)\n";
13331     SetVersion($DBversion);
13332 }
13333
13334 $DBversion = "16.06.00.037";
13335 if ( CheckVersion($DBversion) ) {
13336     $dbh->do(q{
13337         ALTER TABLE `issuingrules` ADD `article_requests` ENUM( 'no', 'yes', 'bib_only', 'item_only' ) NOT NULL DEFAULT 'no' AFTER `opacitemholds`;
13338     });
13339     $dbh->do(q{
13340         INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES
13341             ('ArticleRequests', '0', NULL, 'Enables the article request feature', 'YesNo'),
13342             ('ArticleRequestsMandatoryFields', '', NULL, 'Comma delimited list of required fields for bibs where article requests rule = ''yes''', 'multiple'),
13343             ('ArticleRequestsMandatoryFieldsItemsOnly', '', NULL, 'Comma delimited list of required fields for bibs where article requests rule = ''item_only''', 'multiple'),
13344             ('ArticleRequestsMandatoryFieldsRecordOnly', '', NULL, 'Comma delimited list of required fields for bibs where article requests rule = ''bib_only''', 'multiple');
13345     });
13346     $dbh->do(q{
13347         CREATE TABLE IF NOT EXISTS `article_requests` (
13348           `id` int(11) NOT NULL AUTO_INCREMENT,
13349           `borrowernumber` int(11) NOT NULL,
13350           `biblionumber` int(11) NOT NULL,
13351           `itemnumber` int(11) DEFAULT NULL,
13352           `branchcode` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
13353           `title` text,
13354           `author` text,
13355           `volume` text,
13356           `issue` text,
13357           `date` text,
13358           `pages` text,
13359           `chapters` text,
13360           `patron_notes` text,
13361           `status` enum('PENDING','PROCESSING','COMPLETED','CANCELED') NOT NULL DEFAULT 'PENDING',
13362           `notes` text,
13363           `created_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
13364           `updated_on` timestamp NULL DEFAULT NULL,
13365           PRIMARY KEY (`id`),
13366           KEY `borrowernumber` (`borrowernumber`),
13367           KEY `biblionumber` (`biblionumber`),
13368           KEY `itemnumber` (`itemnumber`),
13369           KEY `branchcode` (`branchcode`),
13370           CONSTRAINT `article_requests_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
13371           CONSTRAINT `article_requests_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
13372           CONSTRAINT `article_requests_ibfk_3` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE SET NULL ON UPDATE CASCADE,
13373           CONSTRAINT `article_requests_ibfk_4` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE SET NULL ON UPDATE CASCADE
13374         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13375     });
13376     $dbh->do(q{
13377         INSERT INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`) VALUES
13378         ('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'),
13379         ('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'),
13380         ('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'),
13381         ('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'),
13382         ('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');
13383     });
13384
13385     print "Upgrade to $DBversion done (Bug 14610 - Add ability to place article requests in Koha)\n";
13386     SetVersion($DBversion);
13387 }
13388
13389 $DBversion = '16.06.00.038';
13390 if ( CheckVersion($DBversion) ) {
13391     $dbh->do(q{
13392         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');
13393     });
13394
13395     print "Upgrade to $DBversion done (Bug 14874 - Add ability to search for patrons by date of birth from checkout and patron quick searches)\n";
13396     SetVersion($DBversion);
13397 }
13398
13399 $DBversion = "16.06.00.039";
13400 if ( CheckVersion($DBversion) ) {
13401
13402     my $sth = $dbh->prepare(q{
13403         SELECT s.itemnumber, i.itype, b.itemtype
13404         FROM
13405          ( SELECT DISTINCT itemnumber
13406            FROM statistics
13407            WHERE ( type = "return" OR type = "localuse" ) AND
13408                  itemtype IS NULL
13409          ) s
13410         LEFT JOIN
13411          ( SELECT itemnumber,biblionumber, itype
13412              FROM items
13413            UNION
13414            SELECT itemnumber,biblionumber, itype
13415              FROM deleteditems
13416          ) i
13417         ON (s.itemnumber=i.itemnumber)
13418         LEFT JOIN
13419          ( SELECT biblionumber, itemtype
13420              FROM biblioitems
13421            UNION
13422            SELECT biblionumber, itemtype
13423              FROM deletedbiblioitems
13424          ) b
13425         ON (i.biblionumber=b.biblionumber);
13426     });
13427     $sth->execute();
13428
13429     my $update_sth = $dbh->prepare(q{
13430         UPDATE statistics
13431         SET itemtype=?
13432         WHERE itemnumber=? AND itemtype IS NULL
13433     });
13434     my $ilevel_itypes = C4::Context->preference('item-level_itypes');
13435
13436     while ( my ($itemnumber,$item_itype,$biblio_itype) = $sth->fetchrow_array ) {
13437
13438         my $effective_itemtype = $ilevel_itypes
13439                                     ? $item_itype // $biblio_itype
13440                                     : $biblio_itype;
13441         warn "item-level_itypes set but no itype defined for item ($itemnumber)"
13442             if $ilevel_itypes and !defined $item_itype;
13443         $update_sth->execute( $effective_itemtype, $itemnumber );
13444     }
13445
13446     print "Upgrade to $DBversion done (Bug 14598: itemtype is not set on statistics by C4::Circulation::AddReturn)\n";
13447     SetVersion($DBversion);
13448 }
13449
13450 $DBversion = '16.06.00.040';
13451 if ( CheckVersion($DBversion) ) {
13452     $dbh->do(q{
13453         ALTER TABLE `aqcontacts` ADD `orderacquisition` BOOLEAN NOT NULL DEFAULT 0 AFTER `notes`;
13454     });
13455     $dbh->do(q{
13456         INSERT IGNORE INTO `letter` (module, code, name, title, content, message_transport_type) VALUES
13457         ('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');
13458     });
13459
13460     print "Upgrade to $DBversion done (Bug 5260 - Add option to send an order by e-mail to the acquisition module)\n";
13461     SetVersion($DBversion);
13462 }
13463
13464 $DBversion = '16.06.00.041';
13465 if ( CheckVersion($DBversion) ) {
13466     $dbh->do(q{
13467         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')
13468     });
13469
13470     print "Upgrade to $DBversion done (Bug 14629 - Add aggressive ISSN matching feature equivalent to the aggressive ISBN matcher)\n";
13471     SetVersion($DBversion);
13472 }
13473
13474 $DBversion = '16.06.00.042';
13475 if ( CheckVersion($DBversion) ) {
13476     $dbh->do(q|
13477         ALTER TABLE aqorders
13478             ADD COLUMN unitprice_tax_excluded decimal(28,6) default NULL AFTER unitprice,
13479             ADD COLUMN unitprice_tax_included decimal(28,6) default NULL AFTER unitprice_tax_excluded,
13480             ADD COLUMN rrp_tax_excluded decimal(28,6) default NULL AFTER rrp,
13481             ADD COLUMN rrp_tax_included decimal(28,6) default NULL AFTER rrp_tax_excluded,
13482             ADD COLUMN ecost_tax_excluded decimal(28,6) default NULL AFTER ecost,
13483             ADD COLUMN ecost_tax_included decimal(28,6) default NULL AFTER ecost_tax_excluded,
13484             ADD COLUMN tax_value decimal(6,4) default NULL AFTER gstrate
13485     |);
13486
13487     # rename gstrate with tax_rate
13488     $dbh->do(q|ALTER TABLE aqorders CHANGE COLUMN gstrate tax_rate decimal(6,4) DEFAULT NULL|);
13489     $dbh->do(q|ALTER TABLE aqbooksellers CHANGE COLUMN gstrate tax_rate decimal(6,4) DEFAULT NULL|);
13490
13491     # Fill the new columns
13492     my $orders = $dbh->selectall_arrayref(q|
13493         SELECT * FROM aqorders
13494     |, { Slice => {} } );
13495
13496     my $sth_update_order = $dbh->prepare(q|
13497         UPDATE aqorders
13498         SET unitprice_tax_excluded = ?,
13499             unitprice_tax_included = ?,
13500             rrp_tax_excluded = ?,
13501             rrp_tax_included = ?,
13502             ecost_tax_excluded = ?,
13503             ecost_tax_included = ?,
13504             tax_value = ?
13505         WHERE ordernumber = ?
13506     |);
13507
13508     my $sth_get_bookseller = $dbh->prepare(q|
13509         SELECT aqbooksellers.*
13510         FROM aqbooksellers
13511         LEFT JOIN aqbasket ON aqbasket.booksellerid = aqbooksellers.id
13512         LEFT JOIN aqorders ON aqorders.basketno = aqbasket.basketno
13513         WHERE ordernumber = ?
13514     |);
13515
13516     require Number::Format;
13517     my $format = Number::Format->new;
13518     my $precision = 2;
13519     for my $order ( @$orders ) {
13520         $sth_get_bookseller->execute( $order->{ordernumber} );
13521         my ( $bookseller ) = $sth_get_bookseller->fetchrow_hashref;
13522         $order->{rrp}   = $format->round( $order->{rrp}, $precision );
13523         $order->{ecost} = $format->round( $order->{ecost}, $precision );
13524         $order->{tax_rate} ||= 0 ; # tax_rate can be NULL in DB
13525         # Ordering
13526         if ( $bookseller->{listincgst} ) {
13527             $order->{rrp_tax_included} = $order->{rrp};
13528             $order->{rrp_tax_excluded} = $format->round(
13529                 $order->{rrp_tax_included} / ( 1 + $order->{tax_rate} ), $precision );
13530             $order->{ecost_tax_included} = $order->{ecost};
13531             $order->{ecost_tax_excluded} = $format->round(
13532                 $order->{ecost} / ( 1 + $order->{tax_rate} ), $precision );
13533         }
13534         else {
13535             $order->{rrp_tax_excluded} = $order->{rrp};
13536             $order->{rrp_tax_included} = $format->round(
13537                 $order->{rrp} * ( 1 + $order->{tax_rate} ), $precision );
13538             $order->{ecost_tax_excluded} = $order->{ecost};
13539             $order->{ecost_tax_included} = $format->round(
13540                 $order->{ecost} * ( 1 + $order->{tax_rate} ), $precision );
13541         }
13542
13543         #receiving
13544         if ( $bookseller->{listincgst} ) {
13545             $order->{unitprice_tax_included} = $format->round( $order->{unitprice}, $precision );
13546             $order->{unitprice_tax_excluded} = $format->round(
13547               $order->{unitprice_tax_included} / ( 1 + $order->{tax_rate} ), $precision );
13548         }
13549         else {
13550             $order->{unitprice_tax_excluded} = $format->round( $order->{unitprice}, $precision );
13551             $order->{unitprice_tax_included} = $format->round(
13552               $order->{unitprice_tax_excluded} * ( 1 + $order->{tax_rate} ), $precision );
13553         }
13554
13555         # If the order is received, the tax is calculated from the unit price
13556         if ( $order->{orderstatus} eq 'complete' ) {
13557             $order->{tax_value} = $format->round(
13558               ( $order->{unitprice_tax_included} - $order->{unitprice_tax_excluded} )
13559               * $order->{quantity}, $precision );
13560         } else {
13561             # otherwise the ecost is used
13562             $order->{tax_value} = $format->round(
13563                 ( $order->{ecost_tax_included} - $order->{ecost_tax_excluded} ) *
13564                   $order->{quantity}, $precision );
13565         }
13566
13567         $sth_update_order->execute(
13568             $order->{unitprice_tax_excluded},
13569             $order->{unitprice_tax_included},
13570             $order->{rrp_tax_excluded},
13571             $order->{rrp_tax_included},
13572             $order->{ecost_tax_excluded},
13573             $order->{ecost_tax_included},
13574             $order->{tax_value},
13575             $order->{ordernumber},
13576         );
13577     }
13578
13579     print "Upgrade to $DBversion done (Bug 13321 - Tax and prices calculation need to be fixed)\n";
13580     SetVersion($DBversion);
13581 }
13582
13583 $DBversion = '16.06.00.043';
13584 if ( CheckVersion($DBversion) ) {
13585     # Add the new columns
13586     $dbh->do(q|
13587         ALTER TABLE aqorders
13588             ADD COLUMN tax_rate_on_ordering   decimal(6,4) default NULL AFTER tax_rate,
13589             ADD COLUMN tax_rate_on_receiving  decimal(6,4) default NULL AFTER tax_rate_on_ordering,
13590             ADD COLUMN tax_value_on_ordering  decimal(28,6) default NULL AFTER tax_value,
13591             ADD COLUMN tax_value_on_receiving decimal(28,6) default NULL AFTER tax_value_on_ordering
13592     |);
13593
13594     my $orders = $dbh->selectall_arrayref(q|
13595         SELECT * FROM aqorders
13596     |, { Slice => {} } );
13597
13598     my $sth_update_order = $dbh->prepare(q|
13599         UPDATE aqorders
13600         SET tax_rate_on_ordering = tax_rate,
13601             tax_rate_on_receiving = tax_rate,
13602             tax_value_on_ordering = ?,
13603             tax_value_on_receiving = ?
13604         WHERE ordernumber = ?
13605     |);
13606
13607     for my $order (@$orders) {
13608         my $tax_value_on_ordering =
13609           $order->{quantity} *
13610           $order->{ecost_tax_excluded} *
13611           $order->{tax_rate};
13612
13613         my $tax_value_on_receiving =
13614           ( defined $order->{unitprice_tax_excluded} )
13615           ? $order->{quantity} * $order->{unitprice_tax_excluded} * $order->{tax_rate}
13616           : undef;
13617
13618         $sth_update_order->execute( $tax_value_on_ordering,
13619             $tax_value_on_receiving, $order->{ordernumber} );
13620     }
13621
13622     # Remove the old columns
13623     $dbh->do(q|
13624         ALTER TABLE aqorders
13625             CHANGE COLUMN tax_value tax_value_bak  decimal(28,6) default NULL,
13626             CHANGE COLUMN tax_rate tax_rate_bak decimal(6,4) default NULL
13627     |);
13628
13629     print "Upgrade to $DBversion done (Bug 13323 - Change the tax rate on receiving)\n";
13630     SetVersion($DBversion);
13631 }
13632
13633 $DBversion = '16.06.00.044';
13634 if ( CheckVersion($DBversion) ) {
13635     $dbh->do(q{
13636         ALTER TABLE `messages`
13637         ADD `manager_id` int(11) NULL,
13638         ADD FOREIGN KEY (`manager_id`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL;
13639     });
13640
13641     print "Upgrade to $DBversion done (Bug 17397 - Show name of librarian who created circulation message)\n";
13642     SetVersion($DBversion);
13643 }
13644
13645 $DBversion = '16.06.00.045';
13646 if ( CheckVersion($DBversion) ) {
13647     $dbh->do(q{
13648         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";
13649     });
13650
13651     print "Upgrade to $DBversion done (Bug 17443 - Make possible to renew patron by later of expiry and current date)\n";
13652     SetVersion($DBversion);
13653 }
13654
13655 $DBversion = '16.06.00.046';
13656 if ( CheckVersion($DBversion) ) {
13657     $dbh->do(q{
13658         ALTER TABLE issuingrules ADD COLUMN no_auto_renewal_after INT(4) DEFAULT NULL AFTER auto_renew;
13659     });
13660
13661     print "Upgrade to $DBversion done (Bug 15581 - Add a circ rule to not allow auto-renewals after defined loan period)\n";
13662     SetVersion($DBversion);
13663 }
13664
13665 $DBversion = '16.06.00.047';
13666 if ( CheckVersion($DBversion) ) {
13667     $dbh->do(q{
13668         UPDATE language_descriptions SET description = 'Čeština' WHERE subtag = 'cs' AND type = 'language' AND lang = 'cs'
13669     });
13670
13671     print "Upgrade to $DBversion done (Bug 17518: Displayed language name for Czech is wrong)\n";
13672     SetVersion($DBversion);
13673 }
13674
13675 $DBversion = '16.06.00.048';
13676 if( CheckVersion( $DBversion ) ) {
13677     $dbh->do(q|
13678         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
13679         (13, 'upload_general_files', 'Upload any file'),
13680         (13, 'upload_manage', 'Manage uploaded files');
13681     |);
13682
13683     # Update user_permissions for current users (check count in uploaded_files)
13684     # Note 9 == edit_catalogue and 13 == tools
13685     # We do not insert if someone is superlibrarian, does not have edit_catalogue,
13686     # or already has all tools
13687     $dbh->do(q|
13688         INSERT IGNORE INTO user_permissions (borrowernumber, module_bit, code)
13689         SELECT borrowernumber, 13, 'upload_general_files'
13690         FROM borrowers bo
13691         WHERE flags<>1 AND flags & POW(2,13) = 0 AND
13692             ( flags & POW(2,9) > 0 OR (
13693                 SELECT COUNT(*) FROM user_permissions
13694                 WHERE borrowernumber=bo.borrowernumber AND module_bit=9 ) > 0 )
13695             AND ( SELECT COUNT(*) FROM uploaded_files ) > 0;
13696     |);
13697
13698     SetVersion( $DBversion );
13699     print "Upgrade to $DBversion done (Bug 17663 - Forgotten userpermissions)\n";
13700 }
13701
13702 $DBversion = '16.06.00.049';
13703 if( CheckVersion( $DBversion ) ) {
13704     $dbh->do(q|
13705         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) 
13706         VALUES ('ReplytoDefault',  '',  NULL,  'The default email address to be set as replyto.',  'Free');
13707     |);
13708
13709     $dbh->do(q|
13710         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
13711         VALUES ('ReturnpathDefault',  '',  NULL,  'The default email address to be set as return-path',  'Free');
13712     |);
13713
13714     SetVersion( $DBversion );
13715     print "Upgrade to $DBversion done (Bug 17391 - ReturnpathDefault and ReplyToDefault missing from syspref.sql)\n";
13716 }
13717
13718 $DBversion = "16.06.00.050";
13719 if ( CheckVersion($DBversion) ) {
13720
13721     # If index issn_idx still exists, we assume that dbrev 3.15.00.049 failed,
13722     # and we repeat it (partially).
13723     # Note: the db rev only pertains to biblioitems and is not needed for
13724     # deletedbiblioitems.
13725
13726     my $temp = $dbh->selectall_arrayref( "SHOW INDEXES FROM biblioitems WHERE key_name = 'issn_idx'" );
13727
13728     if( @$temp > 0 ) {
13729         $dbh->do( "ALTER TABLE biblioitems DROP INDEX isbn" );
13730         $dbh->do( "ALTER TABLE biblioitems DROP INDEX issn" );
13731         $dbh->do( "ALTER TABLE biblioitems DROP INDEX issn_idx" );
13732         $dbh->do( "ALTER TABLE biblioitems CHANGE isbn isbn MEDIUMTEXT NULL DEFAULT NULL, CHANGE issn issn MEDIUMTEXT NULL DEFAULT NULL" );
13733         $dbh->do( "ALTER TABLE biblioitems ADD INDEX isbn ( isbn ( 255 ) ), ADD INDEX issn ( issn ( 255 ) )" );
13734         print "Upgrade to $DBversion done (Bug 8835). Removed issn_idx.\n";
13735     } else {
13736         print "Upgrade to $DBversion done (Bug 8835). Everything is fine.\n";
13737     }
13738
13739     SetVersion($DBversion);
13740 }
13741
13742 $DBversion = "16.11.00.000";
13743 if ( CheckVersion($DBversion) ) {
13744     print "Upgrade to $DBversion done (Koha 16.11)\n";
13745     SetVersion($DBversion);
13746 }
13747
13748 $DBversion = "16.12.00.000";
13749 if ( CheckVersion($DBversion) ) {
13750     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";
13751     SetVersion($DBversion);
13752 }
13753
13754 $DBversion = "16.12.00.001";
13755 if ( CheckVersion($DBversion) ) {
13756     $dbh->do(q{
13757         ALTER TABLE borrower_modifications
13758         ADD COLUMN extended_attributes text DEFAULT NULL
13759         AFTER privacy
13760     });
13761
13762     print "Upgrade to $DBversion done (Bug 17767 - Let Koha::Patron::Modification handle extended attributes)\n";
13763     SetVersion($DBversion);
13764 }
13765
13766 $DBversion = '16.12.00.002';
13767 if ( CheckVersion($DBversion) ) {
13768     unless (column_exists( 'branchtransfers', 'branchtransfer_id' )
13769         and index_exists( 'branchtransfers', 'PRIMARY' ) )
13770     {
13771         $dbh->do(
13772             "ALTER TABLE branchtransfers
13773                  ADD COLUMN branchtransfer_id int(12) NOT NULL auto_increment FIRST, ADD CONSTRAINT PRIMARY KEY (branchtransfer_id);"
13774         );
13775     }
13776
13777     SetVersion($DBversion);
13778     print "Upgrade to $DBversion done (Bug 14187 - branchtransfer needs a primary key (id) for DBIx and common sense.)\n";
13779 }
13780
13781 $DBversion = '16.12.00.003';
13782 if ( CheckVersion($DBversion) ) {
13783     $dbh->do(q{DELETE FROM systempreferences WHERE variable="Persona"});
13784     SetVersion($DBversion);
13785     print "Upgrade to $DBversion done (Bug 17486 - Remove 'Mozilla Persona' as an authentication method)\n";
13786 }
13787
13788 $DBversion = '16.12.00.004';
13789 if ( CheckVersion($DBversion) ) {
13790     $dbh->do(q{
13791         CREATE TABLE biblio_metadata (
13792             `id` INT(11) NOT NULL AUTO_INCREMENT,
13793             `biblionumber` INT(11) NOT NULL,
13794             `format` VARCHAR(16) NOT NULL,
13795             `marcflavour` VARCHAR(16) NOT NULL,
13796             `metadata` LONGTEXT NOT NULL,
13797             PRIMARY KEY(id),
13798             UNIQUE KEY `biblio_metadata_uniq_key` (`biblionumber`,`format`,`marcflavour`),
13799             CONSTRAINT `biblio_metadata_fk_1` FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
13800         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13801     });
13802     $dbh->do(q{
13803         CREATE TABLE deletedbiblio_metadata (
13804             `id` INT(11) NOT NULL AUTO_INCREMENT,
13805             `biblionumber` INT(11) NOT NULL,
13806             `format` VARCHAR(16) NOT NULL,
13807             `marcflavour` VARCHAR(16) NOT NULL,
13808             `metadata` LONGTEXT NOT NULL,
13809             PRIMARY KEY(id),
13810             UNIQUE KEY `deletedbiblio_metadata_uniq_key` (`biblionumber`,`format`,`marcflavour`),
13811             CONSTRAINT `deletedbiblio_metadata_fk_1` FOREIGN KEY (biblionumber) REFERENCES deletedbiblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
13812         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13813     });
13814     $dbh->do(q{
13815         INSERT INTO biblio_metadata ( biblionumber, format, marcflavour, metadata ) SELECT biblionumber, 'marcxml', 'CHANGEME', marcxml FROM biblioitems;
13816     });
13817     $dbh->do(q{
13818         INSERT INTO deletedbiblio_metadata ( biblionumber, format, marcflavour, metadata ) SELECT biblionumber, 'marcxml', 'CHANGEME', marcxml FROM deletedbiblioitems;
13819     });
13820     $dbh->do(q{
13821         UPDATE biblio_metadata SET marcflavour = (SELECT value FROM systempreferences WHERE variable="marcflavour");
13822     });
13823     $dbh->do(q{
13824         UPDATE deletedbiblio_metadata SET marcflavour = (SELECT value FROM systempreferences WHERE variable="marcflavour");
13825     });
13826     $dbh->do(q{
13827         ALTER TABLE biblioitems DROP COLUMN marcxml;
13828     });
13829     $dbh->do(q{
13830         ALTER TABLE deletedbiblioitems DROP COLUMN marcxml;
13831     });
13832     SetVersion($DBversion);
13833     print "Upgrade to $DBversion done (Bug 17196 - Move marcxml out of the biblioitems table)\n";
13834 }
13835
13836 $DBversion = '16.12.00.005';
13837 if( CheckVersion( $DBversion ) ) {
13838     $dbh->do( "INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('AuthorityMergeMode','loose','loose|strict','Authority merge mode','Choice')");
13839
13840     SetVersion( $DBversion );
13841     print "Upgrade to $DBversion done (Bug 17913 - AuthorityMergeMode)\n";
13842 }
13843
13844 $DBversion = "16.12.00.006";
13845 if ( CheckVersion($DBversion) ) {
13846     unless (     column_exists( 'borrower_attributes', 'id' )
13847              and index_exists( 'borrower_attributes', 'PRIMARY' ) )
13848     {
13849         $dbh->do(q{
13850             ALTER TABLE `borrower_attributes`
13851                 ADD `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
13852         });
13853     }
13854
13855     print "Upgrade to $DBversion done (Bug 17813: Table borrower_attributes needs a primary key\n";
13856     SetVersion($DBversion);
13857 }
13858
13859 $DBversion = "16.12.00.007";
13860 if( CheckVersion( $DBversion ) ) {
13861
13862     if ( column_exists('opac_news', 'new' ) ) {
13863         $dbh->do(q|ALTER TABLE opac_news CHANGE COLUMN new content text NOT NULL|);
13864     }
13865
13866     $dbh->do(q|
13867         UPDATE letter SET content = REPLACE(content, "<<opac_news.new>>", "<<opac_news.content>>") WHERE content LIKE "%<<opac_news.new>>%"
13868     |);
13869
13870     SetVersion( $DBversion );
13871     print "Upgrade to $DBversion done (Bug 17960 - Rename opac_news with opac_news.content (template notices have been updated!))\n";
13872 }
13873
13874 $DBversion = "16.12.00.008";
13875 if( CheckVersion( $DBversion ) ) {
13876     $dbh->do(q{
13877         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
13878         ('MarcItemFieldsToOrder','','Set the mapping values for new item records created from a MARC record in a staged file. In a YAML format.', NULL, 'textarea');
13879     });
13880
13881     SetVersion( $DBversion );
13882     print "Upgrade to $DBversion done (Bug 15503 - Grab Item Information from Order Files)\n";
13883 }
13884
13885 $DBversion = "16.12.00.009";
13886 if( CheckVersion( $DBversion ) ) {
13887     $dbh->do(q{
13888         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
13889         ('OPACHoldsIfAvailableAtPickup','1','','Allow to pickup up holds at libraries where the item is available','YesNo');
13890     });
13891
13892     $dbh->do(q{
13893         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
13894         ('OPACHoldsIfAvailableAtPickupExceptions','','','List the patron categories not affected by OPACHoldsIfAvailableAtPickup if off','Free');
13895     });
13896
13897     SetVersion( $DBversion );
13898     print "Upgrade to $DBversion done (Bug 17453 - Inter-site holds improvement)\n";
13899 }
13900
13901 $DBversion = "16.12.00.010";
13902 if( CheckVersion( $DBversion ) ) {
13903     $dbh->do(q{
13904         ALTER TABLE borrowers ADD overdrive_auth_token text default NULL AFTER lastseen;
13905     });
13906
13907     $dbh->do(q{
13908         ALTER TABLE deletedborrowers ADD overdrive_auth_token text default NULL AFTER lastseen;
13909     });
13910
13911     $dbh->do(q{
13912         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
13913         VALUES ('OverDriveCirculation','0','Enable client to see their OverDrive account','','YesNo');
13914     });
13915
13916     SetVersion( $DBversion );
13917     print "Upgrade to $DBversion done (Bug 16034 - Integration with OverDrive Patron API)\n";
13918 }
13919
13920 $DBversion = "16.12.00.011";
13921 if( CheckVersion( $DBversion ) ) {
13922     $dbh->do(q{
13923         ALTER TABLE search_field CHANGE COLUMN type type ENUM('', 'string', 'date', 'number', 'boolean', 'sum') NOT NULL
13924         COMMENT 'what type of data this holds, relevant when storing it in the search engine';
13925     });
13926
13927     SetVersion( $DBversion );
13928     print "Upgrade to $DBversion done (Bug 17260 - updatedatabase.pl fails on invalid entries in ENUM and BOOLEAN columns)\n";
13929 }
13930
13931 $DBversion = "16.12.00.012";
13932 if( CheckVersion( $DBversion ) ) {
13933     $dbh->do(q{
13934         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`)
13935         VALUES ('OpacNewsLibrarySelect', '0', '', 'Show selector for branches on OPAC news page', 'YesNo');
13936     });
13937
13938     SetVersion( $DBversion );
13939     print "Upgrade to $DBversion done (Bug 14764 - Add OPAC News branch selector)\n";
13940 }
13941
13942 $DBversion = "16.12.00.013";
13943 if( CheckVersion( $DBversion ) ) {
13944     $dbh->do(q{
13945         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
13946         VALUES ('CircSidebar','0','','Activate or deactivate the navigation sidebar on all Circulation pages','YesNo');
13947     });
13948
13949     SetVersion( $DBversion );
13950     print "Upgrade to $DBversion done (Bug 16530 - Add a circ sidebar navigation menu)\n";
13951 }
13952
13953 $DBversion = "16.12.00.014";
13954 if( CheckVersion( $DBversion ) ) {
13955     $dbh->do(q{
13956             INSERT INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
13957             ('LoadSearchHistoryToTheFirstLoggedUser', '1', NULL, 'If ON, the next user will automatically get the last searches in his history', 'YesNo');
13958             });
13959             SetVersion( $DBversion );
13960             print "Upgrade to $DBversion done (Bug 8010 - Search history can be added to the wrong patron)\n";
13961             }
13962
13963 $DBversion = "16.12.00.015";
13964 if( CheckVersion( $DBversion ) ) {
13965     unless( column_exists( 'branches', 'geolocation' ) ) {
13966         $dbh->do(q|
13967                 ALTER TABLE branches ADD COLUMN geolocation VARCHAR(255) DEFAULT NULL after opac_info
13968                 |);
13969     }
13970
13971     $dbh->do(q|
13972             INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type ) VALUES ('UsageStatsGeolocation', '', NULL, 'Geolocation of the main library', 'Free');
13973             |);
13974     $dbh->do(q|
13975             INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type ) VALUES ('UsageStatsLibrariesInfo', '', NULL, 'Share libraries information', 'YesNo');
13976             |);
13977     $dbh->do(q|
13978             INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type ) VALUES ('UsageStatsPublicID', '', NULL, 'Public ID for Hea website', 'Free');
13979             |);
13980         
13981         SetVersion( $DBversion );
13982     print "Upgrade to $DBversion done (Bug 18066 - Hea version 2)\n";
13983 }
13984
13985 $DBversion = "16.12.00.016";
13986 if ( CheckVersion($DBversion) ) {
13987     unless ( column_exists( 'borrower_attribute_types', 'opac_editable' ) )
13988     {
13989         $dbh->do(q{
13990             ALTER TABLE borrower_attribute_types
13991                 ADD COLUMN `opac_editable` tinyint(1) NOT NULL default 0 AFTER `opac_display`
13992         });
13993     }
13994
13995     print "Upgrade to $DBversion done (Bug 13757: Make patron attributes editable in the opac if set to 'editable in OPAC)'\n";
13996     SetVersion($DBversion);
13997 }
13998
13999 $DBversion = "16.12.00.017";
14000 if ( CheckVersion($DBversion) ) {
14001     $dbh->do(q{
14002         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
14003         VALUES ('CumulativeRestrictionPeriods',  0,  NULL,  'Cumulate the restriction periods instead of keeping the highest',  'YesNo')
14004     });
14005
14006     print "Upgrade to $DBversion done (Bug 14146 - Additional days are not added to restriction period when checking-in several overdues for same patron)'\n";
14007     SetVersion($DBversion);
14008 }
14009
14010 $DBversion = "16.12.00.018";
14011 if ( CheckVersion($DBversion) ) {
14012     $dbh->do(q{
14013         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
14014             SELECT 'ExportCircHistory', COUNT(*), NULL, "Display the export circulation options",  'YesNo'
14015             FROM systempreferences
14016             WHERE ( variable = 'ExportRemoveFields' AND value != "" AND value IS NOT NULL )
14017                 OR ( variable = 'ExportWithCsvProfile' AND value != "" AND value IS NOT NULL );
14018     });
14019
14020     $dbh->do(q{
14021         DELETE FROM systempreferences WHERE variable="ExportWithCsvProfile";
14022     });
14023
14024     print "Upgrade to $DBversion done (Bug 15498 - Replace ExportWithCsvProfile with ExportCircHistory)'\n";
14025     SetVersion($DBversion);
14026 }
14027
14028 $DBversion = "16.12.00.019";
14029 if( CheckVersion( $DBversion ) ) {
14030     if ( column_exists( 'issues', 'return' ) ) {
14031         $dbh->do(q|ALTER TABLE issues DROP column `return`|);
14032     }
14033
14034     if ( column_exists( 'old_issues', 'return' ) ) {
14035         $dbh->do(q|ALTER TABLE old_issues DROP column `return`|);
14036     }
14037
14038     SetVersion( $DBversion );
14039     print "Upgrade to $DBversion done (Bug 18173 - Remove issues.return DB field)\n";
14040 }
14041
14042 $DBversion = "16.12.00.020";
14043 if( CheckVersion( $DBversion ) ) {
14044     $dbh->do(q{
14045         UPDATE systempreferences SET options="any_time_is_placed|not_always|any_time_is_collected" WHERE variable="HoldFeeMode";
14046     });
14047
14048     $dbh->do(q{
14049         UPDATE systempreferences SET value="any_time_is_placed" WHERE variable="HoldFeeMode" AND value="always";
14050     });
14051
14052     SetVersion( $DBversion );
14053     print "Upgrade to $DBversion done (Bug 17560 - Hold fee placement at point of checkout)\n";
14054 }
14055
14056 $DBversion = "16.12.00.021";
14057 if( CheckVersion( $DBversion ) ) {
14058     $dbh->do(q{
14059         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14060         ('RenewalLog','0','','If ON, log information about renewals','YesNo');
14061     });
14062
14063     SetVersion( $DBversion );
14064     print "Upgrade to $DBversion done (Bug 17708 - Renewal log seems empty)\n";
14065 }
14066
14067 $DBversion = "16.12.00.022";
14068 if( CheckVersion( $DBversion ) ) {
14069     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";
14070     SetVersion( $DBversion );
14071     print "Upgrade to $DBversion done (Bug 17866 - Change sender for serial claim notifications)\n";
14072 }
14073
14074 $DBversion = '16.12.00.023';
14075 if( CheckVersion( $DBversion ) ) {
14076     my $oldval = C4::Context->preference('dontmerge');
14077     my $newval = $oldval ? 0 : 50;
14078
14079     # Remove dontmerge, add AuthorityMergeLimit
14080     $dbh->do(q{
14081         DELETE FROM systempreferences WHERE variable = 'dontmerge';
14082     });
14083     $dbh->do(qq{
14084         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');
14085     });
14086
14087     $dbh->do(q{
14088         ALTER TABLE need_merge_authorities
14089             ADD COLUMN authid_new BIGINT AFTER authid,
14090             ADD COLUMN reportxml text AFTER authid_new,
14091             ADD COLUMN timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
14092     });
14093
14094     $dbh->do(q{
14095         UPDATE need_merge_authorities SET authid_new=authid WHERE done <> 1
14096     });
14097
14098     SetVersion( $DBversion );
14099     if( $newval == 0 ) {
14100         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";
14101     }
14102     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";
14103     print "Upgrade to $DBversion done (Bug 9988 - Add AuthorityMergeLimit)\n";
14104 }
14105
14106 $DBversion = '16.12.00.024';
14107 if( CheckVersion( $DBversion ) ) {
14108     $dbh->do(q{
14109         UPDATE systempreferences SET variable="NoticeBcc" WHERE variable="OverdueNoticeBcc";
14110     });
14111
14112     SetVersion( $DBversion );
14113     print "Upgrade to $DBversion done (Bug 14537 - The system preference 'OverdueNoticeBcc' is mis-named.)\n";
14114 }
14115
14116 $DBversion = '16.12.00.025';
14117 if( CheckVersion( $DBversion ) ) {
14118     $dbh->do(q|
14119         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
14120         VALUES ('UploadPurgeTemporaryFilesDays','',NULL,'If not empty, number of days used when automatically deleting temporary uploads','integer');
14121     |);
14122
14123     my ( $cnt ) = $dbh->selectrow_array( "SELECT COUNT(*) FROM uploaded_files WHERE permanent IS NULL or permanent=0" );
14124     if( $cnt ) {
14125         print "NOTE: You have $cnt temporary uploads. You could benefit from setting pref UploadPurgeTemporaryFilesDays now to automatically delete them.\n";
14126     }
14127
14128     SetVersion( $DBversion );
14129     print "Upgrade to $DBversion done (Bug 17669 - Introduce preference for deleting temporary uploads)\n";
14130 }
14131
14132 $DBversion = '16.12.00.026';
14133 if( CheckVersion( $DBversion ) ) {
14134
14135     # In order to be overcomplete, we check if the situation is what we expect
14136     if( !index_exists( 'serialitems', 'PRIMARY' ) ) {
14137         if( index_exists( 'serialitems', 'serialitemsidx' ) ) {
14138             $dbh->do(q|
14139                 ALTER TABLE serialitems ADD PRIMARY KEY (itemnumber), DROP INDEX serialitemsidx;
14140             |);
14141         } else {
14142             $dbh->do(q|ALTER TABLE serialitems ADD PRIMARY KEY (itemnumber)|);
14143         }
14144     }
14145
14146     SetVersion( $DBversion );
14147     print "Upgrade to $DBversion done (Bug 18427 - Add a primary key to serialitems)\n";
14148 }
14149
14150 $DBversion = '16.12.00.027';
14151 if( CheckVersion( $DBversion ) ) {
14152
14153     $dbh->do(q{
14154         CREATE TABLE IF NOT EXISTS club_templates (
14155           id int(11) NOT NULL AUTO_INCREMENT,
14156           `name` tinytext NOT NULL,
14157           description text,
14158           is_enrollable_from_opac tinyint(1) NOT NULL DEFAULT '0',
14159           is_email_required tinyint(1) NOT NULL DEFAULT '0',
14160           branchcode varchar(10) NULL DEFAULT NULL,
14161           date_created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
14162           date_updated timestamp NULL DEFAULT NULL,
14163           is_deletable tinyint(1) NOT NULL DEFAULT '1',
14164           PRIMARY KEY (id),
14165           KEY ct_branchcode (branchcode),
14166           CONSTRAINT `club_templates_ibfk_1` FOREIGN KEY (branchcode) REFERENCES `branches` (branchcode) ON DELETE CASCADE ON UPDATE CASCADE
14167         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14168     });
14169
14170     $dbh->do(q{
14171         CREATE TABLE IF NOT EXISTS clubs (
14172           id int(11) NOT NULL AUTO_INCREMENT,
14173           club_template_id int(11) NOT NULL,
14174           `name` tinytext NOT NULL,
14175           description text,
14176           date_start date DEFAULT NULL,
14177           date_end date DEFAULT NULL,
14178           branchcode varchar(10) NULL DEFAULT NULL,
14179           date_created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
14180           date_updated timestamp NULL DEFAULT NULL,
14181           PRIMARY KEY (id),
14182           KEY club_template_id (club_template_id),
14183           KEY branchcode (branchcode),
14184           CONSTRAINT clubs_ibfk_1 FOREIGN KEY (club_template_id) REFERENCES club_templates (id) ON DELETE CASCADE ON UPDATE CASCADE,
14185           CONSTRAINT clubs_ibfk_2 FOREIGN KEY (branchcode) REFERENCES branches (branchcode)
14186         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14187     });
14188
14189     $dbh->do(q{
14190         CREATE TABLE IF NOT EXISTS club_enrollments (
14191           id int(11) NOT NULL AUTO_INCREMENT,
14192           club_id int(11) NOT NULL,
14193           borrowernumber int(11) NOT NULL,
14194           date_enrolled timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
14195           date_canceled timestamp NULL DEFAULT NULL,
14196           date_created timestamp NULL DEFAULT NULL,
14197           date_updated timestamp NULL DEFAULT NULL,
14198           branchcode varchar(10) NULL DEFAULT NULL,
14199           PRIMARY KEY (id),
14200           KEY club_id (club_id),
14201           KEY borrowernumber (borrowernumber),
14202           KEY branchcode (branchcode),
14203           CONSTRAINT club_enrollments_ibfk_1 FOREIGN KEY (club_id) REFERENCES clubs (id) ON DELETE CASCADE ON UPDATE CASCADE,
14204           CONSTRAINT club_enrollments_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE,
14205           CONSTRAINT club_enrollments_ibfk_3 FOREIGN KEY (branchcode) REFERENCES branches (branchcode) ON DELETE SET NULL ON UPDATE CASCADE
14206         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14207     });
14208
14209     $dbh->do(q{
14210         CREATE TABLE IF NOT EXISTS club_template_enrollment_fields (
14211           id int(11) NOT NULL AUTO_INCREMENT,
14212           club_template_id int(11) NOT NULL,
14213           `name` tinytext NOT NULL,
14214           description text,
14215           authorised_value_category varchar(16) DEFAULT NULL,
14216           PRIMARY KEY (id),
14217           KEY club_template_id (club_template_id),
14218           CONSTRAINT club_template_enrollment_fields_ibfk_1 FOREIGN KEY (club_template_id) REFERENCES club_templates (id) ON DELETE CASCADE ON UPDATE CASCADE
14219         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14220     });
14221
14222     $dbh->do(q{
14223         CREATE TABLE IF NOT EXISTS club_enrollment_fields (
14224           id int(11) NOT NULL AUTO_INCREMENT,
14225           club_enrollment_id int(11) NOT NULL,
14226           club_template_enrollment_field_id int(11) NOT NULL,
14227           `value` text NOT NULL,
14228           PRIMARY KEY (id),
14229           KEY club_enrollment_id (club_enrollment_id),
14230           KEY club_template_enrollment_field_id (club_template_enrollment_field_id),
14231           CONSTRAINT club_enrollment_fields_ibfk_1 FOREIGN KEY (club_enrollment_id) REFERENCES club_enrollments (id) ON DELETE CASCADE ON UPDATE CASCADE,
14232           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
14233         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14234     });
14235
14236     $dbh->do(q{
14237         CREATE TABLE IF NOT EXISTS club_template_fields (
14238           id int(11) NOT NULL AUTO_INCREMENT,
14239           club_template_id int(11) NOT NULL,
14240           `name` tinytext NOT NULL,
14241           description text,
14242           authorised_value_category varchar(16) DEFAULT NULL,
14243           PRIMARY KEY (id),
14244           KEY club_template_id (club_template_id),
14245           CONSTRAINT club_template_fields_ibfk_1 FOREIGN KEY (club_template_id) REFERENCES club_templates (id) ON DELETE CASCADE ON UPDATE CASCADE
14246         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14247     });
14248
14249     $dbh->do(q{
14250         CREATE TABLE IF NOT EXISTS club_fields (
14251           id int(11) NOT NULL AUTO_INCREMENT,
14252           club_template_field_id int(11) NOT NULL,
14253           club_id int(11) NOT NULL,
14254           `value` text,
14255           PRIMARY KEY (id),
14256           KEY club_template_field_id (club_template_field_id),
14257           KEY club_id (club_id),
14258           CONSTRAINT club_fields_ibfk_3 FOREIGN KEY (club_template_field_id) REFERENCES club_template_fields (id) ON DELETE CASCADE ON UPDATE CASCADE,
14259           CONSTRAINT club_fields_ibfk_4 FOREIGN KEY (club_id) REFERENCES clubs (id) ON DELETE CASCADE ON UPDATE CASCADE
14260         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14261     });
14262
14263     $dbh->do(q{
14264         INSERT IGNORE INTO userflags (bit, flag, flagdesc, defaulton) VALUES (21, 'clubs', 'Patron clubs', '0');
14265     });
14266
14267     $dbh->do(q{
14268         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
14269            (21, 'edit_templates', 'Create and update club templates'),
14270            (21, 'edit_clubs', 'Create and update clubs'),
14271            (21, 'enroll', 'Enroll patrons in clubs')
14272         ;
14273     });
14274
14275     SetVersion( $DBversion );
14276     print "Upgrade to $DBversion done (Bug 12461 - Add patron clubs feature)\n";
14277 }
14278
14279 $DBversion = '16.12.00.028';
14280 if( CheckVersion( $DBversion ) ) {
14281     $dbh->do(q{
14282         UPDATE systempreferences  SET options = 'us|de|fr' WHERE variable = 'AddressFormat';
14283     });
14284
14285     SetVersion( $DBversion );
14286     print "Upgrade to $DBversion done (Bug 18110 - Adds FR to the syspref AddressFormat)\n";
14287 }
14288
14289 $DBversion = '16.12.00.029';
14290 if( CheckVersion( $DBversion ) ) {
14291     unless( column_exists( 'issues', 'note' ) ) {
14292         $dbh->do(q|ALTER TABLE issues ADD note mediumtext default NULL AFTER onsite_checkout|);
14293     }
14294     unless( column_exists( 'issues', 'notedate' ) ) {
14295         $dbh->do(q|ALTER TABLE issues ADD notedate datetime default NULL AFTER note|);
14296     }
14297     unless( column_exists( 'old_issues', 'note' ) ) {
14298         $dbh->do(q|ALTER TABLE old_issues ADD note mediumtext default NULL AFTER onsite_checkout|);
14299     }
14300     unless( column_exists( 'old_issues', 'notedate' ) ) {
14301         $dbh->do(q|ALTER TABLE old_issues ADD notedate datetime default NULL AFTER note|);
14302     }
14303
14304     $dbh->do(q|
14305         INSERT IGNORE INTO letter (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`)
14306         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');
14307     |);
14308
14309     $dbh->do(q|
14310         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`,`type`)
14311         VALUES ('AllowCheckoutNotes', '0', NULL, 'Allow patrons to submit notes about checked out items.','YesNo');
14312     |);
14313
14314     SetVersion( $DBversion );
14315     print "Upgrade to $DBversion done (Bug 14224: Add column issues.note and issues.notedate)\n";
14316 }
14317
14318 $DBversion = '16.12.00.030';
14319 if( CheckVersion( $DBversion ) ) {
14320     unless( column_exists( 'issuingrules', 'no_auto_renewal_after_hard_limit' ) ) {
14321         $dbh->do(q{
14322             ALTER TABLE issuingrules ADD COLUMN no_auto_renewal_after_hard_limit DATE DEFAULT NULL AFTER no_auto_renewal_after;
14323         });
14324     }
14325
14326     SetVersion( $DBversion );
14327     print "Upgrade to $DBversion done (Bug 16344 - Add a circ rule to limit the auto renewals given a specific date)\n";
14328 }
14329
14330 $DBversion = '16.12.00.031';
14331 if( CheckVersion( $DBversion ) ) {
14332     if ( !index_exists( 'biblioitems', 'timestamp' ) ) {
14333         $dbh->do("ALTER TABLE biblioitems ADD KEY `timestamp` (`timestamp`);");
14334     }
14335     if ( !index_exists( 'deletedbiblioitems', 'timestamp' ) ) {
14336         $dbh->do("ALTER TABLE deletedbiblioitems ADD KEY `timestamp` (`timestamp`);");
14337     }
14338     if ( !index_exists( 'items', 'timestamp' ) ) {
14339         $dbh->do("ALTER TABLE items ADD KEY `timestamp` (`timestamp`);");
14340     }
14341     if ( !index_exists( 'deleteditems', 'timestamp' ) ) {
14342         $dbh->do("ALTER TABLE deleteditems ADD KEY `timestamp` (`timestamp`);");
14343     }
14344
14345     SetVersion( $DBversion );
14346     print "Upgrade to $DBversion done (Bug 15108: OAI-PMH provider improvements)\n";
14347 }
14348
14349 $DBversion = '16.12.00.032';
14350 if( CheckVersion( $DBversion ) ) {
14351     require Koha::Calendar;
14352
14353     $dbh->do(q{
14354         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) 
14355         VALUES ('ExcludeHolidaysFromMaxPickUpDelay', '0', 'If ON, reserves max pickup delay takes into account the closed days.', NULL, 'Integer');
14356     });
14357
14358     my $waiting_holds = $dbh->selectall_arrayref(q|
14359         SELECT expirationdate, waitingdate, branchcode
14360         FROM reserves
14361         WHERE found = 'W' AND priority = 0
14362     |, { Slice => {} });
14363     my $update_sth = $dbh->prepare(q|
14364         UPDATE reserves
14365         SET expirationdate = ?
14366         WHERE reserve_id = ?
14367     |);
14368     my $max_pickup_delay = C4::Context->preference("ReservesMaxPickUpDelay");
14369     for my $hold ( @$waiting_holds ) {
14370
14371         my $requested_expiration;
14372         if ($hold->{expirationdate}) {
14373             $requested_expiration = dt_from_string($hold->{expirationdate});
14374         }
14375
14376         my $expirationdate = dt_from_string($hold->{waitingdate});
14377         if ( C4::Context->preference("ExcludeHolidaysFromMaxPickUpDelay") ) {
14378             my $calendar = Koha::Calendar->new( branchcode => $hold->{branchcode}, days_mode => C4::Context->preference('useDaysMode') );
14379             $expirationdate = $calendar->days_forward( $expirationdate, $max_pickup_delay );
14380         } else {
14381             $expirationdate->add( days => $max_pickup_delay );
14382         }
14383
14384         my $cmp = $requested_expiration ? DateTime->compare($requested_expiration, $expirationdate) : 0;
14385         $update_sth->execute($cmp == -1 ? $requested_expiration->ymd : $expirationdate->ymd, $hold->{reserve_id});
14386     }
14387
14388     SetVersion( $DBversion );
14389     print "Upgrade to $DBversion done (Bug 12063 - Update reserves.expirationdate)\n";
14390 }
14391
14392 $DBversion = '16.12.00.033';
14393 if( CheckVersion( $DBversion ) ) {
14394
14395     if( !column_exists( 'letter', 'lang' ) ) {
14396         $dbh->do( "ALTER TABLE letter ADD COLUMN lang VARCHAR(25) NOT NULL DEFAULT 'default' AFTER message_transport_type" );
14397     }
14398
14399     if( !column_exists( 'borrowers', 'lang' ) ) {
14400         $dbh->do( "ALTER TABLE borrowers ADD COLUMN lang VARCHAR(25) NOT NULL DEFAULT 'default' AFTER lastseen" );
14401         $dbh->do( "ALTER TABLE deletedborrowers ADD COLUMN lang VARCHAR(25) NOT NULL DEFAULT 'default' AFTER lastseen" );
14402     }
14403
14404     # Add test on existene of this key
14405     $dbh->do( "ALTER TABLE message_transports DROP FOREIGN KEY message_transports_ibfk_3 ");
14406     $dbh->do( "ALTER TABLE letter DROP PRIMARY KEY ");
14407     $dbh->do( "ALTER TABLE letter ADD PRIMARY KEY (`module`, `code`, `branchcode`, `message_transport_type`, `lang`) ");
14408
14409     $dbh->do( "INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
14410         VALUES ('TranslateNotices',  '0',  NULL,  'Allow notices to be translated',  'YesNo') ");
14411
14412     SetVersion( $DBversion );
14413     print "Upgrade to $DBversion done (Bug 17762 - Add columns letter.lang and borrowers.lang to allow translation of notices)\n";
14414 }
14415
14416 $DBversion = '16.12.00.034';
14417 if( CheckVersion( $DBversion ) ) {
14418     $dbh->do(q{
14419         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
14420         VALUES ('OPACFineNoRenewalsBlockAutoRenew','0','','Block/Allow auto renewals if the patron owe more than OPACFineNoRenewals','YesNo')
14421     });
14422
14423     SetVersion( $DBversion );
14424     print "Upgrade to $DBversion done (Bug 15582 - Ability to block auto renewals if the OPACFineNoRenewals amount is reached)\n";
14425 }
14426
14427 $DBversion = '16.12.00.035';
14428 if( CheckVersion( $DBversion ) ) {
14429     if( !column_exists( 'issues', 'auto_renew_error' ) ) {
14430         $dbh->do(q{
14431            ALTER TABLE issues ADD COLUMN auto_renew_error VARCHAR(32) DEFAULT NULL AFTER auto_renew;
14432         });
14433     }
14434
14435     if( !column_exists( 'old_issues', 'auto_renew_error' ) ) {
14436         $dbh->do(q{
14437             ALTER TABLE old_issues ADD COLUMN auto_renew_error VARCHAR(32) DEFAULT NULL AFTER auto_renew;
14438         });
14439     }
14440
14441     $dbh->do(q{
14442             INSERT INTO letter (module, code, name, title, content, message_transport_type) VALUES ('circulation', 'AUTO_RENEWALS', 'Notification of automatic renewal', 'Automatic renewal notice',
14443         "Dear [% borrower.firstname %] [% borrower.surname %],
14444 [% IF checkout.auto_renew_error %]
14445 The following item, [% biblio.title %], has not been renewed because:
14446 [% IF checkout.auto_renew_error == 'too_many' %]
14447 You have reached the maximum number of renewals possible.
14448 [% ELSIF checkout.auto_renew_error == 'on_reserve' %]
14449 This item is on hold for another patron.
14450 [% ELSIF checkout.auto_renew_error == 'restriction' %]
14451 You are currently restricted.
14452 [% ELSIF checkout.auto_renew_error == 'overdue' %]
14453 You have overdue items.
14454 [% ELSIF checkout.auto_renew_error == 'auto_too_late' %]
14455 It\'s too late to renew this item.
14456 [% ELSIF checkout.auto_renew_error == 'auto_too_much_oweing' %]
14457 Your total unpaid fines are too high.
14458 [% END %]
14459 [% ELSE %]
14460 The following item, [% biblio.title %], has correctly been renewed and is now due on [% checkout.date_due | $KohaDates as_due_date => 1 %]
14461 [% END %]", 'email');
14462     });
14463
14464     SetVersion( $DBversion );
14465     print "Upgrade to $DBversion done (Bug 15705 - Notify the user on auto renewing)\n";
14466 }
14467
14468 $DBversion = '16.12.00.036';
14469 if( CheckVersion( $DBversion ) ) {
14470     $dbh->do(q{
14471         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
14472         VALUES ('NumSavedReports', '20', NULL, 'By default, show this number of saved reports.', 'Integer');
14473     });
14474
14475     SetVersion( $DBversion );
14476     print "Upgrade to $DBversion done (Bug 17465 - Add a System Preference to control number of Saved Reports displayed)\n";
14477 }
14478
14479 $DBversion = '16.12.00.037';
14480 if( CheckVersion( $DBversion ) ) {
14481     $dbh->do( q|
14482         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
14483         VALUES ('FailedLoginAttempts','','','Number of login attempts before lockout the patron account','Integer');
14484     |);
14485
14486     unless( column_exists( 'borrowers', 'login_attempts' ) ) {
14487         $dbh->do(q|
14488             ALTER TABLE borrowers ADD COLUMN login_attempts INT(4) DEFAULT 0 AFTER lastseen
14489         |);
14490         $dbh->do(q|
14491             ALTER TABLE deletedborrowers ADD COLUMN login_attempts INT(4) DEFAULT 0 AFTER lastseen
14492         |);
14493     }
14494
14495     SetVersion( $DBversion );
14496     print "Upgrade to $DBversion done (Bug 18314 - Add FailedLoginAttempts and borrowers.login_attempts)\n";
14497 }
14498
14499 $DBversion = '16.12.00.038';
14500 if( CheckVersion( $DBversion ) ) {
14501     $dbh->do(q{
14502         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14503         ('ExportRemoveFields','',NULL,'List of fields for non export in circulation.pl (separated by a space)','Free');
14504     });
14505
14506     SetVersion( $DBversion );
14507     print "Upgrade to $DBversion done (Bug 18663 - Missing db update for ExportRemoveFields)\n";
14508 }
14509
14510 $DBversion = '16.12.00.039';
14511 if( CheckVersion( $DBversion ) ) {
14512     $dbh->do(q{
14513         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14514         ('TalkingTechItivaPhoneNotification','0',NULL,'If ON, enables Talking Tech I-tiva phone notifications','YesNo');
14515     });
14516
14517     SetVersion( $DBversion );
14518     print "Upgrade to $DBversion done (Bug 18600 - Missing db update for TalkingTechItivaPhoneNotification)\n";
14519 }
14520
14521 $DBversion = '17.05.00.000';
14522 if( CheckVersion( $DBversion ) ) {
14523
14524     SetVersion( $DBversion );
14525     print "Upgrade to $DBversion done (Koha 17.05)\n";
14526 }
14527
14528 $DBversion = '17.06.00.000';
14529 if( CheckVersion( $DBversion ) ) {
14530     SetVersion( $DBversion );
14531     print "Upgrade to $DBversion done (He pai ake te iti i te kore)\n";
14532 }
14533
14534 $DBversion = '17.06.00.001';
14535 if( CheckVersion( $DBversion ) ) {
14536
14537     unless ( column_exists( 'export_format', 'used_for' ) ) {
14538         $dbh->do(q|ALTER TABLE export_format ADD used_for varchar(255) DEFAULT 'export_records' AFTER type|);
14539
14540         $dbh->do(q|UPDATE export_format SET used_for = 'late_issues' WHERE type = 'sql'|);
14541         $dbh->do(q|UPDATE export_format SET used_for = 'export_records' WHERE type = 'marc'|);
14542     }
14543     SetVersion( $DBversion );
14544     print "Upgrade to $DBversion done (Bug 8612 - Add new column export_format.used_for)\n";
14545 }
14546
14547 $DBversion = '17.06.00.002';
14548 if ( CheckVersion($DBversion) ) {
14549
14550     unless ( column_exists('virtualshelves', 'allow_change_from_owner' ) ) {
14551         $dbh->do(q|
14552             ALTER TABLE virtualshelves
14553             ADD COLUMN allow_change_from_owner tinyint(1) default 1,
14554             ADD COLUMN allow_change_from_others tinyint(1) default 0
14555         |);
14556
14557         # Conversion:
14558         # Since we had no readonly lists, change_from_owner is set to true.
14559         # When adding or delete_other was granted, change_from_others is true.
14560         # Note: In my opinion the best choice; there is no exact match.
14561         $dbh->do(q|
14562             UPDATE virtualshelves
14563             SET allow_change_from_owner = 1,
14564                 allow_change_from_others = CASE WHEN allow_add=1 OR allow_delete_other=1 THEN 1 ELSE 0 END
14565         |);
14566
14567         # Remove the old columns
14568         $dbh->do(q|
14569             ALTER TABLE virtualshelves
14570             DROP COLUMN allow_add,
14571             DROP COLUMN allow_delete_own,
14572             DROP COLUMN allow_delete_other
14573         |);
14574     }
14575
14576     SetVersion($DBversion);
14577     print "Upgrade to $DBversion done (Bug 18228 - Alter table virtualshelves to simplify permissions)\n";
14578 }
14579
14580 $DBversion = '17.06.00.003';
14581 if ( CheckVersion($DBversion) ) {
14582
14583     # Fetch all auth types
14584     my $authtypes = $dbh->selectcol_arrayref(q|SELECT authtypecode FROM auth_types|);
14585
14586     if ( grep { $_ eq 'Default' } @$authtypes ) {
14587
14588         # If this exists as an authtypecode, we don't do anything
14589     }
14590     else {
14591         # Replace the incorrect Default by empty string
14592         $dbh->do(q|
14593             UPDATE auth_header SET authtypecode='' WHERE authtypecode='Default'
14594         |);
14595     }
14596
14597     SetVersion($DBversion);
14598     print "Upgrade to $DBversion done (Bug 18801 - Update incorrect Default auth type codes)\n";
14599 }
14600
14601 $DBversion = '17.06.00.004';
14602 if( CheckVersion( $DBversion ) ) {
14603     $dbh->do(q{
14604         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14605         ('GoogleOpenIDConnectAutoRegister',   '0',NULL,' Google OpenID Connect logins to auto-register patrons.','YesNo'),
14606         ('GoogleOpenIDConnectDefaultCategory','','','This category code will be used to create Google OpenID Connect patrons.','Textarea'),
14607         ('GoogleOpenIDConnectDefaultBranch',  '','','This branch code will be used to create Google OpenID Connect patrons.','Textarea');
14608     });
14609
14610     SetVersion( $DBversion );
14611     print "Upgrade to $DBversion done (Bug 16892: Add automatic patron registration via OAuth2 login)\n";
14612 }
14613
14614 $DBversion = '17.06.00.005';
14615 if( CheckVersion( $DBversion ) ) {
14616     $dbh->do(q{
14617         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')
14618         });
14619
14620     SetVersion( $DBversion );
14621     print "Upgrade to $DBversion done (Bug 18718 - Language selector in staff header menu similar to OPAC )\n";
14622 }
14623
14624 $DBversion = '17.06.00.006';
14625 if( CheckVersion( $DBversion ) ) {
14626     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.};
14627     print "\n";
14628
14629     SetVersion( $DBversion );
14630     print "Upgrade to $DBversion done (Bug 18811 - Visibility settings inconsistent between framework and authority editor)\n";
14631 }
14632
14633 $DBversion = '17.06.00.007';
14634 if( CheckVersion( $DBversion ) ) {
14635     if( !column_exists( 'branches', 'marcorgcode' ) ) {
14636         $dbh->do( "ALTER TABLE branches ADD COLUMN marcorgcode VARCHAR(16) default NULL AFTER geolocation" );
14637     }
14638
14639     SetVersion( $DBversion );
14640     print "Upgrade to $DBversion done (Bug 10132 - MARCOrgCode on branch level (branches.marcorgcode))\n";
14641 }
14642
14643 $DBversion = '17.06.00.008';
14644 if( CheckVersion( $DBversion ) ) {
14645     unless ( column_exists( 'borrowers', 'date_renewed' ) ) {
14646         $dbh->do(q{
14647             ALTER TABLE borrowers ADD COLUMN date_renewed DATE NULL DEFAULT NULL AFTER dateexpiry;
14648         });
14649     }
14650
14651     unless ( column_exists( 'deletedborrowers', 'date_renewed' ) ) {
14652         $dbh->do(q{
14653             ALTER TABLE deletedborrowers ADD COLUMN date_renewed DATE NULL DEFAULT NULL AFTER dateexpiry;
14654         });
14655     }
14656
14657     unless ( column_exists( 'borrower_modifications', 'date_renewed' ) ) {
14658         $dbh->do(q{
14659             ALTER TABLE borrower_modifications ADD COLUMN date_renewed DATE NULL DEFAULT NULL AFTER dateexpiry;
14660         });
14661     }
14662
14663     SetVersion( $DBversion );
14664     print "Upgrade to $DBversion done (Bug 6758 - Capture membership renewal date for reporting purposes (borrowers.date_renewed))\n";
14665 }
14666
14667 $DBversion = '17.06.00.009';
14668 if( CheckVersion( $DBversion ) ) {
14669     $dbh->do(q{
14670         ALTER TABLE borrowers MODIFY COLUMN login_attempts int(4) DEFAULT 0 AFTER lang;
14671     });
14672     $dbh->do(q{
14673         ALTER TABLE deletedborrowers MODIFY COLUMN login_attempts int(4) DEFAULT 0 AFTER lang;
14674     });
14675
14676     SetVersion( $DBversion );
14677     print "Upgrade to $DBversion done (Bug 19344 -  Reorder lang and login_attempts in the [deleted]borrowers tables)\n";
14678 }
14679
14680 $DBversion = '17.06.00.010';
14681 if ( CheckVersion($DBversion) ) {
14682     $dbh->do(q{
14683         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
14684         VALUES (
14685             'DefaultCountryField008','','',
14686             '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')
14687     });
14688     SetVersion($DBversion);
14689     print "Upgrade to $DBversion done (Bug 13912 - System preference for default place of publication (country code) for field 008, range 15-17)\n";
14690 }
14691
14692 $DBversion = '17.06.00.011';
14693 if ( CheckVersion($DBversion) ) {
14694     # Drop index that might exist because of bug 5337
14695     if( index_exists('biblioitems', 'ean')) {
14696         $dbh->do(q{ ALTER TABLE biblioitems DROP INDEX ean });
14697     }
14698     if( index_exists('deletedbiblioitems', 'ean')) {
14699         $dbh->do(q{ ALTER TABLE deletedbiblioitems DROP INDEX ean });
14700     }
14701
14702     # Change data type of column
14703     $dbh->do(q{ ALTER TABLE biblioitems MODIFY COLUMN ean MEDIUMTEXT default NULL });
14704     $dbh->do(q{ ALTER TABLE deletedbiblioitems MODIFY COLUMN ean MEDIUMTEXT default NULL });
14705
14706     # Add indexes
14707     $dbh->do(q{ ALTER TABLE biblioitems ADD INDEX ean ( ean(255) )});
14708     $dbh->do(q{ ALTER TABLE deletedbiblioitems ADD INDEX ean ( ean(255 ) )});
14709
14710     SetVersion($DBversion);
14711     print "Upgrade to $DBversion done (Bug 13766 - Make ean mediumtext and add ean indexes)\n";
14712 }
14713
14714 $DBversion = '17.06.00.012';
14715 if( CheckVersion( $DBversion ) ) {
14716     my $where = q|host='clio-db.cc.columbia.edu' AND port=7090|;
14717     my $sql = "SELECT COUNT(*) FROM z3950servers WHERE $where";
14718     my ( $cnt ) = $dbh->selectrow_array( $sql );
14719     if( $cnt ) {
14720         $dbh->do( "DELETE FROM z3950servers WHERE $where" );
14721         print "Removed $cnt Z39.50 target(s) for Columbia University\n";
14722     }
14723
14724     SetVersion( $DBversion );
14725     print "Upgrade to $DBversion done (Bug 19043 - Z39.50 target for Columbia University is no longer publicly available.)\n";
14726 }
14727
14728 $DBversion = '17.06.00.013';
14729 if( CheckVersion( $DBversion ) ) {
14730     $dbh->do( "UPDATE systempreferences SET value = CONCAT('http://', value) WHERE variable = 'staffClientBaseURL' AND value <> '' AND value NOT LIKE 'http%'" );
14731
14732     my ( $staffClientBaseURL_used_in_notices ) = $dbh->selectrow_array(q|
14733         SELECT COUNT(*) FROM letter where content like "%staffClientBaseURL%"
14734     |);
14735     if ( $staffClientBaseURL_used_in_notices ) {
14736         warn "\tYou may need to update one or more notice templates if they contain 'staffClientBaseURL'\n";
14737     }
14738
14739     SetVersion( $DBversion );
14740     print "Upgrade to $DBversion done (Bug 16401 - fix potentialy bad set staffClientBaseURL preference)\n";
14741 }
14742
14743 $DBversion = '17.06.00.014';
14744 if( CheckVersion( $DBversion ) ) {
14745     unless( column_exists('aqbasket','create_items') ){
14746         $dbh->do(q{
14747             ALTER TABLE aqbasket
14748                 ADD COLUMN create_items ENUM('ordering', 'receiving', 'cataloguing') default NULL AFTER is_standing
14749         });
14750     }
14751
14752     SetVersion( $DBversion );
14753     print "Upgrade to $DBversion done (Bug 15685 - Allow creation of items (AcqCreateItem) to be customizable per-basket)\n";
14754 }
14755
14756 $DBversion = '17.06.00.015';
14757 if( CheckVersion( $DBversion ) ) {
14758     $dbh->do(q{
14759         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES
14760         ('SelfCheckoutByLogin','0',NULL,'Have patrons login into the web-based self checkout system with their username/password or their cardnumber','YesNo')
14761     });
14762
14763     SetVersion( $DBversion );
14764     print "Upgrade to $DBversion done (Bug 19186 - Insert system preference SelfCheckoutByLogin if missing)\n";
14765 }
14766
14767 $DBversion = '17.06.00.016';
14768 if( CheckVersion( $DBversion ) ) {
14769     $dbh->do(q{
14770         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
14771         VALUES ('RequireStrongPassword','0','','Require a strong login password for staff and patrons','YesNo');
14772     });
14773
14774     SetVersion( $DBversion );
14775     print "Upgrade to $DBversion done (Bug 18298 - Allow enforcing password complexity (system preference RequireStrongPassword))\n";
14776 }
14777
14778 $DBversion = '17.06.00.017';
14779 if( CheckVersion( $DBversion ) ) {
14780     unless (TableExists('account_offsets')) {
14781         $dbh->do(q{
14782             DROP TABLE IF EXISTS `accountoffsets`;
14783         });
14784
14785         $dbh->do(q{
14786             CREATE TABLE IF NOT EXISTS `account_offset_types` (
14787               `type` varchar(16) NOT NULL, -- The type of offset this is
14788               PRIMARY KEY (`type`)
14789             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14790         });
14791
14792         $dbh->do(q{
14793             CREATE TABLE IF NOT EXISTS `account_offsets` (
14794               `id` int(11) NOT NULL auto_increment, -- unique identifier for each offset
14795               `credit_id` int(11) NULL DEFAULT NULL, -- The id of the accountline the increased the patron's balance
14796               `debit_id` int(11) NULL DEFAULT NULL, -- The id of the accountline that decreased the patron's balance
14797               `type` varchar(16) NOT NULL, -- The type of offset this is
14798               `amount` decimal(26,6) NOT NULL, -- The amount of the change
14799               `created_on` timestamp NOT NULL default CURRENT_TIMESTAMP,
14800               PRIMARY KEY (`id`),
14801               CONSTRAINT `account_offsets_ibfk_p` FOREIGN KEY (`credit_id`) REFERENCES `accountlines` (`accountlines_id`) ON DELETE CASCADE ON UPDATE CASCADE,
14802               CONSTRAINT `account_offsets_ibfk_f` FOREIGN KEY (`debit_id`) REFERENCES `accountlines` (`accountlines_id`) ON DELETE CASCADE ON UPDATE CASCADE,
14803               CONSTRAINT `account_offsets_ibfk_t` FOREIGN KEY (`type`) REFERENCES `account_offset_types` (`type`) ON DELETE CASCADE ON UPDATE CASCADE
14804             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14805         });
14806
14807         $dbh->do(q{
14808             INSERT IGNORE INTO account_offset_types ( type ) VALUES
14809             ('Writeoff'),
14810             ('Payment'),
14811             ('Lost Item'),
14812             ('Processing Fee'),
14813             ('Manual Debit'),
14814             ('Reverse Payment'),
14815             ('Forgiven'),
14816             ('Dropbox'),
14817             ('Rental Fee'),
14818             ('Fine Update'),
14819             ('Fine');
14820         });
14821     }
14822
14823     SetVersion( $DBversion );
14824     print "Upgrade to $DBversion done (Bug 14826 - Resurrect account offsets table (Add new tables account_offsets and account_offset_types))\n";
14825 }
14826
14827 $DBversion = '17.06.00.018';
14828 if( CheckVersion( $DBversion ) ) {
14829     $dbh->do(q{
14830         INSERT IGNORE INTO systempreferences (variable,value,explanation,type) VALUES ('useDefaultReplacementCost',0,'default replacement cost defined in item type','YesNo');
14831     });
14832     $dbh->do(q{
14833         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');
14834     });
14835     $dbh->do(q{
14836         ALTER TABLE `itemtypes` MODIFY COLUMN `rentalcharge` DECIMAL(28,6) NULL DEFAULT NULL;
14837     });
14838     unless ( column_exists( 'itemtypes', 'defaultreplacecost' ) ) {
14839         $dbh->do(q{
14840             ALTER TABLE `itemtypes` ADD `defaultreplacecost` DECIMAL(28,6) NULL DEFAULT NULL AFTER `rentalcharge`;
14841         });
14842     }
14843     unless ( column_exists( 'itemtypes', 'processfee' ) ) {
14844         $dbh->do(q{
14845             ALTER TABLE `itemtypes` ADD `processfee` DECIMAL(28,6) NULL DEFAULT NULL AFTER `defaultreplacecost`;
14846         });
14847
14848     }
14849     SetVersion( $DBversion );
14850     print "Upgrade to $DBversion done (Bug 12768 - Insert system preferences useDefaultReplacementCost and ProcessingFeeNote + Add new columns defaultreplacecost and processfee to the itemtypes table)\n";
14851 }
14852
14853 $DBversion = '17.06.00.019';
14854 if( CheckVersion( $DBversion ) ) {
14855     $dbh->do(q{
14856         INSERT IGNORE INTO account_offset_types ( type ) VALUES ( 'Processing Fee' );
14857     });
14858
14859     SetVersion( $DBversion );
14860     print "Upgrade to $DBversion done (Bug 12768 - Add 'Processing Fee' to the account_offset_types table if missing)\n";
14861 }
14862
14863 $DBversion = '17.06.00.020';
14864 if( CheckVersion( $DBversion ) ) {
14865     $dbh->do(q{
14866         UPDATE systempreferences
14867         SET
14868             variable='OpacLocationOnDetail',
14869             options='holding|home|both|column',
14870             explanation='In the OPAC detail, display the shelving location on its own column or under a library columns.'
14871         WHERE
14872             variable='OpacLocationBranchToDisplayShelving'
14873     });
14874
14875     SetVersion( $DBversion );
14876     print "Upgrade to $DBversion done (Bug 19028: Add 'shelving location' to holdings table in detail page (Rename syspref OpacLocationBranchToDisplayShelving with OpacLocationOnDetail))\n";
14877 }
14878
14879 $DBversion = '17.06.00.021';
14880 if( CheckVersion( $DBversion ) ) {
14881     $dbh->do(q{
14882         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')
14883     });
14884
14885     SetVersion( $DBversion );
14886     print "Upgrade to $DBversion done (Bug 17381 - Add system preference SCOMainUserBlock)\n";
14887 }
14888
14889 $DBversion = '17.06.00.022';
14890 if( CheckVersion( $DBversion ) ) {
14891     my $hide_barcode = C4::Context->preference('OPACShowBarcode') ? 0 : 1;
14892     $dbh->do(q{
14893         DELETE FROM systempreferences
14894         WHERE
14895             variable='OPACShowBarcode'
14896     });
14897
14898     # Configure column visibility if it isn't
14899     $dbh->do(q{
14900         INSERT IGNORE INTO columns_settings
14901             (module,page,tablename,columnname,cannot_be_toggled,is_hidden)
14902         VALUES
14903             ('opac','biblio-detail','holdingst','item_barcode',0,?)
14904     }, undef, $hide_barcode);
14905
14906     SetVersion( $DBversion );
14907     print "Upgrade to $DBversion done (Bug 19038: Remove OPACShowBarcode syspref)\n";
14908 }
14909
14910 $DBversion = '17.06.00.023';
14911 if( CheckVersion( $DBversion ) ) {
14912     $dbh->do(q{
14913         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14914         ('MarkLostItemsAsReturned','1','','Mark items as returned when flagged as lost','YesNo');
14915     });
14916
14917     SetVersion( $DBversion );
14918     print "Upgrade to $DBversion done (Bug 12363 - Add system preference MarkLostItemsAsReturned)\n";
14919 }
14920
14921 $DBversion = '17.06.00.024';
14922 if( CheckVersion( $DBversion ) ) {
14923     $dbh->do(q{
14924         INSERT IGNORE INTO systempreferences (`variable`,`value`,`options`,`explanation`,`type`) VALUES
14925         ('OPACUserSummary', 1, NULL, "Show the summary of a logged in user's checkouts, overdues, holds and fines on the mainpage", 'YesNo');
14926     });
14927
14928     SetVersion( $DBversion );
14929     print "Upgrade to $DBversion done (Bug 2093 - Add system preference OPACUserSummary)\n";
14930 }
14931
14932 $DBversion = '17.06.00.025';
14933 if( CheckVersion( $DBversion ) ) {
14934     $dbh->do(q{
14935         ALTER TABLE borrowers MODIFY cardnumber varchar(32);
14936     });
14937     $dbh->do(q{
14938         ALTER TABLE borrower_modifications MODIFY cardnumber varchar(32);
14939     });
14940     $dbh->do(q{
14941         ALTER TABLE deletedborrowers MODIFY cardnumber varchar(32);
14942     });
14943     $dbh->do(q{
14944         ALTER TABLE pending_offline_operations MODIFY cardnumber varchar(32);
14945     });
14946     $dbh->do(q{
14947         ALTER TABLE tmp_holdsqueue MODIFY cardnumber varchar(32);
14948     });
14949
14950     SetVersion( $DBversion );
14951     print "Upgrade to $DBversion done (Bug 13178 - Increase cardnumber fields to VARCHAR(32))\n";
14952 }
14953
14954 $DBversion = '17.06.00.026';
14955 if( CheckVersion( $DBversion ) ) {
14956     $dbh->do(q{
14957         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14958         ('BlockReturnOfLostItems','0','0','If enabled, items that are marked as lost cannot be returned.','YesNo');
14959     });
14960
14961     SetVersion( $DBversion );
14962     print "Upgrade to $DBversion done (Bug 10748 - Add system preference BlockReturnOfLostItems)\n";
14963 }
14964
14965 $DBversion = '17.06.00.027';
14966 if( CheckVersion( $DBversion ) ) {
14967     if ( !column_exists( 'statistics', 'location' ) ) {
14968         $dbh->do('ALTER TABLE statistics ADD COLUMN location VARCHAR(80) default NULL AFTER itemtype');
14969     }
14970
14971     SetVersion($DBversion);
14972     print "Upgrade to $DBversion done (Bug 18882 - Add location code to statistics table for checkouts and renewals)\n";
14973 }
14974
14975 $DBversion = '17.06.00.028';
14976 if( CheckVersion( $DBversion ) ) {
14977     if ( !TableExists( 'illrequests' ) ) {
14978         $dbh->do(q{
14979             CREATE TABLE illrequests (
14980                illrequest_id serial PRIMARY KEY,           -- ILL request number
14981                borrowernumber integer DEFAULT NULL,        -- Patron associated with request
14982                biblio_id integer DEFAULT NULL,             -- Potential bib linked to request
14983                branchcode varchar(50) NOT NULL,            -- The branch associated with the request
14984                status varchar(50) DEFAULT NULL,            -- Current Koha status of request
14985                placed date DEFAULT NULL,                   -- Date the request was placed
14986                replied date DEFAULT NULL,                  -- Last API response
14987                updated timestamp DEFAULT CURRENT_TIMESTAMP -- Last modification to request
14988                  ON UPDATE CURRENT_TIMESTAMP,
14989                completed date DEFAULT NULL,                -- Date the request was completed
14990                medium varchar(30) DEFAULT NULL,            -- The Koha request type
14991                accessurl varchar(500) DEFAULT NULL,        -- Potential URL for accessing item
14992                cost varchar(20) DEFAULT NULL,              -- Cost of request
14993                notesopac text DEFAULT NULL,                -- Patron notes attached to request
14994                notesstaff text DEFAULT NULL,               -- Staff notes attached to request
14995                orderid varchar(50) DEFAULT NULL,           -- Backend id attached to request
14996                backend varchar(20) DEFAULT NULL,           -- The backend used to create request
14997                CONSTRAINT `illrequests_bnfk`
14998                  FOREIGN KEY (`borrowernumber`)
14999                  REFERENCES `borrowers` (`borrowernumber`)
15000                  ON UPDATE CASCADE ON DELETE CASCADE,
15001                CONSTRAINT `illrequests_bcfk_2`
15002                  FOREIGN KEY (`branchcode`)
15003                  REFERENCES `branches` (`branchcode`)
15004                  ON UPDATE CASCADE ON DELETE CASCADE
15005            ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
15006         });
15007     }
15008
15009     if ( !TableExists( 'illrequestattributes' ) ) {
15010         $dbh->do(q{
15011             CREATE TABLE illrequestattributes (
15012                 illrequest_id bigint(20) unsigned NOT NULL, -- ILL request number
15013                 type varchar(200) NOT NULL,                 -- API ILL property name
15014                 value text NOT NULL,                        -- API ILL property value
15015                 PRIMARY KEY  (`illrequest_id`,`type`),
15016                 CONSTRAINT `illrequestattributes_ifk`
15017                   FOREIGN KEY (illrequest_id)
15018                   REFERENCES `illrequests` (`illrequest_id`)
15019                   ON UPDATE CASCADE ON DELETE CASCADE
15020             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
15021         });
15022     }
15023
15024     # System preferences
15025     $dbh->do(q{
15026         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
15027             ('ILLModule','0','If ON, enables the interlibrary loans module.','','YesNo');
15028     });
15029
15030     $dbh->do(q{
15031         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
15032             ('ILLModuleCopyrightClearance','','70|10','Enter text to enable the copyright clearance stage of request creation. Text will be displayed','Textarea');
15033     });
15034     # userflags
15035     $dbh->do(q{
15036         INSERT IGNORE INTO userflags (bit,flag,flagdesc,defaulton) VALUES
15037             (22,'ill','The Interlibrary Loans Module',0);
15038     });
15039
15040     SetVersion( $DBversion );
15041     print "Upgrade to $DBversion done (Bug 7317 - Add an Interlibrary Loan Module to Circulation and OPAC)\n";
15042 }
15043
15044 $DBversion = '17.11.00.000';
15045 if( CheckVersion( $DBversion ) ) {
15046     SetVersion( $DBversion );
15047     print "Upgrade to $DBversion done (Koha 17.11)\n";
15048 }
15049
15050 $DBversion = '17.12.00.000';
15051 if( CheckVersion( $DBversion ) ) {
15052     SetVersion( $DBversion );
15053     print "Upgrade to $DBversion done (Tē tōia, tē haumatia)\n";
15054 }
15055
15056 $DBversion = '17.12.00.001';
15057 if( CheckVersion( $DBversion ) ) {
15058     foreach my $table (qw(biblio_metadata deletedbiblio_metadata)) {
15059         if (!column_exists($table, 'timestamp')) {
15060             $dbh->do(qq{
15061                 ALTER TABLE `$table`
15062                 ADD COLUMN `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER `metadata`,
15063                 ADD KEY `timestamp` (`timestamp`)
15064             });
15065             $dbh->do(qq{
15066                 UPDATE $table metadata
15067                     LEFT JOIN biblioitems ON (biblioitems.biblionumber = metadata.biblionumber)
15068                     LEFT JOIN biblio ON (biblio.biblionumber = metadata.biblionumber)
15069                 SET metadata.timestamp = GREATEST(biblioitems.timestamp, biblio.timestamp);
15070             });
15071         }
15072     }
15073
15074     SetVersion( $DBversion );
15075     print "Upgrade to $DBversion done (Bug 19724 - Add [deleted]biblio_metadata.timestamp)\n";
15076 }
15077
15078 $DBversion = '17.12.00.002';
15079 if( CheckVersion( $DBversion ) ) {
15080
15081     my $msss = $dbh->selectall_arrayref(q|
15082         SELECT kohafield, tagfield, tagsubfield, frameworkcode
15083         FROM marc_subfield_structure
15084         WHERE   frameworkcode != ''
15085     |, { Slice => {} });
15086
15087
15088     my $sth = $dbh->prepare(q|
15089         SELECT kohafield
15090         FROM marc_subfield_structure
15091         WHERE frameworkcode = ''
15092         AND tagfield = ?
15093         AND tagsubfield = ?
15094     |);
15095
15096     my @exceptions;
15097     for my $mss ( @$msss ) {
15098         $sth->execute($mss->{tagfield}, $mss->{tagsubfield} );
15099         my ( $default_kohafield ) = $sth->fetchrow_array();
15100         if( $mss->{kohafield} ) {
15101             push @exceptions, { frameworkcode => $mss->{frameworkcode}, tagfield => $mss->{tagfield}, tagsubfield => $mss->{tagsubfield}, kohafield => $mss->{kohafield} } if not $default_kohafield or $default_kohafield ne $mss->{kohafield};
15102         } else {
15103             push @exceptions, { frameworkcode => $mss->{frameworkcode}, tagfield => $mss->{tagfield}, tagsubfield => $mss->{tagsubfield}, kohafield => q{} } if $default_kohafield;
15104         }
15105     }
15106
15107     if (@exceptions) {
15108         print "WARNING: The Default framework is now considered as authoritative for Koha to MARC mappings. We have found that your additional frameworks contained "
15109           . scalar(@exceptions)
15110           . " 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";
15111         for my $exception (@exceptions) {
15112             print "Field "
15113               . $exception->{tagfield} . '$'
15114               . $exception->{tagsubfield}
15115               . " in framework "
15116               . $exception->{frameworkcode} . ': ';
15117             if ( $exception->{kohafield} ) {
15118                 print "Mapping to "
15119                   . $exception->{kohafield}
15120                   . " has been adjusted.\n";
15121             }
15122             else {
15123                 print "Mapping has been reset.\n";
15124             }
15125         }
15126
15127         # Sync kohafield
15128
15129         # Clear the destination frameworks first
15130         $dbh->do(q|
15131             UPDATE marc_subfield_structure
15132             SET kohafield = NULL
15133             WHERE   frameworkcode > ''
15134                 AND     Kohafield > ''
15135         |);
15136
15137         # Now copy from Default
15138         my $msss = $dbh->selectall_arrayref(q|
15139             SELECT kohafield, tagfield, tagsubfield
15140             FROM marc_subfield_structure
15141             WHERE   frameworkcode = ''
15142                 AND     kohafield > ''
15143         |, { Slice => {} });
15144         my $sth = $dbh->prepare(q|
15145             UPDATE marc_subfield_structure
15146             SET kohafield = ?
15147             WHERE frameworkcode > ''
15148             AND tagfield = ?
15149             AND tagsubfield = ?
15150         |);
15151         for my $mss (@$msss) {
15152             $sth->execute( $mss->{kohafield}, $mss->{tagfield},
15153                 $mss->{tagsubfield} );
15154         }
15155
15156         # Clear the cache
15157         my @frameworkcodes = $dbh->selectall_arrayref(q|
15158             SELECT frameworkcode FROM biblio_framework WHERE frameworkcode > ''
15159         |);
15160         for my $frameworkcode (@frameworkcodes) {
15161             Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
15162         }
15163     }
15164
15165     SetVersion( $DBversion );
15166     print "Upgrade to $DBversion done (Bug 19096 - Make Default authoritative for Koha to MARC mappings)\n";
15167 }
15168
15169 $DBversion = '17.12.00.003';
15170 if( CheckVersion( $DBversion ) ) {
15171     $dbh->do(q|DROP TABLE IF EXISTS notifys|);
15172
15173     if( column_exists( 'accountlines', 'notify_id' ) ) {
15174         $dbh->do(q|ALTER TABLE accountlines DROP COLUMN notify_id|);
15175         $dbh->do(q|ALTER TABLE accountlines DROP COLUMN notify_level|);
15176     }
15177
15178     SetVersion( $DBversion );
15179     print "Upgrade to $DBversion done (Bug 10021 - Drop notifys-related table and columns)\n";
15180 }
15181
15182 $DBversion = '17.12.00.004';
15183 if( CheckVersion( $DBversion ) ) {
15184     $dbh->do(q{
15185         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
15186         VALUES
15187             ('RESTdefaultPageSize','20','','Set the default number of results returned by the REST API endpoints','Integer')
15188     });
15189
15190     SetVersion( $DBversion );
15191     print "Upgrade to $DBversion done (Bug 19278 - Add a configurable default page size for REST endpoints)\n";
15192 }
15193
15194 $DBversion = '17.12.00.005';
15195 if( CheckVersion( $DBversion ) ) {
15196     # For installations having the note already
15197     $dbh->do(q{
15198         UPDATE letter
15199         SET code    = 'CHECKOUT_NOTE',
15200             name    = 'Checkout note on item set by patron',
15201             title   = 'Checkout note',
15202             content = REPLACE(content, "<<biblio.item>>", "<<biblio.title>>")
15203         WHERE code = 'PATRON_NOTE'
15204     });
15205     # For installations coming from 17.11
15206     $dbh->do(q{
15207         INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`)
15208         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')
15209     });
15210
15211     SetVersion( $DBversion );
15212     print "Upgrade to $DBversion done (Bug 18915 - Correct CHECKOUT_NOTE notice template)\n";
15213 }
15214
15215 $DBversion = '17.12.00.006';
15216 if( CheckVersion( $DBversion ) ) {
15217     $dbh->do(q{
15218         UPDATE systempreferences SET value=replace(value, "http://www.scholar", "https://scholar") WHERE variable='OPACSearchForTitleIn';
15219     });
15220
15221     SetVersion( $DBversion );
15222     print "Upgrade to $DBversion done (Bug 17682 - Update URL for Google Scholar in OPACSearchForTitleIn)\n";
15223 }
15224
15225 $DBversion = '17.12.00.007';
15226 if( CheckVersion( $DBversion ) ) {
15227
15228     unless ( TableExists( 'library_groups' ) ) {
15229         $dbh->do(q{
15230             CREATE TABLE library_groups (
15231                 id INT(11) NOT NULL auto_increment,    -- unique id for each group
15232                 parent_id INT(11) NULL DEFAULT NULL,   -- if this is a child group, the id of the parent group
15233                 branchcode VARCHAR(10) NULL DEFAULT NULL, -- The branchcode of a branch belonging to the parent group
15234                 title VARCHAR(100) NULL DEFAULT NULL,     -- Short description of the goup
15235                 description TEXT NULL DEFAULT NULL,    -- Longer explanation of the group, if necessary
15236                 created_on TIMESTAMP NULL,             -- Date and time of creation
15237                 updated_on TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- Date and time of last
15238                 PRIMARY KEY id ( id ),
15239                 FOREIGN KEY (parent_id) REFERENCES library_groups(id) ON UPDATE CASCADE ON DELETE CASCADE,
15240                 FOREIGN KEY (branchcode) REFERENCES branches(branchcode) ON UPDATE CASCADE ON DELETE CASCADE,
15241                 UNIQUE KEY title ( title )
15242             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
15243         });
15244     }
15245
15246     SetVersion( $DBversion );
15247     print "Upgrade to $DBversion done (Bug 15707 - Add new table library_groups)\n";
15248 }
15249
15250 $DBversion = '17.12.00.008';
15251 if ( CheckVersion($DBversion) ) {
15252
15253     if ( TableExists( 'branchcategories' ) and TableExists('branchrelations' )) {
15254         $dbh->do(q{
15255             INSERT INTO library_groups ( title, description, created_on ) VALUES ( '__SEARCH_GROUPS__', 'Library search groups', NOW() )
15256         });
15257         my $search_groups_root_id = $dbh->last_insert_id(undef, undef, 'library_groups', undef);
15258
15259         my $sth = $dbh->prepare("SELECT * FROM branchcategories");
15260
15261         my $sth2 = $dbh->prepare("INSERT INTO library_groups ( parent_id, title, description, created_on ) VALUES ( ?, ?, ?, NOW() )");
15262
15263         my $sth3 = $dbh->prepare("SELECT * FROM branchrelations WHERE categorycode = ?");
15264
15265         my $sth4 = $dbh->prepare("INSERT INTO library_groups ( parent_id, branchcode, created_on ) VALUES ( ?, ?, NOW() )");
15266
15267         $sth->execute();
15268         while ( my $lc = $sth->fetchrow_hashref ) {
15269             my $description = $lc->{categorycode};
15270             $description .= " - " . $lc->{codedescription} if $lc->{codedescription};
15271
15272             $sth2->execute($search_groups_root_id, $lc->{categoryname}, $description);
15273
15274             my $subgroup_id = $dbh->last_insert_id(undef, undef, 'library_groups', undef);
15275
15276             $sth3->execute( $lc->{categorycode} );
15277
15278             while ( my $l = $sth3->fetchrow_hashref ) {
15279                 $sth4->execute( $subgroup_id, $l->{branchcode} );
15280             }
15281         }
15282
15283         $dbh->do("DROP TABLE branchrelations");
15284         $dbh->do("DROP TABLE branchcategories");
15285     }
15286
15287     print "Upgrade to $DBversion done (Bug 16735 - Migrate library search groups into the new hierarchical groups)\n";
15288     SetVersion($DBversion);
15289 }
15290
15291 $DBversion = '17.12.00.009';
15292 if ( CheckVersion($DBversion) ) {
15293     $dbh->do(q|
15294         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
15295         (4, 'edit_borrowers', 'Add, modify and view patron information'),
15296         (4, 'view_borrower_infos_from_any_libraries', 'View patron infos from any libraries');
15297     |);
15298
15299     # We are lucky here, there is nothing else to do: flags 4-borrowers did not contain sub permissions
15300
15301     SetVersion( $DBversion );
15302     print "Upgrade to $DBversion done (Bug 18403 - Add the view_borrower_infos_from_any_libraries permission )\n";
15303 }
15304
15305 $DBversion = '17.12.00.010';
15306 if( CheckVersion( $DBversion ) ) {
15307
15308     if( !column_exists( 'library_groups', 'ft_hide_patron_info' ) ) {
15309         $dbh->do( "ALTER TABLE library_groups ADD COLUMN ft_hide_patron_info tinyint(1) NOT NULL DEFAULT 0 AFTER description" );
15310     }
15311
15312     SetVersion( $DBversion );
15313     print "Upgrade to $DBversion done (Bug 20133 - Add library_groups.ft_hide_patron_info)\n";
15314 }
15315
15316 $DBversion = '17.12.00.011';
15317 if( CheckVersion( $DBversion ) ) {
15318
15319     if( !column_exists( 'library_groups', 'ft_search_groups_opac' ) ) {
15320         $dbh->do( "ALTER TABLE library_groups ADD COLUMN ft_search_groups_opac tinyint(1) NOT NULL DEFAULT 0 AFTER ft_hide_patron_info" );
15321         $dbh->do( "ALTER TABLE library_groups ADD COLUMN ft_search_groups_staff tinyint(1) NOT NULL DEFAULT 0 AFTER ft_search_groups_opac" );
15322         $dbh->do( "UPDATE library_groups SET ft_search_groups_staff = 1 AND ft_search_groups_opac = 1 WHERE title = '__SEARCH_GROUPS__'" );
15323     }
15324
15325     SetVersion( $DBversion );
15326     print "Upgrade to $DBversion done (Bug 20157 - Use group 'features' to decide which groups to use for group searching functionality)\n";
15327 }
15328
15329 $DBversion = '17.12.00.012';
15330 if( CheckVersion( $DBversion ) ) {
15331
15332     $dbh->do( q|
15333         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15334         VALUES ('AutoSwitchPatron', '0', '', 'Auto switch to patron', 'YesNo');
15335     |);
15336
15337     SetVersion( $DBversion );
15338     print "Upgrade to $DBversion done (Bug 15752 - Add system preference AutoSwitchPatron)\n";
15339 }
15340
15341 $DBversion = '17.12.00.013';
15342 if( CheckVersion( $DBversion ) ) {
15343
15344     $dbh->do(q|
15345         ALTER TABLE club_enrollments MODIFY date_created timestamp NULL DEFAULT NULL;
15346     |);
15347
15348     SetVersion( $DBversion );
15349     print "Upgrade to $DBversion done (Bug 20175 - Set DEFAULT NULL value for club_enrollments.date_created)\n";
15350 }
15351
15352 $DBversion = '17.12.00.014';
15353 if( CheckVersion( $DBversion ) ) {
15354     $dbh->do( "UPDATE marc_subfield_structure SET kohafield=NULL where kohafield='additionalauthors.author'" );
15355     SetVersion( $DBversion );
15356     print "Upgrade to $DBversion done (Bug 19790 - Remove additionalauthors.author from installer files)\n";
15357 }
15358
15359 $DBversion = '17.12.00.015';
15360 if( CheckVersion( $DBversion ) ) {
15361     $dbh->do(q|
15362         ALTER TABLE borrowers
15363         MODIFY surname MEDIUMTEXT,
15364         MODIFY address MEDIUMTEXT,
15365         MODIFY city MEDIUMTEXT
15366     |);
15367     $dbh->do(q|
15368         ALTER TABLE deletedborrowers
15369         MODIFY surname MEDIUMTEXT,
15370         MODIFY address MEDIUMTEXT,
15371         MODIFY city MEDIUMTEXT
15372     |);
15373
15374     $dbh->do(q|
15375         ALTER TABLE export_format
15376         MODIFY csv_separator VARCHAR(2) NOT NULL DEFAULT ',',
15377         MODIFY field_separator VARCHAR(2),
15378         MODIFY subfield_separator VARCHAR(2)
15379     |);
15380     $dbh->do(q|
15381         ALTER TABLE export_format MODIFY encoding VARCHAR(255) NOT NULL DEFAULT 'utf8'
15382     |);
15383
15384     $dbh->do(q|
15385         ALTER TABLE reserves MODIFY lowestPriority tinyint(1) NOT NULL DEFAULT 0
15386     |);
15387     $dbh->do(q|
15388         ALTER TABLE old_reserves MODIFY lowestPriority tinyint(1) NOT NULL DEFAULT 0
15389     |);
15390
15391     SetVersion( $DBversion );
15392     print "Upgrade to $DBversion done (Bug 20144 - Adapt DB structure to work with new SQL modes)\n";
15393 }
15394
15395 $DBversion = '17.12.00.016';
15396 if( CheckVersion( $DBversion ) ) {
15397     $dbh->do(q|SET foreign_key_checks = 0|);
15398     my $sth = $dbh->table_info( '','','','TABLE' );
15399
15400     while ( my ( $cat, $schema, $name, $type, $remarks ) = $sth->fetchrow_array ) {
15401         my $table_sth = $dbh->prepare(qq|SHOW CREATE TABLE $name|);
15402         $table_sth->execute;
15403         my @table = $table_sth->fetchrow_array;
15404         unless ( $table[1] =~ /COLLATE=utf8mb4_unicode_ci/ ) {
15405             # Some users might have done the upgrade to utf8mb4 on their own
15406             # to support supplemental chars (japanese, chinese, etc)
15407             if ( $name eq 'additional_fields' ) {
15408                 $dbh->do(qq|
15409                     ALTER TABLE $name
15410                         DROP KEY `fields_uniq`,
15411                         ADD UNIQUE KEY `fields_uniq` (`tablename` (191), `name` (191))
15412                 |);
15413                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15414             }
15415             elsif ( $name eq 'authorised_values' ) {
15416                 $dbh->do(qq|
15417                     ALTER TABLE $name
15418                         DROP KEY `lib`,
15419                         ADD KEY `lib` (`lib` (191))
15420                 |);
15421                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15422             }
15423             elsif ( $name eq 'borrower_modifications' ) {
15424                 $dbh->do(qq|
15425                     ALTER TABLE $name
15426                         DROP PRIMARY KEY,
15427                         DROP KEY `verification_token`,
15428                         ADD PRIMARY KEY (`verification_token` (191),`borrowernumber`),
15429                         ADD KEY `verification_token` (`verification_token` (191))
15430                 |);
15431                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15432             }
15433             elsif ( $name eq 'columns_settings' ) {
15434                 $dbh->do(qq|
15435                     ALTER TABLE $name
15436                         DROP PRIMARY KEY,
15437                         ADD PRIMARY KEY (`module` (191), `page` (191), `tablename` (191), `columnname` (191))
15438                 |);
15439                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15440             }
15441             elsif ( $name eq 'illrequestattributes' ) {
15442                 $dbh->do(qq|
15443                     ALTER TABLE $name
15444                         DROP PRIMARY KEY,
15445                         ADD PRIMARY KEY  (`illrequest_id`, `type` (191))
15446                 |);
15447                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15448             }
15449             elsif ( $name eq 'items_search_fields' ) {
15450                 $dbh->do(qq|
15451                     ALTER TABLE $name
15452                         DROP PRIMARY KEY,
15453                         ADD PRIMARY KEY (`name` (191))
15454                 |);
15455                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15456             }
15457             elsif ( $name eq 'marc_subfield_structure' ) {
15458                 # In this case we convert each column explicitly
15459                 # to preserve 'tagsubield' collation (utf8mb4_bin)
15460                 $dbh->do(qq|
15461                     ALTER TABLE $name
15462                         MODIFY COLUMN tagfield
15463                             VARCHAR(3) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
15464                         MODIFY COLUMN tagsubfield
15465                             VARCHAR(1) COLLATE utf8mb4_bin NOT NULL DEFAULT '',
15466                         MODIFY COLUMN liblibrarian
15467                             VARCHAR(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
15468                         MODIFY COLUMN libopac
15469                             VARCHAR(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
15470                         MODIFY COLUMN kohafield
15471                             VARCHAR(40) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15472                         MODIFY COLUMN authorised_value
15473                             VARCHAR(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15474                         MODIFY COLUMN authtypecode
15475                             VARCHAR(20) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15476                         MODIFY COLUMN value_builder
15477                             VARCHAR(80) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15478                         MODIFY COLUMN frameworkcode
15479                             VARCHAR(4) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
15480                         MODIFY COLUMN seealso
15481                             VARCHAR(1100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15482                         MODIFY COLUMN link
15483                             VARCHAR(80) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15484                         MODIFY COLUMN defaultvalue
15485                             MEDIUMTEXT COLLATE utf8mb4_unicode_ci default NULL
15486                 |);
15487                 $dbh->do(qq|ALTER TABLE $name CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15488             }
15489             elsif ( $name eq 'plugin_data' ) {
15490                 $dbh->do(qq|
15491                     ALTER TABLE $name
15492                         DROP PRIMARY KEY,
15493                         ADD PRIMARY KEY (`plugin_class` (191), `plugin_key` (191))
15494                 |);
15495                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15496             }
15497             elsif ( $name eq 'search_field' ) {
15498                 $dbh->do(qq|
15499                     ALTER TABLE $name
15500                         DROP KEY `name`,
15501                         ADD UNIQUE KEY `name` (`name` (191))
15502                 |);
15503                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15504             }
15505             elsif ( $name eq 'search_marc_map' ) {
15506                 $dbh->do(qq|
15507                     ALTER TABLE $name
15508                         DROP KEY `index_name`,
15509                         ADD UNIQUE KEY `index_name` (`index_name`, `marc_field` (191), `marc_type`)
15510                 |);
15511                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15512             }
15513             elsif ( $name eq 'sms_providers' ) {
15514                 $dbh->do(qq|
15515                     ALTER TABLE $name
15516                         DROP KEY `name`,
15517                         ADD UNIQUE KEY `name` (`name` (191))
15518                 |);
15519                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15520             }
15521             elsif ( $name eq 'tags' ) {
15522                 $dbh->do(qq|
15523                     ALTER TABLE $name
15524                         DROP PRIMARY KEY,
15525                         ADD PRIMARY KEY (`entry` (191))
15526                 |);
15527                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15528             }
15529             elsif ( $name eq 'tags_approval' ) {
15530                 $dbh->do(qq|
15531                     ALTER TABLE $name
15532                         MODIFY COLUMN `term` VARCHAR(191) NOT NULL
15533                 |);
15534                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15535             }
15536             elsif ( $name eq 'tags_index' ) {
15537                 $dbh->do(qq|
15538                     ALTER TABLE $name
15539                         MODIFY COLUMN `term` VARCHAR(191) NOT NULL
15540                 |);
15541                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15542             }
15543             else {
15544                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15545             }
15546         }
15547     }
15548     $dbh->do(q|SET foreign_key_checks = 1|);
15549
15550     print "Upgrade to $DBversion done (Bug 18336 - Convert DB tables to utf8mb4 🎁)\n";
15551     SetVersion($DBversion);
15552 }
15553
15554
15555 $DBversion = '17.12.00.017';
15556 if( CheckVersion( $DBversion ) ) {
15557
15558     if( !column_exists( 'items', 'damaged_on' ) ) {
15559         $dbh->do( "ALTER TABLE items ADD COLUMN damaged_on DATETIME NULL AFTER damaged");
15560     }
15561     if( !column_exists( 'deleteditems', 'damaged_on' ) ) {
15562         $dbh->do( "ALTER TABLE deleteditems ADD COLUMN damaged_on DATETIME NULL AFTER damaged");
15563     }
15564
15565     SetVersion( $DBversion );
15566     print "Upgrade to $DBversion done (Bug 17672 - Add damaged_on to items and deleteditems tables)\n";
15567 }
15568
15569 $DBversion = '17.12.00.018';
15570 if( CheckVersion( $DBversion ) ) {
15571
15572     $dbh->do( q|
15573         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')
15574     |);
15575
15576     SetVersion( $DBversion );
15577     print "Upgrade to $DBversion done (Bug 19290 - Add system preference BrowseResultSelection)\n";
15578 }
15579
15580 $DBversion = '17.12.00.019';
15581 if( CheckVersion( $DBversion ) ) {
15582
15583     $dbh->do(q|UPDATE auth_subfield_structure SET hidden=1 WHERE hidden<>0|);
15584
15585     SetVersion( $DBversion );
15586     print "Upgrade to $DBversion done (Bug 20074 - Auth_subfield_structure changes hidden attribute)\n";
15587 }
15588
15589 $DBversion = '17.12.00.020';
15590 if( CheckVersion( $DBversion ) ) {
15591
15592     $dbh->do(q|
15593         INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)
15594         VALUES ('vi', 'language', 'de', 'Vietnamesisch')
15595     |);
15596
15597     $dbh->do(q|
15598         UPDATE language_descriptions SET description = 'Tiếng Việt'
15599         WHERE subtag = 'vi' and type = 'language' and lang = 'vi'
15600     |);
15601
15602     SetVersion( $DBversion );
15603     print "Upgrade to $DBversion done (Bug 20082 - Update descriptions of Vietnamese language)\n";
15604 }
15605
15606 $DBversion = '17.12.00.021';
15607 if( CheckVersion( $DBversion ) ) {
15608
15609     $dbh->do(q|
15610         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
15611         ('PurgeSuggestionsOlderThan', '', NULL, 'Default value for cronjob purge_suggestions.pl', 'Integer');
15612     |);
15613
15614     SetVersion( $DBversion );
15615     print "Upgrade to $DBversion done (Bug 13287 - Add system preference PurgeSuggestionsOlderThan)\n";
15616 }
15617
15618 $DBversion = '17.12.00.022';
15619 if( CheckVersion( $DBversion ) ) {
15620
15621     if( !column_exists( 'currency', 'p_sep_by_space' ) ) {
15622         $dbh->do(q|
15623             ALTER TABLE currency ADD COLUMN p_sep_by_space tinyint(1) default 0 after archived
15624         |);
15625     }
15626
15627     SetVersion( $DBversion );
15628     print "Upgrade to $DBversion done (Bug 4078 - Add column currency.p_sep_by_space)\n";
15629 }
15630
15631 $DBversion = '17.12.00.023';
15632 if( CheckVersion( $DBversion ) ) {
15633     $dbh->do(q{
15634         DELETE FROM systempreferences
15635         WHERE variable='checkdigit'
15636     });
15637
15638     SetVersion( $DBversion );
15639     print "Upgrade to $DBversion done (Bug 20264 - Remove system preference 'checkdigit')\n";
15640 }
15641
15642 $DBversion = '17.12.00.024';
15643 if( CheckVersion( $DBversion ) ) {
15644
15645     $dbh->do(q{
15646         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15647         VALUES ('SelfCheckInMainUserBlock', '', '70|10', 'Add a block of HTML that will display on the self check-in screen.', 'Textarea');
15648     });
15649
15650     $dbh->do(q{
15651         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15652         VALUES ('SelfCheckInModule', 0, NULL, 'Enable the standalone self-checkin module.', 'YesNo');
15653     });
15654
15655     $dbh->do(q{
15656         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15657         VALUES ('SelfCheckInModuleUserID', NULL, NULL, 'Patron ID (borrowernumber) to be allowed on the self-checkin module.', 'Integer');
15658     });
15659
15660     $dbh->do(q{
15661         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15662         VALUES ('SelfCheckInTimeout', 120, NULL, 'Define the number of seconds before the self check-in module times out.', 'Integer');
15663     });
15664
15665     $dbh->do(q{
15666         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15667         VALUES ('SelfCheckInUserCSS', '', NULL, 'Add CSS to be included in the self check-in module in an embedded <style> tag.', 'free');
15668     });
15669
15670     $dbh->do(q{
15671         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15672         VALUES ('SelfCheckInUserJS', '', NULL, 'Define custom javascript for inclusion in the self check-in module.', 'free');
15673     });
15674
15675     # Add new userflag for self check
15676     $dbh->do(q{
15677         INSERT IGNORE INTO userflags (bit,flag,flagdesc,defaulton) VALUES
15678             (23,'self_check','Self check modules',0);
15679     });
15680
15681     # Add self check-in module subpermission
15682     $dbh->do(q{
15683         INSERT IGNORE INTO permissions (module_bit,code,description)
15684         VALUES (23, 'self_checkin_module', 'Log into the self check-in module');
15685     });
15686
15687     # Add self check-in module subpermission
15688     $dbh->do(q{
15689         INSERT IGNORE INTO permissions (module_bit,code,description)
15690         VALUES (23, 'self_checkout_module', 'Perform self checkout at the OPAC. It should be used for the patron matching the AutoSelfCheckID');
15691     });
15692
15693     # Update patrons with self_checkout permission
15694     # IMPORTANT: Needs to happen before removing the old subpermission
15695     $dbh->do(q{
15696         UPDATE user_permissions
15697         SET module_bit = 23,
15698                   code = 'self_checkout_module'
15699         WHERE module_bit = 1 AND code = 'self_checkout';
15700     });
15701
15702     # Remove old self_checkout permission
15703     $dbh->do(q{
15704         DELETE IGNORE FROM permissions
15705         WHERE  code='self_checkout';
15706     });
15707
15708     SetVersion( $DBversion );
15709     print "Upgrade to $DBversion done (Bug 15492 - Add a standalone self-checkin module)\n";
15710 }
15711
15712 $DBversion = '17.12.00.025';
15713 if( CheckVersion( $DBversion ) ) {
15714     $dbh->do(q|
15715         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
15716         VALUES ('StaffLoginInstructions','','HTML to go into the login box for the staff client',NULL,'Free')
15717     |);
15718     $dbh->do(q|
15719         UPDATE systempreferences
15720         SET variable = 'OpacLoginInstructions'
15721         WHERE variable = 'NoLoginInstructions'
15722     |);
15723
15724     SetVersion( $DBversion );
15725     print "Upgrade to $DBversion done (Bug 20291 - Add StaffLoginInstructions system preference and rename NoLoginInstructions with OpacLoginInstructions)\n";
15726 }
15727
15728 $DBversion = '17.12.00.026';
15729 if( CheckVersion( $DBversion ) ) {
15730     if( !column_exists( 'issuingrules', 'suspension_chargeperiod' ) ) {
15731         $dbh->do(q|
15732             ALTER TABLE issuingrules ADD COLUMN suspension_chargeperiod int(11) DEFAULT '1' AFTER maxsuspensiondays;
15733         |);
15734     }
15735
15736     SetVersion( $DBversion );
15737     print "Upgrade to $DBversion done (Bug 19804 - Add issuingrules.suspension_chargeperiod)\n";
15738 }
15739
15740 $DBversion = '17.12.00.027';
15741 if( CheckVersion( $DBversion ) ) {
15742     $dbh->do(q|
15743         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
15744         VALUES ('UseACQFrameworkForBiblioRecords','0','','Use the ACQ framework for the catalog details','YesNo')
15745     |);
15746
15747     SetVersion( $DBversion );
15748     print "Upgrade to $DBversion done (Bug 19289 - Add system preference UseACQFrameworkForBiblioRecords)\n";
15749 }
15750
15751 $DBversion = '17.12.00.028';
15752 if( CheckVersion( $DBversion ) ) {
15753     if( !column_exists( 'marc_tag_structure', 'ind1_defaultvalue' ) ) {
15754         $dbh->do(q|
15755             ALTER TABLE marc_tag_structure
15756             ADD COLUMN ind2_defaultvalue VARCHAR(1) NOT NULL DEFAULT '' AFTER authorised_value,
15757             ADD COLUMN ind1_defaultvalue VARCHAR(1) NOT NULL DEFAULT '' AFTER authorised_value;
15758         |);
15759     }
15760
15761     SetVersion( $DBversion );
15762     print "Upgrade to $DBversion done (Bug 9701 - Add default indicators (marc_tag_structure.indX_defaultvalue))\n";
15763 }
15764
15765 $DBversion = '17.12.00.029';
15766 if( CheckVersion( $DBversion ) ) {
15767     my $pref =
15768 q|# PERSO_NAME  100 600 696 700 796 800 896
15769 marc21, 100, ind1:auth1
15770 marc21, 600, ind1:auth1, ind2:thesaurus
15771 marc21, 696, ind1:auth1
15772 marc21, 700, ind1:auth1
15773 marc21, 796, ind1:auth1
15774 marc21, 800, ind1:auth1
15775 marc21, 896, ind1:auth1
15776 # CORPO_NAME  110 610 697 710 797 810 897
15777 marc21, 110, ind1:auth1
15778 marc21, 610, ind1:auth1, ind2:thesaurus
15779 marc21, 697, ind1:auth1
15780 marc21, 710, ind1:auth1
15781 marc21, 797, ind1:auth1
15782 marc21, 810, ind1:auth1
15783 marc21, 897, ind1:auth1
15784 # MEETI_NAME    111 611 698 711 798 811 898
15785 marc21, 111, ind1:auth1
15786 marc21, 611, ind1:auth1, ind2:thesaurus
15787 marc21, 698, ind1:auth1
15788 marc21, 711, ind1:auth1
15789 marc21, 798, ind1:auth1
15790 marc21, 811, ind1:auth1
15791 marc21, 898, ind1:auth1
15792 # UNIF_TITLE        130 440 630 699 730 799 830 899 / 240
15793 marc21, 130, ind1:auth2
15794 marc21, 240, , ind2:auth2
15795 marc21, 440, , ind2:auth2
15796 marc21, 630, ind1:auth2, ind2:thesaurus
15797 marc21, 699, ind1:auth2
15798 marc21, 730, ind1:auth2
15799 marc21, 799, ind1:auth2
15800 marc21, 830, , ind2:auth2
15801 marc21, 899, ind1:auth2
15802 # CHRON_TERM    648
15803 marc21, 648, , ind2:thesaurus
15804 # TOPIC_TERM      650 654 656 657 658 690
15805 marc21, 650, , ind2:thesaurus
15806 # GEOGR_NAME   651 662 691 / 751
15807 marc21, 651, , ind2:thesaurus
15808 # GENRE/FORM    655
15809 marc21, 655, , ind2:thesaurus
15810
15811 # UNIMARC: Always copy the indicators from the authority
15812 unimarc, *, ind1:auth1, ind2:auth2|;
15813
15814     $dbh->do( q|
15815         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
15816         VALUES ( 'AuthorityControlledIndicators', ?, 'Authority controlled indicators per biblio field', NULL, 'Free' );
15817     |, undef, $pref );
15818
15819     SetVersion( $DBversion );
15820     print "Upgrade to $DBversion done (Bug 14769 - Authorities merge: Set correct indicators in biblio field (new system preference AuthorityControlledIndicators))\n";
15821 }
15822
15823 $DBversion = '17.12.00.030';
15824 if( CheckVersion( $DBversion ) ) {
15825     $dbh->do(q|
15826         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
15827         VALUES ('NovelistSelectStaffProfile',NULL,'Novelist staff client user Profile',NULL,'free')
15828     |);
15829
15830     SetVersion( $DBversion );
15831     print "Upgrade to $DBversion done (Bug 19882 - Add system preference NovelistSelectStaffProfile)\n";
15832 }
15833
15834 $DBversion = '17.12.00.031';
15835 if( CheckVersion( $DBversion ) ) {
15836     $dbh->do(q|
15837         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
15838         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')
15839     |);
15840
15841     SetVersion( $DBversion );
15842     print "Upgrade to $DBversion done (Bug 11674 - Add system preference MarcFieldDocURL)\n";
15843 }
15844
15845 $DBversion = '17.12.00.032';
15846 if( CheckVersion( $DBversion ) ) {
15847     $dbh->do(q|
15848         UPDATE letter SET code = "SERIAL_ALERT" WHERE code = "RLIST";
15849     |);
15850     $dbh->do(q|
15851         UPDATE letter SET name = "New serial issue" WHERE name = "Routing List";
15852     |);
15853     $dbh->do(q|
15854         UPDATE subscription SET letter = "SERIAL_ALERT" WHERE letter = "RLIST";
15855     |);
15856
15857     SetVersion( $DBversion );
15858     print "Upgrade to $DBversion done (Bug 19794 - Rename RLIST notice to SERIAL_ALERT)\n";
15859 }
15860
15861 $DBversion = '17.12.00.033';
15862 if( CheckVersion( $DBversion ) ) {
15863     if ( !column_exists( 'accountlines', 'payment_type' ) ) {
15864         $dbh->do(q{
15865             ALTER TABLE accountlines ADD payment_type varchar(80) default NULL AFTER accounttype
15866         });
15867     }
15868
15869     $dbh->do(q{
15870         INSERT IGNORE INTO authorised_value_categories( category_name ) VALUES ('PAYMENT_TYPE')
15871     });
15872
15873     SetVersion( $DBversion );
15874     print "Upgrade to $DBversion done (Bug 18786 - Add ability to create custom payment types)\n";
15875 }
15876
15877 $DBversion = '17.12.00.034';
15878 if( CheckVersion( $DBversion ) ) {
15879
15880     $dbh->do( q{
15881         INSERT IGNORE INTO account_offset_types ( type ) VALUES ('Void Payment')
15882     } );
15883
15884     SetVersion( $DBversion );
15885     print "Upgrade to $DBversion done (Bug 18790 - Add ability to void payment)\n";
15886 }
15887
15888 $DBversion = '17.12.00.035';
15889 if( CheckVersion( $DBversion ) ) {
15890     my ( $original_value ) = $dbh->selectrow_array(q|
15891         SELECT value FROM systempreferences WHERE variable="MarkLostItemsAsReturned"
15892     |);
15893     if ( $original_value and $original_value eq '1' ) {
15894         $dbh->do(q{
15895             UPDATE systempreferences
15896             SET type="multiple",
15897                 options="batchmod|moredetail|cronjob|additem",
15898                 value="batchmod,moredetail,cronjob,additem"
15899             WHERE variable="MarkLostItemsAsReturned"
15900         });
15901     } elsif ( $original_value == 0 || !defined($original_value) )  {
15902         $dbh->do(q{
15903             UPDATE systempreferences
15904             SET type="multiple",
15905                 options="batchmod|moredetail|cronjob|additem",
15906                 value=""
15907             WHERE variable="MarkLostItemsAsReturned"
15908         });
15909     }
15910
15911     SetVersion( $DBversion );
15912     print "Upgrade to $DBversion done (Bug 19974 - Make MarkLostItemsAsReturned multiple)\n";
15913 }
15914
15915 $DBversion = '17.12.00.036';
15916 if( CheckVersion( $DBversion ) ) {
15917
15918     $dbh->do( q{
15919         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');
15920     } );
15921     $dbh->do( q{
15922         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');
15923     } );
15924     $dbh->do( q{
15925         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');
15926     } );
15927     $dbh->do( q{
15928         UPDATE systempreferences SET options="batchmod|moredetail|cronjob|additem|pendingreserves" WHERE variable="MarkLostItemsAsReturned";
15929     } );
15930
15931     SetVersion( $DBversion );
15932     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";
15933 }
15934
15935 $DBversion = '17.12.00.037';
15936 if( CheckVersion( $DBversion ) ) {
15937
15938     SetVersion( $DBversion );
15939     print "Upgrade to $DBversion done (This change has been reverted, nothing done!)\n";
15940 }
15941
15942 $DBversion = '17.12.00.038';
15943 if( CheckVersion( $DBversion ) ) {
15944
15945     $dbh->do( q{
15946         UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'slo' WHERE iso639_2_code = 'slk' AND rfc4646_subtag = 'sk';
15947     } );
15948
15949     SetVersion( $DBversion );
15950     print "Upgrade to $DBversion done (Bug 20245 - Use Bibliographic code value for Slovak language)\n";
15951 }
15952
15953 $DBversion = '17.12.00.039';
15954 if( CheckVersion( $DBversion ) ) {
15955
15956     $dbh->do( q{
15957         UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'baq' WHERE iso639_2_code = 'eus' AND rfc4646_subtag = 'eu';
15958     } );
15959     $dbh->do( q{
15960         UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'mao' WHERE iso639_2_code = 'mri' AND rfc4646_subtag = 'mi';
15961     } );
15962     $dbh->do( q{
15963         UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'alb' WHERE iso639_2_code = 'sqi' AND rfc4646_subtag = 'sq';
15964     } );
15965
15966     SetVersion( $DBversion );
15967     print "Upgrade to $DBversion done (Bug 20482 - Use Bibliographic code value for Basque, Maori and Albanian languages)\n";
15968 }
15969
15970 $DBversion = '17.12.00.040';
15971 if( CheckVersion( $DBversion ) ) {
15972
15973     $dbh->do( q{
15974         INSERT IGNORE INTO systempreferences ( value, variable, options, explanation, type )
15975         VALUES ( '0', 'ProtectSuperlibrarianPrivileges', NULL, 'If enabled, non-superlibrarians cannot set superlibrarian privileges', 'YesNo' )
15976     } );
15977
15978     SetVersion( $DBversion );
15979     print "Upgrade to $DBversion done (Bug 20100 - Add new system preference ProtectSuperlibrarianPrivileges)\n";
15980 }
15981
15982 $DBversion = '17.12.00.041';
15983 if( CheckVersion( $DBversion ) ) {
15984
15985     $dbh->do( q{
15986         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES (13, 'access_files', 'Access to the files stored on the server');
15987     } );
15988
15989     SetVersion( $DBversion );
15990     print "Upgrade to $DBversion done (Bug 11317 - Add a new permission to access files stored on the server)\n";
15991 }
15992
15993 $DBversion = '17.12.00.042';
15994 if( CheckVersion( $DBversion ) ) {
15995
15996     if (!TableExists('oauth_access_tokens')) {
15997         $dbh->do(q{
15998             CREATE TABLE oauth_access_tokens (
15999                 `access_token` VARCHAR(191) NOT NULL,
16000                 `client_id`    VARCHAR(191) NOT NULL,
16001                 `expires`      INT NOT NULL,
16002                 PRIMARY KEY (`access_token`)
16003             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
16004         });
16005     }
16006
16007     SetVersion( $DBversion );
16008     print "Upgrade to $DBversion done (Bug 20402 - Implement OAuth2 authentication for REST API)\n";
16009 }
16010
16011 $DBversion = '17.12.00.043';
16012 if(CheckVersion($DBversion)) {
16013
16014     if (!TableExists('api_keys')) {
16015         $dbh->do(q{
16016             CREATE TABLE `api_keys` (
16017                 `client_id`   VARCHAR(191) NOT NULL,
16018                 `secret`      VARCHAR(191) NOT NULL,
16019                 `description` VARCHAR(255) NOT NULL,
16020                 `patron_id`   INT(11) NOT NULL,
16021                 `active`      TINYINT(1) DEFAULT 1 NOT NULL,
16022                 PRIMARY KEY `client_id` (`client_id`),
16023                 UNIQUE KEY `secret` (`secret`),
16024                 KEY `patron_id` (`patron_id`),
16025                 CONSTRAINT `api_keys_fk_patron_id`
16026                   FOREIGN KEY (`patron_id`)
16027                   REFERENCES `borrowers` (`borrowernumber`)
16028                   ON DELETE CASCADE ON UPDATE CASCADE
16029             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16030         });
16031     }
16032
16033     print "Upgrade to $DBversion done (Bug 20568 - Add API key management interface for patrons)\n";
16034     SetVersion($DBversion);
16035 }
16036
16037 $DBversion = '17.12.00.044';
16038 if(CheckVersion($DBversion)) {
16039
16040     $dbh->do(q{
16041         INSERT IGNORE INTO systempreferences (`variable`,`value`,`options`,`explanation`,`type`)
16042         VALUES
16043             ('RESTOAuth2ClientCredentials','0',NULL,'If enabled, the OAuth2 client credentials flow is enabled for the REST API.','YesNo');
16044     });
16045
16046     print "Upgrade to $DBversion done (Bug 20624 - Disable OAuth2 client credentials grant by default)\n";
16047     SetVersion($DBversion);
16048 }
16049
16050 $DBversion = '18.05.00.000';
16051 if( CheckVersion( $DBversion ) ) {
16052     SetVersion( $DBversion );
16053     print "Upgrade to $DBversion done (Koha 18.05)\n";
16054 }
16055
16056 $DBversion = '18.06.00.000';
16057 if( CheckVersion( $DBversion ) ) {
16058     SetVersion( $DBversion );
16059     print "Upgrade to $DBversion done (Koha 18.06 - It's Adventure time!)\n";
16060 }
16061
16062 $DBversion = '18.06.00.001';
16063 if( CheckVersion( $DBversion ) ) {
16064     $dbh->do(q{UPDATE permissions SET description = 'Manage budgets' WHERE code = 'period_manage';});
16065     $dbh->do(q{UPDATE permissions SET description = 'Manage funds' WHERE code = 'budget_manage';});
16066     $dbh->do(q{UPDATE permissions SET description = 'Modify funds (can''t create lines, but can modify existing ones)' WHERE code = 'budget_modify';});
16067     $dbh->do(q{UPDATE permissions SET description = 'Manage baskets and order lines' WHERE code = 'order_manage';});
16068     $dbh->do(q{UPDATE permissions SET description = 'Manage all baskets and order lines, regardless of restrictions on them' WHERE code = 'order_manage_all';});
16069     $dbh->do(q{UPDATE permissions SET description = 'Manage basket groups' WHERE code = 'group_manage';});
16070     $dbh->do(q{UPDATE permissions SET description = 'Receive orders and manage shipments' WHERE code = 'order_receive';});
16071     $dbh->do(q{UPDATE permissions SET description = 'Add and delete funds (but can''t modify funds)' WHERE code = 'budget_add_del';});
16072     $dbh->do(q{UPDATE permissions SET description = 'Manage all funds' WHERE code = 'budget_manage_all';});
16073     SetVersion( $DBversion );
16074     print "Upgrade to $DBversion done (Bug 3849- Improve descriptions of granular acquisition permissions)\n";
16075 }
16076
16077 $DBversion = '18.06.00.002';
16078 if( CheckVersion( $DBversion ) ) {
16079     $dbh->do(q{DELETE FROM userflags WHERE bit = 12 AND flag = 'management';});
16080     $dbh->do(q{UPDATE borrowers SET flags = flags - ( flags & (1<<12) ) WHERE flags & (1 << 12);});
16081     SetVersion( $DBversion );
16082     print "Upgrade to $DBversion done (Bug 2426 - Remove deprecated management permission)\n";
16083 }
16084
16085 $DBversion = '18.06.00.003';
16086 if( CheckVersion( $DBversion ) ) {
16087     $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'" );
16088     SetVersion( $DBversion );
16089     print "Upgrade to $DBversion done (Bug 20073 - Add new types for Elasticsearch fields)\n";
16090 }
16091
16092 $DBversion = '18.06.00.004';
16093 if( CheckVersion( $DBversion ) ) {
16094
16095     # Add 'Manual Credit' offset type
16096     $dbh->do(q{
16097         INSERT IGNORE INTO `account_offset_types` (`type`) VALUES ('Manual Credit');
16098     });
16099
16100     # Fix wrong account offsets / Manual credits
16101     $dbh->do(q{
16102         UPDATE account_offsets
16103         SET credit_id=debit_id,
16104             debit_id=NULL,
16105             type='Manual Credit'
16106         WHERE amount < 0 AND
16107               type='Manual Debit' AND
16108               debit_id IN
16109                 (SELECT accountlines_id AS debit_id
16110                  FROM accountlines
16111                  WHERE accounttype='C');
16112     });
16113
16114     # Fix wrong account offsets / Manually forgiven amounts
16115     $dbh->do(q{
16116         UPDATE account_offsets
16117         SET credit_id=debit_id,
16118             debit_id=NULL,
16119             type='Writeoff'
16120         WHERE amount < 0 AND
16121               type='Manual Debit' AND
16122               debit_id IN
16123                 (SELECT accountlines_id AS debit_id
16124                  FROM accountlines
16125                  WHERE accounttype='FOR');
16126     });
16127
16128     SetVersion( $DBversion );
16129     print "Upgrade to $DBversion done (Bug 20980 - Manual credit offsets are stored as debits)\n";
16130 }
16131
16132 $DBversion = '18.06.00.005';
16133 if( CheckVersion( $DBversion ) ) {
16134     unless ( column_exists('aqorders', 'created_by') ) {
16135         $dbh->do( "ALTER TABLE aqorders ADD COLUMN created_by int(11) NULL DEFAULT NULL AFTER quantityreceived;" );
16136         unless ( foreign_key_exists('aqorders', 'aqorders_created_by') ) {
16137             $dbh->do( "ALTER TABLE aqorders ADD CONSTRAINT aqorders_created_by FOREIGN KEY (created_by) REFERENCES borrowers (borrowernumber) ON DELETE SET NULL ON UPDATE CASCADE;" );
16138         }
16139         $dbh->do( "UPDATE aqbasket LEFT JOIN borrowers ON ( aqbasket.authorisedby = borrowers.borrowernumber ) SET aqbasket.authorisedby = NULL WHERE borrowers.borrowernumber IS NULL;" );
16140         $dbh->do( "UPDATE aqorders LEFT JOIN aqbasket ON ( aqorders.basketno = aqbasket.basketno ) SET aqorders.created_by = aqbasket.authorisedby WHERE aqorders.created_by IS NULL;" );
16141     }
16142     SetVersion( $DBversion );
16143     print "Upgrade to $DBversion done (Bug 12395 - Save order line's creator)\n";
16144 }
16145
16146 $DBversion = '18.06.00.006';
16147 if( CheckVersion( $DBversion ) ) {
16148     unless ( column_exists('patron_lists', 'shared') ) {
16149         $dbh->do( "ALTER TABLE patron_lists ADD COLUMN shared tinyint(1) default 0 AFTER owner;" );
16150     }
16151     SetVersion( $DBversion );
16152     print "Upgrade to $DBversion done (Bug 19524 - Share patron lists between staff)\n";
16153 }
16154
16155 $DBversion = '18.06.00.007';
16156 if( CheckVersion( $DBversion ) ) {
16157     $dbh->do( "INSERT IGNORE INTO permissions (module_bit, code, description) VALUES (11, 'currencies_manage', 'Manage currencies and exchange rates');" );
16158     $dbh->do(q{
16159         INSERT IGNORE INTO user_permissions (borrowernumber, module_bit, code)
16160             SELECT borrowernumber, 11, 'currencies_manage' FROM borrowers WHERE flags & (1 << 3) OR borrowernumber IN
16161             (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16162     });
16163     SetVersion( $DBversion );
16164     print "Upgrade to $DBversion done (Bug 7651 - Add separate permission for managing currencies and exchange rates)\n";
16165 }
16166
16167 $DBversion = '18.06.00.008';
16168 if( CheckVersion( $DBversion ) ) {
16169     $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')" );
16170     SetVersion( $DBversion );
16171     print "Upgrade to $DBversion done (Bug 13560 - need an add option in marc modification templates)\n";
16172 }
16173
16174 $DBversion = '18.06.00.009';
16175 if( CheckVersion( $DBversion ) ) {
16176     $dbh->do( "
16177         CREATE TABLE IF NOT EXISTS aqinvoice_adjustments (
16178             adjustment_id int(11) NOT NULL AUTO_INCREMENT,
16179             invoiceid int(11) NOT NULL,
16180             adjustment decimal(28,6),
16181             reason varchar(80) default NULL,
16182             note mediumtext default NULL,
16183             budget_id int(11) default NULL,
16184             encumber_open smallint(1) NOT NULL default 1,
16185             timestamp timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
16186             PRIMARY KEY (adjustment_id),
16187             CONSTRAINT aqinvoice_adjustments_fk_invoiceid FOREIGN KEY (invoiceid) REFERENCES aqinvoices (invoiceid) ON DELETE CASCADE ON UPDATE CASCADE,
16188             CONSTRAINT aqinvoice_adjustments_fk_budget_id FOREIGN KEY (budget_id) REFERENCES aqbudgets (budget_id) ON DELETE SET NULL ON UPDATE CASCADE
16189         ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
16190         " );
16191     $dbh->do("INSERT IGNORE INTO authorised_value_categories (category_name) VALUES ('ADJ_REASON')");
16192     SetVersion( $DBversion );
16193     print "Upgrade to $DBversion done (Bug 19166 - Add the ability to add adjustments to an invoice)\n";
16194 }
16195
16196 $DBversion = '18.06.00.010';
16197 if( CheckVersion( $DBversion ) ) {
16198     $dbh->do(q{
16199         INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`, `lang`)
16200         VALUES
16201             ('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'),
16202                 ('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');
16203     });
16204     $dbh->do(q{
16205         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
16206         VALUES ('UseEmailReceipts','0','','Send email receipts for payments and write-offs','YesNo')
16207     });
16208     SetVersion( $DBversion );
16209     print "Upgrade to $DBversion done (Bug 19191 - Add ability to email receipts for account payments and write-offs)\n";
16210 }
16211
16212 $DBversion = '18.06.00.011';
16213 if( CheckVersion( $DBversion ) ) {
16214     unless( column_exists( 'issues', 'noteseen' ) ) {
16215         $dbh->do(q|ALTER TABLE issues ADD COLUMN noteseen int(1) default NULL AFTER notedate|);
16216     }
16217
16218     unless( column_exists( 'old_issues', 'noteseen' ) ) {
16219         $dbh->do(q|ALTER TABLE old_issues ADD COLUMN noteseen int(1) default NULL AFTER notedate|);
16220     }
16221     $dbh->do(q|INSERT IGNORE INTO permissions (module_bit, code, description) VALUES ( 1, 'manage_checkout_notes', 'Mark checkout notes as seen/not seen');|);
16222     SetVersion( $DBversion );
16223     print "Upgrade to $DBversion done (Bug 17698: Add column issues.noteseen and old_issues.noteseen)\n";
16224 }
16225
16226 $DBversion = '18.06.00.012';
16227 if( CheckVersion( $DBversion ) ) {
16228     $dbh->do(q|INSERT IGNORE INTO permissions (module_bit, code, description) VALUES (11, 'suggestions_manage', 'Manage purchase suggestions');|);
16229     $dbh->do(q|INSERT IGNORE INTO user_permissions (borrowernumber, module_bit, code) SELECT borrowernumber, 11, 'suggestions_manage' FROM borrowers WHERE flags & (1 << 2);|);
16230     SetVersion( $DBversion );
16231     print "Upgrade to $DBversion done (Bug 11911 - Add separate permission for managing suggestions)\n";
16232 }
16233
16234 $DBversion = '18.06.00.013';
16235 if( CheckVersion( $DBversion ) ) {
16236     $dbh->do(q{
16237         INSERT IGNORE INTO `account_offset_types` (`type`) VALUES ('Credit Applied');
16238     });
16239     SetVersion( $DBversion );
16240     print "Upgrade to $DBversion done (Bug 20997 - Add Koha::Account::Line::apply)\n";
16241 }
16242
16243 $DBversion = '18.06.00.014';
16244 if( CheckVersion( $DBversion ) ) {
16245     $dbh->do(q{
16246             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');
16247     });
16248     SetVersion( $DBversion );
16249     print "Upgrade to $DBversion done (Bug 21121 - New syspref to allow hiding of private patron data in circulation page)\n";
16250 }
16251
16252 $DBversion = '18.06.00.015';
16253 if( CheckVersion( $DBversion ) ) {
16254     $dbh->do(q{DELETE FROM systempreferences where variable="OCLCAffiliateID";});
16255     $dbh->do(q{DELETE FROM systempreferences where variable="XISBN";});
16256     $dbh->do(q{DELETE FROM systempreferences where variable="XISBNDailyLimit";});
16257     SetVersion( $DBversion );
16258     print "Upgrade to $DBversion done (Bug 21226 - Remove prefs OCLCAffiliateID, XISBN and XISBNDailyLimit)\n";
16259 }
16260
16261 $DBversion = '18.06.00.016';
16262 if( CheckVersion( $DBversion ) ) {
16263     my $dtf  = Koha::Database->new->schema->storage->datetime_parser;
16264     my $days = C4::Context->preference('MaxPickupDelay') || 7;
16265     my $date = dt_from_string()->add( days => $days );
16266     my $sql  = q|UPDATE reserves SET expirationdate = ? WHERE expirationdate IS NULL AND waitingdate IS NOT NULL|;
16267     $dbh->do( $sql, undef, $dtf->format_datetime($date) );
16268     SetVersion( $DBversion );
16269     print "Upgrade to $DBversion done (Bug 20773 - expirationdate filled for waiting holds)\n";
16270 }
16271
16272 $DBversion = '18.06.00.017';
16273 if( CheckVersion( $DBversion ) ) {
16274     $dbh->do(q|INSERT IGNORE INTO authorised_value_categories (category_name) VALUES ('ROADTYPE');|);
16275     SetVersion( $DBversion );
16276     print "Upgrade to $DBversion done (Bug 21144: Add ROADTYPE to default authorised values categories)\n";
16277 }
16278
16279 $DBversion = '18.06.00.018';
16280 if( CheckVersion( $DBversion ) ) {
16281     $dbh->do( q|
16282 UPDATE items LEFT JOIN issues USING (itemnumber)
16283 SET items.onloan = NULL
16284 WHERE issues.itemnumber IS NULL
16285     |);
16286     SetVersion( $DBversion );
16287     print "Upgrade to $DBversion done (Bug 20487: Clear items.onloan for unissued items)\n";
16288 }
16289
16290 $DBversion = '18.06.00.019';
16291 if( CheckVersion( $DBversion ) ) {
16292     $dbh->do( q|
16293 INSERT IGNORE INTO columns_settings (module, page, tablename, columnname, cannot_be_toggled, is_hidden) VALUES
16294 ("circ", "circulation", "issues-table", "collection", 0, 1),
16295 ("members", "moremember", "issues-table", "collection", 0, 1);
16296     |);
16297     SetVersion( $DBversion );
16298     print "Upgrade to $DBversion done (Bug 19719: Default to hiding collection code column)\n";
16299 }
16300
16301 $DBversion = '18.06.00.020';
16302 if( CheckVersion( $DBversion ) ) {
16303     if( !column_exists( 'branch_borrower_circ_rules', 'max_holds' ) ) {
16304         $dbh->do(q{
16305             ALTER TABLE branch_borrower_circ_rules ADD COLUMN max_holds INT(4) NULL DEFAULT NULL AFTER maxonsiteissueqty
16306         });
16307     }
16308     if( !column_exists( 'default_borrower_circ_rules', 'max_holds' ) ) {
16309         $dbh->do(q{
16310             ALTER TABLE default_borrower_circ_rules ADD COLUMN max_holds INT(4) NULL DEFAULT NULL AFTER maxonsiteissueqty
16311         });
16312     }
16313     SetVersion( $DBversion );
16314     print "Upgrade to $DBversion done (Bug 15524 - Set limit on maximum possible holds per patron by category)\n";
16315 }
16316
16317 $DBversion = '18.06.00.021';
16318 if( CheckVersion( $DBversion ) ) {
16319     my $dbh = C4::Context->dbh;
16320     unless ( C4::Context->preference('NorwegianPatronDBEnable') ) {
16321         $dbh->do(q|
16322             DELETE FROM systempreferences
16323             WHERE variable IN ('NorwegianPatronDBEnable', 'NorwegianPatronDBEndpoint', 'NorwegianPatronDBUsername', 'NorwegianPatronDBPassword', 'NorwegianPatronDBSearchNLAfterLocalHit')
16324         |);
16325         if ( TableExists('borrower_sync') ) {
16326             $dbh->do(q|DROP TABLE borrower_sync|);
16327         }
16328     }
16329     SetVersion( $DBversion );
16330     print "Upgrade to $DBversion done (Bug 21068 - Remove system preferences NorwegianPatronDB*)\n";
16331 }
16332
16333 $DBversion = '18.06.00.022';
16334 if( CheckVersion( $DBversion ) ) {
16335     my $dbh = C4::Context->dbh;
16336     $dbh->do(q|
16337         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
16338         ('HoldsAutoFill','0',NULL,'If on, librarian will not be asked if hold should be filled, it will be filled automatically','YesNo'),
16339         ('HoldsAutoFillPrintSlip','0',NULL,'If on, hold slip print dialog will be displayed automatically','YesNo')
16340     |);
16341     SetVersion( $DBversion );
16342     print "Upgrade to $DBversion done (Bug 19383 - Add ability to print hold receipts automatically)\n";
16343 }
16344
16345 $DBversion = '18.06.00.023';
16346 if( CheckVersion( $DBversion ) ) {
16347     if( !column_exists( 'aqorders', 'replacementprice' ) ){
16348         $dbh->do( "ALTER TABLE aqorders ADD COLUMN replacementprice DECIMAL(28,6)" );
16349         $dbh->do( "UPDATE aqorders set replacementprice = rrp WHERE replacementprice IS NULL" );
16350     }
16351     SetVersion( $DBversion );
16352     print "Upgrade to $DBversion done (Bug 18639 - Add replacementprice field to aqorders table)\n";
16353 }
16354
16355 $DBversion = '18.06.00.024';
16356 if( CheckVersion( $DBversion ) ) {
16357     if( !column_exists( 'branches', 'pickup_location' ) ){
16358         $dbh->do( "ALTER TABLE branches ADD COLUMN pickup_location TINYINT(1) not null default 1" );
16359     }
16360     SetVersion( $DBversion );
16361     print "Upgrade to $DBversion done (Bug 7534 - Let libraries have configuration for pickup locations)\n";
16362 }
16363
16364 $DBversion = '18.06.00.025';
16365 if( CheckVersion( $DBversion ) ) {
16366     $dbh->do(q{
16367         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
16368         ('KohaManualBaseURL','https://koha-community.org/manual/','','Where is the Koha manual/documentation located?','Free'),
16369         ('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')
16370     });
16371     SetVersion( $DBversion );
16372     print "Upgrade to $DBversion done (Bug 19817: Add pref KohaManualLanguage and KohaManualBaseURL)\n";
16373 }
16374
16375 $DBversion = '18.06.00.026';
16376 if( CheckVersion( $DBversion ) ) {
16377     $dbh->do(q|
16378 INSERT IGNORE INTO  systempreferences (variable, value, options, explanation, type) VALUES ('ArticleRequestsLinkControl', 'always', 'always\|calc', 'Control display of article request link on search results', 'Choice')
16379     |);
16380     SetVersion( $DBversion );
16381     print "Upgrade to $DBversion done (Bug 17530 - Add pref ArticleRequestsLinkControl)\n";
16382 }
16383
16384 $DBversion = '18.06.00.027';
16385 if( CheckVersion( $DBversion ) ) {
16386     $dbh->do( "DROP TABLE IF EXISTS services_throttle" );
16387     SetVersion( $DBversion );
16388     print "Upgrade to $DBversion done (Bug 21235: Remove table services_throttle)\n";
16389 }
16390
16391 $DBversion = '18.06.00.028';
16392 if( CheckVersion( $DBversion ) ) {
16393     $dbh->do(q{
16394 INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
16395 ('HoldsSplitQueue','nothing','nothing|branch|itemtype|branch_itemtype','In the staff client, split the holds view by the given criteria','Choice'),
16396 ('HoldsSplitQueueNumbering', 'actual', 'actual|virtual', 'If the holds queue is split, decide if the acual priorities should be displayed', 'Choice');
16397 });
16398     SetVersion( $DBversion );
16399     print "Upgrade to $DBversion done (Bug 19469 - Add ability to split view of holds view on record by pickup library and/or itemtype)\n";
16400 }
16401
16402 $DBversion = '18.06.00.029';
16403 if( CheckVersion( $DBversion ) ) {
16404     unless ( index_exists( 'subscription', 'by_biblionumber' ) ) {
16405         $dbh->do(q{
16406             CREATE INDEX `by_biblionumber` ON `subscription` (`biblionumber`)
16407         });
16408     }
16409     SetVersion( $DBversion );
16410     print "Upgrade to $DBversion done (Bug 21288: Slowness in acquisition caused by GetInvoices\n";
16411 }
16412
16413 $DBversion = '18.06.00.030';
16414 if( CheckVersion( $DBversion ) ) {
16415     if ( column_exists( 'accountlines', 'dispute' ) ) {
16416         $dbh->do(q{
16417             ALTER TABLE `accountlines`
16418                 DROP COLUMN `dispute`
16419         });
16420     }
16421     SetVersion( $DBversion );
16422     print "Upgrade to $DBversion done (Bug 20777 - Remove unused field accountlines.dispute)\n";
16423 }
16424
16425 $DBversion = '18.06.00.031';
16426 if( CheckVersion( $DBversion ) ) {
16427     # Add table and add column
16428     unless (TableExists('patron_consent')) {
16429         $dbh->do(q|
16430     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 )
16431         |);
16432     }
16433     unless ( column_exists( 'borrower_modifications', 'gdpr_proc_consent' ) ) {
16434         $dbh->do(q|
16435     ALTER TABLE borrower_modifications ADD COLUMN gdpr_proc_consent datetime
16436         |);
16437     }
16438     # Add two sysprefs too
16439     $dbh->do(q|
16440 INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type ) VALUES ('PrivacyPolicyURL','',NULL,'This URL is used in messages about GDPR consents.', 'Free')
16441     |);
16442     $dbh->do(q|
16443 INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type ) VALUES ('GDPR_Policy','','Enforced\|Permissive\|Disabled','General Data Protection Regulation - policy', 'Choice')
16444     |);
16445     SetVersion( $DBversion );
16446     print "Upgrade to $DBversion done (Bug 20819: Add patron_consent)\n";
16447 }
16448
16449 $DBversion = '18.06.00.032';
16450 if( CheckVersion( $DBversion ) ) {
16451     $dbh->do(q|ALTER TABLE items                   CHANGE COLUMN ccode ccode varchar(80) default NULL|);
16452     $dbh->do(q|ALTER TABLE deleteditems            CHANGE COLUMN ccode ccode varchar(80) default NULL|);
16453     $dbh->do(q|ALTER TABLE branch_transfer_limits  CHANGE COLUMN ccode ccode varchar(80) default NULL|);
16454     $dbh->do(q|ALTER TABLE course_items            CHANGE COLUMN ccode ccode varchar(80) default NULL|);
16455     SetVersion( $DBversion );
16456     print "Upgrade to $DBversion done (Bug 5458: length of items.ccode disagrees with authorised_values.authorised_value)\n";
16457 }
16458
16459 $DBversion = '18.06.00.033';
16460 if( CheckVersion( $DBversion ) ) {
16461     $dbh->do(q|
16462         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')
16463     |);
16464     SetVersion( $DBversion );
16465     print "Upgrade to $DBversion done (Bug 12747 - Add AdditionalFieldsInZ3950ResultSearch system preference)\n";
16466 }
16467
16468 $DBversion = '18.06.00.034';
16469 if( CheckVersion( $DBversion ) ) {
16470     $dbh->do(q|
16471         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
16472         VALUES ('RecordedBooksClientSecret','','30','Client key for RecordedBooks integration','YesNo'),
16473                ('RecordedBooksLibraryID','','','Library ID for RecordedBooks integration','Integer'),
16474                ('RecordedBooksDomain','','','RecordedBooks domain','Free');
16475     |);
16476     SetVersion( $DBversion );
16477     print "Upgrade to $DBversion done (Bug 17602 - Integrate support for OneClickdigital/Recorded Books API)\n";
16478 }
16479
16480 $DBversion = '18.06.00.035';
16481 if( CheckVersion( $DBversion ) ) {
16482     $dbh->do(q{
16483         UPDATE `systempreferences` SET options = 'US|CA|DE|FR|IN|JP|UK' WHERE variable = 'AmazonLocale' AND options='US|CA|DE|FR|JP|UK';
16484     });
16485     SetVersion( $DBversion );
16486     print "Upgrade to $DBversion done (Bug 21403 - Add Indian Amazon Affiliate option to AmazonLocale setting)\n";
16487 }
16488
16489
16490 $DBversion = '18.06.00.036';
16491 if( CheckVersion( $DBversion ) ) {
16492     unless (TableExists('circulation_rules')){
16493         $dbh->do(q{
16494             CREATE TABLE `circulation_rules` (
16495               `id` int(11) NOT NULL auto_increment,
16496               `branchcode` varchar(10) NULL default NULL,
16497               `categorycode` varchar(10) NULL default NULL,
16498               `itemtype` varchar(10) NULL default NULL,
16499               `rule_name` varchar(32) NOT NULL,
16500               `rule_value` varchar(32) NOT NULL,
16501               PRIMARY KEY (`id`),
16502               CONSTRAINT `circ_rules_ibfk_1` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
16503               CONSTRAINT `circ_rules_ibfk_2` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`) ON DELETE CASCADE ON UPDATE CASCADE,
16504               CONSTRAINT `circ_rules_ibfk_3` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE,
16505               KEY `rule_name` (`rule_name`),
16506               UNIQUE (`branchcode`,`categorycode`,`itemtype`,`rule_name`)
16507             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16508         });
16509     }
16510     if (column_exists('branch_borrower_circ_rules', 'max_holds') ){
16511         $dbh->do(q{
16512             INSERT IGNORE INTO circulation_rules ( branchcode, categorycode, itemtype, rule_name, rule_value )
16513             SELECT branchcode, categorycode, NULL, 'max_holds', COALESCE( max_holds, '' ) FROM branch_borrower_circ_rules
16514         });
16515         $dbh->do(q{
16516             ALTER TABLE branch_borrower_circ_rules DROP COLUMN max_holds
16517         });
16518     }
16519     if (column_exists('default_borrower_circ_rules', 'max_holds') ){
16520         $dbh->do(q{
16521             INSERT IGNORE INTO circulation_rules ( branchcode, categorycode, itemtype, rule_name, rule_value )
16522             SELECT NULL, categorycode, NULL, 'max_holds', COALESCE( max_holds, '' ) FROM default_borrower_circ_rules
16523         });
16524         $dbh->do(q{
16525             ALTER TABLE default_borrower_circ_rules DROP COLUMN max_holds
16526         });
16527     }
16528     SetVersion( $DBversion );
16529     print "Upgrade to $DBversion done (Bug 18887 - Introduce new table 'circulation_rules', use for 'max_holds' rules)\n";
16530 }
16531
16532 $DBversion = '18.06.00.037';
16533 if( CheckVersion( $DBversion ) ) {
16534     unless (TableExists('branches_overdrive')){
16535         $dbh->do( q|
16536             CREATE TABLE branches_overdrive (
16537                 `branchcode` VARCHAR( 10 ) NOT NULL ,
16538                 `authname` VARCHAR( 255 ) NOT NULL ,
16539                 PRIMARY KEY (`branchcode`) ,
16540                 CONSTRAINT `branches_overdrive_ibfk_1` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
16541             ) ENGINE = INNODB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci |
16542         );
16543     }
16544     $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');");
16545     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('OverDriveWebsiteID','', 'WebsiteID provided by OverDrive', NULL, 'Free');");
16546     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('OverDrivePasswordRequired','', 'Does the library require passwords for OverDrive SIP authentication', NULL, 'YesNo');");
16547     SetVersion( $DBversion );
16548     print "Upgrade to $DBversion done (Bug 21082 - Add overdrive patron auth method)\n";
16549 }
16550
16551 $DBversion = '18.06.00.038';
16552 if( CheckVersion( $DBversion ) ) {
16553     $dbh->do( "ALTER TABLE edifact_ean MODIFY branchcode VARCHAR(10) NULL DEFAULT NULL" );
16554     SetVersion( $DBversion );
16555     print "Upgrade to $DBversion done (Bug 21417 - EDI ordering fails when basket and EAN libraries do not match)\n";
16556 }
16557
16558 $DBversion = '18.06.00.039';
16559 if( CheckVersion( $DBversion ) ) {
16560     $dbh->do(q{
16561         INSERT IGNORE INTO `permissions` (module_bit, code, description) VALUES(3, 'manage_circ_rules_from_any_libraries', 'Manage circ rules for any libraries');
16562     });
16563     SetVersion( $DBversion );
16564     print "Upgrade to $DBversion done (Bug 15520 - Add more granular permission for only editing own library's circ rules)\n";
16565 }
16566
16567 $DBversion = '18.06.00.040';
16568 if( CheckVersion( $DBversion ) ) {
16569     # Stock Rotation Rotas
16570     unless (TableExists('stockrotationrotas')){
16571         $dbh->do(q{
16572           CREATE TABLE `stockrotationrotas` (
16573             `rota_id` int(11) auto_increment,         -- Stockrotation rota ID
16574             `title` varchar(100) NOT NULL,            -- Title for this rota
16575             `description` text NOT NULL,              -- Description for this rota
16576             `cyclical` tinyint(1) NOT NULL default 0, -- Should items on this rota keep cycling?
16577             `active` tinyint(1) NOT NULL default 0,   -- Is this rota currently active?
16578             PRIMARY KEY (`rota_id`),
16579             CONSTRAINT `stockrotationrotas_title`
16580             UNIQUE (`title`)
16581           ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16582         });
16583     }
16584     # Stock Rotation Stages
16585     unless (TableExists('stockrotationstages')){
16586         $dbh->do(q{
16587           CREATE TABLE `stockrotationstages` (
16588               `stage_id` int(11) auto_increment,     -- Unique stage ID
16589               `position` int(11) NOT NULL,           -- The position of this stage within its rota
16590               `rota_id` int(11) NOT NULL,            -- The rota this stage belongs to
16591               `branchcode_id` varchar(10) NOT NULL,  -- Branch this stage relates to
16592               `duration` int(11) NOT NULL default 4, -- The number of days items shoud occupy this stage
16593               PRIMARY KEY (`stage_id`),
16594               CONSTRAINT `stockrotationstages_rifk`
16595                 FOREIGN KEY (`rota_id`)
16596                 REFERENCES `stockrotationrotas` (`rota_id`)
16597                 ON UPDATE CASCADE ON DELETE CASCADE,
16598               CONSTRAINT `stockrotationstages_bifk`
16599                 FOREIGN KEY (`branchcode_id`)
16600                 REFERENCES `branches` (`branchcode`)
16601                 ON UPDATE CASCADE ON DELETE CASCADE
16602           ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16603         });
16604     }
16605     # Stock Rotation Items
16606     unless (TableExists('stockrotationitems')){
16607         $dbh->do(q{
16608           CREATE TABLE `stockrotationitems` (
16609               `itemnumber_id` int(11) NOT NULL,         -- Itemnumber to link to a stage & rota
16610               `stage_id` int(11) NOT NULL,              -- stage ID to link the item to
16611               `indemand` tinyint(1) NOT NULL default 0, -- Should this item be skipped for rotation?
16612               `fresh` tinyint(1) NOT NULL default 0,    -- Flag showing item is only just added to rota
16613               PRIMARY KEY (itemnumber_id),
16614               CONSTRAINT `stockrotationitems_iifk`
16615                 FOREIGN KEY (`itemnumber_id`)
16616                 REFERENCES `items` (`itemnumber`)
16617                 ON UPDATE CASCADE ON DELETE CASCADE,
16618               CONSTRAINT `stockrotationitems_sifk`
16619                 FOREIGN KEY (`stage_id`)
16620                 REFERENCES `stockrotationstages` (`stage_id`)
16621                 ON UPDATE CASCADE ON DELETE CASCADE
16622           ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16623         });
16624     }
16625     # System preferences
16626     $dbh->do(q{
16627         INSERT IGNORE INTO `systempreferences` (`variable`,`value`,`explanation`,`options`,`type`)
16628         VALUES ('StockRotation','0','If ON, enables the stock rotation module','','YesNo'),
16629                ('RotationPreventTransfers','0','If ON, prevent any transfers for items on stock rotation rotas, except for stock rotation transfers','','YesNo');
16630     });
16631     # Permissions
16632     $dbh->do(q{
16633         INSERT IGNORE INTO `userflags` (`bit`, `flag`, `flagdesc`, `defaulton`)
16634         VALUES (24, 'stockrotation', 'Manage stockrotation operations', 0);
16635     });
16636     $dbh->do(q{
16637         INSERT IGNORE INTO `permissions` (`module_bit`, `code`, `description`)
16638         VALUES (24, 'manage_rotas', 'Create, edit and delete rotas'),
16639                (24, 'manage_rota_items', 'Add and remove items from rotas');
16640     });
16641     # Notices
16642     $dbh->do(q{
16643         INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`)
16644         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');
16645     });
16646     print "Upgrade to $DBversion done (Bug 11897 - Add Stock Rotation Feature)\n";
16647     SetVersion( $DBversion );
16648 }
16649
16650 $DBversion = '18.06.00.041';
16651 if( CheckVersion( $DBversion ) ) {
16652
16653      if( !column_exists( 'illrequests', 'price_paid' ) ) {
16654         $dbh->do(q{
16655             ALTER TABLE illrequests
16656                 ADD COLUMN price_paid varchar(20) DEFAULT NULL
16657                 AFTER cost
16658         });
16659      }
16660
16661      if( !column_exists( 'illrequestattributes', 'readonly' ) ) {
16662         $dbh->do(q{
16663             ALTER TABLE illrequestattributes
16664                 ADD COLUMN readonly tinyint(1) NOT NULL DEFAULT 1
16665                 AFTER value
16666         });
16667         $dbh->do(q{
16668             UPDATE illrequestattributes SET readonly = 1
16669         });
16670      }
16671
16672     SetVersion( $DBversion );
16673     print "Upgrade to $DBversion done (Bug 20772 - Add illrequestattributes.readonly and illrequest.price_paid columns)\n";
16674 }
16675
16676 $DBversion = '18.06.00.042';
16677 if( CheckVersion( $DBversion ) ) {
16678     $dbh->do( "alter table statistics change column ccode ccode varchar(80) default NULL" );
16679
16680     SetVersion( $DBversion );
16681     print "Upgrade to $DBversion done (Bug 21617: Make statistics.ccode longer)\n";
16682 }
16683
16684 $DBversion = "18.06.00.043";
16685 if ( CheckVersion($DBversion) ) {
16686     if ( !column_exists( 'issuingrules', 'holds_per_day' ) ) {
16687         $dbh->do(q{
16688             ALTER TABLE `issuingrules`
16689                 ADD COLUMN `holds_per_day` SMALLINT(6) DEFAULT NULL
16690                 AFTER `holds_per_record`
16691         });
16692     }
16693     print "Upgrade to $DBversion done (Bug 15486: Restrict number of holds placed by day)\n";
16694     SetVersion($DBversion);
16695 }
16696
16697 $DBversion = '18.06.00.044';
16698 if( CheckVersion( $DBversion ) ) {
16699     unless( column_exists( 'creator_batches', 'description' ) ) {
16700         $dbh->do(q|ALTER TABLE creator_batches ADD description mediumtext default NULL AFTER batch_id|);
16701     }
16702     SetVersion( $DBversion );
16703     print "Upgrade to $DBversion done (Bug 15766: Add column creator_batches.description)\n";
16704 }
16705
16706 $DBversion = '18.06.00.045';
16707 if( CheckVersion( $DBversion ) ) {
16708     $dbh->do(q(
16709         INSERT IGNORE INTO message_transports
16710         (message_attribute_id,message_transport_type,is_digest,letter_module,letter_code)
16711         VALUES
16712         (2, 'phone', 0, 'circulation', 'PREDUE'),
16713         (2, 'phone', 1, 'circulation', 'PREDUEDGST'),
16714         (4, 'phone', 0, 'reserves',    'HOLD')
16715         ));
16716     SetVersion( $DBversion );
16717     print "Upgrade to $DBversion done (Bug 21639 - Add phone transports by default)\n";
16718 }
16719
16720 $DBversion = '18.06.00.046';
16721 if( CheckVersion( $DBversion ) ) {
16722     unless (TableExists('illcomments')) {
16723         $dbh->do(q{
16724             CREATE TABLE illcomments (
16725                 illcomment_id int(11) NOT NULL AUTO_INCREMENT, -- Unique ID of the comment
16726                 illrequest_id bigint(20) unsigned NOT NULL,    -- ILL request number
16727                 borrowernumber integer DEFAULT NULL,           -- Link to the user who made the comment (could be librarian, patron or ILL partner library)
16728                 comment text DEFAULT NULL,                     -- The text of the comment
16729                 timestamp timestamp DEFAULT CURRENT_TIMESTAMP, -- Date and time when the comment was made
16730                 PRIMARY KEY  ( illcomment_id ),
16731                 CONSTRAINT illcomments_bnfk
16732                   FOREIGN KEY ( borrowernumber )
16733                   REFERENCES  borrowers  ( borrowernumber )
16734                   ON UPDATE CASCADE ON DELETE CASCADE,
16735                 CONSTRAINT illcomments_ifk
16736                   FOREIGN KEY (illrequest_id)
16737                   REFERENCES illrequests ( illrequest_id )
16738                   ON UPDATE CASCADE ON DELETE CASCADE
16739             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16740         });
16741     }
16742
16743     SetVersion( $DBversion );
16744     print "Upgrade to $DBversion done (Bug 18591 - Add comments to ILL requests)\n";
16745 }
16746
16747 $DBversion = '18.06.00.047';
16748 if( CheckVersion( $DBversion ) ) {
16749     # insert the authorized_value_category for CONTROL_NUM_SEQUENCE
16750     $dbh->do( "INSERT IGNORE INTO authorised_value_categories values ('CONTROL_NUM_SEQUENCE');" );
16751     SetVersion( $DBversion );
16752     print "Upgrade to $DBversion done (Bug 19263 - Advanced Editor - Rancor - Add auto control number (001) widget)\n";
16753 }
16754
16755 $DBversion = '18.06.00.048';
16756 if( CheckVersion( $DBversion ) ) {
16757     $dbh->do( "ALTER TABLE stockrotationrotas CHANGE COLUMN description description text" );
16758     SetVersion( $DBversion );
16759     print "Upgrade to $DBversion done (Bug 21682 - Remove default on stockrotationrotas.description)\n";
16760 }
16761
16762 $DBversion = '18.06.00.049';
16763 if( CheckVersion( $DBversion ) ) {
16764     $dbh->do(q{
16765         UPDATE letter SET content = REPLACE(content,"item.reason ne \'in-demand\'","item.reason != \'in-demand\'")
16766         WHERE code="SR_SLIP";
16767     });
16768     print "Upgrade to $DBversion done (Bug 21656 - Stock Rotation Notice, Template Toolkit Syntax Correction)\n";
16769     SetVersion( $DBversion );
16770 }
16771
16772 $DBversion = '18.06.00.050';
16773 if( CheckVersion( $DBversion ) ) {
16774     $dbh->do(q{
16775         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');
16776     });
16777     print "Upgrade to $DBversion done (Bug 14385 - Add OpacHiddenItemExceptions)\n";
16778     SetVersion( $DBversion );
16779 }
16780
16781 $DBversion = '18.06.00.051';
16782 if( CheckVersion( $DBversion ) ) {
16783     $dbh->do(q{
16784         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES
16785         ('AdlibrisCoversEnabled', '0', NULL, 'Display cover images in OPAC results and detail listing from Swedish retailer Adlibris.','YesNo'),
16786         ('AdlibrisCoversURL', 'http://www.adlibris.com/se/organisationer/showimagesafe.aspx', NULL, 'Base URL for Adlibris cover image web service.', 'Free');
16787     });
16788     print "Upgrade to $DBversion done (Bug 8630 - Add covers from AdLibris to the OPAC and Intranet)\n";
16789     SetVersion( $DBversion );
16790 }
16791
16792 $DBversion = '18.06.00.052';
16793 if( CheckVersion( $DBversion ) ) {
16794     $dbh->do(q{
16795         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
16796            ( 3, 'manage_sysprefs', 'Manage global system preferences'),
16797            ( 3, 'manage_libraries', 'Manage libraries and library groups'),
16798            ( 3, 'manage_itemtypes', 'Manage item types'),
16799            ( 3, 'manage_auth_values', 'Manage authorized values'),
16800            ( 3, 'manage_patron_categories', 'Manage patron categories'),
16801            ( 3, 'manage_patron_attributes', 'Manage extended patron attributes'),
16802            ( 3, 'manage_transfers', 'Manage library transfer limits and transport cost matrix'),
16803            ( 3, 'manage_item_circ_alerts', 'Manage item circulation alerts'),
16804            ( 3, 'manage_cities', 'Manage cities and towns'),
16805            ( 3, 'manage_marc_frameworks', 'Manage MARC bibliographic and authority frameworks'),
16806            ( 3, 'manage_keywords2koha_mappings', 'Manage keywords to Koha mappings'),
16807            ( 3, 'manage_classifications', 'Manage classification sources'),
16808            ( 3, 'manage_matching_rules', 'Manage record matching rules'),
16809            ( 3, 'manage_oai_sets', 'Manage OAI sets'),
16810            ( 3, 'manage_item_search_fields', 'Manage item search fields'),
16811            ( 3, 'manage_search_engine_config', 'Manage search engine configuration'),
16812            ( 3, 'manage_search_targets', 'Manage Z39.50 and SRU server configuration'),
16813            ( 3, 'manage_didyoumean', 'Manage Did you mean? configuration'),
16814            ( 3, 'manage_column_config', 'Manage column configuration'),
16815            ( 3, 'manage_sms_providers', 'Manage SMS cellular providers'),
16816            ( 3, 'manage_audio_alerts', 'Manage audio alerts'),
16817            ( 3, 'manage_usage_stats', 'Manage usage statistics settings');
16818     });
16819     $dbh->do(q{
16820         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16821             SELECT borrowernumber, 3, 'manage_sysprefs' 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_libraries' 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_itemtypes' 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_auth_values' 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_categories' 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_patron_attributes' 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_transfers' 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_item_circ_alerts' 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_cities' 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_marc_frameworks' 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_keywords2koha_mappings' 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_classifications' 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_matching_rules' 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_oai_sets' 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_item_search_fields' 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_engine_config' 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_search_targets' 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_didyoumean' 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_column_config' 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_sms_providers' 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_audio_alerts' 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_usage_stats' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16906     });
16907     $dbh->do(q{
16908         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16909             SELECT borrowernumber, 3, 'manage_item_search_fields' FROM borrowers WHERE flags & (1 << 2);
16910     });
16911     SetVersion( $DBversion );
16912     print "Upgrade to $DBversion done (Bug 14391: Add granular permissions to the administration module)\n";
16913 }
16914
16915 $DBversion = '18.06.00.053';
16916 if( CheckVersion( $DBversion ) ) {
16917     $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')" );
16918     SetVersion( $DBversion );
16919     print "Upgrade to $DBversion done (Bug 15494 - Block renewals by arbitrary item values)\n";
16920 }
16921
16922 $DBversion = '18.06.00.054';
16923 if( CheckVersion( $DBversion ) ) {
16924     if( !column_exists( 'search_field', 'weight' ) ) {
16925         $dbh->do( "ALTER TABLE `search_field` ADD COLUMN `weight` decimal(5,2) DEFAULT NULL AFTER `type`" );
16926     }
16927     SetVersion( $DBversion );
16928     print "Upgrade to $DBversion done (Bug 18316 - Add column search_field.weight)\n";
16929 }
16930
16931 $DBversion = '18.06.00.055';
16932 if( CheckVersion( $DBversion ) ) {
16933     unless( column_exists( 'issuingrules', 'note' ) ) {
16934         $dbh->do(q|ALTER TABLE `issuingrules` ADD `note` varchar(100) default NULL AFTER `article_requests`|);
16935     }
16936     SetVersion( $DBversion );
16937     print "Upgrade to $DBversion done (Bug 12365: Add column issuingrules.note)\n";
16938 }
16939
16940 $DBversion = '18.06.00.056';
16941 if( CheckVersion( $DBversion ) ) {
16942
16943     # All attributes we're potentially interested in
16944     my $ff_req = $dbh->selectall_arrayref(
16945         'SELECT a.illrequest_id, a.type, a.value '.
16946         'FROM illrequests r, illrequestattributes a '.
16947         'WHERE r.illrequest_id = a.illrequest_id '.
16948         'AND r.backend = "FreeForm"',
16949         { Slice => {} }
16950     );
16951
16952     # Before we go any further, identify whether we've done
16953     # this before, we test for the presence of "container_title"
16954     # We stop as soon as we find one
16955     foreach my $req(@{$ff_req}) {
16956         if ($req->{type} eq 'container_title') {
16957             warn "Upgrade already carried out";
16958         }
16959     }
16960
16961     # Transform into a hashref with the key of the request ID
16962     my $requests = {};
16963     foreach my $request(@{$ff_req}) {
16964         my $id = $request->{illrequest_id};
16965         if (!exists $requests->{$id}) {
16966             $requests->{$id} = {};
16967         }
16968         $requests->{$id}->{$request->{type}} = $request->{value};
16969     }
16970
16971     # Transform any article requests
16972     my $transformed = {};
16973     foreach my $id(keys %{$requests}) {
16974         if (lc($requests->{$id}->{type}) eq 'article') {
16975             $transformed->{$id} = $requests->{$id};
16976             $transformed->{$id}->{type} = 'article';
16977             $transformed->{$id}->{container_title} = $transformed->{$id}->{title}
16978                 if defined $transformed->{$id}->{title} &&
16979                     length $transformed->{$id}->{title} > 0;
16980             $transformed->{$id}->{title} = $transformed->{$id}->{article_title}
16981                 if defined $transformed->{$id}->{article_title} &&
16982                     length $transformed->{$id}->{article_title} > 0;
16983             $transformed->{$id}->{author} = $transformed->{$id}->{article_author}
16984                 if defined $transformed->{$id}->{article_author} &&
16985                     length $transformed->{$id}->{article_author} > 0;
16986             $transformed->{$id}->{pages} = $transformed->{$id}->{article_pages}
16987                 if defined $transformed->{$id}->{article_pages} &&
16988                     length $transformed->{$id}->{article_pages} > 0;
16989         }
16990     }
16991
16992     # Now write back the transformed data
16993     # Rather than selectively replace, we just remove all attributes we've
16994     # transformed and re-write them
16995     my @changed = keys %{$transformed};
16996     my $changed_str = join(',', @changed);
16997
16998     if (scalar @changed > 0) {
16999         my ($raise_error) = $dbh->{RaiseError};
17000         $dbh->{AutoCommit} = 0;
17001         $dbh->{RaiseError} = 1;
17002         eval {
17003             my $del = $dbh->do(
17004                 "DELETE FROM illrequestattributes ".
17005                 "WHERE illrequest_id IN ($changed_str)"
17006             );
17007             foreach my $reqid(keys %{$transformed}) {
17008                 my $attr = $transformed->{$reqid};
17009                 foreach my $key(keys %{$attr}) {
17010                     my $sth = $dbh->prepare(
17011                         'INSERT INTO illrequestattributes '.
17012                         '(illrequest_id, type, value) '.
17013                         'VALUES '.
17014                         '(?, ?, ?)'
17015                     );
17016                     $sth->execute(
17017                         $reqid,
17018                         $key,
17019                         $attr->{$key}
17020                     );
17021                 }
17022             }
17023             $dbh->commit;
17024         };
17025
17026         if ($@) {
17027             warn "Upgrade to $DBversion failed: $@\n";
17028             eval { $dbh->rollback };
17029         } else {
17030             SetVersion( $DBversion );
17031             print "Upgrade to $DBversion done (Bug 21079 - Unify metadata schema across backends)\n";
17032         }
17033
17034         $dbh->{AutoCommit} = 1;
17035         $dbh->{RaiseError} = $raise_error;
17036     }
17037
17038 }
17039
17040 $DBversion = '18.06.00.057';
17041 if( CheckVersion( $DBversion ) ) {
17042     # System preferences
17043     $dbh->do(q{
17044         INSERT IGNORE INTO `systempreferences` (`variable`,`value`,`explanation`,`options`,`type`)
17045         VALUES ('showLastPatron','0','','If ON, enables the last patron feature in the intranet','YesNo');
17046     });
17047     SetVersion( $DBversion );
17048     print "Upgrade to $DBversion done (Bug 20312 - Add showLastPatron systempreference)\n";
17049 }
17050
17051 $DBversion = '18.06.00.058';
17052 if( CheckVersion( $DBversion ) ) {
17053     $dbh->do(q{
17054         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES
17055         ('MarcFieldForCreatorId','',NULL,'Where to store the borrowernumber of the record''s creator','Free'),
17056         ('MarcFieldForCreatorName','',NULL,'Where to store the name of the record''s creator','Free'),
17057         ('MarcFieldForModifierId','',NULL,'Where to store the borrowernumber of the record''s last modifier','Free'),
17058         ('MarcFieldForModifierName','',NULL,'Where to store the name of the record''s last modifier','Free')
17059     });
17060
17061     SetVersion( $DBversion );
17062     print "Upgrade to $DBversion done (Bug 19349 - Add system preferences MarcFieldForCreatorId, MarcFieldForCreatorName, MarcFieldForModifierId, MarcFieldForModifierName)\n";
17063 }
17064
17065 $DBversion = '18.06.00.059';
17066 if( CheckVersion( $DBversion ) ) {
17067     $dbh->do(q{
17068         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type`) VALUES  ('EmailSMSSendDriverFromAddress', '', '', 'Email SMS send driver from address override', 'Free');
17069     });
17070     SetVersion( $DBversion );
17071     print "Upgrade to $DBversion done (Bug 20356 - Add EmailSMSSendDriverFromAddress system preference)\n";
17072 }
17073
17074 $DBversion = '18.06.00.060';
17075 if( CheckVersion( $DBversion ) ) {
17076     unless( TableExists( 'class_split_rules' ) ) {
17077         $dbh->do(q|
17078             CREATE TABLE class_split_rules (
17079               class_split_rule varchar(10) NOT NULL default '',
17080               description LONGTEXT,
17081               split_routine varchar(30) NOT NULL default '',
17082               split_regex varchar(255) NOT NULL default '',
17083               PRIMARY KEY (class_split_rule),
17084               UNIQUE KEY class_split_rule_idx (class_split_rule)
17085             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
17086         |);
17087
17088         $dbh->do(q|
17089             ALTER TABLE class_sources
17090             ADD COLUMN class_split_rule varchar(10) NOT NULL default ''
17091             AFTER class_sort_rule
17092         |);
17093
17094         $dbh->do(q|
17095             UPDATE class_sources
17096             SET class_split_rule = class_sort_rule
17097         |);
17098
17099         $dbh->do(q|
17100             UPDATE class_sources
17101             SET class_split_rule = 'generic'
17102             WHERE class_split_rule NOT IN('dewey', 'generic', 'lcc')
17103         |);
17104
17105         $dbh->do(q|
17106             INSERT INTO class_split_rules(class_split_rule, description, split_routine)
17107             VALUES
17108             ('dewey', 'Default sorting rules for DDC', 'Dewey'),
17109             ('lcc', 'Default sorting rules for LCC', 'LCC'),
17110             ('generic', 'Generic call number sorting rules', 'Generic')
17111         |);
17112
17113         $dbh->do(q|
17114             ALTER TABLE class_sources
17115             ADD CONSTRAINT class_source_ibfk_2 FOREIGN KEY (class_split_rule)
17116             REFERENCES class_split_rules (class_split_rule)
17117         |);
17118     }
17119
17120     SetVersion( $DBversion );
17121     print "Upgrade to $DBversion done (Bug 15836 - Add class_sort_rules.split_routine and split_regex)\n";
17122 }
17123
17124 $DBversion = '18.06.00.061';
17125 if ( CheckVersion($DBversion) ) {
17126     $dbh->do(q{
17127         INSERT IGNORE INTO `systempreferences` (`variable`,`value`,`explanation`,`options`,`type`) VALUES
17128         ('ElasticsearchIndexStatus_biblios', '0', 'Biblios index status', NULL, NULL),
17129         ('ElasticsearchIndexStatus_authorities', '0', 'Authorities index status', NULL, NULL)
17130     });
17131     SetVersion($DBversion);
17132     print "Upgrade to $DBversion done (Bug 19893 - Add elasticsearch index status preferences)\n";
17133 }
17134
17135 $DBversion = '18.06.00.062';
17136 if( CheckVersion( $DBversion ) ) {
17137     $dbh->do( "INSERT IGNORE INTO authorised_value_categories (category_name) VALUES ('PA_CLASS');");
17138     SetVersion( $DBversion );
17139     print "Upgrade to $DBversion done (Bug 21730: Add new authorised value category PA_CLASS)\n";
17140 }
17141
17142 $DBversion = '18.11.00.000';
17143 if( CheckVersion( $DBversion ) ) {
17144     SetVersion( $DBversion );
17145     print "Upgrade to $DBversion done (18.11.00 release)\n";
17146 }
17147
17148 $DBversion = '18.12.00.000';
17149 if( CheckVersion( $DBversion ) ) {
17150     SetVersion( $DBversion );
17151     print "Upgrade to $DBversion done (...and Steven!)\n";
17152 }
17153
17154 $DBversion = '18.12.00.001';
17155 if( CheckVersion( $DBversion ) ) {
17156     $dbh->do(q{
17157         UPDATE permissions SET code = 'manage_didyoumean' WHERE code = 'manage_didyouean';
17158     });
17159     $dbh->do(q{
17160         UPDATE user_permissions SET code = 'manage_didyoumean' WHERE code = 'manage_didyouean';
17161     });
17162     SetVersion( $DBversion );
17163     print "Upgrade to $DBversion (Bug 21961 - Fix typo in manage_didyoumean permission)\n";
17164 }
17165
17166 $DBversion = '18.12.00.002';
17167 if( CheckVersion( $DBversion ) ) {
17168     my $sth = $dbh->prepare(q|SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_NAME='accountlines_ibfk_1'|);
17169     $sth->execute;
17170     if ($sth->fetchrow_hashref) {
17171         $dbh->do(q|
17172             ALTER TABLE accountlines DROP FOREIGN KEY accountlines_ibfk_1;
17173         |);
17174         $dbh->do(q|
17175             ALTER TABLE accountlines CHANGE COLUMN borrowernumber borrowernumber INT(11) DEFAULT NULL;
17176         |);
17177         $dbh->do(q|
17178             ALTER TABLE accountlines ADD CONSTRAINT accountlines_ibfk_borrowers FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE SET NULL ON UPDATE CASCADE;
17179         |);
17180     }
17181     SetVersion( $DBversion );
17182     print "Upgrade to $DBversion done (Bug 21065 - Set ON DELETE SET NULL on accountlines.borrowernumber)\n";
17183 }
17184
17185 $DBversion = '18.12.00.003';
17186 if( CheckVersion( $DBversion ) ) {
17187     # On a new installation the class_sources.sql will have failed, so we need to add all missing data
17188     my( $sort_cnt ) = $dbh->selectrow_array( q|SELECT COUNT(*) FROM class_sort_rules|);
17189     if( !$sort_cnt ) {
17190         $dbh->do(q|INSERT INTO `class_sort_rules` (`class_sort_rule`, `description`, `sort_routine`) VALUES
17191                                ('dewey', 'Default filing rules for DDC', 'Dewey'),
17192                                ('lcc', 'Default filing rules for LCC', 'LCC'),
17193                                ('generic', 'Generic call number filing rules', 'Generic')
17194             |);
17195     }
17196
17197     my ( $split_cnt ) = $dbh->selectrow_array( q|SELECT COUNT(*) FROM class_split_rules|);
17198     if( !$split_cnt ) {
17199         $dbh->do(q|INSERT INTO `class_split_rules` (`class_split_rule`, `description`, `split_routine`) VALUES
17200                                ('dewey', 'Default splitting rules for DDC', 'Dewey'),
17201                                ('lcc', 'Default splitting rules for LCC', 'LCC'),
17202                                ('generic', 'Generic call number splitting rules', 'Generic')
17203             |);
17204     }
17205
17206     my( $source_cnt ) = $dbh->selectrow_array( q|SELECT COUNT(*) FROM class_sources|);
17207     if( !$source_cnt ) {
17208         $dbh->do(q|INSERT INTO `class_sources` (`cn_source`, `description`, `used`, `class_sort_rule`, `class_split_rule`) VALUES
17209                             ('ddc', 'Dewey Decimal Classification', 1, 'dewey', 'dewey'),
17210                             ('lcc', 'Library of Congress Classification', 1, 'lcc', 'lcc'),
17211                             ('udc', 'Universal Decimal Classification', 0, 'generic', 'generic'),
17212                             ('sudocs', 'SuDoc Classification (U.S. GPO)', 0, 'generic', 'generic'),
17213                             ('anscr', 'ANSCR (Sound Recordings)', 0, 'generic', 'generic'),
17214                             ('z', 'Other/Generic Classification Scheme', 0, 'generic', 'generic')
17215             |);
17216
17217     }
17218
17219     SetVersion( $DBversion );
17220     print "Upgrade to $DBversion done (Bug 22024 - Add missing splitting rule definitions)\n";
17221 }
17222
17223 $DBversion = '18.12.00.004';
17224 if( CheckVersion( $DBversion ) ) {
17225     if( !column_exists( 'accountlines', 'branchcode' ) ) {
17226         $dbh->do("ALTER TABLE accountlines ADD branchcode VARCHAR( 10 ) NULL DEFAULT NULL AFTER manager_id");
17227         $dbh->do("ALTER TABLE accountlines ADD CONSTRAINT accountlines_ibfk_branches FOREIGN KEY (branchcode) REFERENCES branches (branchcode) ON DELETE SET NULL ON UPDATE CASCADE");
17228     }
17229     SetVersion( $DBversion );
17230     print "Upgrade to $DBversion done (Bug 19066 - Add branchcode to accountlines)\n";
17231 }
17232
17233 $DBversion = '18.12.00.005';
17234 if( CheckVersion( $DBversion ) ) {
17235     $dbh->do(q{
17236         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
17237         ('OverDriveUsername','cardnumber','cardnumber|userid','Which patron information should be passed as OverDrive username','Choice')
17238     });
17239     SetVersion( $DBversion );
17240     print "Upgrade to $DBversion done (Bug 22030: Add OverDriveUsername syspref)\n";
17241 }
17242
17243 $DBversion = '18.12.00.006';
17244 if( CheckVersion( $DBversion ) ) {
17245     $dbh->do(q{
17246         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
17247         ('AccountAutoReconcile','0','If enabled, patron balances will get reconciled automatically on each transaction.',NULL,'YesNo');
17248     });
17249     SetVersion($DBversion);
17250     print "Upgrade to $DBversion done (Bug 21915 - Add a way to automatically reconcile balance for patrons)\n";
17251 }
17252
17253 $DBversion = '18.12.00.007';
17254 if( CheckVersion( $DBversion ) ) {
17255     if( column_exists( 'issuingrules', 'chargename' ) ) {
17256         $dbh->do( "ALTER TABLE issuingrules DROP chargename" );
17257     }
17258     SetVersion( $DBversion );
17259     print "Upgrade to $DBversion done (Bug 21753: Drop chargename from issuingrules )\n";
17260 }
17261
17262 $DBversion = '18.12.00.008';
17263 if( CheckVersion( $DBversion ) ) {
17264     if( !column_exists( 'subscription', 'mana_id' ) ) {
17265         $dbh->do( "ALTER TABLE subscription ADD mana_id int(11) NULL DEFAULT NULL" );
17266     }
17267
17268     if( !column_exists( 'saved_sql', 'mana_id' ) ) {
17269         $dbh->do( "ALTER TABLE saved_sql ADD mana_id int(11) NULL DEFAULT NULL" );
17270     }
17271     $dbh->do(q{
17272         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
17273         ('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');
17274     });
17275     $dbh->do(q{
17276         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
17277         ('AutoShareWithMana','','','defines datas automatically shared with mana','multiple');
17278     });
17279     $dbh->do(q{
17280         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
17281         ('ManaToken','',NULL,'Security token used for authentication on Mana KB service (anti spam)','Textarea');
17282     });
17283     SetVersion( $DBversion );
17284     print "Upgrade to $DBversion done (Bug 17047 - Mana knowledge base)\n";
17285 }
17286
17287 $DBversion = '18.12.00.009';
17288 if( CheckVersion( $DBversion ) ) {
17289     $dbh->do(q{
17290         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');
17291     });
17292     SetVersion( $DBversion );
17293     print "Upgrade to $DBversion done (Bug 21241 - Add FallbackToSMSIfNoEmail syspref )\n";
17294 }
17295
17296 $DBversion = '18.12.00.010';
17297 if( CheckVersion( $DBversion ) ) {
17298     $dbh->do(q{
17299         INSERT IGNORE INTO systempreferences
17300             ( variable, value, options, explanation, type )
17301         VALUES
17302             ('RESTPublicAPI','1',NULL,'If enabled, the REST API will expose the /public endpoints.','YesNo')
17303     });
17304
17305     # Always end with this (adjust the bug info)
17306     SetVersion( $DBversion );
17307     print "Upgrade to $DBversion done (Bug 22061 - Add a /public namespace that can be switched on/off)\n";
17308 }
17309
17310 $DBversion = '18.12.00.011';
17311 if( CheckVersion( $DBversion ) ) {
17312     if ( column_exists( 'biblio_metadata', 'marcflavour' ) ) {
17313         $dbh->do(q{
17314             ALTER TABLE biblio_metadata
17315                 CHANGE COLUMN marcflavour `schema` VARCHAR(16)
17316         });
17317     }
17318     if ( column_exists( 'deletedbiblio_metadata', 'marcflavour' ) ) {
17319         $dbh->do(q{
17320             ALTER TABLE deletedbiblio_metadata
17321                 CHANGE COLUMN marcflavour `schema` VARCHAR(16)
17322         });
17323     }
17324     SetVersion( $DBversion );
17325     print "Upgrade to $DBversion done (Bug 22155 - biblio_metadata.marcflavour should be renamed 'schema')\n";
17326 }
17327
17328 $DBversion = '18.12.00.012';
17329 if( CheckVersion( $DBversion ) ) {
17330     $dbh->do(q{
17331         INSERT IGNORE INTO systempreferences
17332             (variable, value, options, explanation, type )
17333         VALUES
17334             ('RESTBasicAuth','0',NULL,'If enabled, Basic authentication is enabled for the REST API.','YesNo')
17335     });
17336     SetVersion( $DBversion );
17337     print "Upgrade to $DBversion done (Bug 22132 - Add Basic authentication)\n";
17338 }
17339
17340 $DBversion = '18.12.00.013';
17341 if( CheckVersion( $DBversion ) ) {
17342     $dbh->do(q{
17343         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES ( 3, 'manage_mana', 'Manage Mana KB content sharing');
17344     });
17345     SetVersion( $DBversion );
17346     print "Upgrade to $DBversion done (Bug 22198 - Add ghranular permission setting for Mana KB)\n";
17347 }
17348
17349 $DBversion = '18.12.00.014';
17350 if( CheckVersion( $DBversion ) ) {
17351     unless( foreign_key_exists( 'messages', 'messages_borrowernumber' ) ) {
17352         $dbh->do(q|
17353             DELETE m FROM messages m
17354             LEFT JOIN borrowers b ON m.borrowernumber=b.borrowernumber
17355             WHERE b.borrowernumber IS NULL
17356         |);
17357         $dbh->do(q|
17358             ALTER TABLE messages
17359             ADD CONSTRAINT messages_borrowernumber
17360             FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
17361         |);
17362     }
17363     SetVersion( $DBversion );
17364     print "Upgrade to $DBversion done (Bug 13515 - Add a FOREIGN KEY constaint on messages.borrowernumber)\n";
17365 }
17366
17367 $DBversion = '18.12.00.015';
17368 if( CheckVersion( $DBversion ) ) {
17369     $dbh->do( "UPDATE action_logs SET info = REPLACE(info,'cardnumber_replaced','cardnumber'), timestamp = timestamp WHERE module='MEMBERS' AND action='MODIFY'" );
17370     $dbh->do( "UPDATE action_logs SET info = REPLACE(info,'previous_cardnumber','before'), timestamp = timestamp WHERE module='MEMBERS' AND action='MODIFY'" );
17371     $dbh->do( "UPDATE action_logs SET info = REPLACE(info,'new_cardnumber','after'), timestamp = timestamp WHERE module='MEMBERS' AND action='MODIFY'" );
17372
17373     SetVersion( $DBversion );
17374     print "Upgrade to $DBversion done (Bug 3820 - Update patron modification logs)\n";
17375 }
17376
17377 $DBversion = '18.12.00.016';
17378 if( CheckVersion( $DBversion ) ) {
17379
17380     if ( !column_exists( 'illrequests', 'status_alias' ) ) {
17381         # Fresh upgrade, just add the column and constraint
17382         $dbh->do( "ALTER TABLE illrequests ADD COLUMN status_alias varchar(80) DEFAULT NULL AFTER status" );
17383     } else {
17384         # Migrate all existing foreign keys from referencing authorised_values.id
17385         # to referencing authorised_values.authorised_value
17386         # First remove the foreign key constraint and index
17387         if ( foreign_key_exists( 'illrequests', 'illrequests_safk' ) ) {
17388             $dbh->do( "ALTER TABLE illrequests DROP FOREIGN KEY illrequests_safk");
17389         }
17390         if ( index_exists( 'illrequests', 'illrequests_safk' ) ) {
17391             $dbh->do( "DROP INDEX illrequests_safk ON illrequests" );
17392         }
17393         # Now change the illrequests.status_alias column definition from int to varchar
17394         $dbh->do( "ALTER TABLE illrequests MODIFY COLUMN status_alias varchar(80)" );
17395         # Now replace all references to authorised_values.id with their
17396         # corresponding authorised_values.authorised_value
17397         my $sth = $dbh->prepare( "SELECT illrequest_id, status_alias FROM illrequests WHERE status_alias IS NOT NULL" );
17398         $sth->execute();
17399         while (my @row = $sth->fetchrow_array()) {
17400             my $r_id = $row[0];
17401             my $av_id = $row[1];
17402             # Get the authorised value's authorised_value value
17403             my ($av_val) = $dbh->selectrow_array( "SELECT authorised_value FROM authorised_values WHERE id = ?", {}, $av_id );
17404             # Now update illrequests.status_alias
17405             if ($av_val) {
17406                 $dbh->do( "UPDATE illrequests SET status_alias = ? WHERE illrequest_id = ?", {}, ($av_val, $r_id) );
17407             }
17408         }
17409     }
17410     if ( !foreign_key_exists( 'illrequests', 'illrequests_safk' ) ) {
17411         $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" );
17412     }
17413     $dbh->do( "INSERT IGNORE INTO authorised_value_categories SET category_name = 'ILLSTATUS'");
17414
17415     SetVersion( $DBversion );
17416     print "Upgrade to $DBversion done (Bug 20581 - Allow manual selection of custom ILL request statuses)\n";
17417 }
17418
17419 $DBversion = '18.12.00.017';
17420 if( CheckVersion( $DBversion ) ) {
17421     $dbh->do(q{
17422         INSERT IGNORE INTO account_offset_types ( type ) VALUES ( 'fine_increase' ), ( 'fine_decrease' );
17423     });
17424     $dbh->do(q{
17425         UPDATE account_offsets SET type = 'fine_increase' WHERE type = 'Fine Update' AND amount > 0;
17426     });
17427     $dbh->do(q{
17428         UPDATE account_offsets SET type = 'fine_decrease' WHERE type = 'Fine Update' AND amount < 0;
17429     });
17430
17431     $dbh->do(q{
17432         DELETE FROM account_offset_types WHERE type = 'Fine Update';
17433     });
17434     SetVersion( $DBversion );
17435     print "Upgrade to $DBversion done (Bug 21747 - Update account_offset_types to include 'fine_increase' and 'fine_decrease')\n";
17436 }
17437
17438 $DBversion = '18.12.00.018';
17439 if( CheckVersion( $DBversion ) ) {
17440   $dbh->do( "UPDATE `search_field` SET `name` = 'date-of-publication', `label` = 'date-of-publication' WHERE `name` = 'pubdate'" );
17441   $dbh->do( "UPDATE `search_field` SET `name` = 'title-series', `label` = 'title-series' WHERE `name` = 'se'" );
17442   $dbh->do( "UPDATE `search_field` SET `name` = 'identifier-standard', `label` = 'identifier-standard' WHERE `name` = 'identifier-standard'" );
17443   $dbh->do( "UPDATE `search_field` SET `name` = 'author', `label` = 'author' WHERE `name` = 'author'" );
17444   $dbh->do( "UPDATE `search_field` SET `name` = 'control-number', `label` = 'control-number' WHERE `name` = 'control-number'" );
17445   $dbh->do( "UPDATE `search_field` SET `name` = 'place-of-publication', `label` = 'place-of-publication' WHERE `name` = 'place'" );
17446   $dbh->do( "UPDATE `search_field` SET `name` = 'date-of-acquisition', `label` = 'date-of-acquisition' WHERE `name` = 'acqdate'" );
17447   $dbh->do( "UPDATE `search_field` SET `name` = 'isbn', `label` = 'isbn' WHERE `name` = 'isbn'" );
17448   $dbh->do( "UPDATE `search_field` SET `name` = 'koha-auth-number', `label` = 'koha-auth-number' WHERE `name` = 'an'" );
17449   $dbh->do( "UPDATE `search_field` SET `name` = 'subject', `label` = 'subject' WHERE `name` = 'subject'" );
17450   $dbh->do( "UPDATE `search_field` SET `name` = 'publisher', `label` = 'publisher' WHERE `name` = 'publisher'" );
17451   $dbh->do( "UPDATE `search_field` SET `name` = 'record-source', `label` = 'record-source' WHERE `name` = 'record-source'" );
17452   $dbh->do( "UPDATE `search_field` SET `name` = 'title', `label` = 'title' WHERE `name` = 'title'" );
17453   $dbh->do( "UPDATE `search_field` SET `name` = 'local-classification', `label` = 'local-classification' WHERE `name` = 'local-classification'" );
17454   $dbh->do( "UPDATE `search_field` SET `name` = 'bib-level', `label` = 'bib-level' WHERE `name` = 'bib-level'" );
17455   $dbh->do( "UPDATE `search_field` SET `name` = 'microform-generation', `label` = 'microform-generation' WHERE `name` = 'microform-generation'" );
17456   $dbh->do( "UPDATE `search_field` SET `name` = 'material-type', `label` = 'material-type' WHERE `name` = 'material-type'" );
17457   $dbh->do( "UPDATE `search_field` SET `name` = 'bgf-number', `label` = 'bgf-number' WHERE `name` = 'bgf-number'" );
17458   $dbh->do( "UPDATE `search_field` SET `name` = 'number-db', `label` = 'number-db' WHERE `name` = 'number-db'" );
17459   $dbh->do( "UPDATE `search_field` SET `name` = 'number-natl-biblio', `label` = 'number-natl-biblio' WHERE `name` = 'number-natl-biblio'" );
17460   $dbh->do( "UPDATE `search_field` SET `name` = 'number-legal-deposit', `label` = 'number-legal-deposit' WHERE `name` = 'number-legal-deposit'" );
17461   $dbh->do( "UPDATE `search_field` SET `name` = 'issn', `label` = 'issn' WHERE `name` = 'issn'" );
17462   $dbh->do( "UPDATE `search_field` SET `name` = 'local-number', `label` = 'local-number' WHERE `name` = 'local-number'" );
17463   $dbh->do( "UPDATE `search_field` SET `name` = 'suppress', `label` = 'supress' WHERE `name` = 'suppress'" );
17464   $dbh->do( "UPDATE `search_field` SET `name` = 'bnb-card-number', `label` = 'bnb-card-number' WHERE `name` = 'bnb-card-number'" );
17465   $dbh->do( "UPDATE `search_field` SET `name` = 'date/time-last-modified', `label` = 'date/time-last-modified' WHERE `name` = 'date-time-last-modified'" );
17466   $dbh->do( "DELETE FROM `search_field` WHERE `name` = 'lc-cardnumber'" );
17467   $dbh->do( "DELETE FROM `search_marc_map` WHERE `id` NOT IN(SELECT `search_marc_map_id` FROM `search_marc_to_field`)" );
17468   SetVersion( $DBversion );
17469   print "Upgrade to $DBversion done (Bug 19575 - Use canonical field names and resolve aliased fields)\n";
17470 }
17471
17472 $DBversion = '18.12.00.019';
17473 if( CheckVersion( $DBversion ) ) {
17474     $dbh->do(q{
17475         INSERT IGNORE INTO account_offset_types ( type ) VALUES ( 'Reserve Fee' );
17476     });
17477
17478     SetVersion( $DBversion );
17479     print "Upgrade to $DBversion done (Bug 21728 - Add 'Reserve Fee' to the account_offset_types table if missing)\n";
17480 }
17481
17482 $DBversion = '18.12.00.020';
17483 if( CheckVersion( $DBversion ) ) {
17484     if ( TableExists( 'branch_borrower_circ_rules' ) ) {
17485         if ( column_exists( 'branch_borrower_circ_rules', 'maxissueqty' ) ) {
17486             $dbh->do("
17487                 INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17488                 SELECT categorycode, branchcode, NULL, 'patron_maxissueqty', COALESCE( maxissueqty, '' )
17489                 FROM branch_borrower_circ_rules
17490             ");
17491             $dbh->do("
17492                 INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17493                 SELECT categorycode, branchcode, NULL, 'patron_maxonsiteissueqty', COALESCE( maxonsiteissueqty, '' )
17494                 FROM branch_borrower_circ_rules
17495             ");
17496             $dbh->do("DROP TABLE branch_borrower_circ_rules");
17497         }
17498     }
17499
17500     if ( TableExists( 'default_borrower_circ_rules' ) ) {
17501         if ( column_exists( 'default_borrower_circ_rules', 'maxissueqty' ) ) {
17502             $dbh->do("
17503                 INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17504                 SELECT categorycode, NULL, NULL, 'patron_maxissueqty', COALESCE( maxissueqty, '' )
17505                 FROM default_borrower_circ_rules
17506             ");
17507             $dbh->do("
17508                 INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17509                 SELECT categorycode, NULL, NULL, 'patron_maxonsiteissueqty', COALESCE( maxonsiteissueqty, '' )
17510                 FROM default_borrower_circ_rules
17511             ");
17512             $dbh->do("DROP TABLE default_borrower_circ_rules");
17513         }
17514     }
17515
17516     if ( column_exists( 'default_circ_rules', 'maxissueqty' ) ) {
17517         $dbh->do("
17518             INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17519             SELECT NULL, NULL, NULL, 'patron_maxissueqty', COALESCE( maxissueqty, '' )
17520             FROM default_circ_rules
17521         ");
17522         $dbh->do("
17523             INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17524             SELECT NULL, NULL, NULL, 'patron_maxonsiteissueqty', COALESCE( maxonsiteissueqty, '' )
17525             FROM default_circ_rules
17526         ");
17527         $dbh->do("ALTER TABLE default_circ_rules DROP COLUMN maxissueqty, DROP COLUMN maxonsiteissueqty");
17528     }
17529
17530     if ( column_exists( 'default_branch_circ_rules', 'maxissueqty' ) ) {
17531         $dbh->do("
17532             INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17533             SELECT NULL, branchcode, NULL, 'patron_maxissueqty', COALESCE( maxissueqty, '' )
17534             FROM default_branch_circ_rules
17535         ");
17536         $dbh->do("
17537             INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17538             SELECT NULL, NULL, NULL, 'patron_maxonsiteissueqty', COALESCE( maxonsiteissueqty, '' )
17539             FROM default_branch_circ_rules
17540         ");
17541         $dbh->do("ALTER TABLE default_branch_circ_rules DROP COLUMN maxissueqty, DROP COLUMN maxonsiteissueqty");
17542     }
17543
17544     if ( column_exists( 'issuingrules', 'maxissueqty' ) ) {
17545         # Cleaning invalid rules before, to avoid FK contraints to fail
17546         $dbh->do(q|
17547             DELETE FROM issuingrules WHERE categorycode != '*' AND categorycode NOT IN (SELECT categorycode FROM categories);
17548         |);
17549         $dbh->do(q|
17550             DELETE FROM issuingrules WHERE branchcode != '*' AND branchcode NOT IN (SELECT branchcode FROM branches);
17551         |);
17552         $dbh->do(q|
17553             DELETE FROM issuingrules WHERE itemtype != '*' AND itemtype NOT IN (SELECT itemtype FROM itemtypes);
17554         |);
17555
17556         $dbh->do("
17557             INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17558             SELECT IF(categorycode='*', NULL, categorycode),
17559                    IF(branchcode='*', NULL, branchcode),
17560                    IF(itemtype='*', NULL, itemtype),
17561                    'maxissueqty',
17562                    COALESCE( maxissueqty, '' )
17563             FROM issuingrules
17564         ");
17565         $dbh->do("
17566             INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17567             SELECT IF(categorycode='*', NULL, categorycode),
17568                    IF(branchcode='*', NULL, branchcode),
17569                    IF(itemtype='*', NULL, itemtype),
17570                    'maxonsiteissueqty',
17571                    COALESCE( maxonsiteissueqty, '' )
17572             FROM issuingrules
17573         ");
17574         $dbh->do("ALTER TABLE issuingrules DROP COLUMN maxissueqty, DROP COLUMN maxonsiteissueqty");
17575     }
17576
17577     SetVersion( $DBversion );
17578     print "Upgrade to $DBversion done (Bug 18925 - Move maxissueqty and maxonsiteissueqty to circulation_rules)\n";
17579 }
17580
17581 $DBversion = '18.12.00.021';
17582 if ( CheckVersion($DBversion) ) {
17583
17584     if ( !column_exists( 'itemtypes', 'rentalcharge_daily' ) ) {
17585         $dbh->do("ALTER TABLE `itemtypes` ADD COLUMN `rentalcharge_daily` decimal(28,6) default NULL AFTER `rentalcharge`");
17586     }
17587
17588     if ( !column_exists( 'itemtypes', 'rentalcharge_hourly' ) ) {
17589         $dbh->do("ALTER TABLE `itemtypes` ADD COLUMN `rentalcharge_hourly` decimal(28,6) default NULL AFTER `rentalcharge_daily`");
17590     }
17591
17592     if ( column_exists( 'itemtypes', 'rental_charge_daily' ) ) {
17593         $dbh->do("UPDATE `itemtypes` SET `rentalcharge_daily` = `rental_charge_daily`");
17594         $dbh->do("ALTER TABLE `itemtypes` DROP COLUMN `rental_charge_daily`");
17595     }
17596
17597     SetVersion($DBversion);
17598     print "Upgrade to $DBversion done (Bug 20912 - Support granular rental charges)\n";
17599 }
17600
17601 $DBversion = '18.12.00.022';
17602 if( CheckVersion( $DBversion ) ) {
17603     $dbh->do( q{
17604         INSERT IGNORE INTO permissions (module_bit,code,description)
17605         VALUES
17606         (3,'manage_additional_fields','Add, edit, or delete additional custom fields for baskets or subscriptions (also requires order_manage or edit_subscription permissions)')
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 DISTINCT borrowernumber FROM user_permissions WHERE code = 'order_manage' OR code = 'edit_subscription');
17611     });
17612     $dbh->do( q{
17613         INSERT INTO user_permissions (borrowernumber, module_bit, code)
17614         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);
17615     });
17616     SetVersion( $DBversion );
17617     print "Upgrade to $DBversion done (Bug 15774 - Add permission for managing additional fields)\n";
17618 }
17619
17620 $DBversion = '18.12.00.023';
17621 if( CheckVersion( $DBversion ) ) {
17622     $dbh->do(q|
17623       INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
17624       VALUES ('ILLOpacbackends',NULL,NULL,'ILL backends to enabled for OPAC initiated requests','multiple');
17625     |);
17626
17627     # Always end with this (adjust the bug info)
17628     SetVersion( $DBversion );
17629     print "Upgrade to $DBversion done (Bug 20639 - Add ILLOpacbackends syspref)\n";
17630 }
17631
17632 $DBversion = '18.12.00.024';
17633 if ( CheckVersion($DBversion) ) {
17634
17635     # Fixup any pre-existing bad suggestedby, manageddate, accepteddate dates
17636     eval {
17637         local $dbh->{PrintError} = 0;
17638         $dbh->do(
17639             "UPDATE suggestions SET suggesteddate = '1970-01-01' WHERE suggesteddate = '0000-00-00';"
17640         );
17641         $dbh->do(
17642             "UPDATE suggestions SET manageddate = '1970-01-01' WHERE manageddate = '0000-00-00';"
17643         );
17644         $dbh->do(
17645             "UPDATE suggestions SET accepteddate = '1970-01-01' WHERE accepteddate = '0000-00-00';"
17646         );
17647     };
17648
17649     # Add constraint for suggestedby
17650     unless ( foreign_key_exists( 'suggestions', 'suggestions_ibfk_suggestedby' ) )
17651     {
17652         $dbh->do(
17653 "ALTER TABLE suggestions CHANGE COLUMN suggestedby suggestedby INT(11) NULL DEFAULT NULL;"
17654         );
17655         $dbh->do(
17656 "UPDATE suggestions LEFT JOIN borrowers ON (suggestions.suggestedby = borrowers.borrowernumber) SET suggestedby = null WHERE borrowernumber IS null"
17657         );
17658         $dbh->do(
17659 "ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_suggestedby` FOREIGN KEY (`suggestedby`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE"
17660         );
17661     }
17662
17663     # Add constraint for managedby
17664     unless ( foreign_key_exists( 'suggestions', 'suggestions_ibfk_managedby' ) )
17665     {
17666         $dbh->do(
17667 "UPDATE suggestions LEFT JOIN borrowers ON (suggestions.managedby = borrowers.borrowernumber) SET managedby = null WHERE borrowernumber IS NULL"
17668         );
17669         $dbh->do(
17670 "ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_managedby` FOREIGN KEY (`managedby`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE"
17671         );
17672     }
17673
17674     # Add constraint for acceptedby
17675     unless (
17676         foreign_key_exists( 'suggestions', 'suggestions_ibfk_acceptedby' ) )
17677     {
17678         $dbh->do(
17679 "UPDATE suggestions LEFT JOIN borrowers ON (suggestions.acceptedby = borrowers.borrowernumber) SET acceptedby = null WHERE borrowernumber IS NULL"
17680         );
17681         $dbh->do(
17682 "ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_acceptedby` FOREIGN KEY (`acceptedby`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE"
17683         );
17684     }
17685
17686     # Add constraint for rejectedby
17687     unless (
17688         foreign_key_exists( 'suggestions', 'suggestions_ibfk_rejectedby' ) )
17689     {
17690         $dbh->do(
17691 "UPDATE suggestions LEFT JOIN borrowers ON (suggestions.rejectedby = borrowers.borrowernumber) SET rejectedby = null WHERE borrowernumber IS null"
17692         );
17693         $dbh->do(
17694 "ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_rejectedby` FOREIGN KEY (`rejectedby`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE"
17695         );
17696     }
17697
17698     # Add constraint for biblionumber
17699     unless (
17700         foreign_key_exists( 'suggestions', 'suggestions_ibfk_biblionumber' ) )
17701     {
17702         $dbh->do(
17703 "UPDATE suggestions s LEFT JOIN biblio b ON (s.biblionumber = b.biblionumber) SET s.biblionumber = null WHERE b.biblionumber IS null"
17704         );
17705         $dbh->do(
17706 "ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_biblionumber` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE SET NULL ON UPDATE CASCADE"
17707         );
17708     }
17709
17710     # Add constraint for branchcode
17711     unless (
17712         foreign_key_exists( 'suggestions', 'suggestions_ibfk_branchcode' ) )
17713     {
17714         $dbh->do(
17715 "UPDATE suggestions s LEFT JOIN branches b ON (s.branchcode = b.branchcode) SET s.branchcode = null WHERE b.branchcode IS null"
17716         );
17717         $dbh->do(
17718 "ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_branchcode` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE SET NULL ON UPDATE CASCADE"
17719         );
17720     }
17721
17722     SetVersion($DBversion);
17723     print
17724 "Upgrade to $DBversion done (Bug 22368 - Add missing constraints to suggestions)\n";
17725 }
17726
17727 $DBversion = '18.12.00.025';
17728 if( CheckVersion( $DBversion ) ) {
17729
17730     $dbh->do('SET FOREIGN_KEY_CHECKS=0');
17731
17732     # Change columns accordingly
17733     $dbh->do(q{
17734         ALTER TABLE tags_index
17735             MODIFY COLUMN term VARCHAR(191) COLLATE utf8mb4_bin NOT NULL;
17736     });
17737
17738     $dbh->do(q{
17739         ALTER TABLE tags_approval
17740             MODIFY COLUMN term VARCHAR(191) COLLATE utf8mb4_bin NOT NULL;
17741     });
17742
17743     $dbh->do(q{
17744         ALTER TABLE tags_all
17745             MODIFY COLUMN term VARCHAR(191) COLLATE utf8mb4_bin NOT NULL;
17746     });
17747
17748     $dbh->do('SET FOREIGN_KEY_CHECKS=1');
17749
17750     SetVersion( $DBversion );
17751     print "Upgrade to $DBversion done (Bug 21846 - Using emoji as tags has broken weights)\n";
17752     my $maintenance_script = C4::Context->config("intranetdir") . "/misc/maintenance/fix_tags_weight.pl";
17753     print "WARNING: (Bug 21846) You need to manually run $maintenance_script to fix possible issues with tags.\n";
17754 }
17755
17756 $DBversion = '18.12.00.026';
17757 if( CheckVersion( $DBversion ) ) {
17758     $dbh->do( "INSERT IGNORE INTO systempreferences (variable, value, explanation, type) VALUES ('IllLog', 0, 'If ON, log information about ILL requests', 'YesNo')" );
17759
17760     SetVersion( $DBversion );
17761     print "Upgrade to $DBversion done (Bug 20750 - Allow timestamped auditing of ILL request events)\n";
17762 }
17763
17764 $DBversion = '18.12.00.027';
17765 if( CheckVersion( $DBversion ) ) {
17766     $dbh->do(q{
17767 INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
17768        ('ILLModuleUnmediated','0','','If enabled, try to immediately progress newly placed ILL requests.','YesNo');
17769     });
17770     SetVersion( $DBversion );
17771     print "Upgrade to $DBversion done (Bug 18837: Add ILLModuleUnmediated Syspref)\n";
17772 }
17773
17774 $DBversion = '18.12.00.028';
17775 if( CheckVersion( $DBversion ) ) {
17776     $dbh->do(q{
17777         INSERT IGNORE INTO account_offset_types ( type ) VALUES ( 'Account Fee' );
17778     });
17779
17780     $dbh->do(q{
17781         INSERT IGNORE INTO account_offset_types ( type ) VALUES ( 'Hold Expired' );
17782     });
17783
17784     SetVersion( $DBversion );
17785     print "Upgrade to $DBversion done (Bug 21756 - Add 'Account Fee' and 'Hold Expired' to the account_offset_types table if missing)\n";
17786 }
17787
17788 $DBversion = '18.12.00.029';
17789 if( CheckVersion( $DBversion ) ) {
17790     $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')" );
17791
17792     SetVersion( $DBversion );
17793     print "Upgrade to $DBversion done (Bug 18736 - Add syspref to control order rounding)\n";
17794 }
17795
17796 $DBversion = '18.12.00.030';
17797 if( CheckVersion( $DBversion ) ) {
17798     if( column_exists( 'accountlines', 'accountno' ) ) {
17799         $dbh->do( "ALTER TABLE accountlines DROP COLUMN accountno" );
17800     }
17801     if( column_exists( 'statistics', 'proccode' ) ) {
17802         $dbh->do( "ALTER TABLE statistics DROP COLUMN proccode" );
17803     }
17804     SetVersion( $DBversion );
17805     print "Upgrade to $DBversion done (Bug 21683 - Remove accountlines.accountno and statistics.proccode fields)\n";
17806 }
17807
17808 $DBversion = '18.12.00.031';
17809 if( CheckVersion( $DBversion ) ) {
17810
17811     # Add constraint for manager_id
17812     unless( foreign_key_exists( 'accountlines', 'accountlines_ibfk_borrowers_2' ) ) {
17813         $dbh->do("ALTER TABLE accountlines CHANGE COLUMN manager_id manager_id INT(11) NULL DEFAULT NULL");
17814         $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");
17815         $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");
17816     }
17817
17818     # Rename accountlines_ibfk_2 to accountlines_ibfk_items
17819     if ( foreign_key_exists( 'accountlines', 'accountlines_ibfk_2' ) ) {
17820         $dbh->do("ALTER TABLE accountlines DROP FOREIGN KEY accountlines_ibfk_2");
17821     }
17822     unless ( foreign_key_exists( 'accountlines', 'accountlines_ibfk_items' ) ) {
17823         $dbh->do("ALTER TABLE accountlines ADD CONSTRAINT `accountlines_ibfk_items` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE SET NULL ON UPDATE CASCADE");
17824     }
17825
17826     SetVersion( $DBversion );
17827     print "Upgrade to $DBversion done (Bug 22008 - Add missing constraints for accountlines.manager_id)\n";
17828 }
17829
17830 $DBversion = '18.12.00.032';
17831 if( CheckVersion( $DBversion ) ) {
17832     if( !column_exists( 'search_field', 'facet_order' ) ) {
17833         $dbh->do("ALTER TABLE search_field ADD COLUMN facet_order TINYINT(4) DEFAULT NULL AFTER weight");
17834     }
17835     $dbh->do("UPDATE search_field SET facet_order=1 WHERE name='author'");
17836     $dbh->do("UPDATE search_field SET facet_order=2 WHERE name='itype'");
17837     $dbh->do("UPDATE search_field SET facet_order=3 WHERE name='location'");
17838     $dbh->do("UPDATE search_field SET facet_order=4 WHERE name='su-geo'");
17839     $dbh->do("UPDATE search_field SET facet_order=5 WHERE name='title-series'");
17840     $dbh->do("UPDATE search_field SET facet_order=6 WHERE name='subject'");
17841     $dbh->do("UPDATE search_field SET facet_order=7 WHERE name='ccode'");
17842     $dbh->do("UPDATE search_field SET facet_order=8 WHERE name='holdingbranch'");
17843     $dbh->do("UPDATE search_field SET facet_order=9 WHERE name='homebranch'");
17844     SetVersion( $DBversion );
17845     print "Upgrade to $DBversion done (Bug 18235 - Elastic search - make facets configurable)\n";
17846 }
17847
17848 $DBversion = '18.12.00.033';
17849 if( CheckVersion( $DBversion ) ) {
17850     $dbh->do( "UPDATE search_field SET facet_order=10 WHERE name='ln'" );
17851     SetVersion( $DBversion );
17852     print "Upgrade to $DBversion done (Bug 18213 - Add language facets to Elasticsearch)\n";
17853 }
17854
17855 $DBversion = '18.12.00.034';
17856 if( CheckVersion( $DBversion ) ) {
17857
17858     if ( column_exists( 'accountlines', 'lastincrement' ) ) {
17859         $dbh->do("ALTER TABLE `accountlines` DROP COLUMN `lastincrement`");
17860     }
17861
17862     SetVersion( $DBversion );
17863     print "Upgrade to $DBversion done (Bug 22516 - Drop deprecated accountlines.lastincrement field)\n";
17864 }
17865
17866 $DBversion = '18.12.00.035';
17867 if( CheckVersion( $DBversion ) ) {
17868     $dbh->do( "INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type)
17869                VALUES ('MaxItemsToDisplayForBatchMod','1000',NULL,'Display up to a given number of items in a single item modification batch.','Integer')"
17870             );
17871     SetVersion( $DBversion );
17872     print "Upgrade to $DBversion done (Bug 19722 - Add a MaxItemsToDisplayForBatchMod preference)\n";
17873 }
17874
17875 $DBversion = '18.12.00.036';
17876 if ( CheckVersion($DBversion) ) {
17877
17878     my $rows = $dbh->do(
17879         qq{
17880         UPDATE `accountlines`
17881         SET
17882           `accounttype` = 'FU'
17883         WHERE
17884           `accounttype` = 'O'
17885       }
17886     );
17887
17888     SetVersion($DBversion);
17889     printf "Upgrade to $DBversion done (Bug 22518 - Fix accounttype 'O' to 'FU' - %d updated)\n", $rows;
17890 }
17891
17892 $DBversion = '18.12.00.037';
17893 if( CheckVersion( $DBversion ) ) {
17894
17895     $dbh->do( "UPDATE issues SET renewals = 0 WHERE renewals IS NULL" );
17896     $dbh->do( "UPDATE old_issues SET renewals = 0 WHERE renewals IS NULL" );
17897
17898     $dbh->do( "ALTER TABLE issues MODIFY COLUMN renewals tinyint(4) NOT NULL default 0");
17899     $dbh->do( "ALTER TABLE old_issues MODIFY COLUMN renewals tinyint(4) NOT NULL default 0");
17900
17901     # Always end with this (adjust the bug info)
17902     SetVersion( $DBversion );
17903     print "Upgrade to $DBversion done (Bug 22607 - Set default value of issues.renewals to 0)\n";
17904 }
17905
17906 $DBversion = '18.12.00.038';
17907 if ( CheckVersion($DBversion) ) {
17908
17909     if ( !column_exists( 'accountlines', 'status' ) ) {
17910         $dbh->do(
17911             qq{
17912             ALTER TABLE `accountlines`
17913             ADD
17914               `status` varchar(16) DEFAULT NULL
17915             AFTER
17916               `accounttype`
17917           }
17918         );
17919     }
17920
17921     SetVersion($DBversion);
17922     print "Upgrade to $DBversion done (Bug 22512 - Add status to accountlines)\n";
17923 }
17924
17925 $DBversion = '18.12.00.039';
17926 if ( CheckVersion($DBversion) ) {
17927
17928     if ( !column_exists( 'accountlines', 'interface' ) ) {
17929         $dbh->do(
17930             qq{
17931             ALTER TABLE `accountlines`
17932             ADD
17933               `interface` varchar(16)
17934             AFTER
17935               `manager_id`;
17936           }
17937         );
17938     }
17939
17940     $dbh->do(qq{
17941         UPDATE
17942           `accountlines`
17943         SET
17944           interface = 'opac'
17945         WHERE
17946           borrowernumber = manager_id;
17947     });
17948
17949     $dbh->do(qq{
17950         UPDATE
17951           `accountlines`
17952         SET
17953           interface = 'cron'
17954         WHERE
17955           manager_id IS NULL
17956         AND
17957           branchcode IS NULL;
17958     });
17959
17960     $dbh->do(qq{
17961         UPDATE
17962           `accountlines`
17963         SET
17964           interface = 'intranet'
17965         WHERE
17966           interface IS NULL;
17967     });
17968
17969     $dbh->do(qq{
17970         ALTER TABLE `accountlines`
17971         MODIFY COLUMN `interface` varchar(16) NOT NULL;
17972     });
17973
17974     SetVersion($DBversion);
17975     print "Upgrade to $DBversion done (Bug 22600 - Add interface to accountlines)\n";
17976 }
17977
17978 $DBversion = '18.12.00.040';
17979 if( CheckVersion( $DBversion ) ) {
17980     $dbh->do("UPDATE accountlines SET description = REPLACE(description, 'Reserve Charge - ', '') WHERE description LIKE 'Reserve Charge - %'");
17981     SetVersion( $DBversion );
17982     print "Upgrade to $DBversion done (Bug 12166 - Remove 'Reserve Charge' text from accountlines description)\n";
17983 }
17984
17985 $DBversion = '18.12.00.041';
17986 if( CheckVersion( $DBversion ) ) {
17987     my $table_sth = $dbh->prepare('SHOW CREATE TABLE `search_marc_map`');
17988     $table_sth->execute();
17989     my @table = $table_sth->fetchrow_array();
17990     unless ( $table[1] =~ /`marc_field`.*COLLATE utf8mb4_bin/ ) { #catches utf8mb4 collated tables
17991         $dbh->do("ALTER TABLE `search_marc_map` MODIFY `marc_field` VARCHAR(255) NOT NULL COLLATE utf8mb4_bin COMMENT 'the MARC specifier for this field'");
17992     }
17993
17994     # Always end with this (adjust the bug info)
17995     SetVersion( $DBversion );
17996         print "Upgrade to $DBversion done (Bug 19670 - Change collation of marc_field to allow mixed case search field mappings)\n";
17997 }
17998
17999 $DBversion = '18.12.00.042';
18000 if( CheckVersion( $DBversion ) ) {
18001     $dbh->do( "UPDATE systempreferences SET value = 'default' WHERE variable = 'XSLTDetailsDisplay' AND value = ''" );
18002     SetVersion( $DBversion );
18003     print "Upgrade to $DBversion done (Bug 29891 - Remove non-XSLT detail view in the staff client)\n";
18004 }
18005
18006 $DBversion = '18.12.00.043';
18007 if ( CheckVersion($DBversion) ) {
18008     $dbh->do("UPDATE accountlines SET description = REPLACE(description, 'Lost Item ', '') WHERE description LIKE 'Lost Item %'");
18009     SetVersion($DBversion);
18010     print "Upgrade to $DBversion done (Bug 21953 - Remove 'Lost Item' text from accountlines description)\n";
18011 }
18012
18013 $DBversion = '18.12.00.044';
18014 if( CheckVersion( $DBversion ) ) {
18015
18016     if ( !column_exists( 'categories', 'reset_password' ) ) {
18017         $dbh->do(q{
18018             ALTER TABLE categories
18019                 ADD COLUMN reset_password TINYINT(1) NULL DEFAULT NULL
18020                 AFTER checkprevcheckout
18021         });
18022     }
18023
18024     SetVersion( $DBversion );
18025     print "Upgrade to $DBversion done (Bug 21890 - Patron password reset by category)\n";
18026 }
18027
18028 $DBversion = '18.12.00.045';
18029 if( CheckVersion( $DBversion ) ) {
18030
18031     if ( !column_exists( 'categories', 'change_password' ) ) {
18032         $dbh->do(q{
18033             ALTER TABLE categories
18034                 ADD COLUMN change_password TINYINT(1) NULL DEFAULT NULL
18035                 AFTER reset_password
18036         });
18037     }
18038
18039     SetVersion( $DBversion );
18040     print "Upgrade to $DBversion done (Bug 10796 - Patron password change by category)\n";
18041 }
18042
18043 $DBversion = '18.12.00.046';
18044 if( CheckVersion( $DBversion ) ) {
18045     $dbh->do( "UPDATE systempreferences SET value = 'default' WHERE variable = 'XSLTResultsDisplay' AND value = ''" );
18046     SetVersion( $DBversion );
18047     print "Upgrade to $DBversion done (Bug 22695 - Remove non-XSLT search results view from the staff client)\n";
18048 }
18049
18050 $DBversion = '18.12.00.047';
18051 if( CheckVersion( $DBversion ) ) {
18052     $dbh->do(q|
18053         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');
18054     |);
18055     $dbh->do(q|
18056         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');
18057     |);
18058     SetVersion( $DBversion );
18059     print "Upgrade to $DBversion done (Bug 14557: Add Libris spellchecking system preferences)\n";
18060 }
18061
18062 $DBversion = '18.12.00.048';
18063 if( CheckVersion( $DBversion ) ) {
18064     $dbh->do( q{
18065         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
18066         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');
18067     });
18068     $dbh->do("UPDATE systempreferences SET value='exact_time' WHERE variable='NoRenewalBeforePrecision' AND value IS NULL;" );
18069     SetVersion( $DBversion );
18070     print "Upgrade to $DBversion done (Bug 22044 - Set a default value for NoRenewalBeforePrecision)\n";
18071 }
18072
18073 $DBversion = '18.12.00.049';
18074 if( CheckVersion( $DBversion ) ) {
18075
18076     $dbh->do(q{
18077         ALTER TABLE borrowers
18078             ADD COLUMN flgAnonymized tinyint DEFAULT 0
18079             AFTER overdrive_auth_token
18080     }) if !column_exists('borrowers', 'flgAnonymized');
18081
18082     $dbh->do(q{
18083         ALTER TABLE deletedborrowers
18084             ADD COLUMN flgAnonymized tinyint DEFAULT 0
18085             AFTER overdrive_auth_token
18086     }) if !column_exists('deletedborrowers', 'flgAnonymized');
18087
18088     SetVersion( $DBversion );
18089     print "Upgrade to $DBversion done (Bug 21336 - Add field flgAnonymized)\n";
18090 }
18091
18092 $DBversion = '18.12.00.050';
18093 if( CheckVersion( $DBversion ) ) {
18094     $dbh->do( q|
18095 INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
18096 VALUES
18097 ('UnsubscribeReflectionDelay','',NULL,'Delay for locking unsubscribers', 'Integer'),
18098 ('PatronAnonymizeDelay','',NULL,'Delay for anonymizing patrons', 'Integer'),
18099 ('PatronRemovalDelay','',NULL,'Delay for removing anonymized patrons', 'Integer')
18100     |);
18101     SetVersion( $DBversion );
18102     print "Upgrade to $DBversion done (Bug 21336 - Add preferences)\n";
18103 }
18104
18105 $DBversion = '18.12.00.051';
18106 if( CheckVersion( $DBversion ) ) {
18107     my $failed_attempts = C4::Context->preference('FailedLoginAttempts');
18108     $dbh->do( "UPDATE borrowers SET login_attempts = ? WHERE login_attempts > ?", undef, $failed_attempts, $failed_attempts ) if $failed_attempts && $failed_attempts > 0;
18109     SetVersion( $DBversion );
18110     print "Upgrade to $DBversion done (Bug 21336 - Reset login_attempts)\n";
18111 }
18112
18113 $DBversion = '18.12.00.052';
18114 if( CheckVersion( $DBversion ) ) {
18115     $dbh->do(q{
18116         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
18117         ('OpacMoreSearches', '', NULL, 'Add additional elements to the OPAC more searches bar', 'Textarea')
18118     } );
18119
18120     SetVersion( $DBversion );
18121     print "Upgrade to $DBversion done (Bug 22311 - Add a SysPref to allow adding content to the #moresearches div in the opac)\n";
18122 }
18123
18124 $DBversion = '18.12.00.053';
18125 if( CheckVersion( $DBversion ) ) {
18126     $dbh->do(q{
18127         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES
18128         ('AutoReturnCheckedOutItems', '0', '', 'If disabled, librarian must confirm return of checked out item when checking out to another.', 'YesNo');
18129     });
18130
18131     SetVersion( $DBversion );
18132     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";
18133 }
18134
18135 $DBversion = '18.12.00.054';
18136 if( CheckVersion( $DBversion ) ) {
18137     $dbh->do(q{
18138         INSERT IGNORE permissions (module_bit, code, description)
18139         VALUES
18140         (9,'advanced_editor','Use the advanced cataloging editor')
18141     });
18142     if( C4::Context->preference('EnableAdvancedCatalogingEditor') ){
18143         $dbh->do(q{
18144             INSERT INTO user_permissions (borrowernumber, module_bit, code)
18145             SELECT borrowernumber, 9, 'advanced_editor' FROM borrowers WHERE borrowernumber IN (SELECT DISTINCT borrowernumber FROM user_permissions WHERE code = 'edit_catalogue');
18146         });
18147     }
18148     SetVersion( $DBversion );
18149     print "Upgrade to $DBversion done (Bug 20128: Add permission for Advanced Cataloging Editor)\n";
18150 }
18151
18152 $DBversion = '18.12.00.055';
18153 if ( CheckVersion($DBversion) ) {
18154
18155     $dbh->do(qq{
18156         UPDATE
18157           `account_offset_types`
18158         SET
18159           type = 'OVERDUE'
18160         WHERE
18161           type = 'Fine';
18162     });
18163
18164     $dbh->do(qq{
18165         UPDATE
18166           `account_offset_types`
18167         SET
18168           type = 'OVERDUE_INCREASE'
18169         WHERE
18170           type = 'fine_increase';
18171     });
18172
18173     $dbh->do(qq{
18174         UPDATE
18175           `account_offset_types`
18176         SET
18177           type = 'OVERDUE_DECREASE'
18178         WHERE
18179           type = 'fine_decrease';
18180     });
18181
18182     if ( column_exists( 'accountlines', 'accounttype' ) ) {
18183         $dbh->do(
18184             qq{
18185             ALTER TABLE `accountlines`
18186             CHANGE COLUMN `accounttype`
18187               `accounttype` varchar(16) DEFAULT NULL;
18188           }
18189         );
18190     }
18191
18192     $dbh->do(qq{
18193         UPDATE
18194           accountlines
18195         SET
18196           accounttype = 'OVERDUE',
18197           status = 'UNRETURNED'
18198         WHERE
18199           accounttype = 'FU';
18200     });
18201
18202     $dbh->do(qq{
18203         UPDATE
18204           accountlines
18205         SET
18206           accounttype = 'OVERDUE',
18207           status = 'FORGIVEN'
18208         WHERE
18209           accounttype = 'FFOR';
18210     });
18211
18212     $dbh->do(qq{
18213         UPDATE
18214           accountlines
18215         SET
18216           accounttype = 'OVERDUE',
18217           status = 'RETURNED'
18218         WHERE
18219           accounttype = 'F';
18220     });
18221     SetVersion($DBversion);
18222     print "Upgrade to $DBversion done (Bug 22521 - Update accountlines.accounttype to varchar(16), and map new statuses)\n";
18223 }
18224
18225 $DBversion = '18.12.00.056';
18226 if( CheckVersion( $DBversion ) ) {
18227     $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'");
18228     SetVersion( $DBversion );
18229     print "Upgrade to $DBversion done (Bug 8701 - Update OpacHiddenItems system preference description)\n";
18230 }
18231
18232 $DBversion = '18.12.00.057';
18233 if( CheckVersion( $DBversion ) ) {
18234     if( column_exists('statistics', 'associatedborrower') ) {
18235         $dbh->do(q{ ALTER TABLE statistics DROP COLUMN associatedborrower });
18236     }
18237     if( column_exists('statistics', 'usercode') ) {
18238         $dbh->do(q{ ALTER TABLE statistics DROP COLUMN usercode });
18239     }
18240
18241     SetVersion($DBversion);
18242     print "Upgrade to $DBversion done (Bug 13795 - Delete unused fields from statistics table)\n";
18243 }
18244
18245 $DBversion = '18.12.00.058';
18246 if( CheckVersion( $DBversion ) ) {
18247     my $opaclang = C4::Context->preference("opaclanguages");
18248     my @langs;
18249     push @langs, split ( '\,', $opaclang );
18250     # Get any existing value from the OpacNavRight system preference
18251     my ($OpacNavRight) = $dbh->selectrow_array( q|
18252         SELECT value FROM systempreferences WHERE variable='OpacNavRight';
18253     |);
18254     if( $OpacNavRight ){
18255         # If there is a value in the OpacNavRight preference, insert it into opac_news
18256         $dbh->do("INSERT INTO opac_news (branchcode, lang, title, content ) VALUES (NULL, ?, '', ?)", undef, "OpacNavRight_$langs[0]", $OpacNavRight);
18257     }
18258     # Remove the OpacNavRight system preference
18259     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacNavRight'");
18260     SetVersion ($DBversion);
18261     print "Upgrade to $DBversion done (Bug 22318: Move contents of OpacNavRight preference to Koha news system)\n";
18262 }
18263
18264 $DBversion = '18.12.00.059';
18265 if( CheckVersion( $DBversion ) ) {
18266     if( column_exists( 'import_records', 'z3950random' ) ) {
18267         $dbh->do( "ALTER TABLE import_records DROP COLUMN z3950random" );
18268     }
18269
18270     # Always end with this (adjust the bug info)
18271     SetVersion( $DBversion );
18272     print "Upgrade to $DBversion done (Bug 22532 - Remove import_records z3950random column)\n";
18273 }
18274
18275 $DBversion = '18.12.00.060';
18276 if ( CheckVersion($DBversion) ) {
18277
18278     my $rows = $dbh->do(
18279         qq{
18280         UPDATE `accountlines`
18281         SET
18282           `accounttype` = 'L',
18283           `status`      = 'REPLACED'
18284         WHERE
18285           `accounttype` = 'Rep'
18286       }
18287     );
18288
18289     SetVersion($DBversion);
18290     printf "Upgrade to $DBversion done (Bug 22564 - Fix accounttype 'Rep' - %d updated)\n", $rows;
18291 }
18292
18293 $DBversion = '18.12.00.061';
18294 if( CheckVersion( $DBversion ) ) {
18295
18296     if ( column_exists( 'borrowers', 'flgAnonymized' ) ) {
18297         $dbh->do(q{
18298             UPDATE borrowers SET flgAnonymized = 0 WHERE flgAnonymized IS NULL
18299         });
18300         $dbh->do(q{
18301             ALTER TABLE borrowers
18302                 CHANGE `flgAnonymized` `anonymized` TINYINT(1) NOT NULL DEFAULT 0
18303         });
18304     }
18305
18306     if ( column_exists( 'deletedborrowers', 'flgAnonymized' ) ) {
18307         $dbh->do(q{
18308             UPDATE deletedborrowers SET flgAnonymized = 0 WHERE flgAnonymized IS NULL
18309         });
18310         $dbh->do(q{
18311             ALTER TABLE deletedborrowers
18312                 CHANGE `flgAnonymized` `anonymized` TINYINT(1) NOT NULL DEFAULT 0
18313         });
18314     }
18315
18316     SetVersion( $DBversion );
18317     print "Upgrade to $DBversion done (Bug 21336 - (follow-up) Rename flgAnonymized column)\n";
18318 }
18319
18320 $DBversion = '18.12.00.062';
18321 if( CheckVersion( $DBversion ) ) {
18322     $dbh->do( q|
18323         UPDATE search_marc_map SET marc_field='007_/0'
18324           WHERE marc_type IN ('marc21', 'normarc') AND marc_field='007_/1' AND id IN
18325             (SELECT search_marc_map_id FROM search_marc_to_field WHERE search_field_id IN
18326               (SELECT id FROM search_field WHERE label='ff7-00')
18327             )
18328     |);
18329
18330     $dbh->do( q|
18331         UPDATE search_marc_map SET marc_field='007_/1'
18332           WHERE marc_type IN ('marc21', 'normarc') AND marc_field='007_/2' AND id IN
18333             (SELECT search_marc_map_id FROM search_marc_to_field WHERE search_field_id IN
18334               (SELECT id FROM search_field WHERE label='ff7-01')
18335             )
18336     |);
18337
18338     $dbh->do( q|
18339         UPDATE search_marc_map SET marc_field='007_/2'
18340           WHERE marc_type IN ('marc21', 'normarc') AND marc_field='007_/3' AND id IN
18341             (SELECT search_marc_map_id FROM search_marc_to_field WHERE search_field_id IN
18342               (SELECT id FROM search_field WHERE label='ff7-02')
18343             )
18344     |);
18345
18346     # N.B. ff7-01-02 really is 00-01!
18347     $dbh->do( q|
18348         UPDATE search_marc_map SET marc_field='007_/0-1'
18349           WHERE marc_type IN ('marc21', 'normarc') AND marc_field='007_/1-2' AND id IN
18350             (SELECT search_marc_map_id FROM search_marc_to_field WHERE search_field_id IN
18351               (SELECT id FROM search_field WHERE label='ff7-01-02')
18352             )
18353     |);
18354
18355     $dbh->do( q|
18356         UPDATE search_marc_map SET marc_field='008_/0-5'
18357           WHERE marc_type IN ('marc21', 'normarc') AND marc_field='008_/1-5' AND id IN
18358             (SELECT search_marc_map_id FROM search_marc_to_field WHERE search_field_id IN
18359               (SELECT id FROM search_field WHERE label='date-entered-on-file')
18360             )
18361     |);
18362
18363     $dbh->do( q|
18364         UPDATE search_marc_map SET marc_field='leader_/0-4'
18365           WHERE marc_type IN ('marc21', 'normarc') AND marc_field='leader_/1-5' AND id IN
18366             (SELECT search_marc_map_id FROM search_marc_to_field WHERE search_field_id IN
18367               (SELECT id FROM search_field WHERE label='llength')
18368             )
18369     |);
18370
18371     # Always end with this (adjust the bug info)
18372     SetVersion( $DBversion );
18373     print "Upgrade to $DBversion done (Bug 22339 - Fix search field mappings of MARC fixed fields)\n";
18374 }
18375
18376 $DBversion = '18.12.00.063';
18377 if ( CheckVersion($DBversion) ) {
18378
18379     my $types_map = {
18380         'Writeoff'      => 'W',
18381         'Payment'       => 'Pay',
18382         'Lost Item'     => 'CR',
18383         'Manual Credit' => 'C',
18384         'Forgiven'      => 'FOR'
18385     };
18386
18387     my $sth = $dbh->prepare( "SELECT accountlines_id FROM accountlines WHERE accounttype = 'VOID'" );
18388     my $sth2 = $dbh->prepare( "SELECT type FROM account_offsets WHERE credit_id = ? ORDER BY created_on LIMIT 1" );
18389     my $sth3 = $dbh->prepare( "UPDATE accountlines SET accounttype = ?, status = 'VOID' WHERE accountlines_id = ?" );
18390     $sth->execute();
18391     while (my $row = $sth->fetchrow_hashref) {
18392         $sth2->execute($row->{accountlines_id});
18393         my $result = $sth2->fetchrow_hashref;
18394         my $type = $types_map->{$result->{'type'}} // 'Pay';
18395         $sth3->execute($type,$row->{accountlines_id});
18396     }
18397
18398     SetVersion($DBversion);
18399     print "Upgrade to $DBversion done (Bug 22511 - Update existing VOID accountlines)\n";
18400 }
18401
18402 $DBversion = '18.12.00.064';
18403 if( CheckVersion( $DBversion ) ) {
18404     $dbh->do(q{
18405         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');
18406     });
18407     $dbh->do(q{
18408         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%';
18409     });
18410     $dbh->do(q{
18411         DELETE FROM systempreferences WHERE variable='InProcessingToShelvingCart';
18412     });
18413     $dbh->do(q{
18414         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%';
18415     });
18416     $dbh->do(q{
18417         DELETE FROM systempreferences WHERE variable='ReturnToShelvingCart';
18418     });
18419     SetVersion( $DBversion );
18420     print "Upgrade to $DBversion done (Bug 14576: Add UpdateItemLocationOnCheckin syspref)\n";
18421 }
18422
18423 $DBversion = '18.12.00.065';
18424 if( CheckVersion( $DBversion ) ) {
18425     $dbh->do( q{
18426         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
18427         SELECT 'IndependentBranchesTransfers', value, NULL, 'Allow non-superlibrarians to transfer items between libraries','YesNo'
18428         FROM systempreferences WHERE variable = 'IndependentBranches'
18429     });
18430     SetVersion( $DBversion );
18431     print "Upgrade to $DBversion done (Bug 10300 - Allow transferring of items to be have separate IndependentBranches syspref)\n";
18432 }
18433
18434 $DBversion = '18.12.00.066';
18435 if ( CheckVersion($DBversion) ) {
18436     $dbh->do(q{
18437         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `explanation`, `options`, `type`) VALUES
18438           ('OpenURLResolverURL', '', 'URL of OpenURL Resolver', NULL, 'Free'),
18439           ('OpenURLText', '', 'Text of OpenURL links (or image title if OpenURLImageLocation is defined)', NULL, 'Free'),
18440           ('OpenURLImageLocation', '', 'Location of image for OpenURL links', NULL, 'Free'),
18441           ('OPACShowOpenURL', '', 'Enable display of OpenURL links in OPAC search results and detail page', NULL, 'YesNo'),
18442           ('OPACOpenURLItemTypes', '', 'Show the OpenURL link only for these item types', NULL, 'Free');
18443     });
18444
18445     SetVersion($DBversion);
18446     print
18447 "Upgrade to $DBversion done (Bug 8995 - Add new preferences for OpenURLResolvers)\n";
18448 }
18449
18450 $DBversion = '18.12.00.067';
18451 if ( CheckVersion($DBversion) ) {
18452     $dbh->do(q{
18453         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
18454         VALUES ('SendAllEmailsTo','',NULL,'All emails will be redirected to this email if it is not empty','free');
18455     });
18456     SetVersion($DBversion);
18457     print
18458 "Upgrade to $DBversion done (Bug 8000 - Add new preferences for SendAllEmailsTo)\n";
18459 }
18460
18461 $DBversion = '18.12.00.068';
18462 if ( CheckVersion($DBversion) ) {
18463     $dbh->do(q{
18464         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
18465         ('AllowRenewalOnHoldOverride','0','','If on, allow items on hold to be renewed with a specified due date','YesNo');
18466     });
18467     SetVersion($DBversion);
18468     print "Upgrade to $DBversion done (Bug 7088: Cannot renew items on hold even with override)\n";
18469 }
18470
18471 $DBversion = '18.12.00.069';
18472 if( CheckVersion( $DBversion ) ) {
18473
18474     $dbh->do(q{
18475         INSERT INTO plugin_data
18476             (plugin_class, plugin_key, plugin_value)
18477         SELECT
18478             plugin_class,
18479             '__ENABLED__',
18480             1
18481         FROM plugin_data
18482         WHERE plugin_key='__INSTALLED_VERSION__'
18483     });
18484
18485     # Always end with this (adjust the bug info)
18486     SetVersion( $DBversion );
18487     print "Upgrade to $DBversion done (Bug 22053 - enable all plugins)\n";
18488 }
18489
18490 $DBversion = '18.12.00.070';
18491 if ( CheckVersion($DBversion) ) {
18492     $dbh->do(q{
18493         INSERT IGNORE INTO systempreferences
18494             ( `variable`, `value`, `options`, `explanation`, `type` )
18495         VALUES
18496         ('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');
18497     });
18498     SetVersion($DBversion);
18499     print "Upgrade to $DBversion done (Bug 14407 - Limit web-based self-checkout to specific IP addresses)\n";
18500 }
18501
18502 $DBversion = '18.12.00.071';
18503 if( CheckVersion( $DBversion ) ) {
18504     $dbh->do(q{
18505 INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`, `lang`) VALUES
18506 ('circulation', 'ACCOUNT_CREDIT', '', 'Account payment', 0, 'Account payment', '<table>
18507 [% IF ( LibraryName ) %]
18508  <tr>
18509     <th colspan="4" class="centerednames">
18510         <h3>[% LibraryName | html %]</h3>
18511     </th>
18512  </tr>
18513 [% END %]
18514  <tr>
18515     <th colspan="4" class="centerednames">
18516         <h2><u>Fee receipt</u></h2>
18517     </th>
18518  </tr>
18519  <tr>
18520     <th colspan="4" class="centerednames">
18521         <h2>[% Branches.GetName( patron.branchcode ) | html %]</h2>
18522     </th>
18523  </tr>
18524  <tr>
18525     <th colspan="4">
18526         Received with thanks from  [% patron.firstname | html %] [% patron.surname | html %] <br />
18527         Card number: [% patron.cardnumber | html %]<br />
18528     </th>
18529  </tr>
18530   <tr>
18531     <th>Date</th>
18532     <th>Description of charges</th>
18533     <th>Note</th>
18534     <th>Amount</th>
18535  </tr>
18536
18537   [% FOREACH account IN accounts %]
18538     <tr class="highlight">
18539       <td>[% account.date | $KohaDates %]</td>
18540       <td>
18541         [% PROCESS account_type_description account=account %]
18542         [%- IF account.description %], [% account.description | html %][% END %]
18543       </td>
18544       <td>[% account.note | html %]</td>
18545       [% IF ( account.amountcredit ) %]<td class="credit">[% ELSE %]<td class="debit">[% END %][% account.amount | $Price %]</td>
18546     </tr>
18547
18548   [% END %]
18549 <tfoot>
18550   <tr>
18551     <td colspan="3">Total outstanding dues as on date: </td>
18552     [% IF ( totalcredit ) %]<td class="credit">[% ELSE %]<td class="debit">[% END %][% total | $Price %]</td>
18553   </tr>
18554 </tfoot>
18555 </table>', 'print', 'default');
18556     });
18557     SetVersion( $DBversion );
18558     print "Upgrade to $DBversion done (Bug 22809 - Move 'ACCOUNT_CREDIT' from template to a slip)\n";
18559 }
18560
18561 $DBversion = '18.12.00.072';
18562 if( CheckVersion( $DBversion ) ) {
18563     $dbh->do(q{
18564 INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`, `lang`) VALUES
18565 ('circulation', 'ACCOUNT_DEBIT', '', 'Account fee', 0, 'Account fee', '<table>
18566   [% IF ( LibraryName ) %]
18567     <tr>
18568       <th colspan="5" class="centerednames">
18569         <h3>[% LibraryName | html %]</h3>
18570       </th>
18571     </tr>
18572   [% END %]
18573
18574   <tr>
18575     <th colspan="5" class="centerednames">
18576       <h2><u>INVOICE</u></h2>
18577     </th>
18578   </tr>
18579   <tr>
18580     <th colspan="5" class="centerednames">
18581       <h2>[% Branches.GetName( patron.branchcode ) | html %]</h2>
18582     </th>
18583   </tr>
18584   <tr>
18585     <th colspan="5" >
18586       Bill to: [% patron.firstname | html %] [% patron.surname | html %] <br />
18587       Card number: [% patron.cardnumber | html %]<br />
18588     </th>
18589   </tr>
18590   <tr>
18591     <th>Date</th>
18592     <th>Description of charges</th>
18593     <th>Note</th>
18594     <th style="text-align:right;">Amount</th>
18595     <th style="text-align:right;">Amount outstanding</th>
18596   </tr>
18597
18598   [% FOREACH account IN accounts %]
18599     <tr class="highlight">
18600       <td>[% account.date | $KohaDates%]</td>
18601       <td>
18602         [% PROCESS account_type_description account=account %]
18603         [%- IF account.description %], [% account.description | html %][% END %]
18604       </td>
18605       <td>[% account.note | html %]</td>
18606       [% IF ( account.amountcredit ) %]<td class="credit">[% ELSE %]<td class="debit">[% END %][% account.amount | $Price %]</td>
18607       [% IF ( account.amountoutstandingcredit ) %]<td class="credit">[% ELSE %]<td class="debit">[% END %][% account.amountoutstanding | $Price %]</td>
18608     </tr>
18609   [% END %]
18610
18611   <tfoot>
18612     <tr>
18613       <td colspan="4">Total outstanding dues as on date: </td>
18614       [% IF ( totalcredit ) %]<td class="credit">[% ELSE %]<td class="debit">[% END %][% total | $Price %]</td>
18615     </tr>
18616   </tfoot>
18617 </table>', 'print', 'default');
18618     });
18619     SetVersion( $DBversion );
18620     print "Upgrade to $DBversion done (Bug 22809 - Move 'INVOICE' from template to a slip)\n";
18621 }
18622
18623 $DBversion = '18.12.00.073';
18624 if( CheckVersion( $DBversion ) ) {
18625     $dbh->do( q{
18626             INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
18627             ('EmailPurchaseSuggestions','0','0|EmailAddressForSuggestions|BranchEmailAddress|KohaAdminEmailAddress','Choose email address that will be sent new purchase suggestions','Choice'),
18628             ('EmailAddressForSuggestions','','','If you choose EmailAddressForSuggestions you should enter a valid email address','free')
18629     });
18630
18631     $dbh->do( q{
18632             INSERT IGNORE INTO `letter` (module, code, name, title, content, is_html, message_transport_type) VALUES
18633             ('suggestions','NEW_SUGGESTION','New suggestion','New suggestion','<h3>Suggestion pending approval</h3>
18634                 <p><h4>Suggested by</h4>
18635                     <ul>
18636                         <li><<borrowers.firstname>> <<borrowers.surname>></li>
18637                         <li><<borrowers.cardnumber>></li>
18638                         <li><<borrowers.phone>></li>
18639                         <li><<borrowers.email>></li>
18640                     </ul>
18641                 </p>
18642                 <p><h4>Title suggested</h4>
18643                     <ul>
18644                         <li><b>Library:</b> <<branches.branchname>></li>
18645                         <li><b>Title:</b> <<suggestions.title>></li>
18646                         <li><b>Author:</b> <<suggestions.author>></li>
18647                         <li><b>Copyright date:</b> <<suggestions.copyrightdate>></li>
18648                         <li><b>Standard number (ISBN, ISSN or other):</b> <<suggestions.isbn>></li>
18649                         <li><b>Publisher:</b> <<suggestions.publishercode>></li>
18650                         <li><b>Collection title:</b> <<suggestions.collectiontitle>></li>
18651                         <li><b>Publication place:</b> <<suggestions.place>></li>
18652                         <li><b>Quantity:</b> <<suggestions.quantity>></li>
18653                         <li><b>Item type:</b> <<suggestions.itemtype>></li>
18654                         <li><b>Reason for suggestion:</b> <<suggestions.patronreason>></li>
18655                         <li><b>Notes:</b> <<suggestions.note>></li>
18656                     </ul>
18657                 </p>',1, 'email')
18658     });
18659
18660     SetVersion( $DBversion );
18661     print "Upgrade to $DBversion done (Bug 5770 - Email librarian when purchase suggestion made)\n";
18662 }
18663
18664 $DBversion = '18.12.00.074';
18665 if( CheckVersion( $DBversion ) ) {
18666     unless ( TableExists( 'keyboard_shortcuts' ) ) {
18667         $dbh->do(q|
18668             CREATE TABLE keyboard_shortcuts (
18669             shortcut_name varchar(80) NOT NULL,
18670             shortcut_keys varchar(80) NOT NULL,
18671             PRIMARY KEY (shortcut_name)
18672             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;|
18673         );
18674     }
18675     $dbh->do(q|
18676         INSERT IGNORE INTO keyboard_shortcuts (shortcut_name, shortcut_keys) VALUES
18677         ("insert_copyright","Alt-C"),
18678         ("insert_copyright_sound","Alt-P"),
18679         ("insert_delimiter","Ctrl-D"),
18680         ("subfield_help","Ctrl-H"),
18681         ("link_authorities","Shift-Ctrl-L"),
18682         ("delete_field","Ctrl-X"),
18683         ("delete_subfield","Shift-Ctrl-X"),
18684         ("new_line","Enter"),
18685         ("line_break","Shift-Enter"),
18686         ("next_position","Tab"),
18687         ("prev_position","Shift-Tab")
18688         ;|
18689     );
18690     $dbh->do(q|
18691         INSERT IGNORE permissions (module_bit, code, description)
18692         VALUES
18693         (3,'manage_keyboard_shortcuts','Manage keyboard shortcuts for advanced cataloging editor')
18694         ;|
18695     );
18696     SetVersion( $DBversion );
18697     print "Upgrade to $DBversion done (Bug 21411 - Add keyboard_shortcuts table)\n";
18698 }
18699
18700 $DBversion = '18.12.00.075';
18701 if( CheckVersion( $DBversion ) ) {
18702     # you can use $dbh here like:
18703     unless ( foreign_key_exists( 'tmp_holdsqueue', 'tmp_holdsqueue_ibfk_1' ) ) {
18704         $dbh->do(q{
18705             DELETE t FROM tmp_holdsqueue t
18706             LEFT JOIN items i ON t.itemnumber=i.itemnumber
18707             WHERE i.itemnumber IS NULL
18708         });
18709         $dbh->do(q{
18710             ALTER TABLE tmp_holdsqueue
18711             ADD CONSTRAINT `tmp_holdsqueue_ibfk_1` FOREIGN KEY (`itemnumber`)
18712             REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE
18713         });
18714     }
18715     SetVersion( $DBversion );
18716     print "Upgrade to $DBversion done (Bug 22899 - Add items constraint to tmp_holdsqueue)\n";
18717 }
18718
18719 $DBversion = '19.05.00.000';
18720 if( CheckVersion( $DBversion ) ) {
18721     SetVersion( $DBversion );
18722     print "Upgrade to $DBversion done (19.05.00 release)\n";
18723 }
18724
18725 $DBversion = '19.06.00.000';
18726 if( CheckVersion( $DBversion ) ) {
18727     SetVersion( $DBversion );
18728     print "Upgrade to $DBversion done (Wingardium Leviosa!)\n";
18729 }
18730
18731 $DBversion = '19.06.00.001'; 
18732 if( CheckVersion( $DBversion ) ) {
18733     $dbh->do( q{
18734         UPDATE systempreferences 
18735         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.' 
18736         WHERE variable = 'UpdateItemLocationOnCheckin'
18737     });
18738     SetVersion( $DBversion );
18739     print "Upgrade to $DBversion done (Bug 22960: Fix typo in syspref description)\n";
18740 }
18741
18742 $DBversion = '19.06.00.002';
18743 if ( CheckVersion($DBversion) ) {
18744
18745     $dbh->do(q{ALTER TABLE subscriptionhistory CHANGE opacnote opacnote LONGTEXT NULL});
18746     $dbh->do(q{ALTER TABLE subscriptionhistory CHANGE librariannote librariannote LONGTEXT NULL});
18747
18748     $dbh->do(q{UPDATE subscriptionhistory SET opacnote = NULL WHERE opacnote = ''});
18749     $dbh->do(q{UPDATE subscriptionhistory SET librariannote = NULL WHERE librariannote = ''});
18750
18751     SetVersion ($DBversion);
18752     print "Upgrade to $DBversion done (Bug 10215: Increase the size of opacnote and librariannote for table subscriptionhistory)\n";
18753 }
18754
18755 $DBversion = '19.06.00.003';
18756 if( CheckVersion( $DBversion ) ) {
18757     $dbh->do(q{UPDATE systempreferences SET value = REPLACE( value, ' ', '|' ) WHERE variable = 'UniqueItemFields'; });
18758
18759     SetVersion( $DBversion );
18760     print "Upgrade to $DBversion done (Bug 22867: UniqueItemFields preference value should be pipe-delimited)\n";
18761 }
18762
18763 $DBversion = '19.06.00.004';
18764 if( CheckVersion( $DBversion ) ) {
18765     $dbh->do( 'UPDATE language_descriptions SET description = "Griechisch (Modern 1453-)"
18766       WHERE subtag = "el" and type = "language" and lang ="de"' );
18767     SetVersion( $DBversion );
18768     print "Upgrade to $DBversion done (Bug 22770: Fix typo in language description for el in German)\n";
18769 }
18770
18771 $DBversion = '19.06.00.005';
18772 if( CheckVersion( $DBversion ) ) {
18773     unless ( column_exists( 'reserves', 'item_level_hold' ) ) {
18774         $dbh->do( "ALTER TABLE reserves ADD COLUMN item_level_hold BOOLEAN NOT NULL DEFAULT 0 AFTER itemtype" );
18775     }
18776     unless ( column_exists( 'old_reserves', 'item_level_hold' ) ) {
18777         $dbh->do( "ALTER TABLE old_reserves ADD COLUMN item_level_hold BOOLEAN NOT NULL DEFAULT 0 AFTER itemtype" );
18778     }
18779
18780     SetVersion( $DBversion );
18781     print "Upgrade to $DBversion done (Bug  9834: Add the reserves.item_level_hold column)\n";
18782 }
18783
18784 $DBversion = '19.06.00.006';
18785 if( CheckVersion( $DBversion ) ) {
18786
18787     unless ( TableExists('plugin_methods') ) {
18788         $dbh->do(q{
18789             CREATE TABLE plugin_methods (
18790               plugin_class varchar(255) NOT NULL,
18791               plugin_method varchar(255) NOT NULL,
18792               PRIMARY KEY ( `plugin_class` (191), `plugin_method` (191) )
18793             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
18794         });
18795     }
18796
18797     require Koha::Plugins;
18798     Koha::Plugins->new({ enable_plugins => 1 })->InstallPlugins;
18799
18800     SetVersion( $DBversion );
18801     print "Upgrade to $DBversion done (Bug 21073: Improve plugin performance)\n";
18802 }
18803
18804 $DBversion = '19.06.00.007';
18805 if( CheckVersion( $DBversion ) ) {
18806     $dbh->do( "DELETE FROM systempreferences WHERE variable = 'RotationPreventTransfers'" );
18807     SetVersion( $DBversion );
18808     print "Upgrade to $DBversion done (Bug 22653: Remove unimplemented RotationPreventTransfers system preference)\n";
18809 }
18810
18811 $DBversion = '19.06.00.008';
18812 if( CheckVersion( $DBversion ) ) {
18813     $dbh->do( "UPDATE userflags SET flagdesc = 'Allow staff members to modify permissions and passwords for other staff members' WHERE flag = 'staffaccess'" );
18814     SetVersion( $DBversion );
18815     print "Upgrade to $DBversion done (Bug 23109: Improve description of staffaccess permission)\n";
18816 }
18817
18818 $DBversion = '19.06.00.009';
18819 if( CheckVersion( $DBversion ) ) {
18820     $dbh->do(q{
18821         INSERT IGNORE INTO keyboard_shortcuts (shortcut_name, shortcut_keys)
18822             VALUES ("toggle_keyboard", "Shift-Ctrl-K")
18823     });
18824
18825     SetVersion( $DBversion );
18826     print "Upgrade to $DBversion done (Bug 17178: add shortcut to keyboard_shortcuts)\n";
18827 }
18828
18829 $DBversion = '19.06.00.010';
18830 if( CheckVersion( $DBversion ) ) {
18831
18832     if ( TableExists('default_circ_rules') ) {
18833         if ( column_exists( 'default_circ_rules', 'holdallowed' ) ) {
18834             $dbh->do("
18835                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18836                 SELECT NULL, NULL, NULL, 'holdallowed', holdallowed
18837                 FROM default_circ_rules
18838             ");
18839             $dbh->do("
18840                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18841                 SELECT NULL, NULL, NULL, 'hold_fulfillment_policy', hold_fulfillment_policy
18842                 FROM default_circ_rules
18843             ");
18844             $dbh->do("
18845                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18846                 SELECT NULL, NULL, NULL, 'returnbranch', returnbranch
18847                 FROM default_circ_rules
18848             ");
18849             $dbh->do("DROP TABLE default_circ_rules");
18850         }
18851     }
18852
18853     if ( TableExists('default_branch_circ_rules') ) {
18854         if ( column_exists( 'default_branch_circ_rules', 'holdallowed' ) ) {
18855             $dbh->do("
18856                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18857                 SELECT NULL, branchcode, NULL, 'holdallowed', holdallowed
18858                 FROM default_branch_circ_rules
18859             ");
18860             $dbh->do("
18861                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18862                 SELECT NULL, branchcode, NULL, 'hold_fulfillment_policy', hold_fulfillment_policy
18863                 FROM default_branch_circ_rules
18864             ");
18865             $dbh->do("
18866                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18867                 SELECT NULL, branchcode, NULL, 'returnbranch', returnbranch
18868                 FROM default_branch_circ_rules
18869             ");
18870             $dbh->do("DROP TABLE default_branch_circ_rules");
18871         }
18872     }
18873
18874     if ( TableExists('branch_item_rules') ) {
18875         if ( column_exists( 'branch_item_rules', 'holdallowed' ) ) {
18876             $dbh->do("
18877                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18878                 SELECT NULL, branchcode, itemtype, 'holdallowed', holdallowed
18879                 FROM branch_item_rules
18880             ");
18881             $dbh->do("
18882                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18883                 SELECT NULL, branchcode, itemtype, 'hold_fulfillment_policy', hold_fulfillment_policy
18884                 FROM branch_item_rules
18885             ");
18886             $dbh->do("
18887                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18888                 SELECT NULL, branchcode, itemtype, 'returnbranch', returnbranch
18889                 FROM branch_item_rules
18890             ");
18891             $dbh->do("DROP TABLE branch_item_rules");
18892         }
18893     }
18894
18895     if ( TableExists('default_branch_item_rules') ) {
18896         if ( column_exists( 'default_branch_item_rules', 'holdallowed' ) ) {
18897             $dbh->do("
18898                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18899                 SELECT NULL, NULL, itemtype, 'holdallowed', holdallowed
18900                 FROM default_branch_item_rules
18901             ");
18902             $dbh->do("
18903                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18904                 SELECT NULL, NULL, itemtype, 'hold_fulfillment_policy', hold_fulfillment_policy
18905                 FROM default_branch_item_rules
18906             ");
18907             $dbh->do("
18908                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18909                 SELECT NULL, NULL, itemtype, 'returnbranch', returnbranch
18910                 FROM default_branch_item_rules
18911             ");
18912             $dbh->do("DROP TABLE default_branch_item_rules");
18913         }
18914     }
18915
18916     SetVersion( $DBversion );
18917     print "Upgrade to $DBversion done (Bug 18928: Move holdallowed, hold_fulfillment_policy, returnbranch to circulation_rules)\n";
18918 }
18919
18920 $DBversion = '19.06.00.011';
18921 if( CheckVersion( $DBversion ) ) {
18922
18923     if ( TableExists('refund_lost_item_fee_rules') ) {
18924         if ( column_exists( 'refund_lost_item_fee_rules', 'refund' ) ) {
18925             $dbh->do("
18926                 INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18927                 SELECT NULL, IF(branchcode='*', NULL, branchcode), NULL, 'refund', refund
18928                 FROM refund_lost_item_fee_rules
18929             ");
18930             $dbh->do("DROP TABLE refund_lost_item_fee_rules");
18931         }
18932     }
18933
18934     SetVersion( $DBversion );
18935     print "Upgrade to $DBversion done (Bug 18930: Move lost item refund rules to circulation_rules table)\n";
18936 }
18937
18938 $DBversion = '19.06.00.012';
18939 if ( CheckVersion($DBversion) ) {
18940
18941     # Find and correct pathological cases of LR becoming a credit
18942     my $sth = $dbh->prepare( "SELECT accountlines_id, issue_id, borrowernumber, itemnumber, amount, manager_id FROM accountlines WHERE accounttype = 'LR' AND amount < 0" );
18943     $sth->execute();
18944     while ( my $row = $sth->fetchrow_hashref ) {
18945         $dbh->do(
18946             "INSERT INTO accountlines (accounttype, issue_id, borrowernumber, itemnumber, amount, manager_id, interface) VALUES ( ?, ?, ?, ?, ?, ?, ? );",
18947             {},
18948             (
18949                 'CR',                   $row->{issue_id},
18950                 $row->{borrowernumber}, $row->{itemnumber},
18951                 $row->{amount},         $row->{manager_id},
18952                 'upgrade'
18953             )
18954         );
18955         my $credit_id = $dbh->last_insert_id(undef, undef, 'accountlines', undef);
18956         my $amount = $row->{amount} * -1;
18957         $dbh->do("INSERT INTO account_offsets (credit_id, debit_id, type, amount) VALUES (?,?,?,?);",{},($credit_id, $row->{accountlines_id}, 'Lost Item', $amount));
18958         $dbh->do("UPDATE accountlines SET amount = '$amount' WHERE accountlines_id = '$row->{accountlines_id}';");
18959     }
18960
18961     $dbh->do(qq{
18962         UPDATE
18963           accountlines
18964         SET
18965           accounttype = 'LOST',
18966           status = 'RETURNED'
18967         WHERE
18968           accounttype = 'LR';
18969     });
18970
18971     # Find and correct pathalogical cases of L having been converted to W
18972     $sth = $dbh->prepare( "SELECT accountlines_id, issue_id, borrowernumber, itemnumber, amount, manager_id FROM accountlines WHERE accounttype = 'W' AND itemnumber IS NOT NULL" );
18973     $sth->execute();
18974     while ( my $row = $sth->fetchrow_hashref ) {
18975         my $amount = $row->{amount} * -1;
18976         $dbh->do(
18977             "INSERT INTO accountlines (accounttype, issue_id, borrowernumber, itemnumber, amount, manager_id, interface) VALUES ( ?, ?, ?, ?, ?, ?, ? );",
18978             {},
18979             (
18980                 'LOST', $row->{issue_id}, $row->{borrowernumber},
18981                 $row->{itemnumber}, $amount, $row->{manager_id},
18982                 'upgrade'
18983             )
18984         );
18985         my $debit_id = $dbh->last_insert_id(undef, undef, 'accountlines', undef);
18986         $dbh->do(
18987             "INSERT INTO account_offsets (credit_id, debit_id, type, amount) VALUES (?,?,?,?);",
18988             {},
18989             (
18990                 $row->{accountlines_id}, $debit_id,
18991                 'Lost Item',    $amount
18992             )
18993         );
18994     }
18995
18996     $dbh->do(qq{
18997         UPDATE
18998           accountlines
18999         SET
19000           accounttype = 'LOST'
19001         WHERE
19002           accounttype = 'L';
19003     });
19004
19005     $dbh->do(qq{
19006         UPDATE
19007           accountlines
19008         SET
19009           accounttype = 'LOST_RETURN'
19010         WHERE
19011           accounttype = 'CR';
19012     });
19013
19014     SetVersion($DBversion);
19015     print "Upgrade to $DBversion done (Bug 22563: Fix accounttypes for 'L', 'LR' and 'CR')\n";
19016 }
19017
19018 $DBversion = '19.06.00.013';
19019 if ( CheckVersion( $DBversion ) ) {
19020     unless ( column_exists( 'borrower_modifications', 'changed_fields' ) ) {
19021         $dbh->do("ALTER TABLE borrower_modifications ADD changed_fields MEDIUMTEXT AFTER verification_token;");
19022     }
19023     SetVersion( $DBversion );
19024     print "Upgrade to $DBversion done (Bug 23151: Add borrower_modifications.changed_fields column)\n";
19025 }
19026
19027 $DBversion = '19.06.00.014';
19028 if ( CheckVersion($DBversion) ) {
19029
19030     $dbh->do(qq{
19031         UPDATE
19032           accountlines
19033         SET
19034           accounttype = 'RENT_DAILY_RENEW'
19035         WHERE
19036           accounttype = 'Rent'
19037         AND
19038           description LIKE 'Renewal of Daily Rental Item%';
19039     });
19040
19041     $dbh->do(qq{
19042         UPDATE
19043           accountlines
19044         SET
19045           accounttype = 'RENT_DAILY'
19046         WHERE
19047           accounttype = 'Rent'
19048         AND
19049           description LIKE 'Daily rental';
19050     });
19051
19052
19053     $dbh->do(qq{
19054         UPDATE
19055           accountlines
19056         SET
19057           accounttype = 'RENT_RENEW'
19058         WHERE
19059           accounttype = 'Rent'
19060         AND
19061           description LIKE 'Renewal of Rental Item%';
19062     });
19063
19064     $dbh->do(qq{
19065         UPDATE
19066           accountlines
19067         SET
19068           accounttype = 'RENT'
19069         WHERE
19070           accounttype = 'Rent';
19071     });
19072
19073     SetVersion($DBversion);
19074     print "Upgrade to $DBversion done (Bug 11573: Fix accounttypes for 'Rent')\n";
19075 }
19076
19077 $DBversion = '19.06.00.015';
19078 if( CheckVersion( $DBversion ) ) {
19079     $dbh->do( "UPDATE `search_field` SET `name` = 'date-time-last-modified', `label` = 'date-time-last-modified' WHERE `name` = 'date/time-last-modified'" );
19080
19081     SetVersion( $DBversion );
19082     print "Upgrade to $DBversion done (Bug 22524: Fix date/time-last-modified search with Elasticsearch)\n";
19083 }
19084
19085 $DBversion = '19.06.00.016';
19086 if( CheckVersion( $DBversion ) ) {
19087
19088     $dbh->do(q|
19089         INSERT IGNORE INTO keyboard_shortcuts (shortcut_name, shortcut_keys) VALUES
19090             ("insert_copyright","Alt-C"),
19091             ("insert_copyright_sound","Alt-P"),
19092             ("insert_delimiter","Ctrl-D"),
19093             ("subfield_help","Ctrl-H"),
19094             ("link_authorities","Shift-Ctrl-L"),
19095             ("delete_field","Ctrl-X"),
19096             ("delete_subfield","Shift-Ctrl-X"),
19097             ("new_line","Enter"),
19098             ("line_break","Shift-Enter"),
19099             ("next_position","Tab"),
19100             ("prev_position","Shift-Tab"),
19101             ("toggle_keyboard", "Shift-Ctrl-K")
19102     ;|);
19103
19104     SetVersion( $DBversion );
19105     print "Upgrade to $DBversion done (Bug 23396: Fix missing keyboard_shortcuts table)\n";
19106 }
19107
19108 $DBversion = '19.06.00.017';
19109 if ( CheckVersion($DBversion) ) {
19110
19111     $dbh->do(qq{
19112         INSERT INTO
19113           authorised_values (category,authorised_value,lib)
19114         VALUES
19115           ('PAYMENT_TYPE','SIP00','Cash via SIP2'),
19116           ('PAYMENT_TYPE','SIP01','VISA via SIP2'),
19117           ('PAYMENT_TYPE','SIP02','Creditcard via SIP2')
19118     });
19119
19120     $dbh->do(qq{
19121         UPDATE
19122           accountlines
19123         SET
19124           accounttype  = 'Pay',
19125           payment_type = 'SIP00'
19126         WHERE
19127           accounttype = 'Pay00';
19128     });
19129
19130     $dbh->do(qq{
19131         UPDATE
19132           accountlines
19133         SET
19134           accounttype  = 'Pay',
19135           payment_type = 'SIP01'
19136         WHERE
19137           accounttype = 'Pay01';
19138     });
19139
19140     $dbh->do(qq{
19141         UPDATE
19142           accountlines
19143         SET
19144           accounttype  = 'Pay',
19145           payment_type = 'SIP02'
19146         WHERE
19147           accounttype = 'Pay02';
19148     });
19149
19150     my $sth = $dbh->prepare( q{SELECT * FROM accountlines WHERE accounttype REGEXP '^Pay[[:digit:]]{2}$' } );
19151     $sth->execute();
19152     my $seen = {};
19153     while (my $row = $sth->fetchrow_hashref) {
19154         my $type = $row->{accounttype};
19155         my $sipcode = $type;
19156         $sipcode =~ s/Pay/SIP/g;
19157         unless ($seen->{$sipcode}) {
19158             $dbh->do(qq{
19159                 INSERT INTO
19160                   authorised_values (category,authorised_value,lib)
19161                 VALUES
19162                   ('PAYMENT_TYPE',"$sipcode",'Unrecognised SIP2 payment type')
19163             });
19164
19165              $dbh->do(qq{
19166                 UPDATE
19167                   accountlines
19168                 SET
19169                   accounttype  = 'Pay',
19170                   payment_type = "$sipcode"
19171                 WHERE
19172                   accounttype = "$type";
19173             });
19174
19175             $seen->{$sipcode} = 1;
19176         }
19177     }
19178
19179     SetVersion($DBversion);
19180     print "Upgrade to $DBversion done (Bug 22610: Fix accounttypes for SIP2 payments)\n";
19181 }
19182
19183 $DBversion = '19.06.00.018';
19184 if( CheckVersion( $DBversion ) ) {
19185     if( !column_exists( 'biblio', 'subtitle' ) ) {
19186         $dbh->do( "ALTER TABLE biblio ADD COLUMN medium LONGTEXT AFTER title" );
19187         $dbh->do( "ALTER TABLE biblio ADD COLUMN subtitle LONGTEXT AFTER medium" );
19188         $dbh->do( "ALTER TABLE biblio ADD COLUMN part_number LONGTEXT AFTER subtitle" );
19189         $dbh->do( "ALTER TABLE biblio ADD COLUMN part_name LONGTEXT AFTER part_number" );
19190
19191         $dbh->do( "ALTER TABLE deletedbiblio ADD COLUMN medium LONGTEXT AFTER title" );
19192         $dbh->do( "ALTER TABLE deletedbiblio ADD COLUMN subtitle LONGTEXT AFTER medium" );
19193         $dbh->do( "ALTER TABLE deletedbiblio ADD COLUMN part_number LONGTEXT AFTER subtitle" );
19194         $dbh->do( "ALTER TABLE deletedbiblio ADD COLUMN part_name LONGTEXT AFTER part_number" );
19195     }
19196
19197     $dbh->do( "UPDATE marc_subfield_structure SET kohafield='biblio.subtitle' WHERE kohafield='bibliosubtitle.subtitle'" );
19198
19199     my $marcflavour = C4::Context->preference('marcflavour');
19200
19201     if ( $marcflavour eq 'UNIMARC' ) {
19202         $dbh->do(qq{
19203             UPDATE marc_subfield_structure SET kohafield='biblio.medium'
19204             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='200' AND tagsubfield='b'
19205         });
19206         $dbh->do(qq{
19207             UPDATE marc_subfield_structure SET kohafield='biblio.subtitle'
19208             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='200' AND tagsubfield='e'
19209         });
19210         $dbh->do(qq{
19211             UPDATE marc_subfield_structure SET kohafield='biblio.part_number'
19212             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='200' AND tagsubfield='h'
19213         });
19214         $dbh->do(qq{
19215             UPDATE marc_subfield_structure SET kohafield='biblio.part_name'
19216             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='200' AND tagsubfield='i'
19217         });
19218     } else {
19219         $dbh->do(qq{
19220             UPDATE marc_subfield_structure SET kohafield='biblio.medium'
19221             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='245' AND tagsubfield='h'
19222         });
19223         $dbh->do(qq{
19224             UPDATE marc_subfield_structure SET kohafield='biblio.subtitle'
19225             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='245' AND tagsubfield='b'
19226         });
19227         $dbh->do(qq{
19228             UPDATE marc_subfield_structure SET kohafield='biblio.part_number'
19229             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='245' AND tagsubfield='n'
19230         });
19231         $dbh->do(qq{
19232             UPDATE marc_subfield_structure SET kohafield='biblio.part_name'
19233             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='245' AND tagsubfield='p'
19234         });
19235     }
19236
19237     $sth = $dbh->prepare("SELECT * FROM fieldmapping");
19238     $sth->execute;
19239     my @fails_11529;
19240     if ( $sth->rows ) {
19241         while ( my $value = $sth->fetchrow_hashref() ) {
19242             my $framework =
19243               $value->{frameworkcode} eq ""
19244               ? "Default"
19245               : $value->{frameworkcode};
19246             push @fails_11529,
19247               {
19248                 field        => $value->{field},
19249                 fieldcode    => $value->{fieldcode},
19250                 subfieldcode => $value->{subfieldcode},
19251                 framework    => $framework
19252               };
19253         }
19254     }
19255
19256     $dbh->do( "DROP TABLE IF EXISTS fieldmapping" );
19257
19258     $dbh->do( "DELETE FROM user_permissions WHERE code='manage_keywords2koha_mappings'" );
19259
19260     $dbh->do( "DELETE FROM permissions WHERE code='manage_keywords2koha_mappings'" );
19261
19262     # Always end with this (adjust the bug info)
19263     SetVersion( $DBversion );
19264     print "Upgrade to $DBversion done (Bug 11529: Add medium, subtitle and part information to biblio table)\n";
19265     if ( @fails_11529 ) {
19266         print "WARNING: Keyword to MARC Mappings:\n";
19267         for my $fail_11529 ( @fails_11529 ) {
19268             print "    keyword: "
19269               . $fail_11529->{field}
19270               . " to field: "
19271               . $fail_11529->{fieldcode} . "\$"
19272               . $fail_11529->{subfieldcode} . " for "
19273               . $fail_11529->{framework}
19274               . " framework\n";
19275         }
19276         print "The keyword to marc mapping feature is no longer supported. Above find the\n";
19277         print "mappings that had been defined in your system. You will need to remap any\n";
19278         print "desired MARC fields to the Koha field you desire in the Koha to MARC mappings\n";
19279         print "page under Administration\n";
19280     }
19281     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"
19282 }
19283
19284 $DBversion = '19.06.00.019';
19285 if ( CheckVersion($DBversion) ) {
19286     $dbh->do(q{
19287         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type)
19288         VALUES
19289           (
19290             'FinePaymentAutoPopup',
19291             '0',
19292             NULL,
19293             'If enabled, automatically display a print dialog for a payment receipt when making a payment.',
19294             'YesNo'
19295           )
19296     });
19297
19298     SetVersion($DBversion);
19299     print
19300 "Upgrade to $DBversion done (Bug 23228: Add option to automatically display payment receipt for printing after making a payment)\n";
19301 }
19302
19303 $DBversion = '19.06.00.020';
19304 if( CheckVersion( $DBversion ) ) {
19305     $dbh->do(q|
19306         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
19307         ('PreserveSerialNotes','1','','When a new "Expected" issue is generated, should it be prefilled with last created issue notes?','YesNo');
19308     |);
19309
19310     SetVersion( $DBversion );
19311     print "Upgrade to $DBversion done (Bug 23416: Add PreserveSerialNotes syspref)\n";
19312 }
19313
19314 $DBversion = '19.06.00.021';
19315 if( CheckVersion( $DBversion ) ) {
19316
19317     $dbh->do(q|
19318         ALTER TABLE marc_subfield_structure CHANGE COLUMN hidden hidden TINYINT(1) DEFAULT 8 NOT NULL;
19319     |);
19320     # Always end with this (adjust the bug info)
19321     SetVersion( $DBversion );
19322     print "Upgrade to $DBversion done (Bug 23309: Can't add new subfields to bibliographic frameworks in strict mode)\n";
19323 }
19324
19325 $DBversion = '19.06.00.022';
19326 if ( CheckVersion($DBversion) ) {
19327
19328     unless ( TableExists('borrower_relationships') ) {
19329         $dbh->do(q{
19330             CREATE TABLE `borrower_relationships` (
19331                   id INT(11) NOT NULL AUTO_INCREMENT,
19332                   guarantor_id INT(11) NOT NULL,
19333                   guarantee_id INT(11) NOT NULL,
19334                   relationship VARCHAR(100) NOT NULL,
19335                   PRIMARY KEY (id),
19336                   UNIQUE KEY `guarantor_guarantee_idx` ( `guarantor_id`, `guarantee_id` ),
19337                   CONSTRAINT r_guarantor FOREIGN KEY ( guarantor_id ) REFERENCES borrowers ( borrowernumber ) ON UPDATE CASCADE ON DELETE CASCADE,
19338                   CONSTRAINT r_guarantee FOREIGN KEY ( guarantee_id ) REFERENCES borrowers ( borrowernumber ) ON UPDATE CASCADE ON DELETE CASCADE
19339             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
19340         });
19341
19342         $dbh->do(q{
19343             UPDATE borrowers
19344             LEFT JOIN borrowers guarantor ON ( borrowers.guarantorid = guarantor.borrowernumber )
19345             SET borrowers.guarantorid = NULL WHERE guarantor.borrowernumber IS NULL;
19346         });
19347
19348         # Bad data handling: guarantorid IS NOT NULL AND relationship IS NULL
19349         $dbh->do(q{
19350             UPDATE borrowers
19351             SET relationship = '_bad_data'
19352             WHERE guarantorid IS NOT NULL AND
19353                   relationship IS NULL
19354         });
19355
19356         $dbh->do(q{
19357             INSERT INTO borrower_relationships ( guarantor_id, guarantee_id, relationship )
19358             SELECT guarantorid, borrowernumber, relationship FROM borrowers WHERE guarantorid IS NOT NULL;
19359         });
19360
19361         # Clean migrated guarantor data
19362         $dbh->do(q{
19363             UPDATE borrowers
19364             SET contactname=NULL,
19365                 contactfirstname=NULL,
19366                 relationship=NULL
19367             WHERE guarantorid IS NOT NULL
19368         });
19369     }
19370
19371     if ( column_exists( 'borrowers', 'guarantorid' ) ) {
19372         $dbh->do(q{
19373             ALTER TABLE borrowers DROP guarantorid;
19374         });
19375     }
19376
19377     if ( column_exists( 'deletedborrowers', 'guarantorid' ) ) {
19378         $dbh->do(q{
19379             ALTER TABLE deletedborrowers DROP guarantorid;
19380         });
19381     }
19382
19383     if ( column_exists( 'borrower_modifications', 'guarantorid' ) ) {
19384         $dbh->do(q{
19385             ALTER TABLE borrower_modifications DROP guarantorid;
19386         });
19387     }
19388
19389     SetVersion($DBversion);
19390     print "Upgrade to $DBversion done (Bug 14570: Make it possible to add multiple guarantors to a record)\n";
19391 }
19392
19393 $DBversion = '19.06.00.023';
19394 if( CheckVersion( $DBversion ) ) {
19395     $dbh->do(q{
19396         INSERT IGNORE INTO `systempreferences` (`variable`,`value`,`explanation`,`options`,`type`) VALUES
19397         ('ElasticsearchMARCFormat', 'ISO2709', 'ISO2709|ARRAY', 'Elasticsearch MARC format. ISO2709 format is recommended as it is faster and takes less space, whereas array is searchable.', 'Choice')
19398     });
19399
19400     SetVersion( $DBversion );
19401     print "Upgrade to $DBversion done (Bug 22258: Add ElasticsearchMARCFormat preference)\n";
19402 }
19403
19404 $DBversion = '19.06.00.024';
19405 if( CheckVersion( $DBversion ) ) {
19406     $dbh->do(q{ALTER TABLE accountlines CHANGE COLUMN accounttype accounttype varchar(80) default NULL});
19407
19408     SetVersion( $DBversion );
19409     print "Upgrade to $DBversion done (Bug 23539: accountlines.accounttype should match authorised_values.authorised_value in size)\n";
19410 }
19411
19412 $DBversion = '19.06.00.025';
19413 if( CheckVersion( $DBversion ) ) {
19414     $dbh->do( q/INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES (?, ?, ?, ?, ?)/, undef, 'BarcodeSeparators','\s\r\n','','Splitting characters for barcodes','Free' );
19415     SetVersion( $DBversion );
19416     print "Upgrade to $DBversion done (Bug 22996: Add pref BarcodeSeparators)\n";
19417 }
19418
19419 $DBversion = '19.06.00.026';
19420 if( CheckVersion( $DBversion ) ) {
19421
19422     unless ( column_exists( 'borrowers', 'privacy_guarantor_fines' ) ) {
19423         $dbh->do(q{
19424             ALTER TABLE borrowers
19425                 ADD privacy_guarantor_fines TINYINT(1) NOT NULL DEFAULT '0' AFTER privacy;
19426         });
19427     }
19428
19429     unless ( column_exists( 'deletedborrowers', 'privacy_guarantor_fines' ) ) {
19430         $dbh->do(q{
19431             ALTER TABLE deletedborrowers
19432                 ADD privacy_guarantor_fines TINYINT(1) NOT NULL DEFAULT '0' AFTER privacy;
19433         });
19434     }
19435
19436     $dbh->do(q{
19437         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type )
19438         VALUES (
19439             'AllowStaffToSetFinesVisibilityForGuarantor',  '0', NULL,
19440             'If enabled, library staff can set a patron''s fines to be visible to linked patrons from the opac.',  'YesNo'
19441         ), (
19442             'AllowPatronToSetFinesVisibilityForGuarantor',  '0', NULL,
19443             'If enabled, the patron can set fines to be visible to  his or her guarantor',  'YesNo'
19444         )
19445     });
19446
19447     SetVersion( $DBversion );
19448     print "Upgrade to $DBversion done (Bug 20691: Add ability for guarantors to view guarantee's fines in OPAC)\n";
19449 }
19450
19451 $DBversion = '19.06.00.027';
19452 if( CheckVersion( $DBversion ) ) {
19453
19454     if( !TableExists( 'itemtypes_branches' ) ) {
19455        $dbh->do( "
19456             CREATE TABLE itemtypes_branches( -- association table between authorised_values and branches
19457                 itemtype VARCHAR(10) NOT NULL,
19458                 branchcode VARCHAR(10) NOT NULL,
19459                 FOREIGN KEY (itemtype) REFERENCES itemtypes(itemtype) ON DELETE CASCADE,
19460                 FOREIGN KEY (branchcode) REFERENCES branches(branchcode) ON DELETE CASCADE
19461             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
19462         ");
19463     }
19464
19465     SetVersion( $DBversion );
19466     print "Upgrade to $DBversion done (Bug 15497: Add itemtypes_branches table)\n";
19467 }
19468
19469 $DBversion = '19.06.00.028';
19470 if ( CheckVersion($DBversion) ) {
19471
19472     $dbh->do(qq{
19473         UPDATE
19474           accountlines
19475         SET
19476           accounttype = 'ACCOUNT'
19477         WHERE
19478           accounttype = 'A';
19479     });
19480
19481     SetVersion($DBversion);
19482     print "Upgrade to $DBversion done (Bug 11573: Fix accounttypes for 'A')\n";
19483 }
19484
19485 $DBversion = '19.06.00.029';
19486 if ( CheckVersion($DBversion) ) {
19487
19488     unless ( TableExists( 'cash_registers' ) ) {
19489         $dbh->do(qq{
19490     CREATE TABLE `cash_registers` (
19491     `id` int(11) NOT NULL auto_increment, -- unique identifier for each account register
19492     `name` varchar(24) NOT NULL, -- the user friendly identifier for each account register
19493     `description` longtext NOT NULL, -- the user friendly description for each account register
19494     `branch` varchar(10) NOT NULL, -- the foreign key the library this account register belongs
19495     `branch_default` tinyint(1) NOT NULL DEFAULT 0, -- boolean flag to denote that this till is the branch default
19496     `starting_float` decimal(28, 6), -- the starting float this account register should be assigned
19497     `archived` tinyint(1) NOT NULL DEFAULT 0, -- boolean flag to denote if this till is archived or not
19498     PRIMARY KEY (`id`),
19499     UNIQUE KEY `name` (`name`,`branch`),
19500     CONSTRAINT cash_registers_branch FOREIGN KEY (branch) REFERENCES branches (branchcode) ON UPDATE CASCADE ON DELETE CASCADE
19501     ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
19502         });
19503     }
19504
19505     unless ( column_exists( 'accountlines', 'register_id' ) ) {
19506         $dbh->do(qq{ALTER TABLE `accountlines` ADD `register_id` int(11) NULL DEFAULT NULL AFTER `manager_id`});
19507         $dbh->do(qq{
19508             ALTER TABLE `accountlines`
19509             ADD CONSTRAINT `accountlines_ibfk_registers` FOREIGN KEY (`register_id`)
19510             REFERENCES `cash_registers` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
19511         });
19512     }
19513
19514     $dbh->do(qq{
19515         INSERT IGNORE INTO `userflags` (`bit`, `flag`, `flagdesc`, `defaulton`)
19516         VALUES (25, 'cash_management', 'Cash management', 0)
19517     });
19518
19519     $dbh->do(qq{
19520         INSERT IGNORE permissions (module_bit, code, description)
19521         VALUES
19522         (25, 'manage_cash_registers', 'Add and remove cash registers')
19523     });
19524
19525     $dbh->do(qq{
19526         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
19527         ('UseCashRegisters','0','','Use cash registers with the accounting system and assign patron transactions to them.','YesNo')
19528     });
19529
19530     SetVersion($DBversion);
19531     print "Upgrade to $DBversion done (Bug 23321: Add cash_registers table, permissions and preferences)\n";
19532 }
19533
19534 $DBversion = '19.06.00.030';
19535 if( CheckVersion( $DBversion ) ) {
19536
19537     if ( !TableExists('club_holds') ) {
19538         $dbh->do(q|
19539             CREATE TABLE club_holds (
19540                 id        INT(11) NOT NULL AUTO_INCREMENT,
19541                 club_id   INT(11) NOT NULL, -- id for the club the hold was generated for
19542                 biblio_id INT(11) NOT NULL, -- id for the bibliographic record the hold has been placed against
19543                 item_id   INT(11) NULL DEFAULT NULL, -- If item-level, the id for the item the hold has been placed agains
19544                 date_created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, -- Timestamp for the placed hold
19545                 PRIMARY KEY (id),
19546                 -- KEY club_id (club_id),
19547                 CONSTRAINT clubs_holds_ibfk_1 FOREIGN KEY (club_id)   REFERENCES clubs  (id) ON DELETE CASCADE ON UPDATE CASCADE,
19548                 CONSTRAINT clubs_holds_ibfk_2 FOREIGN KEY (biblio_id) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE,
19549                 CONSTRAINT clubs_holds_ibfk_3 FOREIGN KEY (item_id)   REFERENCES items  (itemnumber) ON DELETE CASCADE ON UPDATE CASCADE
19550             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
19551         |);
19552     }
19553
19554     if ( !TableExists('club_holds_to_patron_holds') ) {
19555         $dbh->do(q|
19556             CREATE TABLE club_holds_to_patron_holds (
19557                 id              INT(11) NOT NULL AUTO_INCREMENT,
19558                 club_hold_id    INT(11) NOT NULL,
19559                 patron_id       INT(11) NOT NULL,
19560                 hold_id         INT(11),
19561                 error_code      ENUM ( 'damaged', 'ageRestricted', 'itemAlreadyOnHold',
19562                                     'tooManyHoldsForThisRecord', 'tooManyReservesToday',
19563                                     'tooManyReserves', 'notReservable', 'cannotReserveFromOtherBranches',
19564                                     'libraryNotFound', 'libraryNotPickupLocation', 'cannotBeTransferred'
19565                                 ) NULL DEFAULT NULL,
19566                 error_message   varchar(100) NULL DEFAULT NULL,
19567                 PRIMARY KEY (id),
19568                 -- KEY club_hold_id (club_hold_id),
19569                 CONSTRAINT clubs_holds_paton_holds_ibfk_1 FOREIGN KEY (club_hold_id) REFERENCES club_holds (id) ON DELETE CASCADE ON UPDATE CASCADE,
19570                 CONSTRAINT clubs_holds_paton_holds_ibfk_2 FOREIGN KEY (patron_id) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE,
19571                 CONSTRAINT clubs_holds_paton_holds_ibfk_3 FOREIGN KEY (hold_id) REFERENCES reserves (reserve_id) ON DELETE CASCADE ON UPDATE CASCADE
19572             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
19573         |);
19574     }
19575
19576     # Always end with this (adjust the bug info)
19577     SetVersion( $DBversion );
19578     print "Upgrade to $DBversion done (Bug 19618: add club_holds tables)\n";
19579 }
19580
19581 $DBversion = '19.06.00.031';
19582 if( CheckVersion( $DBversion ) ) {
19583     $dbh->do(q|
19584         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
19585         ('OPACDetailQRCode','0','','Enable the display of a QR Code on the OPAC detail page','YesNo');
19586     |);
19587
19588     SetVersion( $DBversion );
19589     print "Upgrade to $DBversion done (Bug 23566: Add OPACDetailQRCode system preference)\n";
19590 }
19591
19592 $DBversion = '19.06.00.032';
19593 if ( CheckVersion($DBversion) ) {
19594     if ( !column_exists( 'search_marc_to_field', 'search' ) ) {
19595         $dbh->do(q|
19596             ALTER TABLE `search_marc_to_field` ADD COLUMN `search` tinyint(1) NOT NULL DEFAULT 1
19597         |);
19598     }
19599     if ( !column_exists( 'search_field', 'staff_client' ) ) {
19600         $dbh->do(q|
19601             ALTER TABLE `search_field` ADD COLUMN `staff_client` tinyint(1) NOT NULL DEFAULT 1
19602         |);
19603     }
19604     if ( !column_exists( 'search_field', 'opac' ) ) {
19605         $dbh->do(q|
19606             ALTER TABLE `search_field` ADD COLUMN `opac` tinyint(1) NOT NULL DEFAULT 1
19607         |);
19608     }
19609
19610     SetVersion($DBversion);
19611     print
19612 "Upgrade to $DBversion done (Bug 20589: Add field boosting and use elastic query fields parameter instead of depricated _all)\n";
19613 }
19614
19615 $DBversion = '19.06.00.033';
19616 if( CheckVersion( $DBversion ) ) {
19617
19618     $dbh->do(qq{
19619         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
19620         ('OnSiteCheckoutAutoCheck','0','','Enable/Do not enable onsite checkout by default if last checkout was an onsite checkout','YesNo')
19621     });
19622     SetVersion( $DBversion );
19623     print "Upgrade to $DBversion done (Bug 23686: Add OnSiteCheckoutAutoCheck system preference)\n";
19624 }
19625
19626 $DBversion = '19.06.00.034';
19627 if( CheckVersion( $DBversion ) ) {
19628     $dbh->do(q{
19629         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
19630         ('TransfersBlockCirc','1',NULL,'Should the transfer modal block circulation staff from continuing scanning items','YesNo')
19631     });
19632     SetVersion( $DBversion );
19633     print "Upgrade to $DBversion done (Bug 23007: Make transfer modals optionally block circ)\n";
19634 }
19635
19636 $DBversion = '19.06.00.035';
19637 if( CheckVersion( $DBversion ) ) {
19638
19639     $dbh->do(q{
19640         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
19641         ( 'IntranetCoce','0', NULL, 'If on, enables cover retrieval from the configured Coce server in the staff client', 'YesNo')
19642     });
19643
19644     $dbh->do(qq{
19645         UPDATE systempreferences SET 
19646           variable = 'OpacCoce', 
19647           explanation = 'If on, enables cover retrieval from the configured Coce server in the OPAC'
19648         WHERE 
19649           variable = 'Coce'
19650     });
19651
19652     SetVersion( $DBversion );
19653     print "Upgrade to $DBversion done (Bug 18421: Add Coce image cache to the Intranet)\n";
19654 }
19655
19656 $DBversion = '19.06.00.036';
19657 if( CheckVersion( $DBversion ) ) {
19658
19659     $dbh->do(q{
19660         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type`) VALUES  
19661         ('QueryRegexEscapeOptions', 'escape', 'dont_escape|escape|unescape_escaped', 'Escape option for regexps delimiters in Elasicsearch queries.', 'Choice')
19662     });
19663
19664     SetVersion( $DBversion );
19665     print "Upgrade to $DBversion done (Bug 20334: Add elasticsearch escape options preference)\n";
19666 }
19667
19668 $DBversion = '19.06.00.037';
19669 if( CheckVersion( $DBversion ) ) {
19670     $dbh->do(q{
19671         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
19672         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')
19673     });
19674
19675     SetVersion( $DBversion );
19676     print "Upgrade to $DBversion done (Bug 21701: PayPal return URL option)\n";
19677 }
19678
19679 $DBversion = '19.06.00.038';
19680 if( CheckVersion( $DBversion ) ) {
19681     $dbh->do( "UPDATE systempreferences SET variable='PatronAutoComplete' WHERE variable='CircAutocompl' LIMIT 1" );
19682     SetVersion( $DBversion );
19683     print "Upgrade to $DBversion done (Bug 23697: Rename CircAutocompl system preference to PatronAutoComplete)\n";
19684 }
19685
19686 $DBversion = '19.06.00.039';
19687 if( CheckVersion( $DBversion ) ) {
19688     $dbh->do(q|
19689         INSERT IGNORE INTO keyboard_shortcuts (shortcut_name, shortcut_keys) VALUES
19690         ("copy_line","Ctrl-C"),
19691         ("copy_subfield","Shift-Ctrl-C"),
19692         ("paste_line","Ctrl-P"),
19693         ("insert_line","Ctrl-I")
19694         ;
19695     |);
19696     SetVersion( $DBversion );
19697     print "Upgrade to $DBversion done (Bug 17179: Add additional keyboard_shortcuts)\n";
19698 }
19699
19700 $DBversion = '19.06.00.040';
19701 if( CheckVersion( $DBversion ) ) {
19702     $dbh->do(q|
19703         INSERT IGNORE INTO systempreferences
19704         (variable,value,explanation,options,type)
19705         VALUES
19706         ('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')
19707     |);
19708
19709     SetVersion( $DBversion );
19710     print "Upgrade to $DBversion done (Bug 17140: Add pref to allow rounding fines at payment)\n";
19711 }
19712
19713 $DBversion = '19.06.00.041';
19714 if( CheckVersion( $DBversion ) ) {
19715     my ($socialnetworks) = $dbh->selectrow_array( q|
19716         SELECT value FROM systempreferences WHERE variable='socialnetworks';
19717     |);
19718     if( $socialnetworks ){
19719         # If the socialnetworks preference is enabled, enable all social networks
19720         $dbh->do("UPDATE systempreferences SET value = 'email,facebook,linkedin,twitter', explanation = 'email|facebook|linkedin|twitter', type = 'multiple'  WHERE variable = 'SocialNetworks'");
19721     } else {
19722         $dbh->do("UPDATE systempreferences SET value = '', explanation = 'email|facebook|linkedin|twitter', type = 'multiple'  WHERE variable = 'SocialNetworks'");
19723     }
19724     SetVersion ($DBversion);
19725     print "Upgrade to $DBversion done (Bug 22880: Allow granular control of socialnetworks preference)\n";
19726 }
19727
19728 $DBversion = '19.06.00.042';
19729 if( CheckVersion( $DBversion ) ) {
19730     $dbh->do(q{
19731         INSERT IGNORE INTO systempreferences
19732             ( variable, value, options, explanation, type )
19733         VALUES
19734             ('CustomCoverImages','0',NULL,'If enabled, the custom cover images will be displayed in the staff client. CustomCoverImagesURL must be defined.','YesNo'),
19735             ('OPACCustomCoverImages','0',NULL,'If enabled, the custom cover images will be displayed at the OPAC. CustomCoverImagesURL must be defined.','YesNo'),
19736             ('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')
19737     });
19738
19739     SetVersion( $DBversion );
19740     print "Upgrade to $DBversion done (Bug 22445: Add new pref *CustomCoverImages*)\n";
19741 }
19742
19743 $DBversion = '19.06.00.043';
19744 if ( CheckVersion($DBversion) ) {
19745
19746     # Adding account_debit_types
19747     if ( !TableExists('account_debit_types') ) {
19748         $dbh->do(
19749             qq{
19750                 CREATE TABLE account_debit_types (
19751                   code varchar(80) NOT NULL,
19752                   description varchar(200) NULL,
19753                   can_be_added_manually tinyint(4) NOT NULL DEFAULT 1,
19754                   default_amount decimal(28, 6) NULL,
19755                   is_system tinyint(1) NOT NULL DEFAULT 0,
19756                   archived tinyint(1) NOT NULL DEFAULT 0,
19757                   PRIMARY KEY (code)
19758                 ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci
19759               }
19760         );
19761     }
19762
19763     # Adding account_debit_types_branches
19764     if ( !TableExists('account_debit_types_branches') ) {
19765         $dbh->do(
19766             qq{
19767                 CREATE TABLE account_debit_types_branches (
19768                     debit_type_code VARCHAR(80),
19769                     branchcode VARCHAR(10),
19770                     FOREIGN KEY (debit_type_code) REFERENCES account_debit_types(code) ON DELETE CASCADE,
19771                     FOREIGN KEY (branchcode) REFERENCES branches(branchcode) ON DELETE CASCADE
19772                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
19773             }
19774         );
19775     }
19776
19777     # Populating account_debit_types
19778     $dbh->do(
19779         qq{
19780             INSERT IGNORE INTO account_debit_types (
19781               code,
19782               description,
19783               can_be_added_manually,
19784               default_amount,
19785               is_system
19786             )
19787             VALUES
19788               ('ACCOUNT', 'Account creation fee', 0, NULL, 1),
19789               ('ACCOUNT_RENEW', 'Account renewal fee', 0, NULL, 1),
19790               ('RESERVE_EXPIRED', 'Hold waiting too long', 0, NULL, 1),
19791               ('LOST', 'Lost item', 1, NULL, 1),
19792               ('MANUAL', 'Manual fee', 1, NULL, 0),
19793               ('NEW_CARD', 'New card fee', 1, NULL, 1),
19794               ('OVERDUE', 'Overdue fine', 0, NULL, 1),
19795               ('PROCESSING', 'Lost item processing fee', 0, NULL, 1),
19796               ('RENT', 'Rental fee', 0, NULL, 1),
19797               ('RENT_DAILY', 'Daily rental fee', 0, NULL, 1),
19798               ('RENT_RENEW', 'Renewal of rental item', 0, NULL, 1),
19799               ('RENT_DAILY_RENEW', 'Renewal of daily rental item', 0, NULL, 1),
19800               ('RESERVE', 'Hold fee', 0, NULL, 1)
19801         }
19802     );
19803
19804     # Update accountype 'Res' to 'RESERVE'
19805     $dbh->do(
19806         qq{
19807           UPDATE accountlines SET accounttype = 'RESERVE' WHERE accounttype = 'Res'
19808         }
19809     );
19810
19811     # Update accountype 'PF' to 'PROCESSING'
19812     $dbh->do(
19813         qq{
19814           UPDATE accountlines SET accounttype = 'PROCESSING' WHERE accounttype = 'PF'
19815         }
19816     );
19817
19818     # Update accountype 'HE' to 'RESERVE_EXPIRED'
19819     $dbh->do(
19820         qq{
19821           UPDATE accountlines SET accounttype = 'RESERVE_EXPIRED' WHERE accounttype = 'HE'
19822         }
19823     );
19824
19825     # Update accountype 'N' to 'NEW_CARD'
19826     $dbh->do(
19827         qq{
19828           UPDATE accountlines SET accounttype = 'NEW_CARD' WHERE accounttype = 'N'
19829         }
19830     );
19831
19832     # Update accountype 'M' to 'MANUAL'
19833     $dbh->do(
19834         qq{
19835           UPDATE accountlines SET accounttype = 'MANUAL' WHERE accounttype = 'M'
19836         }
19837     );
19838
19839     # Catch 'F' cases introduced since bug 22521
19840     $dbh->do(qq{
19841         UPDATE
19842           accountlines
19843         SET
19844           accounttype = 'OVERDUE',
19845           status = 'RETURNED'
19846         WHERE
19847           accounttype = 'F';
19848     });
19849
19850     # Moving MANUAL_INV to account_debit_types
19851     $dbh->do(
19852         qq{
19853             INSERT IGNORE INTO account_debit_types (
19854               code,
19855               default_amount,
19856               description,
19857               can_be_added_manually,
19858               is_system
19859             )
19860             SELECT
19861               authorised_value,
19862               lib,
19863               authorised_value,
19864               1,
19865               0
19866             FROM
19867               authorised_values
19868             WHERE
19869               category = 'MANUAL_INV'
19870           }
19871     );
19872
19873     # Update uncaught partial accounttypes left behind after bugs 23539 and 22521
19874     my $sth = $dbh->prepare( "SELECT code, SUBSTR(code, 1,5) AS subcode FROM account_debit_types" );
19875     $sth->execute();
19876     while ( my $row = $sth->fetchrow_hashref ) {
19877         $dbh->do(
19878             qq{
19879               UPDATE accountlines SET accounttype = ? WHERE accounttype = ?
19880             },
19881             {},
19882             (
19883                 $row->{code},
19884                 $row->{subcode}
19885             )
19886         );
19887     }
19888
19889     # Add any unexpected accounttype codes to debit_types as appropriate
19890     $dbh->do(
19891         qq{
19892           INSERT IGNORE INTO account_debit_types (
19893             code,
19894             description,
19895             can_be_added_manually,
19896             default_amount,
19897             is_system
19898           )
19899           SELECT
19900             DISTINCT(accounttype),
19901             "Unexpected type found during upgrade",
19902             1,
19903             NULL,
19904             0
19905           FROM
19906             accountlines
19907           WHERE
19908             amount >= 0
19909         }
19910     );
19911
19912     # Adding debit_type_code to accountlines
19913     unless ( column_exists('accountlines', 'debit_type_code') ) {
19914         $dbh->do(
19915             qq{
19916                 ALTER TABLE accountlines
19917                 ADD
19918                   debit_type_code varchar(80) DEFAULT NULL
19919                 AFTER
19920                   accounttype
19921               }
19922         );
19923     }
19924
19925     # Linking debit_type_code in accountlines to code in account_debit_types
19926     unless ( foreign_key_exists( 'accountlines', 'accountlines_ibfk_debit_type' ) ) {
19927         $dbh->do(
19928             qq{
19929             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
19930               }
19931         );
19932     }
19933
19934     # Populating debit_type_code
19935     $dbh->do(
19936         qq{
19937         UPDATE accountlines SET debit_type_code = accounttype, accounttype = NULL WHERE accounttype IN (SELECT code from account_debit_types) AND amount >= 0
19938         }
19939     );
19940
19941     # Remove MANUAL_INV
19942     $dbh->do(
19943         qq{
19944         DELETE FROM authorised_values WHERE category = 'MANUAL_INV'
19945         }
19946     );
19947     $dbh->do(
19948         qq{
19949         DELETE FROM authorised_value_categories WHERE category_name = 'MANUAL_INV'
19950         }
19951     );
19952
19953     # Add new permission
19954     $dbh->do(
19955         q{
19956             INSERT IGNORE INTO permissions (module_bit, code, description)
19957             VALUES
19958               (
19959                 3,
19960                 'manage_accounts',
19961                 'Manage Account Debit and Credit Types'
19962               )
19963         }
19964     );
19965
19966     SetVersion($DBversion);
19967     print "Upgrade to $DBversion done (Bug 23049: Add account debit_types)\n";
19968 }
19969
19970 $DBversion = '19.06.00.044';
19971 if ( CheckVersion($DBversion) ) {
19972
19973     # Adding account_credit_types
19974     if ( !TableExists('account_credit_types') ) {
19975         $dbh->do(
19976             qq{
19977                 CREATE TABLE account_credit_types (
19978                   code varchar(80) NOT NULL,
19979                   description varchar(200) NULL,
19980                   can_be_added_manually tinyint(4) NOT NULL DEFAULT 1,
19981                   is_system tinyint(1) NOT NULL DEFAULT 0,
19982                   PRIMARY KEY (code)
19983                 ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci
19984               }
19985         );
19986     }
19987
19988     # Adding account_credit_types_branches
19989     if ( !TableExists('account_credit_types_branches') ) {
19990         $dbh->do(
19991             qq{
19992                 CREATE TABLE account_credit_types_branches (
19993                     credit_type_code VARCHAR(80),
19994                     branchcode VARCHAR(10),
19995                     FOREIGN KEY (credit_type_code) REFERENCES account_credit_types(code) ON DELETE CASCADE,
19996                     FOREIGN KEY (branchcode) REFERENCES branches(branchcode) ON DELETE CASCADE
19997                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
19998             }
19999         );
20000     }
20001
20002     # Populating account_credit_types
20003     $dbh->do(
20004         qq{
20005             INSERT IGNORE INTO account_credit_types (
20006               code,
20007               description,
20008               can_be_added_manually,
20009               is_system
20010             )
20011             VALUES
20012               ('PAYMENT', 'Payment', 0, 1),
20013               ('WRITEOFF', 'Writeoff', 0, 1),
20014               ('FORGIVEN', 'Forgiven', 1, 1),
20015               ('CREDIT', 'Credit', 1, 1),
20016               ('LOST_RETURN', 'Lost item fee refund', 0, 1)
20017         }
20018     );
20019
20020     # Adding credit_type_code to accountlines
20021     unless ( column_exists('accountlines', 'credit_type_code') ) {
20022         $dbh->do(
20023             qq{
20024                 ALTER TABLE accountlines
20025                 ADD
20026                   credit_type_code varchar(80) DEFAULT NULL
20027                 AFTER
20028                   accounttype
20029               }
20030         );
20031     }
20032
20033     # Catch LOST_RETURNED cases from original bug 22563 update
20034     $dbh->do(
20035         qq{
20036             UPDATE accountlines
20037             SET accounttype = 'LOST_RETURN'
20038             WHERE accounttype = 'LOST_RETURNED'
20039     });
20040
20041     # Linking credit_type_code in accountlines to code in account_credit_types
20042     unless ( foreign_key_exists( 'accountlines', 'accountlines_ibfk_credit_type' ) ) {
20043         $dbh->do(
20044             qq{
20045                 ALTER TABLE accountlines
20046                 ADD CONSTRAINT
20047                   `accountlines_ibfk_credit_type`
20048                 FOREIGN KEY (`credit_type_code`) REFERENCES `account_credit_types` (`code`)
20049                 ON DELETE RESTRICT
20050                 ON UPDATE CASCADE
20051               }
20052         );
20053     }
20054
20055     # Update accountype 'C' to 'CREDIT'
20056     $dbh->do(
20057         qq{
20058           UPDATE accountlines SET accounttype = 'CREDIT' WHERE accounttype = 'C' OR accounttype = 'CR'
20059         }
20060     );
20061
20062     # Update accountype 'FOR' to 'FORGIVEN'
20063     $dbh->do(
20064         qq{
20065           UPDATE accountlines SET accounttype = 'FORGIVEN' WHERE accounttype = 'FOR' OR accounttype = 'FORW'
20066         }
20067     );
20068
20069     # Update accountype 'Pay' to 'PAYMENT'
20070     $dbh->do(
20071         qq{
20072           UPDATE accountlines SET accounttype = 'PAYMENT' WHERE accounttype = 'Pay' OR accounttype = 'PAY'
20073         }
20074     );
20075
20076     # Update accountype 'W' to 'WRITEOFF'
20077     $dbh->do(
20078         qq{
20079           UPDATE accountlines SET accounttype = 'WRITEOFF' WHERE accounttype = 'W' OR accounttype = 'WO'
20080         }
20081     );
20082
20083     # Add any unexpected accounttype codes to credit_types as appropriate
20084     $dbh->do(
20085         qq{
20086           INSERT IGNORE INTO account_credit_types (
20087             code,
20088             description,
20089             can_be_added_manually,
20090             is_system
20091           )
20092           SELECT
20093             DISTINCT(accounttype),
20094             "Unexpected type found during upgrade",
20095             1,
20096             0
20097           FROM
20098             accountlines
20099           WHERE
20100             amount < 0
20101         }
20102     );
20103
20104     # Populating credit_type_code
20105     $dbh->do(
20106         qq{
20107           UPDATE
20108             accountlines 
20109           SET
20110             credit_type_code = accounttype, accounttype = NULL
20111           WHERE accounttype IN (SELECT code from account_credit_types)
20112         }
20113     );
20114
20115     # Drop accounttype field
20116     $dbh->do(
20117         qq{
20118           ALTER TABLE accountlines
20119           DROP COLUMN `accounttype`
20120         }
20121     );
20122
20123     SetVersion($DBversion);
20124     print "Upgrade to $DBversion done (Bug 23805: Add account credit_types)\n";
20125 }
20126
20127 $DBversion = '19.06.00.045';
20128 if( CheckVersion( $DBversion ) ) {
20129     $dbh->do( "UPDATE systempreferences SET value = '2' WHERE value = '0' AND variable = 'UsageStats'" );
20130
20131     SetVersion( $DBversion );
20132     print "Upgrade to $DBversion done (Bug 23866: Set HEA syspref to prompt for review)\n";
20133 }
20134
20135 $DBversion = '19.06.00.046';
20136 if( CheckVersion( $DBversion ) ) {
20137     $dbh->do(qq{
20138         UPDATE systempreferences
20139         SET 
20140           options = "Calendar|Days|Datedue|Dayweek", 
20141           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"
20142         WHERE
20143           variable = "useDaysMode"
20144     });
20145
20146     # Always end with this (adjust the bug info)
20147     SetVersion( $DBversion );
20148     print "Upgrade to $DBversion done (Bug 15260: Option for extended loan with useDaysMode)\n";
20149 }
20150
20151 $DBversion = '19.06.00.047';
20152 if ( CheckVersion($DBversion) ) {
20153     if ( !TableExists('return_claims') ) {
20154         $dbh->do(
20155             q{
20156             CREATE TABLE return_claims (
20157                 id int(11) auto_increment,                             -- Unique ID of the return claim
20158                 itemnumber int(11) NOT NULL,                           -- ID of the item
20159                 issue_id int(11) NULL DEFAULT NULL,                    -- ID of the checkout that triggered the claim
20160                 borrowernumber int(11) NOT NULL,                       -- ID of the patron
20161                 notes MEDIUMTEXT DEFAULT NULL,                         -- Notes about the claim
20162                 created_on TIMESTAMP NULL,                             -- Time and date the claim was created
20163                 created_by int(11) NULL DEFAULT NULL,                  -- ID of the staff member that registered the claim
20164                 updated_on TIMESTAMP NULL ON UPDATE CURRENT_TIMESTAMP, -- Time and date of the latest change on the claim (notes)
20165                 updated_by int(11) NULL DEFAULT NULL,                  -- ID of the staff member that updated the claim
20166                 resolution  varchar(80) NULL DEFAULT NULL,             -- Resolution code (RETURN_CLAIM_RESOLUTION AVs)
20167                 resolved_on TIMESTAMP NULL DEFAULT NULL,               -- Time and date the claim was resolved
20168                 resolved_by int(11) NULL DEFAULT NULL,                 -- ID of the staff member that resolved the claim
20169                 PRIMARY KEY (`id`),
20170                 KEY `itemnumber` (`itemnumber`),
20171                 CONSTRAINT UNIQUE `issue_id` ( issue_id ),
20172                 CONSTRAINT `issue_id` FOREIGN KEY (`issue_id`) REFERENCES `issues` (`issue_id`) ON DELETE SET NULL ON UPDATE CASCADE,
20173                 CONSTRAINT `rc_items_ibfk` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
20174                 CONSTRAINT `rc_borrowers_ibfk` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
20175                 CONSTRAINT `rc_created_by_ibfk` FOREIGN KEY (`created_by`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE,
20176                 CONSTRAINT `rc_updated_by_ibfk` FOREIGN KEY (`updated_by`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE,
20177                 CONSTRAINT `rc_resolved_by_ibfk` FOREIGN KEY (`resolved_by`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE
20178             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
20179         }
20180         );
20181     }
20182
20183     $dbh->do(
20184         q{
20185         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
20186         ('ClaimReturnedChargeFee', 'ask', 'ask|charge|no_charge', 'Controls whether or not a lost item fee is charged for return claims', 'Choice'),
20187         ('ClaimReturnedLostValue', '', '', 'Sets the LOST AV value that represents "Claims returned" as a lost value', 'Free'),
20188         ('ClaimReturnedWarningThreshold', '', '', 'Sets the number of return claims past which the librarian will be warned the patron has many return claims', 'Integer');
20189     }
20190     );
20191
20192     $dbh->do(
20193         q{
20194         INSERT IGNORE INTO authorised_value_categories ( category_name ) VALUES
20195             ('RETURN_CLAIM_RESOLUTION');
20196     }
20197     );
20198
20199     $dbh->do(
20200         q{
20201         INSERT IGNORE INTO `authorised_values` ( category, authorised_value, lib )
20202         VALUES
20203           ('RETURN_CLAIM_RESOLUTION', 'RET_BY_PATRON', 'Returned by patron'),
20204           ('RETURN_CLAIM_RESOLUTION', 'FOUND_IN_LIB', 'Found in library');
20205     }
20206     );
20207
20208     SetVersion($DBversion);
20209     print
20210 "Upgrade to $DBversion done (Bug 14697: Extend and enhance 'Claims returned' lost status)\n";
20211 }
20212
20213 $DBversion = '19.06.00.048';
20214 if( CheckVersion( $DBversion ) ) {
20215     # you can use $dbh here like:
20216     $dbh->do( qq{
20217         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
20218         VALUES  ('OPACShowMusicalInscripts','0','','Display musical inscripts on the OPAC record details page when available.','YesNo'),
20219                 ('OPACPlayMusicalInscripts','0','','If displayed musical inscripts, play midi conversion on the OPAC record details page.','YesNo')
20220     } );
20221
20222     SetVersion( $DBversion );
20223     print "Upgrade to $DBversion done (Bug 22581: add new OPACShowMusicalInscripts and OPACPlayMusicalInscripts system preferences)\n";
20224 }
20225
20226 $DBversion = '19.06.00.049';
20227 if( CheckVersion( $DBversion ) ) {
20228
20229     $dbh->do(q{
20230         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
20231         SELECT
20232             'SuspensionsCalendar',
20233             IF( value='noFinesWhenClosed', 'noSuspensionsWhenClosed', 'ignoreCalendar'),
20234             'ignoreCalendar|noSuspensionsWhenClosed',
20235             'Specify whether to use the Calendar in calculating suspensions',
20236             'Choice'
20237         FROM systempreferences
20238         WHERE variable='finesCalendar';
20239     });
20240
20241     SetVersion( $DBversion );
20242     print "Upgrade to $DBversion done (Bug 13958: Add a SuspensionsCalendar syspref)\n";
20243 }
20244
20245 $DBversion = '19.06.00.050';
20246 if( CheckVersion( $DBversion ) ) {
20247     $dbh->do( q{
20248             INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
20249             VALUES ('OPACFineNoRenewalsIncludeCredits','1',NULL,'If enabled the value specified in OPACFineNoRenewals should include any unapplied account credits in the calculation','YesNo')
20250     });
20251
20252     SetVersion( $DBversion );
20253     print "Upgrade to $DBversion done (Bug 23293: Add 'OPACFineNoRenewalsIncludeCredits' system preference)\n";
20254 }
20255
20256 $DBversion = '19.11.00.000';
20257 if( CheckVersion( $DBversion ) ) {
20258     NewVersion( $DBversion, undef, '19.11.00 release' );
20259 }
20260
20261 $DBversion = '19.12.00.000';
20262 if( CheckVersion( $DBversion ) ) {
20263     NewVersion( $DBversion, undef, 'Dobbie is a free elf...' );
20264 }
20265
20266 $DBversion = '19.12.00.001';
20267 if( CheckVersion( $DBversion ) ) {
20268     $dbh->do( "UPDATE marc_subfield_structure SET kohafield = NULL WHERE kohafield = 'bibliosubject.subject';" );
20269     NewVersion( $DBversion, 17831, 'Remove non-existing bibliosubject.subject from frameworks' );
20270 }
20271
20272 $DBversion = '19.12.00.002';
20273 if( CheckVersion( $DBversion ) ) {
20274     $dbh->do(q{
20275         UPDATE systempreferences SET
20276         variable = 'AllowItemsOnHoldCheckoutSIP',
20277         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.'
20278         WHERE variable = 'AllowItemsOnHoldCheckout'
20279     });
20280
20281     NewVersion( $DBversion, 23233, 'Rename AllowItemsOnHoldCheckout syspref' );
20282 }
20283
20284 $DBversion = '19.12.00.003';
20285 if( CheckVersion( $DBversion ) ) {
20286
20287     if( !column_exists( 'library_groups', 'ft_local_hold_group' ) ) {
20288         $dbh->do( "ALTER TABLE library_groups ADD COLUMN ft_local_hold_group tinyint(1) NOT NULL DEFAULT 0 AFTER ft_search_groups_staff" );
20289     }
20290
20291     NewVersion( $DBversion, 22284, 'Add ft_local_hold_group column to library_groups' );
20292 }
20293
20294 $DBversion = '19.12.00.004';
20295 if ( CheckVersion($DBversion) ) {
20296
20297     $dbh->do(
20298         qq{
20299             INSERT IGNORE INTO account_debit_types (
20300               code,
20301               description,
20302               can_be_added_manually,
20303               default_amount,
20304               is_system
20305             )
20306             VALUES
20307               ('PAYOUT', 'Payment from library to patron', 0, NULL, 1)
20308         }
20309     );
20310
20311     $dbh->do(qq{
20312         INSERT IGNORE INTO account_offset_types ( type ) VALUES ('PAYOUT');
20313     });
20314
20315     $dbh->do(qq{
20316         INSERT IGNORE permissions (module_bit, code, description)
20317         VALUES
20318         (10, 'payout', 'Perform account payout action')
20319     });
20320
20321     NewVersion( $DBversion, 24080, ['Add PAYOUT account_debit_type', 'Add PAYOUT account_offset_type', 'Add accounts payout permission'] );
20322 }
20323
20324 $DBversion = '19.12.00.005';
20325 if( CheckVersion( $DBversion ) ) {
20326     $dbh->do( "ALTER TABLE action_logs MODIFY COLUMN `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP" );
20327
20328     NewVersion( $DBversion, 24329, 'Do not update action_log.timestamp' );
20329 }
20330
20331 $DBversion = '19.12.00.006';
20332 if( CheckVersion( $DBversion ) ) {
20333     $dbh->do( q|
20334         UPDATE borrowers SET relationship = NULL
20335         WHERE relationship = ""
20336     |);
20337
20338     NewVersion( $DBversion, 24263, 'Replace relationship with NULL when empty string' );
20339 }
20340
20341 $DBversion = '19.12.00.007';
20342 if ( CheckVersion($DBversion) ) {
20343
20344     $dbh->do(
20345         qq{
20346             INSERT IGNORE INTO account_credit_types (code, description, can_be_added_manually, is_system)
20347             VALUES
20348               ('REFUND', 'A refund applied to a patrons fine', 0, 1)
20349         }
20350     );
20351
20352     $dbh->do(qq{
20353         INSERT IGNORE INTO account_offset_types ( type ) VALUES ('REFUND');
20354     });
20355
20356     $dbh->do(qq{
20357         INSERT IGNORE permissions (module_bit, code, description)
20358         VALUES
20359         (10, 'refund', 'Perform account refund action')
20360     });
20361
20362     NewVersion( $DBversion, 23442, ['Add REFUND to account_credit_types', 'Add REFUND to account_offset_types', 'Add accounts refund permission'] );
20363 }
20364
20365 $DBversion = '19.12.00.008';
20366 if( CheckVersion( $DBversion ) ) {
20367     $dbh->do( 'UPDATE systempreferences SET value = REPLACE(value, "http://worldcat.org", "https://worldcat.org") WHERE variable = "OPACSearchForTitleIn"' );
20368     $dbh->do( 'UPDATE systempreferences SET value = REPLACE(value, "http://www.bookfinder.com", "https://www.bookfinder.com") WHERE variable = "OPACSearchForTitleIn"' );
20369     $dbh->do( 'UPDATE systempreferences SET value = REPLACE(value, "https://openlibrary.org/search/?", "https://openlibrary.org/search?") WHERE variable = "OPACSearchForTitleIn"' );
20370
20371     NewVersion( $DBversion, 24206, 'Update OpacSearchForTitleIn system preference' );
20372 }
20373
20374 $DBversion = '19.12.00.009';
20375 if( CheckVersion( $DBversion ) ) {
20376
20377     $dbh->do(q{
20378         INSERT IGNORE INTO account_offset_types ( type ) VALUES ( 'Purchase' );
20379     });
20380
20381     $dbh->do(q{
20382         INSERT IGNORE INTO account_credit_types ( code, description, can_be_added_manually, is_system )
20383         VALUES ('PURCHASE', 'Purchase', 0, 1);
20384     });
20385
20386     my $sth = $dbh->prepare(q{
20387         SELECT COUNT(*) FROM authorised_values WHERE category = 'PAYMENT_TYPE' AND authorised_value = 'CASH'
20388     });
20389     $sth->execute;
20390     my $already_exists = $sth->fetchrow;
20391     if ( not $already_exists ) {
20392         $dbh->do(q{
20393            INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('PAYMENT_TYPE','CASH','Cash')
20394         });
20395     }
20396
20397     # Updating field in account_debit_types
20398     unless ( column_exists('account_debit_types', 'can_be_invoiced') ) {
20399         $dbh->do(
20400             qq{
20401                 ALTER TABLE account_debit_types
20402                 CHANGE COLUMN
20403                   can_be_added_manually can_be_invoiced tinyint(1) NOT NULL DEFAULT 1
20404               }
20405         );
20406     }
20407     unless ( column_exists('account_debit_types', 'can_be_sold') ) {
20408         $dbh->do(
20409             qq{
20410                 ALTER TABLE account_debit_types
20411                 ADD
20412                   can_be_sold tinyint(1) DEFAULT 0
20413                 AFTER
20414                   can_be_invoiced
20415               }
20416         );
20417     }
20418
20419     $dbh->do(q{
20420 INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`, `lang`) VALUES
20421 ('pos', 'RECEIPT', '', 'Point of sale receipt', 0, 'Receipt', '[% PROCESS "accounts.inc" %]
20422 <table>
20423 [% IF ( LibraryName ) %]
20424  <tr>
20425     <th colspan="2" class="centerednames">
20426         <h3>[% LibraryName | html %]</h3>
20427     </th>
20428  </tr>
20429 [% END %]
20430  <tr>
20431     <th colspan="2" class="centerednames">
20432         <h2>[% Branches.GetName( payment.branchcode ) | html %]</h2>
20433     </th>
20434  </tr>
20435 <tr>
20436     <th colspan="2" class="centerednames">
20437         <h3>[% payment.date | $KohaDates %]</h3>
20438 </tr>
20439 <tr>
20440   <td>Transaction ID: </td>
20441   <td>[% payment.accountlines_id %]</td>
20442 </tr>
20443 <tr>
20444   <td>Operator ID: </td>
20445   <td>[% payment.manager_id %]</td>
20446 </tr>
20447 <tr>
20448   <td>Payment type: </td>
20449   <td>[% payment.payment_type %]</td>
20450 </tr>
20451  <tr></tr>
20452  <tr>
20453     <th colspan="2" class="centerednames">
20454         <h2><u>Fee receipt</u></h2>
20455     </th>
20456  </tr>
20457  <tr></tr>
20458  <tr>
20459     <th>Description of charges</th>
20460     <th>Amount</th>
20461   </tr>
20462
20463   [% FOREACH offset IN offsets %]
20464     <tr>
20465         <td>[% PROCESS account_type_description account=offset.debit %]</td>
20466         <td>[% offset.amount * -1 | $Price %]</td>
20467     </tr>
20468   [% END %]
20469
20470 <tfoot>
20471   <tr class="highlight">
20472     <td>Total: </td>
20473     <td>[% payment.amount * -1| $Price %]</td>
20474   </tr>
20475   <tr>
20476     <td>Tendered: </td>
20477     <td>[% collected | $Price %]</td>
20478   </tr>
20479   <tr>
20480     <td>Change: </td>
20481     <td>[% change | $Price %]</td>
20482     </tr>
20483 </tfoot>
20484 </table>', 'print', 'default');
20485     });
20486
20487     $dbh->do(qq{
20488         INSERT IGNORE permissions (module_bit, code, description)
20489         VALUES
20490         (25, 'takepayment', 'Access the point of sale page and take payments')
20491     });
20492
20493     NewVersion( $DBversion, 23354, [q|Add 'Purchase' account offset type|, q|Add 'RECEIPT' notice for Point of Sale|, q|Add point of sale permissions|] );
20494 }
20495
20496 $DBversion = '19.12.00.010';
20497 if( CheckVersion( $DBversion ) ) {
20498     if( !column_exists( 'oai_sets_mappings', 'rule_order' ) ) {
20499         $dbh->do( "ALTER TABLE oai_sets_mappings ADD COLUMN rule_order INT AFTER set_id, ADD COLUMN rule_operator VARCHAR(3) AFTER rule_order" );
20500         $dbh->do( "UPDATE oai_sets_mappings SET rule_operator='or'" );
20501         my $sets = $dbh->selectall_arrayref("SELECT * from oai_sets_mappings ORDER BY set_id", { Slice => {} });
20502         my $i = 0;
20503         my $previous_set_id;
20504         for my $set ( @{$sets}) {
20505             my $set_id = $set->{set_id};
20506     
20507             if ($previous_set_id && $previous_set_id != $set_id) {
20508                 $i = 0;
20509             }
20510     
20511             if ($i == 0) {
20512                 $dbh->do("UPDATE oai_sets_mappings SET rule_operator=NULL WHERE set_id=? LIMIT 1", {}, $set_id);
20513             }
20514     
20515             $dbh->do("UPDATE oai_sets_mappings SET rule_order=? WHERE set_id=? AND rule_order IS NULL LIMIT 1", {}, $i, $set_id);
20516     
20517             $i++;
20518             $previous_set_id = $set_id;
20519         }
20520     }
20521
20522     NewVersion( $DBversion, 21520, 'Add rule_order and rule_operator fields to oai_sets_mappings table' );
20523 }
20524
20525 $DBversion = '19.12.00.011';
20526 if( CheckVersion( $DBversion ) ) {
20527     if( !foreign_key_exists( 'repeatable_holidays', 'repeatable_holidays_ibfk_1' ) ) {
20528         $dbh->do(q|
20529             DELETE h
20530             FROM repeatable_holidays h
20531             LEFT JOIN branches b ON h.branchcode=b.branchcode
20532             WHERE b.branchcode IS NULL;
20533         |);
20534         $dbh->do(q|
20535             ALTER TABLE repeatable_holidays
20536             ADD FOREIGN KEY repeatable_holidays_ibfk_1 (branchcode) REFERENCES branches (branchcode) ON DELETE CASCADE ON UPDATE CASCADE
20537         |);
20538     }
20539
20540     if( !foreign_key_exists( 'special_holidays', 'special_holidays_ibfk_1' ) ) {
20541         $dbh->do(q|
20542             DELETE h
20543             FROM special_holidays h
20544             LEFT JOIN branches b ON h.branchcode=b.branchcode
20545             WHERE b.branchcode IS NULL;
20546         |);
20547         $dbh->do(q|
20548             ALTER TABLE special_holidays
20549             ADD FOREIGN KEY special_holidays_ibfk_1 (branchcode) REFERENCES branches (branchcode) ON DELETE CASCADE ON UPDATE CASCADE
20550         |);
20551     }
20552
20553     NewVersion( $DBversion, 24289, 'Adding foreign keys on *_holidays.branchcode tables' );
20554 }
20555
20556 $DBversion = '19.12.00.012';
20557 if( CheckVersion( $DBversion ) ) {
20558
20559     $dbh->do(qq{
20560         UPDATE
20561           `permissions`
20562         SET
20563           `module_bit` = 3
20564         WHERE
20565           `code` = 'manage_cash_registers'
20566     });
20567
20568     NewVersion( $DBversion, 24481, 'Move permission to correct module_bit' );
20569 }
20570
20571 $DBversion = '19.12.00.013';
20572 if( CheckVersion( $DBversion ) ) {
20573     $dbh->do(qq{
20574         INSERT IGNORE INTO 
20575           systempreferences (variable,value,options,explanation,type)
20576         VALUES
20577           ('EnablePointOfSale','0',NULL,'Enable the point of sale feature to allow anonymous transactions with the accounting system. (Requires UseCashRegisters)','YesNo')
20578     });
20579
20580     NewVersion( $DBversion, 24478, 'Add `EnablePointOfSale` system preference to allow disabling the point of sale feature)' );
20581 }
20582
20583 $DBversion = '19.12.00.014';
20584 if( CheckVersion( $DBversion ) ) {
20585     unless ( column_exists('branchtransfers', 'reason') ) {
20586         $dbh->do(
20587             qq{
20588                 ALTER TABLE branchtransfers
20589                 ADD
20590                   `reason` enum('Manual')
20591                 AFTER
20592                   comments
20593               }
20594         );
20595     }
20596
20597     NewVersion( $DBversion, 24287, q|Add 'reason' field to transfers table| );
20598 }
20599
20600 $DBversion = '19.12.00.015';
20601 if( CheckVersion( $DBversion ) ) {
20602
20603     # Add stockrotation states to reason enum
20604     $dbh->do(
20605         qq{
20606             ALTER TABLE
20607                 `branchtransfers`
20608             MODIFY COLUMN
20609                 `reason` enum(
20610                     'Manual',
20611                     'StockrotationAdvance',
20612                     'StockrotationRepatriation'
20613                 )
20614             AFTER `comments`
20615           }
20616     );
20617
20618     # Move stockrotation states to reason field
20619     $dbh->do(
20620         qq{
20621             UPDATE
20622               `branchtransfers`
20623             SET
20624               `reason` = 'StockrotationAdvance',
20625               `comments` = NULL
20626             WHERE
20627               `comments` = 'StockrotationAdvance'
20628           }
20629     );
20630     $dbh->do(
20631         qq{
20632             UPDATE
20633               `branchtransfers`
20634             SET
20635               `reason` = 'StockrotationRepatriation',
20636               `comments` = NULL
20637             WHERE
20638               `comments` = 'StockrotationRepatriation'
20639           }
20640     );
20641
20642     NewVersion( $DBversion, 24296, q|Update stockrotation to use 'reason' field in transfers table| );
20643 }
20644
20645 $DBversion = '19.12.00.016';
20646 if( CheckVersion( $DBversion ) ) {
20647     $dbh->do(q{
20648         INSERT IGNORE INTO `userflags` (`bit`, `flag`, `flagdesc`, `defaulton`)
20649         VALUES (12, 'suggestions', 'Suggestion management', 0)
20650     });
20651
20652     $dbh->do(q{
20653         UPDATE permissions SET module_bit=12
20654         WHERE code="suggestions_manage"
20655     });
20656
20657     $dbh->do(q{
20658         UPDATE borrowers SET flags = flags | (1<<12) WHERE flags & (1 << 11)
20659     });
20660
20661     NewVersion( $DBversion, 22868, 'Move suggestions_manage subpermission out of acquisition permission' );
20662 }
20663
20664 $DBversion = '19.12.00.017';
20665 if( CheckVersion( $DBversion ) ) {
20666     if( !index_exists( 'library_groups', 'library_groups_uniq_2' ) ) {
20667         $dbh->do(q|
20668             DELETE FROM library_groups
20669             WHERE id NOT IN (
20670                 SELECT MIN(id)
20671                 FROM ( SELECT * FROM library_groups ) AS lg
20672                 GROUP BY parent_id, branchcode
20673             )
20674             AND NOT(parent_id IS NULL OR branchcode IS NULL);
20675         |);
20676         $dbh->do(q|
20677             ALTER TABLE library_groups
20678             ADD UNIQUE KEY library_groups_uniq_2 (parent_id, branchcode)
20679         |);
20680     }
20681
20682     NewVersion( $DBversion, 21674, 'Add unique key (parent_id, branchcode) to library_group' );
20683 }
20684
20685 $DBversion = '19.12.00.018';
20686 if( CheckVersion( $DBversion ) ) {
20687     my @columns = qw(
20688         restrictedtype
20689         rentaldiscount
20690         fine
20691         finedays
20692         maxsuspensiondays
20693         suspension_chargeperiod
20694         firstremind
20695         chargeperiod
20696         chargeperiod_charge_at
20697         accountsent
20698         issuelength
20699         lengthunit
20700         hardduedate
20701         hardduedatecompare
20702         renewalsallowed
20703         renewalperiod
20704         norenewalbefore
20705         auto_renew
20706         no_auto_renewal_after
20707         no_auto_renewal_after_hard_limit
20708         reservesallowed
20709         holds_per_record
20710         holds_per_day
20711         onshelfholds
20712         opacitemholds
20713         overduefinescap
20714         cap_fine_to_replacement_price
20715         article_requests
20716         note
20717     );
20718
20719     $dbh->do(q|
20720         DELETE i FROM issuingrules i
20721         LEFT JOIN itemtypes it ON i.itemtype=it.itemtype
20722         WHERE it.itemtype IS NULL AND i.itemtype!='*'
20723     |);
20724     $dbh->do(q|
20725         DELETE i FROM issuingrules i
20726         LEFT JOIN branches b ON i.branchcode=b.branchcode
20727         WHERE b.branchcode IS NULL AND i.branchcode!='*'
20728     |);
20729     $dbh->do(q|
20730         DELETE i FROM issuingrules i
20731         LEFT JOIN categories c ON i.categorycode=c.categorycode
20732         WHERE c.categorycode IS NULL AND i.categorycode!='*'
20733     |);
20734     if ( column_exists( 'issuingrules', 'categorycode' ) ) {
20735         foreach my $column ( @columns ) {
20736             $dbh->do("
20737                 INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
20738                 SELECT IF(categorycode='*', NULL, categorycode), IF(branchcode='*', NULL, branchcode), IF(itemtype='*', NULL, itemtype), \'$column\', COALESCE( $column, '' )
20739                 FROM issuingrules
20740             ");
20741         }
20742         $dbh->do("
20743             DELETE FROM circulation_rules WHERE rule_name='holdallowed' AND rule_value='';
20744         ");
20745         $dbh->do("DROP TABLE issuingrules");
20746     }
20747
20748     NewVersion( $DBversion, 18936, 'Convert issuingrules fields to circulation_rules' );
20749 }
20750
20751 $DBversion = '19.12.00.019';
20752 if( CheckVersion( $DBversion ) ) {
20753
20754     $dbh->do("ALTER TABLE message_queue MODIFY time_queued timestamp NULL");
20755
20756     if( !column_exists( 'message_queue', 'updated_on' ) ) {
20757         $dbh->do("ALTER TABLE message_queue ADD COLUMN updated_on timestamp NOT NULL default CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER time_queued");
20758         $dbh->do("UPDATE message_queue SET updated_on=time_queued");
20759     }
20760
20761     NewVersion( $DBversion, 23673, 'modify time_queued and add updated_on to message_queue' );
20762 }
20763
20764 $DBversion = '19.12.00.020';
20765 if ( CheckVersion($DBversion) ) {
20766     if ( !column_exists( 'marc_subfield_structure', 'important') ){
20767         $dbh->do("ALTER TABLE marc_subfield_structure ADD COLUMN important TINYINT(4) NOT NULL DEFAULT 0  AFTER mandatory");
20768     }
20769     if ( !column_exists( 'marc_tag_structure', 'important') ){
20770         $dbh->do("ALTER TABLE marc_tag_structure ADD COLUMN important TINYINT(4) NOT NULL DEFAULT 0  AFTER mandatory");
20771     }
20772
20773     NewVersion( $DBversion, 8643, 'Add important constraint to marc subfields' );
20774 }
20775
20776 $DBversion = '19.12.00.021';
20777 if( CheckVersion( $DBversion ) ) {
20778
20779     # Add LOST_FOUND debit type
20780     $dbh->do(qq{
20781         INSERT IGNORE INTO
20782           account_credit_types ( code, description, can_be_added_manually, is_system )
20783         VALUES
20784           ('LOST_FOUND', 'Lost item fee refund', 0, 1)
20785     });
20786
20787     # Migrate LOST_RETURN to LOST_FOUND
20788     $dbh->do(qq{
20789         UPDATE
20790           accountlines
20791         SET
20792           credit_type_code = 'LOST_FOUND'
20793         WHERE
20794           credit_type_code = 'LOST_RETURN'
20795         OR
20796           credit_type_code = 'LOST_RETURNED'
20797     });
20798
20799     # Migrate LOST + RETURNED to LOST + FOUND
20800     $dbh->do(qq{
20801         UPDATE
20802           accountlines
20803         SET
20804           status = 'FOUND'
20805         WHERE
20806           debit_type_code = 'LOST'
20807         AND
20808           status = 'RETURNED'
20809     });
20810
20811     # Drop LOST_RETURNED credit type
20812     $dbh->do(qq{
20813         DELETE FROM account_credit_types WHERE code = 'LOST_RETURNED'
20814     });
20815
20816     # Drop LOST_RETURN credit type
20817     $dbh->do(qq{
20818         DELETE FROM account_credit_types WHERE code = 'LOST_RETURN'
20819     });
20820
20821     # Add Lost Item Found offset type
20822     $dbh->do(qq{
20823         INSERT IGNORE INTO
20824           account_offset_types ( type )
20825         VALUES
20826           ( 'Lost Item Found' )
20827     });
20828
20829     NewVersion( $DBversion, 24592, 'Update LOST_RETURN to LOST_FOUND');
20830 }
20831
20832 $DBversion = '19.12.00.022';
20833 if( CheckVersion( $DBversion ) ) {
20834     $dbh->do( "ALTER TABLE items MODIFY COLUMN uri MEDIUMTEXT" );
20835     $dbh->do( "ALTER TABLE deleteditems MODIFY COLUMN uri MEDIUMTEXT" );
20836
20837     NewVersion( $DBversion, 20882, 'items.uri to MEDIUMTEXT');
20838 }
20839
20840 $DBversion = '19.12.00.023';
20841 if( CheckVersion( $DBversion ) ) {
20842     $dbh->do( "ALTER TABLE quotes MODIFY timestamp datetime NULL" );
20843
20844     NewVersion( $DBversion, 24640, 'Allow quotes.timestamp to be NULL');
20845 }
20846
20847 $DBversion = '19.12.00.024';
20848 if( CheckVersion( $DBversion ) ) {
20849     $dbh->do(q{
20850         UPDATE systempreferences SET value = 'off'
20851         WHERE variable = 'finesMode' AND (value <> 'production' OR value IS NULL)
20852     });
20853     $dbh->do(q{
20854         UPDATE systempreferences SET options = 'off|production',
20855         explanation = "Choose the fines mode, 'off' (do not accrue fines) or 'production' (accrue overdue fines).  Requires accruefines cronjob or CalculateFinesOnReturn system preference."
20856         WHERE variable = 'finesMode'
20857     });
20858
20859     NewVersion( $DBversion, 21633, 'Remove finesMode "test"');
20860 }
20861
20862 $DBversion = '19.12.00.025';
20863 if( CheckVersion( $DBversion ) ) {
20864     $dbh->do(q{
20865         INSERT IGNORE INTO `systempreferences` (variable,value,options,explanation,type)
20866         VALUES ('DumpSearchQueryTemplate',0,'','Add the search query being passed to the search engine into the template for debugging','YesNo')
20867     });
20868
20869     NewVersion( $DBversion, 24103, 'add DumpSearchQueryTemplate syspref');
20870 }
20871
20872 $DBversion = '19.12.00.026';
20873 if( CheckVersion( $DBversion ) ) {
20874     if( !column_exists( 'z3950servers', 'attributes' ) ) {
20875         $dbh->do( "ALTER TABLE z3950servers ADD COLUMN attributes VARCHAR(255) after add_xslt" );
20876     }
20877
20878     NewVersion( $DBversion, 11297, 'Add support for custom PQF attributes for Z39.50 server searches');
20879 }
20880
20881 $DBversion = '19.12.00.027';
20882 if( CheckVersion( $DBversion ) ) {
20883
20884     # Add any pathalogical incorrect debit_types as credit_types as appropriate
20885     $dbh->do(
20886         qq{
20887           INSERT IGNORE INTO account_credit_types (
20888             code,
20889             description,
20890             can_be_added_manually,
20891             is_system
20892           )
20893           SELECT
20894             DISTINCT(debit_type_code),
20895             "Unexpected type found during upgrade",
20896             1,
20897             0
20898           FROM
20899             accountlines
20900           WHERE
20901             amount < 0
20902           AND
20903             debit_type_code IS NOT NULL
20904         }
20905     );
20906
20907     # Correct any pathalogical cases
20908     $dbh->do( qq{
20909       UPDATE
20910         accountlines
20911       SET
20912         credit_type_code = debit_type_code,
20913         debit_type_code = NULL
20914       WHERE
20915         amount < 0
20916       AND
20917         debit_type_code IS NOT NULL
20918     });
20919
20920     NewVersion( $DBversion, 24532, 'Fix pathological cases of negative debits');
20921 }
20922
20923 $DBversion = '19.12.00.028';
20924 if( CheckVersion( $DBversion ) ) {
20925     $dbh->do(q{
20926         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
20927         VALUES
20928         ('OpacBrowseSearch', '0',NULL, "Elasticsearch only: add a page allowing users to 'browse' all items in the collection",'YesNo')
20929     });
20930
20931     NewVersion( $DBversion, 14567, 'Add OpacBrowseSearch syspref');
20932 }
20933
20934 $DBversion = '19.12.00.029';
20935 if( CheckVersion( $DBversion ) ) {
20936     if (!column_exists('account_credit_types', 'archived')) {
20937         $dbh->do('ALTER TABLE account_credit_types ADD COLUMN archived tinyint(1) NOT NULL DEFAULT 0 AFTER is_system');
20938     }
20939
20940     NewVersion( $DBversion, 17702, 'Add column account_credit_types.archived');
20941 }
20942
20943 $DBversion = '19.12.00.030';
20944 if( CheckVersion( $DBversion ) ) {
20945
20946     # get list of installed translations
20947     require C4::Languages;
20948     my @langs;
20949     my $tlangs = C4::Languages::getTranslatedLanguages('opac','bootstrap');
20950
20951     foreach my $language ( @$tlangs ) {
20952         foreach my $sublanguage ( @{$language->{'sublanguages_loop'}} ) {
20953             push @langs, $sublanguage->{'rfc4646_subtag'};
20954         }
20955     }
20956
20957     # Get any existing value from the opacheader system preference
20958     my ($opacheader) = $dbh->selectrow_array( q|
20959         SELECT value FROM systempreferences WHERE variable='opacheader';
20960     |);
20961
20962     my @detail;
20963     if( $opacheader ){
20964         foreach my $lang ( @langs ) {
20965             # If there is a value in the opacheader preference, insert it into opac_news
20966             $dbh->do("INSERT INTO opac_news (branchcode, lang, title, content ) VALUES (NULL, ?, '', ?)", undef, "opacheader_$lang", $opacheader);
20967             push @detail, "Inserted opacheader contents into $lang news item...";
20968         }
20969     }
20970     # Remove the opacheader system preference
20971     $dbh->do("DELETE FROM systempreferences WHERE variable='opacheader'");
20972
20973     unshift @detail, 'Move contents of opacheader preference to Koha news system';
20974     NewVersion( $DBversion, 22880, \@detail);
20975 }
20976
20977 $DBversion = '19.12.00.031';
20978 if( CheckVersion( $DBversion ) ) {
20979     $dbh->do( q|
20980 ALTER TABLE article_requests MODIFY COLUMN created_on timestamp NULL, MODIFY COLUMN updated_on timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
20981     |);
20982
20983     NewVersion( $DBversion, 22273, "Column article_requests.created_on should not be updated" );
20984 }
20985
20986 $DBversion = '19.12.00.032';
20987 if( CheckVersion( $DBversion ) ) {
20988     $dbh->do( q|
20989         DELETE FROM systempreferences WHERE variable="UseQueryParser"
20990     |);
20991
20992     NewVersion( $DBversion, 24735, "Remove UseQueryParser system preference" );
20993 }
20994
20995 $DBversion = '19.12.00.033';
20996 if ( CheckVersion($DBversion) ) {
20997
20998     # Add cash_register_actions table
20999     if ( !TableExists('cash_register_actions') ) {
21000         $dbh->do(qq{
21001             CREATE TABLE `cash_register_actions` (
21002               `id` int(11) NOT NULL auto_increment, -- unique identifier for each account register action
21003               `code` varchar(24) NOT NULL, -- action code denoting the type of action recorded (enum),
21004               `register_id` int(11) NOT NULL, -- id of cash_register this action belongs to,
21005               `manager_id` int(11) NOT NULL, -- staff member performing the action
21006               `amount` decimal(28,6) DEFAULT NULL, -- amount recorded in action (signed)
21007               `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
21008               PRIMARY KEY (`id`),
21009               CONSTRAINT `cash_register_actions_manager` FOREIGN KEY (`manager_id`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
21010               CONSTRAINT `cash_register_actions_register` FOREIGN KEY (`register_id`) REFERENCES `cash_registers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
21011             ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
21012         });
21013     }
21014
21015     # Add cashup permission
21016     $dbh->do(qq{
21017         INSERT IGNORE permissions (module_bit, code, description)
21018         VALUES
21019         (25, 'cashup', 'Perform cash register cashup action')
21020     });
21021
21022     NewVersion( $DBversion, 23355, [ "Add cash_register_actions table", "Add cash register cashup permissions" ] );
21023 }
21024
21025 $DBversion = '19.12.00.034';
21026 if ( CheckVersion($DBversion) ) {
21027
21028     $dbh->do(
21029         qq{
21030             INSERT IGNORE INTO account_credit_types (code, description, can_be_added_manually, is_system)
21031             VALUES
21032               ('DISCOUNT', 'A discount applied to a patrons fine', 0, 1)
21033         }
21034     );
21035
21036     $dbh->do(
21037         qq{
21038         INSERT IGNORE INTO account_offset_types ( type ) VALUES ('DISCOUNT');
21039     }
21040     );
21041
21042     $dbh->do(
21043         qq{
21044         INSERT IGNORE permissions (module_bit, code, description)
21045         VALUES
21046         (10, 'discount', 'Perform account discount action')
21047     }
21048     );
21049
21050     NewVersion( $DBversion, 24081, "Add DISCOUNT to account_credit_types and account_offset_types, Add accounts discount permission");
21051 }
21052
21053 $DBversion = '19.12.00.035';
21054 if ( CheckVersion($DBversion) ) {
21055
21056     $dbh->do(qq{
21057         INSERT IGNORE permissions (module_bit, code, description)
21058         VALUES
21059         (25, 'anonymous_refund', 'Perform refund actions from cash registers')
21060     });
21061
21062     NewVersion( $DBversion, 23442, "Add a refund option to the point of sale system" );
21063 }
21064
21065 $DBversion = '19.12.00.036';
21066 if( CheckVersion( $DBversion ) ) {
21067     $dbh->do(q{
21068         INSERT IGNORE INTO `systempreferences`
21069             (`variable`, `value`, `options`, `explanation`, `type`)
21070         VALUES
21071             ('AccessControlAllowOrigin', '', NULL, 'Set the Access-Control-Allow-Origin header to the specified value', 'Free');
21072     });
21073
21074     NewVersion( $DBversion, 24369, "Add CORS support to Koha");
21075 }
21076
21077 $DBversion = '19.12.00.037';
21078 if( CheckVersion( $DBversion ) ) {
21079
21080     $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'); | );
21081     
21082     $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'); | );
21083
21084     NewVersion( $DBversion, 23051, [ "Add RenewAccruingItemInOpac syspref", "Add RenewAccruingItemWhenPaid syspref" ]);
21085 }
21086
21087 $DBversion = '19.12.00.038';
21088 if( CheckVersion( $DBversion ) ) {
21089     $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'); | );
21090
21091     NewVersion( $DBversion, 23112, "Add CirculateILL syspref");
21092 }
21093
21094 $DBversion = '19.12.00.039';
21095 if( CheckVersion( $DBversion ) ) {
21096     $dbh->do( "DROP TABLE IF EXISTS printers" );
21097
21098     if( column_exists( 'branches', 'branchprinter' ) ) {
21099         $dbh->do( "ALTER TABLE branches DROP COLUMN branchprinter" );
21100     }
21101
21102     $dbh->do(qq{ DELETE FROM systempreferences WHERE variable = "printcirculationslips"} );
21103
21104     NewVersion( $DBversion, 17845, "Drop unused table printers and branchprinter column");
21105 }
21106
21107 $DBversion = '19.12.00.040';
21108 if( CheckVersion( $DBversion ) ) {
21109     $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' " );
21110
21111     NewVersion( $DBversion, 17374, "Update description of DefaultPatronSearchFields");
21112 }
21113
21114 $DBversion = '19.12.00.041';
21115 if( CheckVersion( $DBversion ) ) {
21116
21117     # Update existing NULL priorities
21118     $dbh->do(q|
21119         UPDATE reserves SET priority = 1 WHERE priority IS NULL
21120     |);
21121
21122     $dbh->do(q|
21123         ALTER TABLE reserves MODIFY priority SMALLINT(6) NOT NULL DEFAULT 1
21124     |);
21125
21126     $dbh->do(q|
21127         UPDATE old_reserves SET priority = 1 WHERE priority IS NULL
21128     |);
21129
21130     $dbh->do(q|
21131         ALTER TABLE old_reserves MODIFY priority SMALLINT(6) NOT NULL DEFAULT 1
21132     |);
21133
21134     NewVersion( $DBversion, 24722, "Enforce NOT NULL constraint for reserves.priority");
21135 }
21136
21137 $DBversion = '19.12.00.042';
21138 if( CheckVersion( $DBversion ) ) {
21139     if (!column_exists('message_queue', 'reply_address')) {
21140         $dbh->do('ALTER TABLE message_queue ADD COLUMN reply_address LONGTEXT AFTER from_address');
21141     }
21142
21143     NewVersion( $DBversion, 22821, "Add reply_address to message_queue");
21144 }
21145
21146 $DBversion = '19.12.00.043';
21147 if( CheckVersion( $DBversion ) ) {
21148
21149     # Add return reasons to enum
21150     $dbh->do(
21151         qq{
21152             ALTER TABLE
21153                 `branchtransfers`
21154             MODIFY COLUMN
21155                 `reason` enum(
21156                     'Manual',
21157                     'StockrotationAdvance',
21158                     'StockrotationRepatriation',
21159                     'ReturnToHome',
21160                     'ReturnToHolding'
21161                 )
21162             AFTER `comments`
21163           }
21164     );
21165
21166     NewVersion( $DBversion, 24296, "Add 'return' reasons to branchtransfers enum");
21167 }
21168
21169 $DBversion = '19.12.00.044';
21170 if( CheckVersion( $DBversion ) ) {
21171     $dbh->do(qq{
21172         INSERT IGNORE permissions (module_bit, code, description)
21173         VALUES
21174         (13, 'batch_extend_due_dates', 'Perform batch extend due dates')
21175     });
21176
21177     NewVersion( $DBversion, 24846, "Add a new permission for new tool batch extend due dates");
21178 }
21179
21180 $DBversion = '19.12.00.045';
21181 if( CheckVersion( $DBversion ) ) {
21182     $dbh->do(q{
21183         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) 
21184         VALUES
21185         ('CollapseFieldsPatronAddForm','',NULL,'Collapse these fields by default when adding a new patron. These fields can still be expanded.','Multiple') 
21186     });
21187
21188     NewVersion( $DBversion, 4461, "Add CollapseFieldsPatronAddForm system preference");
21189 }
21190
21191 $DBversion = '19.12.00.046';
21192 if( CheckVersion( $DBversion ) ) {
21193
21194     $dbh->do( "ALTER TABLE accountlines MODIFY COLUMN date TIMESTAMP NULL" );
21195
21196     NewVersion( $DBversion, 24818, "Update 'accountlines.date' from DATE to TIMESTAMP");
21197 }
21198
21199 $DBversion = '19.12.00.047';
21200 if( CheckVersion( $DBversion ) ) {
21201     $dbh->do(q{
21202         ALTER TABLE biblioimages
21203         ADD `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
21204         AFTER `thumbnail`;
21205     });
21206
21207     NewVersion( $DBversion, 22987, "Add biblioimages.timestamp");
21208 }
21209
21210 $DBversion = '19.12.00.048';
21211 if( CheckVersion( $DBversion ) ) {
21212
21213     # Add rotating collection states to reason enum
21214     $dbh->do(
21215         qq{
21216             ALTER TABLE
21217                 `branchtransfers`
21218             MODIFY COLUMN
21219                 `reason` enum(
21220                     'Manual',
21221                     'StockrotationAdvance',
21222                     'StockrotationRepatriation',
21223                     'ReturnToHome',
21224                     'ReturnToHolding',
21225                     'RotatingCollection'
21226                 )
21227             AFTER `comments`
21228           }
21229     );
21230
21231     NewVersion( $DBversion, 24299, "Add 'collection' reasons to branchtransfers enum");
21232 }
21233
21234 $DBversion = '19.12.00.049';
21235 if( CheckVersion( $DBversion ) ) {
21236
21237     # Add reserve reasons enum
21238     $dbh->do(
21239         qq{
21240             ALTER TABLE
21241                 `branchtransfers`
21242             MODIFY COLUMN
21243                 `reason` enum(
21244                     'Manual',
21245                     'StockrotationAdvance',
21246                     'StockrotationRepatriation',
21247                     'ReturnToHome',
21248                     'ReturnToHolding',
21249                     'RotatingCollection',
21250                     'Reserve',
21251                     'LostReserve',
21252                     'CancelReserve'
21253                 )
21254             AFTER `comments`
21255           }
21256     );
21257
21258     NewVersion( $DBversion, 24299, "Add 'reserve' reasons to branchtransfers enum");
21259 }
21260
21261 $DBversion = '19.12.00.050';
21262 if( CheckVersion( $DBversion ) ) {
21263     $dbh->do( "DELETE FROM systempreferences WHERE variable in ('IDreamBooksReadometer','IDreamBooksResults','IDreamBooksReviews')" );
21264
21265     NewVersion( $DBversion, 24854, "Remove IDreamBooks* system preferences");
21266 }
21267
21268 $DBversion = '19.12.00.051';
21269 if( CheckVersion( $DBversion ) ) {
21270     $dbh->do(q{
21271         UPDATE systempreferences SET options = 'itemhomebranch|patronhomebranch|checkoutbranch|none' WHERE variable='OpacRenewalBranch'
21272     });
21273     $dbh->do(q{
21274         UPDATE systempreferences SET value = "none" WHERE variable='OpacRenewalBranch'
21275         AND value = 'NULL'
21276     });
21277     $dbh->do(q{
21278         UPDATE systempreferences SET value = 'opacrenew' WHERE variable='OpacRenewalBranch'
21279         AND value NOT IN ('checkoutbranch','itemhomebranch','opacrenew','patronhomebranch','none')
21280     });
21281
21282     NewVersion( $DBversion, 24759, "Cleanup OpacRenewalBranch");
21283 }
21284
21285 $DBversion = '19.12.00.052';
21286 if( CheckVersion( $DBversion ) ) {
21287     my $finesCalendar = C4::Context->preference('finesCalendar');
21288     my $value = $finesCalendar eq 'noFinesWhenClosed' ? 1 : 0;
21289
21290     if( !column_exists( 'itemtypes', 'rentalcharge_daily_calendar' ) ) {
21291         $dbh->do(q{
21292             ALTER TABLE itemtypes ADD COLUMN
21293             rentalcharge_daily_calendar tinyint(1) NOT NULL DEFAULT 1
21294             AFTER rentalcharge_daily;
21295         });
21296
21297         $dbh->do("UPDATE itemtypes SET rentalcharge_daily_calendar = $value");
21298     }
21299
21300     if( !column_exists( 'itemtypes', 'rentalcharge_hourly_calendar' ) ) {
21301         $dbh->do(q{
21302             ALTER TABLE itemtypes ADD COLUMN
21303             rentalcharge_hourly_calendar tinyint(1) NOT NULL DEFAULT 1
21304             AFTER rentalcharge_hourly;
21305         });
21306
21307         $dbh->do("UPDATE itemtypes SET rentalcharge_hourly_calendar = $value");
21308     }
21309
21310     NewVersion( $DBversion, 21443, "Add ability to exclude holidays when calculating rentals fees by time period");
21311 }
21312
21313 $DBversion = '19.12.00.053';
21314 if( CheckVersion( $DBversion ) ) {
21315     unless( column_exists('borrowers','autorenew_checkouts') ){
21316         $dbh->do( "ALTER TABLE borrowers ADD COLUMN autorenew_checkouts TINYINT(1) NOT NULL DEFAULT 1 AFTER anonymized" );
21317     }
21318     unless( column_exists('deletedborrowers','autorenew_checkouts') ){
21319         $dbh->do( "ALTER TABLE deletedborrowers ADD COLUMN autorenew_checkouts TINYINT(1) NOT NULL DEFAULT 1 AFTER anonymized" );
21320     }
21321     $dbh->do(q{
21322         INSERT IGNORE INTO systempreferences
21323         ( `variable`, `value`, `options`, `explanation`, `type` )
21324         VALUES
21325         ('AllowPatronToControlAutorenewal','0',NULL,'If enabled, patrons will have a field in their account to choose whether their checkouts are auto renewed or not','YesNo')
21326     });
21327
21328     NewVersion( $DBversion, 24476, "Allow patrons to opt-out of autorenewal");
21329 }
21330
21331 $DBversion = '19.12.00.054';
21332 if( CheckVersion( $DBversion ) ) {
21333
21334     if ( !TableExists('desks') ) {
21335         $dbh->do(qq{
21336              CREATE TABLE `desks` ( -- desks available in a library
21337                `desk_id` int(11) NOT NULL auto_increment, -- unique identifier added by Koha
21338                `desk_name` varchar(100) NOT NULL default '', -- name of the desk
21339                `branchcode` varchar(10) NOT NULL,       -- library the desk is located at
21340                PRIMARY KEY (`desk_id`),
21341                KEY `fk_desks_branchcode` (`branchcode`),
21342                CONSTRAINT `fk_desks_branchcode` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
21343              ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
21344         });
21345     }
21346
21347     NewVersion( $DBversion, 13881, "Add desk management");
21348 }
21349
21350 $DBversion = '19.12.00.055';
21351 if( CheckVersion( $DBversion ) ) {
21352     if( !column_exists( 'suggestions', 'lastmodificationby' ) ) {
21353         $dbh->do(q|
21354             ALTER TABLE suggestions ADD COLUMN lastmodificationby INT(11) DEFAULT NULL AFTER rejecteddate
21355         |);
21356
21357         $dbh->do(q|
21358             ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_lastmodificationby` FOREIGN KEY (`lastmodificationby`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE
21359         |);
21360     }
21361
21362     if( !column_exists( 'suggestions', 'lastmodificationdate' ) ) {
21363         $dbh->do(q|
21364             ALTER TABLE suggestions ADD COLUMN lastmodificationdate DATE DEFAULT NULL AFTER lastmodificationby
21365         |);
21366
21367         my $suggestions = $dbh->selectall_arrayref(q|
21368             SELECT suggestionid, managedby, manageddate, acceptedby, accepteddate, rejectedby, rejecteddate
21369             FROM suggestions
21370         |, { Slice => {} });
21371         for my $suggestion ( @$suggestions ) {
21372             my ( $max_date ) = sort ( $suggestion->{manageddate} || (), $suggestion->{accepteddate} || (), $suggestion->{rejecteddate} || () );
21373             next unless $max_date;
21374             my $last_modif_by = ( defined $suggestion->{manageddate} and $max_date eq $suggestion->{manageddate} )
21375               ? $suggestion->{managedby}
21376               : ( defined $suggestion->{accepteddate} and $max_date eq $suggestion->{accepteddate} )
21377               ? $suggestion->{acceptedby}
21378               : ( defined $suggestion->{rejecteddate} and $max_date eq $suggestion->{rejecteddate} )
21379               ? $suggestion->{rejectedby}
21380               : undef;
21381             next unless $last_modif_by;
21382             $dbh->do(q|
21383                 UPDATE suggestions
21384                 SET lastmodificationdate = ?, lastmodificationby = ?
21385                 WHERE suggestionid = ?
21386             |, undef, $max_date, $last_modif_by, $suggestion->{suggestionid});
21387         }
21388
21389     }
21390
21391     $dbh->do( q|
21392         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');
21393     | );
21394
21395     NewVersion( $DBversion, 23590, "Add lastmodificationby and lastmodificationdate to the suggestions table");
21396 }
21397
21398 $DBversion = '19.12.00.056';
21399 if( CheckVersion( $DBversion ) ) {
21400
21401     $dbh->do( "DELETE FROM systempreferences WHERE variable='UseKohaPlugins'" );
21402
21403     NewVersion( $DBversion, 20415, "Remove UseKohaPlugins preference");
21404 }
21405
21406 $DBversion = '19.12.00.057';
21407 if( CheckVersion( $DBversion ) ) {
21408
21409     $dbh->do( "DELETE FROM systempreferences WHERE variable='INTRAdidyoumean'" );
21410
21411     NewVersion( $DBversion, 20399, "Remove INTRAdidyoumean preference");
21412 }
21413
21414 $DBversion = '19.12.00.058';
21415 if( CheckVersion( $DBversion ) ) {
21416     $dbh->do(q{
21417         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`,`type`) VALUES
21418         ('OPACnumSearchResultsDropdown', 0, NULL, 'Enable option list of number of results per page to show in OPAC search results','YesNo'),
21419         ('numSearchResultsDropdown', 0, NULL, 'Enable option list of number of results per page to show in staff client search results','YesNo')
21420     });
21421
21422     NewVersion( $DBversion, 14715, "Add sysprefs numSearchResultsDropdown and OPACnumSearchResultsDropdown");
21423 }
21424
21425 $DBversion = '19.12.00.059';
21426 if( CheckVersion( $DBversion ) ) {
21427
21428     for my $column ( qw(othersupplier booksellerfax booksellerurl bookselleremail currency) ) {
21429         if( column_exists( 'aqbooksellers', $column ) ) {
21430             my ($count) = $dbh->selectrow_array(qq|
21431                 SELECT COUNT(*)
21432                 FROM aqbooksellers
21433                 WHERE $column IS NOT NULL AND $column <> ""
21434             |);
21435             if ( $count ) {
21436                 warn "Warning - Cannot remove column aqbooksellers.$column. At least one value exists";
21437             } else {
21438                 $dbh->do(qq|
21439                     ALTER TABLE aqbooksellers
21440                     DROP COLUMN $column
21441                 |);
21442             }
21443         }
21444     }
21445
21446     NewVersion( $DBversion, 18177, "Remove some unused columns from aqbooksellers");
21447 }
21448
21449 $DBversion = '19.12.00.060';
21450 if( CheckVersion( $DBversion ) ) {
21451     $dbh->do(q{
21452         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';
21453     });
21454     NewVersion( $DBversion, 23204, "Change enum order for marc_type in search_marc_map to fix sorting");
21455 }
21456
21457 $DBversion = '19.12.00.061';
21458 if ( CheckVersion($DBversion) ) {
21459     $dbh->do(q{
21460         UPDATE
21461           systempreferences
21462         SET
21463           options = "batchmod|moredetail|cronjob|additem|pendingreserves|onpayment"
21464         WHERE
21465           variable = "MarkLostItemsAsReturned"
21466     });
21467
21468     my $lost_item_returned = C4::Context->preference("MarkLostItemsAsReturned");
21469     my @set = split( ",", $lost_item_returned );
21470     push @set, 'onpayment';
21471     $lost_item_returned = join( ",", @set );
21472
21473     $dbh->do(qq{
21474         UPDATE
21475           systempreferences
21476         SET
21477           value = "$lost_item_returned"
21478         WHERE
21479           variable = "MarkLostItemsAsReturned"
21480     });
21481
21482     NewVersion( $DBversion, 24474, "Add `onpayment` option to MarkLostItemsAsReturned");
21483 }
21484
21485 $DBversion = '19.12.00.062';
21486 if( CheckVersion( $DBversion ) ) {
21487     $dbh->do( "UPDATE account_debit_types SET description = REPLACE(description,'Rewewal','Renewal') WHERE description like '%Rewewal%'" );
21488
21489     NewVersion( $DBversion, 25010, "Fix typo in account_debit_type description");
21490 }
21491
21492 $DBversion = '19.12.00.063';
21493 if( CheckVersion( $DBversion ) ) {
21494     $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') });
21495
21496     NewVersion( $DBversion, 22534, "Add PreFillGuaranteeField syspref");
21497 }
21498
21499 $DBversion = '19.12.00.064';
21500 if( CheckVersion( $DBversion ) ) {
21501
21502     $dbh->do( q|
21503         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
21504             SELECT 'OpacNoItemTypeImages', value, NULL, 'If ON, disables itemtype images in the OPAC','YesNo'
21505             FROM (SELECT value FROM systempreferences WHERE variable="NoItemTypeImages") tmp
21506     | );
21507     $dbh->do( "UPDATE systempreferences SET explanation = 'If ON, disables itemtype images in the staff interface'
21508         WHERE variable = 'noItemTypeImages' ");
21509
21510     NewVersion( $DBversion, 4944, "Add new system preference OpacNoItemTypeImages");
21511 }
21512
21513 $DBversion = '19.12.00.065';
21514 if( CheckVersion( $DBversion ) ) {
21515
21516     $dbh->do( q| 
21517         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type) 
21518         VALUES ('ILLCheckAvailability', '0', 'If enabled, during the ILL request process third party sources will be checked for current availability', '', 'YesNo')
21519     | );
21520
21521     NewVersion( $DBversion, 23173, "Add ILLCheckAvailability syspref");
21522 }
21523
21524 $DBversion = '19.12.00.066';
21525 if ( CheckVersion($DBversion) ) {
21526     $dbh->do(
21527 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') }
21528     );
21529     $dbh->do(
21530 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') }
21531     );
21532     if ( !TableExists('problem_reports') ) {
21533         $dbh->do(
21534             q{ CREATE TABLE problem_reports (
21535             reportid int(11) NOT NULL auto_increment, -- unique identifier assigned by Koha
21536             title varchar(40) NOT NULL default '', -- report subject line
21537             content varchar(255) NOT NULL default '', -- report message content
21538             borrowernumber int(11) NOT NULL default 0, -- the user who created the problem report
21539             branchcode varchar(10) NOT NULL default '', -- borrower's branch
21540             username varchar(75) default NULL, -- OPAC username
21541             problempage TEXT default NULL, -- page the user triggered the problem report form from
21542             recipient enum('admin','library') NOT NULL default 'library', -- the 'to-address' of the problem report
21543             created_on timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of report submission
21544             status varchar(6) NOT NULL default 'New', -- status of the report. New, Viewed, Closed
21545             PRIMARY KEY (reportid),
21546             CONSTRAINT problem_reports_ibfk1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE,
21547             CONSTRAINT problem_reports_ibfk2 FOREIGN KEY (branchcode) REFERENCES branches (branchcode) ON DELETE CASCADE ON UPDATE CASCADE
21548         ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci }
21549         );
21550     }
21551     $dbh->do(
21552 q{INSERT IGNORE INTO userflags (bit, flag, flagdesc, defaulton) VALUES (26, 'problem_reports', 'Manage problem reports', 0) }
21553     );
21554     $dbh->do(
21555 q{INSERT IGNORE INTO permissions (module_bit, code, description) VALUES (26, 'manage_problem_reports', 'Manage OPAC problem reports') }
21556     );
21557
21558     NewVersion(
21559         $DBversion,
21560         4461,
21561         [
21562             "Add OPACReportProblem system preference",
21563             "Adding PROBLEM_REPORT notice",
21564             "Add problem reports table",
21565             "Add user permissions for managing OPAC problem reports"
21566         ]
21567     );
21568 }
21569
21570 $DBversion = '19.12.00.067';
21571 if( CheckVersion( $DBversion ) ) {
21572     # From: https://stackoverflow.com/questions/3311903/remove-duplicate-rows-in-mysql
21573     $dbh->do(q|
21574         DELETE a
21575         FROM virtualshelfshares as a, virtualshelfshares as b
21576         WHERE
21577           a.id < b.id 
21578         AND
21579           a.borrowernumber IS NOT NULL
21580         AND
21581           a.borrowernumber=b.borrowernumber
21582         AND
21583           a.shelfnumber=b.shelfnumber
21584     |);
21585
21586     NewVersion( $DBversion, 20754, "Remove double accepted list shares" );
21587 }
21588
21589 $DBversion = '19.12.00.068';
21590 if( CheckVersion( $DBversion ) ) {
21591     $dbh->do(q|
21592         INSERT IGNORE INTO systempreferences
21593           (variable,value,explanation,options,type)
21594         VALUES
21595           ('AuthFailureLog','','If enabled, log authentication failures',NULL,'YesNo'),
21596           ('AuthSuccessLog','','If enabled, log successful authentications',NULL,'YesNo')
21597     |);
21598
21599     NewVersion( $DBversion, 21190, "Add prefs AuthFailureLog and AuthSuccessLog");
21600 }
21601
21602 $DBversion = '19.12.00.069';
21603 if( CheckVersion( $DBversion ) ) {
21604     if( !column_exists( 'suggestions', 'archived' ) ) {
21605         $dbh->do(q|
21606             ALTER TABLE suggestions ADD COLUMN archived TINYINT(1) NOT NULL DEFAULT 0 AFTER `STATUS`;
21607         |);
21608     }
21609
21610     NewVersion( $DBversion, 22784, "Add a new suggestions.archived column");
21611 }
21612
21613 $DBversion = '19.12.00.070';
21614 if( CheckVersion( $DBversion ) ) {
21615
21616     $dbh->do( q{
21617             INSERT IGNORE INTO systempreferences (variable,value,explanation,type) VALUES
21618                 ('MaxTotalSuggestions','','Number of total suggestions used for time limit with NumberOfSuggestionDays','Free'),
21619                 ('NumberOfSuggestionDays','','Number of days that will be used to determine the MaxTotalSuggestions limit','Free')
21620             });
21621
21622     NewVersion( $DBversion, 22774, "Limit purchase suggestion in a specified time period");
21623 }
21624
21625 $DBversion = '19.12.00.071';
21626 if( CheckVersion( $DBversion ) ) {
21627     my @description = ("Add unique constraint to authorised_values");
21628     unless ( index_exists('authorised_values', 'av_uniq') ) {
21629         $dbh->do(q|
21630             DELETE FROM authorised_values
21631             WHERE category="COUNTRY" AND authorised_value="CC" AND lib="Keeling"
21632         |);
21633         my $duplicates = $dbh->selectall_arrayref(q|
21634             SELECT category, authorised_value, COUNT(concat(category, ':', authorised_value)) AS c
21635             FROM authorised_values
21636             GROUP BY category, authorised_value
21637             HAVING COUNT(concat(category, ':', authorised_value)) > 1
21638         |, { Slice => {} });
21639         if ( @$duplicates ) {
21640             push @description, "WARNING - Cannot create unique constraint on authorised_value(category, authorised_value)";
21641             push @description, "The following entries are duplicated: " . join(
21642                 ', ',
21643                 map {
21644                     sprintf "%s:%s (%s)", $_->{category},
21645                       $_->{authorised_value}, $_->{c}
21646                 } @$duplicates
21647             );
21648             for my $warning (@description) {
21649                 warn $warning;
21650             }
21651         } else {
21652             $dbh->do( q{ALTER TABLE `authorised_values` ADD CONSTRAINT `av_uniq` UNIQUE (category, authorised_value)} );
21653         }
21654     }
21655
21656     NewVersion( $DBversion, 22887, \@description );
21657 }
21658
21659 $DBversion = '19.12.00.072';
21660 if( CheckVersion( $DBversion ) ) {
21661     $dbh->do(q{
21662         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
21663             SELECT 'CalculateFinesOnBackdate',value,'','Switch to control if overdue fines are calculated on return when backdating','YesNo'
21664             FROM ( SELECT value FROM systempreferences WHERE variable = 'CalculateFinesOnReturn' ) tmp
21665     });
21666
21667     NewVersion( $DBversion, 24380, "Add syspref CalculateFinesOnBackdate");
21668 }
21669
21670 $DBversion = '19.12.00.073';
21671 if( CheckVersion( $DBversion ) ) {
21672     $dbh->do( "ALTER TABLE subscription MODIFY COLUMN closed tinyint(1) not null default 0" );
21673
21674     NewVersion( $DBversion, 25152, "Update subscription.closed to tinyint(1) as per guidelines");
21675 }
21676
21677 $DBversion = '19.12.00.074';
21678 if( CheckVersion( $DBversion ) ) {
21679     $dbh->do( "UPDATE systempreferences SET variable = 'SCOAllowCheckin' WHERE variable = 'AllowSelfCheckReturns'" );
21680
21681     # Always end with this (adjust the bug info)
21682     NewVersion( $DBversion, 25147, "Rename AllowSelfCheckReturns to SCOAllowCheckin for consistency");
21683 }
21684
21685 $DBversion = '19.12.00.075';
21686 if( CheckVersion( $DBversion ) ) {
21687
21688     $dbh->do( "ALTER TABLE borrower_modifications MODIFY changed_fields MEDIUMTEXT DEFAULT NULL" );
21689
21690     NewVersion( $DBversion, 25086, "Set changed_fields column of borrower_modifications as nullable");
21691 }
21692
21693 $DBversion = '19.12.00.076';
21694 if( CheckVersion( $DBversion ) ) {
21695     my @warnings;
21696
21697     sanitize_zero_date('serial', 'planneddate');
21698     sanitize_zero_date('serial', 'publisheddate');
21699     sanitize_zero_date('serial', 'claimdate');
21700
21701     $dbh->do(q|
21702         ALTER TABLE serial
21703         MODIFY COLUMN biblionumber INT(11) NOT NULL
21704     |);
21705
21706     unless ( foreign_key_exists( 'serial', 'serial_ibfk_1' ) ) {
21707         my $serials = $dbh->selectall_arrayref(q|
21708             SELECT serialid FROM serial JOIN subscription USING (subscriptionid) WHERE serial.biblionumber != subscription.biblionumber
21709         |, { Slice => {} });
21710         if ( @$serials ) {
21711             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;
21712             $dbh->do(q|
21713                 UPDATE serial JOIN subscription USING (subscriptionid) SET serial.biblionumber = subscription.biblionumber WHERE serial.biblionumber != subscription.biblionumber
21714             |);
21715         }
21716         $serials = $dbh->selectall_arrayref(q|
21717             SELECT serialid FROM serial WHERE biblionumber NOT IN (SELECT biblionumber FROM biblio)
21718         |, { Slice => {} });
21719         if ( @$serials ) {
21720             push @warnings, q|WARNING - The following serials are deleted, they were not attached to an existing bibliographic record (serialid): | . join ", ", map { $_->{serialid} } @$serials;
21721             $dbh->do(q|
21722                 DELETE FROM serial WHERE biblionumber NOT IN (SELECT biblionumber FROM biblio)
21723             |);
21724         }
21725         $dbh->do(q|
21726             ALTER TABLE serial
21727             ADD CONSTRAINT serial_ibfk_1 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
21728         |);
21729     }
21730
21731     $dbh->do(q|
21732         ALTER TABLE serial
21733         MODIFY COLUMN subscriptionid INT(11) NOT NULL
21734     |);
21735
21736     unless ( foreign_key_exists( 'serial', 'serial_ibfk_2' ) ) {
21737         my $serials = $dbh->selectall_arrayref(q|
21738             SELECT serialid FROM serial WHERE subscriptionid NOT IN (SELECT subscriptionid FROM subscription)
21739         |, { Slice => {} });
21740         if ( @$serials ) {
21741             push @warnings, q|WARNING - The following serials are deleted, they were not attached to an existing subscription (serialid): | . join ", ", map { $_->{serialid} } @$serials;
21742             $dbh->do(q|
21743                 DELETE FROM serial WHERE subscriptionid NOT IN (SELECT subscriptionid FROM subscription)
21744             |);
21745         }
21746         $dbh->do(q|
21747             ALTER TABLE serial
21748             ADD CONSTRAINT serial_ibfk_2 FOREIGN KEY (subscriptionid) REFERENCES subscription (subscriptionid) ON DELETE CASCADE ON UPDATE CASCADE
21749         |);
21750     }
21751
21752     $dbh->do(q|
21753         ALTER TABLE subscriptionhistory
21754         MODIFY COLUMN biblionumber int(11) NOT NULL,
21755         MODIFY COLUMN subscriptionid int(11) NOT NULL
21756     |);
21757
21758     unless ( foreign_key_exists( 'subscriptionhistory', 'subscription_history_ibfk_1' ) ) {
21759         $dbh->do(q|
21760             UPDATE subscriptionhistory JOIN subscription USING (subscriptionid) SET subscriptionhistory.biblionumber = subscription.biblionumber WHERE subscriptionhistory.biblionumber != subscription.biblionumber
21761         |);
21762         $dbh->do(q|
21763             DELETE FROM subscriptionhistory WHERE biblionumber NOT IN (SELECT biblionumber FROM biblio)
21764         |);
21765         $dbh->do(q|
21766             ALTER TABLE subscriptionhistory
21767             ADD CONSTRAINT subscription_history_ibfk_1 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
21768         |);
21769     }
21770
21771     unless ( foreign_key_exists( 'subscriptionhistory', 'subscription_history_ibfk_2' ) ) {
21772         $dbh->do(q|
21773             DELETE FROM subscriptionhistory WHERE subscriptionid NOT IN (SELECT subscriptionid FROM subscription)
21774         |);
21775         $dbh->do(q|
21776             ALTER TABLE subscriptionhistory
21777             ADD CONSTRAINT subscription_history_ibfk_2 FOREIGN KEY (subscriptionid) REFERENCES subscription (subscriptionid) ON DELETE CASCADE ON UPDATE CASCADE
21778         |);
21779     }
21780
21781     $dbh->do(q|
21782         ALTER TABLE subscription
21783         MODIFY COLUMN biblionumber int(11) NOT NULL
21784     |);
21785
21786     unless ( foreign_key_exists( 'subscription', 'subscription_ibfk_3' ) ) {
21787         my $subscriptions = $dbh->selectall_arrayref(q|
21788             SELECT subscriptionid FROM subscription WHERE biblionumber NOT IN (SELECT biblionumber FROM biblio)
21789         |, { Slice => {} });
21790         if ( @$subscriptions ) {
21791             push @warnings, q|WARNING - The following subscriptions are deleted, they were not attached to an existing bibliographic record (subscriptionid): | . join ", ", map { $_->{subscriptionid} } @$subscriptions;
21792
21793             $dbh->do(q|
21794                 DELETE FROM subscription WHERE biblionumber NOT IN (SELECT biblionumber FROM biblio)
21795             |);
21796         }
21797         $dbh->do(q|
21798             ALTER TABLE subscription
21799             ADD CONSTRAINT subscription_ibfk_3 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
21800         |);
21801     }
21802
21803     for my $warning (@warnings) {
21804         warn $warning;
21805     }
21806
21807     my $description = [ "Add foreign key constraints on serial", @warnings ];
21808     NewVersion( $DBversion, 21901, $description);
21809 }
21810
21811 $DBversion = '19.12.00.077';
21812 if( CheckVersion( $DBversion ) ) {
21813     if ( !column_exists( 'course_items', 'itype_enabled' ) ) {
21814         $dbh->do(q{
21815             ALTER TABLE course_items
21816             ADD COLUMN itype_enabled tinyint(1) NOT NULL DEFAULT 0 AFTER itype,
21817             ADD COLUMN ccode_enabled tinyint(1) NOT NULL DEFAULT 0 AFTER ccode,
21818             ADD COLUMN holdingbranch_enabled tinyint(1) NOT NULL DEFAULT 0 AFTER holdingbranch,
21819             ADD COLUMN location_enabled tinyint(1) NOT NULL DEFAULT 0 AFTER location,
21820             ADD COLUMN itype_storage varchar(10) DEFAULT NULL AFTER itype_enabled,
21821             ADD COLUMN ccode_storage varchar(80) DEFAULT NULL AFTER ccode_enabled,
21822             ADD COLUMN holdingbranch_storage varchar(10) DEFAULT NULL AFTER ccode_enabled,
21823             ADD COLUMN location_storage varchar(80) DEFAULT NULL AFTER location_enabled
21824         });
21825
21826         my $item_level_items = C4::Context->preference('item-level_itypes');
21827         my $itype_field = $item_level_items ? 'i.itype' : 'bi.itemtype';
21828         $dbh->do(qq{
21829             UPDATE course_items ci
21830             LEFT JOIN items i USING ( itemnumber )
21831             LEFT JOIN biblioitems bi USING ( biblioitemnumber )
21832             SET
21833
21834             -- Assume the column is enabled if the course item is active and i.itype/bi.itemtype is set,
21835             -- or if the course item is not enabled and ci.itype is set
21836             ci.itype_enabled = IF( ci.enabled = 'yes', IF( $itype_field IS NULL, 0, 1 ), IF(  ci.itype IS NULL, 0, 1  ) ),
21837             ci.ccode_enabled = IF( ci.enabled = 'yes', IF( i.ccode IS NULL, 0, 1 ), IF(  ci.ccode IS NULL, 0, 1  ) ),
21838             ci.holdingbranch_enabled = IF( ci.enabled = 'yes', IF( i.holdingbranch IS NULL, 0, 1 ), IF(  ci.holdingbranch IS NULL, 0, 1  ) ),
21839             ci.location_enabled = IF( ci.enabled = 'yes', IF( i.location IS NULL, 0, 1 ), IF(  ci.location IS NULL, 0, 1  ) ),
21840
21841             -- If the course item is enabled, copy the value from the item.
21842             -- If the course item is not enabled, keep the existing value
21843             ci.itype = IF( ci.enabled = 'yes', $itype_field, ci.itype ),
21844             ci.ccode = IF( ci.enabled = 'yes', i.ccode, ci.ccode ),
21845             ci.holdingbranch = IF( ci.enabled = 'yes', i.holdingbranch, ci.holdingbranch ),
21846             ci.location = IF( ci.enabled = 'yes', i.location, ci.location ),
21847
21848             -- If the course is enabled, copy the value from the item to storage.
21849             -- If it is not enabled, copy the value from the course item to storage
21850             ci.itype_storage = IF( ci.enabled = 'no', $itype_field, ci.itype ),
21851             ci.ccode_storage = IF( ci.enabled = 'no', i.ccode, ci.ccode ),
21852             ci.holdingbranch_storage = IF( ci.enabled = 'no', i.holdingbranch, ci.holdingbranch ),
21853             ci.location_storage = IF( ci.enabled = 'no', i.location, ci.location );
21854         });
21855
21856         # Clean up the storage columns
21857         $dbh->do(q{
21858             UPDATE course_items SET
21859                 itype_storage = NULL,
21860                 ccode_storage = NULL,
21861                 holdingbranch_storage = NULL,
21862                 location_storage = NULL
21863             WHERE enabled = 'no';
21864         });
21865
21866         # Clean up the course enabled value columns
21867         $dbh->do(q{
21868             UPDATE course_items SET
21869                 itype = IF( itype_enabled = 'no', NULL, itype ),
21870                 ccode = IF( ccode_enabled = 'no', NULL, ccode ),
21871                 holdingbranch = IF( holdingbranch_enabled = 'no', NULL, holdingbranch ),
21872                 location = IF( location_enabled = 'no', NULL, location )
21873             WHERE enabled = 'no';
21874         });
21875     }
21876
21877     NewVersion( $DBversion, 23727, "Editing course reserve items is broken");
21878 }
21879
21880 $DBversion = '19.12.00.078';
21881 if( CheckVersion( $DBversion ) ) {
21882     $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') });
21883
21884     NewVersion( $DBversion, 24913, "Add PatronSelfRegistrationConfirmEmail syspref");
21885 }
21886
21887 $DBversion = '19.12.00.079';
21888 if( CheckVersion( $DBversion ) ) {
21889
21890     # Default to the homologous OpacPublic syspref
21891     my $opac_public = C4::Context->preference('OpacPublic') ? 1 : 0;
21892
21893     $dbh->do(qq{
21894         INSERT IGNORE INTO `systempreferences`
21895             (`variable`,`value`,`explanation`,`options`,`type`)
21896         VALUES
21897             ('RESTPublicAnonymousRequests', $opac_public, NULL,'If enabled, the API will allow anonymous access to public routes that do not require authenticated access.','YesNo');
21898     });
21899
21900     NewVersion( $DBversion, 25045, "Add a way to restrict anonymous access to public routes (OpacPublic behaviour)");
21901 }
21902
21903 $DBversion = '19.12.00.080';
21904 if( CheckVersion( $DBversion ) ) {
21905      $dbh->do( "UPDATE items set issues=0 where issues is null" );
21906      $dbh->do( "UPDATE deleteditems set issues=0 where issues is null" );
21907      $dbh->do( "ALTER TABLE items ALTER issues set default 0" );
21908      $dbh->do( "ALTER TABLE deleteditems ALTER issues set default 0" );
21909
21910     NewVersion( $DBversion, 23081, "Set default to 0 for items.issues");
21911 }
21912
21913 $DBversion = '19.12.00.081';
21914 if (CheckVersion($DBversion)) {
21915     if (!column_exists('course_items', 'homebranch')) {
21916         $dbh->do(q{
21917             ALTER TABLE course_items
21918             ADD COLUMN homebranch VARCHAR(10) NULL DEFAULT NULL AFTER ccode_storage
21919         });
21920     }
21921
21922     if (!foreign_key_exists('course_items', 'fk_course_items_homebranch')) {
21923         $dbh->do(q{
21924             ALTER TABLE course_items
21925             ADD CONSTRAINT fk_course_items_homebranch
21926               FOREIGN KEY (homebranch) REFERENCES branches (branchcode)
21927               ON DELETE CASCADE ON UPDATE CASCADE
21928         });
21929     }
21930
21931     if (!column_exists('course_items', 'homebranch_enabled')) {
21932         $dbh->do(q{
21933             ALTER TABLE course_items
21934             ADD COLUMN homebranch_enabled tinyint(1) NOT NULL DEFAULT 0 AFTER homebranch
21935         });
21936     }
21937
21938     if (!column_exists('course_items', 'homebranch_storage')) {
21939         $dbh->do(q{
21940             ALTER TABLE course_items
21941             ADD COLUMN homebranch_storage VARCHAR(10) NULL DEFAULT NULL AFTER homebranch_enabled
21942         });
21943     }
21944
21945     if (!foreign_key_exists('course_items', 'fk_course_items_homebranch_storage')) {
21946         $dbh->do(q{
21947             ALTER TABLE course_items
21948             ADD CONSTRAINT fk_course_items_homebranch_storage
21949               FOREIGN KEY (homebranch_storage) REFERENCES branches (branchcode)
21950               ON DELETE CASCADE ON UPDATE CASCADE
21951         });
21952     }
21953
21954     NewVersion( $DBversion, 22630, "Add course_items.homebranch");
21955 }
21956
21957 $DBversion = '19.12.00.082';
21958 if( CheckVersion( $DBversion ) ) {
21959
21960     # get list of installed translations
21961     require C4::Languages;
21962     my @langs;
21963     my $tlangs = C4::Languages::getTranslatedLanguages('opac','bootstrap');
21964
21965     foreach my $language ( @$tlangs ) {
21966         foreach my $sublanguage ( @{$language->{'sublanguages_loop'}} ) {
21967             push @langs, $sublanguage->{'rfc4646_subtag'};
21968         }
21969     }
21970
21971     # Get any existing value from the OpacMainUserBlock system preference
21972     my ($opacmainuserblock) = $dbh->selectrow_array( q|
21973         SELECT value FROM systempreferences WHERE variable='OpacMainUserBlock';
21974     |);
21975
21976     my @detail;
21977     if( $opacmainuserblock ){
21978         foreach my $lang ( @langs ) {
21979             # If there is a value in the OpacMainUserBlock preference, insert it into opac_news
21980             $dbh->do("INSERT INTO opac_news (branchcode, lang, title, content ) VALUES (NULL, ?, '', ?)", undef, "OpacMainUserBlock_$lang", $opacmainuserblock);
21981             push @detail, "Inserting OpacMainUserBlock contents into $lang news item...";
21982         }
21983     }
21984     # Remove the OpacMainUserBlock system preference
21985     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacMainUserBlock'");
21986
21987     unshift @detail, "Move contents of OpacMainUserBlock preference to Koha news system";
21988     NewVersion( $DBversion, 23794, \@detail);
21989 }
21990
21991 $DBversion = '19.12.00.083';
21992 if( CheckVersion( $DBversion ) ) {
21993
21994     unless ( column_exists( 'authorised_value_categories', 'is_system' ) ) {
21995         $dbh->do(q|
21996             ALTER TABLE authorised_value_categories
21997             ADD COLUMN is_system TINYINT(1) DEFAULT 0 AFTER category_name
21998         |);
21999     }
22000
22001     $dbh->do(q|
22002         UPDATE authorised_value_categories
22003         SET is_system = 1
22004         WHERE category_name IN ('LOC', 'LOST', 'WITHDRAWN', 'Bsort1', 'Bsort2', 'Asort1', 'Asort2', 'SUGGEST', 'DAMAGED', 'LOST', 'BOR_NOTES', 'CCODE', 'NOT_LOAN')
22005     |);
22006
22007     $dbh->do(q|
22008         UPDATE authorised_value_categories
22009         SET is_system = 1
22010         WHERE category_name IN ('branches', 'itemtypes', 'cn_source')
22011     |);
22012
22013     NewVersion( $DBversion, 17355, "Add is_system to authorised_value_categories table");
22014 }
22015
22016 $DBversion = '19.12.00.084';
22017 if( CheckVersion( $DBversion ) ) {
22018     unless ( TableExists('advanced_editor_macros') ) {
22019         $dbh->do(q|
22020             CREATE TABLE advanced_editor_macros (
22021             id INT(11) NOT NULL AUTO_INCREMENT,
22022             name varchar(80) NOT NULL,
22023             macro longtext NULL,
22024             borrowernumber INT(11) default NULL,
22025             shared TINYINT(1) default 0,
22026             PRIMARY KEY (id),
22027             CONSTRAINT borrower_macro_fk FOREIGN KEY ( borrowernumber ) REFERENCES borrowers ( borrowernumber ) ON UPDATE CASCADE ON DELETE CASCADE
22028             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;|
22029         );
22030     }
22031     $dbh->do(q|
22032         INSERT IGNORE INTO permissions (module_bit, code, description)
22033         VALUES (9, 'create_shared_macros', 'Create public macros')
22034     |);
22035     $dbh->do(q|
22036         INSERT IGNORE INTO permissions (module_bit, code, description)
22037         VALUES (9, 'delete_shared_macros', 'Delete public macros')
22038     |);
22039
22040     NewVersion( $DBversion, 17682, "Add macros db table and permissions");
22041 }
22042
22043 $DBversion = '19.12.00.085';
22044 if( CheckVersion( $DBversion ) ) {
22045     unless ( TableExists( 'aqorders_claims' ) ) {
22046         $dbh->do(q|
22047             CREATE TABLE aqorders_claims (
22048                 id int(11) AUTO_INCREMENT,
22049                 ordernumber INT(11) NOT NULL,
22050                 claimed_on TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
22051                 PRIMARY KEY (id),
22052                 CONSTRAINT aqorders_claims_ibfk_1 FOREIGN KEY (ordernumber) REFERENCES aqorders (ordernumber) ON DELETE CASCADE ON UPDATE CASCADE
22053             ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci
22054         |);
22055
22056         my $orders = $dbh->selectall_arrayref(q|
22057             SELECT ordernumber, claims_count, claimed_date
22058             FROM aqorders
22059             WHERE claims_count > 0
22060         |, { Slice => {} });
22061         my $insert_claim_sth = $dbh->prepare(q|
22062             INSERT INTO aqorders_claims (ordernumber, claimed_on)
22063             VALUES (?,?)
22064         |);
22065
22066         for my $order ( @$orders ) {
22067             for my $claim (1..$order->{claims_count}) {
22068                 $insert_claim_sth->execute($order->{ordernumber}, $order->{claimed_date});
22069             }
22070         }
22071
22072         $dbh->do(q|ALTER TABLE aqorders DROP COLUMN claims_count, DROP COLUMN claimed_date|);
22073     }
22074
22075     NewVersion( $DBversion, 24161, "Add new join table aqorders_claims to keep track of claims");
22076 }
22077
22078 $DBversion = '19.12.00.086';
22079 if( CheckVersion( $DBversion ) ) {
22080     $dbh->do(q{
22081         INSERT IGNORE INTO export_format( profile, description, content, csv_separator, type, used_for ) VALUES
22082         ("Late orders (CSV profile)", "Default CSV export for late orders", 'Title[% separator %]Author[% separator %]Publication year[% separator %]ISBN[% separator %]Quantity[% separator %]Number of claims
22083         [% FOR order IN orders ~%]
22084         [%~ SET biblio = order.biblio ~%]
22085         "[% biblio.title %]"[% separator ~%]
22086         "[% biblio.author %]"[% separator ~%]
22087         "[% bibio.biblioitem.publicationyear %]"[% separator ~%]
22088         "[% biblio.biblioitem.isbn %]"[% separator ~%]
22089         "[% order.quantity%]"[% separator ~%]
22090         "[% order.claims.count%][% IF order.claims.count %]([% FOR c IN order.claims %][% c.claimed_on | $KohaDates %][% UNLESS loop.last %], [% END %][% END %])[% END %]"
22091         [% END %]', ",", "sql", "late_orders")
22092     });
22093
22094     NewVersion( $DBversion, 24163, "Define a default CSV profile for late orders");
22095 }
22096
22097 $DBversion = '19.12.00.087';
22098 if( CheckVersion( $DBversion ) ) {
22099     $dbh->do(q{
22100         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
22101         ('TrapHoldsOnOrder','1',NULL,'If enabled, Koha will trap holds for on order items ( notforloan < 0 )','YesNo')
22102     });
22103
22104     NewVersion( $DBversion, 25184, "Items with a negative notforloan status should not be captured for holds");
22105 }
22106
22107 $DBversion = '19.12.00.088';
22108 if( CheckVersion( $DBversion ) ) {
22109
22110     $dbh->do(q{
22111         UPDATE letter SET
22112         name = REPLACE(name, "notification on auto renewing", "Notification of automatic renewal"),
22113         title = REPLACE(title, "Auto renewals", "Automatic renewal notice"),
22114         content = REPLACE(content, "You have reach the maximum of checkouts possible.", "You have reached the maximum number of renewals possible.")
22115         WHERE code = 'AUTO_RENEWALS';
22116     });
22117     $dbh->do(q{
22118         UPDATE letter SET
22119         content = REPLACE(content, "You have overdues.", "You have overdue items.")
22120         WHERE code = 'AUTO_RENEWALS';
22121     });
22122     $dbh->do(q{
22123         UPDATE letter SET
22124         content = REPLACE(content, "It's too late to renew this checkout.", "It's too late to renew this item.")
22125         WHERE code = 'AUTO_RENEWALS';
22126     });
22127     $dbh->do(q{
22128         UPDATE letter SET
22129         content = REPLACE(content, "You have too much unpaid fines.", "Your total unpaid fines are too high.")
22130         WHERE code = 'AUTO_RENEWALS';
22131     });
22132     $dbh->do(q{
22133         UPDATE letter SET
22134         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 %]
22135 ")
22136         WHERE code = 'AUTO_RENEWALS';
22137     });
22138
22139     NewVersion( $DBversion, 24378, "Fix some grammatical errors in default auto renewal notice");
22140 }
22141
22142 $DBversion = '19.12.00.089';
22143 if( CheckVersion( $DBversion ) ) {
22144
22145     # Migrate LOST_RETURNED to LOST_FOUND
22146     $dbh->do(qq{
22147         UPDATE
22148           accountlines
22149         SET
22150           credit_type_code = 'LOST_FOUND'
22151         WHERE
22152           credit_type_code = 'LOST_RETURNED'
22153     });
22154
22155     # Drop LOST_RETURNED credit type
22156     $dbh->do(qq{
22157         DELETE FROM account_credit_types WHERE code = 'LOST_RETURNED'
22158     });
22159
22160     NewVersion( $DBversion, 25389, "Catch errant cases of LOST_RETURNED");
22161 }
22162
22163 $DBversion = '19.12.00.090';
22164 if ( CheckVersion($DBversion) ) {
22165
22166     $dbh->do(
22167         qq{
22168           INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
22169           ('UseIssueDesks','0','','Use issue desks with circulation.','YesNo')
22170       }
22171     );
22172
22173     NewVersion( $DBversion, 13881, "Add issue desks system preference");
22174 }
22175
22176 $DBversion = '19.12.00.091';
22177 if ( CheckVersion($DBversion) ) {
22178
22179     $dbh->do(qq{
22180         UPDATE systempreferences SET variable = 'UseCirculationDesks' WHERE variable = 'UseIssueDesks'
22181     });
22182
22183     NewVersion( $DBversion, 13881, "Correction to preference terminology");
22184 }
22185
22186 $DBversion = '20.05.00.000';
22187 if( CheckVersion( $DBversion ) ) {
22188     NewVersion( $DBversion, undef, '20.05.00 alpha release' );
22189 }
22190
22191 $DBversion = '20.06.00.000';
22192 if( CheckVersion( $DBversion ) ) {
22193     NewVersion( $DBversion, undef, 'All our codebase are belong to everybody' );
22194 }
22195
22196 $DBversion = '20.06.00.001';
22197 if( CheckVersion( $DBversion ) ) {
22198     for my $f (qw( streetnumber streettype zipcode mobile B_streetnumber B_streettype B_zipcode ) ) {
22199         $dbh->do(qq|
22200             ALTER TABLE borrowers MODIFY $f TINYTEXT DEFAULT NULL
22201         |);
22202         $dbh->do(qq|
22203             ALTER TABLE deletedborrowers MODIFY $f TINYTEXT DEFAULT NULL
22204         |);
22205     }
22206     for my $f ( qw( B_address altcontactfirstname altcontactsurname altcontactaddress1 altcontactaddress2 altcontactaddress3 altcontactzipcode altcontactphone ) ) {
22207         $dbh->do(qq|
22208             ALTER TABLE borrowers MODIFY $f MEDIUMTEXT DEFAULT NULL
22209         |);
22210         $dbh->do(qq|
22211             ALTER TABLE deletedborrowers MODIFY $f MEDIUMTEXT DEFAULT NULL
22212         |);
22213     }
22214
22215     NewVersion( $DBversion, 24986, "Switch borrowers address related fields to TINYTEXT or MEDIUMTEXT");
22216 }
22217
22218 $DBversion = '20.06.00.002';
22219 if( CheckVersion( $DBversion ) ) {
22220     $dbh->do(q{
22221         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
22222         ('SkipHoldTrapOnNotForLoanValue','',NULL,'If set, Koha will never trap items for hold with this notforloan value','Integer')
22223     });
22224
22225     NewVersion( $DBversion, 25184, "Items with a negative notforloan status should not be captured for holds");
22226 }
22227
22228 $DBversion = '20.06.00.003';
22229 if( CheckVersion( $DBversion ) ) {
22230     unless ( TableExists( 'tables_settings' ) ) {
22231         $dbh->do(q|
22232             CREATE TABLE tables_settings (
22233                 module varchar(255) NOT NULL,
22234                 page varchar(255) NOT NULL,
22235                 tablename varchar(255) NOT NULL,
22236                 default_display_length smallint(6) NOT NULL DEFAULT 20,
22237                 default_sort_order varchar(255),
22238                 PRIMARY KEY(module (191), page (191), tablename (191) )
22239             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
22240         |);
22241     }
22242
22243     NewVersion( $DBversion, 24156, "Add new table tables_settings" );
22244 }
22245
22246 $DBversion = '20.06.00.004';
22247 if( CheckVersion( $DBversion ) ) {
22248     $dbh->do("
22249         DELETE FROM circulation_rules WHERE rule_name='holdallowed' AND rule_value='';
22250     ");
22251     NewVersion( $DBversion, 25851, "Remove holdallowed rule if value is an empty string");
22252 }
22253
22254 $DBversion = '20.06.00.005';
22255 if( CheckVersion( $DBversion ) ) {
22256     $dbh->do( "UPDATE borrowers SET login_attempts=0 WHERE login_attempts IS NULL" );
22257     $dbh->do( "ALTER TABLE borrowers MODIFY COLUMN login_attempts int(4) NOT NULL DEFAULT 0" );
22258     $dbh->do( "UPDATE deletedborrowers SET login_attempts=0 WHERE login_attempts IS NULL" );
22259     $dbh->do( "ALTER TABLE deletedborrowers MODIFY COLUMN login_attempts int(4) NOT NULL DEFAULT 0" );
22260     NewVersion( $DBversion, 24379, "Set login_attempts NOT NULL" );
22261 }
22262
22263 $DBversion = '20.06.00.006';
22264 if( CheckVersion( $DBversion ) ) {
22265     unless( TableExists( 'pseudonymized_transactions' ) ) {
22266         $dbh->do(q|
22267             CREATE TABLE `pseudonymized_transactions` (
22268               `id` INT(11) NOT NULL AUTO_INCREMENT,
22269               `hashed_borrowernumber` VARCHAR(60) NOT NULL,
22270               `has_cardnumber` TINYINT(1) NOT NULL DEFAULT 0,
22271               `title` LONGTEXT,
22272               `city` LONGTEXT,
22273               `state` MEDIUMTEXT default NULL,
22274               `zipcode` varchar(25) default NULL,
22275               `country` MEDIUMTEXT,
22276               `branchcode` varchar(10) NOT NULL default '',
22277               `categorycode` varchar(10) NOT NULL default '',
22278               `dateenrolled` date default NULL,
22279               `sex` varchar(1) default NULL,
22280               `sort1` varchar(80) default NULL,
22281               `sort2` varchar(80) default NULL,
22282               `datetime` datetime default NULL,
22283               `transaction_branchcode` varchar(10) default NULL,
22284               `transaction_type` varchar(16) default NULL,
22285               `itemnumber` int(11) default NULL,
22286               `itemtype` varchar(10) default NULL,
22287               `holdingbranch` varchar(10) default null,
22288               `homebranch` varchar(10) default null,
22289               `location` varchar(80) default NULL,
22290               `itemcallnumber` varchar(255) default NULL,
22291               `ccode` varchar(80) default NULL,
22292               PRIMARY KEY (`id`),
22293               CONSTRAINT `pseudonymized_transactions_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`),
22294               CONSTRAINT `pseudonymized_transactions_borrowers_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`),
22295               CONSTRAINT `pseudonymized_transactions_borrowers_ibfk_3` FOREIGN KEY (`transaction_branchcode`) REFERENCES `branches` (`branchcode`)
22296             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
22297         |);
22298     }
22299
22300     $dbh->do(q|
22301         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
22302         VALUES ('Pseudonymization','0',NULL,'If enabled patrons and transactions will be copied in a separate table for statistics purpose','YesNo')
22303     |);
22304     $dbh->do(q|
22305         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
22306         VALUES ('PseudonymizationPatronFields','','title,city,state,zipcode,country,branchcode,categorycode,dateenrolled,sex,sort1,sort2','Patron fields to copy to the pseudonymized_transactions table','multiple')
22307     |);
22308     $dbh->do(q|
22309         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
22310         VALUES ('PseudonymizationTransactionFields','','datetime,transaction_branchcode,transaction_type,itemnumber,itemtype,holdingbranch,homebranch,location,itemcallnumber,ccode','Transaction fields to copy to the pseudonymized_transactions table','multiple')
22311     |);
22312
22313     unless( TableExists( 'pseudonymized_borrower_attributes' ) ) {
22314         $dbh->do(q|
22315             CREATE TABLE pseudonymized_borrower_attributes (
22316               `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, -- Row id field
22317               `transaction_id` int(11) NOT NULL,
22318               `code` varchar(10) NOT NULL,
22319               `attribute` varchar(255) default NULL,
22320               CONSTRAINT `pseudonymized_borrower_attributes_ibfk_1` FOREIGN KEY (`transaction_id`) REFERENCES `pseudonymized_transactions` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
22321               CONSTRAINT `anonymized_borrower_attributes_ibfk_2` FOREIGN KEY (`code`) REFERENCES `borrower_attribute_types` (`code`) ON DELETE CASCADE ON UPDATE CASCADE
22322             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
22323         |);
22324     }
22325
22326     unless( column_exists('borrower_attribute_types', 'keep_for_pseudonymization') ) {
22327         $dbh->do(q|
22328             ALTER TABLE borrower_attribute_types ADD COLUMN `keep_for_pseudonymization` TINYINT(1) NOT NULL DEFAULT 0 AFTER `class`
22329         |);
22330     }
22331
22332     NewVersion( $DBversion, 24151, "Add pseudonymized_transactions tables and sysprefs for Pseudonymization" );
22333 }
22334
22335 $DBversion = '20.06.00.007';
22336 if( CheckVersion( $DBversion ) ) {
22337     if( !column_exists( 'borrower_attribute_types', 'mandatory' ) ) {
22338         $dbh->do(q|
22339             ALTER TABLE borrower_attribute_types
22340             ADD COLUMN mandatory TINYINT(1) NOT NULL DEFAULT 0
22341             AFTER keep_for_pseudonymization
22342         |);
22343     }
22344
22345     NewVersion( $DBversion, 22844, "Add borrower_attribute_types.mandatory" );
22346 }
22347
22348 $DBversion = '20.06.00.008';
22349 if( CheckVersion( $DBversion ) ) {
22350     $dbh->do( "UPDATE itemtypes SET imageurl = REPLACE (imageurl, '.gif', '.png') WHERE imageurl LIKE 'bridge/%'" );
22351
22352     NewVersion( $DBversion, 23148, "Replace Bridge icons with transparent PNG files" );
22353 }
22354
22355 $DBversion = '20.06.00.009';
22356 if( CheckVersion( $DBversion ) ) {
22357     $dbh->do( q{
22358             INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
22359             VALUES ('ILLHiddenRequestStatuses',NULL,NULL,'ILL statuses that are considered finished and should not be displayed in the ILL module','multiple')
22360     });
22361
22362     NewVersion( $DBversion, 23391, "Hide finished ILL requests" );
22363 }
22364
22365 $DBversion = '20.06.00.010';
22366 if( CheckVersion( $DBversion ) ) {
22367     $dbh->do(q{
22368         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
22369         ('NoRefundOnLostReturnedItemsAge','','','Do not refund lost item fees if item is lost for more than this number of days','Integer')
22370     });
22371
22372     NewVersion( $DBversion, 20815, "Add NoRefundOnLostReturnedItemsAge system preference" );
22373 }
22374
22375 $DBversion = '20.06.00.011';
22376 if( CheckVersion( $DBversion ) ) {
22377     unless( column_exists( 'export_format', 'staff_only' ) ) {
22378         $dbh->do(q|
22379             ALTER TABLE export_format
22380                 ADD staff_only TINYINT(1) NOT NULL DEFAULT 0 AFTER used_for,
22381                 ADD KEY `staff_only_idx` (`staff_only`);
22382         |);
22383     }
22384
22385     unless ( index_exists( 'export_format', 'used_for_idx' ) ) {
22386         $dbh->do(q|
22387             ALTER TABLE export_format
22388                 ADD KEY `used_for_idx` (`used_for` (191));
22389         |);
22390     }
22391
22392     NewVersion( $DBversion, 5087, "Add export_format.staff_only" );
22393 }
22394
22395 $DBversion = '20.06.00.012';
22396 if( CheckVersion( $DBversion ) ) {
22397
22398     # get list of installed translations
22399     require C4::Languages;
22400     my @langs;
22401     my $tlangs = C4::Languages::getTranslatedLanguages('opac','bootstrap');
22402
22403     foreach my $language ( @$tlangs ) {
22404         foreach my $sublanguage ( @{$language->{'sublanguages_loop'}} ) {
22405             push @langs, $sublanguage->{'rfc4646_subtag'};
22406         }
22407     }
22408
22409     # Get any existing value from the opaccredits system preference
22410     my ($opaccredits) = $dbh->selectrow_array( q|
22411         SELECT value FROM systempreferences WHERE variable='opaccredits';
22412     |);
22413     if( $opaccredits ){
22414         foreach my $lang ( @langs ) {
22415             # If there is a value in the opaccredits preference, insert it into opac_news
22416             $dbh->do("INSERT IGNORE INTO opac_news (branchcode, lang, title, content ) VALUES (NULL, ?, '', ?)", undef, "opaccredits_$lang", $opaccredits);
22417         }
22418     }
22419     # Remove the opaccredits system preference
22420     $dbh->do("DELETE FROM systempreferences WHERE variable='opaccredits'");
22421
22422     NewVersion( $DBversion, 23795, "Convert OpacCredits system preference to news block" );
22423 }
22424
22425 $DBversion = '20.06.00.013';
22426 if( CheckVersion( $DBversion ) ) {
22427
22428     # get list of installed translations
22429     require C4::Languages;
22430     my @langs;
22431     my $tlangs = C4::Languages::getTranslatedLanguages('opac','bootstrap');
22432
22433     foreach my $language ( @$tlangs ) {
22434         foreach my $sublanguage ( @{$language->{'sublanguages_loop'}} ) {
22435             push @langs, $sublanguage->{'rfc4646_subtag'};
22436         }
22437     }
22438
22439     # Get any existing value from the OpacCustomSearch system preference
22440     my ($OpacCustomSearch) = $dbh->selectrow_array( q|
22441         SELECT value FROM systempreferences WHERE variable='OpacCustomSearch';
22442     |);
22443     if( $OpacCustomSearch ){
22444         foreach my $lang ( @langs ) {
22445             # If there is a value in the OpacCustomSearch preference, insert it into opac_news
22446             $dbh->do("INSERT INTO opac_news (branchcode, lang, title, content ) VALUES (NULL, ?, '', ?)", undef, "OpacCustomSearch_$lang", $OpacCustomSearch);
22447         }
22448     }
22449     # Remove the OpacCustomSearch system preference
22450     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacCustomSearch'");
22451
22452     NewVersion( $DBversion, 23795, "Convert OpacCustomSearch system preference to news block" );
22453 }
22454
22455 $DBversion = '20.06.00.014';
22456 if( CheckVersion( $DBversion ) ) {
22457
22458     $dbh->do( "ALTER TABLE opac_news CHANGE lang lang VARCHAR(50) NOT NULL DEFAULT ''" );
22459
22460     NewVersion( $DBversion, 23797, "Extend the opac_news lang column to accommodate longer values" );
22461 }
22462
22463 $DBversion = '20.06.00.015';
22464 if( CheckVersion( $DBversion ) ) {
22465
22466     # get list of installed translations
22467     require C4::Languages;
22468     my @langs;
22469     my $tlangs = C4::Languages::getTranslatedLanguages('opac','bootstrap');
22470
22471     foreach my $language ( @$tlangs ) {
22472         foreach my $sublanguage ( @{$language->{'sublanguages_loop'}} ) {
22473             push @langs, $sublanguage->{'rfc4646_subtag'};
22474         }
22475     }
22476
22477     # Get any existing value from the OpacLoginInstructions system preference
22478     my ($opaclogininstructions) = $dbh->selectrow_array( q|
22479         SELECT value FROM systempreferences WHERE variable='OpacLoginInstructions';
22480     |);
22481     if( $opaclogininstructions ){
22482         foreach my $lang ( @langs ) {
22483             # If there is a value in the OpacLoginInstructions preference, insert it into opac_news
22484             $dbh->do("INSERT INTO opac_news (branchcode, lang, title, content ) VALUES (NULL, ?, '', ?)", undef, "OpacLoginInstructions_$lang", $opaclogininstructions);
22485         }
22486     }
22487     # Remove the OpacLoginInstructions system preference
22488     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacLoginInstructions'");
22489
22490     NewVersion( $DBversion, 23797, "Convert OpacLoginInstructions system preference to news block" );
22491 }
22492
22493 $DBversion = '20.06.00.016';
22494 if( CheckVersion( $DBversion ) ) {
22495
22496     unless ( column_exists('branchtransfers', 'daterequested') ) {
22497         $dbh->do(
22498             qq{
22499                 ALTER TABLE branchtransfers
22500                 ADD
22501                   `daterequested` timestamp NOT NULL default CURRENT_TIMESTAMP
22502                 AFTER
22503                   `itemnumber`
22504               }
22505         );
22506     }
22507
22508     NewVersion( $DBversion, 23092, "Add 'daterequested' field to transfers table" );
22509 }
22510
22511 $DBversion = '20.06.00.017';
22512 if( CheckVersion( $DBversion ) ) {
22513     $dbh->do( "UPDATE systempreferences SET variable='NotesToHide' WHERE variable = 'NotesBlacklist'" );
22514     NewVersion( $DBversion, 25709, "Rename systempreference to NotesToHide");
22515 }
22516
22517 $DBversion = '20.06.00.018';
22518 if( CheckVersion( $DBversion ) ) {
22519     $dbh->do(q|
22520         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
22521         (11, 'reopen_closed_invoices', 'Reopen closed invoices')
22522     |);
22523
22524     $dbh->do(q|
22525         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
22526         (11, 'edit_invoices', 'Edit invoices')
22527     |);
22528
22529     $dbh->do(q|
22530         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
22531         (11, 'delete_baskets', 'Delete baskets')
22532     |);
22533
22534     $dbh->do(q|
22535         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
22536         (11, 'delete_invoices', 'Delete invoices')
22537     |);
22538
22539     $dbh->do(q|
22540         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
22541         (11, 'merge_invoices', 'Merge invoices')
22542     |);
22543
22544     NewVersion( $DBversion, 24157, "Add new permissions reopen_closed_invoices, edit_invoices, delete_invoices, merge_invoices, delete_basket");
22545 }
22546
22547 $DBversion = '20.06.00.019';
22548 if( CheckVersion( $DBversion ) ) {
22549     $dbh->do( "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('NewsToolEditor','tinymce', 'Choose tool for editing News','tinymce|codemirror','Choice')" );
22550
22551     NewVersion( $DBversion, 22660, "Adds NewsToolEditor system preference");
22552 }
22553
22554 $DBversion = '20.06.00.020';
22555 if( CheckVersion( $DBversion ) ) {
22556     # Remove from the systempreferences table
22557     $dbh->do("DELETE FROM systempreferences WHERE variable = 'GoogleIndicTransliteration'");
22558
22559     NewVersion( $DBversion, 26070, "Remove references to deprecated Google Transliterate API");
22560 }
22561
22562 $DBversion = '20.06.00.021';
22563 if( CheckVersion( $DBversion ) ) {
22564     $dbh->do(q{
22565         UPDATE systempreferences SET options = "callnum|ccode|location|library"
22566         WHERE variable = "OpacItemLocation"
22567     });
22568     NewVersion( $DBversion, 25871, "Add library option to OpacItemLocation");
22569 }
22570
22571 $DBversion = '20.06.00.022';
22572 if( CheckVersion( $DBversion ) ) {
22573     unless ( column_exists('itemtypes', 'parent_type') ) {
22574         $dbh->do(q{
22575             ALTER TABLE itemtypes
22576                 ADD COLUMN parent_type VARCHAR(10) NULL DEFAULT NULL
22577                 AFTER itemtype;
22578
22579         });
22580     }
22581     unless ( foreign_key_exists( 'itemtypes', 'itemtypes_ibfk_1') ){
22582         $dbh->do(q{
22583             ALTER TABLE itemtypes
22584             ADD CONSTRAINT itemtypes_ibfk_1
22585             FOREIGN KEY (parent_type) REFERENCES itemtypes (itemtype)
22586         });
22587     }
22588
22589     NewVersion( $DBversion, 21946, "Add parent type to itemtypes" );
22590 }
22591
22592 $DBversion = '20.06.00.023';
22593 if( CheckVersion( $DBversion ) ) {
22594
22595     my ( $QuoteOfTheDay ) = $dbh->selectrow_array(q|
22596         SELECT value FROM systempreferences WHERE variable='QuoteOfTheDay'
22597     |);
22598     my $options = $QuoteOfTheDay ? 'opac' : '';
22599     $dbh->do( q|
22600         UPDATE systempreferences
22601         SET value = ?,
22602             options = 'intranet,opac',
22603             explanation = 'Enable or disable display of Quote of the Day on the OPAC and staff interface home page',
22604             type = 'multiple'
22605         WHERE variable = 'QuoteOfTheDay'
22606     |, undef, $options );
22607
22608     NewVersion( $DBversion, 16371, "Quote of the Day (QOTD) for the staff interface " );
22609 }
22610
22611 $DBversion = '20.06.00.024';
22612 if( CheckVersion( $DBversion ) ) {
22613
22614     $dbh->do( "UPDATE marc_subfield_structure SET liblibrarian = 'Home library' WHERE liblibrarian = 'Permanent location'
22615         AND tagfield = 952 and tagsubfield = 'a'" );
22616     $dbh->do( "UPDATE marc_subfield_structure SET libopac = 'Home library' WHERE libopac = 'Permanent location'
22617         AND tagfield = 952 and tagsubfield = 'a'" );
22618     $dbh->do( "UPDATE marc_subfield_structure SET liblibrarian = 'Current library' WHERE liblibrarian = 'Current location'
22619         AND tagfield = 952 and tagsubfield = 'b'" );
22620     $dbh->do( "UPDATE marc_subfield_structure SET libopac = 'Current library' WHERE libopac = 'Current location'
22621         AND tagfield = 952 and tagsubfield = 'b'" );
22622
22623     NewVersion( $DBversion, 25867, "Update subfield descriptions for 952\$a and 952\$b");
22624 }
22625
22626 $DBversion = '20.06.00.025';
22627 if( CheckVersion( $DBversion ) ) {
22628
22629     $dbh->do( q{
22630         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
22631         ('PatronDuplicateMatchingAddFields','surname|firstname|dateofbirth', NULL,'A list of fields separated by "|" to deduplicate patrons when created','Free')
22632     });
22633
22634     NewVersion( $DBversion, 6725, "Adds PatronDuplicateMatchingAddFields system preference");
22635 }
22636
22637 $DBversion = '20.06.00.026';
22638 if (CheckVersion($DBversion)) {
22639     unless (column_exists('accountlines', 'credit_number')) {
22640         $dbh->do('ALTER TABLE accountlines ADD COLUMN credit_number VARCHAR(20) NULL DEFAULT NULL COMMENT "autogenerated number for credits" AFTER debit_type_code');
22641     }
22642
22643     unless (column_exists('account_credit_types', 'credit_number_enabled')) {
22644         $dbh->do(q{
22645             ALTER TABLE account_credit_types
22646             ADD COLUMN credit_number_enabled TINYINT(1) NOT NULL DEFAULT 0
22647                 COMMENT "Is autogeneration of credit number enabled for this credit type"
22648                 AFTER can_be_added_manually
22649         });
22650     }
22651
22652     $dbh->do('INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES(?, ?, ?, ?, ?)', undef, 'AutoCreditNumber', '', '', 'Automatically generate a number for account credits', 'Choice');
22653
22654     NewVersion( $DBversion, 19036, "Add accountlines.credit_number, account_credit_types.credit_number_enabled and syspref AutoCreditNumber" );
22655 }
22656
22657 $DBversion = '20.06.00.027';
22658 if( CheckVersion( $DBversion ) ) {
22659     $dbh->do( "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('BiblioItemtypeInfo', '0','Control whether biblio level itemtype image displays','0','YesNo')" );
22660
22661     NewVersion( $DBversion, 8732, 'Add new BiblioItemtypeInfo to system preferences' );
22662 }
22663
22664 $DBversion = '20.06.00.028';
22665 if( CheckVersion( $DBversion ) ) {
22666     $dbh->do(q{
22667         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
22668         ('DefaultLongOverdueSkipLostStatuses', '', NULL, 'Skip these lost statuses by default in longoverdue.pl', 'Free')
22669     });
22670
22671     NewVersion( $DBversion, 25958, "Allow LongOverdue cron to exclude specified lost values");
22672 }
22673
22674 $DBversion = '20.06.00.029';
22675 if ( CheckVersion( $DBversion ) ) {
22676     $dbh->do(q{
22677         INSERT IGNORE INTO authorised_value_categories( category_name, is_system ) VALUES ('HOLD_CANCELLATION', 0);
22678     });
22679
22680     if ( !column_exists( 'reserves', 'cancellation_reason' ) ) {
22681         $dbh->do(q{
22682             ALTER TABLE reserves ADD COLUMN `cancellation_reason` varchar(80) default NULL AFTER cancellationdate;
22683         });
22684     }
22685
22686     if ( !column_exists( 'old_reserves', 'cancellation_reason' ) ) {
22687         $dbh->do(q{
22688             ALTER TABLE old_reserves ADD COLUMN `cancellation_reason` varchar(80) default NULL AFTER cancellationdate;
22689         });
22690     }
22691
22692     NewVersion( $DBversion, 25534, "Add ability to send an email specifying a reason when canceling a hold");
22693 }
22694
22695 $DBversion = '20.06.00.030';
22696 if ( CheckVersion( $DBversion ) ) {
22697
22698     $dbh->do(q{
22699         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type`) VALUES
22700         ('AutoApprovePatronProfileSettings', '0', '', 'Automatically approve patron profile changes from the OPAC.', 'YesNo');
22701     });
22702
22703     NewVersion( $DBversion, 20057, "Add new system preference 'AutoApprovePatronProfileSettings'");
22704 }
22705
22706 $DBversion = '20.06.00.031';
22707 if( CheckVersion( $DBversion ) ) {
22708
22709     if( !column_exists( 'reserves', 'non_priority' ) ) {
22710         $dbh->do("ALTER TABLE reserves ADD COLUMN `non_priority` tinyint(1) NOT NULL DEFAULT 0 AFTER `item_level_hold`");
22711     }
22712
22713     if( !column_exists( 'old_reserves', 'non_priority' ) ) {
22714         $dbh->do("ALTER TABLE old_reserves ADD COLUMN `non_priority` tinyint(1) NOT NULL DEFAULT 0 AFTER `item_level_hold`");
22715     }
22716
22717     NewVersion( $DBversion, 22789, "Add non_priority column on reserves and old_reserves tables");
22718 }
22719
22720 $DBversion = '20.06.00.032';
22721 if( CheckVersion( $DBversion ) ) {
22722     if( !column_exists( 'items', 'exclude_from_local_holds_priority' ) ) {
22723         $dbh->do(q{
22724             ALTER TABLE `items` ADD COLUMN `exclude_from_local_holds_priority` tinyint(1) default NULL AFTER `new_status`
22725         });
22726     }
22727
22728     if( !column_exists( 'deleteditems', 'exclude_from_local_holds_priority' ) ) {
22729         $dbh->do(q{
22730             ALTER TABLE `deleteditems` ADD COLUMN `exclude_from_local_holds_priority` tinyint(1) default NULL AFTER `new_status`
22731         });
22732     }
22733
22734     if( !column_exists( 'categories', 'exclude_from_local_holds_priority' ) ) {
22735         $dbh->do(q{
22736             ALTER TABLE `categories` ADD COLUMN `exclude_from_local_holds_priority` tinyint(1) default NULL AFTER `change_password`
22737         });
22738     }
22739     NewVersion( $DBversion, 19889, "Add exclude_from_local_holds_priority column to items, deleteditems and categories tables");
22740 }
22741
22742 $DBversion = '20.06.00.033';
22743 if( CheckVersion( $DBversion ) ) {
22744     if( column_exists( 'opac_news', 'timestamp' ) ) {
22745         $dbh->do(q|
22746             ALTER TABLE opac_news
22747             CHANGE COLUMN timestamp published_on date DEFAULT NULL
22748         |);
22749     }
22750     if( !column_exists( 'opac_news', 'updated_on' ) ) {
22751         $dbh->do(q|
22752             ALTER TABLE opac_news
22753             ADD COLUMN updated_on timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER published_on
22754         |);
22755     }
22756
22757     $dbh->do(q|
22758         UPDATE letter
22759         SET content = REPLACE(content,?,?)
22760         WHERE content LIKE ?
22761     |, undef, 'opac_news.timestamp', 'opac_news.published_on', '%opac_news.timestamp%' );
22762
22763     NewVersion( $DBversion, 21066, ["Rename column opac_news.timestamp with published_on", "Add new column opac_news.updated_on", "Replace timestamp references in letters table"] );
22764 }
22765
22766 $DBversion = '20.06.00.034';
22767 if( CheckVersion( $DBversion ) ) {
22768     $dbh->do(q|
22769         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type)
22770         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')
22771     |);
22772
22773     NewVersion( $DBversion, 24197, "Add new system preference 'AddressForFailedOverdueNotices'" );
22774 }
22775
22776 $DBversion = '20.06.00.035';
22777 if ( CheckVersion( $DBversion ) ) {
22778     $dbh->do(q{
22779         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
22780         ('EdifactInvoiceImport', 'automatic', 'automatic|manual', "If on, don't auto-import EDI invoices, just keep them in the database with the status 'new'", 'Choice')
22781     });
22782
22783     NewVersion( $DBversion, 23682, "Add new system preference 'EdifactInvoiceImport'" );
22784 }
22785
22786 $DBversion = '20.06.00.036';
22787 if( CheckVersion( $DBversion ) ) {
22788     # Fix the markup in the OPACSearchForTitleIn system preference
22789     $dbh->do("UPDATE systempreferences SET VALUE = replace( value, '</li>', ''), value = REPLACE( value, '<li>', '') WHERE VARIABLE = 'OPACSearchForTitleIn';");
22790
22791     NewVersion( $DBversion, 20168, "Update OPACSearchForTitleIn to work with Bootstrap 4");
22792 }
22793
22794 $DBversion = '20.06.00.037';
22795 if( CheckVersion( $DBversion ) ) {
22796     if( !column_exists( 'categories', 'min_password_length' ) ) {
22797         $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");
22798     }
22799     if( !column_exists( 'categories', 'require_strong_password' ) ) {
22800         $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");
22801     }
22802
22803     NewVersion( $DBversion, 23816, "Add min_password_length and require_strong_password columns in categories table");
22804 }
22805
22806 $DBversion = '20.06.00.038';
22807 if( CheckVersion( $DBversion ) ) {
22808     $dbh->do( "ALTER TABLE `search_field` MODIFY COLUMN `type` enum('','string','date','number','boolean','sum','isbn','stdno','year') NOT NULL" );
22809     $dbh->do( "UPDATE `search_field` SET type = 'year' WHERE name = 'date-of-publication'" );
22810
22811     NewVersion( $DBversion, 24807, "Add 'year' type to improve sorting behaviour" );
22812 }
22813
22814 $DBversion = '20.06.00.039';
22815 if( CheckVersion( $DBversion ) ) {
22816
22817     if( !column_exists( 'hold_fill_targets', 'reserve_id' ) ) {
22818         $dbh->do( "ALTER TABLE hold_fill_targets ADD COLUMN reserve_id int(11) DEFAULT NULL AFTER item_level_request" );
22819     }
22820
22821     NewVersion( $DBversion, 18958, "Add reserve_id to hold_fill_targets");
22822 }
22823
22824 $DBversion = '20.06.00.040';
22825 if( CheckVersion( $DBversion ) ) {
22826     $dbh->do( "INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES ('OpacMetaDescription','','','This description will show in search engine results (160 characters).','Textarea');" );
22827
22828     NewVersion( $DBversion, 26454, "Add system preference to set meta description for the OPAC");
22829 }
22830
22831 $DBversion = '20.06.00.041';
22832 if ( CheckVersion($DBversion) ) {
22833
22834     if ( column_exists( 'items', 'paidfor' ) ) {
22835         my ($count) = $dbh->selectrow_array(
22836             q|
22837                 SELECT COUNT(*)
22838                 FROM items
22839                 WHERE paidfor IS NOT NULL AND paidfor <> ""
22840             |
22841         );
22842         if ($count) {
22843             warn "Warning - Cannot remove column items.paidfor. At least one value exists";
22844         }
22845         else {
22846             $dbh->do(q|ALTER TABLE items DROP COLUMN paidfor|);
22847             $dbh->do(q|UPDATE marc_subfield_structure SET kohafield = '' WHERE kohafield = 'items.paidfor'|);
22848         }
22849     }
22850
22851     if ( column_exists( 'deleteditems', 'paidfor' ) ) {
22852         my ($count) = $dbh->selectrow_array(
22853             q|
22854                 SELECT COUNT(*)
22855                 FROM deleteditems
22856                 WHERE paidfor IS NOT NULL AND paidfor <> ""
22857             |
22858         );
22859         if ($count) {
22860             warn "Warning - Cannot remove column deleteditems.paidfor. At least one value exists";
22861         }
22862         else {
22863             $dbh->do(q|ALTER TABLE deleteditems DROP COLUMN paidfor|);
22864         }
22865     }
22866
22867     NewVersion( $DBversion, 26268, "Remove items.paidfor field" );
22868 }
22869
22870 $DBversion = '20.06.00.042';
22871 if( CheckVersion( $DBversion ) ) {
22872     unless ( column_exists('letter', 'updated_on') ) {
22873         $dbh->do(q|
22874             ALTER TABLE letter ADD COLUMN updated_on timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER lang
22875         |);
22876     }
22877
22878     NewVersion( $DBversion, 25776, "Add letter.updated_on");
22879 }
22880
22881 $DBversion = '20.06.00.043';
22882 if( CheckVersion( $DBversion ) ) {
22883     $dbh->do(q{
22884         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')
22885     });
22886
22887     NewVersion( $DBversion, 25261, "Add CircConfirmItemParts syspref");
22888 }
22889
22890 $DBversion = '20.06.00.044';
22891 if( CheckVersion( $DBversion ) ) {
22892
22893     unless (TableExists('smtp_servers')) {
22894
22895         # Create the table
22896         $dbh->do(q{
22897             CREATE TABLE `smtp_servers` (
22898                 `id` INT(11) NOT NULL AUTO_INCREMENT,
22899                 `name` VARCHAR(80) NOT NULL,
22900                 `host` VARCHAR(80) NOT NULL DEFAULT 'localhost',
22901                 `port` INT(11) NOT NULL DEFAULT 25,
22902                 `timeout` INT(11) NOT NULL DEFAULT 120,
22903                 `ssl_mode` ENUM('disabled', 'ssl', 'starttls') NOT NULL,
22904                 `user_name` VARCHAR(80) NULL DEFAULT NULL,
22905                 `password` VARCHAR(80) NULL DEFAULT NULL,
22906                 `debug` TINYINT(1) NOT NULL DEFAULT 0,
22907                 PRIMARY KEY (`id`),
22908                 KEY `host_idx` (`host`)
22909             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
22910         });
22911     }
22912
22913     unless (TableExists('library_smtp_servers')) {
22914         $dbh->do(q{
22915             CREATE TABLE `library_smtp_servers` (
22916                 `id` INT(11) NOT NULL AUTO_INCREMENT,
22917                 `library_id` VARCHAR(10) NOT NULL,
22918                 `smtp_server_id` INT(11) NOT NULL,
22919                 PRIMARY KEY (`id`),
22920                 UNIQUE KEY `library_id_idx` (`library_id`),
22921                 KEY `smtp_server_id_idx` (`smtp_server_id`),
22922                 CONSTRAINT `library_smtp_servers_library_fk` FOREIGN KEY (`library_id`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
22923                 CONSTRAINT `library_smtp_servers_smtp_servers_fk` FOREIGN KEY (`smtp_server_id`) REFERENCES `smtp_servers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
22924             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
22925         });
22926     }
22927
22928     $dbh->do(q{
22929         INSERT IGNORE INTO permissions
22930             (module_bit, code, description)
22931         VALUES ( 3, 'manage_smtp_servers', 'Manage SMTP servers configuration');
22932     });
22933
22934     NewVersion( $DBversion, 22343, "Add SMTP configuration options");
22935 }
22936
22937 $DBversion = '20.06.00.045';
22938 if( CheckVersion( $DBversion ) ) {
22939
22940     unless ( TableExists('background_jobs') ) {
22941         $dbh->do(q|
22942             CREATE TABLE background_jobs (
22943                 id INT(11) NOT NULL AUTO_INCREMENT,
22944                 status VARCHAR(32),
22945                 progress INT(11),
22946                 size INT(11),
22947                 borrowernumber INT(11),
22948                 type VARCHAR(64),
22949                 data TEXT,
22950                 enqueued_on DATETIME DEFAULT NULL,
22951                 started_on DATETIME DEFAULT NULL,
22952                 ended_on DATETIME DEFAULT NULL,
22953                 PRIMARY KEY (id)
22954             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
22955         |);
22956     }
22957
22958     $dbh->do(qq{
22959         INSERT IGNORE permissions (module_bit, code, description)
22960         VALUES
22961         (3, 'manage_background_jobs', 'Manage background jobs')
22962     });
22963
22964     NewVersion( $DBversion, 22417, "Add new table background_jobs");
22965 }
22966
22967 $DBversion = '20.06.00.046';
22968 if( CheckVersion( $DBversion ) ) {
22969     unless ( foreign_key_exists( 'alert', 'alert_ibfk_1' ) ) {
22970         $dbh->do(q|
22971             DELETE a FROM alert a
22972             LEFT JOIN borrowers b ON a.borrowernumber=b.borrowernumber
22973             WHERE b.borrowernumber IS NULL
22974         |);
22975         $dbh->do(q|
22976             ALTER TABLE alert
22977             ADD CONSTRAINT alert_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON UPDATE CASCADE ON DELETE CASCADE
22978         |);
22979     }
22980     NewVersion( $DBversion, 13535, "Add FK constraint on borrowernumber to alert table" );
22981 }
22982
22983 $DBversion = '20.06.00.047';
22984 if ( CheckVersion($DBversion) ) {
22985
22986     #Get value from AllowPurchaseSuggestionBranchChoice system preference
22987     my ($allowpurchasesuggestionbranchchoice) =
22988       C4::Context->preference('AllowPurchaseSuggestionBranchChoice');
22989     if ($allowpurchasesuggestionbranchchoice) {
22990         $dbh->do(q{
22991             INSERT IGNORE INTO systempreferences
22992             (`variable`, `value`, `options`, `explanation`, `type`)
22993             VALUES
22994             ('OPACSuggestionUnwantedFields','branch', NULL,'Define the hidden fields for a patron purchase suggestions made via OPAC.','multiple');
22995         });
22996     }
22997     else {
22998         $dbh->do(q{
22999             INSERT IGNORE INTO systempreferences
23000             (`variable`, `value`, `options`, `explanation`, `type`)
23001             VALUES
23002             ('OPACSuggestionUnwantedFields','', NULL,'Define the hidden fields for a patron purchase suggestions made via OPAC.','multiple');
23003         });
23004     }
23005
23006     #Remove the  AllowPurchaseSuggestionBranchChoice system preference
23007     $dbh->do(
23008         "DELETE FROM systempreferences WHERE variable='AllowPurchaseSuggestionBranchChoice'"
23009     );
23010     NewVersion( $DBversion, 23420, "Allow configuration of hidden fields on the suggestion form in OPAC" );
23011 }
23012
23013 $DBversion = '20.06.00.048';
23014 if( CheckVersion( $DBversion ) ) {
23015     $dbh->do(q{
23016         DELETE FROM circulation_rules WHERE
23017         rule_name IN ('holdallowed','hold_fulfillment_policy','returnbranch') AND
23018         rule_value = ''
23019     });
23020     NewVersion( $DBversion, 26529, "Remove blank default branch rules");
23021 }
23022
23023 $DBversion = '20.06.00.049';
23024 if( CheckVersion( $DBversion ) ) {
23025
23026     if( TableExists('biblioimages') && !column_exists( 'biblioimages', 'itemnumber' ) ) {
23027         $dbh->do(q|
23028             ALTER TABLE biblioimages
23029             ADD COLUMN itemnumber INT(11) DEFAULT NULL
23030             AFTER biblionumber;
23031         |);
23032         $dbh->do(q|
23033             ALTER TABLE biblioimages
23034             ADD FOREIGN KEY bibliocoverimage_fk2 (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE
23035         |);
23036         $dbh->do(q|
23037             ALTER TABLE biblioimages MODIFY biblionumber INT(11) DEFAULT NULL
23038         |)
23039     }
23040
23041     if( !TableExists('cover_images') ) {
23042         $dbh->do(q|
23043             ALTER TABLE biblioimages RENAME cover_images
23044         |);
23045     }
23046
23047     NewVersion( $DBversion, '26145', ["Add the biblioimages.itemnumber column", "Rename table biblioimages with cover_images"] );
23048 }
23049
23050 $DBversion = '20.06.00.050';
23051 if ( CheckVersion($DBversion) ) {
23052     $dbh->do(q{
23053         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
23054         ('NoIssuesChargeGuarantorsWithGuarantees','','','Define maximum amount withstanding before checkouts are blocked including guarantors and their other guarantees','Integer');
23055     });
23056
23057     NewVersion( $DBversion, 19382, "Add ability to block guarantees based on fees owed by guarantor and other guarantee - new system preference 'NoIssuesChargeGuarantorsWithGuarantees'");
23058 }
23059
23060 $DBversion = '20.06.00.051';
23061 if( CheckVersion( $DBversion ) ) {
23062     $dbh->do(q{
23063         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
23064         ('HoldsNeedProcessingSIP', '0', NULL, 'Require staff to check-in before hold is set to waiting state', 'YesNo' )
23065     });
23066
23067     NewVersion( $DBversion, 12556, "Add new syspref HoldsNeedProcessingSIP");
23068 }
23069
23070 $DBversion = '20.06.00.052';
23071 if ( CheckVersion($DBversion) ) {
23072     $dbh->do(q{
23073         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')
23074     });
23075
23076     $dbh->do(q{
23077         UPDATE systempreferences SET explanation = 'Automatically update OAI sets when a bibliographic or item record is created or updated' WHERE variable = 'OAI-PMH:AutoUpdateSets'
23078     });
23079
23080     NewVersion( $DBversion, 25460, "Update OAI set when adding/editing/deleting item records" );
23081 }
23082
23083 $DBversion = '20.06.00.053';
23084 if( CheckVersion( $DBversion ) ) {
23085     $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'" );
23086     $dbh->do( "UPDATE systempreferences SET explanation='If enabled, the patron can set checkouts to be visible to their guarantor' WHERE variable='AllowPatronToSetCheckoutsVisibilityForGuarantor'" );
23087     $dbh->do( "UPDATE systempreferences SET explanation='If enabled, the patron can set fines to be visible to their guarantor' WHERE variable='AllowPatronToSetFinesVisibilityForGuarantor'" );
23088     $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'" );
23089     $dbh->do( "UPDATE systempreferences SET explanation='If ON, the next user will automatically get the last searches in their history' WHERE variable='LoadSearchHistoryToTheFirstLoggedUser'" );
23090     $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'" );
23091
23092     NewVersion( $DBversion, 26569, "Use gender neutral pronouns in system preference explanations" );
23093 }
23094
23095 $DBversion = '20.06.00.054';
23096 if ( CheckVersion($DBversion) ) {
23097
23098     $dbh->do(
23099         qq{
23100             INSERT IGNORE INTO account_credit_types (code, description, can_be_added_manually, is_system)
23101             VALUES
23102               ('OVERPAYMENT', 'Overpayment refund', 0, 1)
23103         }
23104     );
23105
23106     $dbh->do(
23107         qq{
23108             INSERT IGNORE INTO account_offset_types ( type ) VALUES ('Overpayment');
23109         }
23110     );
23111
23112     $dbh->do(
23113         qq{
23114             UPDATE accountlines SET credit_type_code = 'OVERPAYMENT' WHERE credit_type_code = 'CREDIT' AND description = 'Overpayment refund'
23115         }
23116     );
23117
23118     NewVersion( $DBversion, 25596, "Add OVERPAYMENT credit type" );
23119 }
23120
23121 $DBversion = '20.06.00.055';
23122 if( CheckVersion( $DBversion ) ) {
23123     my $count_missing_budget = $dbh->selectrow_arrayref(q|
23124         SELECT COUNT(*) FROM aqbudgets ab WHERE NOT EXISTS
23125             (SELECT * FROM aqbudgetperiods abp WHERE abp.budget_period_id = ab.budget_period_id)
23126             AND budget_period_id IS NOT NULL;
23127
23128     |);
23129
23130     my $message = "";
23131     if($count_missing_budget->[0] > 0) {
23132         $dbh->do(q|
23133             CREATE TABLE _bug_18050_aqbudgets AS
23134             SELECT * FROM aqbudgets ab WHERE NOT EXISTS
23135                 (SELECT * FROM aqbudgetperiods abp WHERE abp.budget_period_id = ab.budget_period_id)
23136         |);
23137
23138         $dbh->do(q|
23139             UPDATE aqbudgets ab SET budget_period_id = NULL
23140             WHERE NOT EXISTS
23141                 (SELECT * FROM aqbudgetperiods abp WHERE abp.budget_period_id = ab.budget_period_id)
23142         |);
23143         $message = ". There are $count_missing_budget->[0] funds in your database that are not linked
23144         to a valid budget. Setting invalid budget id (budget_period_id) to null. The table _bug_18050_aqbudgets
23145         was created with original data. Please check that table and place valid ids in aqbudget table as soon as possible."
23146
23147     }
23148
23149     if ( !foreign_key_exists( 'aqbudgets', 'aqbudgetperiods_ibfk_1' ) ) {
23150         $dbh->do(q|
23151             ALTER TABLE aqbudgets ADD CONSTRAINT `aqbudgetperiods_ibfk_1` FOREIGN KEY (`budget_period_id`) REFERENCES `aqbudgetperiods` (`budget_period_id`) ON UPDATE CASCADE ON DELETE CASCADE
23152         |);
23153         NewVersion( $DBversion, 18050, "Add FK constraint on aqbudgets.budget_period_id$message");
23154     } else {
23155         NewVersion( $DBversion, 18050, "FK constraint on aqbudgets.budget already exists");
23156     }
23157
23158 }
23159
23160 $DBversion = '20.06.00.056';
23161 if( CheckVersion( $DBversion ) ) {
23162
23163     $dbh->do("DROP INDEX title ON import_biblios");
23164     $dbh->do("DROP INDEX isbn ON import_biblios");
23165     $dbh->do("ALTER TABLE import_biblios MODIFY title LONGTEXT");
23166     $dbh->do("ALTER TABLE import_biblios MODIFY author LONGTEXT");
23167     $dbh->do("ALTER TABLE import_biblios MODIFY isbn LONGTEXT");
23168     $dbh->do("ALTER TABLE import_biblios MODIFY issn LONGTEXT");
23169     $dbh->do("CREATE INDEX title ON import_biblios (title(191));");
23170     $dbh->do("CREATE INDEX isbn ON import_biblios (isbn(191));");
23171
23172     NewVersion( $DBversion, 26853, "Update import_biblios columns and indexes" );
23173 }
23174
23175 $DBversion = '20.06.00.057';
23176 if( CheckVersion( $DBversion ) ) {
23177     $dbh->do(q{
23178         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES
23179             ('ArticleRequestsMandatoryFieldsItemOnly', '', NULL, 'Comma delimited list of required fields for bibs where article requests rule = ''item_only''', 'multiple')
23180     });
23181     $dbh->do(q{
23182         DELETE FROM systempreferences WHERE variable = "ArticleRequestsMandatoryFieldsItemsOnly"
23183     });
23184
23185     NewVersion( $DBversion, 26638, "Add missing system preference ArticleRequestsMandatoryFieldsItemOnly");
23186 }
23187
23188 $DBversion = '20.06.00.058';
23189 if( CheckVersion( $DBversion ) ) {
23190
23191     # Adding the ON DELETE CASCASE ON UPDATE CASCADE, in case it's missing (from 9016 - 3.15.00.039)
23192     if ( foreign_key_exists( 'letter', 'message_transport_type_fk' ) ) {
23193         $dbh->do( q{
23194             ALTER TABLE letter DROP FOREIGN KEY message_transport_type_fk
23195         } );
23196     }
23197     $dbh->do( q{
23198         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
23199     } );
23200
23201     # Foreign keys should prevent this, however, it has been found in many production databases
23202     $dbh->do( q{
23203         DELETE borrower_message_transport_preferences FROM borrower_message_transport_preferences LEFT JOIN borrower_message_preferences USING (borrower_message_preference_id) WHERE borrower_message_preferences.borrower_message_preference_id IS NULL
23204     } );
23205
23206     $dbh->do(q{
23207         UPDATE message_transport_types SET message_transport_type = "itiva" WHERE message_transport_type = "phone"
23208     });
23209
23210     NewVersion( $DBversion, 25333, q{Change message transport type for Talking Tech from "phone" to "itiva"});
23211 }
23212
23213 $DBversion = '20.06.00.059';
23214 if( CheckVersion( $DBversion ) ) {
23215
23216     if( !column_exists( 'search_field', 'mandatory' ) ) {
23217         $dbh->do( "ALTER TABLE search_field ADD COLUMN mandatory tinyint(1) NULL DEFAULT NULL AFTER opac" );
23218     }
23219
23220     NewVersion( $DBversion, 19482, "Add mandatory column to search_field for ES mapping" );
23221 }
23222
23223 $DBversion = '20.06.00.060';
23224 if( CheckVersion( $DBversion ) ) {
23225     $dbh->do(q{
23226         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
23227         ('PhoneNotification','0',NULL,'If ON, enables generation of phone notifications to be sent by plugins','YesNo')
23228     });
23229
23230     $dbh->do(q{
23231         INSERT IGNORE INTO message_transport_types (message_transport_type) VALUES ('phone')
23232     });
23233
23234     $dbh->do(q{
23235         INSERT IGNORE INTO `message_transports`
23236         (`message_attribute_id`, `message_transport_type`, `is_digest`, `letter_module`, `letter_code`)
23237         VALUES
23238         (1, 'phone',       0, 'circulation', 'DUE'),
23239         (1, 'phone',       1, 'circulation', 'DUEDGST'),
23240         (2, 'phone',       0, 'circulation', 'PREDUE'),
23241         (2, 'phone',       1, 'circulation', 'PREDUEDGST'),
23242         (4, 'phone',       0, 'reserves',    'HOLD'),
23243         (5, 'phone',       0, 'circulation', 'CHECKIN'),
23244         (6, 'phone',       0, 'circulation', 'CHECKOUT');
23245     });
23246
23247     NewVersion( $DBversion, 25334, "Add generic 'phone' message transport type");
23248 }
23249
23250 $DBversion = '20.06.00.061';
23251 if( CheckVersion( $DBversion ) ) {
23252     if ( !column_exists( 'reserves', 'desk_id' ) ) {
23253         $dbh->do(q{
23254              ALTER TABLE reserves ADD COLUMN desk_id INT(11) DEFAULT NULL AFTER branchcode,
23255              ADD KEY desk_id (`desk_id`),
23256              ADD CONSTRAINT `reserves_ibfk_6` FOREIGN KEY (`desk_id`) REFERENCES `desks` (`desk_id`) ON DELETE SET NULL ON UPDATE CASCADE ;
23257         });
23258         $dbh->do(q{
23259              ALTER TABLE old_reserves ADD COLUMN desk_id INT(11) DEFAULT NULL AFTER branchcode,
23260              ADD KEY `old_desk_id` (`desk_id`);
23261         });
23262     }
23263
23264     NewVersion( $DBversion, 24412, "Attach waiting reserve to desk" );
23265 }
23266
23267 $DBversion = '20.06.00.062';
23268 if( CheckVersion( $DBversion ) ) {
23269     $dbh->do( "UPDATE circulation_rules SET rule_name = 'lostreturn' WHERE rule_name = 'refund'" );
23270     $dbh->do( "UPDATE circulation_rules SET rule_value = 'refund' WHERE rule_name = 'lostreturn' AND rule_value = 1" );
23271
23272     NewVersion( $DBversion, 23091, "Update refund rules");
23273 }
23274
23275 $DBversion = '20.06.00.063';
23276 if( CheckVersion( $DBversion ) ) {
23277     $dbh->do(q{INSERT IGNORE INTO circulation_rules (branchcode, categorycode, itemtype, rule_name, rule_value) VALUES (NULL, NULL, NULL, 'decreaseloanholds', NULL) });
23278
23279     NewVersion( $DBversion, 14866, "Add decreaseloanholds circulation rule" );
23280 }
23281
23282 $DBversion = '20.06.00.064';
23283 if ( CheckVersion($DBversion) ) {
23284
23285     $dbh->do(q{
23286         INSERT IGNORE INTO account_credit_types (code, description, can_be_added_manually, is_system)
23287         VALUES ('CANCELLATION', 'Cancelled charge', 0, 1)
23288     });
23289
23290     $dbh->do(q{
23291         INSERT IGNORE INTO account_offset_types ( type ) VALUES ('CANCELLATION');
23292     });
23293
23294     NewVersion( $DBversion, 24603, "Add CANCELLATION credit_type_code" );
23295 }
23296
23297 $DBversion = '20.06.00.065';
23298 if( CheckVersion( $DBversion ) ) {
23299     if( !column_exists( 'issues', 'issuer_id' ) ) {
23300         $dbh->do( q| ALTER TABLE issues ADD issuer_id INT(11) DEFAULT NULL AFTER borrowernumber | );
23301     }
23302     if (!foreign_key_exists( 'issues', 'issues_ibfk_borrowers_borrowernumber' )) {
23303         $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 | );
23304     }
23305     if( !column_exists( 'old_issues', 'issuer_id' ) ) {
23306         $dbh->do( q| ALTER TABLE old_issues ADD issuer_id INT(11) DEFAULT NULL AFTER borrowernumber | );
23307     }
23308     if (!foreign_key_exists( 'old_issues', 'old_issues_ibfk_borrowers_borrowernumber' )) {
23309         $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 | );
23310     }
23311
23312     $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'); | );
23313
23314     NewVersion( $DBversion, 23916, [ "Add new [old_]issues.issuer DB fields", "Add new syspref RecordStaffUserOnCheckout" ] );
23315 }
23316
23317 $DBversion = '20.06.00.066';
23318 if( CheckVersion( $DBversion ) ) {
23319     if( !column_exists( 'branches', 'branchillemail' ) ) {
23320         $dbh->do( q| ALTER TABLE branches ADD branchillemail LONGTEXT AFTER branchemail | );
23321     }
23322     # Add new sysprefs
23323     $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'); | );
23324     $dbh->do( q| INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type) VALUES ('ILLSendStaffNotices', NULL, 'Send these ILL notices to staff', NULL, 'multiple'); | );
23325     # Add new notices
23326     $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'); | );
23327     $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'); | );
23328     $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'); | );
23329     $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'); | );
23330     $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'); | );
23331     $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'); | );
23332     $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'); | );
23333     $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'); | );
23334     $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'); | );
23335     $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'); | );
23336     # Add patron messaging preferences
23337     $dbh->do( q| INSERT IGNORE INTO message_attributes (message_name, takes_days) VALUES ('Ill_ready', 0); | );
23338     my $ready_id = $dbh->last_insert_id(undef, undef, 'message_attributes', undef);
23339     if (defined $ready_id) {
23340         $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');) );
23341         $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');) );
23342         $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');) );
23343     }
23344     $dbh->do( q| INSERT IGNORE INTO message_attributes (message_name, takes_days) VALUES ('Ill_unavailable', 0); | );
23345     my $unavail_id = $dbh->last_insert_id(undef, undef, 'message_attributes', undef);
23346     if (defined $unavail_id) {
23347         $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');) );
23348         $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');) );
23349         $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');) );
23350     }
23351
23352     NewVersion( $DBversion, 22818, "Add ILL notices" );
23353 }
23354
23355 $DBversion = '20.06.00.067';
23356 if( CheckVersion( $DBversion ) ) {
23357     $dbh->do(q{
23358         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
23359         ('OPACHoldsHistory','0','','If ON, enables display of Patron Holds History in OPAC','YesNo')
23360     });
23361
23362     NewVersion( $DBversion, 20936, "Add new system preference OPACHoldsHistory");
23363 }
23364
23365 $DBversion = '20.06.00.068';
23366 if( CheckVersion( $DBversion ) ) {
23367   if( !TableExists( 'import_batch_profiles' ) ) {
23368     $dbh->do(q{
23369       CREATE TABLE `import_batch_profiles` ( -- profile for batches of marc records to be imported
23370         `id` int(11) NOT NULL auto_increment, -- unique identifier and primary key
23371         `name` varchar(100) NOT NULL, -- name of this profile
23372         `matcher_id` int(11) default NULL, -- the id of the match rule used (matchpoints.matcher_id)
23373         `template_id` int(11) default NULL, -- the id of the marc modification template
23374         `overlay_action` varchar(50) default NULL, -- how to handle duplicate records
23375         `nomatch_action` varchar(50) default NULL, -- how to handle records where no match is found
23376         `item_action` varchar(50) default NULL, -- what to do with item records
23377         `parse_items` tinyint(1) default NULL, -- should items be parsed
23378         `record_type` varchar(50) default NULL, -- type of record in the batch
23379         `encoding` varchar(50) default NULL, -- file encoding
23380         `format` varchar(50) default NULL, -- marc format
23381         `comments` LONGTEXT, -- any comments added when the file was uploaded
23382         PRIMARY KEY (`id`),
23383         UNIQUE KEY `u_import_batch_profiles__name` (`name`)
23384       ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
23385     });
23386   }
23387
23388   if(!column_exists('import_batches', 'profile_id')) {
23389     $dbh->do(q{
23390       ALTER TABLE import_batches ADD COLUMN `profile_id` int(11) default NULL AFTER comments
23391     });
23392
23393     $dbh->do(q{
23394       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
23395     });
23396   }
23397
23398   NewVersion( $DBversion, 23019, "Add import_batch_profiles table and profile_id column in import_batches" );
23399 }
23400
23401 $DBversion = '20.06.00.069';
23402 if( CheckVersion( $DBversion ) ) {
23403     my ($count) = $dbh->selectrow_array(
23404         q|
23405             SELECT COUNT(*)
23406             FROM circulation_rules
23407             WHERE rule_name = 'unseen_renewals_allowed'
23408         |
23409     );
23410     if ($count == 0) {
23411         $dbh->do( q|
23412             INSERT INTO circulation_rules (rule_name, rule_value)
23413             VALUES ('unseen_renewals_allowed', '')
23414         | );
23415     }
23416
23417     if( !column_exists( 'issues', 'unseen_renewals' ) ) {
23418         $dbh->do( q| ALTER TABLE issues ADD unseen_renewals TINYINT(4) DEFAULT 0 NOT NULL AFTER renewals | );
23419     }
23420     if( !column_exists( 'old_issues', 'unseen_renewals' ) ) {
23421         $dbh->do( q| ALTER TABLE old_issues ADD unseen_renewals TINYINT(4) DEFAULT 0 NOT NULL AFTER renewals | );
23422     }
23423
23424     $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'); | );
23425
23426     NewVersion( $DBversion, 24083, ["Add circulation_rules 'unseen_renewals_allowed'", "Add issues.unseen_renewals & old_issues.unseen_renewals)", "Add new system preference UnseenRenewals"] );
23427 }
23428
23429 $DBversion = '20.11.00.000';
23430 if( CheckVersion( $DBversion ) ) {
23431     NewVersion( $DBversion, "", "Koha 20.11.00 release" );
23432 }
23433
23434 $DBversion = '20.12.00.000';
23435 if( CheckVersion( $DBversion ) ) {
23436     NewVersion( $DBversion, "", "Sorry, this is my first life, I am still learning!" );
23437 }
23438
23439 $DBversion = '20.12.00.001';
23440 if( CheckVersion( $DBversion ) ) {
23441     $dbh->do(q{
23442         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
23443        ('ElasticsearchCrossFields', '1', '', 'Enable "cross_fields" option for searches using Elastic search.', 'YesNo')
23444     });
23445     NewVersion( $DBversion, 27252, "Add ElasticsearchCrossFields system preference");
23446 }
23447
23448 $DBversion = '20.12.00.002';
23449 if( CheckVersion( $DBversion ) ) {
23450     $dbh->do(q{UPDATE systempreferences SET `type` = 'Choice' WHERE `variable` = 'UsageStatsCountry'});
23451     NewVersion( $DBversion, 27351, "Set type for UsageStatsCountry to Choice");
23452 }
23453
23454 $DBversion = '20.12.00.003';
23455 if( CheckVersion( $DBversion ) ) {
23456     $dbh->do(q{UPDATE systempreferences SET `type` = 'Choice' WHERE `variable` = 'Mana'});
23457     NewVersion( $DBversion, 27349, "Update type for Mana system preference to Choice");
23458 }
23459
23460 $DBversion = '20.12.00.004';
23461 if( CheckVersion( $DBversion ) ) {
23462     $dbh->do(q{UPDATE systempreferences set variable="TaxRates" WHERE variable="gist"});
23463     NewVersion( $DBversion, 27485, "Rename system preference 'gist' to 'TaxRates'");
23464 }
23465
23466 $DBversion = '20.12.00.005';
23467 if( CheckVersion( $DBversion ) ) {
23468     $dbh->do(q{UPDATE systempreferences set variable="OPACLanguages" WHERE variable="opaclanguages"});
23469     NewVersion( $DBversion, 27491, "Rename system preference 'opaclanguages' to 'OPACLanguages'");
23470 }
23471
23472 $DBversion = '20.12.00.006';
23473 if( CheckVersion( $DBversion ) ) {
23474     $dbh->do(q{UPDATE systempreferences SET variable="OPACComments" WHERE variable="reviewson" });
23475     NewVersion( $DBversion, 27487, "Rename system preference 'reviewson' to 'OPACComments");
23476 }
23477
23478 $DBversion = '20.12.00.007';
23479 if( CheckVersion( $DBversion ) ) {
23480     $dbh->do(q{UPDATE systempreferences set variable="CSVDelimiter" WHERE variable="delimiter"});
23481     NewVersion( $DBversion, 27486, "Renaming system preference 'delimiter' to 'CSVDelimiter'");
23482 }
23483
23484 $DBversion = '20.12.00.008';
23485 if( CheckVersion( $DBversion ) ) {
23486     $dbh->do(q{
23487         UPDATE systempreferences
23488         SET options = "claim_returned|batchmod|moredetail|cronjob|additem|pendingreserves|onpayment"
23489         WHERE variable = "MarkLostItemsAsReturned";
23490     });
23491     NewVersion( $DBversion, 25552, "Add missing Claims Returned option to MarkLostItemsAsReturned");
23492 }
23493
23494 $DBversion = '20.12.00.009';
23495 if( CheckVersion( $DBversion ) ) {
23496     $dbh->do( "UPDATE systempreferences SET variable = 'UseICUStyleQUotes' WHERE variable = 'UseICU'" );
23497     NewVersion( $DBversion, 27581, "Rename system preference 'UseICU' to 'UseICUStyleQuotes'");
23498 }
23499
23500 $DBversion = '20.12.00.010';
23501 if( CheckVersion( $DBversion ) ) {
23502     $dbh->do( q{
23503         DELETE FROM systempreferences WHERE variable="OpacGroupResults"
23504     });
23505
23506     NewVersion( $DBversion, 20410, "Remove OpacGroupResults");
23507 }
23508
23509 $DBversion = '20.12.00.011';
23510 if ( CheckVersion($DBversion) ) {
23511     $dbh->do( q{
23512         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
23513         VALUES
23514         ('OPACShibOnly','0','If ON enables shibboleth only authentication for the opac','','YesNo'),
23515         ('staffShibOnly','0','If ON enables shibboleth only authentication for the staff client','','YesNo')
23516     } );
23517     NewVersion( $DBversion, 18506, "Add OPACShibOnly and staffShibOnly system preferences" );
23518 }
23519
23520 $DBversion = '20.12.00.012';
23521 if( CheckVersion( $DBversion ) ) {
23522     my $category_exists = $dbh->selectrow_array("SELECT count(category_name) FROM authorised_value_categories WHERE category_name='UPLOAD'");
23523     my $description;
23524     if( $category_exists ){
23525         $description = "The UPLOAD authorized value category exists. Update the 'is_system' value to 1.";
23526         $dbh->do( "UPDATE authorised_value_categories SET is_system = 1 WHERE category_name = 'UPLOAD'" );
23527     } else {
23528         $description = "The UPLOAD authorized value category does not exist. Create it.";
23529         $dbh->do( "INSERT IGNORE INTO authorised_value_categories (category_name, is_system) VALUES ('UPLOAD', 1)" );
23530     }
23531
23532     NewVersion( $DBversion, 27598, ["Add UPLOAD as a built-in system authorized value category", $description] );
23533 }
23534
23535 $DBversion = '20.12.00.013';
23536 if( CheckVersion( $DBversion ) ) {
23537     $dbh->do(q{
23538          INSERT IGNORE INTO systempreferences
23539          (variable, value, explanation, options, type) VALUES
23540          ('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')
23541     });
23542     NewVersion( $DBversion, 24108, "Add system preference DefaultSaveRecordFileID");
23543 }
23544
23545 $DBversion = '20.12.00.014';
23546 if( CheckVersion( $DBversion ) ) {
23547
23548     sanitize_zero_date('aqorders', 'datecancellationprinted');
23549     sanitize_zero_date('old_issues', 'returndate');
23550
23551     NewVersion( $DBversion, 7806, "Remove remaining possible 0000-00-00 values");
23552 }
23553
23554 $DBversion = '20.12.00.015';
23555 if( CheckVersion( $DBversion ) ) {
23556     $dbh->do( "UPDATE search_marc_to_field SET sort = 1 WHERE sort IS NULL" );
23557     $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'" );
23558     NewVersion( $DBversion, 27316, "In Elastisearch mappings convert NULL (Undef) for sort to 1 (Yes)");
23559 }
23560
23561 $DBversion = '20.12.00.016';
23562 if( CheckVersion( $DBversion ) ) {
23563
23564     unless ( column_exists( 'marc_subfield_structure', 'display_order' ) ) {
23565         $dbh->do(q{
23566             ALTER TABLE marc_subfield_structure
23567             ADD COLUMN display_order INT(2) NOT NULL DEFAULT 0 AFTER maxlength
23568         });
23569     }
23570
23571     unless ( column_exists( 'auth_subfield_structure', 'display_order' ) ) {
23572         $dbh->do(q{
23573             ALTER TABLE auth_subfield_structure
23574             ADD COLUMN display_order INT(2) NOT NULL DEFAULT 0 AFTER defaultvalue
23575         });
23576     }
23577
23578     NewVersion( $DBversion, 8976, "Allow setting a default sequence of subfields in cataloguing editor" );
23579 }
23580
23581 $DBversion = '20.12.00.017';
23582 if( CheckVersion( $DBversion ) ) {
23583     $dbh->do(q|
23584         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
23585         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')
23586     |);
23587
23588     NewVersion( $DBversion, 26937, "Add CheckPrevCheckoutDelay system preference)" );
23589 }
23590
23591 $DBversion = '20.12.00.018';
23592 if( CheckVersion( $DBversion ) ) {
23593
23594     $dbh->do(q|
23595         UPDATE items
23596         LEFT JOIN issues ON issues.itemnumber=items.itemnumber
23597         SET items.onloan=CAST(issues.date_due AS DATE)
23598         WHERE items.onloan IS NULL AND issues.issue_id IS NOT NULL
23599     |);
23600
23601     NewVersion( $DBversion, 27808, "Adjust items.onloan if needed" );
23602 }
23603
23604 $DBversion = '20.12.00.019';
23605 if( CheckVersion( $DBversion ) ) {
23606
23607     if( !column_exists( 'branchtransfers', 'datecancelled' ) ) {
23608         $dbh->do(q|
23609             ALTER TABLE `branchtransfers`
23610             ADD COLUMN `datecancelled` datetime default NULL AFTER `datearrived`
23611         |);
23612     }
23613
23614     if( !column_exists( 'branchtransfers', 'cancellation_reason' ) ) {
23615         $dbh->do(q|
23616             ALTER TABLE `branchtransfers`
23617             ADD COLUMN `cancellation_reason` ENUM('Manual', 'StockrotationAdvance', 'StockrotationRepatriation', 'ReturnToHome', 'ReturnToHolding', 'RotatingCollection', 'Reserve', 'LostReserve', 'CancelReserve') DEFAULT NULL AFTER `reason`
23618         |);
23619     }
23620
23621     NewVersion( $DBversion, 26057, "Add datecancelled field to branchtransfers");
23622 }
23623
23624 $DBversion = '20.12.00.020';
23625 if ( CheckVersion($DBversion) ) {
23626
23627     # Update daterequested from datesent for stockrotation
23628     $dbh->do(q|
23629             UPDATE `branchtransfers`
23630             SET
23631               `daterequested` = `datesent`,
23632               `datesent` = NULL
23633             WHERE `reason` LIKE 'Stockrotation%'
23634             AND   `datearrived` IS NULL
23635     |);
23636
23637     NewVersion( $DBversion, 24446, "Update stockrotation 'daterequested' field in transfers table" );
23638 }
23639
23640 $DBversion = '20.12.00.021';
23641 if( CheckVersion( $DBversion ) ) {
23642     $dbh->do(q{
23643         UPDATE systempreferences SET type="Free" WHERE variable="OverDriveClientSecret" OR variable="RecordedBooksClientSecret"
23644     });
23645     $dbh->do(q{
23646         UPDATE systempreferences SET type="integer" WHERE variable="UsageStats"
23647     });
23648     $dbh->do(q{
23649         UPDATE systempreferences
23650         SET value="0"
23651         WHERE ( ( type = "YesNo" AND ( value NOT IN ( "1", "0" ) OR value IS NULL ) ) )
23652     });
23653
23654     NewVersion( $DBversion, 22824, "Update syspref values for YesNo");
23655 }
23656
23657 $DBversion = '20.12.00.022';
23658 if( CheckVersion( $DBversion ) ) {
23659     $dbh->do(q{ INSERT IGNORE INTO letter (module, code, branchcode, name, is_html, title, content, message_transport_type) VALUES
23660         ('circulation','CHECKINSLIP','','Checkin slip',1,'Checkin slip',
23661 "<h3>[% branch.branchname %]</h3>
23662 Checked in items for [% borrower.title %] [% borrower.firstname %] [% borrower.initials %] [% borrower.surname %] <br />
23663 ([% borrower.cardnumber %]) <br />
23664
23665 [% today | $KohaDates %]<br />
23666
23667 <h4>Checked in today</h4>
23668 [% FOREACH checkin IN old_checkouts %]
23669 [% SET item = checkin.item %]
23670 <p>
23671 [% item.biblio.title %] <br />
23672 Barcode: [% item.barcode %] <br />
23673 </p>
23674 [% END %]",
23675         'print')
23676     });
23677
23678     NewVersion( $DBversion, 12224, "Add CHECKINSLIP notice" );
23679 }
23680
23681 $DBversion = '20.12.00.023';
23682 if( CheckVersion( $DBversion ) ) {
23683
23684     $dbh->do(q{
23685         UPDATE systempreferences
23686         SET value=REPLACE(value, '|', ',')
23687         WHERE variable="OPACHoldsIfAvailableAtPickupExceptions"
23688            OR variable="BatchCheckoutsValidCategories"
23689     });
23690     NewVersion( $DBversion, 27652, "Separate values for OPACHoldsIfAvailableAtPickupExceptions and BatchCheckoutsValidCategories with comma");
23691 }
23692
23693 $DBversion = '20.12.00.024';
23694 if( CheckVersion( $DBversion ) ) {
23695
23696     $dbh->do( q{
23697         INSERT IGNORE INTO letter (module, code, name, title, content, message_transport_type) VALUES ('circulation', 'AUTO_RENEWALS_DGST', 'Notification on auto renewals', 'Auto renewals (Digest)',
23698         "Dear [% borrower.firstname %] [% borrower.surname %],
23699         [% IF error %]
23700             There were [% error %] items that were not renewed.
23701         [% END %]
23702         [% IF success %]
23703             There were [% success %] items that were renewed.
23704         [% END %]
23705         [% FOREACH checkout IN checkouts %]
23706             [% checkout.item.biblio.title %] : [% checkout.item.barcode %]
23707             [% IF !checkout.auto_renew_error %]
23708                 was renewed until [% checkout.date_due | $KohaDates as_due_date => 1%]
23709             [% ELSIF checkout.auto_renew_error == 'too_many' %]
23710                 You have reached the maximum number of renewals possible.
23711             [% ELSIF checkout.auto_renew_error == 'on_reserve' %]
23712                 This item is on hold for another patron.
23713             [% ELSIF checkout.auto_renew_error == 'restriction' %]
23714                 You are currently restricted.
23715             [% ELSIF checkout.auto_renew_error == 'overdue' %]
23716                 You have overdue items.
23717             [% ELSIF checkout.auto_renew_error == 'auto_too_late' %]
23718                 It's too late to renew this item.
23719             [% ELSIF checkout.auto_renew_error == 'auto_too_much_oweing' %]
23720                 Your total unpaid fines are too high.
23721             [% ELSIF checkout.auto_renew_error == 'too_unseen' %]
23722                 This item must be renewed at the library.
23723             [% END %]
23724         [% END %]
23725         ", 'email');
23726     });
23727
23728     $dbh->do( q{
23729         INSERT IGNORE INTO `message_attributes`
23730             (`message_attribute_id`, message_name, `takes_days`)
23731         VALUES (9, 'Auto_Renewals', 0)
23732     });
23733
23734     $dbh->do( q{
23735         INSERT IGNORE INTO `message_transports`
23736             (`message_attribute_id`, `message_transport_type`, `is_digest`, `letter_module`, `letter_code`)
23737         VALUES  (9, 'email', 0, 'circulation', 'AUTO_RENEWALS'),
23738                 (9, 'sms', 0, 'circulation', 'AUTO_RENEWALS'),
23739                 (9, 'email', 1, 'circulation', 'AUTO_RENEWALS_DGST'),
23740                 (9, 'sms', 1, 'circulation', 'AUTO_RENEWALS_DGST')
23741     });
23742
23743      $dbh->do(q{
23744          INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
23745          VALUES ('AutoRenewalNotices','cron','cron|preferences|never','How should Koha determine whether to end autorenewal notices','Choice')
23746      });
23747
23748     NewVersion( $DBversion, 18532, 'Messaging preferences for auto renewals' );
23749 }
23750
23751 $DBversion = '20.12.00.025';
23752 if( CheckVersion( $DBversion ) ) {
23753
23754     $dbh->do(q|
23755         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
23756         VALUES ('ChargeFinesOnClosedDays', '0', NULL, 'Charge fines on days the library is closed.', 'YesNo')
23757     |);
23758
23759     NewVersion( $DBversion, 27835, "Add new system preference ChargeFinesOnClosedDays");
23760 }
23761
23762 $DBversion = '20.12.00.026';
23763 if( CheckVersion( $DBversion ) ) {
23764
23765     $dbh->do(q{INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('DefaultHoldExpirationdate','0','','Automatically set default expiration date for holds','YesNo') });
23766     $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') });
23767     $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') });
23768
23769     NewVersion( $DBversion, 26498, "Bug 26498 - Add option to set a default expire date for holds at reservation time");
23770 }
23771
23772 $DBversion = '20.12.00.027';
23773 if( CheckVersion( $DBversion ) ) {
23774
23775     $dbh->do(q{
23776         UPDATE circulation_rules
23777         SET
23778             rule_value = CASE
23779                 WHEN rule_value='0' THEN 'not_allowed'
23780                 WHEN rule_value='1' THEN 'from_home_library'
23781                 WHEN rule_value='2' THEN 'from_any_library'
23782                 WHEN rule_value='3' THEN 'from_local_hold_group'
23783             END
23784         WHERE rule_name='holdallowed' AND rule_value >= 0 AND rule_value <= 3;
23785     });
23786
23787     NewVersion( $DBversion, 27069, "Change holdallowed values from numbers to strings");
23788 }
23789
23790 $DBversion = '20.12.00.028';
23791 if ( CheckVersion($DBversion) ) {
23792
23793     if ( !column_exists( 'letter', 'id' ) ) {
23794         $dbh->do(q{
23795             ALTER TABLE letter DROP PRIMARY KEY
23796         });
23797         $dbh->do(q{
23798             ALTER TABLE letter ADD COLUMN `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
23799         });
23800         $dbh->do(q{
23801             ALTER TABLE letter ADD UNIQUE KEY letter_uniq_1 (`module`,`code`,`branchcode`,`message_transport_type`,`lang`)
23802         });
23803     }
23804
23805     $dbh->do(q{
23806         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
23807         VALUES ('NoticesLog','0',NULL,'If enabled, log changes to notice templates','YesNo')
23808     });
23809
23810     NewVersion( $DBversion, 14233, "Add id field to letter table" );
23811 }
23812
23813 $DBversion = '20.12.00.029';
23814 if( CheckVersion( $DBversion ) ) {
23815     $dbh->do("ALTER TABLE problem_reports MODIFY content TEXT NOT NULL");
23816
23817     NewVersion( $DBversion, 27726, "Increase field size for problem_reports.content");
23818 }
23819
23820 $DBversion = '20.12.00.030';
23821 if( CheckVersion( $DBversion ) ) {
23822     $dbh->do(q|
23823         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
23824         VALUES ('LockExpiredDelay','','','Delay for locking expired patrons (empty means no locking)','Integer')
23825     |);
23826
23827     NewVersion( $DBversion, 21549, "Add new system preference LockExpiredDelay");
23828 }
23829
23830 $DBversion = '20.12.00.031';
23831 if( CheckVersion( $DBversion ) ) {
23832     $dbh->do(q{
23833         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
23834         VALUES ('Reference_NFL_Statuses','1|2',NULL,'Contains not for loan statuses considered as available for reference','Free')
23835     });
23836
23837     NewVersion( $DBversion, 21260, "Add new system preference Reference_NFL_Statuses");
23838 }
23839
23840 $DBversion = '20.12.00.032';
23841 if( CheckVersion( $DBversion ) ) {
23842     $dbh->do(q{
23843         INSERT IGNORE INTO letter
23844         (module,code,branchcode,name,is_html,title,content,message_transport_type,lang)
23845         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')
23846     });
23847
23848     NewVersion( $DBversion, 15986, "Add sample HOLD_REMINDER notice");
23849 }
23850
23851 $DBversion = '20.12.00.033';
23852 if( CheckVersion( $DBversion ) ) {
23853     my $debar = $dbh->selectall_arrayref(q|
23854         SELECT d.borrowernumber, GROUP_CONCAT(comment SEPARATOR '\n') AS comment
23855         FROM borrower_debarments d
23856         LEFT JOIN borrowers b ON b.borrowernumber=d.borrowernumber
23857         WHERE ( b.debarredcomment IS NULL OR b.debarredcomment = "" ) AND ( expiration > CURRENT_DATE() OR expiration IS NULL )
23858         GROUP BY d.borrowernumber
23859     |, { Slice => {} });
23860
23861
23862     my $update_sth = $dbh->prepare(q|
23863         UPDATE borrowers
23864         SET debarredcomment=?
23865         WHERE borrowernumber=?
23866     |);
23867     for my $d ( @$debar ) {
23868         $update_sth->execute($d->{comment}, $d->{borrowernumber});
23869     }
23870
23871     NewVersion( $DBversion, 26940, "Put in sync borrowers.debarredcomment with comments from borrower_debarments");
23872 }
23873
23874 $DBversion = '20.12.00.034';
23875 if( CheckVersion( $DBversion ) ) {
23876
23877     $dbh->do(q{
23878         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type)
23879         VALUES ('casServerVersion', '2', '2|3', 'Version of the CAS server Koha will connect to.', 'Choice');
23880     });
23881
23882     NewVersion( $DBversion, 20854, "Add new system preference casServerVersion");
23883 }
23884
23885 $DBversion = '20.12.00.035';
23886 if( CheckVersion( $DBversion ) ) {
23887     if( !column_exists( 'itemtypes', 'automatic_checkin' ) ) {
23888         $dbh->do(q{
23889             ALTER TABLE itemtypes
23890                 ADD COLUMN `automatic_checkin` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'If automatic checkin is enabled for items of this type' AFTER `searchcategory`
23891         });
23892     }
23893
23894     NewVersion( $DBversion, 23207, "Add automatic_checkin to itemtypes table");
23895 }
23896
23897 $DBversion = '20.12.00.036';
23898 if( CheckVersion( $DBversion ) ) {
23899     $dbh->do(q{
23900         ALTER TABLE club_holds_to_patron_holds
23901         MODIFY COLUMN error_code
23902         ENUM ( 'damaged', 'ageRestricted', 'itemAlreadyOnHold',
23903             'tooManyHoldsForThisRecord', 'tooManyReservesToday',
23904             'tooManyReserves', 'notReservable', 'cannotReserveFromOtherBranches',
23905             'libraryNotFound', 'libraryNotPickupLocation', 'cannotBeTransferred',
23906             'noReservesAllowed'
23907         )
23908     });
23909
23910     NewVersion( $DBversion, 16787, "Add noReservesAllowed to club holds error codes");
23911 }
23912
23913 $DBversion = '20.12.00.037';
23914 if( CheckVersion( $DBversion ) ) {
23915     $dbh->do( q{
23916         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
23917         VALUES ('AcquisitionLog', '0', 'If enabled, log acquisition activity', '', 'YesNo');
23918     });
23919
23920     NewVersion( $DBversion, 23971, "Add new system preference AcquisitionLog");
23921 }
23922
23923 $DBversion = '20.12.00.038';
23924 if( CheckVersion( $DBversion ) ) {
23925
23926     # Add 'ItemLost' to reserves cancellation_reason enum
23927     $dbh->do(
23928         q{
23929             ALTER TABLE
23930                 `branchtransfers`
23931             MODIFY COLUMN
23932                 `cancellation_reason` enum(
23933                     'Manual',
23934                     'StockrotationAdvance',
23935                     'StockrotationRepatriation',
23936                     'ReturnToHome',
23937                     'ReturnToHolding',
23938                     'RotatingCollection',
23939                     'Reserve',
23940                     'LostReserve',
23941                     'CancelReserve',
23942                     'ItemLost'
23943                 )
23944             AFTER `comments`
23945           }
23946     );
23947
23948     NewVersion( $DBversion, 27281, "Add 'ItemLost' to branchtransfers.cancellation_reason enum");
23949 }
23950
23951 $DBversion = '20.12.00.039';
23952 if( CheckVersion( $DBversion ) ) {
23953
23954     $dbh->do(
23955         q{
23956             ALTER TABLE
23957                 `branchtransfers`
23958             MODIFY COLUMN
23959                 `reason` enum(
23960                     'Manual',
23961                     'StockrotationAdvance',
23962                     'StockrotationRepatriation',
23963                     'ReturnToHome',
23964                     'ReturnToHolding',
23965                     'RotatingCollection',
23966                     'Reserve',
23967                     'LostReserve',
23968                     'CancelReserve',
23969                     'TransferCancellation'
23970                 )
23971             AFTER `comments`
23972           }
23973     );
23974
23975     NewVersion( $DBversion, 12362, "Add 'TransferCancellation' to branchtransfers.reason enum");
23976 }
23977
23978 $DBversion = '20.12.00.040';
23979 if( CheckVersion( $DBversion ) ) {
23980     $dbh->do(
23981         q{
23982             INSERT IGNORE INTO account_debit_types (
23983               code,
23984               description,
23985               can_be_invoiced,
23986               can_be_sold,
23987               default_amount,
23988               is_system
23989             )
23990             VALUES
23991               ('VOID', 'Credit has been voided', 0, 0, NULL, 1)
23992         }
23993     );
23994
23995     $dbh->do(q{
23996         INSERT IGNORE INTO account_offset_types ( type ) VALUES ('VOID');
23997     });
23998
23999     NewVersion( $DBversion, 27971, "Add VOID debit type code");
24000 }
24001
24002 $DBversion = '20.12.00.041';
24003 if ( CheckVersion($DBversion) ) {
24004
24005     # ACCOUNT_CREDIT UPDATES
24006     # backup existing notice to action_logs
24007     my $credit_arr = $dbh->selectall_arrayref(q{SELECT lang FROM letter WHERE code = 'ACCOUNT_CREDIT'}, { Slice => {} });
24008     my $c_sth = $dbh->prepare(q{
24009       INSERT INTO action_logs ( timestamp, module, action, object, info, interface )
24010       SELECT NOW(), 'NOTICES', 'UPGRADE', id, content, 'cli'
24011       FROM letter
24012       WHERE lang = ? AND code = 'ACCOUNT_CREDIT'
24013     });
24014
24015     for my $c ( @{$credit_arr} ) {
24016         $c_sth->execute( $c->{lang} );
24017     }
24018
24019     # replace notice with default
24020     my $c_notice = q{
24021 [% USE Price %]
24022 [% PROCESS 'accounts.inc' %]
24023 <table>
24024 [% IF ( LibraryName ) %]
24025  <tr>
24026     <th colspan="4" class="centerednames">
24027         <h3>[% LibraryName | html %]</h3>
24028     </th>
24029  </tr>
24030 [% END %]
24031  <tr>
24032     <th colspan="4" class="centerednames">
24033         <h2><u>Fee receipt</u></h2>
24034     </th>
24035  </tr>
24036  <tr>
24037     <th colspan="4" class="centerednames">
24038         <h2>[% Branches.GetName( credit.patron.branchcode ) | html %]</h2>
24039     </th>
24040  </tr>
24041  <tr>
24042     <th colspan="4">
24043         Received with thanks from  [% credit.patron.firstname | html %] [% credit.patron.surname | html %] <br />
24044         Card number: [% credit.patron.cardnumber | html %]<br />
24045     </th>
24046  </tr>
24047   <tr>
24048     <th>Date</th>
24049     <th>Description of charges</th>
24050     <th>Note</th>
24051     <th>Amount</th>
24052  </tr>
24053
24054  <tr class="highlight">
24055     <td>[% credit.date | $KohaDates %]</td>
24056     <td>
24057       [% PROCESS account_type_description account=credit %]
24058       [%- IF credit.description %], [% credit.description | html %][% END %]
24059     </td>
24060     <td>[% credit.note | html %]</td>
24061     <td class="credit">[% credit.amount | $Price %]</td>
24062  </tr>
24063
24064 <tfoot>
24065   <tr>
24066     <td colspan="3">Total outstanding dues as on date: </td>
24067     [% IF ( credit.patron.account.balance >= 0 ) %]<td class="credit">[% ELSE %]<td class="debit">[% END %][% credit.patron.account.balance | $Price %]</td>
24068   </tr>
24069 </tfoot>
24070 </table>
24071     };
24072
24073     $dbh->do(q{UPDATE letter SET content = ?, is_html = 1 WHERE code = 'ACCOUNT_CREDIT'}, undef, $c_notice);
24074
24075     # ACCOUNT_DEBIT UPDATES
24076     # backup existing notice to action_logs
24077     my $debit_arr = $dbh->selectall_arrayref(
24078         "SELECT lang FROM letter WHERE code = 'ACCOUNT_DEBIT'", { Slice => {} });
24079     my $d_sth = $dbh->prepare(q{
24080       INSERT INTO action_logs ( timestamp, module, action, object, info, interface )
24081       SELECT NOW(), 'NOTICES', 'UPGRADE', id, content, 'cli'
24082       FROM letter
24083       WHERE lang = ? AND code = 'ACCOUNT_DEBIT'
24084     });
24085
24086     for my $d ( @{$debit_arr} ) {
24087         $d_sth->execute( $d->{lang} );
24088     }
24089
24090     # replace notice with default
24091     my $d_notice = q{
24092 [% USE Price %]
24093 [% PROCESS 'accounts.inc' %]
24094 <table>
24095   [% IF ( LibraryName ) %]
24096     <tr>
24097       <th colspan="5" class="centerednames">
24098         <h3>[% LibraryName | html %]</h3>
24099       </th>
24100     </tr>
24101   [% END %]
24102
24103   <tr>
24104     <th colspan="5" class="centerednames">
24105       <h2><u>INVOICE</u></h2>
24106     </th>
24107   </tr>
24108   <tr>
24109     <th colspan="5" class="centerednames">
24110       <h2>[% Branches.GetName( debit.patron.branchcode ) | html %]</h2>
24111     </th>
24112   </tr>
24113   <tr>
24114     <th colspan="5" >
24115       Bill to: [% debit.patron.firstname | html %] [% debit.patron.surname | html %] <br />
24116       Card number: [% debit.patron.cardnumber | html %]<br />
24117     </th>
24118   </tr>
24119   <tr>
24120     <th>Date</th>
24121     <th>Description of charges</th>
24122     <th>Note</th>
24123     <th style="text-align:right;">Amount</th>
24124     <th style="text-align:right;">Amount outstanding</th>
24125   </tr>
24126
24127   <tr class="highlight">
24128     <td>[% debit.date | $KohaDates%]</td>
24129     <td>
24130       [% PROCESS account_type_description account=debit %]
24131       [%- IF debit.description %], [% debit.description | html %][% END %]
24132     </td>
24133     <td>[% debit.note | html %]</td>
24134     <td class="debit">[% debit.amount | $Price %]</td>
24135     <td class="debit">[% debit.amountoutstanding | $Price %]</td>
24136   </tr>
24137
24138   [% IF ( tendered ) %]
24139     <tr>
24140       <td colspan="3">Amount tendered: </td>
24141       <td>[% tendered | $Price %]</td>
24142     </tr>
24143     <tr>
24144       <td colspan="3">Change given: </td>
24145       <td>[% change | $Price %]</td>
24146     </tr>
24147   [% END %]
24148
24149   <tfoot>
24150     <tr>
24151       <td colspan="4">Total outstanding dues as on date: </td>
24152       [% IF ( debit.patron.account.balance <= 0 ) %]<td class="credit">[% ELSE %]<td class="debit">[% END %][% debit.patron.account.balance | $Price %]</td>
24153     </tr>
24154   </tfoot>
24155 </table>
24156     };
24157     $dbh->do(q{UPDATE letter SET content = ?, is_html = 1 WHERE code = 'ACCOUNT_DEBIT'}, undef, $d_notice);
24158
24159     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."] );
24160 }
24161
24162 $DBversion = '20.12.00.042';
24163 if( CheckVersion( $DBversion ) ) {
24164     unless( foreign_key_exists( 'collections_tracking', 'collectionst_ibfk_1' ) ) {
24165         $dbh->do(q{
24166             DELETE FROM collections_tracking WHERE colId NOT IN ( SELECT colId FROM collections )
24167         });
24168         $dbh->do(q{
24169             ALTER TABLE collections_tracking
24170             ADD CONSTRAINT `collectionst_ibfk_1` FOREIGN KEY (`colId`) REFERENCES `collections` (`colId`) ON DELETE CASCADE ON UPDATE CASCADE
24171         });
24172     }
24173
24174     NewVersion( $DBversion, 17202, "Add FK constraint for collection to collections_tracking");
24175 }
24176
24177 $DBversion = '20.12.00.043';
24178 if( CheckVersion( $DBversion ) ) {
24179     $dbh->do(q{
24180         UPDATE letter SET
24181         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 %]")
24182         WHERE code = 'AUTO_RENEWALS';
24183     });
24184
24185     NewVersion( $DBversion, 28258, "Update AUTO_RENEWAL content");
24186 }
24187
24188 $DBversion = '20.12.00.044';
24189 if( CheckVersion( $DBversion ) ) {
24190     $dbh->do(q{
24191         UPDATE language_subtag_registry SET description = 'Ukrainian' WHERE subtag='uk' and type='language' and description='Ukranian'
24192     });
24193     $dbh->do(q{
24194         UPDATE language_descriptions SET description = 'Ukrainian' WHERE subtag='uk' and type='language' and lang='en' and description='Ukranian'
24195     });
24196
24197     NewVersion( $DBversion, 28244, "Fix Ukrainian typo in English");
24198 }
24199
24200 $DBversion = '20.12.00.045';
24201 if( CheckVersion( $DBversion ) ) {
24202     $dbh->do(q{
24203         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES ('SearchLimitLibrary', 'homebranch', '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')
24204     });
24205
24206     NewVersion( $DBversion, 21249, "Adding new system preference SearchLimitLibrary" );
24207 }
24208
24209 $DBversion = '20.12.00.046';
24210 if( CheckVersion( $DBversion ) ) {
24211     unless ( column_exists('message_queue', 'delivery_note') ) {
24212         $dbh->do(q{
24213             ALTER TABLE message_queue ADD delivery_note mediumtext AFTER content_type
24214         });
24215     }
24216
24217     NewVersion( $DBversion, 14723, "Additional delivery notes to messages" );
24218 }
24219
24220 $DBversion = '20.12.00.047';
24221 if( CheckVersion( $DBversion ) ) {
24222
24223     $dbh->do(q{
24224         DELETE FROM systempreferences
24225         WHERE variable IN
24226             ('EnablePayPalOpacPayments',
24227              'PayPalChargeDescription',
24228              'PayPalPwd',
24229              'PayPalReturnURL',
24230              'PayPalSandboxMode',
24231              'PayPalSignature',
24232              'PayPalUser');
24233     });
24234
24235     NewVersion( $DBversion, 23215, "Remove core PayPal support in favor of the use of plugins" );
24236 }
24237
24238 $DBversion = '20.12.00.048';
24239 if( CheckVersion( $DBversion ) ) {
24240
24241     # This DB upgrade has been commented out because it removes
24242     # actively used data, the relationship columns will be added back
24243
24244     # if ( column_exists( 'borrowers', 'relationship' ) ) {
24245     #     $dbh->do(q{
24246     #         ALTER TABLE borrowers DROP COLUMN relationship
24247     #     });
24248     # }
24249
24250     # if ( column_exists( 'deletedborrowers', 'relationship' ) ) {
24251     #     $dbh->do(q{
24252     #         ALTER TABLE deletedborrowers DROP COLUMN relationship
24253     #     });
24254     # }
24255
24256     # if ( column_exists( 'borrower_modifications', 'relationship' ) ) {
24257     #     $dbh->do(q{
24258     #         ALTER TABLE borrower_modifications DROP COLUMN relationship
24259     #     });
24260     # }
24261
24262     NewVersion( $DBversion, 26995, "[SKIP] Drop column relationship from borrower tables [not executed]");
24263 }
24264
24265 $DBversion = '20.12.00.049';
24266 if ( CheckVersion($DBversion) ) {
24267     $dbh->do(q{
24268         UPDATE action_logs SET module = 'CLAIMS'
24269         WHERE module = 'ACQUISITIONS' AND ( action = 'SERIAL CLAIM' OR action = 'ACQUISITION CLAIM')
24270     });
24271
24272     $dbh->do(q{
24273         UPDATE systempreferences SET variable = 'ClaimsLog' WHERE variable = 'LetterLog';
24274     });
24275
24276     NewVersion( $DBversion, 28108, "Move action logs 'SERIAL CLAIM' and 'ACQUISITION CLAIM' to a new 'CLAIMS' module" );
24277 }
24278
24279 $DBversion = '20.12.00.050';
24280 if ( CheckVersion($DBversion) ) {
24281     $dbh->do(q{
24282         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES
24283         ('OpacHiddenItemsHidesRecord','1','','Hide bibliographic record when all its items are hidden because of OpacHiddenItems','YesNo')
24284     });
24285
24286     NewVersion( $DBversion, 28108, "Add new systempreference OpacHiddenItemsHidesRecord" );
24287 }
24288
24289 $DBversion = '21.05.00.000';
24290 if( CheckVersion( $DBversion ) ) {
24291     NewVersion( $DBversion, "", "Koha 21.05.00 release" );
24292 }
24293
24294 unless ( $ENV{HTTP_HOST} ) { # Is that correct?
24295     my $files = get_db_entries;
24296     my $report = update( $files, { force => $force } );
24297
24298     my $error_code = 0;
24299     for my $s ( @{ $report->{success} } ) {
24300         say Encode::encode_utf8(join "\n", @{$s->{output}});
24301     }
24302     for my $e ( @{ $report->{error} } ) {
24303         say Encode::encode_utf8(join "\n", @{$e->{output}});
24304         say Encode::encode_utf8("ERROR - " . $e->{error});
24305         $error_code = 1;
24306     }
24307
24308     my $atomic_update_files = get_atomic_updates;
24309     $report = run_atomic_updates($atomic_update_files);
24310     for my $s ( @{ $report->{success} } ) {
24311         say Encode::encode_utf8(join "\n", @{$s->{output}});
24312     }
24313     for my $e ( @{ $report->{error} } ) {
24314         say Encode::encode_utf8(join "\n", @{$e->{output}});
24315         say Encode::encode_utf8("ERROR - " . $e->{error});
24316         $error_code = 1;
24317     }
24318     exit $error_code;
24319 }
24320
24321 exit;