Bug 27971: DBRev 20.12.00.040
[koha.git] / installer / data / mysql / updatedatabase.pl
1 #!/usr/bin/perl
2
3 # Database Updater
4 # This script checks for required updates to the database.
5
6 # Parts copyright Catalyst IT 2011
7
8 # Part of the Koha Library Software www.koha-community.org
9 # Koha is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21 #
22
23 # Bugs/ToDo:
24 # - Would also be a good idea to offer to do a backup at this time...
25
26 # NOTE:  If you do something more than once in here, make it table driven.
27
28 # NOTE: Please keep the version in kohaversion.pl up-to-date!
29
30 use Modern::Perl;
31
32 use feature 'say';
33
34 # CPAN modules
35 use DBI;
36 use Getopt::Long;
37 # Koha modules
38 use C4::Context;
39 use C4::Installer;
40 use Koha::Database;
41 use Koha;
42 use Koha::DateUtils;
43
44 use MARC::Record;
45 use MARC::File::XML ( BinaryEncoding => 'utf8' );
46
47 use File::Path qw[remove_tree]; # perl core module
48 use File::Slurp;
49
50 # FIXME - The user might be installing a new database, so can't rely
51 # on /etc/koha.conf anyway.
52
53 my $debug = 0;
54
55 my (
56     $sth,
57     $query,
58     $table,
59     $type,
60 );
61
62 my $schema = Koha::Database->new()->schema();
63
64 my $silent;
65 GetOptions(
66     's' =>\$silent
67     );
68 my $dbh = C4::Context->dbh;
69 $|=1; # flushes output
70
71 local $dbh->{RaiseError} = 0;
72
73 # Record the version we are coming from
74
75 my $original_version = C4::Context->preference("Version");
76
77 # Deal with virtualshelves
78 my $DBversion = "3.00.00.001";
79 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
80     # update virtualshelves table to
81     #
82     $dbh->do("ALTER TABLE `bookshelf` RENAME `virtualshelves`");
83     $dbh->do("ALTER TABLE `shelfcontents` RENAME `virtualshelfcontents`");
84     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD `biblionumber` INT( 11 ) NOT NULL default '0' AFTER shelfnumber");
85     $dbh->do("UPDATE `virtualshelfcontents` SET biblionumber=(SELECT biblionumber FROM items WHERE items.itemnumber=virtualshelfcontents.itemnumber)");
86     # drop all foreign keys : otherwise, we can't drop itemnumber field.
87     DropAllForeignKeys('virtualshelfcontents');
88     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD KEY biblionumber (biblionumber)");
89     # create the new foreign keys (on biblionumber)
90     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD CONSTRAINT `virtualshelfcontents_ibfk_1` FOREIGN KEY (`shelfnumber`) REFERENCES `virtualshelves` (`shelfnumber`) ON DELETE CASCADE ON UPDATE CASCADE");
91     # re-create the foreign key on virtualshelf
92     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD CONSTRAINT `shelfcontents_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE");
93     $dbh->do("ALTER TABLE `virtualshelfcontents` DROP `itemnumber`");
94     print "Upgrade to $DBversion done (virtualshelves)\n";
95     SetVersion ($DBversion);
96 }
97
98
99 $DBversion = "3.00.00.002";
100 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
101     $dbh->do("DROP TABLE sessions");
102     $dbh->do("CREATE TABLE `sessions` (
103   `id` varchar(32) NOT NULL,
104   `a_session` text NOT NULL,
105   UNIQUE KEY `id` (`id`)
106 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
107     print "Upgrade to $DBversion done (sessions uses CGI::session, new table structure for sessions)\n";
108     SetVersion ($DBversion);
109 }
110
111
112 $DBversion = "3.00.00.003";
113 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
114     if (C4::Context->preference("opaclanguages") eq "fr") {
115         $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')");
116     } else {
117         $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')");
118     }
119     print "Upgrade to $DBversion done (adding ReservesNeedReturns systempref, in circulation)\n";
120     SetVersion ($DBversion);
121 }
122
123
124 $DBversion = "3.00.00.004";
125 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
126     $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')");
127     print "Upgrade to $DBversion done (adding DebugLevel systempref, in 'Admin' tab)\n";
128     SetVersion ($DBversion);
129 }
130
131 $DBversion = "3.00.00.005";
132 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
133     $dbh->do("CREATE TABLE `tags` (
134                     `entry` varchar(255) NOT NULL default '',
135                     `weight` bigint(20) NOT NULL default 0,
136                     PRIMARY KEY  (`entry`)
137                     ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
138                 ");
139         $dbh->do("CREATE TABLE `nozebra` (
140                 `server` varchar(20)     NOT NULL,
141                 `indexname` varchar(40)  NOT NULL,
142                 `value` varchar(250)     NOT NULL,
143                 `biblionumbers` longtext NOT NULL,
144                 KEY `indexname` (`server`,`indexname`),
145                 KEY `value` (`server`,`value`))
146                 ENGINE=InnoDB DEFAULT CHARSET=utf8;
147                 ");
148     print "Upgrade to $DBversion done (adding tags and nozebra tables )\n";
149     SetVersion ($DBversion);
150 }
151
152 $DBversion = "3.00.00.006";
153 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
154     sanitize_zero_date('issues', 'issuedate');
155     print "Upgrade to $DBversion done (filled issues.issuedate with timestamp)\n";
156     SetVersion ($DBversion);
157 }
158
159 $DBversion = "3.00.00.007";
160 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
161     $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')");
162     print "Upgrade to $DBversion done (set SessionStorage variable)\n";
163     SetVersion ($DBversion);
164 }
165
166 $DBversion = "3.00.00.008";
167 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
168     $dbh->do("ALTER TABLE `biblio` ADD `datecreated` DATE NOT NULL AFTER `timestamp` ;");
169     $dbh->do("UPDATE biblio SET datecreated=timestamp");
170     print "Upgrade to $DBversion done (biblio creation date)\n";
171     SetVersion ($DBversion);
172 }
173
174 $DBversion = "3.00.00.009";
175 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
176
177     # Create backups of call number columns
178     # in case default migration needs to be customized
179     #
180     # UPGRADE NOTE: temp_upg_biblioitems_call_num should be dropped
181     #               after call numbers have been transformed to the new structure
182     #
183     # Not bothering to do the same with deletedbiblioitems -- assume
184     # default is good enough.
185     $dbh->do("CREATE TABLE `temp_upg_biblioitems_call_num` AS
186               SELECT `biblioitemnumber`, `biblionumber`,
187                      `classification`, `dewey`, `subclass`,
188                      `lcsort`, `ccode`
189               FROM `biblioitems`");
190
191     # biblioitems changes
192     $dbh->do("ALTER TABLE `biblioitems` CHANGE COLUMN `volumeddesc` `volumedesc` TEXT,
193                                     ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
194                                     ADD `cn_class` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
195                                     ADD `cn_item` VARCHAR(10) DEFAULT NULL AFTER `cn_class`,
196                                     ADD `cn_suffix` VARCHAR(10) DEFAULT NULL AFTER `cn_item`,
197                                     ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_suffix`,
198                                     ADD `totalissues` INT(10) AFTER `cn_sort`");
199
200     # default mapping of call number columns:
201     #   cn_class = concatentation of classification + dewey,
202     #              trimmed to fit -- assumes that most users do not
203     #              populate both classification and dewey in a single record
204     #   cn_item  = subclass
205     #   cn_source = left null
206     #   cn_sort = lcsort
207     #
208     # After upgrade, cn_sort will have to be set based on whatever
209     # default call number scheme user sets as a preference.  Misc
210     # script will be added at some point to do that.
211     #
212     $dbh->do("UPDATE `biblioitems`
213               SET cn_class = SUBSTR(TRIM(CONCAT_WS(' ', `classification`, `dewey`)), 1, 30),
214                     cn_item = subclass,
215                     `cn_sort` = `lcsort`
216             ");
217
218     # Now drop the old call number columns
219     $dbh->do("ALTER TABLE `biblioitems` DROP COLUMN `classification`,
220                                         DROP COLUMN `dewey`,
221                                         DROP COLUMN `subclass`,
222                                         DROP COLUMN `lcsort`,
223                                         DROP COLUMN `ccode`");
224
225     # deletedbiblio changes
226     $dbh->do("ALTER TABLE `deletedbiblio` ALTER COLUMN `frameworkcode` SET DEFAULT '',
227                                         DROP COLUMN `marc`,
228                                         ADD `datecreated` DATE NOT NULL AFTER `timestamp`");
229     $dbh->do("UPDATE deletedbiblio SET datecreated = timestamp");
230
231     # deletedbiblioitems changes
232     $dbh->do("ALTER TABLE `deletedbiblioitems`
233                         MODIFY `publicationyear` TEXT,
234                         CHANGE `volumeddesc` `volumedesc` TEXT,
235                         MODIFY `collectiontitle` MEDIUMTEXT DEFAULT NULL AFTER `volumedesc`,
236                         MODIFY `collectionissn` TEXT DEFAULT NULL AFTER `collectiontitle`,
237                         MODIFY `collectionvolume` MEDIUMTEXT DEFAULT NULL AFTER `collectionissn`,
238                         MODIFY `editionstatement` TEXT DEFAULT NULL AFTER `collectionvolume`,
239                         MODIFY `editionresponsibility` TEXT DEFAULT NULL AFTER `editionstatement`,
240                         MODIFY `place` VARCHAR(255) DEFAULT NULL AFTER `size`,
241                         MODIFY `marc` LONGBLOB,
242                         ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `url`,
243                         ADD `cn_class` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
244                         ADD `cn_item` VARCHAR(10) DEFAULT NULL AFTER `cn_class`,
245                         ADD `cn_suffix` VARCHAR(10) DEFAULT NULL AFTER `cn_item`,
246                         ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_suffix`,
247                         ADD `totalissues` INT(10) AFTER `cn_sort`,
248                         ADD `marcxml` LONGTEXT NOT NULL AFTER `totalissues`,
249                         ADD KEY `isbn` (`isbn`),
250                         ADD KEY `publishercode` (`publishercode`)
251                     ");
252
253     $dbh->do("UPDATE `deletedbiblioitems`
254                 SET `cn_class` = SUBSTR(TRIM(CONCAT_WS(' ', `classification`, `dewey`)), 1, 30),
255                `cn_item` = `subclass`,
256                 `cn_sort` = `lcsort`
257             ");
258     $dbh->do("ALTER TABLE `deletedbiblioitems`
259                         DROP COLUMN `classification`,
260                         DROP COLUMN `dewey`,
261                         DROP COLUMN `subclass`,
262                         DROP COLUMN `lcsort`,
263                         DROP COLUMN `ccode`
264             ");
265
266     # deleteditems changes
267     $dbh->do("ALTER TABLE `deleteditems`
268                         MODIFY `barcode` VARCHAR(20) DEFAULT NULL,
269                         MODIFY `price` DECIMAL(8,2) DEFAULT NULL,
270                         MODIFY `replacementprice` DECIMAL(8,2) DEFAULT NULL,
271                         DROP `bulk`,
272                         MODIFY `itemcallnumber` VARCHAR(30) DEFAULT NULL AFTER `wthdrawn`,
273                         MODIFY `holdingbranch` VARCHAR(10) DEFAULT NULL,
274                         DROP `interim`,
275                         MODIFY `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP AFTER `paidfor`,
276                         DROP `cutterextra`,
277                         ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `onloan`,
278                         ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
279                         ADD `ccode` VARCHAR(10) DEFAULT NULL AFTER `cn_sort`,
280                         ADD `materials` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
281                         ADD `uri` VARCHAR(255) DEFAULT NULL AFTER `materials`,
282                         MODIFY `marc` LONGBLOB AFTER `uri`,
283                         DROP KEY `barcode`,
284                         DROP KEY `itembarcodeidx`,
285                         DROP KEY `itembinoidx`,
286                         DROP KEY `itembibnoidx`,
287                         ADD UNIQUE KEY `delitembarcodeidx` (`barcode`),
288                         ADD KEY `delitembinoidx` (`biblioitemnumber`),
289                         ADD KEY `delitembibnoidx` (`biblionumber`),
290                         ADD KEY `delhomebranch` (`homebranch`),
291                         ADD KEY `delholdingbranch` (`holdingbranch`)");
292     $dbh->do("UPDATE deleteditems SET `ccode` = `itype`");
293     $dbh->do("ALTER TABLE deleteditems DROP `itype`");
294     $dbh->do("UPDATE `deleteditems` SET `cn_sort` = `itemcallnumber`");
295
296     # items changes
297     $dbh->do("ALTER TABLE `items` ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `onloan`,
298                                 ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
299                                 ADD `ccode` VARCHAR(10) DEFAULT NULL AFTER `cn_sort`,
300                                 ADD `materials` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
301                                 ADD `uri` VARCHAR(255) DEFAULT NULL AFTER `materials`
302             ");
303     $dbh->do("ALTER TABLE `items`
304                         DROP KEY `itembarcodeidx`,
305                         ADD UNIQUE KEY `itembarcodeidx` (`barcode`)");
306
307     # map items.itype to items.ccode and
308     # set cn_sort to itemcallnumber -- as with biblioitems.cn_sort,
309     # will have to be subsequently updated per user's default
310     # classification scheme
311     $dbh->do("UPDATE `items` SET `cn_sort` = `itemcallnumber`,
312                             `ccode` = `itype`");
313
314     $dbh->do("ALTER TABLE `items` DROP `cutterextra`,
315                                 DROP `itype`");
316
317     print "Upgrade to $DBversion done (major changes to biblio, biblioitems, items, and deleted* versions of same\n";
318     SetVersion ($DBversion);
319 }
320
321 $DBversion = "3.00.00.010";
322 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
323     $dbh->do("CREATE INDEX `userid` ON borrowers (`userid`) ");
324     print "Upgrade to $DBversion done (userid index added)\n";
325     SetVersion ($DBversion);
326 }
327
328 $DBversion = "3.00.00.011";
329 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
330     $dbh->do("ALTER TABLE `branchcategories` CHANGE `categorycode` `categorycode` varchar(10) ");
331     $dbh->do("ALTER TABLE `branchcategories` CHANGE `categoryname` `categoryname` varchar(32) ");
332     $dbh->do("ALTER TABLE `branchcategories` ADD COLUMN `categorytype` varchar(16) ");
333     $dbh->do("UPDATE `branchcategories` SET `categorytype` = 'properties'");
334     $dbh->do("ALTER TABLE `branchrelations` CHANGE `categorycode` `categorycode` varchar(10) ");
335     print "Upgrade to $DBversion done (added branchcategory type)\n";
336     SetVersion ($DBversion);
337 }
338
339 $DBversion = "3.00.00.012";
340 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
341     $dbh->do("CREATE TABLE `class_sort_rules` (
342                                `class_sort_rule` varchar(10) NOT NULL default '',
343                                `description` mediumtext,
344                                `sort_routine` varchar(30) NOT NULL default '',
345                                PRIMARY KEY (`class_sort_rule`),
346                                UNIQUE KEY `class_sort_rule_idx` (`class_sort_rule`)
347                              ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
348     $dbh->do("CREATE TABLE `class_sources` (
349                                `cn_source` varchar(10) NOT NULL default '',
350                                `description` mediumtext,
351                                `used` tinyint(4) NOT NULL default 0,
352                                `class_sort_rule` varchar(10) NOT NULL default '',
353                                PRIMARY KEY (`cn_source`),
354                                UNIQUE KEY `cn_source_idx` (`cn_source`),
355                                KEY `used_idx` (`used`),
356                                CONSTRAINT `class_source_ibfk_1` FOREIGN KEY (`class_sort_rule`)
357                                           REFERENCES `class_sort_rules` (`class_sort_rule`)
358                              ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
359     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type)
360               VALUES('DefaultClassificationSource','ddc',
361                      'Default classification scheme used by the collection. E.g., Dewey, LCC, etc.', NULL,'free')");
362     $dbh->do("INSERT INTO `class_sort_rules` (`class_sort_rule`, `description`, `sort_routine`) VALUES
363                                ('dewey', 'Default filing rules for DDC', 'Dewey'),
364                                ('lcc', 'Default filing rules for LCC', 'LCC'),
365                                ('generic', 'Generic call number filing rules', 'Generic')");
366     $dbh->do("INSERT INTO `class_sources` (`cn_source`, `description`, `used`, `class_sort_rule`) VALUES
367                             ('ddc', 'Dewey Decimal Classification', 1, 'dewey'),
368                             ('lcc', 'Library of Congress Classification', 1, 'lcc'),
369                             ('udc', 'Universal Decimal Classification', 0, 'generic'),
370                             ('sudocs', 'SuDoc Classification (U.S. GPO)', 0, 'generic'),
371                             ('z', 'Other/Generic Classification Scheme', 0, 'generic')");
372     print "Upgrade to $DBversion done (classification sources added)\n";
373     SetVersion ($DBversion);
374 }
375
376 $DBversion = "3.00.00.013";
377 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
378     $dbh->do("CREATE TABLE `import_batches` (
379               `import_batch_id` int(11) NOT NULL auto_increment,
380               `template_id` int(11) default NULL,
381               `branchcode` varchar(10) default NULL,
382               `num_biblios` int(11) NOT NULL default 0,
383               `num_items` int(11) NOT NULL default 0,
384               `upload_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
385               `overlay_action` enum('replace', 'create_new', 'use_template') NOT NULL default 'create_new',
386               `import_status` enum('staging', 'staged', 'importing', 'imported', 'reverting', 'reverted', 'cleaned') NOT NULL default 'staging',
387               `batch_type` enum('batch', 'z3950') NOT NULL default 'batch',
388               `file_name` varchar(100),
389               `comments` mediumtext,
390               PRIMARY KEY (`import_batch_id`),
391               KEY `branchcode` (`branchcode`)
392               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
393     $dbh->do("CREATE TABLE `import_records` (
394               `import_record_id` int(11) NOT NULL auto_increment,
395               `import_batch_id` int(11) NOT NULL,
396               `branchcode` varchar(10) default NULL,
397               `record_sequence` int(11) NOT NULL default 0,
398               `upload_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
399               `import_date` DATE default NULL,
400               `marc` longblob NOT NULL,
401               `marcxml` longtext NOT NULL,
402               `marcxml_old` longtext NOT NULL,
403               `record_type` enum('biblio', 'auth', 'holdings') NOT NULL default 'biblio',
404               `overlay_status` enum('no_match', 'auto_match', 'manual_match', 'match_applied') NOT NULL default 'no_match',
405               `status` enum('error', 'staged', 'imported', 'reverted', 'items_reverted') NOT NULL default 'staged',
406               `import_error` mediumtext,
407               `encoding` varchar(40) NOT NULL default '',
408               `z3950random` varchar(40) default NULL,
409               PRIMARY KEY (`import_record_id`),
410               CONSTRAINT `import_records_ifbk_1` FOREIGN KEY (`import_batch_id`)
411                           REFERENCES `import_batches` (`import_batch_id`) ON DELETE CASCADE ON UPDATE CASCADE,
412               KEY `branchcode` (`branchcode`),
413               KEY `batch_sequence` (`import_batch_id`, `record_sequence`)
414               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
415     $dbh->do("CREATE TABLE `import_record_matches` (
416               `import_record_id` int(11) NOT NULL,
417               `candidate_match_id` int(11) NOT NULL,
418               `score` int(11) NOT NULL default 0,
419               CONSTRAINT `import_record_matches_ibfk_1` FOREIGN KEY (`import_record_id`)
420                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
421               KEY `record_score` (`import_record_id`, `score`)
422               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
423     $dbh->do("CREATE TABLE `import_biblios` (
424               `import_record_id` int(11) NOT NULL,
425               `matched_biblionumber` int(11) default NULL,
426               `control_number` varchar(25) default NULL,
427               `original_source` varchar(25) default NULL,
428               `title` varchar(128) default NULL,
429               `author` varchar(80) default NULL,
430               `isbn` varchar(14) default NULL,
431               `issn` varchar(9) default NULL,
432               `has_items` tinyint(1) NOT NULL default 0,
433               CONSTRAINT `import_biblios_ibfk_1` FOREIGN KEY (`import_record_id`)
434                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
435               KEY `matched_biblionumber` (`matched_biblionumber`),
436               KEY `title` (`title`),
437               KEY `isbn` (`isbn`)
438               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
439     $dbh->do("CREATE TABLE `import_items` (
440               `import_items_id` int(11) NOT NULL auto_increment,
441               `import_record_id` int(11) NOT NULL,
442               `itemnumber` int(11) default NULL,
443               `branchcode` varchar(10) default NULL,
444               `status` enum('error', 'staged', 'imported', 'reverted') NOT NULL default 'staged',
445               `marcxml` longtext NOT NULL,
446               `import_error` mediumtext,
447               PRIMARY KEY (`import_items_id`),
448               CONSTRAINT `import_items_ibfk_1` FOREIGN KEY (`import_record_id`)
449                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
450               KEY `itemnumber` (`itemnumber`),
451               KEY `branchcode` (`branchcode`)
452               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
453
454     $dbh->do("INSERT INTO `import_batches`
455                 (`overlay_action`, `import_status`, `batch_type`, `file_name`)
456               SELECT distinct 'create_new', 'staged', 'z3950', `file`
457               FROM   `marc_breeding`");
458
459     $dbh->do("INSERT INTO `import_records`
460                 (`import_batch_id`, `import_record_id`, `record_sequence`, `marc`, `record_type`, `status`,
461                 `encoding`, `z3950random`, `marcxml`, `marcxml_old`)
462               SELECT `import_batch_id`, `id`, 1, `marc`, 'biblio', 'staged', `encoding`, `z3950random`, '', ''
463               FROM `marc_breeding`
464               JOIN `import_batches` ON (`file_name` = `file`)");
465
466     $dbh->do("INSERT INTO `import_biblios`
467                 (`import_record_id`, `title`, `author`, `isbn`)
468               SELECT `import_record_id`, `title`, `author`, `isbn`
469               FROM   `marc_breeding`
470               JOIN   `import_records` ON (`import_record_id` = `id`)");
471
472     $dbh->do("UPDATE `import_batches`
473               SET `num_biblios` = (
474               SELECT COUNT(*)
475               FROM `import_records`
476               WHERE `import_batch_id` = `import_batches`.`import_batch_id`
477               )");
478
479     $dbh->do("DROP TABLE `marc_breeding`");
480
481     print "Upgrade to $DBversion done (import_batches et al. added)\n";
482     SetVersion ($DBversion);
483 }
484
485 $DBversion = "3.00.00.014";
486 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
487     $dbh->do("ALTER TABLE subscription ADD lastbranch VARCHAR(4)");
488     print "Upgrade to $DBversion done (userid index added)\n";
489     SetVersion ($DBversion);
490 }
491
492 $DBversion = "3.00.00.015";
493 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
494     $dbh->do("CREATE TABLE `saved_sql` (
495            `id` int(11) NOT NULL auto_increment,
496            `borrowernumber` int(11) default NULL,
497            `date_created` datetime default NULL,
498            `last_modified` datetime default NULL,
499            `savedsql` text,
500            `last_run` datetime default NULL,
501            `report_name` varchar(255) default NULL,
502            `type` varchar(255) default NULL,
503            `notes` text,
504            PRIMARY KEY  (`id`),
505            KEY boridx (`borrowernumber`)
506         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
507     $dbh->do("CREATE TABLE `saved_reports` (
508            `id` int(11) NOT NULL auto_increment,
509            `report_id` int(11) default NULL,
510            `report` longtext,
511            `date_run` datetime default NULL,
512            PRIMARY KEY  (`id`)
513         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
514     print "Upgrade to $DBversion done (saved_sql and saved_reports added)\n";
515     SetVersion ($DBversion);
516 }
517
518 $DBversion = "3.00.00.016";
519 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
520     $dbh->do(" CREATE TABLE reports_dictionary (
521           id int(11) NOT NULL auto_increment,
522           name varchar(255) default NULL,
523           description text,
524           date_created datetime default NULL,
525           date_modified datetime default NULL,
526           saved_sql text,
527           area int(11) default NULL,
528           PRIMARY KEY  (id)
529         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
530     print "Upgrade to $DBversion done (reports_dictionary) added)\n";
531     SetVersion ($DBversion);
532 }
533
534 $DBversion = "3.00.00.017";
535 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
536     $dbh->do("ALTER TABLE action_logs DROP PRIMARY KEY");
537     $dbh->do("ALTER TABLE action_logs ADD KEY  timestamp (timestamp,user)");
538     $dbh->do("ALTER TABLE action_logs ADD action_id INT(11) NOT NULL FIRST");
539     $dbh->do("UPDATE action_logs SET action_id = if (\@a, \@a:=\@a+1, \@a:=1)");
540     $dbh->do("ALTER TABLE action_logs MODIFY action_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY");
541     print "Upgrade to $DBversion done (added column to action_logs)\n";
542     SetVersion ($DBversion);
543 }
544
545 $DBversion = "3.00.00.018";
546 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
547     $dbh->do("ALTER TABLE `zebraqueue`
548                     ADD `done` INT NOT NULL DEFAULT '0',
549                     ADD `time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ;
550             ");
551     print "Upgrade to $DBversion done (adding timestamp and done columns to zebraque table to improve problem tracking) added)\n";
552     SetVersion ($DBversion);
553 }
554
555 $DBversion = "3.00.00.019";
556 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
557     $dbh->do("ALTER TABLE biblio MODIFY biblionumber INT(11) NOT NULL AUTO_INCREMENT");
558     $dbh->do("ALTER TABLE biblioitems MODIFY biblioitemnumber INT(11) NOT NULL AUTO_INCREMENT");
559     $dbh->do("ALTER TABLE items MODIFY itemnumber INT(11) NOT NULL AUTO_INCREMENT");
560     print "Upgrade to $DBversion done (made bib/item PKs auto_increment)\n";
561     SetVersion ($DBversion);
562 }
563
564 $DBversion = "3.00.00.020";
565 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
566     $dbh->do("ALTER TABLE deleteditems
567               DROP KEY `delitembarcodeidx`,
568               ADD KEY `delitembarcodeidx` (`barcode`)");
569     print "Upgrade to $DBversion done (dropped uniqueness of key on deleteditems.barcode)\n";
570     SetVersion ($DBversion);
571 }
572
573 $DBversion = "3.00.00.021";
574 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
575     $dbh->do("ALTER TABLE items CHANGE homebranch homebranch VARCHAR(10)");
576     $dbh->do("ALTER TABLE deleteditems CHANGE homebranch homebranch VARCHAR(10)");
577     $dbh->do("ALTER TABLE statistics CHANGE branch branch VARCHAR(10)");
578     $dbh->do("ALTER TABLE subscription CHANGE lastbranch lastbranch VARCHAR(10)");
579     print "Upgrade to $DBversion done (extended missed branchcode columns to 10 chars)\n";
580     SetVersion ($DBversion);
581 }
582
583 $DBversion = "3.00.00.022";
584 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
585     $dbh->do("ALTER TABLE items
586                 ADD `damaged` tinyint(1) default NULL AFTER notforloan");
587     $dbh->do("ALTER TABLE deleteditems
588                 ADD `damaged` tinyint(1) default NULL AFTER notforloan");
589     print "Upgrade to $DBversion done (adding damaged column to items table)\n";
590     SetVersion ($DBversion);
591 }
592
593 $DBversion = "3.00.00.023";
594 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
595      $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
596          VALUES ('yuipath','http://yui.yahooapis.com/2.3.1/build','Insert the path to YUI libraries','','free')");
597     print "Upgrade to $DBversion done (adding new system preference for controlling YUI path)\n";
598     SetVersion ($DBversion);
599 }
600 $DBversion = "3.00.00.024";
601 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
602     $dbh->do("ALTER TABLE biblioitems CHANGE  itemtype itemtype VARCHAR(10)");
603     print "Upgrade to $DBversion done (changing itemtype to (10))\n";
604     SetVersion ($DBversion);
605 }
606
607 $DBversion = "3.00.00.025";
608 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
609     $dbh->do("ALTER TABLE items ADD COLUMN itype VARCHAR(10)");
610     $dbh->do("ALTER TABLE deleteditems ADD COLUMN itype VARCHAR(10) AFTER uri");
611     if(C4::Context->preference('item-level_itypes')){
612         $dbh->do('update items,biblioitems set items.itype=biblioitems.itemtype where items.biblionumber=biblioitems.biblionumber and itype is null');
613     }
614     print "Upgrade to $DBversion done (reintroduce items.itype - fill from itemtype)\n ";
615     SetVersion ($DBversion);
616 }
617
618 $DBversion = "3.00.00.026";
619 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
620     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
621        VALUES ('HomeOrHoldingBranch','homebranch','homebranch|holdingbranch','With independent branches turned on this decides whether to check the items holdingbranch or homebranch at circulatilon','choice')");
622     print "Upgrade to $DBversion done (adding new system preference for choosing whether homebranch or holdingbranch is checked in circulation)\n";
623     SetVersion ($DBversion);
624 }
625
626 $DBversion = "3.00.00.027";
627 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
628     $dbh->do("CREATE TABLE `marc_matchers` (
629                 `matcher_id` int(11) NOT NULL auto_increment,
630                 `code` varchar(10) NOT NULL default '',
631                 `description` varchar(255) NOT NULL default '',
632                 `record_type` varchar(10) NOT NULL default 'biblio',
633                 `threshold` int(11) NOT NULL default 0,
634                 PRIMARY KEY (`matcher_id`),
635                 KEY `code` (`code`),
636                 KEY `record_type` (`record_type`)
637               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
638     $dbh->do("CREATE TABLE `matchpoints` (
639                 `matcher_id` int(11) NOT NULL,
640                 `matchpoint_id` int(11) NOT NULL auto_increment,
641                 `search_index` varchar(30) NOT NULL default '',
642                 `score` int(11) NOT NULL default 0,
643                 PRIMARY KEY (`matchpoint_id`),
644                 CONSTRAINT `matchpoints_ifbk_1` FOREIGN KEY (`matcher_id`)
645                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE
646               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
647     $dbh->do("CREATE TABLE `matchpoint_components` (
648                 `matchpoint_id` int(11) NOT NULL,
649                 `matchpoint_component_id` int(11) NOT NULL auto_increment,
650                 sequence int(11) NOT NULL default 0,
651                 tag varchar(3) NOT NULL default '',
652                 subfields varchar(40) NOT NULL default '',
653                 offset int(4) NOT NULL default 0,
654                 length int(4) NOT NULL default 0,
655                 PRIMARY KEY (`matchpoint_component_id`),
656                 KEY `by_sequence` (`matchpoint_id`, `sequence`),
657                 CONSTRAINT `matchpoint_components_ifbk_1` FOREIGN KEY (`matchpoint_id`)
658                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
659               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
660     $dbh->do("CREATE TABLE `matchpoint_component_norms` (
661                 `matchpoint_component_id` int(11) NOT NULL,
662                 `sequence`  int(11) NOT NULL default 0,
663                 `norm_routine` varchar(50) NOT NULL default '',
664                 KEY `matchpoint_component_norms` (`matchpoint_component_id`, `sequence`),
665                 CONSTRAINT `matchpoint_component_norms_ifbk_1` FOREIGN KEY (`matchpoint_component_id`)
666                            REFERENCES `matchpoint_components` (`matchpoint_component_id`) ON DELETE CASCADE ON UPDATE CASCADE
667               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
668     $dbh->do("CREATE TABLE `matcher_matchpoints` (
669                 `matcher_id` int(11) NOT NULL,
670                 `matchpoint_id` int(11) NOT NULL,
671                 CONSTRAINT `matcher_matchpoints_ifbk_1` FOREIGN KEY (`matcher_id`)
672                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE,
673                 CONSTRAINT `matcher_matchpoints_ifbk_2` FOREIGN KEY (`matchpoint_id`)
674                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
675               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
676     $dbh->do("CREATE TABLE `matchchecks` (
677                 `matcher_id` int(11) NOT NULL,
678                 `matchcheck_id` int(11) NOT NULL auto_increment,
679                 `source_matchpoint_id` int(11) NOT NULL,
680                 `target_matchpoint_id` int(11) NOT NULL,
681                 PRIMARY KEY (`matchcheck_id`),
682                 CONSTRAINT `matcher_matchchecks_ifbk_1` FOREIGN KEY (`matcher_id`)
683                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE,
684                 CONSTRAINT `matcher_matchchecks_ifbk_2` FOREIGN KEY (`source_matchpoint_id`)
685                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE,
686                 CONSTRAINT `matcher_matchchecks_ifbk_3` FOREIGN KEY (`target_matchpoint_id`)
687                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
688               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
689     print "Upgrade to $DBversion done (added C4::Matcher serialization tables)\n ";
690     SetVersion ($DBversion);
691 }
692
693 $DBversion = "3.00.00.028";
694 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
695     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
696        VALUES ('canreservefromotherbranches','1','','With Independent branches on, can a user from one library reserve an item from another library','YesNo')");
697     print "Upgrade to $DBversion done (adding new system preference for changing reserve/holds behaviour with independent branches)\n";
698     SetVersion ($DBversion);
699 }
700
701
702 $DBversion = "3.00.00.029";
703 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
704     $dbh->do("ALTER TABLE `import_batches` ADD `matcher_id` int(11) NULL AFTER `import_batch_id`");
705     print "Upgrade to $DBversion done (adding matcher_id to import_batches)\n";
706     SetVersion ($DBversion);
707 }
708
709 $DBversion = "3.00.00.030";
710 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
711     $dbh->do("
712 CREATE TABLE services_throttle (
713   service_type varchar(10) NOT NULL default '',
714   service_count varchar(45) default NULL,
715   PRIMARY KEY  (service_type)
716 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
717 ");
718     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
719        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')");
720  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
721        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')");
722  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
723        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')");
724  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
725        VALUES ('XISBNDailyLimit',499,'','The xISBN Web service is free for non-commercial use when usage does not exceed 500 requests per day','free')");
726  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
727        VALUES ('PINESISBN',0,'','Use with FRBRizeEditions. If ON, Koha will use PINES OISBN web service in the Editions tab on the detail pages.','YesNo')");
728  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
729        VALUES ('ThingISBN',0,'','Use with FRBRizeEditions. If ON, Koha will use the ThingISBN web service in the Editions tab on the detail pages.','YesNo')");
730     print "Upgrade to $DBversion done (adding services throttle table and sysprefs for xISBN)\n";
731     SetVersion ($DBversion);
732 }
733
734 $DBversion = "3.00.00.031";
735 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
736
737 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryStemming',1,'If ON, enables query stemming',NULL,'YesNo')");
738 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryFuzzy',1,'If ON, enables fuzzy option for searches',NULL,'YesNo')");
739 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryWeightFields',1,'If ON, enables field weighting',NULL,'YesNo')");
740 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('WebBasedSelfCheck',0,'If ON, enables the web-based self-check system',NULL,'YesNo')");
741 $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')");
742 $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')");
743 $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')");
744 $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')");
745 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('defaultSortOrder',NULL,'Specify the default sort order','asc|dsc|az|za','Choice')");
746 $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')");
747 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACdefaultSortOrder',NULL,'Specify the default sort order','asc|dsc|za|az','Choice')");
748 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('staffClientBaseURL','','Specify the base URL of the staff client',NULL,'free')");
749 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('minPasswordLength',3,'Specify the minimum length of a patron/staff password',NULL,'free')");
750 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('noItemTypeImages',0,'If ON, disables item-type images',NULL,'YesNo')");
751 $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')");
752 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('holdCancelLength','','Specify how many days before a hold is canceled',NULL,'free')");
753 $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')");
754 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('finesMode','test','Choose the fines mode, test or production','test|production','Choice')");
755 $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')");
756 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('itemBarcodeInputFilter','','If set, allows specification of a item barcode input filter','cuecat','Choice')");
757 $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')");
758 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('URLLinkText','','Text to display as the link anchor in the OPAC',NULL,'free')");
759 $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')");
760 $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')");
761 $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')");
762 $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')");
763 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACUserCSS',0,'Add CSS to be included in the OPAC',NULL,'free')");
764
765     print "Upgrade to $DBversion done (adding additional system preference)\n";
766     SetVersion ($DBversion);
767 }
768
769 $DBversion = "3.00.00.032";
770 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
771     $dbh->do("UPDATE `marc_subfield_structure` SET `kohafield` = 'items.wthdrawn' WHERE `kohafield` = 'items.withdrawn'");
772     print "Upgrade to $DBversion done (fixed MARC framework references to items.withdrawn)\n";
773     SetVersion ($DBversion);
774 }
775
776 $DBversion = "3.00.00.033";
777 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
778     $dbh->do("INSERT INTO `userflags` VALUES(17,'staffaccess','Modify login / permissions for staff users',0)");
779     print "Upgrade to $DBversion done (Adding permissions flag for staff member access modification.  )\n";
780     SetVersion ($DBversion);
781 }
782
783 $DBversion = "3.00.00.034";
784 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
785     $dbh->do("ALTER TABLE `virtualshelves` ADD COLUMN `sortfield` VARCHAR(16) ");
786     print "Upgrade to $DBversion done (Adding sortfield for Virtual Shelves.  )\n";
787     SetVersion ($DBversion);
788 }
789
790 $DBversion = "3.00.00.035";
791 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
792     $dbh->do("UPDATE marc_subfield_structure
793               SET authorised_value = 'cn_source'
794               WHERE kohafield IN ('items.cn_source', 'biblioitems.cn_source')
795               AND (authorised_value is NULL OR authorised_value = '')");
796     print "Upgrade to $DBversion done (MARC frameworks: make classification source a drop-down)\n";
797     SetVersion ($DBversion);
798 }
799
800 $DBversion = "3.00.00.036";
801 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
802     $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');");
803     print "Upgrade to $DBversion done (OPACItemsResultsDisplay systempreference added)\n";
804     SetVersion ($DBversion);
805 }
806
807 $DBversion = "3.00.00.037";
808 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
809     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactfirstname` varchar(255)");
810     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactsurname` varchar(255)");
811     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress1` varchar(255)");
812     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress2` varchar(255)");
813     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress3` varchar(255)");
814     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactzipcode` varchar(50)");
815     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactphone` varchar(50)");
816     print "Upgrade to $DBversion done (Adding Alternative Contact Person information to borrowers table)\n";
817     SetVersion ($DBversion);
818 }
819
820 $DBversion = "3.00.00.038";
821 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
822     $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'");
823     $dbh->do("DELETE FROM `systempreferences` WHERE variable='hideBiblioNumber'");
824     print "Upgrade to $DBversion done ('alter finesMode systempreference, remove superfluous syspref.')\n";
825     SetVersion ($DBversion);
826 }
827
828 $DBversion = "3.00.00.039";
829 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
830     $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')");
831     $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')");
832     $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')");
833     # $dbh->do("DELETE FROM `systempreferences` WHERE variable='HomeOrHoldingBranch'"); # Bug #2752
834     print "Upgrade to $DBversion done ('add circ sysprefs CircControl, finesCalendar, and uppercasesurnames, and delete HomeOrHoldingBranch.')\n";
835     SetVersion ($DBversion);
836 }
837
838 $DBversion = "3.00.00.040";
839 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
840         $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')");
841         $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')");
842         print "Upgrade to $DBversion done ('add circ sysprefs todaysIssuesDefaultSortOrder and previousIssuesDefaultSortOrder.')\n";
843     SetVersion ($DBversion);
844 }
845
846
847 $DBversion = "3.00.00.041";
848 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
849     # Strictly speaking it is not necessary to explicitly change
850     # NULL values to 0, because the ALTER TABLE statement will do that.
851     # However, setting them first avoids a warning.
852     $dbh->do("UPDATE items SET notforloan = 0 WHERE notforloan IS NULL");
853     $dbh->do("UPDATE items SET damaged = 0 WHERE damaged IS NULL");
854     $dbh->do("UPDATE items SET itemlost = 0 WHERE itemlost IS NULL");
855     $dbh->do("UPDATE items SET wthdrawn = 0 WHERE wthdrawn IS NULL");
856     $dbh->do("ALTER TABLE items
857                 MODIFY notforloan tinyint(1) NOT NULL default 0,
858                 MODIFY damaged    tinyint(1) NOT NULL default 0,
859                 MODIFY itemlost   tinyint(1) NOT NULL default 0,
860                 MODIFY wthdrawn   tinyint(1) NOT NULL default 0");
861     $dbh->do("UPDATE deleteditems SET notforloan = 0 WHERE notforloan IS NULL");
862     $dbh->do("UPDATE deleteditems SET damaged = 0 WHERE damaged IS NULL");
863     $dbh->do("UPDATE deleteditems SET itemlost = 0 WHERE itemlost IS NULL");
864     $dbh->do("UPDATE deleteditems SET wthdrawn = 0 WHERE wthdrawn IS NULL");
865     $dbh->do("ALTER TABLE deleteditems
866                 MODIFY notforloan tinyint(1) NOT NULL default 0,
867                 MODIFY damaged    tinyint(1) NOT NULL default 0,
868                 MODIFY itemlost   tinyint(1) NOT NULL default 0,
869                 MODIFY wthdrawn   tinyint(1) NOT NULL default 0");
870         print "Upgrade to $DBversion done (disallow NULL in several item status columns)\n";
871     SetVersion ($DBversion);
872 }
873
874 $DBversion = "3.00.00.04";
875 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
876     $dbh->do("ALTER TABLE aqbooksellers CHANGE name name mediumtext NOT NULL");
877         print "Upgrade to $DBversion done (disallow NULL in aqbooksellers.name; part of fix for bug 1251)\n";
878     SetVersion ($DBversion);
879 }
880
881 $DBversion = "3.00.00.043";
882 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
883     $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");
884         print "Upgrade to $DBversion done (currency table: add symbol and timestamp columns)\n";
885     SetVersion ($DBversion);
886 }
887
888 $DBversion = "3.00.00.044";
889 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
890     $dbh->do("ALTER TABLE deletedborrowers
891   ADD `altcontactfirstname` varchar(255) default NULL,
892   ADD `altcontactsurname` varchar(255) default NULL,
893   ADD `altcontactaddress1` varchar(255) default NULL,
894   ADD `altcontactaddress2` varchar(255) default NULL,
895   ADD `altcontactaddress3` varchar(255) default NULL,
896   ADD `altcontactzipcode` varchar(50) default NULL,
897   ADD `altcontactphone` varchar(50) default NULL
898   ");
899   $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES
900 ('OPACBaseURL',NULL,'Specify the Base URL of the OPAC, e.g., opac.mylibrary.com, the http:// will be added automatically by Koha.',NULL,'Free'),
901 ('language','en','Set the default language in the staff client.',NULL,'Languages'),
902 ('QueryAutoTruncate',1,'If ON, query truncation is enabled by default',NULL,'YesNo'),
903 ('QueryRemoveStopwords',0,'If ON, stopwords listed in the Administration area will be removed from queries',NULL,'YesNo')
904   ");
905         print "Upgrade to $DBversion done (syncing deletedborrowers table with borrowers table)\n";
906     SetVersion ($DBversion);
907 }
908
909 #-- http://www.w3.org/International/articles/language-tags/
910
911 #-- RFC4646
912 $DBversion = "3.00.00.045";
913 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
914     $dbh->do("
915 CREATE TABLE language_subtag_registry (
916         subtag varchar(25),
917         type varchar(25), -- language-script-region-variant-extension-privateuse
918         description varchar(25), -- only one of the possible descriptions for ease of reference, see language_descriptions for the complete list
919         added date,
920         KEY `subtag` (`subtag`)
921 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
922
923 #-- TODO: add suppress_scripts
924 #-- this maps three letter codes defined in iso639.2 back to their
925 #-- two letter equivilents in rfc4646 (LOC maintains iso639+)
926  $dbh->do("CREATE TABLE language_rfc4646_to_iso639 (
927         rfc4646_subtag varchar(25),
928         iso639_2_code varchar(25),
929         KEY `rfc4646_subtag` (`rfc4646_subtag`)
930 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
931
932  $dbh->do("CREATE TABLE language_descriptions (
933         subtag varchar(25),
934         type varchar(25),
935         lang varchar(25),
936         description varchar(255),
937         KEY `lang` (`lang`)
938 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
939
940 #-- bi-directional support, keyed by script subcode
941  $dbh->do("CREATE TABLE language_script_bidi (
942         rfc4646_subtag varchar(25), -- script subtag, Arab, Hebr, etc.
943         bidi varchar(3), -- rtl ltr
944         KEY `rfc4646_subtag` (`rfc4646_subtag`)
945 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
946
947 #-- BIDI Stuff, Arabic and Hebrew
948  $dbh->do("INSERT INTO language_script_bidi(rfc4646_subtag,bidi)
949 VALUES( 'Arab', 'rtl')");
950  $dbh->do("INSERT INTO language_script_bidi(rfc4646_subtag,bidi)
951 VALUES( 'Hebr', 'rtl')");
952
953 #-- TODO: need to map language subtags to script subtags for detection
954 #-- of bidi when script is not specified (like ar, he)
955  $dbh->do("CREATE TABLE language_script_mapping (
956         language_subtag varchar(25),
957         script_subtag varchar(25),
958         KEY `language_subtag` (`language_subtag`)
959 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
960
961 #-- Default mappings between script and language subcodes
962  $dbh->do("INSERT INTO language_script_mapping(language_subtag,script_subtag)
963 VALUES( 'ar', 'Arab')");
964  $dbh->do("INSERT INTO language_script_mapping(language_subtag,script_subtag)
965 VALUES( 'he', 'Hebr')");
966
967         print "Upgrade to $DBversion done (adding language subtag registry and basic BiDi support NOTE: You should import the subtag registry SQL)\n";
968     SetVersion ($DBversion);
969 }
970
971 $DBversion = "3.00.00.046";
972 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
973     $dbh->do("ALTER TABLE `subscription` CHANGE `numberlength` `numberlength` int(11) default '0' ,
974                  CHANGE `weeklength` `weeklength` int(11) default '0'");
975     $dbh->do("CREATE TABLE `serialitems` (`serialid` int(11) NOT NULL, `itemnumber` int(11) NOT NULL, UNIQUE KEY `serialididx` (`serialid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
976     $dbh->do("INSERT INTO `serialitems` SELECT `serialid`,`itemnumber` from serial where NOT ISNULL(itemnumber) && itemnumber <> '' && itemnumber NOT LIKE '%,%'");
977         print "Upgrade to $DBversion done (Add serialitems table to link serial issues to items. )\n";
978     SetVersion ($DBversion);
979 }
980
981 $DBversion = "3.00.00.047";
982 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
983     $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');");
984         print "Upgrade to $DBversion done ( Added OpacRenewalAllowed syspref )\n";
985     SetVersion ($DBversion);
986 }
987
988 $DBversion = "3.00.00.048";
989 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
990     $dbh->do("ALTER TABLE `items` ADD `more_subfields_xml` longtext default NULL AFTER `itype`");
991         print "Upgrade to $DBversion done (added items.more_subfields_xml)\n";
992     SetVersion ($DBversion);
993 }
994
995 $DBversion = "3.00.00.049";
996 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
997         $dbh->do("ALTER TABLE `z3950servers` ADD `encoding` text default NULL AFTER type ");
998         print "Upgrade to $DBversion done ( Added encoding field to z3950servers table )\n";
999     SetVersion ($DBversion);
1000 }
1001
1002 $DBversion = "3.00.00.050";
1003 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1004     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacHighlightedWords','0','If Set, query matched terms are highlighted in OPAC',NULL,'YesNo');");
1005         print "Upgrade to $DBversion done ( Added OpacHighlightedWords syspref )\n";
1006     SetVersion ($DBversion);
1007 }
1008
1009 $DBversion = "3.00.00.051";
1010 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1011     $dbh->do("UPDATE systempreferences SET explanation = 'Define the current theme for the OPAC interface.' WHERE variable = 'opacthemes';");
1012         print "Upgrade to $DBversion done ( Corrected opacthemes explanation. )\n";
1013     SetVersion ($DBversion);
1014 }
1015
1016 $DBversion = "3.00.00.052";
1017 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1018     $dbh->do("ALTER TABLE `deleteditems` ADD `more_subfields_xml` LONGTEXT DEFAULT NULL AFTER `itype`");
1019         print "Upgrade to $DBversion done ( Adding missing column to deleteditems table. )\n";
1020     SetVersion ($DBversion);
1021 }
1022
1023 $DBversion = "3.00.00.053";
1024 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1025     $dbh->do("CREATE TABLE `printers_profile` (
1026             `prof_id` int(4) NOT NULL auto_increment,
1027             `printername` varchar(40) NOT NULL,
1028             `tmpl_id` int(4) NOT NULL,
1029             `paper_bin` varchar(20) NOT NULL,
1030             `offset_horz` float default NULL,
1031             `offset_vert` float default NULL,
1032             `creep_horz` float default NULL,
1033             `creep_vert` float default NULL,
1034             `unit` char(20) NOT NULL default 'POINT',
1035             PRIMARY KEY  (`prof_id`),
1036             UNIQUE KEY `printername` (`printername`,`tmpl_id`,`paper_bin`),
1037             CONSTRAINT `printers_profile_pnfk_1` FOREIGN KEY (`tmpl_id`) REFERENCES `labels_templates` (`tmpl_id`) ON DELETE CASCADE ON UPDATE CASCADE
1038             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1039     $dbh->do("CREATE TABLE `labels_profile` (
1040             `tmpl_id` int(4) NOT NULL,
1041             `prof_id` int(4) NOT NULL,
1042             UNIQUE KEY `tmpl_id` (`tmpl_id`),
1043             UNIQUE KEY `prof_id` (`prof_id`)
1044             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1045     print "Upgrade to $DBversion done ( Printer Profile tables added )\n";
1046     SetVersion ($DBversion);
1047 }
1048
1049 $DBversion = "3.00.00.054";
1050 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1051     $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';");
1052         print "Upgrade to $DBversion done ( Added another barcode autogeneration sequence to barcode.pl. )\n";
1053     SetVersion ($DBversion);
1054 }
1055
1056 $DBversion = "3.00.00.055";
1057 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1058     $dbh->do("ALTER TABLE `zebraqueue` ADD KEY `zebraqueue_lookup` (`server`, `biblio_auth_number`, `operation`, `done`)");
1059         print "Upgrade to $DBversion done ( Added index on zebraqueue. )\n";
1060     SetVersion ($DBversion);
1061 }
1062 $DBversion = "3.00.00.056";
1063 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1064     if (C4::Context->preference("marcflavour") eq 'UNIMARC') {
1065         $dbh->do("INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`, `tab`, `authorised_value` , `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`) VALUES ('995', 'v', 'Note sur le N° de périodique','Note sur le N° de périodique', 0, 0, 'items.enumchron', 10, '', '', '', 0, 0, '', '', '', NULL) ");
1066     } else {
1067         $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) ");
1068     }
1069     $dbh->do("ALTER TABLE `items` ADD `enumchron` VARCHAR(80) DEFAULT NULL;");
1070     print "Upgrade to $DBversion done ( Added item.enumchron column, and framework map to 952h )\n";
1071     SetVersion ($DBversion);
1072 }
1073
1074 $DBversion = "3.00.00.057";
1075 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1076     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH','0','if ON, OAI-PMH server is enabled',NULL,'YesNo');");
1077     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH:archiveID','KOHA-OAI-TEST','OAI-PMH archive identification',NULL,'Free');");
1078     $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');");
1079     $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');");
1080     $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');");
1081     SetVersion ($DBversion);
1082 }
1083
1084 $DBversion = "3.00.00.058";
1085 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1086     $dbh->do("ALTER TABLE `opac_news`
1087                 CHANGE `lang` `lang` VARCHAR( 25 )
1088                 CHARACTER SET utf8
1089                 COLLATE utf8_general_ci
1090                 NOT NULL default ''");
1091         print "Upgrade to $DBversion done ( lang field in opac_news made longer )\n";
1092     SetVersion ($DBversion);
1093 }
1094
1095 $DBversion = "3.00.00.059";
1096 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1097
1098     $dbh->do("CREATE TABLE IF NOT EXISTS `labels_templates` (
1099             `tmpl_id` int(4) NOT NULL auto_increment,
1100             `tmpl_code` char(100)  default '',
1101             `tmpl_desc` char(100) default '',
1102             `page_width` float default '0',
1103             `page_height` float default '0',
1104             `label_width` float default '0',
1105             `label_height` float default '0',
1106             `topmargin` float default '0',
1107             `leftmargin` float default '0',
1108             `cols` int(2) default '0',
1109             `rows` int(2) default '0',
1110             `colgap` float default '0',
1111             `rowgap` float default '0',
1112             `active` int(1) default NULL,
1113             `units` char(20)  default 'PX',
1114             `fontsize` int(4) NOT NULL default '3',
1115             PRIMARY KEY  (`tmpl_id`)
1116             ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1117     $dbh->do("CREATE TABLE  IF NOT EXISTS `printers_profile` (
1118             `prof_id` int(4) NOT NULL auto_increment,
1119             `printername` varchar(40) NOT NULL,
1120             `tmpl_id` int(4) NOT NULL,
1121             `paper_bin` varchar(20) NOT NULL,
1122             `offset_horz` float default NULL,
1123             `offset_vert` float default NULL,
1124             `creep_horz` float default NULL,
1125             `creep_vert` float default NULL,
1126             `unit` char(20) NOT NULL default 'POINT',
1127             PRIMARY KEY  (`prof_id`),
1128             UNIQUE KEY `printername` (`printername`,`tmpl_id`,`paper_bin`),
1129             CONSTRAINT `printers_profile_pnfk_1` FOREIGN KEY (`tmpl_id`) REFERENCES `labels_templates` (`tmpl_id`) ON DELETE CASCADE ON UPDATE CASCADE
1130             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1131     print "Upgrade to $DBversion done ( Added labels_templates table if it did not exist. )\n";
1132     SetVersion ($DBversion);
1133 }
1134
1135 $DBversion = "3.00.00.060";
1136 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1137     $dbh->do("CREATE TABLE IF NOT EXISTS `patronimage` (
1138             `cardnumber` varchar(16) NOT NULL,
1139             `mimetype` varchar(15) NOT NULL,
1140             `imagefile` mediumblob NOT NULL,
1141             PRIMARY KEY  (`cardnumber`),
1142             CONSTRAINT `patronimage_fk1` FOREIGN KEY (`cardnumber`) REFERENCES `borrowers` (`cardnumber`) ON DELETE CASCADE ON UPDATE CASCADE
1143             ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1144         print "Upgrade to $DBversion done ( Added patronimage table. )\n";
1145     SetVersion ($DBversion);
1146 }
1147
1148 $DBversion = "3.00.00.061";
1149 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1150     $dbh->do("ALTER TABLE labels_templates ADD COLUMN font char(10) NOT NULL DEFAULT 'TR';");
1151         print "Upgrade to $DBversion done ( Added font column to labels_templates )\n";
1152     SetVersion ($DBversion);
1153 }
1154
1155 $DBversion = "3.00.00.062";
1156 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1157     $dbh->do("CREATE TABLE `old_issues` (
1158                 `borrowernumber` int(11) default NULL,
1159                 `itemnumber` int(11) default NULL,
1160                 `date_due` date default NULL,
1161                 `branchcode` varchar(10) default NULL,
1162                 `issuingbranch` varchar(18) default NULL,
1163                 `returndate` date default NULL,
1164                 `lastreneweddate` date default NULL,
1165                 `return` varchar(4) default NULL,
1166                 `renewals` tinyint(4) default NULL,
1167                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1168                 `issuedate` date default NULL,
1169                 KEY `old_issuesborridx` (`borrowernumber`),
1170                 KEY `old_issuesitemidx` (`itemnumber`),
1171                 KEY `old_bordate` (`borrowernumber`,`timestamp`),
1172                 CONSTRAINT `old_issues_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1173                     ON DELETE SET NULL ON UPDATE SET NULL,
1174                 CONSTRAINT `old_issues_ibfk_2` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`)
1175                     ON DELETE SET NULL ON UPDATE SET NULL
1176                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1177     $dbh->do("CREATE TABLE `old_reserves` (
1178                 `borrowernumber` int(11) default NULL,
1179                 `reservedate` date default NULL,
1180                 `biblionumber` int(11) default NULL,
1181                 `constrainttype` varchar(1) default NULL,
1182                 `branchcode` varchar(10) default NULL,
1183                 `notificationdate` date default NULL,
1184                 `reminderdate` date default NULL,
1185                 `cancellationdate` date default NULL,
1186                 `reservenotes` mediumtext,
1187                 `priority` smallint(6) default NULL,
1188                 `found` varchar(1) default NULL,
1189                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1190                 `itemnumber` int(11) default NULL,
1191                 `waitingdate` date default NULL,
1192                 KEY `old_reserves_borrowernumber` (`borrowernumber`),
1193                 KEY `old_reserves_biblionumber` (`biblionumber`),
1194                 KEY `old_reserves_itemnumber` (`itemnumber`),
1195                 KEY `old_reserves_branchcode` (`branchcode`),
1196                 CONSTRAINT `old_reserves_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1197                     ON DELETE SET NULL ON UPDATE SET NULL,
1198                 CONSTRAINT `old_reserves_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`)
1199                     ON DELETE SET NULL ON UPDATE SET NULL,
1200                 CONSTRAINT `old_reserves_ibfk_3` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`)
1201                     ON DELETE SET NULL ON UPDATE SET NULL
1202                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1203
1204     # move closed transactions to old_* tables
1205     $dbh->do("INSERT INTO old_issues SELECT * FROM issues WHERE returndate IS NOT NULL");
1206     $dbh->do("DELETE FROM issues WHERE returndate IS NOT NULL");
1207     $dbh->do("INSERT INTO old_reserves SELECT * FROM reserves WHERE cancellationdate IS NOT NULL OR found = 'F'");
1208     $dbh->do("DELETE FROM reserves WHERE cancellationdate IS NOT NULL OR found = 'F'");
1209
1210         print "Upgrade to $DBversion done ( Added old_issues and old_reserves tables )\n";
1211     SetVersion ($DBversion);
1212 }
1213
1214 $DBversion = "3.00.00.063";
1215 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1216     $dbh->do("ALTER TABLE deleteditems
1217                 CHANGE COLUMN booksellerid booksellerid MEDIUMTEXT DEFAULT NULL,
1218                 ADD COLUMN enumchron VARCHAR(80) DEFAULT NULL AFTER more_subfields_xml,
1219                 ADD COLUMN copynumber SMALLINT(6) DEFAULT NULL AFTER enumchron;");
1220     $dbh->do("ALTER TABLE items
1221                 CHANGE COLUMN booksellerid booksellerid MEDIUMTEXT,
1222                 ADD COLUMN copynumber SMALLINT(6) DEFAULT NULL AFTER enumchron;");
1223         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";
1224     SetVersion ($DBversion);
1225 }
1226
1227 $DBversion = "3.00.00.064";
1228 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1229     $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');");
1230     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AWSAccessKeyID','','See:  http://aws.amazon.com','','free');");
1231     $dbh->do("DELETE FROM `systempreferences` WHERE variable='AmazonDevKey';");
1232     $dbh->do("DELETE FROM `systempreferences` WHERE variable='XISBNAmazonSimilarItems';");
1233     $dbh->do("DELETE FROM `systempreferences` WHERE variable='OPACXISBNAmazonSimilarItems';");
1234     print "Upgrade to $DBversion done (IMPORTANT: Upgrading to Amazon.com Associates Web Service 4.0 ) \n";
1235     SetVersion ($DBversion);
1236 }
1237
1238 $DBversion = "3.00.00.065";
1239 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1240     $dbh->do("CREATE TABLE `patroncards` (
1241                 `cardid` int(11) NOT NULL auto_increment,
1242                 `batch_id` varchar(10) NOT NULL default '1',
1243                 `borrowernumber` int(11) NOT NULL,
1244                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1245                 PRIMARY KEY  (`cardid`),
1246                 KEY `patroncards_ibfk_1` (`borrowernumber`),
1247                 CONSTRAINT `patroncards_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE
1248                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1249     print "Upgrade to $DBversion done (Adding patroncards table for patroncards generation feature. ) \n";
1250     SetVersion ($DBversion);
1251 }
1252
1253 $DBversion = "3.00.00.066";
1254 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1255     $dbh->do("ALTER TABLE `virtualshelfcontents` MODIFY `dateadded` timestamp NOT NULL
1256 DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP;
1257 ");
1258     print "Upgrade to $DBversion done (fix for bug 1873: virtualshelfcontents dateadded column empty. ) \n";
1259     SetVersion ($DBversion);
1260 }
1261
1262 $DBversion = "3.00.00.067";
1263 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1264     $dbh->do("UPDATE systempreferences SET explanation = 'Enable patron images for the Staff Client', type = 'YesNo' WHERE variable = 'patronimages'");
1265     print "Upgrade to $DBversion done (Updating patronimages syspref to reflect current kohastructure.sql. ) \n";
1266     SetVersion ($DBversion);
1267 }
1268
1269 $DBversion = "3.00.00.068";
1270 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1271     $dbh->do("CREATE TABLE `permissions` (
1272                 `module_bit` int(11) NOT NULL DEFAULT 0,
1273                 `code` varchar(30) DEFAULT NULL,
1274                 `description` varchar(255) DEFAULT NULL,
1275                 PRIMARY KEY  (`module_bit`, `code`),
1276                 CONSTRAINT `permissions_ibfk_1` FOREIGN KEY (`module_bit`) REFERENCES `userflags` (`bit`)
1277                     ON DELETE CASCADE ON UPDATE CASCADE
1278               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1279     $dbh->do("CREATE TABLE `user_permissions` (
1280                 `borrowernumber` int(11) NOT NULL DEFAULT 0,
1281                 `module_bit` int(11) NOT NULL DEFAULT 0,
1282                 `code` varchar(30) DEFAULT NULL,
1283                 CONSTRAINT `user_permissions_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1284                     ON DELETE CASCADE ON UPDATE CASCADE,
1285                 CONSTRAINT `user_permissions_ibfk_2` FOREIGN KEY (`module_bit`, `code`)
1286                     REFERENCES `permissions` (`module_bit`, `code`)
1287                     ON DELETE CASCADE ON UPDATE CASCADE
1288               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1289
1290     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
1291     (13, 'edit_news', 'Write news for the OPAC and staff interfaces'),
1292     (13, 'label_creator', 'Create printable labels and barcodes from catalog and patron data'),
1293     (13, 'edit_calendar', 'Define days when the library is closed'),
1294     (13, 'moderate_comments', 'Moderate patron comments'),
1295     (13, 'edit_notices', 'Define notices'),
1296     (13, 'edit_notice_status_triggers', 'Set notice/status triggers for overdue items'),
1297     (13, 'view_system_logs', 'Browse the system logs'),
1298     (13, 'inventory', 'Perform inventory (stocktaking) of your catalogue'),
1299     (13, 'stage_marc_import', 'Stage MARC records into the reservoir'),
1300     (13, 'manage_staged_marc', 'Managed staged MARC records, including completing and reversing imports'),
1301     (13, 'export_catalog', 'Export bibliographic and holdings data'),
1302     (13, 'import_patrons', 'Import patron data'),
1303     (13, 'delete_anonymize_patrons', 'Delete old borrowers and anonymize circulation history (deletes borrower reading history)'),
1304     (13, 'batch_upload_patron_images', 'Upload patron images in batch or one at a time'),
1305     (13, 'schedule_tasks', 'Schedule tasks to run')");
1306
1307     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('GranularPermissions','0','Use detailed staff user permissions',NULL,'YesNo')");
1308
1309     print "Upgrade to $DBversion done (adding permissions and user_permissions tables and GranularPermissions syspref) \n";
1310     SetVersion ($DBversion);
1311 }
1312 $DBversion = "3.00.00.069";
1313 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1314     $dbh->do("ALTER TABLE labels_conf CHANGE COLUMN class classification int(1) DEFAULT NULL;");
1315         print "Upgrade to $DBversion done ( Correcting columname in labels_conf )\n";
1316     SetVersion ($DBversion);
1317 }
1318
1319 $DBversion = "3.00.00.070";
1320 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1321     $sth = $dbh->prepare("SELECT value FROM systempreferences WHERE variable='yuipath'");
1322     $sth->execute;
1323     my ($value) = $sth->fetchrow;
1324     $value =~ s/2.3.1/2.5.1/;
1325     $dbh->do("UPDATE systempreferences SET value='$value' WHERE variable='yuipath';");
1326         print "Update yuipath syspref to 2.5.1 if necessary\n";
1327     SetVersion ($DBversion);
1328 }
1329
1330 $DBversion = "3.00.00.071";
1331 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1332     $dbh->do(" ALTER TABLE `subscription` ADD `serialsadditems` TINYINT( 1 ) NOT NULL DEFAULT '0';");
1333     # fill the new field with the previous systempreference value, then drop the syspref
1334     my $sth = $dbh->prepare("SELECT value FROM systempreferences WHERE variable='serialsadditems'");
1335     $sth->execute;
1336     my ($serialsadditems) = $sth->fetchrow();
1337     $dbh->do("UPDATE subscription SET serialsadditems=$serialsadditems");
1338     $dbh->do("DELETE FROM systempreferences WHERE variable='serialsadditems'");
1339     print "Upgrade to $DBversion done ( moving serialsadditems from syspref to subscription )\n";
1340     SetVersion ($DBversion);
1341 }
1342
1343 $DBversion = "3.00.00.072";
1344 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1345     $dbh->do("ALTER TABLE labels_conf ADD COLUMN formatstring mediumtext DEFAULT NULL AFTER printingtype");
1346         print "Upgrade to $DBversion done ( Adding format string to labels generator. )\n";
1347     SetVersion ($DBversion);
1348 }
1349
1350 $DBversion = "3.00.00.073";
1351 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1352         $dbh->do("DROP TABLE IF EXISTS `tags_all`;");
1353         $dbh->do(q#
1354         CREATE TABLE `tags_all` (
1355           `tag_id`         int(11) NOT NULL auto_increment,
1356           `borrowernumber` int(11) NOT NULL,
1357           `biblionumber`   int(11) NOT NULL,
1358           `term`      varchar(255) NOT NULL,
1359           `language`       int(4) default NULL,
1360           `date_created` datetime  NOT NULL,
1361           PRIMARY KEY  (`tag_id`),
1362           KEY `tags_borrowers_fk_1` (`borrowernumber`),
1363           KEY `tags_biblionumber_fk_1` (`biblionumber`),
1364           CONSTRAINT `tags_borrowers_fk_1` FOREIGN KEY (`borrowernumber`)
1365                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1366           CONSTRAINT `tags_biblionumber_fk_1` FOREIGN KEY (`biblionumber`)
1367                 REFERENCES `biblio`     (`biblionumber`)  ON DELETE CASCADE ON UPDATE CASCADE
1368         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1369         #);
1370         $dbh->do("DROP TABLE IF EXISTS `tags_approval`;");
1371         $dbh->do(q#
1372         CREATE TABLE `tags_approval` (
1373           `term`   varchar(255) NOT NULL,
1374           `approved`     int(1) NOT NULL default '0',
1375           `date_approved` datetime       default NULL,
1376           `approved_by` int(11)          default NULL,
1377           `weight_total` int(9) NOT NULL default '1',
1378           PRIMARY KEY  (`term`),
1379           KEY `tags_approval_borrowers_fk_1` (`approved_by`),
1380           CONSTRAINT `tags_approval_borrowers_fk_1` FOREIGN KEY (`approved_by`)
1381                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE
1382         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1383         #);
1384         $dbh->do("DROP TABLE IF EXISTS `tags_index`;");
1385         $dbh->do(q#
1386         CREATE TABLE `tags_index` (
1387           `term`    varchar(255) NOT NULL,
1388           `biblionumber` int(11) NOT NULL,
1389           `weight`        int(9) NOT NULL default '1',
1390           PRIMARY KEY  (`term`,`biblionumber`),
1391           KEY `tags_index_biblionumber_fk_1` (`biblionumber`),
1392           CONSTRAINT `tags_index_term_fk_1` FOREIGN KEY (`term`)
1393                 REFERENCES `tags_approval` (`term`)  ON DELETE CASCADE ON UPDATE CASCADE,
1394           CONSTRAINT `tags_index_biblionumber_fk_1` FOREIGN KEY (`biblionumber`)
1395                 REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
1396         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1397         #);
1398         $dbh->do(q#
1399         INSERT INTO `systempreferences` VALUES
1400                 ('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=',''),
1401                 ('BakerTaylorEnabled','0','','Enable or disable all Baker & Taylor features.','YesNo'),
1402                 ('BakerTaylorPassword','','','Baker & Taylor Password for Content Cafe (external content)','Textarea'),
1403                 ('BakerTaylorUsername','','','Baker & Taylor Username for Content Cafe (external content)','Textarea'),
1404                 ('TagsEnabled','1','','Enables or disables all tagging features.  This is the main switch for tags.','YesNo'),
1405                 ('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.',''),
1406                 ('TagsInputOnDetail','1','','Allow users to input tags from the detail page.',         'YesNo'),
1407                 ('TagsInputOnList',  '0','','Allow users to input tags from the search results list.', 'YesNo'),
1408                 ('TagsModeration',  NULL,'','Require tags from patrons to be approved before becoming visible.','YesNo'),
1409                 ('TagsShowOnDetail','10','','Number of tags to display on detail page.  0 is off.',        'Integer'),
1410                 ('TagsShowOnList',   '6','','Number of tags to display on search results list.  0 is off.','Integer')
1411         #);
1412         print "Upgrade to $DBversion done (Baker/Taylor,Tags: sysprefs and tables (tags_all, tags_index, tags_approval)) \n";
1413         SetVersion ($DBversion);
1414 }
1415
1416 $DBversion = "3.00.00.074";
1417 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1418     $dbh->do( q(update itemtypes set imageurl = concat( 'npl/', imageurl )
1419                   where imageurl not like 'http%'
1420                     and imageurl is not NULL
1421                     and imageurl != '') );
1422     print "Upgrade to $DBversion done (updating imagetype.imageurls to reflect new icon locations.)\n";
1423     SetVersion ($DBversion);
1424 }
1425
1426 $DBversion = "3.00.00.075";
1427 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1428     $dbh->do( q(alter table authorised_values add imageurl varchar(200) default NULL) );
1429     print "Upgrade to $DBversion done (adding imageurl field to authorised_values table)\n";
1430     SetVersion ($DBversion);
1431 }
1432
1433 $DBversion = "3.00.00.076";
1434 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1435     $dbh->do("ALTER TABLE import_batches
1436               ADD COLUMN nomatch_action enum('create_new', 'ignore') NOT NULL default 'create_new' AFTER overlay_action");
1437     $dbh->do("ALTER TABLE import_batches
1438               ADD COLUMN item_action enum('always_add', 'add_only_for_matches', 'add_only_for_new', 'ignore')
1439                   NOT NULL default 'always_add' AFTER nomatch_action");
1440     $dbh->do("ALTER TABLE import_batches
1441               MODIFY overlay_action  enum('replace', 'create_new', 'use_template', 'ignore')
1442                   NOT NULL default 'create_new'");
1443     $dbh->do("ALTER TABLE import_records
1444               MODIFY status  enum('error', 'staged', 'imported', 'reverted', 'items_reverted',
1445                                   'ignored') NOT NULL default 'staged'");
1446     $dbh->do("ALTER TABLE import_items
1447               MODIFY status enum('error', 'staged', 'imported', 'reverted', 'ignored') NOT NULL default 'staged'");
1448
1449         print "Upgrade to $DBversion done (changes to import_batches and import_records)\n";
1450         SetVersion ($DBversion);
1451 }
1452
1453 $DBversion = "3.00.00.077";
1454 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1455     # drop these tables only if they exist and none of them are empty
1456     # these tables are not defined in the packaged 2.2.9, but since it is believed
1457     # that at least one library may be using them in a post-2.2.9 but pre-3.0 Koha,
1458     # some care is taken.
1459     my ($print_error) = $dbh->{PrintError};
1460     $dbh->{PrintError} = 0;
1461     my ($raise_error) = $dbh->{RaiseError};
1462     $dbh->{RaiseError} = 1;
1463
1464     my $count = 0;
1465     my $do_drop = 1;
1466     eval { $count = $dbh->do("SELECT 1 FROM categorytable"); };
1467     if ($count > 0) {
1468         $do_drop = 0;
1469     }
1470     eval { $count = $dbh->do("SELECT 1 FROM mediatypetable"); };
1471     if ($count > 0) {
1472         $do_drop = 0;
1473     }
1474     eval { $count = $dbh->do("SELECT 1 FROM subcategorytable"); };
1475     if ($count > 0) {
1476         $do_drop = 0;
1477     }
1478
1479     if ($do_drop) {
1480         $dbh->do("DROP TABLE IF EXISTS `categorytable`");
1481         $dbh->do("DROP TABLE IF EXISTS `mediatypetable`");
1482         $dbh->do("DROP TABLE IF EXISTS `subcategorytable`");
1483     }
1484
1485     $dbh->{PrintError} = $print_error;
1486     $dbh->{RaiseError} = $raise_error;
1487         print "Upgrade to $DBversion done (drop categorytable, subcategorytable, and mediatypetable)\n";
1488         SetVersion ($DBversion);
1489 }
1490
1491 $DBversion = "3.00.00.078";
1492 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1493     my ($print_error) = $dbh->{PrintError};
1494     $dbh->{PrintError} = 0;
1495
1496     unless ($dbh->do("SELECT 1 FROM browser")) {
1497         $dbh->{PrintError} = $print_error;
1498         $dbh->do("CREATE TABLE `browser` (
1499                     `level` int(11) NOT NULL,
1500                     `classification` varchar(20) NOT NULL,
1501                     `description` varchar(255) NOT NULL,
1502                     `number` bigint(20) NOT NULL,
1503                     `endnode` tinyint(4) NOT NULL
1504                   ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1505     }
1506     $dbh->{PrintError} = $print_error;
1507         print "Upgrade to $DBversion done (add browser table if not already present)\n";
1508         SetVersion ($DBversion);
1509 }
1510
1511 $DBversion = "3.00.00.079";
1512 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1513  my ($print_error) = $dbh->{PrintError};
1514     $dbh->{PrintError} = 0;
1515
1516     $dbh->do("INSERT INTO `systempreferences` (variable, value,options,type, explanation)VALUES
1517         ('AddPatronLists','categorycode','categorycode|category_type','Choice','Allow user to choose what list to pick up from when adding patrons')");
1518     print "Upgrade to $DBversion done (add browser table if not already present)\n";
1519         SetVersion ($DBversion);
1520 }
1521
1522 $DBversion = "3.00.00.080";
1523 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1524     $dbh->do("ALTER TABLE subscription CHANGE monthlength monthlength int(11) default '0'");
1525     $dbh->do("ALTER TABLE deleteditems MODIFY marc LONGBLOB AFTER copynumber");
1526     $dbh->do("ALTER TABLE aqbooksellers CHANGE name name mediumtext NOT NULL");
1527         print "Upgrade to $DBversion done (catch up on DB schema changes since alpha and beta)\n";
1528         SetVersion ($DBversion);
1529 }
1530
1531 $DBversion = "3.00.00.081";
1532 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1533     $dbh->do("CREATE TABLE `borrower_attribute_types` (
1534                 `code` varchar(10) NOT NULL,
1535                 `description` varchar(255) NOT NULL,
1536                 `repeatable` tinyint(1) NOT NULL default 0,
1537                 `unique_id` tinyint(1) NOT NULL default 0,
1538                 `opac_display` tinyint(1) NOT NULL default 0,
1539                 `password_allowed` tinyint(1) NOT NULL default 0,
1540                 `staff_searchable` tinyint(1) NOT NULL default 0,
1541                 `authorised_value_category` varchar(10) default NULL,
1542                 PRIMARY KEY  (`code`)
1543               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1544     $dbh->do("CREATE TABLE `borrower_attributes` (
1545                 `borrowernumber` int(11) NOT NULL,
1546                 `code` varchar(10) NOT NULL,
1547                 `attribute` varchar(30) default NULL,
1548                 `password` varchar(30) default NULL,
1549                 KEY `borrowernumber` (`borrowernumber`),
1550                 KEY `code_attribute` (`code`, `attribute`),
1551                 CONSTRAINT `borrower_attributes_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1552                     ON DELETE CASCADE ON UPDATE CASCADE,
1553                 CONSTRAINT `borrower_attributes_ibfk_2` FOREIGN KEY (`code`) REFERENCES `borrower_attribute_types` (`code`)
1554                     ON DELETE CASCADE ON UPDATE CASCADE
1555             ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1556     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('ExtendedPatronAttributes','0','Use extended patron IDs and attributes',NULL,'YesNo')");
1557     print "Upgrade to $DBversion done (added borrower_attributes and  borrower_attribute_types)\n";
1558  SetVersion ($DBversion);
1559 }
1560
1561 $DBversion = "3.00.00.082";
1562 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1563     $dbh->do( q(alter table accountlines add column lastincrement decimal(28,6) default NULL) );
1564     print "Upgrade to $DBversion done (adding lastincrement column to accountlines table)\n";
1565     SetVersion ($DBversion);
1566 }
1567
1568 $DBversion = "3.00.00.083";
1569 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1570     $dbh->do( qq(UPDATE systempreferences SET value='local' where variable='yuipath' and value like "%/intranet-tmpl/prog/%"));
1571     print "Upgrade to $DBversion done (Changing yuipath behaviour in managing a local value)\n";
1572     SetVersion ($DBversion);
1573 }
1574 $DBversion = "3.00.00.084";
1575     if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1576     $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')");
1577     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('GoogleJackets','0','if ON, displays jacket covers from Google Books API',NULL,'YesNo')");
1578     print "Upgrade to $DBversion done (add new sysprefs)\n";
1579     SetVersion ($DBversion);
1580 }
1581
1582 $DBversion = "3.00.00.085";
1583 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1584     if (C4::Context->preference("marcflavour") eq 'MARC21') {
1585         $dbh->do("UPDATE marc_subfield_structure SET tab = 0 WHERE tab =  9 AND tagfield = '037'");
1586         $dbh->do("UPDATE marc_subfield_structure SET tab = 1 WHERE tab =  6 AND tagfield in ('100', '110', '111', '130')");
1587         $dbh->do("UPDATE marc_subfield_structure SET tab = 2 WHERE tab =  6 AND tagfield in ('240', '243')");
1588         $dbh->do("UPDATE marc_subfield_structure SET tab = 4 WHERE tab =  6 AND tagfield in ('400', '410', '411', '440')");
1589         $dbh->do("UPDATE marc_subfield_structure SET tab = 5 WHERE tab =  9 AND tagfield = '584'");
1590         $dbh->do("UPDATE marc_subfield_structure SET tab = 7 WHERE tab = -6 AND tagfield = '760'");
1591     }
1592     print "Upgrade to $DBversion done (move editing tab of various MARC21 subfields)\n";
1593     SetVersion ($DBversion);
1594 }
1595
1596 $DBversion = "3.00.00.086";
1597 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1598         $dbh->do(
1599         "CREATE TABLE `tmp_holdsqueue` (
1600         `biblionumber` int(11) default NULL,
1601         `itemnumber` int(11) default NULL,
1602         `barcode` varchar(20) default NULL,
1603         `surname` mediumtext NOT NULL,
1604         `firstname` text,
1605         `phone` text,
1606         `borrowernumber` int(11) NOT NULL,
1607         `cardnumber` varchar(16) default NULL,
1608         `reservedate` date default NULL,
1609         `title` mediumtext,
1610         `itemcallnumber` varchar(30) default NULL,
1611         `holdingbranch` varchar(10) default NULL,
1612         `pickbranch` varchar(10) default NULL,
1613         `notes` text
1614         ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1615
1616         $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')");
1617         $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')");
1618
1619         print "Upgrade to $DBversion done (Table structure for table `tmp_holdsqueue`)\n";
1620         SetVersion ($DBversion);
1621 }
1622
1623 $DBversion = "3.00.00.087";
1624 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1625     $dbh->do("INSERT INTO `systempreferences` VALUES ('AutoEmailOpacUser','0','','Sends notification emails containing new account details to patrons - when account is created.','YesNo')" );
1626     $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')");
1627     print "Upgrade to $DBversion done (added 2 new 'AutoEmailOpacUser' sysprefs)\n";
1628     SetVersion ($DBversion);
1629 }
1630
1631 $DBversion = "3.00.00.088";
1632 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1633         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('OPACShelfBrowser','1','','Enable/disable Shelf Browser on item details page','YesNo')");
1634         $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')");
1635         $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')");
1636         $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')");
1637         print "Upgrade to $DBversion done (added 2 new 'AutoEmailOpacUser' sysprefs)\n";
1638     SetVersion ($DBversion);
1639 }
1640
1641 $DBversion = "3.00.00.089";
1642 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1643         $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')");
1644         print "Upgrade to $DBversion done (added new AdvancedSearchTypes syspref)\n";
1645     SetVersion ($DBversion);
1646 }
1647
1648 $DBversion = "3.00.00.090";
1649 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1650     $dbh->do("
1651         CREATE TABLE `branch_borrower_circ_rules` (
1652           `branchcode` VARCHAR(10) NOT NULL,
1653           `categorycode` VARCHAR(10) NOT NULL,
1654           `maxissueqty` int(4) default NULL,
1655           PRIMARY KEY (`categorycode`, `branchcode`),
1656           CONSTRAINT `branch_borrower_circ_rules_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
1657             ON DELETE CASCADE ON UPDATE CASCADE,
1658           CONSTRAINT `branch_borrower_circ_rules_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`)
1659             ON DELETE CASCADE ON UPDATE CASCADE
1660         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1661     ");
1662     $dbh->do("
1663         CREATE TABLE `default_borrower_circ_rules` (
1664           `categorycode` VARCHAR(10) NOT NULL,
1665           `maxissueqty` int(4) default NULL,
1666           PRIMARY KEY (`categorycode`),
1667           CONSTRAINT `borrower_borrower_circ_rules_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
1668             ON DELETE CASCADE ON UPDATE CASCADE
1669         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1670     ");
1671     $dbh->do("
1672         CREATE TABLE `default_branch_circ_rules` (
1673           `branchcode` VARCHAR(10) NOT NULL,
1674           `maxissueqty` int(4) default NULL,
1675           PRIMARY KEY (`branchcode`),
1676           CONSTRAINT `default_branch_circ_rules_ibfk_1` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`)
1677             ON DELETE CASCADE ON UPDATE CASCADE
1678         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1679     ");
1680     $dbh->do("
1681         CREATE TABLE `default_circ_rules` (
1682             `singleton` enum('singleton') NOT NULL default 'singleton',
1683             `maxissueqty` int(4) default NULL,
1684             PRIMARY KEY (`singleton`)
1685         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1686     ");
1687     print "Upgrade to $DBversion done (added several circ rules tables)\n";
1688     SetVersion ($DBversion);
1689 }
1690
1691
1692 $DBversion = "3.00.00.091";
1693 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1694     $dbh->do(<<'END_SQL');
1695 ALTER TABLE borrowers
1696 ADD `smsalertnumber` varchar(50) default NULL
1697 END_SQL
1698
1699     $dbh->do(<<'END_SQL');
1700 CREATE TABLE `message_attributes` (
1701   `message_attribute_id` int(11) NOT NULL auto_increment,
1702   `message_name` varchar(20) NOT NULL default '',
1703   `takes_days` tinyint(1) NOT NULL default '0',
1704   PRIMARY KEY  (`message_attribute_id`),
1705   UNIQUE KEY `message_name` (`message_name`)
1706 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1707 END_SQL
1708
1709     $dbh->do(<<'END_SQL');
1710 CREATE TABLE `message_transport_types` (
1711   `message_transport_type` varchar(20) NOT NULL,
1712   PRIMARY KEY  (`message_transport_type`)
1713 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1714 END_SQL
1715
1716     $dbh->do(<<'END_SQL');
1717 CREATE TABLE `message_transports` (
1718   `message_attribute_id` int(11) NOT NULL,
1719   `message_transport_type` varchar(20) NOT NULL,
1720   `is_digest` tinyint(1) NOT NULL default '0',
1721   `letter_module` varchar(20) NOT NULL default '',
1722   `letter_code` varchar(20) NOT NULL default '',
1723   PRIMARY KEY  (`message_attribute_id`,`message_transport_type`,`is_digest`),
1724   KEY `message_transport_type` (`message_transport_type`),
1725   KEY `letter_module` (`letter_module`,`letter_code`),
1726   CONSTRAINT `message_transports_ibfk_1` FOREIGN KEY (`message_attribute_id`) REFERENCES `message_attributes` (`message_attribute_id`) ON DELETE CASCADE ON UPDATE CASCADE,
1727   CONSTRAINT `message_transports_ibfk_2` FOREIGN KEY (`message_transport_type`) REFERENCES `message_transport_types` (`message_transport_type`) ON DELETE CASCADE ON UPDATE CASCADE,
1728   CONSTRAINT `message_transports_ibfk_3` FOREIGN KEY (`letter_module`, `letter_code`) REFERENCES `letter` (`module`, `code`) ON DELETE CASCADE ON UPDATE CASCADE
1729 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1730 END_SQL
1731
1732     $dbh->do(<<'END_SQL');
1733 CREATE TABLE `borrower_message_preferences` (
1734   `borrower_message_preference_id` int(11) NOT NULL auto_increment,
1735   `borrowernumber` int(11) NOT NULL default '0',
1736   `message_attribute_id` int(11) default '0',
1737   `days_in_advance` int(11) default '0',
1738   `wants_digets` tinyint(1) NOT NULL default '0',
1739   PRIMARY KEY  (`borrower_message_preference_id`),
1740   KEY `borrowernumber` (`borrowernumber`),
1741   KEY `message_attribute_id` (`message_attribute_id`),
1742   CONSTRAINT `borrower_message_preferences_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1743   CONSTRAINT `borrower_message_preferences_ibfk_2` FOREIGN KEY (`message_attribute_id`) REFERENCES `message_attributes` (`message_attribute_id`) ON DELETE CASCADE ON UPDATE CASCADE
1744 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1745 END_SQL
1746
1747     $dbh->do(<<'END_SQL');
1748 CREATE TABLE `borrower_message_transport_preferences` (
1749   `borrower_message_preference_id` int(11) NOT NULL default '0',
1750   `message_transport_type` varchar(20) NOT NULL default '0',
1751   PRIMARY KEY  (`borrower_message_preference_id`,`message_transport_type`),
1752   KEY `message_transport_type` (`message_transport_type`),
1753   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,
1754   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
1755 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1756 END_SQL
1757
1758     $dbh->do(<<'END_SQL');
1759 CREATE TABLE `message_queue` (
1760   `message_id` int(11) NOT NULL auto_increment,
1761   `borrowernumber` int(11) NOT NULL,
1762   `subject` text,
1763   `content` text,
1764   `message_transport_type` varchar(20) NOT NULL,
1765   `status` enum('sent','pending','failed','deleted') NOT NULL default 'pending',
1766   `time_queued` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1767   KEY `message_id` (`message_id`),
1768   KEY `borrowernumber` (`borrowernumber`),
1769   KEY `message_transport_type` (`message_transport_type`),
1770   CONSTRAINT `messageq_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1771   CONSTRAINT `messageq_ibfk_2` FOREIGN KEY (`message_transport_type`) REFERENCES `message_transport_types` (`message_transport_type`) ON DELETE RESTRICT ON UPDATE CASCADE
1772 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1773 END_SQL
1774
1775     $dbh->do(<<'END_SQL');
1776 INSERT INTO `systempreferences`
1777   (variable,value,explanation,options,type)
1778 VALUES
1779 ('EnhancedMessagingPreferences',0,'If ON, allows patrons to select to receive additional messages about items due or nearly due.','','YesNo')
1780 END_SQL
1781
1782     $dbh->do( <<'END_SQL');
1783 INSERT INTO `letter`
1784 (module, code, name, title, content)
1785 VALUES
1786 ('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>>'),
1787 ('circulation','DUEDGST','Item Due Reminder (Digest)','Item Due Reminder','You have <<count>> items due'),
1788 ('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>>'),
1789 ('circulation','PREDUEDGST','Advance Notice of Item Due (Digest)','Advance Notice of Item Due','You have <<count>> items due soon'),
1790 ('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.');
1791 END_SQL
1792
1793     my @sql_scripts = (
1794         'installer/data/mysql/en/mandatory/message_transport_types.sql',
1795         'installer/data/mysql/en/optional/sample_notices_message_attributes.sql',
1796         'installer/data/mysql/en/optional/sample_notices_message_transports.sql',
1797     );
1798
1799     my $installer = C4::Installer->new();
1800     foreach my $script ( @sql_scripts ) {
1801         my $full_path = $installer->get_file_path_from_name($script);
1802         my $error = $installer->load_sql($full_path);
1803         warn $error if $error;
1804     }
1805
1806     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";
1807     SetVersion ($DBversion);
1808 }
1809
1810 $DBversion = "3.00.00.092";
1811 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1812     $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')");
1813     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES('AllowHoldsOnDamagedItems', '1', '', 'Allow hold requests to be placed on damaged items', 'YesNo')");
1814         print "Upgrade to $DBversion done (added new AllowOnShelfHolds syspref)\n";
1815     SetVersion ($DBversion);
1816 }
1817
1818 $DBversion = "3.00.00.093";
1819 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1820     $dbh->do("ALTER TABLE `items` MODIFY COLUMN `copynumber` VARCHAR(32) DEFAULT NULL");
1821     $dbh->do("ALTER TABLE `deleteditems` MODIFY COLUMN `copynumber` VARCHAR(32) DEFAULT NULL");
1822         print "Upgrade to $DBversion done (Change data type of items.copynumber to allow free text)\n";
1823     SetVersion ($DBversion);
1824 }
1825
1826 $DBversion = "3.00.00.094";
1827 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1828     $dbh->do("ALTER TABLE `marc_subfield_structure` MODIFY `tagsubfield` VARCHAR(1) NOT NULL DEFAULT '' COLLATE utf8_bin");
1829         print "Upgrade to $DBversion done (Change Collation of marc_subfield_structure to allow mixed case in subfield labels.)\n";
1830     SetVersion ($DBversion);
1831 }
1832
1833 $DBversion = "3.00.00.095";
1834 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1835     if (C4::Context->preference("marcflavour") eq 'MARC21') {
1836         $dbh->do("UPDATE marc_subfield_structure SET authtypecode = 'MEETI_NAME' WHERE authtypecode = 'Meeting Name'");
1837         $dbh->do("UPDATE marc_subfield_structure SET authtypecode = 'CORPO_NAME' WHERE authtypecode = 'CORP0_NAME'");
1838     }
1839         print "Upgrade to $DBversion done (fix invalid authority types in MARC21 frameworks [bug 2254])\n";
1840     SetVersion ($DBversion);
1841 }
1842
1843 $DBversion = "3.00.00.096";
1844 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1845     $sth = $dbh->prepare("SHOW COLUMNS FROM borrower_message_preferences LIKE 'wants_digets'");
1846     $sth->execute();
1847     if (my $row = $sth->fetchrow_hashref) {
1848         $dbh->do("ALTER TABLE borrower_message_preferences CHANGE wants_digets wants_digest tinyint(1) NOT NULL default 0");
1849     }
1850         print "Upgrade to $DBversion done (fix name borrower_message_preferences.wants_digest)\n";
1851     SetVersion ($DBversion);
1852 }
1853
1854 $DBversion = '3.00.00.097';
1855 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1856
1857     $dbh->do('ALTER TABLE message_queue ADD to_address   mediumtext default NULL');
1858     $dbh->do('ALTER TABLE message_queue ADD from_address mediumtext default NULL');
1859     $dbh->do('ALTER TABLE message_queue ADD content_type text');
1860     $dbh->do('ALTER TABLE message_queue CHANGE borrowernumber borrowernumber int(11) default NULL');
1861
1862     print "Upgrade to $DBversion done (updating 4 fields in message_queue table)\n";
1863     SetVersion($DBversion);
1864 }
1865
1866 $DBversion = '3.00.00.098';
1867 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1868
1869     $dbh->do(q(DELETE FROM message_transport_types WHERE message_transport_type = 'rss'));
1870     $dbh->do(q(DELETE FROM message_transports WHERE message_transport_type = 'rss'));
1871
1872     print "Upgrade to $DBversion done (removing unused RSS message_transport_type)\n";
1873     SetVersion($DBversion);
1874 }
1875
1876 $DBversion = '3.00.00.099';
1877 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1878     $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')");
1879     print "Upgrade to $DBversion done (Adding OpacSuppression syspref)\n";
1880     SetVersion($DBversion);
1881 }
1882
1883 $DBversion = '3.00.00.100';
1884 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1885         $dbh->do('ALTER TABLE virtualshelves ADD COLUMN lastmodified timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP');
1886     print "Upgrade to $DBversion done (Adding lastmodified column to virtualshelves)\n";
1887     SetVersion($DBversion);
1888 }
1889
1890 $DBversion = '3.00.00.101';
1891 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1892         $dbh->do('ALTER TABLE `overduerules` CHANGE `categorycode` `categorycode` VARCHAR(10) NOT NULL');
1893         $dbh->do('ALTER TABLE `deletedborrowers` CHANGE `categorycode` `categorycode` VARCHAR(10) NOT NULL');
1894     print "Upgrade to $DBversion done (Updating columnd definitions for patron category codes in notice/statsu triggers and deletedborrowers tables.)\n";
1895     SetVersion($DBversion);
1896 }
1897
1898 $DBversion = '3.00.00.102';
1899 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1900         $dbh->do('ALTER TABLE serialitems MODIFY `serialid` int(11) NOT NULL AFTER itemnumber' );
1901         $dbh->do('ALTER TABLE serialitems DROP KEY serialididx' );
1902         $dbh->do('ALTER TABLE serialitems ADD CONSTRAINT UNIQUE KEY serialitemsidx (itemnumber)' );
1903         # before setting constraint, delete any unvalid data
1904         $dbh->do('DELETE from serialitems WHERE serialid not in (SELECT serial.serialid FROM serial)');
1905         $dbh->do('ALTER TABLE serialitems ADD CONSTRAINT serialitems_sfk_1 FOREIGN KEY (serialid) REFERENCES serial (serialid) ON DELETE CASCADE ON UPDATE CASCADE' );
1906     print "Upgrade to $DBversion done (Updating serialitems table to allow for multiple items per serial fixing kohabug 2380)\n";
1907     SetVersion($DBversion);
1908 }
1909
1910 $DBversion = "3.00.00.103";
1911 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1912     $dbh->do("DELETE FROM systempreferences WHERE variable='serialsadditems'");
1913     print "Upgrade to $DBversion done ( Verifying the removal of serialsadditems from syspref fixing kohabug 2219)\n";
1914     SetVersion ($DBversion);
1915 }
1916
1917 $DBversion = "3.00.00.104";
1918 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1919     $dbh->do("DELETE FROM systempreferences WHERE variable='noOPACHolds'");
1920     print "Upgrade to $DBversion done (remove superseded 'noOPACHolds' system preference per bug 2413)\n";
1921     SetVersion ($DBversion);
1922 }
1923
1924 $DBversion = '3.00.00.105';
1925 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
1926
1927     # it is possible that this syspref is already defined since the feature was added some time ago.
1928     unless ( $dbh->do(q(SELECT variable FROM systempreferences WHERE variable = 'SMSSendDriver')) ) {
1929         $dbh->do(<<'END_SQL');
1930 INSERT INTO `systempreferences`
1931   (variable,value,explanation,options,type)
1932 VALUES
1933 ('SMSSendDriver','','Sets which SMS::Send driver is used to send SMS messages.','','free')
1934 END_SQL
1935     }
1936     print "Upgrade to $DBversion done (added SMSSendDriver system preference)\n";
1937     SetVersion($DBversion);
1938 }
1939
1940 $DBversion = "3.00.00.106";
1941 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1942     $dbh->do("DELETE FROM systempreferences WHERE variable='noOPACHolds'");
1943
1944 # db revision 105 didn't apply correctly, so we're rolling this into 106
1945         $dbh->do("INSERT INTO `systempreferences`
1946    (variable,value,explanation,options,type)
1947         VALUES
1948         ('SMSSendDriver','','Sets which SMS::Send driver is used to send SMS messages.','','free')");
1949
1950     print "Upgrade to $DBversion done (remove default '0000-00-00' in subscriptionhistory.enddate field)\n";
1951     $dbh->do("ALTER TABLE `subscriptionhistory` CHANGE `enddate` `enddate` DATE NULL DEFAULT NULL ");
1952
1953     sanitize_zero_date('subscriptionhistory', 'enddate');
1954
1955     SetVersion ($DBversion);
1956 }
1957
1958 $DBversion = '3.00.00.107';
1959 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1960     $dbh->do(<<'END_SQL');
1961 UPDATE systempreferences
1962   SET explanation = CONCAT( explanation, '. WARNING: this feature is very resource consuming on collections with large numbers of items.' )
1963   WHERE variable = 'OPACShelfBrowser'
1964     AND explanation NOT LIKE '%WARNING%'
1965 END_SQL
1966     $dbh->do(<<'END_SQL');
1967 UPDATE systempreferences
1968   SET explanation = CONCAT( explanation, '. WARNING: this feature is very resource consuming.' )
1969   WHERE variable = 'CataloguingLog'
1970     AND explanation NOT LIKE '%WARNING%'
1971 END_SQL
1972     $dbh->do(<<'END_SQL');
1973 UPDATE systempreferences
1974   SET explanation = CONCAT( explanation, '. WARNING: using NoZebra on even modest sized collections is very slow.' )
1975   WHERE variable = 'NoZebra'
1976     AND explanation NOT LIKE '%WARNING%'
1977 END_SQL
1978     print "Upgrade to $DBversion done (warning added to OPACShelfBrowser system preference)\n";
1979     SetVersion ($DBversion);
1980 }
1981
1982 $DBversion = '3.01.00.000';
1983 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1984     print "Upgrade to $DBversion done (start of 3.1)\n";
1985     SetVersion ($DBversion);
1986 }
1987
1988 $DBversion = '3.01.00.001';
1989 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1990     $dbh->do("
1991         CREATE TABLE hold_fill_targets (
1992             `borrowernumber` int(11) NOT NULL,
1993             `biblionumber` int(11) NOT NULL,
1994             `itemnumber` int(11) NOT NULL,
1995             `source_branchcode`  varchar(10) default NULL,
1996             `item_level_request` tinyint(4) NOT NULL default 0,
1997             PRIMARY KEY `itemnumber` (`itemnumber`),
1998             KEY `bib_branch` (`biblionumber`, `source_branchcode`),
1999             CONSTRAINT `hold_fill_targets_ibfk_1` FOREIGN KEY (`borrowernumber`)
2000                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
2001             CONSTRAINT `hold_fill_targets_ibfk_2` FOREIGN KEY (`biblionumber`)
2002                 REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
2003             CONSTRAINT `hold_fill_targets_ibfk_3` FOREIGN KEY (`itemnumber`)
2004                 REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
2005             CONSTRAINT `hold_fill_targets_ibfk_4` FOREIGN KEY (`source_branchcode`)
2006                 REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
2007         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2008     ");
2009     $dbh->do("
2010         ALTER TABLE tmp_holdsqueue
2011             ADD item_level_request tinyint(4) NOT NULL default 0
2012     ");
2013
2014     print "Upgrade to $DBversion done (add hold_fill_targets table and a column to tmp_holdsqueue)\n";
2015     SetVersion($DBversion);
2016 }
2017
2018 $DBversion = '3.01.00.002';
2019 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2020     # use statistics where available
2021     $dbh->do("
2022         ALTER TABLE statistics ADD KEY  tmp_stats (type, itemnumber, borrowernumber)
2023     ");
2024     $dbh->do("
2025         UPDATE issues iss
2026         SET issuedate = (
2027             SELECT max(datetime)
2028             FROM statistics
2029             WHERE type = 'issue'
2030             AND itemnumber = iss.itemnumber
2031             AND borrowernumber = iss.borrowernumber
2032         )
2033         WHERE issuedate IS NULL;
2034     ");
2035     $dbh->do("ALTER TABLE statistics DROP KEY tmp_stats");
2036
2037     # default to last renewal date
2038     $dbh->do("
2039         UPDATE issues
2040         SET issuedate = lastreneweddate
2041         WHERE issuedate IS NULL
2042         and lastreneweddate IS NOT NULL
2043     ");
2044
2045     my $num_bad_issuedates = $dbh->selectrow_array("SELECT COUNT(*) FROM issues WHERE issuedate IS NULL");
2046     if ($num_bad_issuedates > 0) {
2047         print STDERR "After the upgrade to $DBversion, there are still $num_bad_issuedates loan(s) with a NULL (blank) loan date. ",
2048                      "Please check the issues table in your database.";
2049     }
2050     print "Upgrade to $DBversion done (bug 2582: set null issues.issuedate to lastreneweddate)\n";
2051     SetVersion($DBversion);
2052 }
2053
2054 $DBversion = "3.01.00.003";
2055 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2056     $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')");
2057     print "Upgrade to $DBversion done (add new syspref)\n";
2058     SetVersion ($DBversion);
2059 }
2060
2061 $DBversion = '3.01.00.004';
2062 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2063     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACDisplayRequestPriority','0','Show patrons the priority level on holds in the OPAC','','YesNo')");
2064     print "Upgrade to $DBversion done (added OPACDisplayRequestPriority system preference)\n";
2065     SetVersion ($DBversion);
2066 }
2067
2068 $DBversion = '3.01.00.005';
2069 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2070     $dbh->do("
2071         INSERT INTO `letter` (module, code, name, title, content)
2072         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>>')
2073     ");
2074     $dbh->do("INSERT INTO `message_attributes` (message_attribute_id, message_name, takes_days) values(4, 'Hold Filled', 0)");
2075     $dbh->do("INSERT INTO `message_transports` (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) values(4, 'sms', 0, 'reserves', 'HOLD')");
2076     $dbh->do("INSERT INTO `message_transports` (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) values(4, 'email', 0, 'reserves', 'HOLD')");
2077     print "Upgrade to $DBversion done (Add letter for holds notifications)\n";
2078     SetVersion ($DBversion);
2079 }
2080
2081 $DBversion = '3.01.00.006';
2082 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2083     $dbh->do("ALTER TABLE `biblioitems` ADD KEY issn (issn)");
2084     print "Upgrade to $DBversion done (add index on biblioitems.issn)\n";
2085     SetVersion ($DBversion);
2086 }
2087
2088 $DBversion = "3.01.00.007";
2089 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2090     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='intranetmainUserblock'");
2091     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='intranetuserjs'");
2092     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='opacheader'");
2093     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='OpacMainUserBlock'");
2094     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='OpacNav'");
2095     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='opacuserjs'");
2096     $dbh->do("UPDATE `systempreferences` SET options='30|10', type='Textarea' WHERE variable='OAI-PMH:Set'");
2097     $dbh->do("UPDATE `systempreferences` SET options='50' WHERE variable='intranetstylesheet'");
2098     $dbh->do("UPDATE `systempreferences` SET options='50' WHERE variable='intranetcolorstylesheet'");
2099     $dbh->do("UPDATE `systempreferences` SET options='10' WHERE variable='globalDueDate'");
2100     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='numSearchResults'");
2101     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='OPACnumSearchResults'");
2102     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='ReservesMaxPickupDelay'");
2103     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='TransfersMaxDaysWarning'");
2104     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='StaticHoldsQueueWeight'");
2105     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='holdCancelLength'");
2106     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='XISBNDailyLimit'");
2107     $dbh->do("UPDATE `systempreferences` SET type='Float' WHERE variable='gist'");
2108     $dbh->do("UPDATE `systempreferences` SET type='Free' WHERE variable='BakerTaylorUsername'");
2109     $dbh->do("UPDATE `systempreferences` SET type='Free' WHERE variable='BakerTaylorPassword'");
2110     $dbh->do("UPDATE `systempreferences` SET type='Textarea', options='70|10' WHERE variable='ISBD'");
2111     $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'");
2112     print "Upgrade to $DBversion done (fix display of many sysprefs)\n";
2113     SetVersion ($DBversion);
2114 }
2115
2116 $DBversion = '3.01.00.008';
2117 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2118
2119     $dbh->do("CREATE TABLE branch_transfer_limits (
2120                           limitId int(8) NOT NULL auto_increment,
2121                           toBranch varchar(4) NOT NULL,
2122                           fromBranch varchar(4) NOT NULL,
2123                           itemtype varchar(4) NOT NULL,
2124                           PRIMARY KEY  (limitId)
2125                           ) ENGINE=InnoDB DEFAULT CHARSET=utf8"
2126                         );
2127
2128     $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')");
2129
2130     print "Upgrade to $DBversion done (added branch_transfer_limits table and UseBranchTransferLimits system preference)\n";
2131     SetVersion ($DBversion);
2132 }
2133
2134 $DBversion = "3.01.00.009";
2135 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2136     $dbh->do("ALTER TABLE permissions MODIFY `code` varchar(64) DEFAULT NULL");
2137     $dbh->do("ALTER TABLE user_permissions MODIFY `code` varchar(64) DEFAULT NULL");
2138     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'circulate_remaining_permissions', 'Remaining circulation permissions')");
2139     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'override_renewals', 'Override blocked renewals')");
2140     print "Upgrade to $DBversion done (added subpermissions for circulate permission)\n";
2141 }
2142
2143 $DBversion = '3.01.00.010';
2144 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2145     $dbh->do("ALTER TABLE `borrower_attributes` MODIFY COLUMN `attribute` VARCHAR(64) DEFAULT NULL");
2146     $dbh->do("ALTER TABLE `borrower_attributes` MODIFY COLUMN `password` VARCHAR(64) DEFAULT NULL");
2147     print "Upgrade to $DBversion done (bug 2687: increase length of borrower attribute fields)\n";
2148     SetVersion ($DBversion);
2149 }
2150
2151 $DBversion = '3.01.00.011';
2152 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2153
2154     # Yes, the old value was ^M terminated.
2155     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);";
2156
2157     my $intranetuserjs = C4::Context->preference('intranetuserjs');
2158     if ($intranetuserjs  and  $intranetuserjs eq $bad_value) {
2159         my $sql = <<'END_SQL';
2160 UPDATE systempreferences
2161 SET value = ''
2162 WHERE variable = 'intranetuserjs'
2163 END_SQL
2164         $dbh->do($sql);
2165     }
2166     print "Upgrade to $DBversion done (removed bogus intranetuserjs syspref)\n";
2167     SetVersion($DBversion);
2168 }
2169
2170 $DBversion = "3.01.00.012";
2171 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2172     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowHoldPolicyOverride', '0', 'Allow staff to override hold policies when placing holds',NULL,'YesNo')");
2173     $dbh->do("
2174         CREATE TABLE `branch_item_rules` (
2175           `branchcode` varchar(10) NOT NULL,
2176           `itemtype` varchar(10) NOT NULL,
2177           `holdallowed` tinyint(1) default NULL,
2178           PRIMARY KEY  (`itemtype`,`branchcode`),
2179           KEY `branch_item_rules_ibfk_2` (`branchcode`),
2180           CONSTRAINT `branch_item_rules_ibfk_1` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE,
2181           CONSTRAINT `branch_item_rules_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
2182         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2183     ");
2184     $dbh->do("
2185         CREATE TABLE `default_branch_item_rules` (
2186           `itemtype` varchar(10) NOT NULL,
2187           `holdallowed` tinyint(1) default NULL,
2188           PRIMARY KEY  (`itemtype`),
2189           CONSTRAINT `default_branch_item_rules_ibfk_1` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE
2190         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2191     ");
2192     $dbh->do("
2193         ALTER TABLE default_branch_circ_rules
2194             ADD COLUMN holdallowed tinyint(1) NULL
2195     ");
2196     $dbh->do("
2197         ALTER TABLE default_circ_rules
2198             ADD COLUMN holdallowed tinyint(1) NULL
2199     ");
2200     print "Upgrade to $DBversion done (Add tables and system preferences for holds policies)\n";
2201     SetVersion ($DBversion);
2202 }
2203
2204 $DBversion = '3.01.00.013';
2205 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2206     $dbh->do("
2207         CREATE TABLE item_circulation_alert_preferences (
2208             id           int(11) AUTO_INCREMENT,
2209             branchcode   varchar(10) NOT NULL,
2210             categorycode varchar(10) NOT NULL,
2211             item_type    varchar(10) NOT NULL,
2212             notification varchar(16) NOT NULL,
2213             PRIMARY KEY (id),
2214             KEY (branchcode, categorycode, item_type, notification)
2215         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2216     ");
2217
2218     $dbh->do(q{ ALTER TABLE `message_queue` ADD metadata text DEFAULT NULL           AFTER content;  });
2219     $dbh->do(q{ ALTER TABLE `message_queue` ADD letter_code varchar(64) DEFAULT NULL AFTER metadata; });
2220
2221     $dbh->do(q{
2222         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
2223         ('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.');
2224     });
2225     $dbh->do(q{
2226         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
2227         ('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>>.');
2228     });
2229
2230     $dbh->do(q{INSERT INTO message_attributes (message_attribute_id, message_name, takes_days) VALUES (5, 'Item Check-in', 0);});
2231     $dbh->do(q{INSERT INTO message_attributes (message_attribute_id, message_name, takes_days) VALUES (6, 'Item Checkout', 0);});
2232
2233     $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');});
2234     $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');});
2235     $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');});
2236     $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');});
2237
2238     print "Upgrade to $DBversion done (data for Email Checkout Slips project)\n";
2239          SetVersion ($DBversion);
2240 }
2241
2242 $DBversion = "3.01.00.014";
2243 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2244     $dbh->do("ALTER TABLE `branch_transfer_limits` CHANGE `itemtype` `itemtype` VARCHAR( 4 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL");
2245     $dbh->do("ALTER TABLE `branch_transfer_limits` ADD `ccode` VARCHAR( 10 ) NULL ;");
2246     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2247     VALUES (
2248     'BranchTransferLimitsType', 'ccode', 'itemtype|ccode', 'When using branch transfer limits, choose whether to limit by itemtype or collection code.', 'Choice'
2249     );");
2250
2251     print "Upgrade to $DBversion done ( Updated table for Branch Transfer Limits)\n";
2252     SetVersion ($DBversion);
2253 }
2254
2255 $DBversion = '3.01.00.015';
2256 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2257     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsClientCode', '0', 'Client Code for using Syndetics Solutions content','','free')");
2258
2259     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsEnabled', '0', 'Turn on Syndetics Enhanced Content','','YesNo')");
2260
2261     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsCoverImages', '0', 'Display Cover Images from Syndetics','','YesNo')");
2262
2263     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsTOC', '0', 'Display Table of Content information from Syndetics','','YesNo')");
2264
2265     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsSummary', '0', 'Display Summary Information from Syndetics','','YesNo')");
2266
2267     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsEditions', '0', 'Display Editions from Syndetics','','YesNo')");
2268
2269     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsExcerpt', '0', 'Display Excerpts and first chapters on OPAC from Syndetics','','YesNo')");
2270
2271     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsReviews', '0', 'Display Reviews on OPAC from Syndetics','','YesNo')");
2272
2273     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsAuthorNotes', '0', 'Display Notes about the Author on OPAC from Syndetics','','YesNo')");
2274
2275     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsAwards', '0', 'Display Awards on OPAC from Syndetics','','YesNo')");
2276
2277     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsSeries', '0', 'Display Series information on OPAC from Syndetics','','YesNo')");
2278
2279     $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')");
2280
2281     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAmazonCoverImages', '0', 'Display cover images on OPAC from Amazon Web Services','','YesNo')");
2282
2283     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AmazonCoverImages', '0', 'Display Cover Images in Staff Client from Amazon Web Services','','YesNo')");
2284
2285     $dbh->do("UPDATE systempreferences SET variable='AmazonEnabled' WHERE variable = 'AmazonContent'");
2286
2287     $dbh->do("UPDATE systempreferences SET variable='OPACAmazonEnabled' WHERE variable = 'OPACAmazonContent'");
2288
2289     print "Upgrade to $DBversion done (added Syndetics Enhanced Content system preferences)\n";
2290     SetVersion ($DBversion);
2291 }
2292
2293 $DBversion = "3.01.00.016";
2294 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2295     $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')");
2296     print "Upgrade to $DBversion done (Added Babeltheque syspref)\n";
2297     SetVersion ($DBversion);
2298 }
2299
2300 $DBversion = "3.01.00.017";
2301 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2302     $dbh->do("ALTER TABLE `subscription` ADD `staffdisplaycount` VARCHAR(10) NULL;");
2303     $dbh->do("ALTER TABLE `subscription` ADD `opacdisplaycount` VARCHAR(10) NULL;");
2304     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2305     VALUES (
2306     'StaffSerialIssueDisplayCount', '3', '', 'Number of serial issues to display per subscription in the Staff client', 'Integer'
2307     );");
2308         $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2309     VALUES (
2310     'OPACSerialIssueDisplayCount', '3', '', 'Number of serial issues to display per subscription in the OPAC', 'Integer'
2311     );");
2312
2313     print "Upgrade to $DBversion done ( Updated table for Serials Display)\n";
2314     SetVersion ($DBversion);
2315 }
2316
2317 $DBversion = "3.01.00.018";
2318 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2319     $dbh->do("ALTER TABLE deletedborrowers ADD `smsalertnumber` varchar(50) default NULL");
2320     print "Upgrade to $DBversion done (added deletedborrowers.smsalertnumber, missed in 3.00.00.091)\n";
2321     SetVersion ($DBversion);
2322 }
2323
2324 $DBversion = "3.01.00.019";
2325 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2326         $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')");
2327     print "Upgrade to $DBversion done (adding OPACShowCheckoutName systempref)\n";
2328     SetVersion ($DBversion);
2329 }
2330
2331 $DBversion = "3.01.00.020";
2332 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2333     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesID','','See:http://librarything.com/forlibraries/','','free')");
2334     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesEnabled','0','Enable or Disable Library Thing for Libraries Features','','YesNo')");
2335     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesTabbedView','0','Put LibraryThingForLibraries Content in Tabs.','','YesNo')");
2336     print "Upgrade to $DBversion done (adding LibraryThing for Libraries sysprefs)\n";
2337     SetVersion ($DBversion);
2338 }
2339
2340 $DBversion = "3.01.00.021";
2341 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2342     my $enable_reviews = C4::Context->preference('OPACAmazonEnabled') ? '1' : '0';
2343     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAmazonReviews', '$enable_reviews', 'Display Amazon readers reviews on OPAC','','YesNo')");
2344     print "Upgrade to $DBversion done (adding OPACAmazonReviews syspref)\n";
2345     SetVersion ($DBversion);
2346 }
2347
2348 $DBversion = '3.01.00.022';
2349 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2350     $dbh->do("ALTER TABLE `labels_conf` MODIFY COLUMN `formatstring` mediumtext DEFAULT NULL");
2351     print "Upgrade to $DBversion done (bug 2945: increase size of labels_conf.formatstring)\n";
2352     SetVersion ($DBversion);
2353 }
2354
2355 $DBversion = '3.01.00.023';
2356 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2357     $dbh->do("ALTER TABLE biblioitems        MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2358     $dbh->do("ALTER TABLE deletedbiblioitems MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2359     $dbh->do("ALTER TABLE import_biblios     MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2360     $dbh->do("ALTER TABLE suggestions        MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2361     print "Upgrade to $DBversion done (bug 2765: increase width of isbn column in several tables)\n";
2362     SetVersion ($DBversion);
2363 }
2364
2365 $DBversion = "3.01.00.024";
2366 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2367     $dbh->do("ALTER TABLE labels MODIFY COLUMN batch_id int(10) NOT NULL default 1;");
2368     print "Upgrade to $DBversion done (change labels.batch_id from varchar to int)\n";
2369     SetVersion ($DBversion);
2370 }
2371
2372 $DBversion = '3.01.00.025';
2373 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2374     $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')");
2375
2376     print "Upgrade to $DBversion done (added ceilingDueDate system preference)\n";
2377     SetVersion ($DBversion);
2378 }
2379
2380 $DBversion = '3.01.00.026';
2381 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2382     $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')");
2383
2384     print "Upgrade to $DBversion done (added numReturnedItemsToShow system preference)\n";
2385     SetVersion ($DBversion);
2386 }
2387
2388 $DBversion = '3.01.00.027';
2389 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2390     $dbh->do("ALTER TABLE zebraqueue CHANGE `biblio_auth_number` `biblio_auth_number` bigint(20) unsigned NOT NULL default 0");
2391     print "Upgrade to $DBversion done (Increased size of zebraqueue biblio_auth_number to address bug 3148.)\n";
2392     SetVersion ($DBversion);
2393 }
2394
2395 $DBversion = '3.01.00.028';
2396 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2397     my $enable_reviews = C4::Context->preference('AmazonEnabled') ? '1' : '0';
2398     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AmazonReviews', '$enable_reviews', 'Display Amazon reviews on staff interface','','YesNo')");
2399     print "Upgrade to $DBversion done (added AmazonReviews)\n";
2400     SetVersion ($DBversion);
2401 }
2402
2403 $DBversion = '3.01.00.029';
2404 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2405     $dbh->do(q( UPDATE language_rfc4646_to_iso639
2406                 SET iso639_2_code = 'spa'
2407                 WHERE rfc4646_subtag = 'es'
2408                 AND   iso639_2_code = 'rus' )
2409             );
2410     print "Upgrade to $DBversion done (fixed bug 2599: using Spanish search limit retrieves Russian results)\n";
2411     SetVersion ($DBversion);
2412 }
2413
2414 $DBversion = "3.01.00.030";
2415 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2416     $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')");
2417     print "Upgrade to $DBversion done (added AllowNotForLoanOverride system preference)\n";
2418     SetVersion ($DBversion);
2419 }
2420
2421 $DBversion = "3.01.00.031";
2422 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2423     $dbh->do("ALTER TABLE branch_transfer_limits
2424               MODIFY toBranch   varchar(10) NOT NULL,
2425               MODIFY fromBranch varchar(10) NOT NULL,
2426               MODIFY itemtype   varchar(10) NULL");
2427     print "Upgrade to $DBversion done (fix column widths in branch_transfer_limits)\n";
2428     SetVersion ($DBversion);
2429 }
2430
2431 $DBversion = "3.01.00.032";
2432 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2433     $dbh->do(<<ENDOFRENEWAL);
2434 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');
2435 ENDOFRENEWAL
2436     print "Upgrade to $DBversion done (Change the field)\n";
2437     SetVersion ($DBversion);
2438 }
2439
2440 $DBversion = "3.01.00.033";
2441 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2442     $dbh->do(q/
2443         ALTER TABLE borrower_message_preferences
2444         MODIFY borrowernumber int(11) default NULL,
2445         ADD    categorycode varchar(10) default NULL AFTER borrowernumber,
2446         ADD KEY `categorycode` (`categorycode`),
2447         ADD CONSTRAINT `borrower_message_preferences_ibfk_3`
2448                        FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
2449                        ON DELETE CASCADE ON UPDATE CASCADE
2450     /);
2451     print "Upgrade to $DBversion done (DB changes to allow patron category defaults for messaging preferences)\n";
2452     SetVersion ($DBversion);
2453 }
2454
2455 $DBversion = "3.01.00.034";
2456 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2457     $dbh->do("ALTER TABLE `subscription` ADD COLUMN `graceperiod` INT(11) NOT NULL default '0';");
2458     print "Upgrade to $DBversion done (Adding graceperiod column to subscription table)\n";
2459     SetVersion ($DBversion);
2460 }
2461
2462 $DBversion = '3.01.00.035';
2463 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2464     $dbh->do(q{ ALTER TABLE `subscription` ADD location varchar(80) NULL DEFAULT '' AFTER callnumber; });
2465    print "Upgrade to $DBversion done (Adding location to subscription table)\n";
2466     SetVersion ($DBversion);
2467 }
2468
2469 $DBversion = '3.01.00.036';
2470 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2471     $dbh->do("UPDATE systempreferences SET explanation = 'Choose the default detail view in the staff interface; choose between normal, labeled_marc, marc or isbd'
2472               WHERE variable = 'IntranetBiblioDefaultView'
2473               AND   explanation = 'IntranetBiblioDefaultView'");
2474     $dbh->do("UPDATE systempreferences SET type = 'Choice', options = 'normal|marc|isbd|labeled_marc'
2475               WHERE variable = 'IntranetBiblioDefaultView'");
2476     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewISBD','1','Allow display of ISBD view of bibiographic records','','YesNo')");
2477     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewLabeledMARC','0','Allow display of labeled MARC view of bibiographic records','','YesNo')");
2478     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewMARC','1','Allow display of MARC view of bibiographic records','','YesNo')");
2479     print "Upgrade to $DBversion done (new viewISBD, viewLabeledMARC, viewMARC sysprefs and tweak IntranetBiblioDefaultView)\n";
2480     SetVersion ($DBversion);
2481 }
2482
2483 $DBversion = '3.01.00.037';
2484 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2485     $dbh->do('ALTER TABLE authorised_values ADD KEY `lib` (`lib`)');
2486     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('FilterBeforeOverdueReport','0','Do not run overdue report until filter selected','','YesNo')");
2487     SetVersion ($DBversion);
2488     print "Upgrade to $DBversion done (added FilterBeforeOverdueReport syspref and new index on authorised_values)\n";
2489 }
2490
2491 $DBversion = "3.01.00.038";
2492 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2493     # update branches table
2494     #
2495     $dbh->do("ALTER TABLE branches ADD `branchzip` varchar(25) default NULL AFTER `branchaddress3`");
2496     $dbh->do("ALTER TABLE branches ADD `branchcity` mediumtext AFTER `branchzip`");
2497     $dbh->do("ALTER TABLE branches ADD `branchcountry` text AFTER `branchcity`");
2498     $dbh->do("ALTER TABLE branches ADD `branchurl` mediumtext AFTER `branchemail`");
2499     $dbh->do("ALTER TABLE branches ADD `branchnotes` mediumtext AFTER `branchprinter`");
2500     print "Upgrade to $DBversion done (add ZIP, city, country, URL, and notes column to branches)\n";
2501     SetVersion ($DBversion);
2502 }
2503
2504 $DBversion = '3.01.00.039';
2505 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2506     $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')");
2507     $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')");
2508     SetVersion ($DBversion);
2509     print "Upgrade to $DBversion done (added SpineLabelFormat and SpineLabelAutoPrint sysprefs)\n";
2510 }
2511
2512 $DBversion = '3.01.00.040';
2513 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2514     $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')");
2515     $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')");
2516     SetVersion ($DBversion);
2517     print "Upgrade to $DBversion done (AllowHoldDateInFuture and OPACAllowHoldDateInFuture sysprefs)\n";
2518 }
2519
2520 $DBversion = '3.01.00.041';
2521 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2522     $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')");
2523     SetVersion ($DBversion);
2524     print "Upgrade to $DBversion done (added AWSPrivateKey syspref - note that if you use enhanced content from Amazon, this should be set right away.)\n";
2525 }
2526
2527 $DBversion = '3.01.00.042';
2528 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2529     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACFineNoRenewals','99999','Fine Limit above which user canmot renew books via OPAC','','Integer')");
2530     SetVersion ($DBversion);
2531     print "Upgrade to $DBversion done (added OPACFineNoRenewals syspref)\n";
2532 }
2533
2534 $DBversion = '3.01.00.043';
2535 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2536     $dbh->do('ALTER TABLE items ADD COLUMN permanent_location VARCHAR(80) DEFAULT NULL AFTER location');
2537     $dbh->do('UPDATE items SET permanent_location = location');
2538     $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 )', '')");
2539     $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')");
2540     $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')");
2541     SetVersion ($DBversion);
2542     print "Upgrade to $DBversion done (amended Item added NewItemsDefaultLocation, InProcessingToShelvingCart, ReturnToShelvingCart sysprefs)\n";
2543 }
2544
2545 $DBversion = '3.01.00.044';
2546 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2547     $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')");
2548     SetVersion ($DBversion);
2549     print "Upgrade to $DBversion done (added DisplayClearScreenButton system preference)\n";
2550 }
2551
2552 $DBversion = '3.01.00.045';
2553 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2554     $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')");
2555     SetVersion ($DBversion);
2556     print "Upgrade to $DBversion done (added a preference to hide the patrons name in the staff catalog)\n";
2557 }
2558
2559 $DBversion = "3.01.00.046";
2560 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2561     # update borrowers table
2562     #
2563     $dbh->do("ALTER TABLE borrowers ADD `country` text AFTER zipcode");
2564     $dbh->do("ALTER TABLE borrowers ADD `B_country` text AFTER B_zipcode");
2565     $dbh->do("ALTER TABLE deletedborrowers ADD `country` text AFTER zipcode");
2566     $dbh->do("ALTER TABLE deletedborrowers ADD `B_country` text AFTER B_zipcode");
2567     print "Upgrade to $DBversion done (add country and B_country to borrowers)\n";
2568     SetVersion ($DBversion);
2569 }
2570
2571 $DBversion = '3.01.00.047';
2572 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2573     $dbh->do("ALTER TABLE items MODIFY itemcallnumber varchar(255);");
2574     $dbh->do("ALTER TABLE deleteditems MODIFY itemcallnumber varchar(255);");
2575     $dbh->do("ALTER TABLE tmp_holdsqueue MODIFY itemcallnumber varchar(255);");
2576     SetVersion ($DBversion);
2577     print " Upgrade to $DBversion done (bug 2761: change max length of itemcallnumber to 255 from 30)\n";
2578 }
2579
2580 $DBversion = '3.01.00.048';
2581 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2582     $dbh->do("UPDATE userflags SET flagdesc='View Catalog (Librarian Interface)' WHERE bit=2;");
2583     $dbh->do("UPDATE userflags SET flagdesc='Edit Catalog (Modify bibliographic/holdings data)' WHERE bit=9;");
2584     $dbh->do("UPDATE userflags SET flagdesc='Allow to edit authorities' WHERE bit=14;");
2585     $dbh->do("UPDATE userflags SET flagdesc='Allow to access to the reports module' WHERE bit=16;");
2586     $dbh->do("UPDATE userflags SET flagdesc='Allow to manage serials subscriptions' WHERE bit=15;");
2587     SetVersion ($DBversion);
2588     print " Upgrade to $DBversion done (bug 2611: fix spelling/capitalization in permission flag descriptions)\n";
2589 }
2590
2591 $DBversion = '3.01.00.049';
2592 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2593     $dbh->do("UPDATE permissions SET description = 'Perform inventory (stocktaking) of your catalog' WHERE code = 'inventory';");
2594      SetVersion ($DBversion);
2595     print "Upgrade to $DBversion done (bug 2611: changed catalogue to catalog per the standard)\n";
2596 }
2597
2598 $DBversion = '3.01.00.050';
2599 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2600     $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');");
2601     SetVersion ($DBversion);
2602     print "Upgrade to $DBversion done (bug 1934: Add OPACSearchForTitleIn syspref)\n";
2603 }
2604
2605 $DBversion = '3.01.00.051';
2606 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2607     $dbh->do("UPDATE systempreferences SET explanation='Fine limit above which user cannot renew books via OPAC' WHERE variable='OPACFineNoRenewals';");
2608     $dbh->do("UPDATE systempreferences SET explanation='If set to ON, a clear screen button will appear on the circulation page.' WHERE variable='DisplayClearScreenButton';");
2609     SetVersion ($DBversion);
2610     print "Upgrade to $DBversion done (fixed typos in new sysprefs)\n";
2611 }
2612
2613 $DBversion = '3.01.00.052';
2614 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2615     $dbh->do('ALTER TABLE deleteditems ADD COLUMN permanent_location VARCHAR(80) DEFAULT NULL AFTER location');
2616     SetVersion ($DBversion);
2617     print "Upgrade to $DBversion done (bug 3481: add permanent_location column to deleteditems)\n";
2618 }
2619
2620 $DBversion = '3.01.00.053';
2621 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2622     my $upgrade_script = C4::Context->config("intranetdir") . "/installer/data/mysql/labels_upgrade.pl";
2623     system("perl $upgrade_script");
2624     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";
2625     SetVersion ($DBversion);
2626 }
2627
2628 $DBversion = '3.01.00.054';
2629 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2630     $dbh->do("ALTER TABLE borrowers ADD `B_address2` text AFTER B_address");
2631     $dbh->do("ALTER TABLE borrowers ADD `altcontactcountry` text AFTER altcontactzipcode");
2632     $dbh->do("ALTER TABLE deletedborrowers ADD `B_address2` text AFTER B_address");
2633     $dbh->do("ALTER TABLE deletedborrowers ADD `altcontactcountry` text AFTER altcontactzipcode");
2634     SetVersion ($DBversion);
2635     print "Upgrade to $DBversion done (bug 1600, bug 3454: add altcontactcountry and B_address2 to borrowers and deletedborrowers)\n";
2636 }
2637
2638 $DBversion = '3.01.00.055';
2639 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2640     $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'|);
2641     SetVersion ($DBversion);
2642     print "Upgrade to $DBversion done (changed OPACSearchForTitleIn per requests in bug 1934)\n";
2643 }
2644
2645 $DBversion = '3.01.00.056';
2646 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2647     $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');");
2648     SetVersion ($DBversion);
2649     print "Upgrade to $DBversion done (Bug 1172 : Add OPACPatronDetails syspref)\n";
2650 }
2651
2652 $DBversion = '3.01.00.057';
2653 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2654     $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');");
2655     SetVersion ($DBversion);
2656     print "Upgrade to $DBversion done (Bug 2576 : Add OPACFinesTab syspref)\n";
2657 }
2658
2659 $DBversion = '3.01.00.058';
2660 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2661     $dbh->do("ALTER TABLE `language_subtag_registry` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2662     $dbh->do("ALTER TABLE `language_rfc4646_to_iso639` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2663     $dbh->do("ALTER TABLE `language_descriptions` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2664     SetVersion ($DBversion);
2665     print "Upgrade to $DBversion done (Added primary keys to language tables)\n";
2666 }
2667
2668 $DBversion = '3.01.00.059';
2669 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2670     $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')");
2671     SetVersion ($DBversion);
2672     print "Upgrade to $DBversion done (added DisplayOPACiconsXSLT sysprefs)\n";
2673 }
2674
2675 $DBversion = '3.01.00.060';
2676 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2677     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowAllMessageDeletion','0','Allow any Library to delete any message','','YesNo');");
2678     $dbh->do('DROP TABLE IF EXISTS messages');
2679     $dbh->do("CREATE TABLE messages ( `message_id` int(11) NOT NULL auto_increment,
2680         `borrowernumber` int(11) NOT NULL,
2681         `branchcode` varchar(4) default NULL,
2682         `message_type` varchar(1) NOT NULL,
2683         `message` text NOT NULL,
2684         `message_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
2685         PRIMARY KEY (`message_id`)
2686         ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
2687
2688         print "Upgrade to $DBversion done ( Added AllowAllMessageDeletion syspref and messages table )\n";
2689     SetVersion ($DBversion);
2690 }
2691
2692 $DBversion = '3.01.00.061';
2693 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2694     $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')");
2695         print "Upgrade to $DBversion done ( Added ShowPatronImageInWebBasedSelfCheck system preference )\n";
2696     SetVersion ($DBversion);
2697 }
2698
2699 $DBversion = "3.01.00.062";
2700 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2701     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'manage_csv_profiles', 'Manage CSV export profiles')");
2702     $dbh->do(q/
2703         CREATE TABLE `export_format` (
2704           `export_format_id` int(11) NOT NULL auto_increment,
2705           `profile` varchar(255) NOT NULL,
2706           `description` mediumtext NOT NULL,
2707           `marcfields` mediumtext NOT NULL,
2708           PRIMARY KEY  (`export_format_id`)
2709         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Used for CSV export';
2710     /);
2711     print "Upgrade to $DBversion done (added csv export profiles)\n";
2712 }
2713
2714 $DBversion = "3.01.00.063";
2715 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2716     $dbh->do("
2717         CREATE TABLE `fieldmapping` (
2718           `id` int(11) NOT NULL auto_increment,
2719           `field` varchar(255) NOT NULL,
2720           `frameworkcode` char(4) NOT NULL default '',
2721           `fieldcode` char(3) NOT NULL,
2722           `subfieldcode` char(1) NOT NULL,
2723           PRIMARY KEY  (`id`)
2724         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2725              ");
2726     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";
2727 }
2728
2729 $DBversion = '3.01.00.065';
2730 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2731     $dbh->do('ALTER TABLE issuingrules ADD COLUMN `renewalsallowed` smallint(6) NOT NULL default "0" AFTER `issuelength`;');
2732     $sth = $dbh->prepare("SELECT itemtype, renewalsallowed FROM itemtypes");
2733     $sth->execute();
2734
2735     my $sthupd = $dbh->prepare("UPDATE issuingrules SET renewalsallowed = ? WHERE itemtype = ?");
2736
2737     while(my $row = $sth->fetchrow_hashref){
2738         $sthupd->execute($row->{renewalsallowed}, $row->{itemtype});
2739     }
2740
2741     $dbh->do('ALTER TABLE itemtypes DROP COLUMN `renewalsallowed`;');
2742
2743     SetVersion ($DBversion);
2744     print "Upgrade to $DBversion done (Moving allowed renewals from itemtypes to issuingrule)\n";
2745 }
2746
2747 $DBversion = '3.01.00.066';
2748 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2749     $dbh->do('ALTER TABLE issuingrules ADD COLUMN `reservesallowed` smallint(6) NOT NULL default "0" AFTER `renewalsallowed`;');
2750
2751     my $maxreserves = C4::Context->preference('maxreserves');
2752     $sth = $dbh->prepare('UPDATE issuingrules SET reservesallowed = ?;');
2753     $sth->execute($maxreserves);
2754
2755     $dbh->do('DELETE FROM systempreferences WHERE variable = "maxreserves";');
2756
2757     $dbh->do("INSERT INTO systempreferences (variable,value, options, explanation, type) VALUES('ReservesControlBranch','PatronLibrary','ItemHomeLibrary|PatronLibrary','Branch checked for members reservations rights','Choice')");
2758
2759     SetVersion ($DBversion);
2760     print "Upgrade to $DBversion done (Moving max allowed reserves from system preference to issuingrule)\n";
2761 }
2762
2763 $DBversion = "3.01.00.067";
2764 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2765     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'batchmod', 'Perform batch modification of items')");
2766     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'batchdel', 'Perform batch deletion of items')");
2767     print "Upgrade to $DBversion done (added permissions for batch modification and deletion)\n";
2768     SetVersion ($DBversion);
2769 }
2770
2771 $DBversion = "3.01.00.068";
2772 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2773         $dbh->do("ALTER TABLE issuingrules ADD COLUMN `finedays` int(11) default NULL AFTER `fine` ");
2774         print "Upgrade to $DBversion done (Adding finedays in issuingrules table)\n";
2775     SetVersion ($DBversion);
2776 }
2777
2778
2779 $DBversion = "3.01.00.069";
2780 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2781         $dbh->do("INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('EnableOpacSearchHistory', '1', '', 'Enable or disable opac search history', 'YesNo')");
2782
2783         my $create = <<SEARCHHIST;
2784 CREATE TABLE IF NOT EXISTS `search_history` (
2785   `userid` int(11) NOT NULL,
2786   `sessionid` varchar(32) NOT NULL,
2787   `query_desc` varchar(255) NOT NULL,
2788   `query_cgi` varchar(255) NOT NULL,
2789   `total` int(11) NOT NULL,
2790   `time` timestamp NOT NULL default CURRENT_TIMESTAMP,
2791   KEY `userid` (`userid`),
2792   KEY `sessionid` (`sessionid`)
2793 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Opac search history results';
2794 SEARCHHIST
2795         $dbh->do($create);
2796
2797         print "Upgrade to $DBversion done (added OPAC search history preference and table)\n";
2798 }
2799
2800 $DBversion = "3.01.00.070";
2801 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2802         $dbh->do("ALTER TABLE authorised_values ADD COLUMN `lib_opac` VARCHAR(80) default NULL AFTER `lib`");
2803         print "Upgrade to $DBversion done (Added a lib_opac field in authorised_values table)\n";
2804 }
2805
2806 $DBversion = "3.01.00.071";
2807 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2808         $dbh->do("ALTER TABLE `subscription` ADD `enddate` date default NULL");
2809         $dbh->do("ALTER TABLE subscriptionhistory CHANGE enddate histenddate DATE default NULL");
2810         print "Upgrade to $DBversion done ( Adding enddate to subscription)\n";
2811 }
2812
2813 # Acquisitions update
2814
2815 $DBversion = "3.01.00.072";
2816 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2817     $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')");
2818     # create a new syspref for the 'Mr anonymous' patron
2819     $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,'')");
2820     # fill AnonymousPatron with AnonymousSuggestion value (copy)
2821     my $sth=$dbh->prepare("SELECT value FROM systempreferences WHERE variable='AnonSuggestions'");
2822     $sth->execute;
2823     my ($value) = $sth->fetchrow() || 0;
2824     $dbh->do("UPDATE systempreferences SET value='$value' WHERE variable='AnonymousPatron'");
2825     # set AnonymousSuggestion do YesNo
2826     # 1st, set the value (1/True if it had a borrowernumber)
2827     $dbh->do("UPDATE systempreferences SET value=1 WHERE variable='AnonSuggestions' AND value>0");
2828     # 2nd, change the type to Choice
2829     $dbh->do("UPDATE systempreferences SET type='YesNo' WHERE variable='AnonSuggestions'");
2830         # borrower reading record privacy : 0 : forever, 1 : laws, 2 : don't keep at all
2831     $dbh->do("ALTER TABLE `borrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
2832     print "Upgrade to $DBversion done (add new syspref and column in borrowers)\n";
2833     SetVersion ($DBversion);
2834 }
2835
2836 $DBversion = '3.01.00.073';
2837 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2838     $dbh->do('SET FOREIGN_KEY_CHECKS=0 ');
2839     $dbh->do(<<'END_SQL');
2840 CREATE TABLE IF NOT EXISTS `aqcontract` (
2841   `contractnumber` int(11) NOT NULL auto_increment,
2842   `contractstartdate` date default NULL,
2843   `contractenddate` date default NULL,
2844   `contractname` varchar(50) default NULL,
2845   `contractdescription` mediumtext,
2846   `booksellerid` int(11) not NULL,
2847     PRIMARY KEY  (`contractnumber`),
2848         CONSTRAINT `booksellerid_fk1` FOREIGN KEY (`booksellerid`)
2849         REFERENCES `aqbooksellers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
2850 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
2851 END_SQL
2852     $dbh->do('SET FOREIGN_KEY_CHECKS=1 ');
2853     print "Upgrade to $DBversion done (adding aqcontract table)\n";
2854     SetVersion ($DBversion);
2855 }
2856
2857 $DBversion = '3.01.00.074';
2858 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2859     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `basketname` varchar(50) default NULL AFTER `basketno`");
2860     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `note` mediumtext AFTER `basketname`");
2861     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `booksellernote` mediumtext AFTER `note`");
2862     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `contractnumber` int(11) AFTER `booksellernote`");
2863     $dbh->do("ALTER TABLE `aqbasket` ADD FOREIGN KEY (`contractnumber`) REFERENCES `aqcontract` (`contractnumber`)");
2864     print "Upgrade to $DBversion done (edit aqbasket table done)\n";
2865     SetVersion ($DBversion);
2866 }
2867
2868 $DBversion = '3.01.00.075';
2869 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2870     $dbh->do("ALTER TABLE `aqorders` ADD COLUMN `uncertainprice` tinyint(1)");
2871
2872     print "Upgrade to $DBversion done (adding uncertainprices)\n";
2873     SetVersion ($DBversion);
2874 }
2875
2876 $DBversion = '3.01.00.076';
2877 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2878     $dbh->do('SET FOREIGN_KEY_CHECKS=0 ');
2879     $dbh->do("CREATE TABLE IF NOT EXISTS `aqbasketgroups` (
2880                          `id` int(11) NOT NULL auto_increment,
2881                          `name` varchar(50) default NULL,
2882                          `closed` tinyint(1) default NULL,
2883                          `booksellerid` int(11) NOT NULL,
2884                          PRIMARY KEY (`id`),
2885                          KEY `booksellerid` (`booksellerid`),
2886                          CONSTRAINT `aqbasketgroups_ibfk_1` FOREIGN KEY (`booksellerid`) REFERENCES `aqbooksellers` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
2887                          ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
2888     $dbh->do("ALTER TABLE aqbasket ADD COLUMN `basketgroupid` int(11)");
2889     $dbh->do("ALTER TABLE aqbasket ADD FOREIGN KEY (`basketgroupid`) REFERENCES `aqbasketgroups` (`id`) ON UPDATE CASCADE ON DELETE SET NULL");
2890     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('pdfformat','pdfformat::layout2pages','Controls what script is used for printing (basketgroups)','','free')");
2891     $dbh->do('SET FOREIGN_KEY_CHECKS=1 ');
2892     print "Upgrade to $DBversion done (adding basketgroups)\n";
2893     SetVersion ($DBversion);
2894 }
2895 $DBversion = '3.01.00.077';
2896 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2897
2898     $dbh->do("SET FOREIGN_KEY_CHECKS=0 ");
2899     # create a mapping table holding the info we need to match orders to budgets
2900     $dbh->do('DROP TABLE IF EXISTS fundmapping');
2901     $dbh->do(
2902         q|CREATE TABLE fundmapping AS
2903         SELECT aqorderbreakdown.ordernumber, branchcode, bookfundid, budgetdate, entrydate
2904         FROM aqorderbreakdown JOIN aqorders ON aqorderbreakdown.ordernumber = aqorders.ordernumber|);
2905     # match the new type of the corresponding field
2906     $dbh->do('ALTER TABLE fundmapping modify column bookfundid varchar(30)');
2907     # System did not ensure budgetdate was valid historically
2908     sanitize_zero_date('fundmapping', 'budgetdate');
2909     $dbh->do(q|UPDATE fundmapping SET budgetdate = entrydate WHERE budgetdate IS NULL|);
2910     # We save the map in fundmapping in case you need later processing
2911     $dbh->do(q|ALTER TABLE fundmapping add column aqbudgetid integer|);
2912     # these can speed processing up
2913     $dbh->do(q|CREATE INDEX fundmaporder ON fundmapping (ordernumber)|);
2914     $dbh->do(q|CREATE INDEX fundmapid ON fundmapping (bookfundid)|);
2915
2916     $dbh->do("DROP TABLE IF EXISTS `aqbudgetperiods` ");
2917
2918     $dbh->do(qq|
2919                     CREATE TABLE `aqbudgetperiods` (
2920                     `budget_period_id` int(11) NOT NULL auto_increment,
2921                     `budget_period_startdate` date NOT NULL,
2922                     `budget_period_enddate` date NOT NULL,
2923                     `budget_period_active` tinyint(1) default '0',
2924                     `budget_period_description` mediumtext,
2925                     `budget_period_locked` tinyint(1) default NULL,
2926                     `sort1_authcat` varchar(10) default NULL,
2927                     `sort2_authcat` varchar(10) default NULL,
2928                     PRIMARY KEY  (`budget_period_id`)
2929                     ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 |);
2930
2931    $dbh->do(<<ADDPERIODS);
2932 INSERT INTO aqbudgetperiods (budget_period_startdate,budget_period_enddate,budget_period_active,budget_period_description,budget_period_locked)
2933 SELECT DISTINCT startdate, enddate, NOW() BETWEEN startdate and enddate, concat(startdate," ",enddate),NOT NOW() BETWEEN startdate AND enddate from aqbudget
2934 ADDPERIODS
2935 # SORRY , NO AQBUDGET/AQBOOKFUND -> AQBUDGETS IMPORT JUST YET,
2936 # BUT A NEW CLEAN AQBUDGETS TABLE CREATE FOR NOW..
2937 # DROP TABLE IF EXISTS `aqbudget`;
2938 #CREATE TABLE `aqbudget` (
2939 #  `bookfundid` varchar(10) NOT NULL default ',
2940 #    `startdate` date NOT NULL default 0,
2941 #         `enddate` date default NULL,
2942 #           `budgetamount` decimal(13,2) default NULL,
2943 #                 `aqbudgetid` tinyint(4) NOT NULL auto_increment,
2944 #                   `branchcode` varchar(10) default NULL,
2945     DropAllForeignKeys('aqbudget');
2946   #$dbh->do("drop table aqbudget;");
2947
2948
2949     my $maxbudgetid = $dbh->selectcol_arrayref(<<IDsBUDGET);
2950 SELECT MAX(aqbudgetid) from aqbudget
2951 IDsBUDGET
2952
2953 $$maxbudgetid[0] = 0 if !$$maxbudgetid[0];
2954
2955     $dbh->do(<<BUDGETAUTOINCREMENT);
2956 ALTER TABLE aqbudget AUTO_INCREMENT=$$maxbudgetid[0]
2957 BUDGETAUTOINCREMENT
2958
2959     $dbh->do(<<BUDGETNAME);
2960 ALTER TABLE aqbudget RENAME `aqbudgets`
2961 BUDGETNAME
2962
2963     $dbh->do(<<BUDGETS);
2964 ALTER TABLE `aqbudgets`
2965    CHANGE  COLUMN aqbudgetid `budget_id` int(11) NOT NULL AUTO_INCREMENT,
2966    CHANGE  COLUMN branchcode `budget_branchcode` varchar(10) default NULL,
2967    CHANGE  COLUMN budgetamount `budget_amount` decimal(28,6) NOT NULL default '0.00',
2968    CHANGE  COLUMN bookfundid   `budget_code` varchar(30) default NULL,
2969    ADD     COLUMN `budget_parent_id` int(11) default NULL,
2970    ADD     COLUMN `budget_name` varchar(80) default NULL,
2971    ADD     COLUMN `budget_encumb` decimal(28,6) default '0.00',
2972    ADD     COLUMN `budget_expend` decimal(28,6) default '0.00',
2973    ADD     COLUMN `budget_notes` mediumtext,
2974    ADD     COLUMN `budget_description` mediumtext,
2975    ADD     COLUMN `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
2976    ADD     COLUMN `budget_amount_sublevel`  decimal(28,6) AFTER `budget_amount`,
2977    ADD     COLUMN `budget_period_id` int(11) default NULL,
2978    ADD     COLUMN `sort1_authcat` varchar(80) default NULL,
2979    ADD     COLUMN `sort2_authcat` varchar(80) default NULL,
2980    ADD     COLUMN `budget_owner_id` int(11) default NULL,
2981    ADD     COLUMN `budget_permission` int(1) default '0';
2982 BUDGETS
2983
2984     $dbh->do(<<BUDGETCONSTRAINTS);
2985 ALTER TABLE `aqbudgets`
2986    ADD CONSTRAINT `aqbudgets_ifbk_1` FOREIGN KEY (`budget_period_id`) REFERENCES `aqbudgetperiods` (`budget_period_id`) ON DELETE CASCADE ON UPDATE CASCADE
2987 BUDGETCONSTRAINTS
2988 #    $dbh->do(<<BUDGETPKDROP);
2989 #ALTER TABLE `aqbudgets`
2990 #   DROP PRIMARY KEY
2991 #BUDGETPKDROP
2992 #    $dbh->do(<<BUDGETPKADD);
2993 #ALTER TABLE `aqbudgets`
2994 #   ADD PRIMARY KEY budget_id
2995 #BUDGETPKADD
2996
2997
2998         my $query_period= $dbh->prepare(qq|SELECT budget_period_id from aqbudgetperiods where budget_period_startdate=? and budget_period_enddate=?|);
2999         my $query_bookfund= $dbh->prepare(qq|SELECT * from aqbookfund where bookfundid=?|);
3000         my $selectbudgets=$dbh->prepare(qq|SELECT * from aqbudgets|);
3001         my $updatebudgets=$dbh->prepare(qq|UPDATE aqbudgets SET budget_period_id= ? , budget_name=?, budget_branchcode=? where budget_id=?|);
3002         $selectbudgets->execute;
3003         while (my $databudget=$selectbudgets->fetchrow_hashref){
3004                 $query_period->execute ($$databudget{startdate},$$databudget{enddate});
3005                 my ($budgetperiodid)=$query_period->fetchrow;
3006                 $query_bookfund->execute ($$databudget{budget_code});
3007                 my $databf=$query_bookfund->fetchrow_hashref;
3008                 my $branchcode=$$databudget{budget_branchcode}||$$databf{branchcode};
3009                 $updatebudgets->execute($budgetperiodid,$$databf{bookfundname},$branchcode,$$databudget{budget_id});
3010         }
3011     $dbh->do(<<BUDGETDROPDATES);
3012 ALTER TABLE `aqbudgets`
3013    DROP startdate,
3014    DROP enddate
3015 BUDGETDROPDATES
3016
3017
3018     $dbh->do("DROP TABLE IF EXISTS `aqbudgets_planning` ");
3019     $dbh->do("CREATE TABLE  `aqbudgets_planning` (
3020                     `plan_id` int(11) NOT NULL auto_increment,
3021                     `budget_id` int(11) NOT NULL,
3022                     `budget_period_id` int(11) NOT NULL,
3023                     `estimated_amount` decimal(28,6) default NULL,
3024                     `authcat` varchar(30) NOT NULL,
3025                     `authvalue` varchar(30) NOT NULL,
3026                                         `display` tinyint(1) DEFAULT 1,
3027                         PRIMARY KEY  (`plan_id`),
3028                         CONSTRAINT `aqbudgets_planning_ifbk_1` FOREIGN KEY (`budget_id`) REFERENCES `aqbudgets` (`budget_id`) ON DELETE CASCADE ON UPDATE CASCADE
3029                         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
3030
3031     $dbh->do("ALTER TABLE `aqorders`
3032                     ADD COLUMN `budget_id` tinyint(4) NOT NULL,
3033                     ADD COLUMN `budgetgroup_id` int(11) NOT NULL,
3034                     ADD COLUMN  `sort1_authcat` varchar(10) default NULL,
3035                     ADD COLUMN  `sort2_authcat` varchar(10) default NULL" );
3036                 # We need to map the orders to the budgets
3037                 # For Historic reasons this is more complex than it should be on occasions
3038                 my $budg_arr = $dbh->selectall_arrayref(
3039                     q|SELECT aqbudgets.budget_id, aqbudgets.budget_code, aqbudgetperiods.budget_period_startdate,
3040                     aqbudgetperiods.budget_period_enddate
3041                     FROM aqbudgets JOIN aqbudgetperiods ON aqbudgets.budget_period_id = aqbudgetperiods.budget_period_id
3042                     ORDER BY budget_code, budget_period_startdate|, { Slice => {} });
3043                 # We arbitarily order on start date, this means if you have overlapping periods the order will be
3044                 # linked to the latest matching budget YMMV
3045                 my $b_sth = $dbh->prepare(
3046                     'UPDATE fundmapping set aqbudgetid = ? where bookfundid =? AND budgetdate >= ? AND budgetdate <= ?');
3047                 for my $b ( @{$budg_arr}) {
3048                     $b_sth->execute($b->{budget_id}, $b->{budget_code}, $b->{budget_period_startdate}, $b->{budget_period_enddate});
3049                 }
3050                 # move the budgetids to aqorders
3051                 $dbh->do(q|UPDATE aqorders, fundmapping SET aqorders.budget_id = fundmapping.aqbudgetid
3052                     WHERE aqorders.ordernumber = fundmapping.ordernumber AND fundmapping.aqbudgetid IS NOT NULL|);
3053                 # NB fundmapping is left as an accontants trail also if you have budgetids that werent set
3054                 # you can decide what to do with them
3055
3056      $dbh->do(
3057          q|UPDATE aqorders, aqbudgets SET aqorders.budgetgroup_id = aqbudgets.budget_period_id
3058          WHERE aqorders.budget_id = aqbudgets.budget_id|);
3059                 # cannot do until aqorderbreakdown removed
3060 #    $dbh->do("DROP TABLE aqbookfund ");
3061 #    $dbh->do("ALTER TABLE aqorders  ADD FOREIGN KEY (`budget_id`) REFERENCES `aqbudgets` (`budget_id`) ON UPDATE CASCADE  " ); ????
3062     $dbh->do("SET FOREIGN_KEY_CHECKS=1 ");
3063
3064     print "Upgrade to $DBversion done (Adding new aqbudgetperiods, aqbudgets and aqbudget_planning tables  )\n";
3065     SetVersion ($DBversion);
3066 }
3067
3068
3069
3070 $DBversion = '3.01.00.078';
3071 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3072     $dbh->do("ALTER TABLE aqbudgetperiods ADD COLUMN budget_period_total decimal(28,6)");
3073     print "Upgrade to $DBversion done (adds 'budget_period_total' column to aqbudgetperiods table)\n";
3074     SetVersion($DBversion);
3075 }
3076
3077
3078 $DBversion = '3.01.00.079';
3079 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3080     $dbh->do("ALTER TABLE currency ADD COLUMN active  tinyint(1)");
3081
3082     print "Upgrade to $DBversion done (adds 'active' column to currencies table)\n";
3083     SetVersion($DBversion);
3084 }
3085
3086 $DBversion = '3.01.00.080';
3087 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3088     $dbh->do(<<BUDG_PERM );
3089 INSERT INTO permissions (module_bit, code, description) VALUES
3090             (11, 'vendors_manage', 'Manage vendors'),
3091             (11, 'contracts_manage', 'Manage contracts'),
3092             (11, 'period_manage', 'Manage periods'),
3093             (11, 'budget_manage', 'Manage budgets'),
3094             (11, 'budget_modify', "Modify budget (can't create lines but can modify existing ones)"),
3095             (11, 'planning_manage', 'Manage budget plannings'),
3096             (11, 'order_manage', 'Manage orders & basket'),
3097             (11, 'group_manage', 'Manage orders & basketgroups'),
3098             (11, 'order_receive', 'Manage orders & basket'),
3099             (11, 'budget_add_del', "Add and delete budgets (but can't modify budgets)");
3100 BUDG_PERM
3101
3102     print "Upgrade to $DBversion done (adds permissions for the acquisitions module)\n";
3103     SetVersion($DBversion);
3104 }
3105
3106
3107 $DBversion = '3.01.00.081';
3108 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3109     $dbh->do("ALTER TABLE aqbooksellers ADD COLUMN `gstrate` decimal(6,4) default NULL");
3110     if (my $gist=C4::Context->preference("gist")){
3111                 my $sql=$dbh->prepare("UPDATE aqbooksellers set `gstrate`=? ");
3112         $sql->execute($gist) ;
3113         }
3114     print "Upgrade to $DBversion done (added per-supplier gstrate setting)\n";
3115     SetVersion($DBversion);
3116 }
3117
3118 $DBversion = "3.01.00.082";
3119 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3120     if (C4::Context->preference("opaclanguages") eq "fr") {
3121         $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')#);
3122     } else {
3123         $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')");
3124     }
3125     print "Upgrade to $DBversion done (adding ReservesNeedReturns systempref, in circulation)\n";
3126     SetVersion ($DBversion);
3127 }
3128
3129 $DBversion = "3.01.00.083";
3130 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3131     $dbh->do(qq|
3132  CREATE TABLE `aqorders_items` (
3133   `ordernumber` int(11) NOT NULL,
3134   `itemnumber` int(11) NOT NULL,
3135   `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
3136   PRIMARY KEY  (`itemnumber`),
3137   KEY `ordernumber` (`ordernumber`)
3138 ) ENGINE=InnoDB DEFAULT CHARSET=utf8   |
3139     );
3140
3141     $dbh->do(qq| DROP TABLE aqorderbreakdown |);
3142     $dbh->do('DROP TABLE aqbookfund');
3143     print "Upgrade to $DBversion done (New aqorders_items table for acqui)\n";
3144     SetVersion ($DBversion);
3145 }
3146
3147 $DBversion = "3.01.00.084";
3148 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3149     $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')  #);
3150
3151     print "Upgrade to $DBversion done (CurrencyFormat syspref added)\n";
3152     SetVersion ($DBversion);
3153 }
3154
3155 $DBversion = "3.01.00.085";
3156 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3157     $dbh->do("ALTER table aqorders drop column title");
3158     $dbh->do("ALTER TABLE `aqorders` CHANGE `budget_id` `budget_id` INT( 11 ) NOT NULL");
3159     print "Upgrade to $DBversion done update budget_id size that should not be a tinyint\n";
3160     SetVersion ($DBversion);
3161 }
3162
3163 $DBversion = "3.01.00.086";
3164 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3165     $dbh->do(<<SUGGESTIONS);
3166 ALTER table suggestions
3167     ADD budgetid INT(11),
3168     ADD branchcode VARCHAR(10) default NULL,
3169     ADD acceptedby INT(11) default NULL,
3170     ADD accepteddate date default NULL,
3171     ADD suggesteddate date default NULL,
3172     ADD manageddate date default NULL,
3173     ADD rejectedby INT(11) default NULL,
3174     ADD rejecteddate date default NULL,
3175     ADD collectiontitle text default NULL,
3176     ADD itemtype VARCHAR(30) default NULL
3177     ;
3178 SUGGESTIONS
3179     print "Upgrade to $DBversion done (Suggestions)\n";
3180     SetVersion ($DBversion);
3181 }
3182
3183 $DBversion = "3.01.00.087";
3184 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3185     $dbh->do("ALTER table aqbudgets drop column budget_amount_sublevel;");
3186     print "Upgrade to $DBversion done (Drop column budget_amount_sublevel from aqbudgets)\n";
3187     SetVersion ($DBversion);
3188 }
3189
3190 $DBversion = "3.01.00.088";
3191 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3192     $dbh->do(  qq# INSERT INTO `systempreferences` VALUES ('intranetbookbag','1','','If ON, enables display of Cart feature in the intranet','YesNo')  #);
3193
3194     print "Upgrade to $DBversion done (intranetbookbag syspref added)\n";
3195     SetVersion ($DBversion);
3196 }
3197
3198 $DBversion = "3.01.00.090";
3199 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3200 $dbh->do("
3201        INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3202                 (16, 'execute_reports', 'Execute SQL reports'),
3203                 (16, 'create_reports', 'Create SQL Reports')
3204         ");
3205
3206     print "Upgrade to $DBversion done (granular permissions for guided reports added)\n";
3207     SetVersion ($DBversion);
3208 }
3209
3210 $DBversion = "3.01.00.091";
3211 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3212 $dbh->do("
3213         UPDATE `systempreferences` SET `options` = 'holdings|serialcollection|subscriptions'
3214         WHERE `systempreferences`.`variable` = 'opacSerialDefaultTab' LIMIT 1
3215         ");
3216
3217     print "Upgrade to $DBversion done (opac-detail default tag updated)\n";
3218     SetVersion ($DBversion);
3219 }
3220
3221 $DBversion = "3.01.00.092";
3222 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3223     if (C4::Context->preference("opaclanguages") =~ /fr/) {
3224         $dbh->do(qq{
3225 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');
3226         });
3227         }else{
3228         $dbh->do(qq{
3229 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');
3230         });
3231         }
3232     print "Upgrade to $DBversion done (Added RoutingListAddReserves syspref)\n";
3233     SetVersion ($DBversion);
3234 }
3235
3236 $DBversion = "3.01.00.093";
3237 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3238         $dbh->do(qq{
3239         ALTER TABLE biblioitems ADD INDEX issn_idx (issn);
3240         });
3241     print "Upgrade to $DBversion done (added index to ISSN)\n";
3242     SetVersion ($DBversion);
3243 }
3244
3245 $DBversion = "3.01.00.094";
3246 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3247         $dbh->do(qq{
3248         ALTER TABLE aqbasketgroups ADD deliveryplace VARCHAR(10) default NULL, ADD deliverycomment VARCHAR(255) default NULL;
3249         });
3250
3251     print "Upgrade to $DBversion done (adding deliveryplace deliverycomment to basketgroups)\n";
3252     SetVersion ($DBversion);
3253 }
3254
3255 $DBversion = "3.01.00.095";
3256 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3257         $dbh->do(qq{
3258         ALTER TABLE items ADD stocknumber VARCHAR(32) DEFAULT NULL COMMENT "stores the inventory number";
3259         });
3260         $dbh->do(qq{
3261         ALTER TABLE items ADD UNIQUE INDEX itemsstocknumberidx (stocknumber);
3262         });
3263         $dbh->do(qq{
3264         ALTER TABLE deleteditems ADD stocknumber VARCHAR(32) DEFAULT NULL COMMENT "stores the inventory number of deleted items";
3265         });
3266         $dbh->do(qq{
3267         ALTER TABLE deleteditems ADD UNIQUE INDEX deleteditemsstocknumberidx (stocknumber);
3268         });
3269         if (C4::Context->preference('marcflavour') eq 'UNIMARC'){
3270                 $dbh->do(qq{
3271         INSERT IGNORE INTO marc_subfield_structure (frameworkcode,tagfield, tagsubfield, tab, repeatable, mandatory,kohafield)
3272         SELECT DISTINCT (frameworkcode),995,"j",10,0,0,"items.stocknumber" from biblio_framework ;
3273                 });
3274                 #Previously, copynumber was used as stocknumber
3275                 $dbh->do(qq{
3276         UPDATE items set stocknumber=copynumber;
3277                 });
3278                 $dbh->do(qq{
3279         UPDATE items set copynumber=NULL;
3280                 });
3281         }
3282     print "Upgrade to $DBversion done (stocknumber field added)\n";
3283     SetVersion ($DBversion);
3284 }
3285
3286 $DBversion = "3.01.00.096";
3287 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3288     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OrderPdfTemplate','','Uploads a PDF template to use for printing baskets','NULL','Upload')");
3289     $dbh->do("UPDATE systempreferences SET variable='OrderPdfFormat' WHERE variable='pdfformat'");
3290     print "Upgrade to $DBversion done (PDF orders system preferences added and updated)\n";
3291     SetVersion ($DBversion);
3292 }
3293
3294 $DBversion = "3.01.00.097";
3295 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3296         $dbh->do(qq{
3297         ALTER TABLE aqbasketgroups ADD billingplace VARCHAR(10) NOT NULL AFTER deliverycomment;
3298         });
3299
3300     print "Upgrade to $DBversion done (Adding billingplace to aqbasketgroups)\n";
3301     SetVersion ($DBversion);
3302 }
3303
3304 $DBversion = "3.01.00.098";
3305 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3306         $dbh->do(qq{
3307         ALTER TABLE auth_subfield_structure MODIFY frameworkcode VARCHAR(10) NULL;
3308         });
3309
3310     print "Upgrade to $DBversion done (changing frameworkcode length in auth_subfield_structure)\n";
3311     SetVersion ($DBversion);
3312 }
3313
3314 $DBversion = "3.01.00.099";
3315 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3316         $dbh->do(qq{
3317                 INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3318                 (9, 'edit_catalogue', 'Edit catalogue'),
3319                 (9, 'fast_cataloging', 'Fast cataloging')
3320         });
3321
3322     print "Upgrade to $DBversion done (granular permissions for cataloging added)\n";
3323     SetVersion ($DBversion);
3324 }
3325
3326 $DBversion = "3.01.00.100";
3327 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3328         $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')");
3329         print "Upgrade to $DBversion done (added CAS authentication system preferences)\n";
3330     SetVersion ($DBversion);
3331 }
3332
3333 $DBversion = "3.01.00.101";
3334 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3335         $dbh->do(
3336         "INSERT INTO systempreferences
3337            (variable, value, options, explanation, type)
3338          VALUES (
3339             'OverdueNoticeBcc', '', '',
3340             'Email address to Bcc outgoing notices sent by email',
3341             'free')
3342          ");
3343         print "Upgrade to $DBversion done (added OverdueNoticeBcc system preferences)\n";
3344     SetVersion ($DBversion);
3345 }
3346 $DBversion = "3.01.00.102";
3347 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3348     $dbh->do(
3349     "UPDATE permissions set description = 'Edit catalog (Modify bibliographic/holdings data)' where module_bit = 9 and code = 'edit_catalogue'"
3350     );
3351         print "Upgrade to $DBversion done (fixed spelling error in edit_catalogue permission)\n";
3352     SetVersion ($DBversion);
3353 }
3354
3355 $DBversion = "3.01.00.103";
3356 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3357         $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES (13, 'moderate_tags', 'Moderate patron tags')");
3358         print "Upgrade to $DBversion done (adding patron permissions for tags tool)\n";
3359     SetVersion ($DBversion);
3360 }
3361
3362 $DBversion = "3.01.00.104";
3363 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3364
3365     my ($maninv_count, $borrnotes_count);
3366     eval { $maninv_count = $dbh->do("SELECT 1 FROM authorised_values WHERE category='MANUAL_INV'"); };
3367     if ($maninv_count == 0) {
3368         $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('MANUAL_INV','Copier Fees','.25')");
3369     }
3370     eval { $borrnotes_count = $dbh->do("SELECT 1 FROM authorised_values WHERE category='BOR_NOTES'"); };
3371     if ($borrnotes_count == 0) {
3372         $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('BOR_NOTES','ADDR','Address Notes')");
3373     }
3374
3375     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('LOC','CART','Book Cart')");
3376     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('LOC','PROC','Processing Center')");
3377
3378         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";
3379         SetVersion ($DBversion);
3380 }
3381
3382
3383 $DBversion = "3.01.00.105";
3384 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3385     $dbh->do("
3386       CREATE TABLE `collections` (
3387         `colId` int(11) NOT NULL auto_increment,
3388         `colTitle` varchar(100) NOT NULL default '',
3389         `colDesc` text NOT NULL,
3390         `colBranchcode` varchar(4) default NULL COMMENT 'branchcode for branch where item should be held.',
3391         PRIMARY KEY  (`colId`)
3392       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3393     ");
3394
3395     $dbh->do("
3396       CREATE TABLE `collections_tracking` (
3397         `ctId` int(11) NOT NULL auto_increment,
3398         `colId` int(11) NOT NULL default '0' COMMENT 'collections.colId',
3399         `itemnumber` int(11) NOT NULL default '0' COMMENT 'items.itemnumber',
3400         PRIMARY KEY  (`ctId`)
3401       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3402     ");
3403     $dbh->do("
3404         INSERT INTO permissions (module_bit, code, description)
3405         VALUES ( 13, 'rotating_collections', 'Manage Rotating collections')" );
3406         print "Upgrade to $DBversion done (added collection and collection_tracking tables for rotating collections functionality)\n";
3407     SetVersion ($DBversion);
3408 }
3409 $DBversion = "3.01.00.106";
3410 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3411         $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' )");
3412         print "Upgrade to $DBversion done (added OpacAddMastheadLibraryPulldown system preferences)\n";
3413     SetVersion ($DBversion);
3414 }
3415
3416 $DBversion = '3.01.00.107';
3417 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3418     my $upgrade_script = C4::Context->config("intranetdir") . "/installer/data/mysql/patroncards_upgrade.pl";
3419     system("perl $upgrade_script");
3420     print "Upgrade to $DBversion done (Migrated labels and patroncards tables and data to new schema.)\n";
3421     SetVersion ($DBversion);
3422 }
3423
3424 $DBversion = '3.01.00.108';
3425 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3426         $dbh->do(qq{
3427     ALTER TABLE `export_format` ADD `csv_separator` VARCHAR( 2 ) NOT NULL AFTER `marcfields` ,
3428     ADD `field_separator` VARCHAR( 2 ) NOT NULL AFTER `csv_separator` ,
3429     ADD `subfield_separator` VARCHAR( 2 ) NOT NULL AFTER `field_separator`
3430     });
3431         print "Upgrade to $DBversion done (added separators for csv export)\n";
3432     SetVersion ($DBversion);
3433 }
3434
3435 $DBversion = "3.01.00.109";
3436 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3437         $dbh->do(qq{
3438         ALTER TABLE `export_format` ADD `encoding` VARCHAR(255) NOT NULL AFTER `subfield_separator`
3439         });
3440         print "Upgrade to $DBversion done (added encoding for csv export)\n";
3441     SetVersion ($DBversion);
3442 }
3443
3444 $DBversion = '3.01.00.110';
3445 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3446     $dbh->do('ALTER TABLE `categories` ADD COLUMN `enrolmentperioddate` DATE NULL DEFAULT NULL AFTER `enrolmentperiod`');
3447     print "Upgrade to $DBversion done (Add enrolment period date support)\n";
3448     SetVersion ($DBversion);
3449 }
3450
3451 $DBversion = '3.01.00.111';
3452 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3453     print "Upgrade to $DBversion done (mark DBrev for 3.2-alpha release)\n";
3454     SetVersion ($DBversion);
3455 }
3456
3457 $DBversion = '3.01.00.112';
3458 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3459         $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');");
3460         print "Upgrade to $DBversion done ( added Show Spine Label Printer on Bib Items Details preferences )\n";
3461     SetVersion ($DBversion);
3462 }
3463
3464 $DBversion = '3.01.00.113';
3465 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3466     my $value = C4::Context->preference("XSLTResultsDisplay");
3467     $dbh->do(
3468         "INSERT INTO systempreferences (variable,value,type)
3469          VALUES('OPACXSLTResultsDisplay',?,'YesNo')", {}, $value ? 1 : 0);
3470     $value = C4::Context->preference("XSLTDetailsDisplay");
3471     $dbh->do(
3472         "INSERT INTO systempreferences (variable,value,type)
3473          VALUES('OPACXSLTDetailsDisplay',?,'YesNo')", {}, $value ? 1 : 0);
3474     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";
3475     SetVersion ($DBversion);
3476 }
3477
3478 $DBversion = '3.01.00.114';
3479 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3480     $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')");
3481     $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')");
3482     $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')");
3483         print "Upgrade to $DBversion done ( Added AutoSelfCheckAllowed, AutoSelfCheckID, and AutoShelfCheckPass system preference )\n";
3484     SetVersion ($DBversion);
3485 }
3486
3487 $DBversion = '3.01.00.115';
3488 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3489     $dbh->do('UPDATE aqorders SET quantityreceived = 0 WHERE quantityreceived IS NULL');
3490     $dbh->do('ALTER TABLE aqorders MODIFY COLUMN quantityreceived smallint(6) NOT NULL DEFAULT 0');
3491         print "Upgrade to $DBversion done ( Default aqorders.quantityreceived to 0 )\n";
3492     SetVersion ($DBversion);
3493 }
3494
3495 $DBversion = '3.01.00.116';
3496 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3497         if (C4::Context->preference('OrderPdfFormat') eq 'pdfformat::example'){
3498                 $dbh->do("UPDATE `systempreferences` set value='pdfformat::layout2pages' WHERE variable='OrderPdfFormat'");
3499         }
3500         print "Upgrade to $DBversion done (corrected default OrderPdfFormat value if still set wrong )\n";
3501     SetVersion ($DBversion);
3502 }
3503
3504 $DBversion = '3.01.00.117';
3505 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3506     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'por' WHERE rfc4646_subtag='pt' ");
3507     print "Upgrade to $DBversion done (corrected ISO 639-2 language code for Portuguese)\n";
3508     SetVersion ($DBversion);
3509 }
3510
3511 $DBversion = '3.01.00.118';
3512 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3513     my ($count) = $dbh->selectrow_array("SELECT count(*) FROM information_schema.columns
3514                                          WHERE table_name = 'aqbudgets_planning'
3515                                          AND column_name = 'display'");
3516     if ($count < 1) {
3517         $dbh->do("ALTER TABLE aqbudgets_planning ADD COLUMN display tinyint(1) DEFAULT 1");
3518     }
3519     print "Upgrade to $DBversion done (bug 4203: add display column to aqbudgets_planning if missing)\n";
3520     SetVersion ($DBversion);
3521 }
3522
3523 $DBversion = '3.01.00.119';
3524 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3525     eval{require Locale::Currency::Format};
3526     if (!$@) {
3527         print "Upgrade to $DBversion done (Locale::Currency::Format installed.)\n";
3528         SetVersion ($DBversion);
3529     }
3530     else {
3531         print "Upgrade to $DBversion done.\n";
3532         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";
3533         SetVersion ($DBversion);
3534     }
3535 }
3536
3537 $DBversion = '3.01.00.120';
3538 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3539     $dbh->do(q{
3540 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');
3541 });
3542     print "Upgrade to $DBversion done (bug 1080: add soundon system preference for circulation sounds)\n";
3543     SetVersion ($DBversion);
3544 }
3545
3546 $DBversion = '3.01.00.121';
3547 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3548     $dbh->do("ALTER TABLE `reserves` ADD `expirationdate` DATE DEFAULT NULL");
3549     $dbh->do("ALTER TABLE `reserves` ADD `lowestPriority` tinyint(1) NOT NULL");
3550     $dbh->do("ALTER TABLE `old_reserves` ADD `expirationdate` DATE DEFAULT NULL");
3551     $dbh->do("ALTER TABLE `old_reserves` ADD `lowestPriority` tinyint(1) NOT NULL");
3552     print "Upgrade to $DBversion done ( Added Additional Fields to Reserves tables )\n";
3553     SetVersion ($DBversion);
3554 }
3555
3556 $DBversion = '3.01.00.122';
3557 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3558     $dbh->do(q{
3559       INSERT INTO systempreferences (variable,value,explanation,options,type)
3560       VALUES ('OAI-PMH:ConfFile', '', 'If empty, Koha OAI Server operates in normal mode, otherwise it operates in extended mode.','','File');
3561 });
3562     print "Upgrade to $DBversion done. — Add a new system preference OAI-PMF:ConfFile\n";
3563     SetVersion ($DBversion);
3564 }
3565
3566 $DBversion = "3.01.00.123";
3567 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3568     $dbh->do("INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3569         (6, 'place_holds', 'Place holds for patrons')");
3570     $dbh->do("INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3571         (6, 'modify_holds_priority', 'Modify holds priority')");
3572     $dbh->do("UPDATE `userflags` SET `flagdesc` = 'Place and modify holds for patrons' WHERE `flag` = 'reserveforothers'");
3573     print "Upgrade to $DBversion done (Add granular permission for holds modification and update description of reserveforothers permission)\n";
3574     SetVersion ($DBversion);
3575 }
3576
3577 $DBversion = '3.01.00.124';
3578 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3579     $dbh->do("
3580         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>>).');
3581     ");
3582     print "Upgrade to $DBversion done (bug 3242: add HOLDPLACED letter template, which is used when emailLibrarianWhenHoldIsPlaced is enabled)\n";
3583     SetVersion ($DBversion);
3584 }
3585
3586 $DBversion = '3.01.00.125';
3587 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3588     $dbh->do("
3589         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' );
3590     ");
3591     $dbh->do("
3592         INSERT INTO message_transport_types (message_transport_type) values ('print');
3593     ");
3594     print "Upgrade to $DBversion done (bug 3482: Printable hold and overdue notices)\n";
3595     SetVersion ($DBversion);
3596 }
3597
3598 $DBversion = "3.01.00.126";
3599 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3600         $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')");
3601         $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')");
3602
3603     print "Upgrade to $DBversion done (Adding ILS-DI updates and ILS-DI:AuthorizedIPs)\n";
3604     SetVersion ($DBversion);
3605 }
3606
3607 $DBversion = '3.01.00.127';
3608 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3609     $dbh->do("ALTER TABLE messages CHANGE branchcode branchcode varchar(10);");
3610     print "Upgrade to $DBversion done (bug 4190: messages in patron account did not work with branchcodes > 4)\n";
3611     SetVersion ($DBversion);
3612 }
3613
3614 $DBversion = '3.01.00.128';
3615 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3616     $dbh->do('CREATE INDEX budget_id ON aqorders (budget_id );');
3617     print "Upgrade to $DBversion done (bug 4331: index orders by budget_id)\n";
3618     SetVersion ($DBversion);
3619 }
3620
3621 $DBversion = "3.01.00.129";
3622 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3623         $dbh->do("UPDATE `permissions` SET `code` = 'items_batchdel' WHERE `permissions`.`module_bit` =13 AND `permissions`.`code` = 'batchdel' LIMIT 1 ;");
3624         $dbh->do("UPDATE `permissions` SET `code` = 'items_batchmod' WHERE `permissions`.`module_bit` =13 AND `permissions`.`code` = 'batchmod' LIMIT 1 ;");
3625         print "Upgrade to $DBversion done (Change permissions names for item batch modification / deletion)\n";
3626
3627     SetVersion ($DBversion);
3628 }
3629
3630 $DBversion = "3.01.00.130";
3631 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3632     sanitize_zero_date('reserves', 'expirationdate');
3633     print "Upgrade to $DBversion done (change reserves.expirationdate values of 0000-00-00 to NULL (bug 1532)\n";
3634     SetVersion ($DBversion);
3635 }
3636
3637 $DBversion = "3.01.00.131";
3638 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3639         $dbh->do(q{
3640 INSERT IGNORE INTO message_transport_types (message_transport_type) VALUES ('print'),('feed');
3641     });
3642     print "Upgrade to $DBversion done (adding print and feed message transport types)\n";
3643     SetVersion ($DBversion);
3644 }
3645
3646 $DBversion = "3.01.00.132";
3647 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3648         $dbh->do(q{
3649     ALTER TABLE language_descriptions ADD INDEX subtag_type_lang (subtag, type, lang);
3650     });
3651     print "Upgrade to $DBversion done (Adding index to language_descriptions table)\n";
3652     SetVersion ($DBversion);
3653 }
3654
3655 $DBversion = '3.01.00.133';
3656 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3657     $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')");
3658     print "Upgrade to $DBversion done (bug 4405: added OverduesBlockCirc syspref to control whether circulation is blocked if a borrower has overdues)\n";
3659     SetVersion ($DBversion);
3660 }
3661
3662 $DBversion = '3.01.00.134';
3663 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3664     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('DisplayMultiPlaceHold','1','Display the ability to place multiple holds or not','','YesNo')");
3665     print "Upgrade to $DBversion done (adding syspref DisplayMultiPlaceHold to control whether multiple holds can be placed from the search results page)\n";
3666     SetVersion ($DBversion);
3667 }
3668
3669 $DBversion = '3.01.00.135';
3670 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3671     $dbh->do("
3672         INSERT INTO `letter` (module, code, name, title, content) VALUES
3673 ('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')
3674 ");
3675     print "Upgrade to $DBversion done (bug 4377: added HOLD_PRINT message template)\n";
3676     SetVersion ($DBversion);
3677 }
3678
3679 $DBversion = '3.01.00.136';
3680 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3681     $dbh->do(qq{
3682 INSERT INTO permissions (module_bit, code, description) VALUES
3683    ( 9, 'edit_items', 'Edit Items');});
3684     print "Upgrade to $DBversion done (Adding a new permission to edit items)\n";
3685     SetVersion ($DBversion);
3686 }
3687
3688 $DBversion = "3.01.00.137";
3689 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3690         $dbh->do("
3691           INSERT INTO permissions (module_bit, code, description) VALUES
3692           (15, 'check_expiration', 'Check the expiration of a serial'),
3693           (15, 'claim_serials', 'Claim missing serials'),
3694           (15, 'create_subscription', 'Create a new subscription'),
3695           (15, 'delete_subscription', 'Delete an existing subscription'),
3696           (15, 'edit_subscription', 'Edit an existing subscription'),
3697           (15, 'receive_serials', 'Serials receiving'),
3698           (15, 'renew_subscription', 'Renew a subscription'),
3699           (15, 'routing', 'Routing');
3700                  ");
3701     print "Upgrade to $DBversion done (adding granular permissions for serials)\n";
3702     SetVersion ($DBversion);
3703 }
3704
3705 $DBversion = "3.01.00.138";
3706 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3707     $dbh->do("DELETE FROM systempreferences WHERE variable = 'GranularPermissions'");
3708     print "Upgrade to $DBversion done (bug 4896: removing GranularPermissions syspref; use of granular permissions is now the default)\n";
3709     SetVersion ($DBversion);
3710 }
3711
3712 $DBversion = '3.01.00.139';
3713 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3714     $dbh->do("ALTER TABLE message_attributes CHANGE message_name message_name varchar(40);");
3715     print "Upgrade to $DBversion done (bug 3682: change message_name from varchar(20) to varchar(40))\n";
3716     SetVersion ($DBversion);
3717 }
3718
3719 $DBversion = '3.01.00.140';
3720 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3721     $dbh->do("UPDATE systempreferences SET value = '0' WHERE variable = 'TagsModeration' AND value is NULL");
3722     print "Upgrade to $DBversion done (bug 4312 TagsModeration changed from NULL to 0)\n";
3723     SetVersion ($DBversion);
3724 }
3725
3726 $DBversion = '3.01.00.141';
3727 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3728     $dbh->do(qq{DELETE FROM message_attributes WHERE message_attribute_id=3;});
3729     $dbh->do(qq{DELETE FROM letter WHERE code='EVENT' AND title='Upcoming Library Event';});
3730     print "Upgrade to $DBversion done Remove upcoming events messaging option (bug 2434)\n";
3731     SetVersion ($DBversion);
3732 }
3733
3734 $DBversion = '3.01.00.142';
3735 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3736     $dbh->do(qq{DELETE FROM message_transports WHERE message_attribute_id=3;});
3737     print "Upgrade to $DBversion done (Remove upcoming events messaging option part 2 (bug 2434))\n";
3738     SetVersion ($DBversion);
3739 }
3740
3741 $DBversion = '3.01.00.143';
3742 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3743     $dbh->do(qq{CREATE INDEX auth_value_idx ON authorised_values (authorised_value)});
3744     $dbh->do(qq{CREATE INDEX auth_val_cat_idx ON borrower_attribute_types (authorised_value_category)});
3745     print "Upgrade to $DBversion done (Create index on authorised_values and borrower_attribute_types (bug 4139))\n";
3746     SetVersion ($DBversion);
3747 }
3748
3749 $DBversion = '3.01.00.144';
3750 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3751     $dbh->do(qq{UPDATE systempreferences SET value='normal' where value='default' and variable='IntranetBiblioDefaultView'});
3752     print "Upgrade to $DBversion done (Update the 'default' to 'normal' for the IntranetBiblioDefaultView syspref (bug 5007))\n";
3753     SetVersion ($DBversion);
3754 }
3755
3756 $DBversion = "3.01.00.145";
3757 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3758     $dbh->do("ALTER TABLE borrowers ADD KEY `guarantorid` (guarantorid);");
3759     print "Upgrade to $DBversion done (Add index on guarantorid)\n";
3760     SetVersion ($DBversion);
3761 }
3762
3763 $DBversion = '3.01.00.999';
3764 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3765     print "Upgrade to $DBversion done (3.2.0 release candidate)\n";
3766     SetVersion ($DBversion);
3767 }
3768
3769 $DBversion = "3.02.00.000";
3770 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3771     my $value = $dbh->selectrow_array("SELECT value FROM systempreferences WHERE variable = 'HomeOrHoldingBranch'");
3772     $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');");
3773     print "Upgrade to $DBversion done (Add HomeOrHoldingBranchReturn system preference)\n";
3774     SetVersion ($DBversion);
3775 }
3776
3777 $DBversion = "3.02.00.001";
3778 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3779     $dbh->do(q{DELETE FROM systempreferences WHERE variable IN (
3780                 'holdCancelLength',
3781                 'PINESISBN',
3782                 'sortbynonfiling',
3783                 'TemplateEncoding',
3784                 'OPACSubscriptionDisplay',
3785                 'OPACDisplayExtendedSubInfo',
3786                 'OAI-PMH:Set',
3787                 'OAI-PMH:Subset',
3788                 'libraryAddress',
3789                 'kohaspsuggest',
3790                 'OrderPdfTemplate',
3791                 'marc',
3792                 'acquisitions',
3793                 'MIME')
3794                }
3795     );
3796     print "Upgrade to $DBversion done (bug 3756: remove disused system preferences)\n";
3797     SetVersion ($DBversion);
3798 }
3799
3800 $DBversion = "3.02.00.002";
3801 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3802     $dbh->do(q{DELETE FROM systempreferences WHERE variable = 'OpacPrivacy'});
3803     print "Upgrade to $DBversion done (bug 3881: remove unused OpacPrivacy system preference)\n";
3804     SetVersion ($DBversion);
3805 }
3806
3807 $DBversion = "3.02.00.003";
3808 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3809     $dbh->do(q{UPDATE systempreferences SET variable = 'ILS-DI:AuthorizedIPs' WHERE variable = 'ILS-DI:Authorized_IPs'});
3810     print "Upgrade to $DBversion done (correct ILS-DI:AuthorizedIPs)\n";
3811     SetVersion ($DBversion);
3812 }
3813
3814 $DBversion = "3.02.00.004";
3815 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3816     print "Upgrade to $DBversion done (3.2.0 general release)\n";
3817     SetVersion ($DBversion);
3818 }
3819 # This is the point where 3.2.x and master diverged, we can use $original_version to make sure we don't
3820
3821 # apply updates that have already been done
3822
3823 $DBversion = "3.03.00.001";
3824 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.005")) {
3825     $dbh->do("DELETE FROM subscriptionroutinglist WHERE borrowernumber IS NULL;");
3826     $dbh->do("ALTER TABLE subscriptionroutinglist MODIFY COLUMN `borrowernumber` int(11) NOT NULL;");
3827     $dbh->do("DELETE FROM subscriptionroutinglist WHERE subscriptionid IS NULL;");
3828     $dbh->do("ALTER TABLE subscriptionroutinglist MODIFY COLUMN `subscriptionid` int(11) NOT NULL;");
3829     $dbh->do("CREATE TEMPORARY TABLE del_subscriptionroutinglist
3830               SELECT s1.routingid FROM subscriptionroutinglist s1
3831               WHERE EXISTS (SELECT * FROM subscriptionroutinglist s2
3832                             WHERE s2.borrowernumber = s1.borrowernumber
3833                             AND   s2.subscriptionid = s1.subscriptionid
3834                             AND   s2.routingid < s1.routingid);");
3835     $dbh->do("DELETE FROM subscriptionroutinglist
3836               WHERE routingid IN (SELECT routingid FROM del_subscriptionroutinglist);");
3837     $dbh->do("ALTER TABLE subscriptionroutinglist ADD UNIQUE (subscriptionid, borrowernumber);");
3838     $dbh->do("ALTER TABLE subscriptionroutinglist
3839                 ADD CONSTRAINT `subscriptionroutinglist_ibfk_1` FOREIGN KEY (`borrowernumber`)
3840                 REFERENCES `borrowers` (`borrowernumber`)
3841                 ON DELETE CASCADE ON UPDATE CASCADE");
3842     $dbh->do("ALTER TABLE subscriptionroutinglist
3843                 ADD CONSTRAINT `subscriptionroutinglist_ibfk_2` FOREIGN KEY (`subscriptionid`)
3844                 REFERENCES `subscription` (`subscriptionid`)
3845                 ON DELETE CASCADE ON UPDATE CASCADE");
3846     print "Upgrade to $DBversion done (Make subscriptionroutinglist more strict)\n";
3847     SetVersion ($DBversion);
3848 }
3849
3850 $DBversion = '3.03.00.002';
3851 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.006")) {
3852     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='arm' WHERE rfc4646_subtag='hy';");
3853     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='eng' WHERE rfc4646_subtag='en';");
3854     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'fi','fin');");
3855     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='fre' WHERE rfc4646_subtag='fr';");
3856     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'lo','lao');");
3857     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='ita' WHERE rfc4646_subtag='it';");
3858     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'sr','srp');");
3859     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'tet','tet');");
3860     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'ur','urd');");
3861
3862     print "Upgrade to $DBversion done (Correct language mappings)\n";
3863     SetVersion ($DBversion);
3864 }
3865
3866 $DBversion = '3.03.00.003';
3867 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.007")) {
3868     $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');");
3869     print "Upgrade to $DBversion done (Add UseTablesortForCirc syspref)\n";
3870     SetVersion ($DBversion);
3871 }
3872
3873 $DBversion = '3.03.00.004';
3874 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.001")) {
3875     my $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'ACCEPTED');
3876     $dbh->do(q/
3877 INSERT INTO `letter`
3878 (module, code, name, title, content)
3879 VALUES
3880 ('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>>')
3881 /) unless $count > 0;
3882     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'AVAILABLE');
3883     $dbh->do(q/
3884 INSERT INTO `letter`
3885 (module, code, name, title, content)
3886 VALUES
3887 ('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>>')
3888 /) unless $count > 0;
3889     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'ORDERED');
3890     $dbh->do(q/
3891 INSERT INTO `letter`
3892 (module, code, name, title, content)
3893 VALUES
3894 ('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>>')
3895 /) unless $count > 0;
3896     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'REJECTED');
3897     $dbh->do(q/
3898 INSERT INTO `letter`
3899 (module, code, name, title, content)
3900 VALUES
3901 ('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>>')
3902 /) unless $count > 0;
3903     print "Upgrade to $DBversion done (bug 5127: add default templates for suggestion status change notifications)\n";
3904     SetVersion ($DBversion);
3905 };
3906
3907 $DBversion = '3.03.00.005';
3908 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3909     $dbh->do("update `systempreferences` set options='whitespace|T-prefix|cuecat|libsuite8' where variable='itemBarcodeInputFilter'");
3910     print "Upgrade to $DBversion done (Add itemBarcodeInputFilter choice libsuite8)\n";
3911 }
3912
3913 $DBversion = '3.03.00.006';
3914 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.002")) {
3915     $dbh->do("ALTER TABLE deletedborrowers ADD `privacy` int(11) AFTER smsalertnumber;");
3916     $dbh->do("ALTER TABLE deletedborrowers CHANGE `cardnumber` `cardnumber` varchar(16);");
3917     print "Upgrade to $DBversion done (Fix differences between borrowers and deletedborrowers)\n";
3918     SetVersion ($DBversion);
3919 }
3920
3921 $DBversion = '3.03.00.007';
3922 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3923     $dbh->do("ALTER table suggestions ADD quantity SMALLINT(6) default NULL,
3924                 ADD currency VARCHAR(3) default NULL,
3925                 ADD price DECIMAL(28,6) default NULL,
3926                 ADD total DECIMAL(28,6) default NULL;
3927                 ");
3928     print "Upgrade to $DBversion done (Added acq related columns to suggestions)\n";
3929     SetVersion ($DBversion);
3930 }
3931
3932 $DBversion = '3.03.00.008';
3933 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3934     $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')");
3935     print "Upgrade to $DBversion done (adding syspref OPACNoResultsFound to control what displays when no results are found for a search in the OPAC.)\n";
3936     SetVersion ($DBversion);
3937 }
3938
3939 $DBversion = '3.03.00.009';
3940 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.003")) {
3941     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('IntranetUserCSS','','Add CSS to be included in the Intranet',NULL,'free')");
3942     print "Upgrade to $DBversion done (Add IntranetUserCSS syspref)\n";
3943     SetVersion ($DBversion);
3944 }
3945
3946 $DBversion = "3.03.00.010";
3947 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.02.001")) {
3948     $dbh->do("UPDATE `marc_subfield_structure` SET liblibrarian = 'Distance from earth' WHERE liblibrarian = 'Distrance from earth' AND tagfield = '034' AND tagsubfield = 'r';");
3949     $dbh->do("UPDATE `marc_subfield_structure` SET libopac = 'Distance from earth' WHERE libopac = 'Distrance from earth' AND tagfield = '034' AND tagsubfield = 'r';");
3950     print "Upgrade to $DBversion done (Fix misspelled 034r subfield in MARC21 Frameworks)\n";
3951     SetVersion ($DBversion);
3952 }
3953
3954 $DBversion = "3.03.00.011";
3955 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3956     $dbh->do("UPDATE aqbooksellers SET gstrate=NULL WHERE gstrate=0.0");
3957     print "Upgrade to $DBversion done (Bug 5186: allow GST rate to be set to 0)\n";
3958     SetVersion ($DBversion);
3959 }
3960
3961 $DBversion = "3.03.00.012";
3962 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3963    $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')");
3964    print "Upgrade to $DBversion done (Bug 2142: maxItemsInSearchResults syspref resurrected)\n";
3965    SetVersion ($DBversion);
3966 }
3967
3968 $DBversion = "3.03.00.013";
3969 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3970     $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')");
3971     print "Upgrade to $DBversion done (added 'OpacPublic' syspref)\n";
3972    SetVersion ($DBversion);
3973 }
3974
3975 $DBversion = "3.03.00.014";
3976 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3977     $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')");
3978     $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')");
3979     $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')");
3980     print "Upgrade to $DBversion done (Add flexible shelf browser constraints)\n";
3981     SetVersion ($DBversion);
3982 }
3983
3984 $DBversion = "3.03.00.015";
3985 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3986     if ( C4::Context->preference("marcflavour") eq "MARC21" ) {
3987         my $sth = $dbh->prepare(
3988 "INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`,
3989                              `tab`, `authorised_value`, `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`)
3990                              VALUES ( ?, '9', '9 (RLIN)', '9 (RLIN)', 0, 0, '', 6, '', '', '', 0, -5, '', '', '', NULL)"
3991         );
3992         $sth->execute('648');
3993         $sth->execute('654');
3994         $sth->execute('655');
3995         $sth->execute('656');
3996         $sth->execute('657');
3997         $sth->execute('658');
3998         $sth->execute('662');
3999         $sth->finish;
4000         print
4001 "Upgrade to $DBversion done (Bug 5619: Add subfield 9 to marc21 648,654,655,656,657,658,662)\n";
4002     }
4003     SetVersion($DBversion);
4004 }
4005
4006 $DBversion = '3.03.00.016';
4007 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4008     # reimplement OpacPrivacy system preference
4009     $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')");
4010     $dbh->do("ALTER TABLE `borrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
4011     $dbh->do("ALTER TABLE `deletedborrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
4012     print "Upgrade to $DBversion done (OpacPrivacy reimplementation)\n";
4013     SetVersion($DBversion);
4014 };
4015
4016 $DBversion = '3.03.00.017';
4017 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.001")) {
4018     $dbh->do("ALTER TABLE  `currency` CHANGE `rate` `rate` FLOAT( 15, 5 ) NULL DEFAULT NULL;");
4019     print "Upgrade to $DBversion done (Enable currency rates >= 100)\n";
4020     SetVersion ($DBversion);
4021 }
4022
4023 $DBversion = '3.03.00.018';
4024 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.002")) {
4025     $dbh->do( q|update language_descriptions set description = 'Nederlands' where lang = 'nl' and subtag = 'nl'|);
4026     $dbh->do( q|update language_descriptions set description = 'Dansk' where lang = 'da' and subtag = 'da'|);
4027     print "Upgrade to $DBversion done (Correct language descriptions)\n";
4028     SetVersion ($DBversion);
4029 }
4030
4031 $DBversion = '3.03.00.019';
4032 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.003")) {
4033     # Fix bokmål
4034     $dbh->do("UPDATE language_subtag_registry SET description = 'Norwegian bokm&#229;l' WHERE subtag = 'nb';");
4035     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'nb','nob');");
4036     $dbh->do("UPDATE language_descriptions SET description = 'Norsk bokm&#229;l' WHERE subtag = 'nb' AND lang = 'nb';");
4037     $dbh->do("UPDATE language_descriptions SET description = 'Norwegian bokm&#229;l' WHERE subtag = 'nb' AND lang = 'en';");
4038     $dbh->do("UPDATE language_descriptions SET description = 'Norvégien bokm&#229;l' WHERE subtag = 'nb' AND lang = 'fr';");
4039     # Add nynorsk
4040     $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'nn', 'language', 'Norwegian nynorsk','2011-02-14' )");
4041     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'nn','nno')");
4042     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'nb', 'Norsk nynorsk')");
4043     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'nn', 'Norsk nynorsk')");
4044     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'en', 'Norwegian nynorsk')");
4045     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'fr', 'Norvégien nynorsk')");
4046     print "Upgrade to $DBversion done (Correct language descriptions for Norwegian)\n";
4047     SetVersion ($DBversion);
4048 }
4049
4050 $DBversion = '3.03.00.020';
4051 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4052     $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')");
4053     $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')");
4054     print "Upgrade to $DBversion done (Bug 5811: Add sysprefs controlling overriding fines)\n";
4055     SetVersion($DBversion);
4056 };
4057
4058 $DBversion = '3.03.00.021';
4059 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.001")) {
4060     $dbh->do("ALTER TABLE items MODIFY enumchron TEXT");
4061     $dbh->do("ALTER TABLE deleteditems MODIFY enumchron TEXT");
4062     print "Upgrade to $DBversion done (bug 5642: longer serial enumeration)\n";
4063     SetVersion ($DBversion);
4064 }
4065
4066 $DBversion = '3.03.00.022';
4067 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4068     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('AuthoritiesLog','0','If ON, log edit/create/delete actions on authorities.','','YesNo');");
4069     print "Upgrade to $DBversion done (Add AuthoritiesLog syspref)\n";
4070     SetVersion ($DBversion);
4071 }
4072
4073 # due to a mismatch in kohastructure.sql some koha will have missing columns in aqbasketgroup
4074 # this attempts to fix that
4075 $DBversion = '3.03.00.023';
4076 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.002")) {
4077     my $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'billingplace'");
4078     $sth->execute;
4079     $dbh->do("ALTER TABLE aqbasketgroups ADD billingplace VARCHAR(10)") if ! $sth->fetchrow_hashref;
4080     $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'deliveryplace'");
4081     $sth->execute;
4082     $dbh->do("ALTER TABLE aqbasketgroups ADD deliveryplace VARCHAR(10)") if ! $sth->fetchrow_hashref;
4083     $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'deliverycomment'");
4084     $sth->execute;
4085     $dbh->do("ALTER TABLE aqbasketgroups ADD deliverycomment VARCHAR(255)") if ! $sth->fetchrow_hashref;
4086     print "Upgrade to $DBversion done (Reconcile aqbasketgroups)\n";
4087     SetVersion ($DBversion);
4088 }
4089
4090 $DBversion = '3.03.00.024';
4091 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4092     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('TraceCompleteSubfields','0','Force subject tracings to only match complete subfields.','0','YesNo')");
4093     $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')");
4094     print "Upgrade to $DBversion done (Add syspref to force whole-subfield matching on subject tracings)\n";
4095     SetVersion($DBversion);
4096 };
4097
4098 $DBversion = "3.03.00.025";
4099 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4100     $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')");
4101     print "Upgrade to $DBversion done (Add syspref to control if user can choose pickup branch for holds)\n";
4102     SetVersion ($DBversion);
4103 }
4104
4105 $DBversion = '3.03.00.026';
4106 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.003")) {
4107     $dbh->do("UPDATE `message_attributes` SET message_name='Item Due' WHERE message_attribute_id=1 AND message_name LIKE 'Item DUE'");
4108         print "Upgrade to $DBversion done ( fix capitalization in message type )\n";
4109     SetVersion ($DBversion);
4110 }
4111
4112 $DBversion = '3.03.00.027';
4113 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4114     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('displayFacetCount', '0', NULL, NULL, 'YesNo')");
4115     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('maxRecordsForFacets', '20', NULL, NULL, 'Integer')");
4116     print "Upgrade to $DBversion done (Preferences for facet count)\n";
4117     SetVersion ($DBversion);
4118 }
4119
4120 $DBversion = "3.03.00.028";
4121 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4122     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('FacetLabelTruncationLength', 20, 'Truncate facets length to','','free')");
4123     print "Upgrade to $DBversion done (Add FacetLabelTruncationLength syspref to control facets displayed length)\n";
4124     SetVersion ($DBversion);
4125 }
4126
4127 $DBversion = "3.03.00.029";
4128 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4129     $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')");
4130     print "Upgrade to $DBversion done (Add syspref to control if user can choose branch when making purchase suggestion)\n";
4131     SetVersion ($DBversion);
4132 }
4133
4134 $DBversion = "3.03.00.030";
4135 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4136     $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')");
4137     $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')");
4138     print "Upgrade to $DBversion done (Add sysprefs to control custom favicons)\n";
4139     SetVersion ($DBversion);
4140 }
4141
4142 $DBversion = "3.03.00.031";
4143 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4144     $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');");
4145     print "Upgrade to $DBversion done (Add syspref FineNotifyAtCheckin)\n";
4146     SetVersion ($DBversion);
4147 }
4148
4149 $DBversion = '3.03.00.032';
4150 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4151     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('TraceSubjectSubdivisions', 1, 'Create searches on all subdivisions for subject tracings.','1','YesNo')");
4152     print "Upgrade to $DBversion done ( include subdivisions when generating subject tracing searches )\n";
4153 }
4154
4155
4156 $DBversion = '3.03.00.033';
4157 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4158     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('StaffAuthorisedValueImages', '1', '', NULL, 'YesNo')");
4159     print "Upgrade to $DBversion done (System pref StaffAuthorisedValueImages)\n";
4160     SetVersion ($DBversion);
4161 }
4162
4163 $DBversion = '3.03.00.034';
4164 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4165     $dbh->do("ALTER TABLE `categories` ADD `hidelostitems` tinyint(1) NOT NULL default '0' AFTER `reservefee`");
4166     print "Upgrade to $DBversion done (Add hidelostitems preference to borrower categories)\n";
4167     SetVersion ($DBversion);
4168 }
4169
4170 $DBversion = '3.03.00.035';
4171 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4172     $dbh->do("ALTER TABLE `issuingrules` ADD hardduedate date default NULL AFTER issuelength");
4173     $dbh->do("ALTER TABLE `issuingrules` ADD hardduedatecompare tinyint NOT NULL default 0 AFTER hardduedate");
4174     my $duedate;
4175     if (C4::Context->preference("globalDueDate")) {
4176       $duedate = eval { output_pref( { dt => dt_from_string( C4::Context->preference("globalDueDate") ), dateonly => 1, dateformat => 'iso' } ); };
4177       $dbh->do("UPDATE `issuingrules` SET hardduedate = '$duedate', hardduedatecompare = 0");
4178     } elsif (C4::Context->preference("ceilingDueDate")) {
4179       $duedate = eval { output_pref( { dt => dt_from_string( C4::Context->preference("ceilingDueDate") ), dateonly => 1, dateformat => 'iso' } ); };
4180       $dbh->do("UPDATE `issuingrules` SET hardduedate = '$duedate', hardduedatecompare = -1");
4181     }
4182     $dbh->do("DELETE FROM `systempreferences` WHERE variable = 'globalDueDate' OR variable = 'ceilingDueDate'");
4183     print "Upgrade to $DBversion done (Move global and ceiling due dates to Circ Rules level)\n";
4184     SetVersion ($DBversion);
4185 }
4186
4187 $DBversion = '3.03.00.036';
4188 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4189     $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')");
4190     print "Upgrade to $DBversion done ( Make COinS optional in OPAC search results )\n";
4191     SetVersion ($DBversion);
4192 }
4193
4194 $DBversion = '3.03.00.037';
4195 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4196     $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')");
4197     $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')");
4198     print "Upgrade to $DBversion done (Add 'Display856uAsImage' and 'OPACDisplay856uAsImage' syspref)\n";
4199     SetVersion ($DBversion);
4200 }
4201
4202 $DBversion = '3.03.00.038';
4203 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4204     $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')");
4205     $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')");
4206     $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')");
4207     print "Upgrade to $DBversion done ( Add Self-checkout by Login system preferences )\n";
4208 }
4209
4210 $DBversion = "3.03.00.039";
4211 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4212     $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');");
4213     print "Upgrade to $DBversion done (Add syspref ShowReviewer)\n";
4214 }
4215
4216 $DBversion = "3.03.00.040";
4217 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4218     $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');");
4219     print "Upgrade to $DBversion done (Add syspref UseControlNumber)\n";
4220 }
4221
4222 $DBversion = "3.03.00.041";
4223 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4224     $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')");
4225     $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')");
4226     print "Upgrade to $DBversion done (Add sysprefs to control alternate holdings information display)\n";
4227     SetVersion ($DBversion);
4228 }
4229
4230 $DBversion = '3.03.00.042';
4231 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4232     stocknumber_checker();
4233     print "Upgrade to $DBversion done (5860 Index itemstocknumber)\n";
4234     SetVersion ($DBversion);
4235 }
4236
4237 sub stocknumber_checker { #code reused later on
4238   my @row;
4239   #drop the obsolete itemSStocknumber idx if it exists
4240   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemsstocknumberidx'");
4241   $dbh->do("ALTER TABLE `items` DROP INDEX `itemsstocknumberidx`;") if @row;
4242
4243   #check itemstocknumber idx; remove it if it is unique
4244   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemstocknumberidx' AND non_unique=0");
4245   $dbh->do("ALTER TABLE `items` DROP INDEX `itemstocknumberidx`;") if @row;
4246
4247   #add itemstocknumber index non-unique IF it still not exists
4248   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemstocknumberidx'");
4249   $dbh->do("ALTER TABLE items ADD INDEX itemstocknumberidx (stocknumber);") unless @row;
4250 }
4251
4252 $DBversion = "3.03.00.043";
4253 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4254
4255     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib,lib_opac) VALUES ('YES_NO','0','No','No')");
4256     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib,lib_opac) VALUES ('YES_NO','1','Yes','Yes')");
4257
4258         print "Upgrade to $DBversion done ( add generic boolean YES_NO authorised_values pair )\n";
4259         SetVersion ($DBversion);
4260 }
4261
4262 $DBversion = '3.03.00.044';
4263 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4264     $dbh->do("ALTER TABLE `aqbasketgroups` ADD `freedeliveryplace` TEXT NULL AFTER `deliveryplace`;");
4265     print "Upgrade to $DBversion done (adding freedeliveryplace to basketgroups)\n";
4266 }
4267
4268 $DBversion = '3.03.00.045';
4269 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4270     #Remove obsolete columns from aqbooksellers if needed
4271     my $a = $dbh->selectall_hashref('SHOW columns from aqbooksellers','Field');
4272     my $sqldrop="ALTER TABLE aqbooksellers DROP COLUMN ";
4273     foreach(qw/deliverydays followupdays followupscancel invoicedisc nocalc specialty/) {
4274       $dbh->do($sqldrop.$_) if exists $a->{$_};
4275     }
4276     #Remove obsolete column from aqbudgets if needed
4277     #The correct column is budget_notes
4278     $a = $dbh->selectall_hashref('SHOW columns from aqbudgets','Field');
4279     if(exists $a->{budget_description}) {
4280       $dbh->do("ALTER TABLE aqbudgets DROP COLUMN budget_description");
4281     }
4282     print "Upgrade to $DBversion done (Remove obsolete columns from aqbooksellers and aqbudgets if needed)\n";
4283     SetVersion ($DBversion);
4284 }
4285
4286 $DBversion = "3.03.00.046";
4287 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4288     $dbh->do("ALTER TABLE overduerules ALTER delay1 SET DEFAULT NULL, ALTER delay2 SET DEFAULT NULL, ALTER delay3 SET DEFAULT NULL");
4289     print "Upgrade to $DBversion done (Setting NULL default value for delayn columns in table overduerules)\n";
4290     SetVersion($DBversion);
4291 }
4292
4293 $DBversion = '3.03.00.047';
4294 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4295     $dbh->do("ALTER TABLE borrowers ADD `state` mediumtext AFTER city;");
4296     $dbh->do("ALTER TABLE borrowers ADD `B_state` mediumtext AFTER B_city;");
4297     $dbh->do("ALTER TABLE borrowers ADD `altcontactstate` mediumtext AFTER altcontactaddress3;");
4298     $dbh->do("ALTER TABLE deletedborrowers ADD `state` mediumtext AFTER city;");
4299     $dbh->do("ALTER TABLE deletedborrowers ADD `B_state` mediumtext AFTER B_city;");
4300     $dbh->do("ALTER TABLE deletedborrowers ADD `altcontactstate` mediumtext AFTER altcontactaddress3;");
4301     print "Upgrade to $DBversion done (Add state field to patron's addresses)\n";
4302 }
4303
4304 $DBversion = '3.03.00.048';
4305 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4306     $dbh->do("ALTER TABLE branches ADD `branchstate` mediumtext AFTER `branchcity`;");
4307     print "Upgrade to $DBversion done (Add state to branch address)\n";
4308     SetVersion ($DBversion);
4309 }
4310
4311 $DBversion = '3.03.00.049';
4312 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4313     $dbh->do("ALTER TABLE `accountlines` ADD `note` text NULL default NULL");
4314     $dbh->do("ALTER TABLE `accountlines` ADD `manager_id` int( 11 ) NULL ");
4315     print "Upgrade to $DBversion done (adding note and manager_id fields in accountlines table)\n";
4316     SetVersion($DBversion);
4317 }
4318
4319 $DBversion = "3.03.00.050";
4320 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4321     $dbh->do("
4322         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');
4323         ");
4324     print "Upgrade to $DBversion done (Adding OpacHiddenItems syspref)\n";
4325     SetVersion($DBversion);
4326 }
4327
4328 $DBversion = "3.03.00.051";
4329 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4330     print "Upgrade to $DBversion done (Remove spaces and dashes from message_attribute names)\n";
4331     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Due' WHERE message_name='Item Due'");
4332     $dbh->do("UPDATE message_attributes SET message_name = 'Advance_Notice' WHERE message_name='Advance Notice'");
4333     $dbh->do("UPDATE message_attributes SET message_name = 'Hold_Filled' WHERE message_name='Hold Filled'");
4334     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Check_in' WHERE message_name='Item Check-in'");
4335     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Checkout' WHERE message_name='Item Checkout'");
4336     SetVersion ($DBversion);
4337 }
4338
4339 $DBversion = "3.03.00.052";
4340 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4341     $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');");
4342     print "Upgrade to $DBversion done (Add syspref WaitingNotifyAtCheckin)\n";
4343     SetVersion ($DBversion);
4344 }
4345
4346 $DBversion = "3.04.00.000";
4347 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4348     print "Upgrade to $DBversion done Koha 3.4.0 release \n";
4349     SetVersion ($DBversion);
4350 }
4351
4352 $DBversion = "3.05.00.001";
4353 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4354     $dbh->do(qq{
4355     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');
4356     });
4357     print "Upgrade to $DBversion done (Adds New System preference numSearchRSSResults)\n";
4358     SetVersion($DBversion);
4359 }
4360
4361 $DBversion = '3.05.00.002';
4362 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4363     #follow up fix 5860: some installs already past 3.3.0.42
4364     stocknumber_checker();
4365     print "Upgrade to $DBversion done (Fix for stocknumber index)\n";
4366     SetVersion ($DBversion);
4367 }
4368
4369 $DBversion = "3.05.00.003";
4370 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4371     $dbh->do(qq{
4372     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');
4373     });
4374     print "Upgrade to $DBversion done (Adds New System preference OpacRenewalBranch)\n";
4375     SetVersion($DBversion);
4376 }
4377
4378 $DBversion = "3.05.00.004";
4379 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4380     $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');");
4381     print "Upgrade to $DBversion done (Add syspref ShowReviewerPhoto)\n";
4382     SetVersion($DBversion);
4383 }
4384
4385 $DBversion = "3.05.00.005";
4386 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4387     $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');");
4388     print "Upgrade to $DBversion done (Adds pref BasketConfirmations)\n";
4389     SetVersion($DBversion);
4390 }
4391
4392 $DBversion = "3.05.00.006";
4393 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4394     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('MARCAuthorityControlField008', '|| aca||aabn           | a|a     d', NULL, NULL, 'Textarea')");
4395     print "Upgrade to $DBversion done (Add syspref MARCAuthorityControlField008)\n";
4396     SetVersion ($DBversion);
4397 }
4398
4399 $DBversion = "3.05.00.007";
4400 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4401     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpenLibraryCovers',0,'If ON Openlibrary book covers will be show',NULL,'YesNo');");
4402     print "Upgrade to $DBversion done (Add syspref OpenLibraryCovers)\n";
4403     SetVersion($DBversion);
4404 }
4405
4406 $DBversion = "3.05.00.008";
4407 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4408     $dbh->do("ALTER TABLE `cities` ADD `city_state` VARCHAR( 100 ) NULL DEFAULT NULL AFTER  `city_name`;");
4409     $dbh->do("ALTER TABLE `cities` ADD `city_country` VARCHAR( 100 ) NULL DEFAULT NULL AFTER  `city_zipcode`;");
4410     print "Add state and country to cities table corresponding to new columns in borrowers\n";
4411     SetVersion($DBversion);
4412 }
4413
4414 $DBversion = "3.05.00.009";
4415 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4416     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4417               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE borrowernumber IS NULL");
4418     $dbh->do("DELETE FROM issues WHERE borrowernumber IS NULL");
4419
4420     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4421               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE itemnumber IS NULL");
4422     $dbh->do("DELETE FROM issues WHERE itemnumber IS NULL");
4423
4424     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4425               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)");
4426     $dbh->do("DELETE FROM issues WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowernumber = issues.borrowernumber)");
4427
4428     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4429               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)");
4430     $dbh->do("DELETE FROM issues WHERE NOT EXISTS (SELECT * FROM items WHERE itemnumber = issues.itemnumber)");
4431
4432     $dbh->do("ALTER TABLE issues DROP FOREIGN KEY `issues_ibfk_1`");
4433     $dbh->do("ALTER TABLE issues DROP FOREIGN KEY `issues_ibfk_2`");
4434     $dbh->do("ALTER TABLE issues ALTER COLUMN borrowernumber DROP DEFAULT");
4435     $dbh->do("ALTER TABLE issues ALTER COLUMN itemnumber DROP DEFAULT");
4436     $dbh->do("ALTER TABLE issues MODIFY COLUMN borrowernumber int(11) NOT NULL");
4437     $dbh->do("ALTER TABLE issues MODIFY COLUMN itemnumber int(11) NOT NULL");
4438     $dbh->do("ALTER TABLE issues DROP KEY `issuesitemidx`");
4439     $dbh->do("ALTER TABLE issues ADD PRIMARY KEY (`itemnumber`)");
4440     $dbh->do("ALTER TABLE issues ADD CONSTRAINT `issues_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE RESTRICT ON UPDATE CASCADE");
4441     $dbh->do("ALTER TABLE issues ADD CONSTRAINT `issues_ibfk_2` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE RESTRICT ON UPDATE CASCADE");
4442
4443     print "Upgrade to $DBversion done (issues referential integrity)\n";
4444     SetVersion ($DBversion);
4445 }
4446
4447 $DBversion = "3.05.00.010";
4448 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4449     $dbh->do("CREATE INDEX priorityfoundidx ON reserves (priority,found)");
4450     print "Create an index on reserves to speed up holds awaiting pickup report bug 5866\n";
4451     SetVersion($DBversion);
4452 }
4453
4454
4455 $DBversion = "3.05.00.011";
4456 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4457     $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')");
4458     print "Upgrade to $DBversion done (add OPACResultsSidebar syspref (enh 6165))\n";
4459     SetVersion($DBversion);
4460 }
4461
4462 $DBversion = "3.05.00.012";
4463 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4464     $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')");
4465     print "Upgrade to $DBversion done (add RecordLocalUseOnReturn syspref (enh 6403))\n";
4466     SetVersion($DBversion);
4467 }
4468
4469 $DBversion = "3.05.00.013";
4470 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4471     $dbh->do(qq|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OpacKohaUrl','0',"Show 'Powered by Koha' text on OPAC footer.",NULL,NULL)|);
4472     print "Upgrade to $DBversion done (Add syspref 'OpacKohaUrl')\n";
4473     SetVersion($DBversion);
4474 }
4475
4476 $DBversion = "3.05.00.014";
4477 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4478     $dbh->do("ALTER TABLE `borrowers` MODIFY `userid` VARCHAR(75)");
4479     print "Modified userid column length into 75 in borrowers\n";
4480     SetVersion($DBversion);
4481 }
4482
4483 $DBversion = "3.05.00.015";
4484 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4485     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectEnabled',0,'Enable Novelist Select content.  Requires Novelist Profile and Password',NULL,'YesNo')");
4486     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectProfile',NULL,'Novelist Select user Password',NULL,'free')");
4487     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectPassword',NULL,'Enable Novelist user Profile',NULL,'free')");
4488     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectView','tab','Where to display Novelist Select content','tab|above|below|right','Choice')");
4489     print "Upgrade to $DBversion done (Add support for EBSCO's NoveList Select (enh 6902))\n";
4490     SetVersion($DBversion);
4491 }
4492
4493 $DBversion = '3.05.00.016';
4494 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4495     $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');");
4496     print "Upgrade to $DBversion done (Add EasyAnalyticalRecords syspref)\n";
4497     SetVersion ($DBversion);
4498 }
4499
4500 $DBversion = '3.05.00.017';
4501 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4502     if (C4::Context->preference("marcflavour") eq 'MARC21' ||
4503         C4::Context->preference("marcflavour") eq 'NORMARC'){
4504         $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)");
4505         $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)");
4506         print "Upgrade to $DBversion done (Add 773 subfield 9 and 0 to default framework)\n";
4507         SetVersion ($DBversion);
4508     } elsif (C4::Context->preference("marcflavour") eq 'UNIMARC'){
4509         $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)");
4510         print "Upgrade to $DBversion done (Add 461 subfield 9 to default framework)\n";
4511         SetVersion ($DBversion);
4512     }
4513 }
4514
4515 $DBversion = "3.05.00.018";
4516 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4517     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacNavBottom','','Links after OpacNav links','70|10','Textarea')");
4518     print "Upgrade to $DBversion done (add OpacNavBottom syspref (enh 6825): if appropriate, you can split OpacNav into OpacNav and OpacNavBottom)\n";
4519     SetVersion($DBversion);
4520 }
4521
4522 $DBversion = "3.05.00.019";
4523 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4524     $dbh->do("UPDATE itemtypes SET imageurl = 'vokal/Book.png' WHERE imageurl = 'vokal/BOOK.png'");
4525     $dbh->do("UPDATE itemtypes SET imageurl = 'vokal/Book-32px.png' WHERE imageurl = 'vokal/BOOK-32px.png'");
4526     $dbh->do("UPDATE authorised_values SET imageurl = 'vokal/Book.png' WHERE imageurl = 'vokal/BOOK.png'");
4527     $dbh->do("UPDATE authorised_values SET imageurl = 'vokal/Book-32px.png' WHERE imageurl = 'vokal/BOOK-32px.png'");
4528     print "Upgrade to $DBversion done (remove duplicate VOKAL Book icons, bug 6862)\n";
4529     SetVersion($DBversion);
4530 }
4531
4532 $DBversion = "3.05.00.020";
4533 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4534     $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')");
4535     print "Upgrade to $DBversion done (Add syspref AcqViewBaskets)\n";
4536     SetVersion($DBversion);
4537 }
4538
4539 $DBversion = "3.05.00.021";
4540 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4541     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN display_checkout TINYINT(1) NOT NULL DEFAULT '0';");
4542     print "Upgrade to $DBversion done (Added a display_checkout field in borrower_attribute_types table)\n";
4543     SetVersion($DBversion);
4544 }
4545
4546 $DBversion = "3.05.00.022";
4547 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4548     $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");
4549     print "Upgrade to $DBversion done (6094: Fixing ModAuthority problems, add a need_merge_authorities table)\n";
4550     SetVersion($DBversion);
4551 }
4552
4553 $DBversion = "3.05.00.023";
4554 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4555     $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');");
4556     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";
4557     SetVersion($DBversion);
4558 }
4559
4560 $DBversion = "3.06.00.000";
4561 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4562     print "Upgrade to $DBversion done Koha 3.6.0 release \n";
4563     SetVersion ($DBversion);
4564 }
4565
4566 $DBversion = "3.07.00.001";
4567 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4568     my $borrowers = $dbh->selectcol_arrayref( "SELECT borrowernumber from borrowers where debarred =1;", { Columns => [1] } );
4569     $dbh->do("ALTER TABLE borrowers MODIFY debarred DATE DEFAULT NULL;");
4570     $dbh->do( "UPDATE borrowers set debarred='9999-12-31' where borrowernumber IN (" . join( ",", @$borrowers ) . ");" ) if ($borrowers and scalar(@$borrowers)>0);
4571     $dbh->do("ALTER TABLE borrowers ADD COLUMN debarredcomment VARCHAR(255) DEFAULT NULL AFTER debarred;");
4572     $dbh->do("ALTER TABLE deletedborrowers MODIFY debarred DATE DEFAULT NULL;");
4573     $dbh->do("ALTER TABLE deletedborrowers ADD COLUMN debarredcomment VARCHAR(255) DEFAULT NULL AFTER debarred;");
4574     print "Upgrade done (Change borrowers.debarred into Date )\n";
4575     SetVersion($DBversion);
4576 }
4577
4578 $DBversion = "3.07.00.002";
4579 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4580     sanitize_zero_date('borrowers', 'debarred');
4581     print "Setting NULL to debarred where 0000-00-00 is stored (bug 7272)\n";
4582     SetVersion($DBversion);
4583 }
4584
4585 $DBversion = "3.07.00.003";
4586 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4587     $dbh->do(" UPDATE `message_attributes` SET message_name='Item_Due' WHERE message_name='Item_DUE'");
4588     print "Updating message_name in message_attributes\n";
4589     SetVersion($DBversion);
4590 }
4591
4592 $DBversion = "3.07.00.004";
4593 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4594     $dbh->do("ALTER TABLE  `suggestions` ADD  `patronreason` TEXT NULL AFTER  `reason`");
4595     print "Upgrade to $DBversion done (Add column to suggestions table to store patrons' reasons for submitting a suggestion. )\n";
4596     SetVersion($DBversion);
4597 }
4598
4599 $DBversion = "3.07.00.005";
4600 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4601     $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')");
4602     print "Upgrade to $DBversion done (BorrowerUnwantedField syspref)\n";
4603     SetVersion ($DBversion);
4604 }
4605
4606 $DBversion = "3.07.00.006";
4607 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4608     $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');");
4609     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";
4610     SetVersion($DBversion);
4611 }
4612
4613 $DBversion = "3.07.00.007";
4614 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4615     $dbh->do("ALTER TABLE items MODIFY materials text;");
4616     print "Upgrade to $DBversion done alter items.material from varchar(10) to text \n";
4617     SetVersion($DBversion);
4618 }
4619
4620 $DBversion = '3.07.00.008';
4621 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4622     if (C4::Context->preference("marcflavour") eq 'MARC21') {
4623         if (C4::Context->preference("opaclanguages") eq "de") {
4624             $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, '');");
4625         } else {
4626             $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, '');");
4627         }
4628     }
4629     print "Upgrade to $DBversion done (add MARC21 field 545 to framework)\n";
4630     SetVersion ($DBversion);
4631 }
4632
4633 $DBversion = "3.07.00.009";
4634 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4635     $dbh->do("ALTER TABLE `aqorders` ADD COLUMN `claims_count` INT(11)  DEFAULT 0, ADD COLUMN `claimed_date` DATE  DEFAULT NULL AFTER `claims_count`");
4636     print "Upgrade to $DBversion done (Add claims_count and claimed_date fields in aqorders table)\n";
4637     SetVersion($DBversion);
4638 }
4639
4640 $DBversion = "3.07.00.010";
4641 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4642     $dbh->do(
4643         q|CREATE TABLE `biblioimages` (
4644           `imagenumber` int(11) NOT NULL AUTO_INCREMENT,
4645           `biblionumber` int(11) NOT NULL,
4646           `mimetype` varchar(15) NOT NULL,
4647           `imagefile` mediumblob NOT NULL,
4648           `thumbnail` mediumblob NOT NULL,
4649           PRIMARY KEY (`imagenumber`),
4650           CONSTRAINT `bibliocoverimage_fk1` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
4651           ) ENGINE=InnoDB DEFAULT CHARSET=utf8|
4652     );
4653     $dbh->do(
4654         q|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OPACLocalCoverImages','0','Display local cover images on OPAC search and details pages.','1','YesNo')|
4655         );
4656     $dbh->do(
4657         q|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('LocalCoverImages','0','Display local cover images on intranet search and details pages.','1','YesNo')|
4658         );
4659     $dbh->do(
4660         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')|
4661     );
4662     $dbh->do(
4663         q|INSERT INTO permissions (module_bit, code, description) VALUES (13, 'upload_local_cover_images', 'Upload local cover images')|
4664     );
4665     print "Upgrade to $DBversion done (Added support for local cover images)\n";
4666     SetVersion($DBversion);
4667 }
4668
4669 $DBversion = "3.07.00.011";
4670 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4671     $dbh->do(<<ENDOFRENEWAL);
4672     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');
4673 ENDOFRENEWAL
4674     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";
4675     SetVersion($DBversion);
4676 }
4677
4678 $DBversion = "3.07.00.012";
4679 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4680     $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')");
4681     print "Upgrade to $DBversion add 'AllowItemsOnHoldCheckout' syspref \n";
4682     SetVersion ($DBversion);
4683 }
4684
4685 $DBversion = "3.07.00.013";
4686 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4687     $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');");
4688     print "Upgrade to $DBversion done (Bug 7345: Add system preference OpacExportOptions.)\n";
4689     SetVersion ($DBversion);
4690 }
4691
4692 $DBversion = "3.07.00.014";
4693 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4694     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";
4695     SetVersion($DBversion);
4696 }
4697
4698 $DBversion = "3.07.00.015";
4699 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4700     my $sth = $dbh->prepare(q|
4701         SELECT COUNT(*) FROM marc_subfield_structure where kohafield="biblioitems.editionstatement"
4702         |);
4703     $sth->execute;
4704     my $already_exists = $sth->fetchrow;
4705     if ( not $already_exists ) {
4706         my $field = C4::Context->preference("marcflavour") eq "UNIMARC" ? "205" : "250";
4707         my $subfield = "a";
4708         my $sth = $dbh->prepare( q|
4709             UPDATE marc_subfield_structure SET kohafield = "biblioitems.editionstatement"
4710             WHERE tagfield = ? AND tagsubfield = ?
4711         |);
4712         $sth->execute( $field, $subfield );
4713         print "Upgrade to $DBversion done (Added a mapping for biblioitems.editionstatement.)\n";
4714     } else {
4715         print "Upgrade to $DBversion done (Added a mapping for biblioitems.editionstatement (already exists, nothing to do).)\n";
4716     }
4717     SetVersion($DBversion);
4718 }
4719
4720 $DBversion = "3.07.00.016";
4721 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4722     $dbh->do("ALTER TABLE items ADD KEY `itemcallnumber` (itemcallnumber)");
4723     print "Upgrade to $DBversion done (Added index on items.itemcallnumber)\n";
4724     SetVersion($DBversion);
4725 }
4726
4727 $DBversion = "3.07.00.017";
4728 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4729     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('TransferWhenCancelAllWaitingHolds','0','Transfer items when cancelling all waiting holds',NULL,'YesNo')");
4730     print "Upgrade to $DBversion done (Add sysprefs to control transfer when cancel all waiting holds)\n";
4731     SetVersion ($DBversion);
4732 }
4733
4734 $DBversion = "3.07.00.018";
4735 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4736     $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;");
4737     print "Upgrade to $DBversion done ( adding offline operations table )\n";
4738     SetVersion($DBversion);
4739 }
4740
4741 $DBversion = "3.07.00.019";
4742 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4743     $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");
4744     $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");
4745     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";
4746     SetVersion($DBversion);
4747 }
4748
4749 $DBversion = "3.07.00.020";
4750 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4751     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OPACpatronimages',0,'Enable patron images in the OPAC',NULL,'YesNo');");
4752     print "Upgrade to $DBversion done (Bug 3516: Add the option to show patron images in the OPAC.)\n";
4753     SetVersion($DBversion);
4754 }
4755
4756 $DBversion = "3.07.00.021";
4757 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4758     $dbh->do(
4759     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('LinkerModule','Default','Chooses which linker module to use (see documentation).','Default|FirstMatchLastMatch','Choice');"
4760     );
4761     $dbh->do(
4762     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('LinkerOptions','','A pipe-separated list of options for the linker.','','free');"
4763     );
4764     $dbh->do(
4765     "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');"
4766     );
4767     $dbh->do(
4768     "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');"
4769     );
4770     $dbh->do(
4771     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AutoCreateAuthorities',0,'Automatically create authorities that do not exist when cataloging records.',NULL,'YesNo');"
4772     );
4773     $dbh->do(
4774     "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');"
4775     );
4776     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";
4777     SetVersion($DBversion);
4778 }
4779
4780 $DBversion = "3.07.00.022";
4781 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4782     $dbh->do("DELETE FROM reviews WHERE biblionumber NOT IN (SELECT biblionumber from biblio)");
4783     $dbh->do("UPDATE reviews SET borrowernumber = NULL WHERE borrowernumber NOT IN (SELECT borrowernumber FROM borrowers)");
4784     $dbh->do("ALTER TABLE reviews ADD CONSTRAINT reviews_ibfk_2 FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE");
4785     $dbh->do("ALTER TABLE reviews ADD CONSTRAINT reviews_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber ) ON UPDATE CASCADE ON DELETE SET NULL");
4786     print "Upgrade to $DBversion done (Bug 7493 - Add constraint linking OPAC comment biblionumber to biblio, OPAC comment borrowernumber to borrowers.)\n";
4787     SetVersion($DBversion);
4788 }
4789
4790 $DBversion = "3.07.00.023";
4791 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4792     $dbh->do("ALTER TABLE `message_transports` DROP FOREIGN KEY `message_transports_ibfk_3`");
4793     $dbh->do("ALTER TABLE `letter` DROP PRIMARY KEY");
4794     $dbh->do("ALTER TABLE `letter` ADD `branchcode` varchar(10) default NULL AFTER `code`");
4795     $dbh->do("ALTER TABLE `letter` ADD PRIMARY KEY  (`module`,`code`, `branchcode`)");
4796     $dbh->do("ALTER TABLE `message_transports` ADD `branchcode` varchar(10) NOT NULL default ''");
4797     $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");
4798     $dbh->do("ALTER TABLE `letter` ADD `is_html` tinyint(1) default 0 AFTER `name`");
4799
4800     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4801               VALUES ('circulation','ISSUESLIP','Issue Slip','Issue Slip', '<h3><<branches.branchname>></h3>
4802 Checked out to <<borrowers.title>> <<borrowers.firstname>> <<borrowers.initials>> <<borrowers.surname>> <br />
4803 (<<borrowers.cardnumber>>) <br />
4804
4805 <<today>><br />
4806
4807 <h4>Checked Out</h4>
4808 <checkedout>
4809 <p>
4810 <<biblio.title>> <br />
4811 Barcode: <<items.barcode>><br />
4812 Date due: <<issues.date_due>><br />
4813 </p>
4814 </checkedout>
4815
4816 <h4>Overdues</h4>
4817 <overdue>
4818 <p>
4819 <<biblio.title>> <br />
4820 Barcode: <<items.barcode>><br />
4821 Date due: <<issues.date_due>><br />
4822 </p>
4823 </overdue>
4824
4825 <hr>
4826
4827 <h4 style=\"text-align: center; font-style:italic;\">News</h4>
4828 <news>
4829 <div class=\"newsitem\">
4830 <h5 style=\"margin-bottom: 1px; margin-top: 1px\"><b><<opac_news.title>></b></h5>
4831 <p style=\"margin-bottom: 1px; margin-top: 1px\"><<opac_news.new>></p>
4832 <p class=\"newsfooter\" style=\"font-size: 8pt; font-style:italic; margin-bottom: 1px; margin-top: 1px\">Posted on <<opac_news.timestamp>></p>
4833 <hr />
4834 </div>
4835 </news>', 1)");
4836     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4837               VALUES ('circulation','ISSUEQSLIP','Issue Quick Slip','Issue Quick Slip', '<h3><<branches.branchname>></h3>
4838 Checked out to <<borrowers.title>> <<borrowers.firstname>> <<borrowers.initials>> <<borrowers.surname>> <br />
4839 (<<borrowers.cardnumber>>) <br />
4840
4841 <<today>><br />
4842
4843 <h4>Checked Out Today</h4>
4844 <checkedout>
4845 <p>
4846 <<biblio.title>> <br />
4847 Barcode: <<items.barcode>><br />
4848 Date due: <<issues.date_due>><br />
4849 </p>
4850 </checkedout>', 1)");
4851     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4852               VALUES ('circulation','RESERVESLIP','Reserve Slip','Reserve Slip', '<h5>Date: <<today>></h5>
4853
4854 <h3> Transfer to/Hold in <<branches.branchname>></h3>
4855
4856 <h3><<borrowers.surname>>, <<borrowers.firstname>></h3>
4857
4858 <ul>
4859     <li><<borrowers.cardnumber>></li>
4860     <li><<borrowers.phone>></li>
4861     <li> <<borrowers.address>><br />
4862          <<borrowers.address2>><br />
4863          <<borrowers.city >>  <<borrowers.zipcode>>
4864     </li>
4865     <li><<borrowers.email>></li>
4866 </ul>
4867 <br />
4868 <h3>ITEM ON HOLD</h3>
4869 <h4><<biblio.title>></h4>
4870 <h5><<biblio.author>></h5>
4871 <ul>
4872    <li><<items.barcode>></li>
4873    <li><<items.itemcallnumber>></li>
4874    <li><<reserves.waitingdate>></li>
4875 </ul>
4876 <p>Notes:
4877 <pre><<reserves.reservenotes>></pre>
4878 </p>', 1)");
4879     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4880               VALUES ('circulation','TRANSFERSLIP','Transfer Slip','Transfer Slip', '<h5>Date: <<today>></h5>
4881 <h3>Transfer to <<branches.branchname>></h3>
4882
4883 <h3>ITEM</h3>
4884 <h4><<biblio.title>></h4>
4885 <h5><<biblio.author>></h5>
4886 <ul>
4887    <li><<items.barcode>></li>
4888    <li><<items.itemcallnumber>></li>
4889 </ul>', 1)");
4890
4891     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('NoticeCSS','','Notices CSS url.',NULL,'free')");
4892     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('SlipCSS','','Slips CSS url.',NULL,'free')");
4893
4894     $dbh->do("UPDATE `letter` SET content = replace(content, '<<title>>', '<<biblio.title>>') WHERE code = 'HOLDPLACED'");
4895
4896     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";
4897     SetVersion($DBversion);
4898 }
4899
4900 $DBversion = "3.07.00.024";
4901 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4902     $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')");
4903     $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')");
4904     print "Upgrade to $DBversion done (Added system preference ExpireReservesMaxPickUpDelay, system preference ExpireReservesMaxPickUpDelayCharge, add reseves.charge_if_expired)\n";
4905 }
4906
4907 $DBversion = "3.07.00.025";
4908 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4909     if (TableExists('bibliocoverimage')) {
4910         $dbh->do( q|DROP TABLE bibliocoverimage;| );
4911         $dbh->do(
4912             q|CREATE TABLE biblioimages (
4913               imagenumber int(11) NOT NULL AUTO_INCREMENT,
4914               biblionumber int(11) NOT NULL,
4915               mimetype varchar(15) NOT NULL,
4916               imagefile mediumblob NOT NULL,
4917               thumbnail mediumblob NOT NULL,
4918               PRIMARY KEY (imagenumber),
4919               CONSTRAINT bibliocoverimage_fk1 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
4920               ) ENGINE=InnoDB DEFAULT CHARSET=utf8;|
4921         );
4922     }
4923     print "Upgrade to $DBversion done (Correct table name for local cover images if needed. )\n";
4924     SetVersion($DBversion);
4925 }
4926
4927 $DBversion = "3.07.00.026";
4928 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4929     $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');");
4930     print "Upgrade to $DBversion done (Add syspref CalendarFirstDayOfWeek used to select the first day of week to use in the calendar. )\n";
4931     SetVersion($DBversion);
4932 }
4933
4934 $DBversion = "3.07.00.027";
4935 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4936     $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');});
4937     print "Upgrade to $DBversion done (Added system preference RoutingListNote for adding a general note to all routing lists.)\n";
4938     SetVersion($DBversion);
4939 }
4940
4941 $DBversion = "3.07.00.028";
4942 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4943     $dbh->do(qq{
4944     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');
4945     });
4946     print "Upgrade to $DBversion done (Bug 6296 New System preference AllowPKIAuth)\n";
4947 }
4948
4949 $DBversion = "3.07.00.029";
4950 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4951     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_descriptions`;});
4952     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_mappings`;});
4953     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_biblios`;});
4954     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets`;});
4955
4956     $dbh->do(q{
4957         CREATE TABLE `oai_sets` (
4958           `id` int(11) NOT NULL auto_increment,
4959           `spec` varchar(80) NOT NULL UNIQUE,
4960           `name` varchar(80) NOT NULL,
4961           PRIMARY KEY (`id`)
4962         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4963     });
4964
4965     $dbh->do(q{
4966         CREATE TABLE `oai_sets_descriptions` (
4967           `set_id` int(11) NOT NULL,
4968           `description` varchar(255) NOT NULL,
4969           CONSTRAINT `oai_sets_descriptions_ibfk_1` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4970         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4971     });
4972
4973     $dbh->do(q{
4974         CREATE TABLE `oai_sets_mappings` (
4975           `set_id` int(11) NOT NULL,
4976           `marcfield` char(3) NOT NULL,
4977           `marcsubfield` char(1) NOT NULL,
4978           `marcvalue` varchar(80) NOT NULL,
4979           CONSTRAINT `oai_sets_mappings_ibfk_1` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4980         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4981     });
4982
4983     $dbh->do(q{
4984         CREATE TABLE `oai_sets_biblios` (
4985           `biblionumber` int(11) NOT NULL,
4986           `set_id` int(11) NOT NULL,
4987           PRIMARY KEY (`biblionumber`, `set_id`),
4988           CONSTRAINT `oai_sets_biblios_ibfk_1` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
4989           CONSTRAINT `oai_sets_biblios_ibfk_2` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4990         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4991     });
4992
4993     $dbh->do(q{
4994         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');
4995     });
4996
4997     print "Upgrade to $DBversion done (Atomic update for OAI-PMH sets management)\n";
4998     SetVersion($DBversion);
4999 }
5000
5001 $DBversion = "3.07.00.030";
5002 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5003     $dbh->do("ALTER TABLE default_circ_rules ADD
5004             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5005     $dbh->do("ALTER TABLE branch_item_rules ADD
5006             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5007     $dbh->do("ALTER TABLE default_branch_circ_rules ADD
5008             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5009     $dbh->do("ALTER TABLE default_branch_item_rules ADD
5010             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5011     # set the default rule to the current value of HomeOrHoldingBranchReturn (default to 'homebranch' if need be)
5012     my $homeorholdingbranchreturn = C4::Context->preference('HomeOrHoldingBranchReturn') || 'homebranch';
5013     $dbh->do("UPDATE default_circ_rules SET returnbranch = '$homeorholdingbranchreturn'");
5014     print "Upgrade to $DBversion done (Atomic update for OAI-PMH sets management)\n";
5015     SetVersion($DBversion);
5016 }
5017
5018 $DBversion = "3.07.00.031";
5019 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5020     $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')");
5021     print "Upgrade to $DBversion done (Add syspref to tell Koha if ICU indexing is in use for Zebra or not.)\n";
5022     SetVersion ($DBversion);
5023 }
5024
5025 $DBversion = "3.07.00.032";
5026 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5027     $dbh->do("ALTER TABLE virtualshelves MODIFY COLUMN owner int"); #should have been int already (fk to borrowers)
5028     $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
5029     $dbh->do("DELETE FROM virtualshelves WHERE owner IS NULL and category=1"); #delete private lists without owner (cascades to shelfcontents)
5030     $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");
5031     $dbh->do("UPDATE virtualshelves SET allow_add=0, allow_delete_own=1, allow_delete_other=0 WHERE category=1");
5032     $dbh->do("UPDATE virtualshelves SET allow_add=0, allow_delete_own=1, allow_delete_other=0 WHERE category=2");
5033     $dbh->do("UPDATE virtualshelves SET allow_add=1, allow_delete_own=1, allow_delete_other=1 WHERE category=3");
5034     $dbh->do("UPDATE virtualshelves SET category=2 WHERE category=3");
5035
5036     $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");
5037     $dbh->do("UPDATE virtualshelfcontents co LEFT JOIN virtualshelves sh USING (shelfnumber) SET co.borrowernumber=sh.owner");
5038
5039     $dbh->do("CREATE TABLE virtualshelfshares
5040     (id int AUTO_INCREMENT PRIMARY KEY, shelfnumber int NOT NULL,
5041     borrowernumber int, invitekey varchar(10), sharedate datetime,
5042     CONSTRAINT `virtualshelfshares_ibfk_1` FOREIGN KEY (`shelfnumber`) REFERENCES `virtualshelves` (`shelfnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
5043         CONSTRAINT `virtualshelfshares_ibfk_2` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE SET NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8");
5044
5045     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacAllowPublicListCreation',1,'If set, allows opac users to create public lists',NULL,'YesNo');");
5046     $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');");
5047
5048     print "Upgrade to $DBversion done (BZ7310: Improving list permissions)\n";
5049     SetVersion($DBversion);
5050 }
5051
5052 $DBversion = "3.07.00.033";
5053 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5054     $dbh->do("ALTER TABLE branches ADD opac_info text;");
5055     print "Upgrade to $DBversion done add opac_info to branches \n";
5056     SetVersion($DBversion);
5057 }
5058
5059 $DBversion = "3.07.00.034";
5060 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5061     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN category_code VARCHAR(10) NULL DEFAULT NULL AFTER `display_checkout`");
5062     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN class VARCHAR(255)  NOT NULL DEFAULT '' AFTER `category_code`");
5063     $dbh->do("ALTER TABLE borrower_attribute_types ADD CONSTRAINT category_code_fk FOREIGN KEY (category_code) REFERENCES categories(categorycode)");
5064     print "Upgrade to $DBversion done (New fields category_code and class in borrower_attribute_types table)\n";
5065     SetVersion($DBversion);
5066 }
5067
5068 $DBversion = "3.07.00.035";
5069 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5070     $dbh->do("ALTER TABLE issues CHANGE date_due date_due datetime");
5071     $dbh->do("UPDATE issues SET date_due = CONCAT(SUBSTR(date_due,1,11),'23:59:00')");
5072     $dbh->do("ALTER TABLE issues CHANGE returndate returndate datetime");
5073     $dbh->do("ALTER TABLE issues CHANGE lastreneweddate lastreneweddate datetime");
5074     $dbh->do("ALTER TABLE issues CHANGE issuedate issuedate datetime");
5075     $dbh->do("ALTER TABLE old_issues CHANGE date_due date_due datetime");
5076     $dbh->do("ALTER TABLE old_issues CHANGE returndate returndate datetime");
5077     $dbh->do("ALTER TABLE old_issues CHANGE lastreneweddate lastreneweddate datetime");
5078     $dbh->do("ALTER TABLE old_issues CHANGE issuedate issuedate datetime");
5079     $dbh->do("UPDATE accountlines SET description = CONCAT(description,' 23:59') WHERE accounttype='F' OR accounttype='FU'"); #BUG-8253
5080     print "Upgrade to $DBversion done (Setting up issues and accountlines tables for hourly loans)\n";
5081     SetVersion($DBversion);
5082 }
5083
5084 $DBversion = "3.07.00.036";
5085 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5086     $dbh->do(qq{
5087        ALTER TABLE z3950servers ADD timeout INT( 11 ) NOT NULL DEFAULT '0' AFTER syntax;
5088     });
5089     print "Upgrade to $DBversion done (New timeout field in z3950servers)\n";
5090 }
5091
5092 $DBversion = "3.07.00.037";
5093 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5094     $dbh->do("
5095        ALTER TABLE  `marc_subfield_structure` ADD  `maxlength` INT( 4 ) NOT NULL DEFAULT  '9999';
5096        ");
5097        $dbh->do("
5098        UPDATE `marc_subfield_structure` SET maxlength=24 WHERE tagfield='000';
5099        ");
5100        $dbh->do("
5101        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='MARC21','40','9999') WHERE tagfield='008';
5102        ");
5103        $dbh->do("
5104        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='NORMARC','40','9999') WHERE tagfield='008';
5105        ");
5106        $dbh->do("
5107        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='UNIMARC','36','9999') WHERE tagfield='100';
5108        ");
5109     print "Upgrade to $DBversion done (Add new field maxlength to marc_subfield_structure)\n";
5110     SetVersion($DBversion);
5111 }
5112
5113 $DBversion = "3.07.00.038";
5114 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5115     $dbh->do(qq{
5116         INSERT INTO systempreferences(variable,value,explanation,options,type)
5117         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')
5118     });
5119     print "Upgrade to $DBversion done (Added system preference 'UniqueItemFields')\n";
5120     SetVersion($DBversion);
5121 }
5122
5123 $DBversion = "3.07.00.039";
5124 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5125     $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')} );
5126     $dbh->do( qq{CREATE TABLE IF NOT EXISTS social_data
5127       ( isbn VARCHAR(30),
5128         num_critics INT,
5129         num_critics_pro INT,
5130         num_quotations INT,
5131         num_videos INT,
5132         score_avg DECIMAL(5,2),
5133         num_scores INT,
5134         PRIMARY KEY  (isbn)
5135       ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5136     } );
5137     $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')} );
5138     print "Upgrade to $DBversion done (added syspref and table for babeltheque (Babeltheque_url_js, babeltheque))\n";
5139     SetVersion($DBversion);
5140 }
5141
5142 $DBversion = "3.07.00.040";
5143 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5144     $dbh->do( qq{INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('SocialNetworks','0','Enable/Disable social networks links in opac detail','','YesNo')} );
5145     print "Upgrade to $DBversion done (added syspref SocialNetworks, to display facebook/ggl+ and other buttons)\n";
5146     SetVersion($DBversion);
5147 }
5148
5149
5150
5151 $DBversion = "3.07.00.041";
5152 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5153     $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')");
5154     print "Upgrade to $DBversion done (Add system preference SubscriptionDuplicateDroppedInput)\n";
5155     SetVersion($DBversion);
5156 }
5157
5158 $DBversion = "3.07.00.042";
5159 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5160     $dbh->do("ALTER TABLE reserves ADD suspend BOOLEAN NOT NULL DEFAULT 0");
5161     $dbh->do("ALTER TABLE old_reserves ADD suspend BOOLEAN NOT NULL DEFAULT 0");
5162
5163     $dbh->do("ALTER TABLE reserves ADD suspend_until DATETIME NULL DEFAULT NULL");
5164     $dbh->do("ALTER TABLE old_reserves ADD suspend_until DATETIME NULL DEFAULT NULL");
5165
5166     $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')");
5167
5168     print "Upgrade to $DBversion done (Add suspend fields to reserves table, add syspref AutoResumeSuspendedHolds)\n";
5169     SetVersion ($DBversion);
5170 }
5171
5172 $DBversion = "3.07.00.043";
5173 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5174     my $countXSLTDetailsDisplay = 0;
5175     my $valueXSLTDetailsDisplay = "";
5176     my $valueXSLTResultsDisplay = "";
5177     my $valueOPACXSLTDetailsDisplay = "";
5178     my $valueOPACXSLTResultsDisplay = "";
5179     #the line below test if database comes from a BibLibre's branch
5180     $countXSLTDetailsDisplay = $dbh->do('SELECT 1 FROM systempreferences WHERE variable="IntranetXSLTDetailsDisplay"');
5181     if ($countXSLTDetailsDisplay > 0)
5182     {
5183         #the two lines below will only be used to update the databases from the BibLibre's branch. They will not affect the others
5184         $dbh->do(q|UPDATE systempreferences SET variable="XSLTDetailsDisplay" WHERE variable="IntranetXSLTDetailsDisplay"|);
5185         $dbh->do(q|UPDATE systempreferences SET variable="XSLTResultsDisplay" WHERE variable="IntranetXSLTResultsDisplay"|);
5186     }
5187     else
5188     {
5189         $valueXSLTDetailsDisplay = "default" if (C4::Context->preference("XSLTDetailsDisplay"));
5190         $valueXSLTResultsDisplay = "default" if (C4::Context->preference("XSLTResultsDisplay"));
5191         $valueOPACXSLTDetailsDisplay = "default" if (C4::Context->preference("OPACXSLTDetailsDisplay"));
5192         $valueOPACXSLTResultsDisplay = "default" if (C4::Context->preference("OPACXSLTResultsDisplay"));
5193         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueXSLTDetailsDisplay\" WHERE variable='XSLTDetailsDisplay'");
5194         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueXSLTResultsDisplay\" WHERE variable='XSLTResultsDisplay'");
5195         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueOPACXSLTDetailsDisplay\" WHERE variable='OPACXSLTDetailsDisplay'");
5196         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueOPACXSLTResultsDisplay\" WHERE variable='OPACXSLTResultsDisplay'");
5197     }
5198     print "Upgrade to $DBversion done (XSLT systempreference takes a path to file rather than YesNo)\n";
5199     SetVersion($DBversion);
5200 }
5201
5202 $DBversion = "3.07.00.044";
5203 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5204     $dbh->do("ALTER TABLE aqbooksellers ADD deliverytime INT DEFAULT NULL");
5205     print "Upgrade to $DBversion done (Add deliverytime field in aqbooksellers table)";
5206     SetVersion($DBversion);
5207 }
5208
5209 $DBversion = "3.07.00.045";
5210 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5211     $dbh->do("ALTER TABLE import_batches MODIFY COLUMN batch_type ENUM('batch','z3950','webservice') NOT NULL default 'batch'");
5212     print "Upgrade to $DBversion done (Add 'webservice' to batch_type enum)\n";
5213     SetVersion ($DBversion);
5214 }
5215
5216 $DBversion = "3.07.00.046";
5217 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5218     $dbh->do("ALTER TABLE issuingrules ADD COLUMN lengthunit varchar(10) DEFAULT 'days' AFTER issuelength");
5219     print "Upgrade to $DBversion done (Setting up issues tables for hourly loans (lengthunit fix))\n";
5220     SetVersion($DBversion);
5221 }
5222
5223 $DBversion = "3.07.00.047";
5224 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5225     $dbh->do("CREATE INDEX items_location ON items(location)");
5226     $dbh->do("CREATE INDEX items_ccode ON items(ccode)");
5227     print "Upgrade to $DBversion done (items_location and items_ccode indexes added for ShelfBrowser)\n";
5228     SetVersion($DBversion);
5229 }
5230
5231 $DBversion = "3.07.00.048";
5232 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5233     $dbh->do(
5234         q | CREATE TABLE ratings (
5235   borrowernumber int(11) NOT NULL,
5236   biblionumber int(11) NOT NULL,
5237   rating_value tinyint(1) NOT NULL,
5238   timestamp timestamp NOT NULL default CURRENT_TIMESTAMP,
5239   PRIMARY KEY  (borrowernumber,biblionumber),
5240   CONSTRAINT ratings_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE,
5241   CONSTRAINT ratings_ibfk_2 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
5242 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
5243     );
5244
5245     $dbh->do(
5246 q /INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OpacStarRatings','disable',NULL,'disable|all|details','Choice') /
5247     );
5248
5249     print
5250 "Upgrade to $DBversion done (Add 'ratings' table and 'OpacStarRatings' syspref)\n";
5251     SetVersion($DBversion);
5252 }
5253
5254 $DBversion = "3.07.00.049";
5255 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5256     $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')");
5257     print "Upgrade to $DBversion done (Add system preference OpacBrowseResults ))\n";
5258     SetVersion($DBversion);
5259 }
5260
5261 $DBversion = "3.08.00.000";
5262 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5263     print "Upgrade to $DBversion done\n";
5264     SetVersion($DBversion);
5265 }
5266
5267 $DBversion = "3.09.00.001";
5268 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5269     $dbh->do("ALTER TABLE borrower_attribute_types MODIFY category_code VARCHAR( 1 ) NULL DEFAULT NULL");
5270     print "Upgrade to $DBversion done. (Bug 8002: Update patron attribute types table to allow NULL category_code)\n";
5271     SetVersion($DBversion);
5272 }
5273
5274 $DBversion = "3.09.00.002";
5275 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5276     $dbh->do("ALTER TABLE saved_sql
5277         ADD (
5278             cache_expiry INT NOT NULL DEFAULT 300,
5279             public BOOLEAN NOT NULL DEFAULT FALSE
5280         );
5281     ");
5282     print "Upgrade to $DBversion done (Added cache_expiry and public fields in
5283 saved_reports table.)\n";
5284     SetVersion($DBversion);
5285 }
5286
5287 $DBversion = "3.09.00.003";
5288 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5289     $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');");
5290     print "Upgrade to $DBversion done (Added SvcMaxReportRows syspref)\n";
5291     SetVersion($DBversion);
5292 }
5293
5294 $DBversion = "3.09.00.004";
5295 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5296     $dbh->do("INSERT IGNORE INTO permissions (module_bit, code, description) VALUES('13', 'edit_patrons', 'Perform batch modifivation of patrons')");
5297     print "Upgrade to $DBversion done (Adds permissions flag for access to the patron modifications tool)\n";
5298     SetVersion($DBversion);
5299 }
5300
5301 $DBversion = "3.09.00.005";
5302 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5303     unless (TableExists('quotes')) {
5304         $dbh->do( qq{
5305             CREATE TABLE `quotes` (
5306               `id` int(11) NOT NULL AUTO_INCREMENT,
5307               `source` text DEFAULT NULL,
5308               `text` mediumtext NOT NULL,
5309               `timestamp` datetime NOT NULL,
5310               PRIMARY KEY (`id`)
5311             ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5312         });
5313     }
5314     $dbh->do( qq{
5315         INSERT IGNORE INTO permissions VALUES (13, "edit_quotes","Edit quotes for quote-of-the-day feature");
5316     });
5317     $dbh->do( qq{
5318         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');
5319     });
5320     print "Upgrade to $DBversion done (Adding Quote of the Day Option.)\n";
5321     SetVersion($DBversion);
5322 }
5323
5324 $DBversion = "3.09.00.006";
5325 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5326     $dbh->do("UPDATE systempreferences SET
5327                 variable = 'OPACShowHoldQueueDetails',
5328                 value = CASE value WHEN '1' THEN 'priority' ELSE 'none' END,
5329                 options = 'none|priority|holds|holds_priority',
5330                 explanation = 'Show holds details in OPAC',
5331                 type = 'Choice'
5332               WHERE variable = 'OPACDisplayRequestPriority'");
5333     print "Upgrade to $DBversion done (Changed system preference OPACDisplayRequestPriority -> OPACShowHoldQueueDetails)\n";
5334     SetVersion($DBversion);
5335 }
5336
5337 $DBversion = "3.09.00.007";
5338 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5339     unless(C4::Context->preference('ReservesControlBranch')){
5340         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('ReservesControlBranch','PatronLibrary','ItemHomeLibrary|PatronLibrary','Branch checked for members reservations rights.','Choice')");
5341     }
5342     print "Upgrade to $DBversion done (Insert ReservesControlBranch systempreference into systempreferences table )\n";
5343     SetVersion($DBversion);
5344 }
5345
5346 $DBversion = "3.09.00.008";
5347 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5348     $dbh->do("ALTER TABLE sessions ADD PRIMARY KEY (id);");
5349     $dbh->do("ALTER TABLE sessions DROP INDEX `id`;");
5350     print "Upgrade to $DBversion done (redefine the field id as PRIMARY KEY of sessions)\n";
5351     SetVersion($DBversion);
5352 }
5353
5354 $DBversion = "3.09.00.009";
5355 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5356     $dbh->do("ALTER TABLE branches ADD PRIMARY KEY (branchcode);");
5357     $dbh->do("ALTER TABLE branches DROP INDEX branchcode;");
5358     print "Upgrade to $DBversion done (redefine the field branchcode as PRIMARY KEY of branches)\n";
5359     SetVersion ($DBversion);
5360 }
5361
5362 $DBversion = "3.09.00.010";
5363 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5364     $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')");
5365     print "Upgrade to $DBversion done (Add system preference issuelostitem ))\n";
5366     SetVersion($DBversion);
5367 }
5368
5369 $DBversion = "3.09.00.011";
5370 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5371     $dbh->do("ALTER TABLE `biblioitems` ADD `ean` VARCHAR( 13 ) NULL AFTER issn");
5372     $dbh->do("CREATE INDEX `ean` ON biblioitems (`ean`) ");
5373     $dbh->do("ALTER TABLE `deletedbiblioitems` ADD `ean` VARCHAR( 13 ) NULL AFTER issn");
5374     if (C4::Context->preference("marcflavour") eq 'UNIMARC') {
5375          $dbh->do("UPDATE marc_subfield_structure SET kohafield='biblioitems.ean' WHERE tagfield='073' and tagsubfield='a'");
5376     }
5377     print "Upgrade to $DBversion done (Adding ean in biblioitems and deletedbiblioitems)\n";
5378     print "If you have records with ean, please run misc/batchRebuildBiblioTables.pl to populate bibliotems.ean\n" if (C4::Context->preference("marcflavour") eq 'UNIMARC');
5379     SetVersion($DBversion);
5380 }
5381
5382 $DBversion = "3.09.00.012";
5383 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5384     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('SuspendHoldsIntranet', '1', NULL , 'Allow holds to be suspended from the intranet.', 'YesNo')");
5385     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('SuspendHoldsOpac', '1', NULL , 'Allow holds to be suspended from the OPAC.', 'YesNo')");
5386     print "Upgrade to $DBversion done (Add system preference OpacBrowseResults ))\n";
5387     SetVersion($DBversion);
5388 }
5389
5390 $DBversion ="3.09.00.013";
5391 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5392     $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');");
5393     print "Upgrade to $DBversion done (Add system preference DefaultLanguageField008))\n";
5394     SetVersion($DBversion);
5395 }
5396
5397 $DBversion ="3.09.00.014";
5398 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5399     # add phone message transport type
5400     $dbh->do("INSERT INTO message_transport_types (message_transport_type) VALUES ('phone')");
5401
5402     # adds HOLD_PHONE and PREDUE_PHONE letters (as placeholders)
5403     $dbh->do("INSERT INTO letter (module, code, name, title, content) VALUES
5404               ('reserves', 'HOLD_PHONE', 'Item Available for Pick-up (phone notice)', 'Item Available for Pick-up (phone notice)', 'Your item is available for pickup'),
5405               ('circulation', 'PREDUE_PHONE', 'Advance Notice of Item Due (phone notice)', 'Advance Notice of Item Due (phone notice)', 'Your item is due soon'),
5406               ('circulation', 'OVERDUE_PHONE', 'Overdue Notice (phone notice)', 'Overdue Notice (phone notice)', 'Your item is overdue')
5407               ");
5408
5409     # add phone notifications to patron message preferences options
5410     $dbh->do("INSERT INTO message_transports
5411              (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) VALUES
5412              (4, 'phone', 0, 'reserves', 'HOLD_PHONE'),
5413              (2, 'phone', 0, 'circulation', 'PREDUE_PHONE')
5414              ");
5415
5416     # add TalkingTechItivaPhoneNotification syspref
5417     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('TalkingTechItivaPhoneNotification',0,'If ON, enables Talking Tech I-tiva phone notifications',NULL,'YesNo');");
5418
5419     print "Upgrade done (Support for Talking Tech i-tiva phone notification system)\n";
5420     SetVersion($DBversion);
5421 }
5422
5423 $DBversion = "3.09.00.015";
5424 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5425     $dbh->do(qq{
5426         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')
5427     });
5428     print "Upgrade to $DBversion done (Add System preference StatisticsFields)\n";
5429     SetVersion($DBversion);
5430 }
5431
5432 $DBversion = "3.09.00.016";
5433 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5434     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACShowBarcode','0','Show items barcode in holding tab','','YesNo')");
5435     print "Upgrade to $DBversion done (Add syspref OPACShowBarcode)\n";
5436     SetVersion ($DBversion);
5437 }
5438
5439 $DBversion = "3.09.00.017";
5440 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5441     $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');");
5442     print "Upgrade to $DBversion done (Add customizable OpacNavRight region to the OPAC main page)\n";
5443     SetVersion ($DBversion);
5444 }
5445
5446 $DBversion = "3.09.00.018";
5447 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5448     $dbh->do("DROP TABLE IF EXISTS aqbudgetborrowers");
5449     $dbh->do("
5450         CREATE TABLE aqbudgetborrowers (
5451           budget_id int(11) NOT NULL,
5452           borrowernumber int(11) NOT NULL,
5453           PRIMARY KEY (budget_id, borrowernumber),
5454           CONSTRAINT aqbudgetborrowers_ibfk_1 FOREIGN KEY (budget_id)
5455             REFERENCES aqbudgets (budget_id)
5456             ON DELETE CASCADE ON UPDATE CASCADE,
5457           CONSTRAINT aqbudgetborrowers_ibfk_2 FOREIGN KEY (borrowernumber)
5458             REFERENCES borrowers (borrowernumber)
5459             ON DELETE CASCADE ON UPDATE CASCADE
5460         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
5461     ");
5462     $dbh->do("
5463         INSERT INTO permissions (module_bit, code, description)
5464         VALUES (11, 'budget_manage_all', 'Manage all budgets')
5465     ");
5466     print "Upgrade to $DBversion done (Add aqbudgetborrowers table)\n";
5467     SetVersion($DBversion);
5468 }
5469
5470 $DBversion = "3.09.00.019";
5471 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5472     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('OPACShowUnusedAuthorities','1','','Show authorities that are not being used in the OPAC.','YesNo')");
5473     print "Upgrade to $DBversion done (Add OPACShowUnusedAuthorities system preference)\n";
5474     SetVersion ($DBversion);
5475 }
5476
5477 $DBversion = "3.09.00.020";
5478 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5479     $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')");
5480     $dbh->do("
5481 CREATE TABLE IF NOT EXISTS borrower_files (
5482   file_id int(11) NOT NULL AUTO_INCREMENT,
5483   borrowernumber int(11) NOT NULL,
5484   file_name varchar(255) NOT NULL,
5485   file_type varchar(255) NOT NULL,
5486   file_description varchar(255) DEFAULT NULL,
5487   file_content longblob NOT NULL,
5488   date_uploaded timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
5489   PRIMARY KEY (file_id),
5490   KEY borrowernumber (borrowernumber)
5491 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
5492     ");
5493     $dbh->do("ALTER TABLE borrower_files ADD CONSTRAINT borrower_files_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE");
5494
5495     print "Upgrade to $DBversion done (Added borrow_files table, EnableBorrowerFiles syspref)\n";
5496     SetVersion($DBversion);
5497 }
5498
5499 $DBversion = "3.09.00.021";
5500 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5501     $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');");
5502     print "Upgrade to $DBversion done (Add syspref UpdateTotalIssuesOnCirc)\n";
5503     SetVersion($DBversion);
5504 }
5505
5506 $DBversion = "3.09.00.022";
5507 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5508     $dbh->do("ALTER TABLE search_history MODIFY COLUMN query_cgi text NOT NULL");
5509     print "Upgrade to $DBversion done (Change search_history.query_cgi type to text. bug 5981)\n";
5510     SetVersion($DBversion);
5511 }
5512
5513 $DBversion = "3.09.00.023";
5514 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5515     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('SearchEngine','Zebra','Solr|Zebra','Search Engine','Choice')");
5516     print "Upgrade to $DBversion done (Add system preference SearchEngine )\n";
5517     SetVersion($DBversion);
5518 }
5519
5520 $DBversion ="3.09.00.024";
5521 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5522     $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')");
5523     print "Upgrade to $DBversion done (Add system preference IntranetSlipPrinterJS))\n";
5524     SetVersion($DBversion);
5525 }
5526
5527 $DBversion = "3.09.00.025";
5528 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5529     $dbh->do('START TRANSACTION');
5530     $dbh->do('CREATE TABLE tmp_reserves AS SELECT * FROM old_reserves LIMIT 0');
5531     $dbh->do('ALTER TABLE tmp_reserves ADD reserve_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
5532     $dbh->do("
5533         INSERT INTO tmp_reserves (
5534           borrowernumber, reservedate, biblionumber,
5535           constrainttype, branchcode, notificationdate,
5536           reminderdate, cancellationdate, reservenotes,
5537           priority, found, timestamp, itemnumber,
5538           waitingdate, expirationdate, lowestPriority,
5539           suspend, suspend_until
5540         ) SELECT
5541           borrowernumber, reservedate, biblionumber,
5542           constrainttype, branchcode, notificationdate,
5543           reminderdate, cancellationdate, reservenotes,
5544           priority, found, timestamp, itemnumber,
5545           waitingdate, expirationdate, lowestPriority,
5546           suspend, suspend_until
5547         FROM old_reserves ORDER BY reservedate
5548     ");
5549     $dbh->do('SET @ai = ( SELECT MAX( reserve_id ) FROM tmp_reserves )');
5550     $dbh->do('TRUNCATE old_reserves');
5551     $dbh->do('ALTER TABLE old_reserves ADD reserve_id INT( 11 ) NOT NULL PRIMARY KEY FIRST');
5552     $dbh->do('INSERT INTO old_reserves SELECT * FROM tmp_reserves WHERE reserve_id <= @ai');
5553     $dbh->do("
5554         INSERT INTO tmp_reserves (
5555           borrowernumber, reservedate, biblionumber,
5556           constrainttype, branchcode, notificationdate,
5557           reminderdate, cancellationdate, reservenotes,
5558           priority, found, timestamp, itemnumber,
5559           waitingdate, expirationdate, lowestPriority,
5560           suspend, suspend_until
5561         ) SELECT
5562           borrowernumber, reservedate, biblionumber,
5563           constrainttype, branchcode, notificationdate,
5564           reminderdate, cancellationdate, reservenotes,
5565           priority, found, timestamp, itemnumber,
5566           waitingdate, expirationdate, lowestPriority,
5567           suspend, suspend_until
5568         FROM reserves ORDER BY reservedate
5569     ");
5570     $dbh->do('TRUNCATE reserves');
5571     $dbh->do('ALTER TABLE reserves ADD reserve_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
5572     $dbh->do('INSERT INTO reserves SELECT * FROM tmp_reserves WHERE reserve_id > COALESCE(@ai, 0)');
5573     $dbh->do('DROP TABLE tmp_reserves');
5574     $dbh->do('COMMIT');
5575
5576     my $sth = $dbh->prepare("
5577         SELECT COUNT( * ) AS count
5578         FROM information_schema.COLUMNS
5579         WHERE COLUMN_NAME =  'reserve_id'
5580         AND (
5581           TABLE_NAME LIKE  'reserves'
5582           OR
5583           TABLE_NAME LIKE  'old_reserves'
5584         )
5585     ");
5586     $sth->execute();
5587     my $row = $sth->fetchrow_hashref();
5588     die("Failed to add reserve_id to reserves tables, please refresh the page to try again.") unless ( $row->{'count'} );
5589
5590     print "Upgrade to $DBversion done (add reserve_id to reserves & old_reserves tables)\n";
5591     SetVersion($DBversion);
5592 }
5593
5594 $DBversion = "3.09.00.026";
5595 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5596     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
5597         ( 3, 'parameters_remaining_permissions', 'Remaining system parameters permissions'),
5598         ( 3, 'manage_circ_rules', 'manage circulation rules')");
5599     $dbh->do("INSERT INTO user_permissions (borrowernumber, module_bit, code)
5600         SELECT borrowernumber, 3, 'parameters_remaining_permissions'
5601         FROM borrowers WHERE flags & (1 << 3)");
5602     # Give new subpermissions to all users that have 'parameters' permission flag (bit 3) set
5603     # see userflags table
5604     $dbh->do("INSERT INTO user_permissions (borrowernumber, module_bit, code)
5605         SELECT borrowernumber, 3, 'manage_circ_rules'
5606         FROM borrowers WHERE flags & (1 << 3)");
5607     print "Upgrade to $DBversion done (Added parameters subpermissions)\n";
5608     SetVersion($DBversion);
5609 }
5610
5611 $DBversion = '3.09.00.027';
5612 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5613     $dbh->do("ALTER TABLE issuingrules ADD overduefinescap decimal(28,6) DEFAULT NULL");
5614     my $maxfine = C4::Context->preference('MaxFine');
5615     if ($maxfine && $maxfine < 900) { # an arbitrary value that tells us it's not "some huge value"
5616       $dbh->do("UPDATE issuingrules SET overduefinescap=?",undef,$maxfine);
5617       $dbh->do("UPDATE systempreferences SET value = NULL WHERE variable = 'MaxFine'");
5618     }
5619     $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'");
5620     print "Upgrade to $DBversion done (Bug 7420 add overduefinescap to circulation matrix)\n";
5621     SetVersion ($DBversion);
5622 }
5623
5624 $DBversion = "3.09.00.028";
5625 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5626     unless ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) {
5627         my %referencetypes = (  '00' => 'PERSO_NAME',
5628                                 '10' => 'CORPO_NAME',
5629                                 '11' => 'MEETI_NAME',
5630                                 '30' => 'UNIF_TITLE',
5631                                 '48' => 'CHRON_TERM',
5632                                 '50' => 'TOPIC_TERM',
5633                                 '51' => 'GEOGR_NAME',
5634                                 '55' => 'GENRE/FORM'
5635                 );
5636         my $query = q{SELECT DISTINCT authtypecode, tagfield
5637                     FROM auth_subfield_structure
5638                     WHERE (tagfield BETWEEN '400' AND '455' OR
5639                     tagfield BETWEEN '500' and '555') AND tagsubfield='a' AND
5640                     frameworkcode = '' AND ROW(authtypecode, tagfield) NOT IN
5641                     (SELECT authtypecode, tagfield FROM auth_subfield_structure
5642                     WHERE tagsubfield ='9' )};
5643         $sth = $dbh->prepare($query);
5644         $sth->execute;
5645         my $sth2 = $dbh->prepare(q{INSERT INTO auth_subfield_structure
5646                 (authtypecode, tagfield, tagsubfield, liblibrarian, libopac,
5647                  repeatable, mandatory, tab, authorised_value, value_builder,
5648                  seealso, isurl, hidden, linkid, kohafield, frameworkcode)
5649                 VALUES (?, ?, '9', '9 (RLIN)', '9 (RLIN)', 0, 0, ?, NULL, NULL,
5650                     NULL, 0, 1, '', '', '')});
5651         my $sth3 = $dbh->prepare(q{UPDATE auth_subfield_structure SET
5652                                     frameworkcode = ? WHERE authtypecode = ? AND
5653                                     tagfield = ? AND tagsubfield = 'a'});
5654         while (my $row = $sth->fetchrow_arrayref()) {
5655             my ($authtypecode, $field) = @$row;
5656             $sth2->execute($authtypecode, $field, substr($field, 0, 1));
5657             my $authtypemarker = substr $field, 1, 2;
5658             if ($authtypemarker && $referencetypes{$authtypemarker}) {
5659                 $sth3->execute($referencetypes{$authtypemarker}, $authtypecode, $field);
5660             }
5661         }
5662     }
5663
5664     print "Upgrade to $DBversion done (Add thesaurus links for MARC21/NORMARC)\n";
5665     SetVersion($DBversion);
5666 }
5667
5668 $DBversion = "3.09.00.029"; # FIXME
5669 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5670     $dbh->do("UPDATE systempreferences SET options=concat(options,'|EAN13') WHERE variable='itemBarcodeInputFilter' AND options NOT LIKE '%EAN13%'");
5671     print "Upgrade to $DBversion done (Add itemBarcodeInputFilter choice EAN13)\n";
5672
5673     $dbh->do("UPDATE systempreferences SET options = concat(options,'|EAN13'), explanation = concat(explanation,'; EAN13 - incremental') WHERE variable = 'autoBarcode' AND options NOT LIKE '%EAN13%'");
5674     print "Upgrade to $DBversion done ( Added EAN13 barcode autogeneration sequence )\n";
5675     SetVersion($DBversion);
5676 }
5677
5678 $DBversion ="3.09.00.030";
5679 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5680     my $query = "SELECT value FROM systempreferences WHERE variable='opacstylesheet'";
5681     my $remote= $dbh->selectrow_arrayref($query);
5682     $dbh->do("DELETE from systempreferences WHERE variable='opacstylesheet'");
5683     if($remote && $remote->[0]) {
5684         $query="UPDATE systempreferences SET value=? WHERE variable='opaclayoutstylesheet'";
5685         $dbh->do($query,undef,$remote->[0]);
5686         print "NOTE: The URL of your remote opac css file has been moved to preference opaclayoutstylesheet.\n";
5687     }
5688     print "Upgrade to $DBversion done (BZ 8263: Make OPAC stylesheet preferences more consistent)\n";
5689     SetVersion($DBversion);
5690 }
5691
5692 $DBversion = "3.09.00.031";
5693 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5694     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonReviews'");
5695     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonSimilarItems'");
5696     $dbh->do("DELETE FROM systempreferences WHERE variable='AWSAccessKeyID'");
5697     $dbh->do("DELETE FROM systempreferences WHERE variable='AWSPrivateKey'");
5698     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonReviews'");
5699     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonSimilarItems'");
5700     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonEnabled'");
5701     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonEnabled'");
5702     print "Upgrade to $DBversion done ('Remove preferences controlling broken Amazon features (Bug 8679')\n";
5703     SetVersion ($DBversion);
5704 }
5705
5706 $DBversion = "3.09.00.032";
5707 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5708     $dbh->do("UPDATE systempreferences SET value = 'call_number' WHERE variable = 'defaultSortField' AND value = 'callnumber'");
5709     $dbh->do("UPDATE systempreferences SET value = 'call_number' WHERE variable = 'OPACdefaultSortField' AND value = 'callnumber'");
5710     print "Upgrade to $DBversion done (Bug 8657 - Default sort by call number does not work. Correcting system preference value.)\n";
5711     SetVersion ($DBversion);
5712 }
5713
5714
5715 $DBversion = '3.09.00.033';
5716 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5717    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacSuppressionByIPRange','','Restrict the suppression to IP adresses outside of the IP range','','free');");
5718    print "Upgrade to $DBversion done (Add OpacSuppressionByIPRange syspref)\n";
5719    SetVersion ($DBversion);
5720 }
5721
5722 $DBversion ="3.09.00.034";
5723 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5724     $dbh->do("UPDATE auth_subfield_structure SET frameworkcode = 'PERSO_NAME' WHERE frameworkcode = 'PERSO_CODE'");
5725     $dbh->do("UPDATE auth_subfield_structure SET frameworkcode = 'CORPO_NAME' WHERE frameworkcode = 'ORGO_CODE'");
5726     print "Upgrade to $DBversion done (Bug 8207: correct typo in authority types)\n";
5727     SetVersion ($DBversion);
5728 }
5729
5730 $DBversion = "3.09.00.035";
5731 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5732     $dbh->do("
5733     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');
5734     ");
5735     $dbh->do(
5736     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SubfieldsToUseWhenPrefill','','Define a list of subfields to use when prefilling items (separated by space)','','Free');
5737     ");
5738     print "Upgrade to $DBversion done (Adding PrefillItem and SubfieldsToUseWhenPrefill sysprefs)\n";
5739     SetVersion ($DBversion);
5740 }
5741
5742 $DBversion = "3.09.00.036";
5743 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5744     # biblioitems changes
5745     $dbh->do("ALTER TABLE biblioitems ADD COLUMN agerestriction VARCHAR(255) DEFAULT NULL AFTER cn_sort");
5746     $dbh->do("ALTER TABLE deletedbiblioitems ADD COLUMN agerestriction VARCHAR(255) DEFAULT NULL AFTER cn_sort");
5747     # preferences changes
5748     $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')");
5749     $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')");
5750
5751     print "Upgrade to $DBversion done (Add colum agerestriction to biblioitems and deletedbiblioitems, add system preferences AgeRestrictionMarker and AgeRestrictionOverride)\n";
5752    SetVersion ($DBversion);
5753 }
5754
5755 $DBversion = "3.09.00.037";
5756 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5757     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('UseTransportCostMatrix',0,'Use Transport Cost Matrix when filling holds','','YesNo')");
5758
5759  $dbh->do("CREATE TABLE `transport_cost` (
5760               `frombranch` varchar(10) NOT NULL,
5761               `tobranch` varchar(10) NOT NULL,
5762               `cost` decimal(6,2) NOT NULL,
5763               `disable_transfer` tinyint(1) NOT NULL DEFAULT 0,
5764               CHECK ( `frombranch` <> `tobranch` ), -- a dud check, mysql does not support that
5765               PRIMARY KEY (`frombranch`, `tobranch`),
5766               CONSTRAINT `transport_cost_ibfk_1` FOREIGN KEY (`frombranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
5767               CONSTRAINT `transport_cost_ibfk_2` FOREIGN KEY (`tobranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
5768           ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
5769
5770     print "Upgrade to $DBversion done (creating `transport_cost` table; adding UseTransportCostMatrix systempref, in circulation)\n";
5771     SetVersion($DBversion);
5772 }
5773
5774 $DBversion ="3.09.00.038";
5775 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5776     $dbh->do("ALTER TABLE borrower_attributes CHANGE  attribute  attribute VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
5777     print "Upgrade to $DBversion done (Increase the maximum size of a borrower attribute value)\n";
5778     SetVersion($DBversion);
5779 }
5780
5781 $DBversion ="3.09.00.039";
5782 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5783     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,type) VALUES('DidYouMeanFromAuthorities','0','Suggest searches based on authority file.','YesNo');");
5784     print "Upgrade to $DBversion done (Add system preference DidYouMeanFromAuthorities)\n";
5785     SetVersion($DBversion);
5786 }
5787
5788 $DBversion = "3.09.00.040";
5789 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5790     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('IncludeSeeFromInSearches','0','','Include see-from references in searches.','YesNo');");
5791     print "Upgrade to $DBversion done (Add IncludeSeeFromInSearches system preference)\n";
5792     SetVersion ($DBversion);
5793 }
5794
5795 $DBversion = "3.09.00.041";
5796 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5797     $dbh->do(qq{
5798         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ExportRemoveFields','','List of fields for non export in circulation.pl (separated by a space)','','');
5799     });
5800     print "Upgrade to $DBversion done (Add system preference ExportRemoveFields)\n";
5801     SetVersion($DBversion);
5802 }
5803
5804 $DBversion = "3.09.00.042";
5805 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5806     $dbh->do(qq{
5807         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ExportWithCsvProfile','','Set a profile name for CSV export','','');
5808     });
5809     print "Upgrade to $DBversion done (Adds New System preference ExportWithCsvProfile)\n";
5810     SetVersion($DBversion)
5811 }
5812
5813 $DBversion = "3.09.00.043";
5814 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5815     $dbh->do("
5816         ALTER TABLE aqorders
5817         ADD parent_ordernumber int(11) DEFAULT NULL
5818     ");
5819     $dbh->do("
5820         UPDATE aqorders
5821         SET parent_ordernumber = ordernumber;
5822     ");
5823     print "Upgrade to $DBversion done (Adding parent_ordernumber in aqorders)\n";
5824     SetVersion($DBversion);
5825 }
5826
5827 $DBversion = '3.09.00.044';
5828 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5829     $dbh->do("ALTER TABLE statistics ADD COLUMN ccode VARCHAR ( 10 ) NULL AFTER associatedborrower");
5830     $dbh->do("UPDATE statistics SET statistics.ccode = ( SELECT items.ccode FROM items WHERE statistics.itemnumber = items.itemnumber )");
5831     $dbh->do("UPDATE statistics SET statistics.ccode = (
5832               SELECT deleteditems.ccode FROM deleteditems
5833                   WHERE statistics.itemnumber = deleteditems.itemnumber
5834               ) WHERE statistics.ccode IS NULL");
5835     print "Upgrade done ( Added Collection Code to Statistics table. )\n";
5836     SetVersion ($DBversion);
5837 }
5838
5839 $DBversion = "3.09.00.045";
5840 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5841     $dbh->do("ALTER TABLE borrower_attribute_types MODIFY category_code VARCHAR( 10 ) NULL DEFAULT NULL");
5842     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.";
5843     SetVersion($DBversion);
5844 }
5845
5846 $DBversion = "3.09.00.046";
5847 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5848     $dbh->do("ALTER TABLE `accountlines` ADD `accountlines_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;");
5849     print "Upgrade to $DBversion done (adding accountlines_id field in accountlines table)\n";
5850     SetVersion($DBversion);
5851 }
5852
5853 $DBversion = "3.09.00.047";
5854 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5855     # to preserve default behaviour as best as possible, set this new preference differently depending on whether IndependantBranches is set or not
5856     my $prefvalue = 'anywhere';
5857     if (C4::Context->preference("IndependantBranches")) { $prefvalue = 'homeorholdingbranch';}
5858     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowReturnToBranch', '$prefvalue', 'Where an item may be returned', 'anywhere|homebranch|holdingbranch|homeorholdingbranch', 'Choice');");
5859
5860     print "Upgrade to $DBversion done: adding AllowReturnToBranch syspref (bug 6151)";
5861     SetVersion($DBversion);
5862 }
5863
5864 $DBversion = "3.09.00.048";
5865 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5866     $dbh->do("ALTER TABLE authorised_values MODIFY lib varchar(200)");
5867     $dbh->do("ALTER TABLE authorised_values MODIFY lib_opac varchar(200)");
5868
5869     print "Upgrade to $DBversion done (Raise the length of Authorised Values descriptions)\n";
5870     SetVersion($DBversion);
5871 }
5872
5873 $DBversion ="3.09.00.049";
5874 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5875     $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');");
5876     $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');");
5877     $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');");
5878     $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');");
5879     print "Upgrade to $DBversion done (Add OPACMobileUserCSS, OpacMainUserBlockMobile, OpacShowLibrariesPulldownMobile and OpacShowFiltersPulldownMobile sysprefs)\n";
5880     SetVersion($DBversion);
5881 }
5882
5883 $DBversion = "3.09.00.050";
5884 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5885     $dbh->do("ALTER TABLE authorised_values MODIFY category varchar(16) NOT NULL DEFAULT '';");
5886     $dbh->do("INSERT INTO authorised_values (category, authorised_value, lib) VALUES
5887               ('REPORT_GROUP', 'CIRC', 'Circulation'),
5888               ('REPORT_GROUP', 'CAT', 'Catalog'),
5889               ('REPORT_GROUP', 'PAT', 'Patrons'),
5890               ('REPORT_GROUP', 'ACQ', 'Acquisitions'),
5891               ('REPORT_GROUP', 'ACC', 'Accounts');");
5892
5893     $dbh->do("ALTER TABLE reports_dictionary ADD report_area varchar(6) DEFAULT NULL;");
5894     $dbh->do("UPDATE reports_dictionary SET report_area = CASE area
5895                   WHEN 1 THEN 'CIRC'
5896                   WHEN 2 THEN 'CAT'
5897                   WHEN 3 THEN 'PAT'
5898                   WHEN 4 THEN 'ACQ'
5899                   WHEN 5 THEN 'ACC'
5900                   END;");
5901     $dbh->do("ALTER TABLE reports_dictionary DROP area;");
5902     $dbh->do("ALTER TABLE reports_dictionary ADD KEY dictionary_area_idx (report_area);");
5903
5904     $dbh->do("ALTER TABLE saved_sql ADD report_area varchar(6) DEFAULT NULL;");
5905     $dbh->do("ALTER TABLE saved_sql ADD report_group varchar(80) DEFAULT NULL;");
5906     $dbh->do("ALTER TABLE saved_sql ADD report_subgroup varchar(80) DEFAULT NULL;");
5907     $dbh->do("ALTER TABLE saved_sql ADD KEY sql_area_group_idx (report_group, report_subgroup);");
5908
5909     print "Upgrade to $DBversion done saved_sql new fields report_group and report_area; authorised_values.category 16 char \n";
5910     SetVersion($DBversion);
5911 }
5912
5913 $DBversion = "3.09.00.051";
5914 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5915     $dbh->do("
5916         CREATE TABLE aqinvoices (
5917           invoiceid int(11) NOT NULL AUTO_INCREMENT,
5918           invoicenumber mediumtext NOT NULL,
5919           booksellerid int(11) NOT NULL,
5920           shipmentdate date default NULL,
5921           billingdate date default NULL,
5922           closedate date default NULL,
5923           shipmentcost decimal(28,6) default NULL,
5924           shipmentcost_budgetid int(11) default NULL,
5925           PRIMARY KEY (invoiceid),
5926           CONSTRAINT aqinvoices_fk_aqbooksellerid FOREIGN KEY (booksellerid) REFERENCES aqbooksellers (id) ON DELETE CASCADE ON UPDATE CASCADE,
5927           CONSTRAINT aqinvoices_fk_shipmentcost_budgetid FOREIGN KEY (shipmentcost_budgetid) REFERENCES aqbudgets (budget_id) ON DELETE SET NULL ON UPDATE CASCADE
5928         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5929     ");
5930
5931     # Fill this new table with existing invoices
5932     my $sth = $dbh->prepare("
5933         SELECT aqorders.booksellerinvoicenumber AS invoicenumber, aqbasket.booksellerid, aqorders.datereceived
5934         FROM aqorders
5935           LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
5936         WHERE aqorders.booksellerinvoicenumber IS NOT NULL
5937           AND aqorders.booksellerinvoicenumber != ''
5938         GROUP BY aqorders.booksellerinvoicenumber
5939     ");
5940     $sth->execute;
5941     my $results = $sth->fetchall_arrayref({});
5942     $sth = $dbh->prepare("
5943         INSERT INTO aqinvoices (invoicenumber, booksellerid, shipmentdate) VALUES (?,?,?)
5944     ");
5945     foreach(@$results) {
5946         $sth->execute($_->{invoicenumber}, $_->{booksellerid}, $_->{datereceived});
5947     }
5948
5949     # Add the column in aqorders, fill it with correct value
5950     # and then drop booksellerinvoicenumber column
5951     $dbh->do("
5952         ALTER TABLE aqorders
5953         ADD COLUMN invoiceid int(11) default NULL AFTER booksellerinvoicenumber,
5954         ADD CONSTRAINT aqorders_ibfk_3 FOREIGN KEY (invoiceid) REFERENCES aqinvoices (invoiceid) ON DELETE SET NULL ON UPDATE CASCADE
5955     ");
5956
5957     $dbh->do("
5958         UPDATE aqorders, aqinvoices
5959         SET aqorders.invoiceid = aqinvoices.invoiceid
5960         WHERE aqorders.booksellerinvoicenumber = aqinvoices.invoicenumber
5961     ");
5962
5963     $dbh->do("
5964         ALTER TABLE aqorders
5965         DROP COLUMN booksellerinvoicenumber
5966     ");
5967
5968     print "Upgrade to $DBversion done (Add aqinvoices table) \n";
5969     SetVersion ($DBversion);
5970 }
5971
5972 $DBversion = "3.09.00.052";
5973 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5974     $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');");
5975     $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');");
5976     $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');");
5977     print "Upgrade to $DBversion done (Add systempreferences to decrease loan length on high demand items decreaseLoanHighHolds, decreaseLoanHighHoldsValue and decreaseLoanHighHoldsDuration) \n";
5978     SetVersion ($DBversion);
5979 }
5980
5981 $DBversion = "3.09.00.053";
5982 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5983     $dbh->do(
5984     q|CREATE TABLE `import_auths` (
5985         import_record_id int(11) NOT NULL,
5986         matched_authid int(11) default NULL,
5987         control_number varchar(25) default NULL,
5988         authorized_heading varchar(128) default NULL,
5989         original_source varchar(25) default NULL,
5990         CONSTRAINT import_auths_ibfk_1 FOREIGN KEY (import_record_id)
5991         REFERENCES import_records (import_record_id) ON DELETE CASCADE ON UPDATE CASCADE,
5992         KEY matched_authid (matched_authid)
5993         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;|
5994     );
5995     $dbh->do("ALTER TABLE import_batches
5996                 CHANGE COLUMN num_biblios num_records int(11) NOT NULL default 0,
5997                 ADD COLUMN record_type enum('biblio', 'auth', 'holdings') NOT NULL default 'biblio'");
5998     $dbh->do("UPDATE import_batches SET record_type='auth' WHERE import_batch_id IN
5999                 (SELECT import_batch_id FROM import_records WHERE record_type='auth')");
6000
6001     print "Upgrade to $DBversion done (Added support for staging authorities)\n";
6002     SetVersion ($DBversion);
6003 }
6004
6005 $DBversion = "3.09.00.054";
6006 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6007     $dbh->do("ALTER TABLE aqorders CHANGE COLUMN gst gstrate DECIMAL(6,4)  DEFAULT NULL");
6008     print "Upgrade to $DBversion done (Change column name in aqorders gst --> gstrate)\n";
6009     SetVersion($DBversion);
6010 }
6011
6012 $DBversion = "3.09.00.055";
6013 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6014     $dbh->do("ALTER TABLE aqorders ADD discount float(6,4) DEFAULT NULL AFTER gstrate");
6015     print "Upgrade to $DBversion done (Add discount field in aqorders table)\n";
6016     SetVersion($DBversion);
6017 }
6018
6019 $DBversion ="3.09.00.056";
6020 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6021     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('AuthDisplayHierarchy','0','Display authority hierarchies','','YesNo')");
6022     print "Upgrade to $DBversion done (Add system preference AuthDisplayHierarchy)\n";
6023     SetVersion($DBversion);
6024 }
6025
6026 $DBversion = "3.09.00.057";
6027 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6028     $dbh->do("ALTER TABLE aqbasket ADD deliveryplace VARCHAR(10) default NULL AFTER basketgroupid;");
6029     $dbh->do("ALTER TABLE aqbasket ADD billingplace VARCHAR(10) default NULL AFTER deliveryplace;");
6030     print "Upgrade to $DBversion done (Bug 5356: Added billingplace, deliveryplace to the aqbasket table)\n";
6031     SetVersion($DBversion);
6032 }
6033
6034 $DBversion ="3.09.00.058";
6035 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6036     $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');");
6037     $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');");
6038     print "Upgrade to $DBversion done (Add Did You Mean? configuration)\n";
6039     SetVersion($DBversion);
6040 }
6041
6042 $DBversion ="3.09.00.059";
6043 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6044     $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');");
6045     print "Upgrade to $DBversion done (Add system preference BlockReturnOfWithdrawnItems)\n";
6046     SetVersion($DBversion);
6047 }
6048
6049 $DBversion = "3.09.00.060";
6050 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6051     $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')");
6052     print "Upgrade to $DBversion done (Added HoldsToPullStartDate syspref)\n";
6053     SetVersion($DBversion);
6054 }
6055
6056 $DBversion = "3.09.00.061";
6057 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6058     $dbh->do("UPDATE systempreferences set value=0 WHERE variable='OPACItemsResultsDisplay' AND value='statuses'");
6059     $dbh->do("UPDATE systempreferences set value=1 WHERE variable='OPACItemsResultsDisplay' AND value='itemdetails'");
6060     $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'");
6061     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";
6062     SetVersion ($DBversion);
6063 }
6064
6065 $DBversion = "3.09.00.062";
6066 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6067    $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='NoZebra'");
6068    $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='QueryRemoveStopwords'");
6069    print "Upgrade to $DBversion done (Disable obsolete NoZebra and QueryRemoveStopwords sysprefs)\n";
6070    SetVersion ($DBversion);
6071 }
6072
6073 $DBversion = "3.09.00.063";
6074 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6075     my $gst_booksellers = $dbh->selectcol_arrayref("SELECT DISTINCT(gstrate) FROM aqbooksellers");
6076     my $gist_syspref = C4::Context->preference("gist");
6077     # remove the undef values and construct and array with the syspref and the supplier values
6078     my @gstrates = map { defined $_ ? $_ : () } @$gst_booksellers;
6079     push @gstrates, split ('\|', $gist_syspref);
6080     # we want to compare integer (or float)
6081     $_ = $_ + 0 for @gstrates;
6082     use List::MoreUtils qw/uniq/;
6083     # remove duplicate values
6084     @gstrates = uniq sort @gstrates;
6085     my $new_syspref_value = join '|', @gstrates;
6086     # update the syspref with the new values
6087     my $sth = $dbh->prepare("UPDATE systempreferences set value=? WHERE variable='gist'");
6088     $sth->execute( $new_syspref_value );
6089
6090     print "Upgrade to $DBversion done (Bug 8832, Set the syspref gist with the existing values)\n";
6091     SetVersion ($DBversion);
6092 }
6093
6094 $DBversion = "3.09.00.064";
6095 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6096    $dbh->do('ALTER TABLE items ADD coded_location_qualifier varchar(10) default NULL AFTER itemcallnumber');
6097    print "Upgrade to $DBversion done (Bug 6428: Added coded_location_qualifier to the items table)\n";
6098    SetVersion ($DBversion);
6099 }
6100
6101 $DBversion = "3.09.00.065";
6102 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6103    $dbh->do('ALTER TABLE deleteditems ADD coded_location_qualifier varchar(10) default NULL AFTER itemcallnumber');
6104    print "Upgrade to $DBversion done (Bug 6428: Added coded_location_qualifier to the deleteditems table)\n";
6105    SetVersion ($DBversion);
6106 }
6107
6108 $DBversion = "3.09.00.066";
6109 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6110    $dbh->do("DELETE FROM systempreferences WHERE variable='DidYouMeanFromAuthorities'");
6111    print "Upgrade to $DBversion done (Bug 9107: remove DidYouMeanFromAuthorities syspref)\n";
6112    SetVersion ($DBversion);
6113 }
6114
6115 $DBversion = "3.09.00.067";
6116 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6117    $dbh->do("ALTER TABLE statistics CHANGE COLUMN ccode ccode varchar(10) NULL");
6118    print "Upgrade to $DBversion done (Bug 9064: statistics.ccode potentially wrongly defined)\n";
6119    SetVersion ($DBversion);
6120 }
6121
6122 $DBversion = "3.10.00.00";
6123 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6124    print "Upgrade to $DBversion done (release tag)\n";
6125    SetVersion ($DBversion);
6126 }
6127
6128 $DBversion = "3.11.00.001";
6129 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6130     $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')");
6131     print "Upgrade to $DBversion done (Bug 2832 - Add alphabet syspref)\n";
6132 }
6133
6134 $DBversion = "3.11.00.002";
6135 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6136     $dbh->do(q{
6137         DELETE from aqorders_items where ordernumber NOT IN (SELECT ordernumber FROM aqorders);
6138     });
6139     $dbh->do(q{
6140         ALTER TABLE aqorders_items
6141         ADD CONSTRAINT aqorders_items_ibfk_1 FOREIGN KEY (ordernumber) REFERENCES aqorders (ordernumber)
6142         ON DELETE CASCADE ON UPDATE CASCADE;
6143     });
6144     print "Upgrade to $DBversion done (Bug 9030: Add constraint on aqorders_items.ordernumber)\n";
6145     SetVersion ($DBversion);
6146 }
6147
6148 $DBversion = "3.11.00.003";
6149 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6150     $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')");
6151     print "Upgrade to $DBversion done (Bug 7189: Add system preference RefundLostItemFeeOnReturn)\n";
6152     SetVersion($DBversion);
6153 }
6154
6155 $DBversion = "3.11.00.004";
6156 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6157     $dbh->do(qq{
6158         ALTER TABLE subscription ADD COLUMN closed INT(1) NOT NULL DEFAULT 0 AFTER enddate;
6159     });
6160
6161     print "Upgrade to $DBversion done (Bug 8782: Add field subscription.closed)\n";
6162     SetVersion($DBversion);
6163 }
6164
6165 $DBversion = "3.11.00.005";
6166 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6167     $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;});
6168
6169     $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;});
6170
6171     $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;});
6172
6173     print "Upgrade to $DBversion done (Bug 7919: Display of values depending on the connexion library)\n";
6174     SetVersion($DBversion);
6175 }
6176
6177 $DBversion = "3.11.00.006";
6178 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6179     $dbh->do(q{
6180         UPDATE virtualshelves SET sortfield="copyrightdate" where sortfield="year";
6181     });
6182     print "Upgrade to $DBversion done (Bug 9167: Update the virtualshelves.sortfield column with 'copyrightdate' if needed)\n";
6183     SetVersion($DBversion);
6184 }
6185
6186 $DBversion = "3.11.00.007";
6187 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6188     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ar', 'language', 'de', 'Arabisch')");
6189     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hy', 'language', 'de', 'Armenisch')");
6190     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'bg', 'language', 'de', 'Bulgarisch')");
6191     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'zh', 'language', 'de', 'Chinesisch')");
6192     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'cs', 'language', 'de', 'Tschechisch')");
6193     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'da', 'language', 'de', 'Dänisch')");
6194     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nl', 'language', 'de', 'Niederländisch')");
6195     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'en', 'language', 'de', 'Englisch')");
6196     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fi', 'language', 'de', 'Finnisch')");
6197     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fr', 'language', 'de', 'Französisch')");
6198     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'lo', 'language', 'fr', 'Laotien')");
6199     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'lo', 'language', 'de', 'Laotisch')");
6200     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'el', 'language', 'de', 'Griechisch (Nach 1453)')");
6201     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'he', 'language', 'de', 'Hebräisch')");
6202     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hi', 'language', 'de', 'Hindi')");
6203     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hu', 'language', 'de', 'Ungarisch')");
6204     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'id', 'language', 'de', 'Indonesisch')");
6205     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'it', 'language', 'de', 'Italienisch')");
6206     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ja', 'language', 'de', 'Japanisch')");
6207     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ko', 'language', 'de', 'Koreanisch')");
6208     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'la', 'language', 'de', 'Latein')");
6209     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'gl', 'language', 'fr', 'Galicien')");
6210     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'gl', 'language', 'de', 'Galizisch')");
6211     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nb', 'language', 'de', 'Norwegisch bokm&#229;l')");
6212     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nn', 'language', 'de', 'Norwegisch nynorsk')");
6213     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fa', 'language', 'de', 'Persisch')");
6214     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'pl', 'language', 'de', 'Polnisch')");
6215     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'pt', 'language', 'de', 'Portugiesisch')");
6216     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ro', 'language', 'de', 'Rumänisch')");
6217     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ru', 'language', 'de', 'Russisch')");
6218     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sr', 'language', 'fr', 'Serbe')");
6219     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sr', 'language', 'de', 'Serbisch')");
6220     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'es', 'language', 'de', 'Spanisch')");
6221     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sv', 'language', 'de', 'Schwedisch')");
6222     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tet', 'language', 'fr', 'Tétoum')");
6223     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tet', 'language', 'de', 'Tetum')");
6224     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'th', 'language', 'de', 'Thailändisch')");
6225     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tr', 'language', 'de', 'Türkisch')");
6226     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'uk', 'language', 'de', 'Ukrainisch')");
6227     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ur', 'language', 'fr', 'Ourdou')");
6228     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ur', 'language', 'de', 'Urdu')");
6229     print "Upgrade to $DBversion done (Bug 9056: add German and a couple of French translations to language_descriptions)\n";
6230     SetVersion ($DBversion);
6231 }
6232
6233 $DBversion = "3.11.00.008";
6234 if (CheckVersion($DBversion)) {
6235     $dbh->do("
6236         CREATE TABLE IF NOT EXISTS `borrower_modifications` (
6237           `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6238           `verification_token` varchar(255) NOT NULL DEFAULT '',
6239           `borrowernumber` int(11) NOT NULL DEFAULT '0',
6240           `cardnumber` varchar(16) DEFAULT NULL,
6241           `surname` mediumtext,
6242           `firstname` text,
6243           `title` mediumtext,
6244           `othernames` mediumtext,
6245           `initials` text,
6246           `streetnumber` varchar(10) DEFAULT NULL,
6247           `streettype` varchar(50) DEFAULT NULL,
6248           `address` mediumtext,
6249           `address2` text,
6250           `city` mediumtext,
6251           `state` text,
6252           `zipcode` varchar(25) DEFAULT NULL,
6253           `country` text,
6254           `email` mediumtext,
6255           `phone` text,
6256           `mobile` varchar(50) DEFAULT NULL,
6257           `fax` mediumtext,
6258           `emailpro` text,
6259           `phonepro` text,
6260           `B_streetnumber` varchar(10) DEFAULT NULL,
6261           `B_streettype` varchar(50) DEFAULT NULL,
6262           `B_address` varchar(100) DEFAULT NULL,
6263           `B_address2` text,
6264           `B_city` mediumtext,
6265           `B_state` text,
6266           `B_zipcode` varchar(25) DEFAULT NULL,
6267           `B_country` text,
6268           `B_email` text,
6269           `B_phone` mediumtext,
6270           `dateofbirth` date DEFAULT NULL,
6271           `branchcode` varchar(10) DEFAULT NULL,
6272           `categorycode` varchar(10) DEFAULT NULL,
6273           `dateenrolled` date DEFAULT NULL,
6274           `dateexpiry` date DEFAULT NULL,
6275           `gonenoaddress` tinyint(1) DEFAULT NULL,
6276           `lost` tinyint(1) DEFAULT NULL,
6277           `debarred` date DEFAULT NULL,
6278           `debarredcomment` varchar(255) DEFAULT NULL,
6279           `contactname` mediumtext,
6280           `contactfirstname` text,
6281           `contacttitle` text,
6282           `guarantorid` int(11) DEFAULT NULL,
6283           `borrowernotes` mediumtext,
6284           `relationship` varchar(100) DEFAULT NULL,
6285           `ethnicity` varchar(50) DEFAULT NULL,
6286           `ethnotes` varchar(255) DEFAULT NULL,
6287           `sex` varchar(1) DEFAULT NULL,
6288           `password` varchar(30) DEFAULT NULL,
6289           `flags` int(11) DEFAULT NULL,
6290           `userid` varchar(75) DEFAULT NULL,
6291           `opacnote` mediumtext,
6292           `contactnote` varchar(255) DEFAULT NULL,
6293           `sort1` varchar(80) DEFAULT NULL,
6294           `sort2` varchar(80) DEFAULT NULL,
6295           `altcontactfirstname` varchar(255) DEFAULT NULL,
6296           `altcontactsurname` varchar(255) DEFAULT NULL,
6297           `altcontactaddress1` varchar(255) DEFAULT NULL,
6298           `altcontactaddress2` varchar(255) DEFAULT NULL,
6299           `altcontactaddress3` varchar(255) DEFAULT NULL,
6300           `altcontactstate` text,
6301           `altcontactzipcode` varchar(50) DEFAULT NULL,
6302           `altcontactcountry` text,
6303           `altcontactphone` varchar(50) DEFAULT NULL,
6304           `smsalertnumber` varchar(50) DEFAULT NULL,
6305           `privacy` int(11) DEFAULT NULL,
6306           PRIMARY KEY (`verification_token`,`borrowernumber`),
6307           KEY `verification_token` (`verification_token`),
6308           KEY `borrowernumber` (`borrowernumber`)
6309         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6310 ");
6311
6312     $dbh->do("
6313         INSERT INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES
6314         ('PatronSelfRegistration', '0', NULL, 'If enabled, patrons will be able to register themselves via the OPAC.', 'YesNo'),
6315         ('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'),
6316         ('PatronSelfRegistrationDefaultCategory', '', '', 'A patron registered via the OPAC will receive a borrower category code set in this system preference.', 'free'),
6317         ('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'),
6318         ('PatronSelfRegistrationBorrowerMandatoryField',  'surname|firstname', NULL ,  'Choose the mandatory fields for a patron''s account, when registering via the OPAC.',  'free'),
6319         ('PatronSelfRegistrationBorrowerUnwantedField',  '', NULL ,  'Name the fields you don''t want to display when registering a new patron via the OPAC.',  'free');
6320     ");
6321
6322     $dbh->do("
6323     INSERT INTO  letter ( `module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content` )
6324     VALUES ( 'members', 'OPAC_REG_VERIFY', '', 'Opac Self-Registration Verification Email', '1', 'Verify Your Account', 'Hello!
6325
6326     Your library account has been created. Please verify your email address by clicking this link to complete the signup process:
6327
6328     http://<<OPACBaseURL>>/cgi-bin/koha/opac-registration-verify.pl?token=<<borrower_modifications.verification_token>>
6329
6330     If you did not initiate this request, you may safely ignore this one-time message. The request will expire shortly.'
6331     )");
6332
6333     print "Upgrade to $DBversion done (Bug 7067: Add Patron Self Registration)\n";
6334     SetVersion ($DBversion);
6335 }
6336
6337 $DBversion = "3.11.00.009";
6338 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6339     $dbh->do("
6340         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
6341         ('SeparateHoldings', '0', 'Separate current branch holdings from other holdings', NULL, 'YesNo'),
6342         ('SeparateHoldingsBranch', 'homebranch', 'Branch used to separate holdings', 'homebranch|holdingbranch', 'Choice'),
6343         ('OpacSeparateHoldings', '0', 'Separate current branch holdings from other holdings (OPAC)', NULL, 'YesNo'),
6344         ('OpacSeparateHoldingsBranch', 'homebranch', 'Branch used to separate holdings (OPAC)', 'homebranch|holdingbranch', 'Choice')
6345     ");
6346
6347     print "Upgrade to $DBversion done (Bug 7674: Add systempreferences SeparateHoldings, SeparateHoldingsBranch, OpacSeparateHoldings and OpacSeparateHoldingsBranch) \n";
6348     SetVersion ($DBversion);
6349 }
6350
6351 $DBversion = "3.11.00.010";
6352 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6353     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('RenewalSendNotice', '0', '', NULL, 'YesNo')");
6354     $dbh->do(q{
6355         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
6356         ('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>>.');
6357     });
6358     print "Upgrade to $DBversion done (Bug 9151 - Renewal notice according to patron alert preferences)\n";
6359     SetVersion($DBversion);
6360 }
6361
6362 $DBversion = "3.11.00.011";
6363 if ( CheckVersion($DBversion) ) {
6364    $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');");
6365    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('HTML5MediaExtensions','webm|ogg|ogv|oga|vtt','Media file extensions','','free');");
6366    print "Upgrade to $DBversion done (Bug 8377: Add HTML5MediaEnabled and HTML5MediaExtensions sysprefs)\n";
6367    SetVersion ($DBversion);
6368 }
6369
6370 $DBversion = "3.11.00.012";
6371 if ( CheckVersion($DBversion) ) {
6372     $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')");
6373     print "Upgrade to $DBversion done (Bug 9206: Only allow place holds in records that the patron don't have in his possession)\n";
6374     SetVersion($DBversion);
6375 }
6376
6377 $DBversion = "3.11.00.013";
6378 if ( CheckVersion($DBversion) ) {
6379     $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')");
6380     print "Upgrade to $DBversion done (Bug 9162 - Add a system preference to set which notes fields appears on title notes/description separator)\n";
6381     SetVersion($DBversion);
6382 }
6383
6384 $DBversion = "3.11.00.014";
6385 if ( CheckVersion($DBversion) ) {
6386    $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' )");
6387    $dbh->do("INSERT INTO systempreferences ( variable, value, explanation, type ) VALUES ( 'SCOUserJS', '', 'Define custom javascript for inclusion in the SCO module', 'free' )");
6388    print "Upgrade to $DBversion done (Bug 9009: Add SCOUserCSS and SCOUserJS sysprefs)\n";
6389 }
6390
6391 $DBversion = "3.11.00.015";
6392 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6393     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('RentalsInNoissuesCharge', '1', 'Rental charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
6394     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('ManInvInNoissuesCharge', '1', 'MANUAL_INV charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
6395     print "Upgrade to $DBversion done (Add sysprefs RentalsInNoissuesCharge and ManInvInNoissuesCharge.)\n";
6396     SetVersion($DBversion);
6397 }
6398
6399 $DBversion = "3.11.00.016";
6400 if ( CheckVersion($DBversion) ) {
6401    $dbh->do(q{
6402         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";
6403         });
6404    $dbh->do(q{
6405         UPDATE userflags SET flagdesc="Edit Authorities" where flagdesc="Allow to edit authorities";
6406         });
6407    $dbh->do(q{
6408         UPDATE userflags SET flagdesc="Allow access to the reports module" where flagdesc="Allow to access to the reports module";
6409         });
6410    $dbh->do(q{
6411         UPDATE userflags SET flagdesc="Set library management parameters (deprecated)" where flagdesc="Set library management parameters";
6412         });
6413    $dbh->do(q{
6414         UPDATE userflags SET flagdesc="Manage serial subscriptions" where flagdesc="Allow to manage serials subscriptions";
6415         });
6416    $dbh->do(q{
6417         UPDATE userflags SET flagdesc="Manage patrons fines and fees" where flagdesc="Update borrower charges";
6418         });
6419    $dbh->do(q{
6420         UPDATE userflags SET flagdesc="Check out and check in items" where flagdesc="Circulate books";
6421         });
6422    $dbh->do(q{
6423         UPDATE userflags SET flagdesc="Manage Koha system settings (Administration panel)" where flagdesc="Set Koha system parameters";
6424         });
6425    $dbh->do(q{
6426         UPDATE userflags SET flagdesc="Add or modify patrons" where flagdesc="Add or modify borrowers";
6427         });
6428    $dbh->do(q{
6429         UPDATE userflags SET flagdesc="Use all tools (expand for granular tools permissions)" where flagdesc="Use tools (export, import, barcodes)";
6430         });
6431    $dbh->do(q{
6432         UPDATE userflags SET flagdesc="Allow staff members to modify permissions for other staff members" where flagdesc="Set user permissions";
6433         });
6434    $dbh->do(q{
6435         UPDATE permissions SET description="Perform batch modification of patrons" where description="Perform batch modifivation of patrons";
6436         });
6437
6438    print "Upgrade to $DBversion done (Bug 9382 (updated with bug 9745) - refresh permission descriptions to make more sense)\n";
6439    SetVersion ($DBversion);
6440 }
6441
6442 $DBversion ="3.11.00.017";
6443 if ( CheckVersion($DBversion) ) {
6444     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksReviews','0','Display book review snippets from IDreamBooks.com','','YesNo');");
6445     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksReadometer','0','Display Readometer from IDreamBooks.com','','YesNo');");
6446     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksResults','0','Display IDreamBooks.com rating in search results','','YesNo');");
6447     print "Upgrade to $DBversion done (Add IDreamBooks enhanced content)\n";
6448     SetVersion($DBversion);
6449 }
6450
6451 $DBversion = "3.11.00.018";
6452 if ( CheckVersion($DBversion) ) {
6453    $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')");
6454    $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')");
6455    print "Upgrade to $DBversion done (Bug 9395: Problem with callnumber and standard number search in OPAC and Staff Client)\n";
6456    SetVersion ($DBversion);
6457 }
6458
6459 $DBversion = "3.11.00.019";
6460 if ( CheckVersion($DBversion) ) {
6461     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('UNIMARCAuthorityField100', 'afrey50      ba0', NULL, NULL, 'Textarea')");
6462     print "Upgrade to $DBversion done (Bug 9145 - Add syspref UNIMARCAuthorityField100)\n";
6463     SetVersion ($DBversion);
6464 }
6465
6466 $DBversion = "3.11.00.020";
6467 if ( CheckVersion($DBversion) ) {
6468     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UNIMARCField100Language', 'fre','UNIMARC field 100 default language',NULL,'short')");
6469     print "Upgrade to $DBversion done (Bug 8347 - Koha forces UNIMARC 100 field code language to 'fre')\n";
6470     SetVersion($DBversion);
6471 }
6472
6473 $DBversion ="3.11.00.021";
6474 if ( CheckVersion($DBversion) ) {
6475     $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');");
6476     print "Upgrade to $DBversion done (Bug 5888 - Subject search pop-up for the OPAC)\n";
6477     SetVersion($DBversion);
6478 }
6479
6480 $DBversion = "3.11.00.022";
6481 if ( CheckVersion($DBversion) ) {
6482     $dbh->do(
6483 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('Persona',0,'Use Mozilla Persona for login','','YesNo')"
6484     );
6485     print "Upgrade to $DBversion done (Bug 9587 - Allow login via Persona)\n";
6486     SetVersion($DBversion);
6487 }
6488
6489 $DBversion = "3.11.00.023";
6490 if ( CheckVersion($DBversion) ) {
6491     $dbh->do("UPDATE z3950servers SET host = 'lx2.loc.gov', port = 210, db = 'LCDB', syntax = 'USMARC', encoding = 'utf8' WHERE name = 'LIBRARY OF CONGRESS'");
6492     print "Upgrade to $DBversion done (Bug 9520 - Update default LOC Z39.50 target)\n";
6493     SetVersion($DBversion);
6494 }
6495
6496 $DBversion = "3.11.00.024";
6497 if ( CheckVersion($DBversion) ) {
6498     $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');");
6499     print "Upgrade to $DBversion done (Bug 5079: Add OpacItemLocation syspref)\n";
6500     SetVersion ($DBversion);
6501 }
6502
6503 $DBversion = "3.11.00.025";
6504 if ( CheckVersion($DBversion) ) {
6505     $dbh->do(
6506         "CREATE TABLE linktracker (
6507   id int(11) NOT NULL AUTO_INCREMENT,
6508   biblionumber int(11) DEFAULT NULL,
6509   itemnumber int(11) DEFAULT NULL,
6510   borrowernumber int(11) DEFAULT NULL,
6511   url text,
6512   timeclicked datetime DEFAULT NULL,
6513   PRIMARY KEY (id),
6514   KEY bibidx (biblionumber),
6515   KEY itemidx (itemnumber),
6516   KEY borridx (borrowernumber),
6517   KEY dateidx (timeclicked)
6518     ) ENGINE=InnoDB DEFAULT CHARSET=utf8;"
6519     );
6520     $dbh->do( "
6521   INSERT INTO systempreferences (variable,value,explanation,options,type)
6522   VALUES('TrackClicks','0','Track links clicked',NULL,'Integer')" );
6523     print
6524 "Upgrade to $DBversion done (Adds feature Bug 8917, the ability to track links clicked)\n";
6525     SetVersion($DBversion);
6526 }
6527
6528 $DBversion = "3.11.00.026";
6529 if ( CheckVersion($DBversion) ) {
6530     $dbh->do(qq{
6531         ALTER TABLE import_records ADD INDEX batch_id_record_type ( import_batch_id, record_type );
6532     });
6533     print "Upgrade to $DBversion done (Bug 9207: Add new index batch_id_record_type to import_records)\n";
6534     SetVersion($DBversion);
6535 }
6536
6537 $DBversion = "3.11.00.027";
6538 if ( CheckVersion($DBversion) ) {
6539     $dbh->do(q{
6540         INSERT INTO permissions ( module_bit, code, description )
6541         VALUES  ( '1', 'overdues_report', 'Execute overdue items report' )
6542     });
6543     # add new permission for users with all report permissions and circulation remaining permission
6544     $dbh->do(q{
6545         INSERT INTO user_permissions (borrowernumber, module_bit, code)
6546         SELECT user_permissions.borrowernumber, 1, 'overdues_report'
6547         FROM user_permissions
6548         LEFT JOIN borrowers USING(borrowernumber)
6549         WHERE borrowers.flags & (1 << 16)
6550         AND user_permissions.code = 'circulate_remaining_permissions'
6551     });
6552     print "Upgrade to $DBversion done ( Add circ permission overdues_report )\n";
6553     SetVersion($DBversion);
6554 }
6555
6556 $DBversion = "3.11.00.028";
6557 if ( CheckVersion($DBversion) ) {
6558     $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'    );");
6559     print "Upgrade to $DBversion done (Bug 9756 - Patron self registration missing the system preference PatronSelfRegistrationAdditionalInstructions)\n";
6560     SetVersion($DBversion);
6561 }
6562
6563 $DBversion = "3.11.00.029";
6564 if (CheckVersion($DBversion)) {
6565     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UseQueryParser', '0', 'If enabled, try to use QueryParser for queries.', NULL, 'YesNo')");
6566     print "Upgrade to $DBversion done (Bug 9239: Make it possible for Koha to use QueryParser)\n";
6567     SetVersion ($DBversion);
6568 }
6569
6570 $DBversion = "3.11.00.030";
6571 if ( CheckVersion($DBversion) ) {
6572     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('FinesIncludeGracePeriod','1','If enabled, fines calculations will include the grace period.',NULL,'YesNo');");
6573     print "Upgrade to $DBversion done (Add system preference FinesIncludeGracePeriod)\n";
6574     SetVersion($DBversion);
6575 }
6576
6577 $DBversion = "3.11.00.100";
6578 if ( CheckVersion($DBversion) ) {
6579     print "Upgrade to $DBversion done (3.12-alpha release)\n";
6580     SetVersion ($DBversion);
6581 }
6582
6583 $DBversion = "3.11.00.101";
6584 if ( CheckVersion($DBversion) ) {
6585    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('UNIMARCAuthorsFacetsSeparator',', ', 'UNIMARC authors facets separator', NULL, 'short')");
6586    print "Upgrade to $DBversion done (Bug 9341: Problem with UNIMARC authors facets)\n";
6587    SetVersion ($DBversion);
6588 }
6589
6590 $DBversion = "3.11.00.102";
6591 if ( CheckVersion($DBversion) ) {
6592     $dbh->do(q{
6593         DELETE FROM systempreferences WHERE variable='NoZebra'
6594     });
6595     $dbh->do(q{
6596         DELETE FROM systempreferences WHERE variable='QueryRemoveStopwords'
6597     });
6598     print "Upgrade to $DBversion done (Remove deprecated NoZebra and QueryRemoveStopwords sysprefs)\n";
6599     SetVersion($DBversion);
6600 }
6601
6602 $DBversion = "3.11.00.103";
6603 if ( CheckVersion($DBversion) ) {
6604     $dbh->do("DELETE FROM systempreferences WHERE variable = 'insecure';");
6605     print "Upgrade to $DBversion done (Bug 9827 - Remove 'insecure' system preference)\n";
6606     SetVersion($DBversion);
6607 }
6608
6609 $DBversion = "3.11.00.104";
6610 if ( CheckVersion($DBversion) ) {
6611     print "Upgrade to $DBversion done (3.12-alpha2 release)\n";
6612     SetVersion ($DBversion);
6613 }
6614
6615 $DBversion = "3.11.00.105";
6616 if ( CheckVersion($DBversion) ) {
6617     if ( C4::Context->preference("marcflavour") eq 'MARC21' ) {
6618         $sth = $dbh->prepare(
6619 "SELECT frameworkcode FROM marc_tag_structure WHERE tagfield = '029'"
6620         );
6621         $sth->execute;
6622         my $frameworkcodes = $sth->fetchall_hashref('frameworkcode');
6623
6624         for my $frameworkcode ( keys %$frameworkcodes ) {
6625             $dbh->do( "
6626     INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian,
6627     libopac, repeatable, mandatory, kohafield, tab, authorised_value, authtypecode,
6628     value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
6629     ('029', 'a', 'OCLC library identifier', 'OCLC library identifier', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6630     ('029', 'b', 'System control number', 'System control number', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6631     ('029', 'c', 'OAI set name', 'OAI set name', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6632     ('029', 't', 'Content type identifier', 'Content type identifier', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL)
6633    " );
6634         }
6635
6636         for my $tag ( '863', '864', '865' ) {
6637             $sth = $dbh->prepare(
6638 "SELECT frameworkcode FROM marc_tag_structure WHERE tagfield = '$tag'"
6639             );
6640             $sth->execute;
6641             my $frameworkcodes = $sth->fetchall_hashref('frameworkcode');
6642
6643             for my $frameworkcode ( keys %$frameworkcodes ) {
6644                 $dbh->do( "
6645      INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian,
6646      libopac, repeatable, mandatory, kohafield, tab, authorised_value, authtypecode,
6647      value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
6648      ('$tag', '6', 'Linkage', 'Linkage', 0, 0, '', 8, '', '', '', NULL, 5, '$frameworkcode', '', '', NULL),
6649      ('$tag', '8', 'Field link and sequence number', 'Field link and sequence number', 0, 0, '', 8, '', '', '', NULL, 5, '$frameworkcode', '', '', NULL),
6650      ('$tag', 'a', 'First level of enumeration', 'First level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6651      ('$tag', 'b', 'Second level of enumeration', 'Second level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6652      ('$tag', 'c', 'Third level of enumeration', 'Third level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6653      ('$tag', 'd', 'Fourth level of enumeration', 'Fourth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6654      ('$tag', 'e', 'Fifth level of enumeration', 'Fifth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6655      ('$tag', 'f', 'Sixth level of enumeration', 'Sixth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6656      ('$tag', 'g', 'Alternative numbering scheme, first level of enumeration', 'Alternative numbering scheme, first level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6657      ('$tag', 'h', 'Alternative numbering scheme, second level of enumeration', 'Alternative numbering scheme, second level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6658      ('$tag', 'i', 'First level of chronology', 'First level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6659      ('$tag', 'j', 'Second level of chronology', 'Second level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6660      ('$tag', 'k', 'Third level of chronology', 'Third level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6661      ('$tag', 'l', 'Fourth level of chronology', 'Fourth level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6662      ('$tag', 'm', 'Alternative numbering scheme, chronology', 'Alternative numbering scheme, chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6663      ('$tag', 'n', 'Converted Gregorian year', 'Converted Gregorian year', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6664      ('$tag', 'o', 'Type of unit', 'Type of unit', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6665      ('$tag', 'p', 'Piece designation', 'Piece designation', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6666      ('$tag', 'q', 'Piece physical condition', 'Piece physical condition', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6667      ('$tag', 's', 'Copyright article-fee code', 'Copyright article-fee code', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6668      ('$tag', 't', 'Copy number', 'Copy number', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6669      ('$tag', 'v', 'Issuing date', 'Issuing date', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6670      ('$tag', 'w', 'Break indicator', 'Break indicator', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6671      ('$tag', 'x', 'Nonpublic note', 'Nonpublic note', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6672      ('$tag', 'z', 'Public note', 'Public note', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL)
6673     " );
6674             }
6675         }
6676     }
6677     print "Upgrade to $DBversion done (Bug 9353: Missing subfields on MARC21 frameworks)\n";
6678     SetVersion($DBversion);
6679 }
6680
6681
6682 $DBversion = "3.11.00.106";
6683 if ( CheckVersion($DBversion) ) {
6684     $dbh->do("INSERT INTO userflags (bit, flag, flagdesc, defaulton) VALUES ('19', 'plugins', 'Koha plugins', '0')");
6685     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
6686               ('19', 'manage', 'Manage plugins ( install / uninstall )'),
6687               ('19', 'tool', 'Use tool plugins'),
6688               ('19', 'report', 'Use report plugins'),
6689               ('19', 'configure', 'Configure plugins')
6690             ");
6691     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UseKohaPlugins','0','Enable or disable the ability to use Koha Plugins.','','YesNo')");
6692
6693     $dbh->do("
6694         CREATE TABLE IF NOT EXISTS plugin_data (
6695             plugin_class varchar(255) NOT NULL,
6696             plugin_key varchar(255) NOT NULL,
6697             plugin_value text,
6698             PRIMARY KEY (plugin_class,plugin_key)
6699         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6700     ");
6701
6702     print "Upgrade to $DBversion done (Bug 7804: Added plugin system.)\n";
6703     SetVersion($DBversion);
6704 }
6705
6706 $DBversion = "3.11.00.107";
6707 if ( CheckVersion($DBversion) ) {
6708    $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('TimeFormat','24hr','12hr|24hr','Defines the global time format for visual output.','Choice')");
6709    print "Upgrade to $DBversion done (Bug 9014: Add syspref TimeFormat)\n";
6710    SetVersion ($DBversion);
6711 }
6712
6713 $DBversion = "3.11.00.108";
6714 if ( CheckVersion($DBversion) ) {
6715     $dbh->do("ALTER TABLE action_logs CHANGE timestamp timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;");
6716     $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');");
6717     $dbh->do("ALTER TABLE action_logs CHANGE timestamp timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;");
6718     print "Upgrade to $DBversion done (Bug 7241: Fix on circulation logs)\n";
6719     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";
6720     SetVersion($DBversion);
6721 }
6722
6723 $DBversion = "3.11.00.109";
6724 if ( CheckVersion($DBversion) ) {
6725    $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');");
6726    print "Upgrade to $DBversion done (Bug 9403: Add DisplayIconsXSLT)\n";
6727    SetVersion ($DBversion);
6728 }
6729
6730 $DBversion = "3.11.00.110";
6731 if ( CheckVersion($DBversion) ) {
6732     $dbh->do("ALTER TABLE pending_offline_operations CHANGE barcode barcode VARCHAR( 20 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
6733     $dbh->do("ALTER TABLE pending_offline_operations ADD amount DECIMAL( 28, 6 ) NULL DEFAULT NULL");
6734     print "Upgrade to $DBversion done (Bug 8220 - Allow koc uploads to go to process queue)\n";
6735     SetVersion ($DBversion);
6736 }
6737
6738 $DBversion = "3.11.00.111";
6739 if ( CheckVersion($DBversion) ) {
6740     my $sth = $dbh->prepare("
6741         SELECT module, code, branchcode, content
6742         FROM letter
6743         WHERE content LIKE '%<fine>%'
6744     ");
6745     $sth->execute;
6746     my $sth_update = $dbh->prepare("UPDATE letter SET content = ? WHERE module = ? AND code = ? AND branchcode = ?");
6747     while(my $row = $sth->fetchrow_hashref){
6748         $row->{content} =~ s/<fine>\w+<\/fine>/<<items.fine>>/;
6749         $sth_update->execute($row->{content}, $row->{module}, $row->{code}, $row->{branchcode});
6750     }
6751     print "Upgrade to $DBversion done (use new <<items.fine>> syntax in notices)\n";
6752     SetVersion($DBversion);
6753 }
6754
6755 $DBversion = "3.11.00.112";
6756 if ( CheckVersion($DBversion) ) {
6757     $dbh->do(qq{
6758         ALTER TABLE issuingrules ADD COLUMN renewalperiod int(4) DEFAULT NULL AFTER renewalsallowed
6759     });
6760     $dbh->do(qq{
6761         UPDATE issuingrules SET renewalperiod = issuelength
6762     });
6763     print "Upgrade to $DBversion done (Bug 8365: Add colum issuingrules.renewalperiod)\n";
6764     SetVersion ($DBversion);
6765 }
6766
6767 $DBversion = "3.11.00.113";
6768 if ( CheckVersion($DBversion) ) {
6769     $dbh->do(q{
6770         ALTER TABLE branchcategories ADD show_in_pulldown BOOLEAN NOT NULL DEFAULT '0',
6771         ADD INDEX ( show_in_pulldown )
6772     });
6773     print "Upgrade to $DBversion done (Bug 9257 - Add groups to normal search pulldown)\n";
6774     SetVersion ($DBversion);
6775 }
6776
6777 $DBversion = "3.11.00.115";
6778 if ( CheckVersion($DBversion) ) {
6779     $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')");
6780     $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')");
6781     print "Upgrade to $DBversion done (Bug 7740: Add syspref HighlightOwnItemsOnOPAC)\n";
6782     SetVersion ($DBversion);
6783 }
6784
6785 $DBversion = "3.11.00.116";
6786 if ( CheckVersion($DBversion) ) {
6787     $dbh->do(q{ALTER TABLE aqorders DROP COLUMN serialid;});
6788     $dbh->do(q{ALTER TABLE aqorders DROP COLUMN subscription;});
6789     $dbh->do(q{ALTER TABLE aqorders ADD COLUMN subscriptionid INT(11) DEFAULT NULL;});
6790     $dbh->do(q{ALTER TABLE aqorders ADD CONSTRAINT aqorders_subscriptionid FOREIGN KEY (subscriptionid) REFERENCES subscription (subscriptionid) ON DELETE CASCADE ON UPDATE CASCADE;});
6791     $dbh->do(q{ALTER TABLE subscription ADD COLUMN reneweddate DATE DEFAULT NULL;});
6792     print "Upgrade to $DBversion done (Bug 5343: table aqorders: DROP serialid and subscription fields and ADD subscriptionid, table subscription: ADD reneweddate)\n";
6793     SetVersion ($DBversion);
6794 }
6795
6796 $DBversion = "3.11.00.200";
6797 if ( CheckVersion($DBversion) ) {
6798     print "Upgrade to $DBversion done (3.12-beta1 release)\n";
6799     SetVersion ($DBversion);
6800 }
6801
6802 $DBversion = "3.11.00.201";
6803 if ( CheckVersion($DBversion) ) {
6804     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'BIBSYS' AND host LIKE 'z3950.bibsys.no'");
6805     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'NORBOK' AND host LIKE 'z3950.nb.no'");
6806     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'SAMBOK' AND host LIKE 'z3950.nb.no'");
6807     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'DEICHMAN' AND host like 'z3950.deich.folkebibl.no'");
6808     print "Upgrade to $DBversion done (Bug 9498 - Update encoding for Norwegian sample Z39.50 servers)\n";
6809     SetVersion($DBversion);
6810 }
6811
6812 $DBversion = "3.11.00.202";
6813 if ( CheckVersion($DBversion) ) {
6814    $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ca', 'language', 'Catalan','2013-01-12' )");
6815    $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'ca','cat')");
6816    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'es', 'Catalán')");
6817    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'en', 'Catalan')");
6818    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'fr', 'Catalan')");
6819    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'ca', 'Català')");
6820    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'de', 'Katalanisch')");
6821    print "Upgrade to $DBversion done (Bug 9381: Add Catalan laguage)\n";
6822    SetVersion ($DBversion);
6823 }
6824
6825 $DBversion = "3.11.00.203";
6826 if ( CheckVersion($DBversion) ) {
6827     $dbh->do(q{ALTER TABLE suggestions CHANGE COLUMN title title VARCHAR(255) DEFAULT NULL;});
6828     print "Upgrade to $DBversion done (Bug 2046 - increasing title column length for suggestions)\n";
6829     SetVersion ($DBversion);
6830 }
6831
6832 $DBversion = "3.11.00.300";
6833 if ( CheckVersion($DBversion) ) {
6834     print "Upgrade to $DBversion done (3.12-beta3 release)\n";
6835     SetVersion ($DBversion);
6836 }
6837
6838 $DBversion = "3.11.00.301";
6839 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6840     #issues
6841     $dbh->do(q{
6842         ALTER TABLE `issues`
6843             ADD KEY `itemnumber_idx` (`itemnumber`),
6844             ADD KEY `branchcode_idx` (`branchcode`),
6845             ADD KEY `issuingbranch_idx` (`issuingbranch`)
6846     });
6847     $dbh->do(q{
6848         ALTER TABLE `old_issues`
6849             ADD KEY `branchcode_idx` (`branchcode`),
6850             ADD KEY `issuingbranch_idx` (`issuingbranch`)
6851     });
6852     #items
6853     $dbh->do(q{
6854         ALTER TABLE `items` ADD KEY `itype_idx` (`itype`)
6855     });
6856     $dbh->do(q{
6857         ALTER TABLE `deleteditems` ADD KEY `itype_idx` (`itype`)
6858     });
6859     # biblioitems
6860     $dbh->do(q{
6861         ALTER TABLE `biblioitems` ADD KEY `itemtype_idx` (`itemtype`)
6862     });
6863     $dbh->do(q{
6864         ALTER TABLE `deletedbiblioitems` ADD KEY `itemtype_idx` (`itemtype`)
6865     });
6866     # statistics
6867     $dbh->do(q{
6868         ALTER TABLE `statistics`
6869             ADD KEY `branch_idx` (`branch`),
6870             ADD KEY `proccode_idx` (`proccode`),
6871             ADD KEY `type_idx` (`type`),
6872             ADD KEY `usercode_idx` (`usercode`),
6873             ADD KEY `itemnumber_idx` (`itemnumber`),
6874             ADD KEY `itemtype_idx` (`itemtype`),
6875             ADD KEY `borrowernumber_idx` (`borrowernumber`),
6876             ADD KEY `associatedborrower_idx` (`associatedborrower`),
6877             ADD KEY `ccode_idx` (`ccode`)
6878     });
6879
6880     print "Upgrade to $DBversion done (Bug 9681: Add some database indexes)\n";
6881     SetVersion($DBversion);
6882 }
6883
6884 $DBversion = "3.12.00.000";
6885 if ( CheckVersion($DBversion) ) {
6886     print "Upgrade to $DBversion done (3.12.0 release)\n";
6887     SetVersion ($DBversion);
6888 }
6889
6890 $DBversion = '3.13.00.000';
6891 if ( CheckVersion($DBversion) ) {
6892     print "Upgrade to $DBversion done (start the journey to Koha Pi)\n";
6893     SetVersion ($DBversion);
6894 }
6895
6896 $DBversion = "3.13.00.001";
6897 if ( CheckVersion($DBversion) ) {
6898     $dbh->do("INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('UseCourseReserves', '0', NULL, 'Enable the course reserves feature.', 'YesNo')");
6899     $dbh->do("INSERT INTO userflags (bit,flag,flagdesc,defaulton) VALUES ('18','coursereserves','Course Reserves','0')");
6900     $dbh->do("
6901 CREATE TABLE `courses` (
6902   `course_id` int(11) NOT NULL AUTO_INCREMENT,
6903   `department` varchar(20) DEFAULT NULL,
6904   `course_number` varchar(255) DEFAULT NULL,
6905   `section` varchar(255) DEFAULT NULL,
6906   `course_name` varchar(255) DEFAULT NULL,
6907   `term` varchar(20) DEFAULT NULL,
6908   `staff_note` mediumtext,
6909   `public_note` mediumtext,
6910   `students_count` varchar(20) DEFAULT NULL,
6911   `enabled` enum('yes','no') NOT NULL DEFAULT 'yes',
6912   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6913    PRIMARY KEY (`course_id`)
6914 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6915     ");
6916
6917     $dbh->do("
6918 CREATE TABLE `course_instructors` (
6919   `course_id` int(11) NOT NULL,
6920   `borrowernumber` int(11) NOT NULL,
6921   PRIMARY KEY (`course_id`,`borrowernumber`),
6922   KEY `borrowernumber` (`borrowernumber`)
6923 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6924     ");
6925
6926     $dbh->do("
6927 ALTER TABLE `course_instructors`
6928   ADD CONSTRAINT `course_instructors_ibfk_2` FOREIGN KEY (`course_id`) REFERENCES `courses` (`course_id`),
6929   ADD CONSTRAINT `course_instructors_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE;
6930     ");
6931
6932     $dbh->do("
6933 CREATE TABLE `course_items` (
6934   `ci_id` int(11) NOT NULL AUTO_INCREMENT,
6935   `itemnumber` int(11) NOT NULL,
6936   `itype` varchar(10) DEFAULT NULL,
6937   `ccode` varchar(10) DEFAULT NULL,
6938   `holdingbranch` varchar(10) DEFAULT NULL,
6939   `location` varchar(80) DEFAULT NULL,
6940   `enabled` enum('yes','no') NOT NULL DEFAULT 'no',
6941   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6942    PRIMARY KEY (`ci_id`),
6943    UNIQUE KEY `itemnumber` (`itemnumber`),
6944    KEY `holdingbranch` (`holdingbranch`)
6945 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6946     ");
6947
6948     $dbh->do("
6949 ALTER TABLE `course_items`
6950   ADD CONSTRAINT `course_items_ibfk_2` FOREIGN KEY (`holdingbranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
6951   ADD CONSTRAINT `course_items_ibfk_1` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE;
6952 ");
6953
6954     $dbh->do("
6955 CREATE TABLE `course_reserves` (
6956   `cr_id` int(11) NOT NULL AUTO_INCREMENT,
6957   `course_id` int(11) NOT NULL,
6958   `ci_id` int(11) NOT NULL,
6959   `staff_note` mediumtext,
6960   `public_note` mediumtext,
6961   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6962    PRIMARY KEY (`cr_id`),
6963    UNIQUE KEY `pseudo_key` (`course_id`,`ci_id`),
6964    KEY `course_id` (`course_id`)
6965 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6966 ");
6967
6968     $dbh->do("
6969 ALTER TABLE `course_reserves`
6970   ADD CONSTRAINT `course_reserves_ibfk_1` FOREIGN KEY (`course_id`) REFERENCES `courses` (`course_id`);
6971     ");
6972
6973     $dbh->do("
6974 INSERT INTO permissions (module_bit, code, description) VALUES
6975   (18, 'manage_courses', 'Add, edit and delete courses'),
6976   (18, 'add_reserves', 'Add course reserves'),
6977   (18, 'delete_reserves', 'Remove course reserves')
6978 ;
6979     ");
6980
6981
6982     print "Upgrade to $DBversion done (Add Course Reserves ( system preference UseCourseReserves ))\n";
6983     SetVersion($DBversion);
6984 }
6985
6986 $DBversion = "3.13.00.002";
6987 if ( CheckVersion($DBversion) ) {
6988    $dbh->do("UPDATE systempreferences SET variable = 'IndependentBranches' WHERE variable = 'IndependantBranches'");
6989    print "Upgrade to $DBversion done (Bug 10080 - Change system pref IndependantBranches to IndependentBranches)\n";
6990    SetVersion ($DBversion);
6991 }
6992
6993 $DBversion = '3.13.00.003';
6994 if ( CheckVersion($DBversion) ) {
6995     $dbh->do("ALTER TABLE serial DROP itemnumber");
6996     print "Upgrade to $DBversion done (Bug 7718 - Remove itemnumber column from serials table)\n";
6997     SetVersion($DBversion);
6998 }
6999
7000 $DBversion = "3.13.00.004";
7001 if(CheckVersion($DBversion)) {
7002     $dbh->do(
7003 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacShowHoldNotes',0,'Show hold notes on OPAC','','YesNo')"
7004     );
7005     print "Upgrade to $DBversion done (Bug 9722: Allow users to add notes when placing a hold in OPAC)\n";
7006     SetVersion($DBversion);
7007 }
7008
7009 $DBversion = "3.13.00.005";
7010 if(CheckVersion($DBversion)) {
7011     my $intra= C4::Context->preference("intranetstylesheet");
7012     #if this pref is not blank or starting with http, https or / [root], then
7013     #add an additional / to the front
7014     if($intra && $intra !~ /^(\/|https?)/) {
7015         $dbh->do("UPDATE systempreferences SET value=? WHERE variable=?",
7016             undef,('/'.$intra,"intranetstylesheet"));
7017         print "WARNING: Your system preference intranetstylesheet has been prefixed with a slash to make it an absolute path.\n";
7018     }
7019     print "Upgrade to $DBversion done (Bug 10052: Make intranetstylesheet and intranetcolorstylesheet behave exactly like their opac counterparts)\n";
7020     SetVersion ($DBversion);
7021 }
7022
7023 $DBversion = "3.13.00.006";
7024 if ( CheckVersion($DBversion) ) {
7025     $dbh->do(q{
7026         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
7027         VALUES ('CalculateFinesOnReturn','1','Switch to control if overdue fines are calculated on return or not', '', 'YesNo')
7028     });
7029     print "Upgrade to $DBversion done (Bug 10120: Fines on item return controlled by a systempreference)\n";
7030     SetVersion($DBversion);
7031 }
7032
7033 $DBversion = "3.13.00.007";
7034 if ( CheckVersion($DBversion) ) {
7035     $dbh->do("UPDATE systempreferences SET variable='OpacHoldNotes' WHERE variable='OpacShowHoldNotes'");
7036     print "Upgrade to $DBversion done (Bug 10343: Rename OpacShowHoldNotes to OpacHoldNotes)\n";
7037     SetVersion($DBversion);
7038 }
7039
7040 $DBversion = "3.13.00.008";
7041 if ( CheckVersion($DBversion) ) {
7042     $dbh->do("
7043 CREATE TABLE IF NOT EXISTS borrower_files (
7044   file_id int(11) NOT NULL AUTO_INCREMENT,
7045   borrowernumber int(11) NOT NULL,
7046   file_name varchar(255) NOT NULL,
7047   file_type varchar(255) NOT NULL,
7048   file_description varchar(255) DEFAULT NULL,
7049   file_content longblob NOT NULL,
7050   date_uploaded timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
7051   PRIMARY KEY (file_id),
7052   KEY borrowernumber (borrowernumber),
7053   CONSTRAINT borrower_files_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
7054 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7055     ");
7056     print "Upgrade to $DBversion done (Bug 10443: make sure borrower_files table exists)\n";
7057     SetVersion($DBversion);
7058 }
7059
7060 $DBversion = "3.13.00.009";
7061 if ( CheckVersion($DBversion) ) {
7062     $dbh->do("ALTER TABLE aqorders DROP COLUMN biblioitemnumber");
7063     print "Upgrade to $DBversion done (Bug 9987 - Drop column aqorders.biblioitemnumber)\n";
7064     SetVersion($DBversion);
7065 }
7066
7067 $DBversion = "3.13.00.010";
7068 if ( CheckVersion($DBversion) ) {
7069     $dbh->do(
7070         q{
7071 INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AcqWarnOnDuplicateInvoice','0','Warn librarians when they try to create a duplicate invoice', '', 'YesNo');
7072 }
7073     );
7074     print
7075 "Upgrade to $DBversion done (Bug 10366 - Add system preference to enabling warning librarian when invoice is duplicated)\n";
7076     SetVersion($DBversion);
7077 }
7078
7079 $DBversion = "3.13.00.011";
7080 if ( CheckVersion($DBversion) ) {
7081     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='ita' WHERE rfc4646_subtag='it'");
7082     print "Upgrade to $DBversion done (Bug 9519: Wrong language code for Italian in the advanced search language limitations)\n";
7083     SetVersion($DBversion);
7084 }
7085
7086 $DBversion = "3.13.00.012";
7087 if ( CheckVersion($DBversion) ) {
7088     $dbh->do("ALTER TABLE issuingrules MODIFY COLUMN overduefinescap decimal(28,6) DEFAULT NULL;");
7089     print "Upgrade to $DBversion done (Bug 10490: Correct datatype for overduefinescap in issuingrules)\n";
7090     SetVersion($DBversion);
7091 }
7092
7093 $DBversion ="3.13.00.013";
7094 if ( CheckVersion($DBversion) ) {
7095     $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');");
7096     print "Upgrade to $DBversion done (Bug 9576: add AllowTooManyOverride syspref to enable or disable issue limit confirmation)\n";
7097     SetVersion($DBversion);
7098 }
7099
7100 $DBversion = "3.13.00.014";
7101 if ( CheckVersion($DBversion) ) {
7102     $dbh->do("ALTER TABLE courses MODIFY COLUMN department varchar(80) DEFAULT NULL;");
7103     $dbh->do("ALTER TABLE courses MODIFY COLUMN term       varchar(80) DEFAULT NULL;");
7104     print "Upgrade to $DBversion done (Bug 10604: correct width of courses.department and courses.term)\n";
7105     SetVersion($DBversion);
7106 }
7107
7108 $DBversion = "3.13.00.015";
7109 if ( CheckVersion($DBversion) ) {
7110     $dbh->do(
7111 "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')"
7112     );
7113     print "Upgrade to $DBversion done (Bug 7494: Add itemBarcodeFallbackSearch syspref)\n";
7114     SetVersion($DBversion);
7115 }
7116
7117 $DBversion = "3.13.00.016";
7118 if ( CheckVersion($DBversion) ) {
7119     $dbh->do(q{
7120         ALTER TABLE items CHANGE wthdrawn withdrawn TINYINT( 1 ) NOT NULL DEFAULT  '0'
7121     });
7122
7123     $dbh->do(q{
7124         ALTER TABLE deleteditems CHANGE wthdrawn withdrawn TINYINT( 1 ) NOT NULL DEFAULT  '0'
7125     });
7126
7127     $dbh->do(q{
7128         UPDATE saved_sql SET savedsql = REPLACE(savedsql, 'wthdrawn', 'withdrawn')
7129     });
7130
7131     $dbh->do(q{
7132         UPDATE marc_subfield_structure SET kohafield = 'items.withdrawn' WHERE kohafield = 'items.wthdrawn'
7133     });
7134
7135     print "Upgrade to $DBversion done (Bug 10550 - Fix database typo wthdrawn)\n";
7136     SetVersion($DBversion);
7137 }
7138
7139 $DBversion = "3.13.00.017";
7140 if ( CheckVersion($DBversion) ) {
7141     $dbh->do(
7142 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveClientKey','','Client key for OverDrive integration','30','Free')"
7143     );
7144     $dbh->do(
7145 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveClientSecret','','Client key for OverDrive integration','30','YesNo')"
7146     );
7147     $dbh->do(
7148 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveLibraryID','','Library ID for OverDrive integration','','Integer')"
7149     );
7150     print "Upgrade to $DBversion done (Bug 10320 - Show results from library's OverDrive collection in OPAC search)\n";
7151     SetVersion($DBversion);
7152 }
7153
7154 $DBversion = "3.13.00.018";
7155 if ( CheckVersion($DBversion) ) {
7156     $dbh->do(qq{DROP TABLE IF EXISTS aqorders_transfers;});
7157     $dbh->do(qq{
7158         CREATE TABLE aqorders_transfers (
7159           ordernumber_from int(11) NULL,
7160           ordernumber_to int(11) NULL,
7161           timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
7162           UNIQUE KEY ordernumber_from (ordernumber_from),
7163           UNIQUE KEY ordernumber_to (ordernumber_to),
7164           CONSTRAINT aqorders_transfers_ordernumber_from FOREIGN KEY (ordernumber_from) REFERENCES aqorders (ordernumber) ON DELETE SET NULL ON UPDATE CASCADE,
7165           CONSTRAINT aqorders_transfers_ordernumber_to FOREIGN KEY (ordernumber_to) REFERENCES aqorders (ordernumber) ON DELETE SET NULL ON UPDATE CASCADE
7166         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7167     });
7168     print "Upgrade to $DBversion done (Bug 5349: Add aqorders_transfers table)\n";
7169     SetVersion($DBversion);
7170 }
7171
7172 $DBversion = "3.13.00.019";
7173 if ( CheckVersion($DBversion) ) {
7174     $dbh->do("ALTER TABLE itemtypes ADD COLUMN checkinmsg VARCHAR(255) AFTER summary;");
7175     $dbh->do("ALTER TABLE itemtypes ADD COLUMN checkinmsgtype CHAR(16) DEFAULT 'message' NOT NULL AFTER checkinmsg;");
7176     print "Upgrade to $DBversion done (Bug 10513 - Light up a warning/message when returning a chosen item type)\n";
7177     SetVersion($DBversion);
7178 }
7179
7180 $DBversion = "3.13.00.020";
7181 if ( CheckVersion($DBversion) ) {
7182     $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')");
7183     $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')");
7184     print "Upgrade to $DBversion done (Bug 7639: system preferences to forgive fines on lost items)\n";
7185     SetVersion($DBversion);
7186 }
7187
7188 $DBversion ="3.13.00.021";
7189 if ( CheckVersion($DBversion) ) {
7190     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ConfirmFutureHolds','0','Number of days for confirming future holds','','Integer');");
7191     print "Upgrade to $DBversion done (Bug 9761: Add ConfirmFutureHolds pref)\n";
7192     SetVersion($DBversion);
7193 }
7194
7195 $DBversion = "3.13.00.022";
7196 if ( CheckVersion($DBversion) ) {
7197     $dbh->do("DELETE from auth_tag_structure WHERE tagfield IN ('68a','68b')");
7198     $dbh->do("DELETE from auth_subfield_structure WHERE tagfield IN ('68a','68b')");
7199     print "Upgrade to $DBversion done (Bug 10687 - Delete erroneous tags 68a and 68b on default MARC21 auth framework)\n";
7200     SetVersion($DBversion);
7201 }
7202
7203 $DBversion = "3.13.00.023";
7204 if ( CheckVersion($DBversion) ) {
7205     $dbh->do("ALTER TABLE borrowers CHANGE password password VARCHAR(60);");
7206     print "Upgrade to $DBversion done (Bug 9611 upgrading password storage system)\n";
7207     SetVersion($DBversion);
7208 }
7209
7210 $DBversion = "3.13.00.024";
7211 if ( CheckVersion($DBversion) ) {
7212     $dbh->do(q{ALTER TABLE z3950servers ADD COLUMN recordtype VARCHAR(45) NOT NULL DEFAULT 'biblio' AFTER description;});
7213     print "Upgrade to $DBversion done (Bug 10096 - Add a Z39.50 interface for authority searching)\n";
7214 }
7215
7216 $DBversion = "3.13.00.025";
7217 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
7218    $dbh->do("ALTER TABLE oai_sets_mappings ADD COLUMN operator varchar(8) NOT NULL default 'equal' AFTER marcsubfield;");
7219    print "Upgrade to $DBversion done (Bug 9295: OAI notequal: add operator column to OAI mappings table)\n";
7220    SetVersion ($DBversion);
7221 }
7222
7223 $DBversion = "3.13.00.026";
7224 if ( CheckVersion($DBversion) ) {
7225     $dbh->do(q|
7226         ALTER TABLE auth_subfield_structure ADD COLUMN defaultvalue TEXT DEFAULT NULL AFTER frameworkcode
7227     |);
7228     print "Upgrade to $DBversion done (Bug 10602: Add the column auth_subfield_structure.defaultvalue)\n";
7229     SetVersion($DBversion);
7230 }
7231
7232 $DBversion = "3.13.00.027";
7233 if ( CheckVersion($DBversion) ) {
7234     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('AllowOfflineCirculation','0','','If on, enables HTML5 offline circulation functionality.','YesNo')");
7235     print "Upgrade to $DBversion done (Bug 10240: Add syspref AllowOfflineCirculation)\n";
7236     SetVersion ($DBversion);
7237 }
7238
7239 $DBversion = "3.13.00.028";
7240 if ( CheckVersion($DBversion) ) {
7241     $dbh->do(q{
7242         ALTER TABLE export_format ADD type VARCHAR(255) DEFAULT 'marc' AFTER encoding
7243     });
7244     $dbh->do(q{
7245         ALTER TABLE export_format CHANGE marcfields content mediumtext NOT NULL
7246     });
7247     print "Upgrade to $DBversion done (Bug 10853: Add new field export_format.type and rename export_format.marcfields with export_format.content)\n";
7248     SetVersion($DBversion);
7249 }
7250
7251 $DBversion = "3.13.00.029";
7252 if ( CheckVersion($DBversion) ) {
7253     $dbh->do(q{
7254         INSERT IGNORE INTO export_format( profile, description, content, csv_separator, type )
7255         VALUES ( "issues to claim", "Default CSV export for serial issue claims",
7256                 "SUPPLIER=aqbooksellers.name|TITLE=subscription.title|ISSUE NUMBER=serial.serialseq|LATE SINCE=serial.planneddate",
7257                 ",", "sql" )
7258     });
7259     print "Upgrade to $DBversion done (Bug 10854: Add the default CSV profile for claiming issues)\n";
7260     SetVersion($DBversion);
7261 }
7262
7263 $DBversion = "3.13.00.030";
7264 if ( CheckVersion($DBversion) ) {
7265     $dbh->do(qq{
7266         DELETE FROM patronimage WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowers.cardnumber = patronimage.cardnumber)
7267     });
7268
7269     $dbh->do(qq{
7270         ALTER TABLE patronimage ADD borrowernumber INT( 11 ) NULL FIRST
7271     });
7272
7273     $dbh->{AutoCommit} = 0;
7274     $dbh->{RaiseError} = 1;
7275
7276     eval {
7277         $dbh->do(qq{
7278             UPDATE patronimage LEFT JOIN borrowers USING ( cardnumber ) SET patronimage.borrowernumber = borrowers.borrowernumber
7279         });
7280         $dbh->commit();
7281     };
7282
7283     if ($@) {
7284         print "Upgrade to $DBversion done (Bug 10636 - patronimage should have borrowernumber as PK, not cardnumber) failed! Transaction aborted because $@\n";
7285         eval { $dbh->rollback };
7286     }
7287     else {
7288         $dbh->do(qq{
7289             ALTER TABLE patronimage DROP FOREIGN KEY patronimage_fk1
7290         });
7291         $dbh->do(qq{
7292             ALTER TABLE patronimage DROP PRIMARY KEY, ADD PRIMARY KEY( borrowernumber )
7293         });
7294         $dbh->do(qq{
7295             ALTER TABLE patronimage DROP cardnumber
7296         });
7297         $dbh->do(qq{
7298             ALTER TABLE patronimage ADD FOREIGN KEY ( borrowernumber ) REFERENCES borrowers ( borrowernumber ) ON DELETE CASCADE ON UPDATE CASCADE
7299         });
7300
7301         print "Upgrade to $DBversion done (Bug 10636 - patronimage should have borrowernumber as PK, not cardnumber)\n";
7302         SetVersion($DBversion);
7303     }
7304
7305     $dbh->{AutoCommit} = 1;
7306     $dbh->{RaiseError} = 0;
7307 }
7308
7309 $DBversion = "3.13.00.031";
7310 if ( CheckVersion($DBversion) ) {
7311
7312     $dbh->do(q{
7313         CREATE TABLE IF NOT EXISTS `patron_lists` (
7314           patron_list_id int(11) NOT NULL AUTO_INCREMENT,
7315           name varchar(255) CHARACTER SET utf8 NOT NULL,
7316           owner int(11) NOT NULL,
7317           PRIMARY KEY (patron_list_id),
7318           KEY owner (owner)
7319         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7320     });
7321
7322     $dbh->do(q{
7323         ALTER TABLE `patron_lists`
7324           ADD CONSTRAINT patron_lists_ibfk_1 FOREIGN KEY (`owner`) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE;
7325     });
7326
7327     $dbh->do(q{
7328         CREATE TABLE patron_list_patrons (
7329           patron_list_patron_id int(11) NOT NULL AUTO_INCREMENT,
7330           patron_list_id int(11) NOT NULL,
7331           borrowernumber int(11) NOT NULL,
7332           PRIMARY KEY (patron_list_patron_id),
7333           KEY patron_list_id (patron_list_id),
7334           KEY borrowernumber (borrowernumber)
7335         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7336     });
7337
7338     $dbh->do(q{
7339         ALTER TABLE `patron_list_patrons`
7340           ADD CONSTRAINT patron_list_patrons_ibfk_1 FOREIGN KEY (patron_list_id) REFERENCES patron_lists (patron_list_id) ON DELETE CASCADE ON UPDATE CASCADE,
7341           ADD CONSTRAINT patron_list_patrons_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE;
7342     });
7343
7344     $dbh->do(q{
7345         INSERT INTO permissions (module_bit, code, description) VALUES
7346         (13, 'manage_patron_lists', 'Add, edit and delete patron lists and their contents')
7347     });
7348
7349     print "Upgrade to $DBversion done (Bug 10565 - Add a 'Patron List' feature for storing and manipulating collections of patrons)\n";
7350     SetVersion($DBversion);
7351 }
7352
7353 $DBversion = "3.13.00.032";
7354 if ( CheckVersion($DBversion) ) {
7355     $dbh->do("ALTER TABLE aqorders ADD COLUMN orderstatus varchar(16) DEFAULT 'new' AFTER parent_ordernumber");
7356     $dbh->do("UPDATE aqorders SET orderstatus='ordered' WHERE basketno IN (SELECT basketno FROM aqbasket WHERE closedate IS NOT NULL)");
7357     $dbh->do(q{
7358         UPDATE aqorders SET orderstatus='partial'
7359         WHERE quantity > quantityreceived
7360         AND quantityreceived > 0
7361         AND ordernumber IN (
7362             SELECT parent_ordernumber
7363             FROM (
7364                 SELECT DISTINCT(parent_ordernumber)
7365                 FROM aqorders
7366                 WHERE ordernumber != parent_ordernumber
7367             ) AS aq
7368         )
7369         AND basketno IN (SELECT basketno FROM aqbasket WHERE closedate IS NOT NULL)
7370     });
7371     $dbh->do("UPDATE aqorders SET orderstatus='complete' WHERE quantity=quantityreceived");
7372     $dbh->do("UPDATE aqorders SET orderstatus='cancelled' WHERE datecancellationprinted IS NOT NULL");
7373     print "Upgrade to $DBversion done (Bug 5336: Add the new column aqorders.orderstatus)\n";
7374     SetVersion($DBversion);
7375 }
7376
7377 $DBversion = "3.13.00.033";
7378 if ( CheckVersion($DBversion) ) {
7379     $dbh->do(qq|
7380         DROP TABLE IF EXISTS subscription_frequencies
7381     |);
7382     $dbh->do(qq|
7383         CREATE TABLE subscription_frequencies (
7384             id INTEGER NOT NULL AUTO_INCREMENT,
7385             description TEXT NOT NULL,
7386             displayorder INT DEFAULT NULL,
7387             unit ENUM('day','week','month','year') DEFAULT NULL,
7388             unitsperissue INTEGER NOT NULL DEFAULT '1',
7389             issuesperunit INTEGER NOT NULL DEFAULT '1',
7390             PRIMARY KEY (id)
7391         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
7392     |);
7393
7394     $dbh->do(qq|
7395         DROP TABLE IF EXISTS subscription_numberpatterns
7396     |);
7397     $dbh->do(qq|
7398         CREATE TABLE subscription_numberpatterns (
7399             id INTEGER NOT NULL AUTO_INCREMENT,
7400             label VARCHAR(255) NOT NULL,
7401             displayorder INTEGER DEFAULT NULL,
7402             description TEXT NOT NULL,
7403             numberingmethod VARCHAR(255) NOT NULL,
7404             label1 VARCHAR(255) DEFAULT NULL,
7405             add1 INTEGER DEFAULT NULL,
7406             every1 INTEGER DEFAULT NULL,
7407             whenmorethan1 INTEGER DEFAULT NULL,
7408             setto1 INTEGER DEFAULT NULL,
7409             numbering1 VARCHAR(255) DEFAULT NULL,
7410             label2 VARCHAR(255) DEFAULT NULL,
7411             add2 INTEGER DEFAULT NULL,
7412             every2 INTEGER DEFAULT NULL,
7413             whenmorethan2 INTEGER DEFAULT NULL,
7414             setto2 INTEGER DEFAULT NULL,
7415             numbering2 VARCHAR(255) DEFAULT NULL,
7416             label3 VARCHAR(255) DEFAULT NULL,
7417             add3 INTEGER DEFAULT NULL,
7418             every3 INTEGER DEFAULT NULL,
7419             whenmorethan3 INTEGER DEFAULT NULL,
7420             setto3 INTEGER DEFAULT NULL,
7421             numbering3 VARCHAR(255) DEFAULT NULL,
7422             PRIMARY KEY (id)
7423         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
7424     |);
7425
7426     $dbh->do(qq|
7427         INSERT INTO subscription_frequencies (description, unit, unitsperissue, issuesperunit, displayorder)
7428         VALUES
7429             ('2/day', 'day', 1, 2, 1),
7430             ('1/day', 'day', 1, 1, 2),
7431             ('3/week', 'week', 1, 3, 3),
7432             ('1/week', 'week', 1, 1, 4),
7433             ('1/2 weeks', 'week', 2, 1, 5),
7434             ('1/3 weeks', 'week', 3, 1, 6),
7435             ('1/month', 'month', 1, 1, 7),
7436             ('1/2 months', 'month', 2, 1, 8),
7437             ('1/3 months', 'month', 3, 1, 9),
7438             ('2/year', 'month', 6, 1, 10),
7439             ('1/year', 'year', 1, 1, 11),
7440             ('1/2 year', 'year', 2, 1, 12),
7441             ('Irregular', NULL, 1, 1, 13)
7442     |);
7443
7444     # Used to link existing subscription to newly created frequencies
7445     my $frequencies_mapping = {     # keys are old frequency numbers, values are the new ones
7446         1 => 2,     # daily (n/week)
7447         2 => 4,     # 1/week
7448         3 => 5,     # 1/2 weeks
7449         4 => 6,     # 1/3 weeks
7450         5 => 7,     # 1/month
7451         6 => 8,     # 1/2 months (6/year)
7452         7 => 9,     # 1/3 months (1/quarter)
7453         8 => 9,    # 1/quarter (seasonal)
7454         9 => 10,    # 2/year
7455         10 => 11,   # 1/year
7456         11 => 12,   # 1/2 years
7457         12 => 1,    # 2/day
7458         16 => 13,   # Without periodicity
7459         32 => 13,   # Irregular
7460         48 => 13    # Unknown
7461     };
7462
7463     $dbh->do(qq|
7464         INSERT INTO subscription_numberpatterns
7465             (label, displayorder, description, numberingmethod,
7466             label1, add1, every1, whenmorethan1, setto1, numbering1,
7467             label2, add2, every2, whenmorethan2, setto2, numbering2,
7468             label3, add3, every3, whenmorethan3, setto3, numbering3)
7469         VALUES
7470             ('Number', 1, 'Simple Numbering method', 'No.{X}',
7471             'Number', 1, 1, 99999, 1, NULL,
7472             NULL, NULL, NULL, NULL, NULL, NULL,
7473             NULL, NULL, NULL, NULL, NULL, NULL),
7474
7475             ('Volume, Number, Issue', 2, 'Volume Number Issue 1', 'Vol.{X}, Number {Y}, Issue {Z}',
7476             'Volume', 1, 48, 99999, 1, NULL,
7477             'Number', 1, 4, 12, 1, NULL,
7478             'Issue', 1, 1, 4, 1, NULL),
7479
7480             ('Volume, Number', 3, 'Volume Number 1', 'Vol {X}, No {Y}',
7481             'Volume', 1, 12, 99999, 1, NULL,
7482             'Number', 1, 1, 12, 1, NULL,
7483             NULL, NULL, NULL, NULL, NULL, NULL),
7484
7485             ('Seasonal', 4, 'Season Year', '{X} {Y}',
7486             'Season', 1, 1, 3, 0, 'season',
7487             'Year', 1, 4, 99999, 1, NULL,
7488             NULL, NULL, NULL, NULL, NULL, NULL)
7489     |);
7490
7491     $dbh->do(qq|
7492         ALTER TABLE subscription
7493         MODIFY COLUMN numberpattern INTEGER DEFAULT NULL,
7494         MODIFY COLUMN periodicity INTEGER DEFAULT NULL
7495     |);
7496
7497     # Update existing subscriptions
7498
7499     my $query = qq|
7500         SELECT subscriptionid, periodicity, numberingmethod,
7501             add1, every1, whenmorethan1, setto1,
7502             add2, every2, whenmorethan2, setto2,
7503             add3, every3, whenmorethan3, setto3
7504         FROM subscription
7505         ORDER BY subscriptionid
7506     |;
7507     my $sth = $dbh->prepare($query);
7508     $sth->execute;
7509     my $insert_numberpatterns_sth = $dbh->prepare(qq|
7510         INSERT INTO subscription_numberpatterns
7511              (label, displayorder, description, numberingmethod,
7512             label1, add1, every1, whenmorethan1, setto1, numbering1,
7513             label2, add2, every2, whenmorethan2, setto2, numbering2,
7514             label3, add3, every3, whenmorethan3, setto3, numbering3)
7515         VALUES
7516             (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
7517     |);
7518     my $check_numberpatterns_sth = $dbh->prepare(qq|
7519         SELECT * FROM subscription_numberpatterns
7520         WHERE (add1 = ? OR (add1 IS NULL AND ? IS NULL)) AND (add2 = ? OR (add2 IS NULL AND ? IS NULL))
7521         AND (add3 = ? OR (add3 IS NULL AND ? IS NULL)) AND (every1 = ? OR (every1 IS NULL AND ? IS NULL))
7522         AND (every2 = ? OR (every2 IS NULL AND ? IS NULL)) AND (every3 = ? OR (every3 IS NULL AND ? IS NULL))
7523         AND (whenmorethan1 = ? OR (whenmorethan1 IS NULL AND ? IS NULL)) AND (whenmorethan2 = ? OR (whenmorethan2 IS NULL AND ? IS NULL))
7524         AND (whenmorethan3 = ? OR (whenmorethan3 IS NULL AND ? IS NULL)) AND (setto1 = ? OR (setto1 IS NULL AND ? IS NULL))
7525         AND (setto2 = ? OR (setto2 IS NULL AND ? IS NULL)) AND (setto3 = ? OR (setto3 IS NULL AND ? IS NULL))
7526         AND (numberingmethod = ? OR (numberingmethod IS NULL AND ? IS NULL))
7527         LIMIT 1
7528     |);
7529     my $update_subscription_sth = $dbh->prepare(qq|
7530         UPDATE subscription
7531         SET numberpattern = ?,
7532             periodicity = ?
7533         WHERE subscriptionid = ?
7534     |);
7535
7536     my $i = 1;
7537     while(my $sub = $sth->fetchrow_hashref) {
7538         $check_numberpatterns_sth->execute(
7539             $sub->{add1}, $sub->{add1}, $sub->{add2}, $sub->{add2}, $sub->{add3}, $sub->{add3},
7540             $sub->{every1}, $sub->{every1}, $sub->{every2}, $sub->{every2}, $sub->{every3}, $sub->{every3},
7541             $sub->{whenmorethan1}, $sub->{whenmorethan1}, $sub->{whenmorethan2}, $sub->{whenmorethan2},
7542             $sub->{whenmorethan3}, $sub->{whenmorethan3}, $sub->{setto1}, $sub->{setto1}, $sub->{setto2},
7543             $sub->{setto2}, $sub->{setto3}, $sub->{setto3}, $sub->{numberingmethod}, $sub->{numberingmethod}
7544         );
7545         my $p = $check_numberpatterns_sth->fetchrow_hashref;
7546         if (defined $p) {
7547             # Pattern already exists, link to it
7548             $update_subscription_sth->execute($p->{id},
7549                 $frequencies_mapping->{$sub->{periodicity}},
7550                 $sub->{subscriptionid});
7551         } else {
7552             # Create a new numbering pattern for this subscription
7553             my $ok = $insert_numberpatterns_sth->execute(
7554                 "Backup pattern $i", 4+$i, "Automatically created pattern by updatedatabase", $sub->{numberingmethod},
7555                 "X", $sub->{add1}, $sub->{every1}, $sub->{whenmorethan1}, $sub->{setto1}, undef,
7556                 "Y", $sub->{add2}, $sub->{every2}, $sub->{whenmorethan2}, $sub->{setto2}, undef,
7557                 "Z", $sub->{add3}, $sub->{every3}, $sub->{whenmorethan3}, $sub->{setto3}, undef
7558             );
7559             if($ok) {
7560                 my $id = $dbh->last_insert_id(undef, undef, 'subscription_numberpatterns', undef);
7561                 # Link to subscription_numberpatterns and subscription_frequencies
7562                 $update_subscription_sth->execute($id,
7563                     $frequencies_mapping->{$sub->{periodicity}},
7564                     $sub->{subscriptionid});
7565             }
7566             $i++;
7567         }
7568     }
7569
7570     # Remove now useless columns
7571     $dbh->do(qq|
7572         ALTER TABLE subscription
7573         DROP COLUMN numberingmethod,
7574         DROP COLUMN add1,
7575         DROP COLUMN every1,
7576         DROP COLUMN whenmorethan1,
7577         DROP COLUMN setto1,
7578         DROP COLUMN add2,
7579         DROP COLUMN every2,
7580         DROP COLUMN whenmorethan2,
7581         DROP COLUMN setto2,
7582         DROP COLUMN add3,
7583         DROP COLUMN every3,
7584         DROP COLUMN whenmorethan3,
7585         DROP COLUMN setto3,
7586         DROP COLUMN dow,
7587         DROP COLUMN issuesatonce,
7588         DROP COLUMN hemisphere,
7589         ADD COLUMN countissuesperunit INTEGER NOT NULL DEFAULT 1 AFTER periodicity,
7590         ADD COLUMN skip_serialseq BOOLEAN NOT NULL DEFAULT 0 AFTER irregularity,
7591         ADD COLUMN locale VARCHAR(80) DEFAULT NULL AFTER numberpattern,
7592         ADD CONSTRAINT subscription_ibfk_1 FOREIGN KEY (periodicity) REFERENCES subscription_frequencies (id) ON DELETE SET NULL ON UPDATE CASCADE,
7593         ADD CONSTRAINT subscription_ibfk_2 FOREIGN KEY (numberpattern) REFERENCES subscription_numberpatterns (id) ON DELETE SET NULL ON UPDATE CASCADE
7594     |);
7595
7596     # Set firstacquidate if not already set (firstacquidate is now mandatory)
7597     my $get_first_planneddate_sth = $dbh->prepare(qq|
7598         SELECT planneddate
7599         FROM serial
7600         WHERE subscriptionid = ?
7601         ORDER BY serialid
7602         LIMIT 1
7603     |);
7604     my $update_firstacquidate_sth = $dbh->prepare(qq|
7605         UPDATE subscription
7606         SET firstacquidate = ?
7607         WHERE subscriptionid = ?
7608     |);
7609
7610     sanitize_zero_date('subscription', 'firstacquidate');
7611     my $get_subscriptions_sth = $dbh->prepare(qq|
7612         SELECT subscriptionid, startdate
7613         FROM subscription
7614         WHERE firstacquidate IS NULL
7615           OR firstacquidate = '0000-00-00'
7616     |);
7617     $get_subscriptions_sth->execute;
7618     while ( my ($subscriptionid, $startdate) = $get_subscriptions_sth->fetchrow ) {
7619         # Try to get the planned date of the first serial
7620         $get_first_planneddate_sth->execute($subscriptionid);
7621         my ($first_planneddate) = $get_first_planneddate_sth->fetchrow;
7622         if ($first_planneddate and $first_planneddate =~ /^\d{4}-\d{2}-\d{2}$/) {
7623             $update_firstacquidate_sth->execute($first_planneddate, $subscriptionid);
7624         } else {
7625             # Defaults to subscription start date
7626             $update_firstacquidate_sth->execute($startdate, $subscriptionid);
7627         }
7628     }
7629
7630     print "Upgrade to $DBversion done (Bug 7688: add subscription_frequencies and subscription_numberpatterns tables)\n";
7631     SetVersion($DBversion);
7632 }
7633
7634 $DBversion = "3.13.00.034";
7635 if ( CheckVersion($DBversion) ) {
7636     $dbh->do("
7637         ALTER TABLE `import_batches`
7638         CHANGE `item_action` `item_action`
7639           ENUM( 'always_add', 'add_only_for_matches', 'add_only_for_new', 'ignore', 'replace' )
7640           NOT NULL DEFAULT 'always_add'
7641     ");
7642     print "Upgrade to $DBversion done (Bug 7131 - way to overlay items in in marc import)\n";
7643     SetVersion($DBversion);
7644 }
7645
7646 $DBversion ="3.13.00.035";
7647 if ( CheckVersion($DBversion) ) {
7648     $dbh->do(q{
7649 CREATE TABLE borrower_debarments (
7650   borrower_debarment_id int(11) NOT NULL AUTO_INCREMENT,
7651   borrowernumber int(11) NOT NULL,
7652   expiration date DEFAULT NULL,
7653   `type` enum('SUSPENSION','OVERDUES','MANUAL') NOT NULL DEFAULT 'MANUAL',
7654   `comment` text,
7655   manager_id int(11) DEFAULT NULL,
7656   created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
7657   updated timestamp NULL DEFAULT NULL,
7658   PRIMARY KEY (borrower_debarment_id),
7659   KEY borrowernumber (borrowernumber) ,
7660   CONSTRAINT `borrower_debarments_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
7661     ON DELETE CASCADE ON UPDATE CASCADE
7662 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7663     });
7664
7665     # debarments with end date
7666     $dbh->do(q{
7667 INSERT INTO borrower_debarments ( borrowernumber, expiration, comment ) SELECT borrowernumber, debarred, debarredcomment FROM borrowers WHERE debarred IS NOT NULL AND debarred <> '9999-12-31'
7668     });
7669     # debarments with no end date
7670     $dbh->do(q{
7671 INSERT INTO borrower_debarments ( borrowernumber, comment ) SELECT borrowernumber, debarredcomment FROM borrowers WHERE debarred = '9999-12-31'
7672     });
7673
7674     $dbh->do(q{
7675 INSERT IGNORE INTO systempreferences (variable,value,explanation,type) VALUES
7676 ('AutoRemoveOverduesRestrictions','0','Defines whether an OVERDUES debarment should be lifted automatically if all overdue items are returned by the patron.','YesNo')
7677     });
7678
7679     print "Upgrade to $DBversion done (Bug 2720 - Overdues which debar automatically should undebar automatically when returned)\n";
7680     SetVersion($DBversion);
7681 }
7682
7683 $DBversion = "3.13.00.036";
7684 if ( CheckVersion($DBversion) ) {
7685     $dbh->do(qq{
7686         INSERT INTO systempreferences (variable, value, explanation, options, type)
7687         VALUES ('StaffDetailItemSelection', '1', 'Enable item selection in record detail page', NULL, 'YesNo')
7688     });
7689     print "Upgrade to $DBversion done (Add system preference StaffDetailItemSelection)\n";
7690     SetVersion($DBversion);
7691 }
7692
7693 $DBversion = "3.13.00.037";
7694 if ( CheckVersion($DBversion) ) {
7695     #add phone if it is not there already (explains the ignore option)
7696     $dbh->do("
7697 INSERT IGNORE INTO message_transport_types (message_transport_type) values ('phone');
7698     ");
7699     print "Upgrade to $DBversion done (Bug 10572: Add phone to message_transport_types table for new installs)\n";
7700     SetVersion($DBversion);
7701 }
7702
7703 $DBversion = "3.13.00.038";
7704 if ( CheckVersion($DBversion) ) {
7705     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES(15, 'superserials', 'Manage subscriptions from any branch (only applies when IndependentBranches is used)')");
7706     print "Upgrade to $DBversion done (Bug 8435: Add superserials permission)\n";
7707     SetVersion($DBversion);
7708 }
7709
7710 $DBversion = "3.13.00.039";
7711 if ( CheckVersion($DBversion) ) {
7712     $dbh->do("
7713         ALTER TABLE aqbasket ADD branch varchar(10) default NULL
7714     ");
7715     $dbh->do("
7716         ALTER TABLE aqbasket
7717         ADD CONSTRAINT aqbasket_ibfk_4 FOREIGN KEY (branch)
7718             REFERENCES branches (branchcode)
7719             ON UPDATE CASCADE ON DELETE SET NULL
7720     ");
7721     $dbh->do("
7722         DROP TABLE IF EXISTS aqbasketusers
7723     ");
7724     $dbh->do("
7725         CREATE TABLE aqbasketusers (
7726             basketno int(11) NOT NULL,
7727             borrowernumber int(11) NOT NULL,
7728             PRIMARY KEY (basketno,borrowernumber),
7729             CONSTRAINT aqbasketusers_ibfk_1 FOREIGN KEY (basketno) REFERENCES aqbasket (basketno) ON DELETE CASCADE ON UPDATE CASCADE,
7730             CONSTRAINT aqbasketusers_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
7731         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7732     ");
7733     $dbh->do("
7734         INSERT INTO permissions (module_bit, code, description)
7735         VALUES (11, 'order_manage_all', 'Manage all orders and baskets, regardless of restrictions on them')
7736     ");
7737
7738     print "Upgrade to $DBversion done (Add branch and users list to baskets. "
7739         . "New permission order_manage_all)\n";
7740     SetVersion($DBversion);
7741 }
7742
7743 $DBversion = "3.13.00.040";
7744 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
7745     $dbh->do("CREATE TABLE IF NOT EXISTS marc_modification_templates (
7746               template_id int(11) NOT NULL auto_increment,
7747               name text NOT NULL,
7748               PRIMARY KEY  (template_id)
7749               ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;"
7750     );
7751
7752     $dbh->do("
7753       CREATE TABLE IF NOT EXISTS marc_modification_template_actions (
7754       mmta_id int(11) NOT NULL auto_increment,
7755       template_id int(11) NOT NULL,
7756       ordering int(3) NOT NULL,
7757       action enum('delete_field','update_field','move_field','copy_field') NOT NULL,
7758       field_number smallint(6) NOT NULL default '0',
7759       from_field varchar(3) NOT NULL,
7760       from_subfield varchar(1) NULL,
7761       field_value varchar(100) default NULL,
7762       to_field varchar(3) default NULL,
7763       to_subfield varchar(1) default NULL,
7764       to_regex_search text,
7765       to_regex_replace text,
7766       to_regex_modifiers varchar(8) default '',
7767       conditional enum('if','unless') default NULL,
7768       conditional_field varchar(3) default NULL,
7769       conditional_subfield varchar(1) default NULL,
7770       conditional_comparison enum('exists','not_exists','equals','not_equals') default NULL,
7771       conditional_value text,
7772       conditional_regex tinyint(1) NOT NULL default '0',
7773       description text,
7774       PRIMARY KEY  (mmta_id),
7775       CONSTRAINT `mmta_ibfk_1` FOREIGN KEY (`template_id`) REFERENCES `marc_modification_templates` (`template_id`) ON DELETE CASCADE ON UPDATE CASCADE
7776       ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7777     ");
7778
7779     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('13', 'marc_modification_templates', 'Manage marc modification templates')");
7780
7781     print "Upgrade to $DBversion done ( Bug 8015: Added tables for MARC Modification Framework )\n";
7782     SetVersion($DBversion);
7783 }
7784
7785 $DBversion = "3.13.00.041";
7786 if(CheckVersion($DBversion)) {
7787     $dbh->do(q{
7788         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');
7789     });
7790     print "Upgrade to $DBversion done (Bug 10986: Added AcqItemSetSubfieldsWhenReceived syspref)\n";
7791     SetVersion($DBversion);
7792 }
7793
7794 $DBversion = "3.13.00.042";
7795 if(CheckVersion($DBversion)) {
7796     print "Upgrade to $DBversion done (Koha 3.14 beta)\n";
7797     SetVersion($DBversion);
7798 }
7799
7800 $DBversion = "3.13.00.043";
7801 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
7802     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('SearchEngine','Zebra','Solr|Zebra','Search Engine','Choice')");
7803     print "Upgrade to $DBversion done (Bug 11196: Add system preference SearchEngine if missing )\n";
7804     SetVersion($DBversion);
7805 }
7806
7807 $DBversion = "3.14.00.000";
7808 if ( CheckVersion($DBversion) ) {
7809     print "Upgrade to $DBversion done (3.14.0 release)\n";
7810     SetVersion ($DBversion);
7811 }
7812
7813 $DBversion = '3.15.00.000';
7814 if ( CheckVersion($DBversion) ) {
7815     print "Upgrade to $DBversion done (the road goes ever on)\n";
7816     SetVersion ($DBversion);
7817 }
7818
7819 $DBversion = "3.15.00.001";
7820 if ( CheckVersion($DBversion) ) {
7821     $dbh->do("UPDATE systempreferences SET value='clear' where variable = 'CircAutoPrintQuickSlip' and value = '0'");
7822     $dbh->do("UPDATE systempreferences SET value='qslip' where variable = 'CircAutoPrintQuickSlip' and value = '1'");
7823     $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'");
7824     print "Upgrade to $DBversion done (Bug 11040: Add option to print full slip when checking out a null barcode)\n";
7825     SetVersion($DBversion);
7826 }
7827
7828 $DBversion = "3.15.00.002";
7829 if(CheckVersion($DBversion)) {
7830     $dbh->do("ALTER TABLE deleteditems MODIFY materials text;");
7831     print "Upgrade to $DBversion done (Bug 11275: alter deleteditems.materials from varchar(10) to text)\n";
7832     SetVersion($DBversion);
7833 }
7834
7835 $DBversion = "3.15.00.003";
7836 if ( CheckVersion($DBversion) ) {
7837     $dbh->do(q{
7838         UPDATE accountlines
7839         SET description = ''
7840         WHERE description IN (
7841             ' New Card',
7842             ' Fine',
7843             ' Sundry',
7844             'Writeoff',
7845             ' Account Management fee',
7846             'Payment,thanks', 'Payment,thanks - ',
7847             ' Lost Item'
7848         )
7849     });
7850     print "Upgrade to $DBversion done (Bug 2546: Update fine descriptions)\n";
7851     SetVersion($DBversion);
7852 }
7853
7854 $DBversion = "3.15.00.004";
7855 if ( CheckVersion($DBversion) ) {
7856     if ( C4::Context->preference("marcflavour") eq 'MARC21' ) {
7857         $dbh->do(qq{
7858             INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian, libopac, repeatable, mandatory,
7859             kohafield, tab, authorised_value, authtypecode, value_builder, isurl, hidden, frameworkcode, seealso, link,
7860             defaultvalue) VALUES
7861             ('015', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7862             ('020', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7863             ('024', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7864             ('027', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7865             ('800', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7866             ('810', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7867             ('811', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7868             ('830', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL);
7869         });
7870         $dbh->do(qq{
7871             INSERT IGNORE INTO auth_subfield_structure (authtypecode, tagfield, tagsubfield, liblibrarian, libopac, repeatable,
7872             mandatory, tab, authorised_value, value_builder, seealso, isurl, hidden, linkid, kohafield, frameworkcode) VALUES
7873             ('', '020', 'q', 'Qualifying information', 'Qualifying information', 1, 0, 0, NULL, NULL, NULL, 0, 0, '', '', ''),
7874             ('', '024', 'q', 'Qualifying information', 'Qualifying information', 1, 0, 0, NULL, NULL, NULL, 0, 0, '', '', '');
7875         });
7876     }
7877     print "Upgrade to $DBversion done (Bug 10970 - Update MARC21 frameworks to Update Nr. 17 - DB update)\n";
7878     SetVersion($DBversion);
7879 }
7880
7881 $DBversion = "3.15.00.005";
7882 if ( CheckVersion($DBversion) ) {
7883    $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('AcquisitionDetails', '1', '', 'Hide/Show acquisition details on the biblio detail page.', 'YesNo');");
7884    print "Upgrade to $DBversion done (Bug 8230: Add AcquisitionDetails system preference)\n";
7885    SetVersion ($DBversion);
7886 }
7887
7888 $DBversion = "3.15.00.006";
7889 if(CheckVersion($DBversion)) {
7890     $dbh->do(q{
7891         ALTER TABLE `borrowers`
7892         ADD KEY `surname_idx` (`surname`(255)),
7893         ADD KEY `firstname_idx` (`firstname`(255)),
7894         ADD KEY `othernames_idx` (`othernames`(255))
7895     });
7896     print "Upgrade to $DBversion done (Bug 11249 - Add DB indexes on borrower names)\n";
7897     SetVersion($DBversion);
7898 }
7899
7900 $DBversion = "3.15.00.007";
7901 if ( CheckVersion($DBversion) ) {
7902    $dbh->do("ALTER TABLE items ADD itemlost_on DATETIME NULL AFTER itemlost");
7903    $dbh->do("ALTER TABLE items ADD withdrawn_on DATETIME NULL AFTER withdrawn");
7904    $dbh->do("ALTER TABLE deleteditems ADD itemlost_on DATETIME NULL AFTER itemlost");
7905    $dbh->do("ALTER TABLE deleteditems ADD withdrawn_on DATETIME NULL AFTER withdrawn");
7906    print "Upgrade to $DBversion done (Bug 9673 - Track when items are marked as lost or withdrawn)\n";
7907    SetVersion ($DBversion);
7908 }
7909
7910 $DBversion = "3.15.00.008";
7911 if ( CheckVersion($DBversion) ) {
7912     $dbh->do(q{
7913         ALTER TABLE collections_tracking CHANGE ctId collections_tracking_id integer(11) NOT NULL auto_increment;
7914     });
7915     print "Upgrade to $DBversion done (Bug 11384) - change name of collections_tracker.ctId column)\n";
7916    SetVersion ($DBversion);
7917 }
7918
7919 $DBversion = "3.15.00.009";
7920 if ( CheckVersion($DBversion) ) {
7921     $dbh->do(q{
7922         ALTER TABLE suggestions MODIFY suggesteddate DATE NOT NULL
7923     });
7924     print "Upgrade to $DBversion done (Bug 11391) - drop default value on suggestions.suggesteddate column)\n";
7925    SetVersion ($DBversion);
7926 }
7927
7928 $DBversion = "3.15.00.010";
7929 if(CheckVersion($DBversion)) {
7930     $dbh->do("ALTER TABLE deleteditems DROP COLUMN marc");
7931     print "Upgrade to $DBversion done (Bug 6331: remove obsolete column in deleteditems.marc)\n";
7932     SetVersion ($DBversion);
7933 }
7934
7935 $DBversion = "3.15.00.011";
7936 if(CheckVersion($DBversion)) {
7937     $dbh->do("UPDATE marc_subfield_structure SET maxlength=9999 WHERE maxlength IS NULL OR maxlength=0;");
7938     print "Upgrade to $DBversion done (Bug 8018: set 9999 as default max length for subfields)\n";
7939     SetVersion ($DBversion);
7940 }
7941
7942 $DBversion = "3.15.00.012";
7943 if ( CheckVersion($DBversion) ) {
7944     $dbh->do(q{
7945         INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'force_checkout', 'Force checkout if a limitation exists')
7946     });
7947     $dbh->do(q{
7948         INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'manage_restrictions', 'Manage restrictions for accounts')
7949     });
7950     $dbh->do(q{
7951         INSERT INTO user_permissions (borrowernumber, module_bit, code)
7952             SELECT user_permissions.borrowernumber, 1, 'force_checkout'
7953             FROM user_permissions
7954             LEFT JOIN borrowers USING(borrowernumber)
7955             WHERE borrowers.flags & (1 << 1)
7956     });
7957     $dbh->do(q{
7958         INSERT INTO user_permissions (borrowernumber, module_bit, code)
7959             SELECT user_permissions.borrowernumber, 1, 'manage_restrictions'
7960             FROM user_permissions
7961             LEFT JOIN borrowers USING(borrowernumber)
7962             WHERE borrowers.flags & (1 << 1)
7963     });
7964
7965     print "Upgrade to $DBversion done (Bug 10863 - Add permissions force_checkout and manage_restrictions)\n";
7966     SetVersion($DBversion);
7967 }
7968
7969 $DBversion = "3.15.00.013";
7970 if(CheckVersion($DBversion)) {
7971     $dbh->do(q{
7972         UPDATE systempreferences
7973         SET explanation = 'Upon receiving items, update their subfields if they were created when placing an order (e.g. o=5|a="foo bar")'
7974         WHERE variable = "AcqItemSetSubfieldsWhenReceived"
7975     });
7976
7977     $dbh->do(q{
7978         UPDATE systempreferences
7979         SET value = ''
7980         WHERE variable = "AcqItemSetSubfieldsWhenReceived"
7981             AND value = "0"
7982     });
7983     print "Upgrade to $DBversion done (Bug 11237: Update explanation and default value for AcqItemSetSubfieldsWhenReceived syspref)\n";
7984     SetVersion($DBversion);
7985 }
7986
7987 $DBversion = "3.15.00.014";
7988 if (CheckVersion($DBversion)) {
7989     $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');");
7990     print "Upgrade to $DBversion done (Bug 11415: add system preference for automatic self checkout receipt printing)\n";
7991     SetVersion($DBversion);
7992 }
7993
7994 $DBversion = "3.15.00.015";
7995 if (CheckVersion($DBversion)) {
7996     $dbh->do("INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
7997         ('OpacSuggestionManagedBy',1,'','Show the name of the staff member who managed a suggestion in OPAC','YesNo');");
7998     print "Upgrade to $DBversion done (Bug 10907: Add OpacSuggestionManagedBy system preference)\n";
7999     SetVersion($DBversion);
8000 }
8001
8002 $DBversion = "3.15.00.016";
8003 if (CheckVersion($DBversion)) {
8004     $dbh->do("ALTER TABLE biblioitems CHANGE url url TEXT NULL DEFAULT NULL");
8005     $dbh->do("ALTER TABLE deletedbiblioitems CHANGE url url TEXT NULL DEFAULT NULL");
8006     print "Upgrade to $DBversion done (Bug 11268 - Biblioitems URL field is too small for some URLs)\n";
8007     SetVersion($DBversion);
8008 }
8009
8010 $DBversion = "3.15.00.017";
8011 if(CheckVersion($DBversion)) {
8012     $dbh->do(q{
8013         UPDATE systempreferences
8014         SET explanation = 'Define the contents of UNIMARC authority control field 100 position 08-35'
8015         WHERE variable = "UNIMARCAuthorityField100"
8016     });
8017     $dbh->do(q{
8018         UPDATE systempreferences
8019         SET explanation = 'Define the contents of MARC21 authority control field 008 position 06-39'
8020         WHERE variable = "MARCAuthorityControlField008"
8021     });
8022     $dbh->do(q{
8023         UPDATE systempreferences
8024         SET explanation = 'Define MARC Organization Code for MARC21 records - http://www.loc.gov/marc/organizations/orgshome.html'
8025         WHERE variable = "MARCOrgCode"
8026     });
8027     print "Upgrade to $DBversion done (Bug 11611 - fix possible confusion between UNIMARC and MARC21 in some sysprefs)\n";
8028     SetVersion($DBversion);
8029 }
8030
8031 $DBversion = "3.15.00.018";
8032 if ( CheckVersion($DBversion) ) {
8033     $dbh->{AutoCommit} = 0;
8034     $dbh->{RaiseError} = 1;
8035
8036     eval {
8037         $dbh->selectcol_arrayref(q|SELECT COUNT(*) FROM roadtype|);
8038     };
8039     unless ( $@ ) {
8040         my $av_added = $dbh->do(q|
8041             INSERT INTO authorised_values(category, authorised_value, lib, lib_opac)
8042                 SELECT 'ROADTYPE', roadtypeid, road_type, road_type
8043                 FROM roadtype;
8044         |);
8045
8046         my $rt_deleted = $dbh->do(q|
8047             DELETE FROM roadtype
8048         |);
8049
8050         if ( $av_added == $rt_deleted or $rt_deleted eq "0E0" ) {
8051             $dbh->do(q|
8052                 DROP TABLE roadtype;
8053             |);
8054             $dbh->commit;
8055             print "Upgrade to $DBversion done (Bug 7372: Move road types from the roadtype table to the ROADTYPE authorised values)\n";
8056             SetVersion($DBversion);
8057         } else {
8058             print "Upgrade to $DBversion failed (Bug 7372: Move road types from the roadtype table to the ROADTYPE authorised values.\nTransaction aborted because $@\n)";
8059             $dbh->rollback;
8060         }
8061     }
8062     $dbh->{AutoCommit} = 1;
8063     $dbh->{RaiseError} = 0;
8064 }
8065
8066 $DBversion = "3.15.00.019";
8067 if ( CheckVersion($DBversion) ) {
8068     $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')");
8069     print "Upgrade to $DBversion done (Bug 11256: Add system preference OpacMaxItemsToDisplay)\n";
8070     SetVersion($DBversion);
8071 }
8072
8073 $DBversion = "3.15.00.020";
8074 if ( CheckVersion($DBversion) ) {
8075     $dbh->do(q|
8076         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')
8077     |);
8078     print "Upgrade to $DBversion done (Bug 11343: Add system preference MaxItemsForBatch )\n";
8079     SetVersion($DBversion);
8080 }
8081
8082 $DBversion = "3.15.00.021";
8083 if(CheckVersion($DBversion)) {
8084     $dbh->do(q{
8085         ALTER TABLE `action_logs`
8086             DROP KEY timestamp,
8087             ADD KEY `timestamp_idx` (`timestamp`),
8088             ADD KEY `user_idx` (`user`),
8089             ADD KEY `module_idx` (`module`(255)),
8090             ADD KEY `action_idx` (`action`(255)),
8091             ADD KEY `object_idx` (`object`),
8092             ADD KEY `info_idx` (`info`(255))
8093     });
8094     print "Upgrade to $DBversion done (Bug 3445: Add indexes to action_logs table)\n";
8095     SetVersion($DBversion);
8096 }
8097
8098 $DBversion = "3.15.00.022";
8099 if (CheckVersion($DBversion)) {
8100     $dbh->do(q|
8101         DELETE FROM systempreferences WHERE variable= "memberofinstitution"
8102     |);
8103     print "Upgrade to $DBversion done (Bug 11751: Remove memberofinstitytion system preference)\n";
8104     SetVersion($DBversion);
8105 }
8106
8107 $DBversion = "3.15.00.023";
8108 if ( CheckVersion($DBversion) ) {
8109    $dbh->do("
8110        INSERT INTO systempreferences (variable,value,options,explanation,type)
8111        VALUES('CardnumberLength', '', '', 'Set a length for card numbers.', 'Free');
8112     ");
8113    print "Upgrade to $DBversion done (Bug 10861: Add CardnumberLength syspref)\n";
8114    SetVersion ($DBversion);
8115 }
8116
8117 $DBversion = "3.15.00.024";
8118 if ( CheckVersion($DBversion) ) {
8119     $dbh->do(q{
8120         DELETE FROM systempreferences WHERE variable = 'NoZebraIndexes'
8121     });
8122     print "Upgrade to $DBversion done (Bug 10012 - remove last vestiges of NoZebra)\n";
8123     SetVersion($DBversion);
8124 }
8125
8126 $DBversion = "3.15.00.025";
8127 if ( CheckVersion($DBversion) ) {
8128     $dbh->do(q{
8129         DROP TABLE aqorderdelivery;
8130     });
8131     print "Upgrade to $DBversion done (Bug 11928 - remove unused table)\n";
8132     SetVersion($DBversion);
8133 }
8134
8135 $DBversion = "3.15.00.026";
8136 if ( CheckVersion($DBversion) ) {
8137     $dbh->do(q{
8138         UPDATE language_descriptions SET description = 'Հայերեն' WHERE subtag = 'hy' AND lang = 'hy';
8139     });
8140     print "Upgrade to $DBversion done (Bug 11973 - Fix Armenian language description)\n";
8141     SetVersion($DBversion);
8142 }
8143
8144 $DBversion = "3.15.00.027";
8145 if (CheckVersion($DBversion)) {
8146     $dbh->do(q{
8147         ALTER TABLE opac_news ADD branchcode varchar(10) DEFAULT NULL
8148                                   AFTER idnew,
8149                               ADD CONSTRAINT opac_news_branchcode_ibfk
8150                                   FOREIGN KEY (branchcode)
8151                                   REFERENCES branches (branchcode)
8152                                   ON DELETE CASCADE ON UPDATE CASCADE;
8153     });
8154     print "Upgrade to $DBversion done (Bug 7567: Add branchcode to opac_news)\n";
8155     SetVersion($DBversion);
8156 }
8157
8158 $DBversion = "3.15.00.028";
8159 if(CheckVersion($DBversion)) {
8160     $dbh->do(q{
8161         ALTER TABLE issuingrules ADD norenewalbefore int(4) default NULL AFTER renewalperiod
8162     });
8163     print "Upgrade to $DBversion done (Bug 7413: Allow OPAC renewal x days before due date)\n";
8164     SetVersion($DBversion);
8165 }
8166
8167 $DBversion = "3.15.00.029";
8168 if ( CheckVersion($DBversion) ) {
8169     $dbh->do(q{
8170         UPDATE borrower_debarments SET expiration = NULL WHERE expiration = '9999-12-31'
8171     });
8172     print "Upgrade to $DBversion done (Bug 11846 - correct borrower_debarments with expiration 9999-12-31)\n";
8173     SetVersion($DBversion);
8174 }
8175
8176 $DBversion = "3.15.00.030";
8177 if(CheckVersion($DBversion)) {
8178     $dbh->do(q|
8179         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')
8180     |);
8181     print "Upgrade to $DBversion done (Bug 12052: Add OPACMySummaryNote syspref)\n";
8182     SetVersion($DBversion);
8183 }
8184
8185 $DBversion = "3.15.00.031";
8186 if ( CheckVersion($DBversion) ) {
8187    $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('10', 'writeoff', 'Write off fines and fees')");
8188    $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('10', 'remaining_permissions', 'Remaining permissions for managing fines and fees')");
8189    print "Upgrade to $DBversion done (Bug 9448 - Add separate permission for writing off fees)\n";
8190    SetVersion ($DBversion);
8191 }
8192
8193 $DBversion = "3.15.00.032";
8194 if ( CheckVersion($DBversion) ) {
8195     $dbh->do("ALTER TABLE aqorders CHANGE notes order_internalnote MEDIUMTEXT;");
8196     $dbh->do("ALTER TABLE aqorders ADD COLUMN order_vendornote MEDIUMTEXT AFTER order_internalnote;");
8197     print "Upgrade to $DBversion done (Bug 9416 - In each order, add a new note made for the vendor)\n";
8198    SetVersion ($DBversion);
8199 }
8200
8201 $DBversion = "3.15.00.033";
8202 if ( CheckVersion($DBversion) ) {
8203     $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')");
8204     print "Upgrade to $DBversion done (Bug 10951: Add NoLoginInstructions pref)\n";
8205     SetVersion($DBversion);
8206 }
8207
8208 $DBversion = "3.15.00.034";
8209 if ( CheckVersion($DBversion) ) {
8210     $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')");
8211     print "Upgrade to $DBversion done (Bug 10986: system preferences to limit languages in advanced search )\n";
8212     SetVersion ($DBversion);
8213 }
8214
8215 $DBversion = "3.15.00.035";
8216 if ( CheckVersion($DBversion) ) {
8217     #insert a notice for sharing a list and accepting a share
8218     $dbh->do("
8219 INSERT INTO letter (module, code, branchcode, name, is_html, title, content)
8220 VALUES ( 'members', 'SHARE_INVITE', '', 'Invitation for sharing a list', '0', 'Share list <<listname>>', 'Dear patron,
8221
8222 One of our patrons, <<borrowers.firstname>> <<borrowers.surname>>, invites you to share a list <<listname>> in our library catalog.
8223
8224 To access this shared list, please click on the following URL or copy-and-paste it into your browser address bar.
8225
8226 <<shareurl>>
8227
8228 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.
8229
8230 Thank you.
8231
8232 Your library.'
8233     )");
8234     $dbh->do("
8235 INSERT INTO letter (module, code, branchcode, name, is_html, title, content)
8236 VALUES ( 'members', 'SHARE_ACCEPT', '', 'Notification about an accepted share', '0', 'Share on list <<listname>> accepted', 'Dear patron,
8237
8238 We want to inform you that <<borrowers.firstname>> <<borrowers.surname>> accepted your invitation to share your list <<listname>> in our library catalog.
8239
8240 Thank you.
8241
8242 Your library.'
8243     )");
8244     print "Upgrade to $DBversion done (Bug 9032: Share a list)\n";
8245     SetVersion($DBversion);
8246 }
8247
8248 $DBversion = "3.15.00.036";
8249 if ( CheckVersion($DBversion) ) {
8250     $dbh->do(q{
8251         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
8252         VALUES('AllowMultipleIssuesOnABiblio',1,'Allow/Don\'t allow patrons to check out multiple items from one biblio','','YesNo')
8253     });
8254
8255     print "Upgrade to $DBversion done (Bug 10859 - Add system preference AllowMultipleIssuesOnABiblio)\n";
8256     SetVersion($DBversion);
8257 }
8258
8259 $DBversion = "3.15.00.037";
8260 if(CheckVersion($DBversion)) {
8261     $dbh->do(q{
8262         ALTER TABLE itemtypes ADD sip_media_type VARCHAR( 3 ) DEFAULT NULL AFTER checkinmsgtype
8263     });
8264     $dbh->do(q{
8265         INSERT INTO authorised_values (category, authorised_value, lib) VALUES
8266          ('SIP_MEDIA_TYPE', '000', 'Other'),
8267          ('SIP_MEDIA_TYPE', '001', 'Book'),
8268          ('SIP_MEDIA_TYPE', '002', 'Magazine'),
8269          ('SIP_MEDIA_TYPE', '003', 'Bound journal'),
8270          ('SIP_MEDIA_TYPE', '004', 'Audio tape'),
8271          ('SIP_MEDIA_TYPE', '005', 'Video tape'),
8272          ('SIP_MEDIA_TYPE', '006', 'CD/CDROM'),
8273          ('SIP_MEDIA_TYPE', '007', 'Diskette'),
8274          ('SIP_MEDIA_TYPE', '008', 'Book with diskette'),
8275          ('SIP_MEDIA_TYPE', '009', 'Book with CD'),
8276          ('SIP_MEDIA_TYPE', '010', 'Book with audio tape')
8277     });
8278     print "Upgrade to $DBversion done (Bug 11351 - Add support for SIP2 media type)\n";
8279     SetVersion($DBversion);
8280 }
8281
8282 $DBversion = '3.15.00.038';
8283 if ( CheckVersion($DBversion) ) {
8284     $dbh->do(q{
8285         INSERT INTO  systempreferences (
8286             variable,
8287             value,
8288             options,
8289             explanation,
8290             type
8291             )
8292         VALUES (
8293             'DisplayLibraryFacets',  'holding',  'home|holding|both',  'Defines which library facets to display.',  'Choice'
8294         );
8295     });
8296     print "Upgrade to $DBversion done (Bug 11334 - Add facet for home library)\n";
8297     SetVersion ($DBversion);
8298 }
8299
8300 $DBversion = "3.15.00.039";
8301 if ( CheckVersion($DBversion) ) {
8302
8303     $dbh->do( q{
8304         ALTER TABLE letter ADD COLUMN message_transport_type VARCHAR(20) NOT NULL DEFAULT 'email' AFTER content
8305     } );
8306
8307     $dbh->do( q{
8308         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
8309     } );
8310
8311     $dbh->do( q{
8312         ALTER TABLE letter DROP PRIMARY KEY, ADD PRIMARY KEY (`module`,`code`,`branchcode`, message_transport_type);
8313     } );
8314
8315     $dbh->do( q{
8316         CREATE TABLE overduerules_transport_types(
8317             id INT(11) NOT NULL AUTO_INCREMENT,
8318             branchcode varchar(10) NOT NULL DEFAULT '',
8319             categorycode VARCHAR(10) NOT NULL DEFAULT '',
8320             letternumber INT(1) NOT NULL DEFAULT 1,
8321             message_transport_type VARCHAR(20) NOT NULL DEFAULT 'email',
8322             PRIMARY KEY (id),
8323             CONSTRAINT overduerules_fk FOREIGN KEY (branchcode, categorycode) REFERENCES overduerules (branchcode, categorycode) ON DELETE CASCADE ON UPDATE CASCADE,
8324             CONSTRAINT mtt_fk FOREIGN KEY (message_transport_type) REFERENCES message_transport_types (message_transport_type) ON DELETE CASCADE ON UPDATE CASCADE
8325         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
8326     } );
8327
8328     my $sth = $dbh->prepare( q{
8329         SELECT * FROM overduerules;
8330     } );
8331
8332     $sth->execute;
8333     my $sth_insert_mtt = $dbh->prepare( q{
8334         INSERT INTO overduerules_transport_types (branchcode, categorycode, letternumber, message_transport_type) VALUES ( ?, ?, ?, ? )
8335     } );
8336     while ( my $row = $sth->fetchrow_hashref ) {
8337         my $branchcode = $row->{branchcode};
8338         my $categorycode = $row->{categorycode};
8339         for my $letternumber ( 1 .. 3 ) {
8340             next unless $row->{"letter$letternumber"};
8341             $sth_insert_mtt->execute(
8342                 $branchcode, $categorycode, $letternumber, 'email'
8343             );
8344         }
8345     }
8346
8347     print "Upgrade done (Bug 9016: Adds multi transport types management for notices)\n";
8348     SetVersion($DBversion);
8349 }
8350
8351 $DBversion = "3.15.00.040";
8352 if ( CheckVersion($DBversion) ) {
8353     $dbh->do(q|
8354         UPDATE message_transports SET letter_code='HOLD' WHERE letter_code='HOLD_PHONE' OR letter_code='HOLD_PRINT'
8355     |);
8356     $dbh->do(q|
8357         UPDATE letter SET code='HOLD', message_transport_type='print' WHERE code='HOLD_PRINT'
8358     |);
8359     $dbh->do(q|
8360         UPDATE letter SET code='HOLD', message_transport_type='phone' WHERE code='HOLD_PHONE'
8361     |);
8362     print "Upgrade to $DBversion done (Bug 10845: Multi transport types for holds)\n";
8363     SetVersion($DBversion);
8364 }
8365
8366 $DBversion = "3.15.00.041";
8367 if ( CheckVersion($DBversion) ) {
8368     my ( $name ) = $dbh->selectrow_array(q|
8369         SELECT name FROM letter WHERE code="HOLD"
8370     |);
8371     $dbh->do(q|
8372         UPDATE letter
8373         SET code="HOLD",
8374             message_transport_type="phone",
8375             name= ?
8376         WHERE code="HOLD_PHONE"
8377     |, {}, $name);
8378
8379     ( $name ) = $dbh->selectrow_array(q|
8380         SELECT name FROM letter WHERE code="PREDUE"
8381     |);
8382     $dbh->do(q|
8383         UPDATE letter
8384         SET code="PREDUE",
8385             message_transport_type="phone",
8386             name= ?
8387         WHERE code="PREDUE_PHONE"
8388     |, {}, $name);
8389
8390     ( $name ) = $dbh->selectrow_array(q|
8391         SELECT name FROM letter WHERE code="OVERDUE"
8392     |);
8393     $dbh->do(q|
8394         UPDATE letter
8395         SET code="OVERDUE",
8396             message_transport_type="phone",
8397             name= ?
8398         WHERE code="OVERDUE_PHONE"
8399     |, {}, $name);
8400
8401     print "Upgrade to $DBversion done (Bug 11867: Update letters *_PHONE)\n";
8402     SetVersion($DBversion);
8403 }
8404
8405 $DBversion = "3.15.00.042";
8406 if ( CheckVersion($DBversion) ) {
8407     $dbh->do(q{
8408         INSERT INTO systempreferences
8409             (variable,value,explanation,options,type)
8410         VALUES
8411             ('SpecifyReturnDate',0,'Define whether to display \"Specify Return Date\" form in Circulation','','YesNo')
8412     });
8413     print "Upgrade to $DBversion done (Bug 10694 - Allow arbitrary backdating of returns)\n";
8414     SetVersion($DBversion);
8415 }
8416
8417 $DBversion = "3.15.00.043";
8418 if ( CheckVersion($DBversion) ) {
8419     $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')");
8420    print "Upgrade to $DBversion done (Bug 7180: Added MarcFieldsToOrder syspref)\n";
8421    SetVersion ($DBversion);
8422 }
8423
8424 $DBversion = "3.15.00.044";
8425 if ( CheckVersion($DBversion) ) {
8426     $dbh->do("ALTER TABLE currency ADD isocode VARCHAR(5) default NULL AFTER symbol;");
8427     print "Upgrade to $DBversion done (Added isocode to the currency table)\n";
8428     SetVersion($DBversion);
8429 }
8430
8431 $DBversion = "3.15.00.045";
8432 if ( CheckVersion($DBversion) ) {
8433     $dbh->do("
8434         INSERT INTO systempreferences (variable,value,explanation,options,type)
8435         VALUES (
8436             'BlockExpiredPatronOpacActions',
8437             '0',
8438             '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',
8439             NULL,
8440             'YesNo'
8441         )
8442     ");
8443     $dbh->do("ALTER TABLE `categories` ADD COLUMN `BlockExpiredPatronOpacActions` TINYINT(1) DEFAULT -1 NOT NULL AFTER category_type");
8444     print "Upgraded to $DBversion done (Bug 6739 - expired patrons not blocked from opac actions)\n";
8445     SetVersion ($DBversion);
8446 }
8447
8448 $DBversion = "3.15.00.046";
8449 if ( CheckVersion($DBversion) ) {
8450     $dbh->do(q|
8451         ALTER TABLE search_history ADD COLUMN type VARCHAR(16) NOT NULL DEFAULT 'biblio' AFTER query_cgi
8452     |);
8453     print "Upgrade to $DBversion done (Bug 10807 - Add db field search_history.type)\n";
8454     SetVersion($DBversion);
8455 }
8456
8457 $DBversion = "3.15.00.047";
8458 if ( CheckVersion($DBversion) ) {
8459     $dbh->do(q|
8460         INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('EnableSearchHistory','0','','Enable or disable search history','YesNo')
8461     |);
8462     print "Upgrade to $DBversion done (Bug 10862: Add EnableSearchHistory syspref)\n";
8463     SetVersion($DBversion);
8464 }
8465
8466 $DBversion = "3.15.00.048";
8467 if ( CheckVersion($DBversion) ) {
8468     $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')");
8469     $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')");
8470     print "Upgrade to $DBversion done (Bug 10195: Records hidden with OpacSuppression can still be accessed)\n";
8471     SetVersion($DBversion);
8472 }
8473
8474 $DBversion = "3.15.00.049";
8475 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
8476     $dbh->do("ALTER TABLE biblioitems DROP INDEX isbn");
8477     $dbh->do("ALTER TABLE biblioitems DROP INDEX issn");
8478     $dbh->do("ALTER TABLE biblioitems DROP INDEX issn_idx");
8479     $dbh->do("ALTER TABLE biblioitems
8480               CHANGE isbn isbn MEDIUMTEXT NULL DEFAULT NULL,
8481               CHANGE issn issn MEDIUMTEXT NULL DEFAULT NULL
8482     ");
8483     $dbh->do("ALTER TABLE biblioitems
8484               ADD INDEX isbn ( isbn ( 255 ) ),
8485               ADD INDEX issn ( issn ( 255 ) )
8486     ");
8487
8488     $dbh->do("ALTER TABLE deletedbiblioitems DROP INDEX isbn");
8489     $dbh->do("ALTER TABLE deletedbiblioitems
8490               CHANGE isbn isbn MEDIUMTEXT NULL DEFAULT NULL,
8491               CHANGE issn issn MEDIUMTEXT NULL DEFAULT NULL
8492     ");
8493     $dbh->do("ALTER TABLE deletedbiblioitems
8494               ADD INDEX isbn ( isbn ( 255 ) )
8495     ");
8496
8497     print "Upgrade to $DBversion done (Bug 5377 - Biblioitems isbn and issn fields too small for multiple ISBN and ISSN)\n";
8498     SetVersion($DBversion);
8499 }
8500
8501 $DBversion = "3.15.00.050";
8502 if ( CheckVersion($DBversion) ) {
8503     $dbh->do("
8504         INSERT INTO systempreferences (
8505             variable,
8506             value,
8507             explanation,
8508             type
8509         ) VALUES (
8510             'AggressiveMatchOnISBN',
8511             '0',
8512             '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',
8513             'YesNo'
8514         )
8515     ");
8516
8517     print "Upgrade to $DBversion done (Bug 10500 - Improve isbn matching when importing records)\n";
8518     SetVersion($DBversion);
8519 }
8520
8521 $DBversion = "3.15.00.051";
8522 if ( CheckVersion($DBversion) ) {
8523     print "Upgrade to $DBversion done (Koha 3.16 beta)\n";
8524     SetVersion($DBversion);
8525 }
8526
8527 $DBversion = "3.15.00.052";
8528 if ( CheckVersion($DBversion) ) {
8529     print "Upgrade to $DBversion done (Koha 3.16 RC)\n";
8530     SetVersion($DBversion);
8531 }
8532
8533 $DBversion = "3.16.00.000";
8534 if ( CheckVersion($DBversion) ) {
8535     print "Upgrade to $DBversion done (3.16.0 release)\n";
8536     SetVersion ($DBversion);
8537 }
8538
8539 $DBversion = '3.17.00.000';
8540 if ( CheckVersion($DBversion) ) {
8541     print "Upgrade to $DBversion done (there is no time to rest on our laurels)\n";
8542     SetVersion ($DBversion);
8543 }
8544
8545 $DBversion = '3.17.00.001';
8546 if ( CheckVersion($DBversion) ) {
8547    $dbh->do("UPDATE systempreferences SET variable = 'AuthoritySeparator' WHERE variable = 'authoritysep'");
8548    print "Upgrade to $DBversion done (Bug 10330 - Rename system preference authoritysep to AuthoritySeparator)\n";
8549    SetVersion ($DBversion);
8550 }
8551
8552 $DBversion = "3.17.00.002";
8553 if (CheckVersion($DBversion)) {
8554     $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')");
8555     $dbh->do("
8556 CREATE TABLE IF NOT EXISTS `misc_files` (
8557   `file_id` int(11) NOT NULL AUTO_INCREMENT,
8558   `table_tag` varchar(255) NOT NULL,
8559   `record_id` int(11) NOT NULL,
8560   `file_name` varchar(255) NOT NULL,
8561   `file_type` varchar(255) NOT NULL,
8562   `file_description` varchar(255) DEFAULT NULL,
8563   `file_content` longblob NOT NULL, -- file content
8564   `date_uploaded` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
8565   PRIMARY KEY (`file_id`),
8566   KEY `table_tag` (`table_tag`),
8567   KEY `record_id` (`record_id`)
8568 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
8569     ");
8570     print "Upgrade to $DBversion done (Bug 3050 - Add an option to upload scanned invoices)\n";
8571     SetVersion($DBversion);
8572 }
8573
8574 $DBversion = "3.17.00.003";
8575 if (CheckVersion($DBversion)) {
8576     $dbh->do("UPDATE systempreferences SET type = 'Choice', options = '0|1|force' WHERE variable = 'OPACItemHolds'");
8577     print "Upgrade to $DBversion done (Bug 7825 - Changed OPACItemHolds syspref to Choice)\n";
8578     SetVersion($DBversion);
8579 }
8580
8581 $DBversion = "3.17.00.004";
8582 if (CheckVersion($DBversion)) {
8583     $dbh->do("ALTER TABLE categories ADD default_privacy ENUM( 'default', 'never', 'forever' ) NOT NULL DEFAULT 'default' AFTER category_type");
8584     print "Upgrade to $DBversion done (Bug 6254 - can't set patron privacy by default)\n";
8585     SetVersion($DBversion);
8586 }
8587
8588 $DBversion = "3.17.00.005";
8589 if (CheckVersion($DBversion)) {
8590     $dbh->do(q|
8591         ALTER TABLE issuingrules
8592         ADD maxsuspensiondays INT(11) DEFAULT NULL AFTER finedays;
8593     |);
8594     print "Upgrade to $DBversion done (Bug 12230: Add new issuing rule maxsuspensiondays)\n";
8595     SetVersion($DBversion);
8596 }
8597
8598 $DBversion = "3.17.00.006";
8599 if ( CheckVersion($DBversion) ) {
8600     $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')");
8601     $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')");
8602     print "Upgrade to $DBversion done (Bug 7720 - Ambiguity in OPAC Details location.)\n";
8603     SetVersion($DBversion);
8604 }
8605
8606 $DBversion = "3.17.00.007";
8607 if (CheckVersion($DBversion)) {
8608     $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');");
8609     print "Upgrade to $DBversion done (Bug 11629 - Add ability to update not for loan status on checkin)\n";
8610     SetVersion($DBversion);
8611 }
8612
8613 $DBversion = "3.17.00.008";
8614 if ( CheckVersion($DBversion) ) {
8615     $dbh->do(q|
8616         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('OPACAcquisitionDetails','0', '','Show the acquisition details at the OPAC','YesNo')
8617     |);
8618     print "Upgrade to $DBversion done (Bug 11169 - Add OPACAcquisitionDetails syspref)\n";
8619     SetVersion($DBversion);
8620 }
8621
8622 $DBversion = "3.17.00.009";
8623 if ( CheckVersion($DBversion) ) {
8624     $dbh->do(q{
8625         DELETE FROM systempreferences WHERE variable = 'UseTablesortForCirc'
8626     });
8627
8628     print "Upgrade to $DBversion done (Bug 11703 - Remove UseTablesortForCirc syspref)\n";
8629     SetVersion($DBversion);
8630 }
8631
8632 $DBversion = "3.17.00.010";
8633 if ( CheckVersion($DBversion) ) {
8634     $dbh->do("DELETE FROM systempreferences WHERE variable='opacsmallimage'");
8635     print "Upgrade to $DBversion done (Bug 11347 - PROG/CCSR deprecation: Remove opacsmallimage system preference)\n";
8636     SetVersion($DBversion);
8637 }
8638
8639 $DBversion = "3.17.00.011";
8640 if ( CheckVersion($DBversion) ) {
8641     $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'hr', 'language', 'Croatian','2014-07-24' )");
8642     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'hr','hrv')");
8643     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'hr', 'Hrvatski')");
8644     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'en', 'Croatian')");
8645     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'fr', 'Croate')");
8646     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'de', 'Kroatisch')");
8647     print "Upgrade to $DBversion done (Bug 12649: Add Croatian language)\n";
8648     SetVersion ($DBversion);
8649 }
8650
8651 $DBversion = "3.17.00.012";
8652 if ( CheckVersion($DBversion) ) {
8653     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacShowFiltersPulldownMobile'");
8654     print "Upgrade to $DBversion done ( Bug 12512 - PROG/CCSR deprecation: Remove OpacShowFiltersPulldownMobile system preference )\n";
8655     SetVersion ($DBversion);
8656 }
8657
8658 $DBversion = "3.17.00.013";
8659 if ( CheckVersion($DBversion) ) {
8660     $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')");
8661     print "Upgrade to $DBversion done (Re-add system preference maxreserves)\n";
8662     SetVersion ($DBversion);
8663 }
8664
8665 $DBversion = '3.17.00.014';
8666 if ( CheckVersion($DBversion) ) {
8667     $dbh->do("
8668         INSERT INTO systempreferences (variable,value,explanation,type) VALUES
8669         ('OverdueNoticeCalendar',0,'Take calendar into consideration when working out sending overdue notices','YesNo')
8670     ");
8671     print "Upgrade to $DBversion done (Bug 12529 - Adding a syspref to allow the overdue notices to consider the calendar when generating notices)\n";
8672     SetVersion($DBversion);
8673 }
8674
8675 $DBversion = "3.17.00.015";
8676 if ( CheckVersion($DBversion) ) {
8677     $dbh->do(q{
8678         CREATE TABLE IF NOT EXISTS columns_settings (
8679             module varchar(255) NOT NULL,
8680             page varchar(255) NOT NULL,
8681             tablename varchar(255) NOT NULL,
8682             columnname varchar(255) NOT NULL,
8683             cannot_be_toggled int(1) NOT NULL DEFAULT 0,
8684             is_hidden int(1) NOT NULL DEFAULT 0,
8685             PRIMARY KEY(module, page, tablename, columnname)
8686         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
8687     });
8688     print "Upgrade to $DBversion done (Bug 10212 - Create new table columns_settings)\n";
8689     SetVersion ($DBversion);
8690 }
8691
8692 $DBversion = "3.17.00.016";
8693 if ( CheckVersion($DBversion) ) {
8694     $dbh->do("CREATE TABLE aqcontacts (
8695         id int(11) NOT NULL auto_increment,
8696         name varchar(100) default NULL,
8697         position varchar(100) default NULL,
8698         phone varchar(100) default NULL,
8699         altphone varchar(100) default NULL,
8700         fax varchar(100) default NULL,
8701         email varchar(100) default NULL,
8702         notes mediumtext,
8703         claimacquisition BOOLEAN NOT NULL DEFAULT 0,
8704         claimissues BOOLEAN NOT NULL DEFAULT 0,
8705         acqprimary BOOLEAN NOT NULL DEFAULT 0,
8706         serialsprimary BOOLEAN NOT NULL DEFAULT 0,
8707         booksellerid int(11) not NULL,
8708         PRIMARY KEY  (id),
8709         CONSTRAINT booksellerid_aqcontacts_fk FOREIGN KEY (booksellerid)
8710             REFERENCES aqbooksellers (id) ON DELETE CASCADE ON UPDATE CASCADE
8711         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;");
8712     $dbh->do("INSERT INTO aqcontacts (name, position, phone, altphone, fax,
8713             email, notes, booksellerid, claimacquisition, claimissues, acqprimary, serialsprimary)
8714         SELECT contact, contpos, contphone, contaltphone, contfax, contemail,
8715             contnotes, id, 1, 1, 1, 1 FROM aqbooksellers;");
8716     $dbh->do("ALTER TABLE aqbooksellers DROP COLUMN contact,
8717         DROP COLUMN contpos, DROP COLUMN contphone,
8718         DROP COLUMN contaltphone, DROP COLUMN contfax,
8719         DROP COLUMN contemail, DROP COLUMN contnotes;");
8720     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contact>>', '<<aqcontacts.name>>')");
8721     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contpos>>', '<<aqcontacts.position>>')");
8722     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contphone>>', '<<aqcontacts.phone>>')");
8723     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contaltphone>>', '<<aqcontacts.altphone>>')");
8724     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contfax>>', '<<aqcontacts.contfax>>')");
8725     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contemail>>', '<<aqcontacts.contemail>>')");
8726     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contnotes>>', '<<aqcontacts.contnotes>>')");
8727     print "Upgrade to $DBversion done (Bug 10402: Move bookseller contacts to separate table)\n";
8728     SetVersion($DBversion);
8729 }
8730
8731 $DBversion = "3.17.00.017";
8732 if ( CheckVersion($DBversion) ) {
8733     # Correct invalid recordtypes (should be very exceptional)
8734     $dbh->do(q{
8735         UPDATE z3950servers set recordtype='biblio' WHERE recordtype NOT IN ('authority','biblio')
8736     });
8737     # Correct invalid server types (should also be very exceptional)
8738     $dbh->do(q{
8739         UPDATE z3950servers set type='zed' WHERE type <> 'zed'
8740     });
8741     # Adjust table
8742     $dbh->do(q{
8743         ALTER TABLE z3950servers
8744         DROP COLUMN icon,
8745         DROP COLUMN description,
8746         DROP COLUMN position,
8747         MODIFY COLUMN id int NOT NULL AUTO_INCREMENT FIRST,
8748         MODIFY COLUMN recordtype enum('authority','biblio') NOT NULL DEFAULT 'biblio',
8749         CHANGE COLUMN name servername mediumtext NOT NULL,
8750         CHANGE COLUMN type servertype enum('zed','sru') NOT NULL DEFAULT 'zed',
8751         ADD COLUMN sru_options varchar(255) default NULL,
8752         ADD COLUMN sru_fields mediumtext default NULL,
8753         ADD COLUMN add_xslt mediumtext default NULL
8754     });
8755     print "Upgrade to $DBversion done (Bug 6536: Z3950 improvements)\n";
8756     SetVersion ($DBversion);
8757 }
8758
8759 $DBversion = "3.17.00.018";
8760 if ( CheckVersion($DBversion) ) {
8761     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('HoldsInNoissuesCharge', '0', 'Hold charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
8762     print "Upgrade to $DBversion done (Bug 12205: Add HoldsInNoissuesCharge systempreference)\n";
8763     SetVersion($DBversion);
8764 }
8765
8766 $DBversion = "3.17.00.019";
8767 if ( CheckVersion($DBversion) ) {
8768     $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')"
8769     );
8770     print "Upgrade to $DBversion done (Bug 6149: Operator highlighted in search results)\n";
8771     SetVersion($DBversion);
8772 }
8773
8774 $DBversion = "3.17.00.020";
8775 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
8776     $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')");
8777     print "Upgrade to $DBversion done (Bug 8735 - Expire holds waiting only on days the library is open)\n";
8778     SetVersion ($DBversion);
8779 }
8780
8781 $DBversion = "3.17.00.021";
8782 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
8783     my $pref = C4::Context->preference('HomeOrHoldingBranch');
8784     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
8785        VALUES ('StaffSearchResultsDisplayBranch', ?,'homebranch|holdingbranch','Controls the display of the home or holding branch for staff search results','choice')", undef, $pref);
8786     print "Upgrade to $DBversion done (Bug 12582 - Control of branch displayed in search results linked to HomeOrHoldingBranch)\n";
8787     SetVersion ($DBversion);
8788 }
8789
8790 $DBversion = '3.17.00.022';
8791 if ( CheckVersion($DBversion) ) {
8792     my @temp= $dbh->selectrow_array(qq|
8793         SELECT count(*)
8794         FROM marc_subfield_structure
8795         WHERE kohafield='permanent_location' OR kohafield='items.permanent_location'
8796     |);
8797     print "Upgrade to $DBversion done (Bug 7817: Check for permanent_location)\n";
8798     if( $temp[0] ) {
8799         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";
8800     }
8801     SetVersion($DBversion);
8802 }
8803
8804 $DBversion = "3.17.00.023";
8805 if ( CheckVersion($DBversion) ) {
8806     $dbh->do(q{
8807         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')
8808     });
8809     print "Upgrade to $DBversion done (Bug 11169 - Add AcqItemSetSubfieldsWhenReceiptIsCancelled syspref)\n";
8810     SetVersion($DBversion);
8811 }
8812
8813 $DBversion = "3.17.00.024";
8814 if(CheckVersion($DBversion)) {
8815     $dbh->do(q{
8816         ALTER TABLE issues ADD auto_renew BOOLEAN default FALSE AFTER renewals
8817     });
8818     $dbh->do(q{
8819         ALTER TABLE old_issues ADD auto_renew BOOLEAN default FALSE AFTER renewals
8820     });
8821     $dbh->do(q{
8822         ALTER TABLE issuingrules ADD auto_renew BOOLEAN default FALSE AFTER norenewalbefore
8823     });
8824     print "Upgrade to $DBversion done (Bug 11577: [ENH] Automatic renewal feature)\n";
8825     SetVersion($DBversion);
8826 }
8827
8828 $DBversion = '3.17.00.025';
8829 if ( CheckVersion($DBversion) ) {
8830     $dbh->do(qq{
8831         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')
8832     });
8833     print "Upgrade to $DBversion done (Bug 12728: Checked syspref StatisticsFields)\n";
8834 }
8835
8836 $DBversion = "3.17.00.026";
8837 if ( CheckVersion($DBversion) ) {
8838     if ( C4::Context->preference('marcflavour') eq 'MARC21' ) {
8839         $dbh->do("UPDATE marc_subfield_structure SET liblibrarian = 'Encoded bitrate', libopac = 'Encoded bitrate' WHERE tagfield = '347' AND tagsubfield = 'f'");
8840         $dbh->do("UPDATE marc_subfield_structure SET repeatable = 1 WHERE tagfield IN ('110','111','610','611','710','711','810','811') AND tagsubfield = 'c'");
8841         $dbh->do("UPDATE auth_subfield_structure SET repeatable = 1 WHERE tagfield IN ('110','111','410','411','510','511','710','711') AND tagsubfield = 'c'");
8842         print "Upgrade to $DBversion done (Bug 12435 - Update MARC21 frameworks to Update No. 18 (April 2014))\n";
8843     }
8844     SetVersion($DBversion);
8845 }
8846
8847 $DBversion = "3.17.00.027";
8848 if ( CheckVersion($DBversion) ) {
8849     $dbh->do(q{
8850         DELETE FROM systempreferences WHERE variable = 'SearchEngine'
8851     });
8852     print "Upgrade to $DBversion done (Bug 12538 - Remove SearchEngine syspref)\n";
8853     SetVersion($DBversion);
8854 }
8855
8856 $DBversion = "3.17.00.028";
8857 if ( CheckVersion($DBversion) ) {
8858     $dbh->do(q{
8859         INSERT INTO systempreferences (variable,value) VALUES('OpacCustomSearch','');
8860     });
8861     print "Upgrade to $DBversion done (Bug 12296 - search box replaceable with a system preference)\n";
8862     SetVersion($DBversion);
8863 }
8864
8865 $DBversion = "3.17.00.029";
8866 if ( CheckVersion($DBversion) ) {
8867     $dbh->do("ALTER TABLE  `items` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8868     $dbh->do("ALTER TABLE  `deleteditems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8869     $dbh->do("ALTER TABLE  `biblioitems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8870     $dbh->do("ALTER TABLE  `deletedbiblioitems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8871     print "Upgrade to $DBversion done (Bug 12424 - ddc sorting of call numbers truncates long Cutter parts)\n";
8872     SetVersion ($DBversion);
8873 }
8874
8875 $DBversion = "3.17.00.030";
8876 if ( CheckVersion($DBversion) ) {
8877     $dbh->do(
8878         q{
8879        INSERT INTO systempreferences (variable, value, options, explanation, type )
8880        VALUES
8881         ('UsageStatsCountry', '', NULL, 'The country where your library is located, to be shown on the Hea Koha community website', 'Choice'),
8882         ('UsageStatsID', '', NULL, 'This preference is part of Koha but it should not be deleted or updated manually.',  'Free'),
8883         ('UsageStatsLastUpdateTime', '', NULL, 'This preference is part of Koha but it should not be deleted or updated manually.', 'Free'),
8884         ('UsageStatsLibraryName', '', NULL, 'The library name to be shown on Hea Koha community website', 'Free'),
8885         ('UsageStatsLibraryType', 'public', 'public|university', 'The library type to be shown on the Hea Koha community website', 'Choice'),
8886         ('UsageStatsLibraryUrl', '', NULL, 'The library URL to be shown on Hea Koha community website', 'Free'),
8887         ('UsageStats', 0, NULL, 'Share anonymous usage data on the Hea Koha community website.', 'YesNo')
8888     });
8889     print "Upgrade to $DBversion done (Bug 11926: Add UsageStats systempreferences (HEA))\n";
8890     SetVersion ($DBversion);
8891 }
8892
8893 $DBversion = "3.17.00.031";
8894 if ( CheckVersion($DBversion) ) {
8895    $dbh->do("ALTER TABLE saved_sql CHANGE report_name report_name VARCHAR( 255 ) NOT NULL DEFAULT '' ");
8896    print "Upgrade to $DBversion done (Bug 2969: Report Name should be mandatory for saved reports)\n";
8897    SetVersion ($DBversion);
8898 }
8899
8900 $DBversion = "3.17.00.032";
8901 if ( CheckVersion($DBversion) ) {
8902     $dbh->do(
8903 "INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('ReplytoDefault',  '',  NULL,  'The default email address to be set as replyto.',  'Free')"
8904     );
8905     $dbh->do(
8906 "INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('ReturnpathDefault',  '',  NULL,  'The default email address to be set as return-path',  'Free')"
8907     );
8908     $dbh->do("ALTER TABLE branches ADD branchreplyto mediumtext AFTER branchemail");
8909     $dbh->do("ALTER TABLE branches ADD branchreturnpath mediumtext AFTER branchreplyto");
8910     print "Upgrade to $DBversion done (Bug 9530: Adding replyto and returnpath addresses.)\n";
8911     SetVersion($DBversion);
8912 }
8913
8914 $DBversion = "3.17.00.033";
8915 if ( CheckVersion($DBversion) ) {
8916     $dbh->do(q{
8917         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
8918         VALUES('FacetMaxCount', '20','Specify the max facet count for each category',NULL,'Integer')
8919     });
8920     print "Upgrade to $DBversion done (Bug 13088 - Allow the user to specify a max amount of facets to show)\n";
8921     SetVersion($DBversion);
8922 }
8923
8924 $DBversion = "3.17.00.034";
8925 if ( CheckVersion($DBversion) ) {
8926     $dbh->do(q|
8927         ALTER TABLE aqorders DROP COLUMN cancelledby;
8928     |);
8929
8930     print "Upgrade to $DBversion done (Bug 11007 - DROP column aqorders.cancelledby)\n";
8931     SetVersion($DBversion);
8932 }
8933
8934 $DBversion = "3.17.00.035";
8935 if ( CheckVersion($DBversion) ) {
8936     $dbh->do(q|
8937         ALTER TABLE serial ADD COLUMN claims_count INT(11) DEFAULT 0 after claimdate
8938     |);
8939     $dbh->do(q|
8940         UPDATE serial
8941         SET claims_count = 1
8942         WHERE claimdate IS NOT NULL
8943     |);
8944     print "Upgrade to $DBversion done (Bug 5342: Add claims_count field in serial table)\n";
8945     SetVersion($DBversion);
8946 }
8947
8948 $DBversion = "3.17.00.036";
8949 if ( CheckVersion($DBversion) ) {
8950     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacShowLibrariesPulldownMobile'");
8951     print "Upgrade to $DBversion done ( Bug 12513 - PROG/CCSR deprecation: Remove OpacShowLibrariesPulldownMobile system preference )\n";
8952     SetVersion ($DBversion);
8953 }
8954
8955 $DBversion = "3.17.00.037";
8956 if ( CheckVersion($DBversion) ) {
8957     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacMainUserBlockMobile'");
8958     print "Upgrade to $DBversion done ( Bug 12246 - PROG/CCSR deprecation: Remove OpacMainUserBlockMobile system preference )\n";
8959     SetVersion ($DBversion);
8960 }
8961
8962 $DBversion = "3.17.00.038";
8963 if ( CheckVersion($DBversion) ) {
8964     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACMobileUserCSS'");
8965     print "Upgrade to $DBversion done ( Bug 12245 - PROG/CCSR deprecation: Remove OPACMobileUserCSS system preference )\n";
8966     SetVersion ($DBversion);
8967 }
8968
8969 $DBversion = "3.17.00.039";
8970 if ( CheckVersion($DBversion) ) {
8971     $dbh->do("INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES
8972     ('OPACFallback', 'prog', 'bootstrap|prog', 'Define the fallback theme for the OPAC interface.', 'Themes')");
8973     print "Upgrade to $DBversion done (Bug 12539 - PROG/CCSR deprecation: Remove hardcoded theme from C4/Templates.pm)\n";
8974     SetVersion ($DBversion);
8975 }
8976
8977 $DBversion = "3.17.00.040";
8978 if ( CheckVersion($DBversion) ) {
8979     my $opac_theme = C4::Context->preference( 'opacthemes' );
8980     if ( !defined $opac_theme || $opac_theme eq 'prog' || $opac_theme eq 'ccsr' ) {
8981         $dbh->do("UPDATE systempreferences SET value='bootstrap' WHERE variable='opacthemes'");
8982     }
8983     print "Upgrade to $DBversion done (Bug 12223: 'prog' and 'ccsr' themes removed)\n";
8984     SetVersion($DBversion);
8985 }
8986
8987 $DBversion = "3.17.00.041";
8988 if ( CheckVersion($DBversion) ) {
8989     print "Upgrade to $DBversion done (Bug 11346: Deprecate the 'prog' and 'CCSR' themes)\n";
8990     SetVersion($DBversion);
8991 }
8992
8993 $DBversion = "3.17.00.042";
8994 if ( CheckVersion($DBversion) ) {
8995     $dbh->do("DELETE FROM systempreferences WHERE variable='yuipath'");
8996     print "Upgrade to $DBversion done (Bug 12494: Remove yuipath system preference)\n";
8997     SetVersion ($DBversion);
8998 }
8999
9000 $DBversion = "3.17.00.043";
9001 if ( CheckVersion($DBversion) ) {
9002     $dbh->do("
9003         ALTER TABLE aqorders
9004         ADD COLUMN cancellationreason TEXT DEFAULT NULL AFTER datecancellationprinted
9005     ");
9006     print "Upgrade to $DBversion done (Bug 7162: Add aqorders.cancellationreason)\n";
9007     SetVersion ($DBversion);
9008 }
9009
9010 $DBversion = "3.17.00.044";
9011 if ( CheckVersion($DBversion) ) {
9012     $dbh->do(q{
9013         INSERT IGNORE INTO systempreferences
9014             (variable,value,explanation,options,type)
9015             VALUES('OnSiteCheckouts','0','Enable/Disable the on-site checkouts feature','','YesNo');
9016     });
9017     $dbh->do(q{
9018         INSERT IGNORE INTO systempreferences
9019             (variable,value,explanation,options,type)
9020             VALUES('OnSiteCheckoutsForce','0','Enable/Disable the on-site for all cases (Even if a user is debarred, etc.)','','YesNo');
9021     });
9022     $dbh->do(q{
9023         ALTER TABLE issues ADD COLUMN onsite_checkout INT(1) NOT NULL DEFAULT 0 AFTER issuedate;
9024     });
9025     $dbh->do(q{
9026         ALTER TABLE old_issues ADD COLUMN onsite_checkout INT(1) NOT NULL DEFAULT 0 AFTER issuedate;
9027     });
9028     print "Upgrade to $DBversion done (Bug 10860: Add new system preference OnSiteCheckouts + fields [old_]issues.onsite_checkout)\n";
9029     SetVersion($DBversion);
9030 }
9031
9032 $DBversion = "3.17.00.045";
9033 if ( CheckVersion($DBversion) ) {
9034     $dbh->do(q{
9035         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
9036         ('LocalHoldsPriority',  '0', NULL,  'Enables the LocalHoldsPriority feature',  'YesNo'),
9037         ('LocalHoldsPriorityItemControl',  'holdingbranch',  'holdingbranch|homebranch',  'decides if the feature operates using the item''s home or holding library.',  'Choice'),
9038         ('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')
9039     });
9040     print "Upgrade to $DBversion done (Bug 11126 - Make the holds system optionally give precedence to local holds)\n";
9041     SetVersion($DBversion);
9042 }
9043
9044 $DBversion = "3.17.00.046";
9045 if ( CheckVersion($DBversion) ) {
9046     $dbh->do(q{
9047         CREATE TABLE IF NOT EXISTS items_search_fields (
9048           name VARCHAR(255) NOT NULL,
9049           label VARCHAR(255) NOT NULL,
9050           tagfield CHAR(3) NOT NULL,
9051           tagsubfield CHAR(1) NULL DEFAULT NULL,
9052           authorised_values_category VARCHAR(16) NULL DEFAULT NULL,
9053           PRIMARY KEY(name),
9054           CONSTRAINT items_search_fields_authorised_values_category
9055             FOREIGN KEY (authorised_values_category) REFERENCES authorised_values (category)
9056             ON DELETE SET NULL ON UPDATE CASCADE
9057         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
9058     });
9059     print "Upgrade to $DBversion done (Bug 11425: Add items_search_fields table)\n";
9060     SetVersion($DBversion);
9061 }
9062
9063 $DBversion = "3.17.00.047";
9064 if ( CheckVersion($DBversion) ) {
9065     $dbh->do(q{
9066         ALTER TABLE collections
9067             CHANGE colBranchcode colBranchcode VARCHAR( 10 ) NULL DEFAULT NULL,
9068             ADD INDEX ( colBranchcode ),
9069             ADD CONSTRAINT collections_ibfk_1 FOREIGN KEY (colBranchcode) REFERENCES branches (branchcode) ON DELETE CASCADE ON UPDATE CASCADE
9070     });
9071     print "Upgrade to $DBversion done (Bug 8836 - Resurrect Rotating Collections)\n";
9072     SetVersion($DBversion);
9073 }
9074
9075 $DBversion = "3.17.00.048";
9076 if ( CheckVersion($DBversion) ) {
9077     $dbh->do(q|
9078         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')
9079     |);
9080     print "Upgrade to $DBversion done (Bug 12448 - Add RentalFeesCheckoutConfirmation syspref)\n";
9081     SetVersion($DBversion);
9082 }
9083
9084 $DBversion = "3.17.00.049";
9085 if ( CheckVersion($DBversion) ) {
9086     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'am', 'language', 'Amharic','2014-10-29')");
9087     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'am','amh')");
9088     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'am', 'language', 'am', 'አማርኛ')");
9089     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'am', 'language', 'en', 'Amharic')");
9090
9091     $dbh->do("UPDATE language_descriptions SET description = 'لعربية' WHERE subtag = 'ar' AND type = 'language' AND lang = 'ar'");
9092
9093     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'az', 'language', 'Azerbaijani','2014-10-30')");
9094     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'az','aze')");
9095     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'az', 'language', 'az', 'Azərbaycan dili')");
9096     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'az', 'language', 'en', 'Azerbaijani')");
9097
9098     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'be', 'language', 'Byelorussian','2014-10-30')");
9099     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'be','bel')");
9100     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'be', 'language', 'be', 'Беларуская мова')");
9101     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'be', 'language', 'en', 'Byelorussian')");
9102
9103     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'bn', 'language', 'Bengali','2014-10-30')");
9104     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'bn','ben')");
9105     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'bn', 'language', 'bn', 'বাংলা')");
9106     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'bn', 'language', 'en', 'Bengali')");
9107
9108     $dbh->do("UPDATE language_descriptions SET description = 'Български' WHERE subtag = 'bg' AND type = 'language' AND lang = 'bg'");
9109     $dbh->do("UPDATE language_descriptions SET description = 'Ceština' WHERE subtag = 'cs' AND type = 'language' AND lang = 'cs'");
9110     $dbh->do("UPDATE language_descriptions SET description = 'Ελληνικά' WHERE subtag = 'el' AND type = 'language' AND lang = 'el'");
9111     $dbh->do("UPDATE language_descriptions SET description = 'Español' WHERE subtag = 'es' AND type = 'language' AND lang = 'es'");
9112
9113     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'eu', 'language', 'Basque','2014-10-30')");
9114     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'eu','eus')");
9115     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'eu', 'language', 'eu', 'Euskera')");
9116     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'eu', 'language', 'en', 'Basque')");
9117
9118     $dbh->do("UPDATE language_descriptions SET description = 'فارسى' WHERE subtag = 'fa' AND type = 'language' AND lang = 'fa'");
9119     $dbh->do("UPDATE language_descriptions SET description = 'Suomi' WHERE subtag = 'fi' AND type = 'language' AND lang = 'fi'");
9120
9121     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'fo', 'language', 'Faroese','2014-10-30')");
9122     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'fo','fao')");
9123     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'fo', 'language', 'fo', 'Føroyskt')");
9124     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'fo', 'language', 'en', 'Faroese')");
9125
9126     $dbh->do("UPDATE language_descriptions SET description = 'Français' WHERE subtag = 'fr' AND type = 'language' AND lang = 'fr'");
9127     $dbh->do("UPDATE language_descriptions SET description = 'עִבְרִית' WHERE subtag = 'he' AND type = 'language' AND lang = 'he'");
9128     $dbh->do("UPDATE language_descriptions SET description = 'हिन्दी' WHERE subtag = 'hi' AND type = 'language' AND lang = 'hi'");
9129
9130     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'is', 'language', 'Icelandic','2014-10-30')");
9131     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'is','ice')");
9132     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'is', 'language', 'is', 'Íslenska')");
9133     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'is', 'language', 'en', 'Icelandic')");
9134
9135     $dbh->do("UPDATE language_descriptions SET description = '日本語' WHERE subtag = 'ja' AND type = 'language' AND lang = 'ja'");
9136
9137     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ka', 'language', 'Kannada','2014-10-30')");
9138     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ka','kan')");
9139     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'ka', 'ಕನ್ನಡ')");
9140     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'en', 'Kannada')");
9141
9142     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'km', 'language', 'Khmer','2014-10-30')");
9143     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'km','khm')");
9144     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'km', 'language', 'km', 'ភាសាខ្មែរ')");
9145     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'km', 'language', 'en', 'Khmer')");
9146
9147     $dbh->do("UPDATE language_descriptions SET description = '한국어' WHERE subtag = 'ko' AND type = 'language' AND lang = 'ko'");
9148
9149     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ku', 'language', 'Kurdish','2014-05-13')");
9150     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ku','kur')");
9151     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'ku', 'کوردی')");
9152     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'en', 'Kurdish')");
9153     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'fr', 'Kurde')");
9154     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'de', 'Kurdisch')");
9155     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'es', 'Kurdo')");
9156
9157     $dbh->do("UPDATE language_descriptions SET description = 'ພາສາລາວ' WHERE subtag = 'lo' AND type = 'language' AND lang = 'lo'");
9158
9159     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mi', 'language', 'Maori','2014-10-30')");
9160     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mi','mri')");
9161     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mi', 'language', 'mi', 'Te Reo Māori')");
9162     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mi', 'language', 'en', 'Maori')");
9163
9164     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mn', 'language', 'Mongolian','2014-10-30')");
9165     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mn','mon')");
9166     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mn', 'language', 'mn', 'Mонгол')");
9167     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mn', 'language', 'en', 'Mongolian')");
9168
9169     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mr', 'language', 'Marathi','2014-10-30')");
9170     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mr','mar')");
9171     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mr', 'language', 'mr', 'मराठी')");
9172     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mr', 'language', 'en', 'Marathi')");
9173
9174     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ms', 'language', 'Malay','2014-10-30')");
9175     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ms','may')");
9176     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ms', 'language', 'ms', 'Bahasa melayu')");
9177     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ms', 'language', 'en', 'Malay')");
9178
9179     $dbh->do("UPDATE language_descriptions SET description = 'Norsk bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'nb'");
9180     $dbh->do("UPDATE language_descriptions SET description = 'Norwegian bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'en'");
9181     $dbh->do("UPDATE language_descriptions SET description = 'Norvégien bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'fr'");
9182     $dbh->do("UPDATE language_descriptions SET description = 'Norwegisch bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'de'");
9183
9184     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ne', 'language', 'Nepali','2014-10-30')");
9185     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ne','nep')");
9186     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)VALUES ( 'ne', 'language', 'ne', 'नेपाली')");
9187     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ne', 'language', 'en', 'Nepali')");
9188
9189     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'pbr', 'language', 'Pangwa','2014-10-30')");
9190     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'pbr','pbr')");
9191     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'pbr', 'language', 'pbr', 'Ekipangwa')");
9192     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'pbr', 'language', 'en', 'Pangwa')");
9193
9194     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'prs', 'language', 'Dari','2014-10-30')");
9195     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'prs','prs')");
9196     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'prs', 'language', 'prs', 'درى')");
9197     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'prs', 'language', 'en', 'Dari')");
9198
9199     $dbh->do("UPDATE language_descriptions SET description = 'Português' WHERE subtag = 'pt' AND type = 'language' AND lang = 'pt'");
9200     $dbh->do("UPDATE language_descriptions SET description = 'Român' WHERE subtag = 'ro' AND type = 'language' AND lang = 'ro'");
9201     $dbh->do("UPDATE language_descriptions SET description = 'Русский' WHERE subtag = 'ru' AND type = 'language' AND lang = 'ru'");
9202
9203     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'rw', 'language', 'Kinyarwanda','2014-10-30')");
9204     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'rw','kin')");
9205     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'rw', 'language', 'rw', 'Ikinyarwanda')");
9206     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'rw', 'language', 'en', 'Kinyarwanda')");
9207
9208     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sd', 'language', 'Sindhi','2014-10-30')");
9209     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sd','snd')");
9210     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sd', 'language', 'sd', 'سنڌي')");
9211     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sd', 'language', 'en', 'Sindhi')");
9212
9213     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sk', 'language', 'Slovak','2014-10-30')");
9214     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sk','slk')");
9215     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sk', 'language', 'sk', 'Slovenčina')");
9216     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sk', 'language', 'en', 'Slovak')");
9217
9218     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sl', 'language', 'Slovene','2014-10-30')");
9219     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sl','slv')");
9220     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sl', 'language', 'sl', 'Slovenščina')");
9221     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sl', 'language', 'en', 'Slovene')");
9222
9223     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sq', 'language', 'Albanian','2014-10-30')");
9224     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sq','sqi')");
9225     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sq', 'language', 'sq', 'Shqip')");
9226     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sq', 'language', 'en', 'Albanian')");
9227
9228     $dbh->do("UPDATE language_descriptions SET description = 'Cрпски' WHERE subtag = 'sr' AND type = 'language' AND lang = 'sr'");
9229
9230     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sw', 'language', 'Swahili','2014-10-30')");
9231     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sw','swa')");
9232     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sw', 'language', 'sw', 'Kiswahili')");
9233     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sw', 'language', 'en', 'Swahili')");
9234
9235     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ta', 'language', 'Tamil','2014-10-30')");
9236     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ta','tam')");
9237     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ta', 'language', 'ta', 'தமிழ்')");
9238     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ta', 'language', 'en', 'Tamil')");
9239
9240     $dbh->do("UPDATE language_descriptions SET description = 'Tetun' WHERE subtag = 'tet' AND type = 'language' AND lang = 'tet'");
9241     $dbh->do("UPDATE language_descriptions SET description = 'ภาษาไทย' WHERE subtag = 'th' AND type = 'language' AND lang = 'th'");
9242
9243     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'tl', 'language', 'Tagalog','2014-10-30')");
9244     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'tl','tgl')");
9245     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'tl', 'language', 'tl', 'Tagalog')");
9246     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'tl', 'language', 'en', 'Tagalog')");
9247
9248     $dbh->do("UPDATE language_descriptions SET description = 'Türkçe' WHERE subtag = 'tr' AND type = 'language' AND lang = 'tr'");
9249     $dbh->do("UPDATE language_descriptions SET description = 'Українська' WHERE subtag = 'uk' AND type = 'language' AND lang = 'uk'");
9250     $dbh->do("UPDATE language_descriptions SET description = 'اردو' WHERE subtag = 'ur' AND type = 'language' AND lang = 'ur'");
9251
9252     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'vi', 'language', 'Vietnamese','2014-10-30')");
9253     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'vi','vie')");
9254     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'vi', 'language', 'vi', '㗂越')");
9255     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'vi', 'language', 'en', 'Vietnamese')");
9256
9257     $dbh->do("UPDATE language_descriptions SET description = '中文' WHERE subtag = 'zh' AND type = 'language' AND lang = 'zh'");
9258     $dbh->do("UPDATE language_descriptions SET description = '' WHERE subtag = 'Arab,script' AND type = 'Arab' AND lang = 'العربية'");
9259
9260     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Armn', 'script', 'Armenian','2014-10-30')");
9261     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Armn', 'script', 'Armn', 'Հայոց այբուբեն')");
9262     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Armn', 'script', 'en', 'Armenian')");
9263
9264     $dbh->do("UPDATE language_descriptions SET description = 'Кирилица' WHERE subtag = 'Cyrl' AND type = 'script' AND lang = 'Cyrl'");
9265
9266     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Ethi', 'script', 'Ethiopic','2014-10-30')");
9267     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Ethi', 'script', 'Ethi', 'ግዕዝ')");
9268     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Ethi', 'script', 'en', 'Ethiopic')");
9269
9270     $dbh->do("UPDATE language_descriptions SET description = 'Ελληνικό αλφάβητο' WHERE subtag = 'Grek' AND type = 'script' AND lang = 'Grek'");
9271     $dbh->do("UPDATE language_descriptions SET description = '简体字' WHERE subtag = 'Hans' AND type = 'script' AND lang = 'Hans'");
9272     $dbh->do("UPDATE language_descriptions SET description = '繁體字' WHERE subtag = 'Hant' AND type = 'script' AND lang = 'Hant'");
9273     $dbh->do("UPDATE language_descriptions SET description = 'אָלֶף־בֵּית עִבְרִי' WHERE subtag = 'Hebr' AND type = 'script' AND lang = 'Hebr'");
9274
9275     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Jpan', 'script', 'Japanese','2014-10-30')");
9276     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Jpan', 'script', 'Jpan', '漢字')");
9277     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Jpan', 'script', 'en', 'Japanese')");
9278
9279     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Knda', 'script', 'Kannada','2014-10-30')");
9280     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Knda', 'script', 'Knda', 'ಕನ್ನಡ ಲಿಪಿ')");
9281     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Knda', 'script', 'en', 'Kannada')");
9282
9283     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Kore', 'script', 'Korean','2014-10-30')");
9284     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Kore', 'script', 'Kore', '한글')");
9285     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Kore', 'script', 'en', 'Korean')");
9286
9287     $dbh->do("UPDATE language_descriptions SET description = 'ອັກສອນລາວ' WHERE subtag = 'Laoo' AND type = 'script' AND lang = 'Laoo'");
9288
9289     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'AL', 'region', 'Albania','2014-10-30')");
9290     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AL', 'region', 'en', 'Albania')");
9291     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AL', 'region', 'sq', 'Shqipërisë')");
9292
9293     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'AZ', 'region', 'Azerbaijan','2014-10-30')");
9294     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AZ', 'region', 'en', 'Azerbaijan')");
9295     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AZ', 'region', 'az', 'Azərbaycan')");
9296
9297     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BE', 'region', 'Belgium','2014-10-30')");
9298     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BE', 'region', 'en', 'Belgium')");
9299     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BE', 'region', 'nl', 'België')");
9300
9301     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BR', 'region', 'Brazil','2014-10-30')");
9302     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BR', 'region', 'en', 'Brazil')");
9303     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BR', 'region', 'pt', 'Brasil')");
9304
9305     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BY', 'region', 'Belarus','2014-10-30')");
9306     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BY', 'region', 'en', 'Belarus')");
9307     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BY', 'region', 'be', 'Беларусь')");
9308
9309     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CA', 'region', 'fr', 'Canada')");
9310
9311     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CH', 'region', 'Switzerland','2014-10-30')");
9312     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CH', 'region', 'en', 'Switzerland')");
9313     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CH', 'region', 'de', 'Schweiz')");
9314
9315     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CN', 'region', 'China','2014-10-30')");
9316     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CN', 'region', 'en', 'China')");
9317     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CN', 'region', 'zh', '中国')");
9318
9319     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CZ', 'region', 'Czech Republic','2014-10-30')");
9320     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CZ', 'region', 'en', 'Czech Republic')");
9321     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CZ', 'region', 'cs', 'Česká republika')");
9322
9323     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'DE', 'region', 'Germany','2014-10-30')");
9324     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DE', 'region', 'en', 'Germany')");
9325     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DE', 'region', 'de', 'Deutschland')");
9326
9327     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DK', 'region', 'en', 'Denmark')");
9328
9329     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ES', 'region', 'Spain','2014-10-30')");
9330     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ES', 'region', 'en', 'Spain')");
9331     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ES', 'region', 'es', 'España')");
9332
9333     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'FI', 'region', 'Finland','2014-10-30')");
9334     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FI', 'region', 'en', 'Finland')");
9335     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FI', 'region', 'fi', 'Suomi')");
9336
9337     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'FO', 'region', 'Faroe Islands','2014-10-30')");
9338     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FO', 'region', 'en', 'Faroe Islands')");
9339     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FO', 'region', 'fo', 'Føroyar')");
9340
9341     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'GR', 'region', 'Greece','2014-10-30')");
9342     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'GR', 'region', 'en', 'Greece')");
9343     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'GR', 'region', 'el', 'Ελλάδα')");
9344
9345     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'HR', 'region', 'Croatia','2014-10-30')");
9346     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HR', 'region', 'en', 'Croatia')");
9347     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HR', 'region', 'hr', 'Hrvatska')");
9348
9349     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'HU', 'region', 'Hungary','2014-10-30')");
9350     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HU', 'region', 'en', 'Hungary')");
9351     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HU', 'region', 'hu', 'Magyarország')");
9352
9353     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ID', 'region', 'Indonesia','2014-10-30')");
9354     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ID', 'region', 'en', 'Indonesia')");
9355     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ID', 'region', 'id', 'Indonesia')");
9356
9357     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'IS', 'region', 'Iceland','2014-10-30')");
9358     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IS', 'region', 'en', 'Iceland')");
9359     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IS', 'region', 'is', 'Ísland')");
9360
9361     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'IT', 'region', 'Italy','2014-10-30')");
9362     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IT', 'region', 'en', 'Italy')");
9363     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IT', 'region', 'it', 'Italia')");
9364
9365     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'JP', 'region', 'Japan','2014-10-30')");
9366     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'JP', 'region', 'en', 'Japan')");
9367     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'JP', 'region', 'ja', '日本')");
9368
9369     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KE', 'region', 'Kenya','2014-10-30')");
9370     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KE', 'region', 'en', 'Kenya')");
9371     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KE', 'region', 'rw', 'Kenya')");
9372
9373     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KH', 'region', 'Cambodia','2014-10-30')");
9374     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KH', 'region', 'en', 'Cambodia')");
9375     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KH', 'region', 'km', 'កម្ពុជា')");
9376
9377     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KP', 'region', 'North Korea','2014-10-30')");
9378     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KP', 'region', 'en', 'North Korea')");
9379     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KP', 'region', 'ko', '조선민주주의인민공화국')");
9380
9381     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'LK', 'region', 'Sri Lanka','2014-10-30')");
9382     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'LK', 'region', 'en', 'Sri Lanka')");
9383     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'LK', 'region', 'ta', 'இலங்கை')");
9384
9385     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'MY', 'region', 'Malaysia','2014-10-30')");
9386     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'MY', 'region', 'en', 'Malaysia')");
9387     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'MY', 'region', 'ms', 'Malaysia')");
9388
9389     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NE', 'region', 'Niger','2014-10-30')");
9390     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NE', 'region', 'en', 'Niger')");
9391     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NE', 'region', 'ne', 'Niger')");
9392
9393     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NL', 'region', 'Netherlands','2014-10-30')");
9394     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NL', 'region', 'en', 'Netherlands')");
9395     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NL', 'region', 'nl', 'Nederland')");
9396
9397     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NO', 'region', 'Norway','2014-10-30')");
9398     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'en', 'Norway')");
9399     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'ne', 'Noreg')");
9400     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'nn', 'Noreg')");
9401
9402     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PH', 'region', 'Philippines','2014-10-30')");
9403     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PH', 'region', 'en', 'Philippines')");
9404     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PH', 'region', 'tl', 'Pilipinas')");
9405
9406     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PK', 'region', 'Pakistan','2014-10-30')");
9407     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PK', 'region', 'en', 'Pakistan')");
9408     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PK', 'region', 'sd', 'پاكستان')");
9409
9410     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PL', 'region', 'Poland','2014-10-30')");
9411     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PL', 'region', 'en', 'Poland')");
9412     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PL', 'region', 'pl', 'Polska')");
9413
9414     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PT', 'region', 'Portugal','2014-10-30')");
9415     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PT', 'region', 'en', 'Portugal')");
9416     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PT', 'region', 'pt', 'Portugal')");
9417
9418     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RO', 'region', 'Romania','2014-10-30')");
9419     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RO', 'region', 'en', 'Romania')");
9420     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RO', 'region', 'ro', 'România')");
9421
9422     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RU', 'region', 'Russia','2014-10-30')");
9423     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RU', 'region', 'en', 'Russia')");
9424     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RU', 'region', 'ru', 'Россия')");
9425
9426     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RW', 'region', 'Rwanda','2014-10-30')");
9427     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RW', 'region', 'en', 'Rwanda')");
9428     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RW', 'region', 'rw', 'Rwanda')");
9429
9430     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SE', 'region', 'Sweden','2014-10-30')");
9431     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SE', 'region', 'en', 'Sweden')");
9432     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SE', 'region', 'sv', 'Sverige')");
9433
9434     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SI', 'region', 'Slovenia','2014-10-30')");
9435     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SI', 'region', 'en', 'Slovenia')");
9436     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SI', 'region', 'sl', 'Slovenija')");
9437
9438     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SK', 'region', 'Slovakia','2014-10-30')");
9439     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SK', 'region', 'en', 'Slovakia')");
9440     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SK', 'region', 'sk', 'Slovensko')");
9441
9442     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TH', 'region', 'Thailand','2014-10-30')");
9443     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TH', 'region', 'en', 'Thailand')");
9444     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TH', 'region', 'th', 'ประเทศไทย')");
9445
9446     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TR', 'region', 'Turkey','2014-10-30')");
9447     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TR', 'region', 'en', 'Turkey')");
9448     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TR', 'region', 'tr', 'Türkiye')");
9449
9450     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TW', 'region', 'Taiwan','2014-10-30')");
9451     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TW', 'region', 'en', 'Taiwan')");
9452     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TW', 'region', 'zh', '台灣')");
9453
9454     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'UA', 'region', 'Ukraine','2014-10-30')");
9455     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'UA', 'region', 'en', 'Ukraine')");
9456     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'UA', 'region', 'uk', 'Україна')");
9457
9458     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'VN', 'region', 'Vietnam','2014-10-30')");
9459     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'VN', 'region', 'en', 'Vietnam')");
9460     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'VN', 'region', 'vi', 'Việt Nam')");
9461
9462     print "Upgrade to $DBversion done (Bug 12250: Update descriptions for languages, scripts and regions)\n";
9463     SetVersion($DBversion);
9464 }
9465
9466 $DBversion = "3.17.00.050";
9467 if ( CheckVersion($DBversion) ) {
9468     $dbh->do(q|
9469         INSERT INTO permissions (module_bit, code, description) VALUES
9470           (13, 'records_batchdel', 'Perform batch deletion of records (bibliographic or authority)')
9471     |);
9472     print "Upgrade to $DBversion done (Bug 12403: Add permission tools_records_batchdelitem)\n";
9473     SetVersion($DBversion);
9474 }
9475
9476 $DBversion = "3.17.00.051";
9477 if ( CheckVersion($DBversion) ) {
9478     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('GoogleIndicTransliteration','0','','GoogleIndicTransliteration on the OPAC.','YesNo')");
9479     print "Upgrade to $DBversion done (Bug 13211: Added system preferences GoogleIndicTransliteration on the OPAC)\n";
9480     SetVersion($DBversion);
9481 }
9482
9483 $DBversion = "3.17.00.052";
9484 if ( CheckVersion($DBversion) ) {
9485     $dbh->do(q{
9486         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');
9487     });
9488
9489     $dbh->do(q{
9490         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');
9491    });
9492    print "Upgrade to $DBversion done (Bug 9043: Add system preference OpacAdvSearchOptions and OpacAdvSearchMoreOptions)\n";
9493    SetVersion ($DBversion);
9494 }
9495
9496 $DBversion = "3.17.00.053";
9497 if ( CheckVersion($DBversion) ) {
9498     $dbh->do(q{
9499         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)');
9500     });
9501
9502     $dbh->do(q{
9503         INSERT INTO permissions (module_bit, code, description) VALUES ('9', 'delete_all_items', 'Delete all items at once');
9504     });
9505
9506     $dbh->do(q{
9507         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)');
9508     });
9509
9510     # The delete_all_items permission should be added to users having the edit_items permission.
9511     $dbh->do(q{
9512         INSERT INTO user_permissions (borrowernumber, module_bit, code) SELECT borrowernumber, module_bit, "delete_all_items" FROM user_permissions WHERE code="edit_items";
9513     });
9514
9515     # Add 2 new prefs
9516     $dbh->do(q{
9517         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');
9518     });
9519
9520     $dbh->do(q{
9521         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');
9522     });
9523
9524     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";
9525     SetVersion($DBversion);
9526 }
9527
9528 $DBversion = "3.17.00.054";
9529 if (CheckVersion($DBversion)) {
9530     $dbh->do(q{
9531         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
9532         ('AllowRenewalIfOtherItemsAvailable','0',NULL,'If enabled, allow a patron to renew an item with unfilled holds if other available items can fill that hold.','YesNo')
9533     });
9534     print "Upgrade to $DBversion done (Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds)\n";
9535     SetVersion($DBversion);
9536 }
9537
9538 $DBversion = "3.17.00.055";
9539 if ( CheckVersion($DBversion) ) {
9540     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBEnable', '0', NULL, 'Enable communication with the Norwegian national patron database.', 'YesNo')");
9541     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBEndpoint', '', NULL, 'Which NL endpoint to use.', 'Free')");
9542     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBUsername', '', NULL, 'Username for communication with the Norwegian national patron database.', 'Free')");
9543     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBPassword', '', NULL, 'Password for communication with the Norwegian national patron database.', 'Free')");
9544     $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')");
9545     $dbh->do("
9546 CREATE TABLE borrower_sync (
9547     borrowersyncid int(11) NOT NULL AUTO_INCREMENT,
9548     borrowernumber int(11) NOT NULL,
9549     synctype varchar(32) NOT NULL,
9550     sync tinyint(1) NOT NULL DEFAULT '0',
9551     syncstatus varchar(10) DEFAULT NULL,
9552     lastsync varchar(50) DEFAULT NULL,
9553     hashed_pin varchar(64) DEFAULT NULL,
9554     PRIMARY KEY (borrowersyncid),
9555     KEY borrowernumber (borrowernumber),
9556     CONSTRAINT borrower_sync_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
9557 ) ENGINE=InnoDB DEFAULT CHARSET=utf8"
9558 );
9559     print "Upgrade to $DBversion done (Bug 11401 - Add support for Norwegian national library card)\n";
9560     SetVersion($DBversion);
9561 }
9562
9563 $DBversion = "3.17.00.056";
9564 if ( CheckVersion($DBversion) ) {
9565     $dbh->do(q{
9566         UPDATE systempreferences SET value = 'pubdate,itemtype,language,sorting,location' WHERE variable='OpacAdvSearchOptions'
9567     });
9568
9569     $dbh->do(q{
9570         UPDATE systempreferences SET value = 'pubdate,itemtype,language,subtype,sorting,location' WHERE variable='OpacAdvSearchMoreOptions'
9571     });
9572
9573     print "Upgrade to $DBversion done (Bug 9043 - Update the values for OpacAdvSearchOptions and OpacAdvSearchOptions)\n";
9574     SetVersion($DBversion);
9575 }
9576
9577 $DBversion = "3.17.00.057";
9578 if ( CheckVersion($DBversion) ) {
9579     print "Upgrade to $DBversion done (Koha 3.18 beta)\n";
9580     SetVersion ($DBversion);
9581 }
9582
9583 $DBversion = "3.17.00.058";
9584 if( CheckVersion($DBversion) ){
9585     $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')");
9586     $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')");
9587     $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')");
9588     print "Upgrade to $DBversion done (Bug 8337: System preferences for longoverdue cron)\n";
9589     SetVersion($DBversion);
9590 }
9591
9592 $DBversion = "3.17.00.059";
9593 if ( CheckVersion($DBversion) ) {
9594     $dbh->do(q{
9595         UPDATE permissions SET description = "Add and delete budgets (but can't modifiy budgets)" WHERE description = "Add and delete budgets (but cant modify budgets)";
9596     });
9597     print "Upgrade to $DBversion done (Bug 10749: Fix typo in budget_add_del permission description)\n";
9598     SetVersion ($DBversion);
9599 }
9600
9601 $DBversion = "3.17.00.060";
9602 if ( CheckVersion($DBversion) ) {
9603     my $count_l = $dbh->selectcol_arrayref(q|
9604         SELECT COUNT(*) FROM letter WHERE message_transport_type='feed'
9605     |);
9606     my $count_mq = $dbh->selectcol_arrayref(q|
9607         SELECT COUNT(*) FROM message_queue WHERE message_transport_type='feed'
9608     |);
9609     my $count_ott = $dbh->selectcol_arrayref(q|
9610         SELECT COUNT(*) FROM overduerules_transport_types WHERE message_transport_type='feed'
9611     |);
9612     my $count_mt = $dbh->selectcol_arrayref(q|
9613         SELECT COUNT(*) FROM message_transports WHERE message_transport_type='feed'
9614     |);
9615     my $count_bmtp = $dbh->selectcol_arrayref(q|
9616         SELECT COUNT(*) FROM borrower_message_transport_preferences WHERE message_transport_type='feed'
9617     |);
9618
9619     my $deleted = 0;
9620     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 ) {
9621         $deleted = $dbh->do(q|
9622             DELETE FROM message_transport_types where message_transport_type='feed'
9623         |);
9624         $deleted = $deleted ne '0E0' ? 1 : 0;
9625     }
9626
9627     print "Upgrade to $DBversion done (Bug 12298: Delete the 'feed' message transport type " . ($deleted ? '(deleted!)' : '(not deleted)') . ")\n";
9628     SetVersion($DBversion);
9629 }
9630
9631 $DBversion = "3.18.00.000";
9632 if ( CheckVersion($DBversion) ) {
9633     print "Upgrade to $DBversion done (3.18.0 release)\n";
9634     SetVersion($DBversion);
9635 }
9636
9637 $DBversion = "3.19.00.000";
9638 if ( CheckVersion($DBversion) ) {
9639     print "Upgrade to $DBversion done (there's life after 3.18)\n";
9640     SetVersion ($DBversion);
9641 }
9642
9643 $DBversion = "3.19.00.001";
9644 if ( CheckVersion($DBversion) ) {
9645     $dbh->do("
9646         UPDATE systempreferences
9647         SET options = 'public|school|academic|research|private|societyAssociation|corporate|government|religiousOrg|subscription'
9648         WHERE variable = 'UsageStatsLibraryType'
9649     ");
9650     if ( C4::Context->preference("UsageStatsLibraryType") eq "university" ) {
9651         C4::Context->set_preference("UsageStatsLibraryType", "academic")
9652     }
9653     print "Upgrade to $DBversion done (Bug 13436: Add more options to UsageStatsLibraryType)\n";
9654     SetVersion ($DBversion);
9655 }
9656
9657 $DBversion = "3.19.00.002";
9658 if ( CheckVersion($DBversion) ) {
9659     $dbh->do(q|
9660         UPDATE suggestions SET branchcode="" WHERE branchcode="__ANY__"
9661     |);
9662     print "upgrade to $DBversion done (Bug 10753: replace __ANY__ with empty string in suggestions.branchcode)\n";
9663     SetVersion ($DBversion);
9664 }
9665
9666 $DBversion = "3.19.00.003";
9667 if ( CheckVersion($DBversion) ) {
9668     my ($count) = $dbh->selectrow_array("SELECT COUNT(*) FROM borrowers GROUP BY userid HAVING COUNT(userid) > 1");
9669
9670     if ( $count ) {
9671         print "Upgrade to $DBversion done (Bug 1861 - Unique patrons logins not (totally) enforced) FAILED!\n";
9672         print "Your database has users with duplicate user logins. Please have your administrator deduplicate your user logins.\n";
9673         print "Afterward, your Koha administrator should execute the following database query: ALTER TABLE borrowers DROP INDEX userid, ADD UNIQUE userid (userid)";
9674     } else {
9675         $dbh->do(q{
9676             ALTER TABLE borrowers
9677                 DROP INDEX userid ,
9678                 ADD UNIQUE userid (userid)
9679         });
9680         print "Upgrade to $DBversion done (Bug 1861: Unique patrons logins not (totally) enforced)\n";
9681     }
9682     SetVersion ($DBversion);
9683 }
9684
9685 $DBversion = "3.19.00.004";
9686 if ( CheckVersion($DBversion) ) {
9687     my $pref_value = C4::Context->preference('OpacExportOptions');
9688     $pref_value =~ s/\|/,/g; # multiple is separated by ,
9689     $dbh->do(q{
9690         UPDATE systempreferences
9691             SET value = ?,
9692                 type = 'multiple'
9693         WHERE variable = 'OpacExportOptions'
9694     }, {}, $pref_value );
9695     print "Upgrade to $DBversion done (Bug 13346: OpacExportOptions is now multiple)\n";
9696     SetVersion ($DBversion);
9697 }
9698
9699 $DBversion = "3.19.00.005";
9700 if(CheckVersion($DBversion)) {
9701     $dbh->do(q{
9702         ALTER TABLE authorised_values MODIFY COLUMN category VARCHAR(32) NOT NULL DEFAULT ''
9703     });
9704
9705     $dbh->do(q{
9706         ALTER TABLE borrower_attribute_types MODIFY COLUMN authorised_value_category VARCHAR(32) DEFAULT NULL
9707     });
9708
9709     print "Upgrade to $DBversion done (Bug 13379: Modify authorised_values.category to varchar(32))\n";
9710     SetVersion($DBversion);
9711 }
9712
9713 $DBversion = "3.19.00.006";
9714 if ( CheckVersion($DBversion) ) {
9715     $dbh->do(q|SET foreign_key_checks = 0|);
9716     my $sth = $dbh->table_info( '','','','TABLE' );
9717     my ( $cat, $schema, $name, $type, $remarks );
9718     while ( ( $cat, $schema, $name, $type, $remarks ) = $sth->fetchrow_array ) {
9719         my $table_sth = $dbh->prepare(qq|SHOW CREATE TABLE $name|);
9720         $table_sth->execute;
9721         my @table = $table_sth->fetchrow_array;
9722         unless ( $table[1] =~ /COLLATE=utf8mb4_unicode_ci/ ) { #catches utf8mb4 collated tables
9723             if ( $name eq 'marc_subfield_structure' ) {
9724                 $dbh->do(q|
9725                     ALTER TABLE marc_subfield_structure
9726                     MODIFY COLUMN tagfield varchar(3) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9727                     MODIFY COLUMN tagsubfield varchar(1) COLLATE utf8_bin NOT NULL DEFAULT '',
9728                     MODIFY COLUMN liblibrarian varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9729                     MODIFY COLUMN libopac varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9730                     MODIFY COLUMN kohafield varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
9731                     MODIFY COLUMN authorised_value varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
9732                     MODIFY COLUMN authtypecode varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
9733                     MODIFY COLUMN value_builder varchar(80) COLLATE utf8_unicode_ci DEFAULT NULL,
9734                     MODIFY COLUMN frameworkcode varchar(4) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9735                     MODIFY COLUMN seealso varchar(1100) COLLATE utf8_unicode_ci DEFAULT NULL,
9736                     MODIFY COLUMN link varchar(80) COLLATE utf8_unicode_ci DEFAULT NULL
9737                 |);
9738                 $dbh->do(qq|ALTER TABLE $name CHARACTER SET utf8 COLLATE utf8_unicode_ci|);
9739             }
9740             else {
9741                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci|);
9742             }
9743         }
9744     }
9745     $dbh->do(q|SET foreign_key_checks = 1|);;
9746
9747     print "Upgrade to $DBversion done (Bug 11944: Convert DB tables to utf8_unicode_ci)\n";
9748     SetVersion($DBversion);
9749 }
9750
9751 $DBversion = "3.19.00.007";
9752 if ( CheckVersion($DBversion) ) {
9753     my $orphan_budgets = $dbh->selectall_arrayref(q|
9754         SELECT budget_id, budget_name, budget_code
9755         FROM aqbudgets
9756         WHERE   budget_parent_id IS NOT NULL
9757             AND budget_parent_id NOT IN (
9758                 SELECT DISTINCT budget_id FROM aqbudgets
9759             )
9760     |, { Slice => {} } );
9761
9762     if ( @$orphan_budgets ) {
9763         for my $b ( @$orphan_budgets ) {
9764             print "Fund $b->{budget_name} (code:$b->{budget_code}, id:$b->{budget_id}) does not have a parent, it may cause problem\n";
9765         }
9766         print "Upgrade to $DBversion done (Bug 12905: Check budget integrity: FAIL)\n";
9767     } else {
9768         print "Upgrade to $DBversion done (Bug 12905: Check budget integrity: OK)\n";
9769     }
9770     SetVersion ($DBversion);
9771 }
9772
9773 $DBversion = "3.19.00.008";
9774 if ( CheckVersion($DBversion) ) {
9775     my $number_of_orders_not_linked = $dbh->selectcol_arrayref(q|
9776         SELECT COUNT(*)
9777         FROM aqorders o
9778         WHERE NOT EXISTS (
9779             SELECT NULL
9780             FROM aqbudgets b
9781             WHERE b.budget_id = o.budget_id
9782         );
9783     |);
9784
9785     if ( $number_of_orders_not_linked->[0] > 0 ) {
9786         $dbh->do(q|
9787             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)
9788         |);
9789         my $budget_period_id = $dbh->last_insert_id( undef, undef, 'aqbudgetperiods', undef );
9790         $dbh->do(qq|
9791             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 );
9792         |);
9793         my $budget_id = $dbh->last_insert_id( undef, undef, 'aqbudgets', undef );
9794         $dbh->do(qq|
9795             UPDATE aqorders o
9796             SET budget_id = $budget_id
9797             WHERE NOT EXISTS (
9798                 SELECT NULL
9799                 FROM aqbudgets b
9800                 WHERE b.budget_id = o.budget_id
9801             )
9802         |);
9803     }
9804
9805     $dbh->do(q|
9806         ALTER TABLE aqorders
9807         ADD CONSTRAINT aqorders_budget_id_fk FOREIGN KEY (budget_id) REFERENCES aqbudgets(budget_id) ON DELETE CASCADE ON UPDATE CASCADE
9808     |);
9809
9810     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";
9811     SetVersion($DBversion);
9812 }
9813
9814 $DBversion = "3.19.00.009";
9815 if ( CheckVersion($DBversion) ) {
9816     $dbh->do(q|
9817         UPDATE suggestions s SET s.budgetid = NULL
9818         WHERE NOT EXISTS (
9819             SELECT NULL
9820             FROM aqbudgets b
9821             WHERE b.budget_id = s.budgetid
9822         );
9823     |);
9824
9825     $dbh->do(q|
9826         ALTER TABLE suggestions
9827         ADD CONSTRAINT suggestions_budget_id_fk FOREIGN KEY (budgetid) REFERENCES aqbudgets(budget_id) ON DELETE SET NULL ON UPDATE CASCADE
9828     |);
9829
9830     print "Upgrade to $DBversion done (Bug 13007: Add new foreign key suggestions.budgetid)\n";
9831     SetVersion($DBversion);
9832 }
9833
9834 $DBversion = "3.19.00.010";
9835 if ( CheckVersion($DBversion) ) {
9836     $dbh->do(q|
9837         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
9838         VALUES('SessionRestrictionByIP','1','Check for Change in  Remote IP address for Session Security. Disable when remote ip address changes frequently.','','YesNo')
9839     |);
9840     print "Upgrade to $DBversion done (Bug 5511: SessionRestrictionByIP)\n";
9841     SetVersion ($DBversion);
9842 }
9843
9844 $DBversion = "3.19.00.011";
9845 if ( CheckVersion($DBversion) ) {
9846     $dbh->do(q|
9847         INSERT INTO userflags (bit, flag, flagdesc, defaulton) VALUES
9848         (20, 'lists', 'Lists', 0)
9849     |);
9850     $dbh->do(q|
9851         INSERT INTO permissions (module_bit, code, description) VALUES
9852         (20, 'delete_public_lists', 'Delete public lists')
9853     |);
9854     print "Upgrade to $DBversion done (Bug 13417: Add permission to delete public lists)\n";
9855     SetVersion ($DBversion);
9856 }
9857
9858 $DBversion = "3.19.00.012";
9859 if(CheckVersion($DBversion)) {
9860     $dbh->do(q{
9861         ALTER TABLE biblioitems MODIFY COLUMN marcxml longtext
9862     });
9863
9864     $dbh->do(q{
9865         ALTER TABLE deletedbiblioitems MODIFY COLUMN marcxml longtext
9866     });
9867
9868     print "Upgrade to $DBversion done (Bug 13523 Remove NOT NULL restriction on field marcxml due to mysql STRICT_TRANS_TABLES)\n";
9869     SetVersion ($DBversion);
9870 }
9871
9872 $DBversion = "3.19.00.013";
9873 if ( CheckVersion($DBversion) ) {
9874     $dbh->do(q|
9875         INSERT INTO permissions (module_bit, code, description) VALUES
9876           (13, 'records_batchmod', 'Perform batch modification of records (biblios or authorities)')
9877     |);
9878     print "Upgrade to $DBversion done (Bug 11395: Add permission tools_records_batchmod)\n";
9879     SetVersion($DBversion);
9880 }
9881
9882 $DBversion = "3.19.00.014";
9883 if ( CheckVersion($DBversion) ) {
9884     $dbh->do(q|
9885         CREATE TABLE aqorder_users (
9886             ordernumber int(11) NOT NULL,
9887             borrowernumber int(11) NOT NULL,
9888             PRIMARY KEY (ordernumber, borrowernumber),
9889             CONSTRAINT aqorder_users_ibfk_1 FOREIGN KEY (ordernumber) REFERENCES aqorders (ordernumber) ON DELETE CASCADE ON UPDATE CASCADE,
9890             CONSTRAINT aqorder_users_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
9891         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
9892     |);
9893
9894     $dbh->do(q|
9895         INSERT INTO letter(module, code, branchcode, name, title, content, message_transport_type)
9896         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')
9897     |);
9898     print "Upgrade to $DBversion done (Bug 12648: Add letter ACQ_NOTIF_ON_RECEIV )\n";
9899     SetVersion ($DBversion);
9900 }
9901
9902 $DBversion = "3.19.00.015";
9903 if ( CheckVersion($DBversion) ) {
9904     $dbh->do(q|
9905         ALTER TABLE search_history ADD COLUMN id INT(11) NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY(id);
9906     |);
9907     print "Upgrade to $DBversion done (Bug 11430: Add primary key for search_history)\n";
9908     SetVersion ($DBversion);
9909 }
9910
9911 $DBversion = "3.19.00.016";
9912 if(CheckVersion($DBversion)) {
9913     my @order_cancellation_reason = $dbh->selectrow_array("SELECT count(*) FROM authorised_values WHERE category='ORDER_CANCELLATION_REASON'");
9914     if ($order_cancellation_reason[0] == 0) {
9915         $dbh->do(q{
9916             INSERT INTO authorised_values (category, authorised_value, lib) VALUES
9917              ('ORDER_CANCELLATION_REASON', 0, 'No reason provided'),
9918              ('ORDER_CANCELLATION_REASON', 1, 'Out of stock'),
9919              ('ORDER_CANCELLATION_REASON', 2, 'Restocking')
9920         });
9921
9922         my $already_existing_reasons = $dbh->selectcol_arrayref(q{
9923             SELECT DISTINCT( cancellationreason )
9924             FROM aqorders;
9925         }, { Slice => {} });
9926
9927         my $update_orders_sth = $dbh->prepare(q{
9928             UPDATE aqorders
9929             SET cancellationreason = ?
9930             WHERE cancellationreason = ?
9931         });
9932
9933         my $insert_av_sth = $dbh->prepare(q{
9934             INSERT INTO authorised_values (category, authorised_value, lib) VALUES
9935              ('ORDER_CANCELLATION_REASON', ?, ?)
9936         });
9937         my $i = 3;
9938         for my $reason ( @$already_existing_reasons ) {
9939             next unless $reason;
9940             $insert_av_sth->execute( $i, $reason );
9941             $update_orders_sth->execute( $i, $reason );
9942             $i++;
9943         }
9944         print "Upgrade to $DBversion done (Bug 13380: Add the ORDER_CANCELLATION_REASON authorised value)\n";
9945     }
9946     else {
9947         print "Upgrade to $DBversion done (Bug 13380: ORDER_CANCELLATION_REASON authorised value already existed from earlier update!)\n";
9948     }
9949
9950     SetVersion($DBversion);
9951 }
9952
9953 $DBversion = '3.19.00.017';
9954 if ( CheckVersion($DBversion) ) {
9955     # First create the column
9956     $dbh->do("ALTER TABLE issuingrules ADD onshelfholds tinyint(1) default 0 NOT NULL");
9957     # Now update the column
9958     if (C4::Context->preference("AllowOnShelfHolds")){
9959         # Pref is on, set allow for all rules
9960         $dbh->do("UPDATE issuingrules SET onshelfholds=1");
9961     } else {
9962         # If the preference is not set, leave off
9963         $dbh->do("UPDATE issuingrules SET onshelfholds=0");
9964     }
9965     # Remove from the systempreferences table
9966     $dbh->do("DELETE FROM systempreferences WHERE variable = 'AllowOnShelfHolds'");
9967
9968     # First create the column
9969     $dbh->do("ALTER TABLE issuingrules ADD opacitemholds char(1) DEFAULT 'N' NOT NULL");
9970     # Now update the column
9971     my $opacitemholds = C4::Context->preference("OPACItemHolds") || '';
9972     if (lc ($opacitemholds) eq 'force') {
9973         $opacitemholds = 'F';
9974     }
9975     else {
9976         $opacitemholds = $opacitemholds ? 'Y' : 'N';
9977     }
9978     # Set allow for all rules
9979     $dbh->do("UPDATE issuingrules SET opacitemholds='$opacitemholds'");
9980
9981     # Remove from the systempreferences table
9982     $dbh->do("DELETE FROM systempreferences WHERE variable = 'OPACItemHolds'");
9983
9984     print "Upgrade to $DBversion done (Bug 5786: Move AllowOnShelfHolds to circulation matrix; Move OPACItemHolds system preference to circulation matrix)\n";
9985     SetVersion ($DBversion);
9986 }
9987
9988
9989 $DBversion = "3.19.00.018";
9990 if ( CheckVersion($DBversion) ) {
9991     $dbh->do(q|
9992         UPDATE systempreferences set variable="OpacAdditionalStylesheet" WHERE variable="opaccolorstylesheet"
9993     |);
9994     print "Upgrade to $DBversion done (Bug 10328: Rename opaccolorstylesheet to OpacAdditionalStylesheet\n";
9995     SetVersion ($DBversion);
9996 }
9997
9998 $DBversion = "3.19.00.019";
9999 if ( CheckVersion($DBversion) ) {
10000     $dbh->do(q{
10001         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
10002         VALUES('Coce','0', 'If on, enables cover retrieval from the configured Coce server', NULL, 'YesNo')
10003     });
10004     $dbh->do(q{
10005         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
10006         VALUES('CoceHost', NULL, 'Coce server URL', NULL,'Free')
10007     });
10008     $dbh->do(q{
10009         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
10010         VALUES('CoceProviders', NULL, 'Coce providers', 'aws,gb,ol', 'multiple')
10011     });
10012     print "Upgrade to $DBversion done (Bug 9580: Cover image from Coce, a remote image URL cache)\n";
10013     SetVersion($DBversion);
10014 }
10015
10016 $DBversion = "3.19.00.020";
10017 if ( CheckVersion($DBversion) ) {
10018     $dbh->do(q|
10019         ALTER TABLE aqorders DROP COLUMN supplierreference;
10020     |);
10021
10022     print "Upgrade to $DBversion done (Bug 11008: DROP column aqorders.supplierreference)\n";
10023     SetVersion($DBversion);
10024 }
10025
10026 $DBversion = "3.19.00.021";
10027 if ( CheckVersion($DBversion) ) {
10028     $dbh->do(q|
10029         ALTER TABLE issues DROP COLUMN issuingbranch
10030     |);
10031     $dbh->do(q|
10032         ALTER TABLE old_issues DROP COLUMN issuingbranch
10033     |);
10034     print "Upgrade to $DBversion done (Bug 2806: Remove issuingbranch columns)\n";
10035     SetVersion ($DBversion);
10036 }
10037
10038 $DBversion = '3.19.00.022';
10039 if ( CheckVersion($DBversion) ) {
10040     $dbh->do(q{
10041         ALTER TABLE suggestions DROP COLUMN mailoverseeing;
10042     });
10043     print "Upgrade to $DBversion done (Bug 13006: Drop column suggestion.mailoverseeing)\n";
10044     SetVersion($DBversion);
10045 }
10046
10047 $DBversion = "3.19.00.023";
10048 if ( CheckVersion($DBversion) ) {
10049     $dbh->do(q|
10050         DELETE FROM systempreferences where variable = 'AddPatronLists'
10051     |);
10052     print "Upgrade to $DBversion done (Bug 13497: Remove the AddPatronLists system preferences)\n";
10053     SetVersion ($DBversion);
10054 }
10055
10056 $DBversion = "3.19.00.024";
10057 if ( CheckVersion($DBversion) ) {
10058     $dbh->do(qq|DROP table patroncards;|);
10059     print "Upgrade to $DBversion done (Bug 13539: Remove table patroncards from database as it's no longer in use)\n";
10060     SetVersion ($DBversion);
10061 }
10062
10063 $DBversion = "3.19.00.025";
10064 if ( CheckVersion($DBversion) ) {
10065     $dbh->do(q|
10066         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
10067         ('SearchWithISBNVariations','0',NULL,'If enabled, search on all variations of the ISBN','YesNo')
10068     |);
10069     print "Upgrade to $DBversion done (Bug 13528: Add the SearchWithISBNVariations syspref)\n";
10070     SetVersion ($DBversion);
10071 }
10072
10073 $DBversion = "3.19.00.026";
10074 if( CheckVersion($DBversion) ) {
10075     if ( C4::Context->preference('marcflavour') eq 'MARC21' ) {
10076     $dbh->do(q{
10077         INSERT IGNORE INTO auth_tag_structure (authtypecode, tagfield, liblibrarian, libopac, repeatable, mandatory, authorised_value) VALUES
10078         ('', '388', 'TIME PERIOD OF CREATION', 'TIME PERIOD OF CREATION', 1, 0, NULL);
10079     });
10080
10081     $dbh->do(q{
10082         INSERT IGNORE INTO auth_subfield_structure (authtypecode, tagfield, tagsubfield, liblibrarian, libopac, repeatable,
10083         mandatory, tab, authorised_value, value_builder, seealso, isurl, hidden, linkid, kohafield, frameworkcode) VALUES
10084         ('', '388', '0', 'Authority record control number or standard number', 'Authority record control number or standard number', 1, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10085         ('', '388', '2', 'Source of term', 'Source of term', 0, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10086         ('', '388', '3', 'Materials specified', 'Materials specified', 0, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10087         ('', '388', '6', 'Linkage', 'Linkage', 0, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10088         ('', '388', '8', 'Field link and sequence number', 'Field link and sequence number', 1, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10089         ('', '388', 'a', 'Time period of creation term', 'Time period of creation term', 1, 0, 3, NULL, NULL, NULL, 0, 0, '', '', '');
10090     });
10091
10092     $dbh->do(q{
10093         UPDATE IGNORE auth_subfield_structure SET repeatable = 1 WHERE tagsubfield = 'g' AND tagfield IN
10094         ('100','110','111','130','400','410','411','430','500','510','511','530','700','710','730');
10095     });
10096
10097     $dbh->do(q{
10098         INSERT IGNORE INTO auth_subfield_structure (authtypecode, tagfield, tagsubfield, liblibrarian, libopac, repeatable,
10099         mandatory, tab, authorised_value, value_builder, seealso, isurl, hidden, linkid, kohafield, frameworkcode) VALUES
10100         ('', '150', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 1, NULL, NULL, NULL, 0, 0, '', '', ''),
10101         ('', '151', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 1, NULL, NULL, NULL, 0, 0, '', '', ''),
10102         ('', '450', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 4, NULL, NULL, NULL, 0, 0, '', '', ''),
10103         ('', '451', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 4, NULL, NULL, NULL, 0, 0, '', '', ''),
10104         ('', '550', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 5, NULL, NULL, NULL, 0, 0, '', '', ''),
10105         ('', '551', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 5, NULL, NULL, NULL, 0, 0, '', '', ''),
10106         ('', '750', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10107         ('', '751', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10108         ('', '748', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10109         ('', '755', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10110         ('', '780', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10111         ('', '781', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10112         ('', '782', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10113         ('', '785', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10114         ('', '710', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10115         ('', '730', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10116         ('', '748', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10117         ('', '750', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10118         ('', '751', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10119         ('', '755', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10120         ('', '762', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10121         ('', '780', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10122         ('', '781', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10123         ('', '782', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10124         ('', '785', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10125         ('', '788', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', '');
10126     });
10127
10128     $dbh->do(q{
10129         UPDATE IGNORE auth_subfield_structure SET liblibrarian = 'Relationship information', libopac = 'Relationship information'
10130         WHERE tagsubfield = 'i' AND tagfield IN ('700','710','730','750','751','762');
10131     });
10132
10133     $dbh->do(q{
10134         UPDATE IGNORE auth_subfield_structure SET liblibrarian = 'Relationship code', libopac = 'Relationship code'
10135         WHERE tagsubfield = '4' AND tagfield IN ('700','710');
10136     });
10137
10138     $dbh->do(q{
10139         INSERT IGNORE INTO marc_tag_structure (tagfield, liblibrarian, libopac, repeatable, mandatory, authorised_value, frameworkcode) VALUES
10140         ('370', 'ASSOCIATED PLACE', 'ASSOCIATED PLACE', 1, 0, NULL, ''),
10141         ('388', 'TIME PERIOD OF CREATION', 'TIME PERIOD OF CREATION', 1, 0, NULL, '');
10142     });
10143
10144     $dbh->do(q{
10145         INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian, libopac, repeatable, mandatory,
10146         kohafield, tab, authorised_value, authtypecode, value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
10147         ('370', '0', 'Authority record control number or standard number', 'Authority record control number or standard number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10148         ('370', '2', 'Source of term', 'Source of term', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10149         ('370', '6', 'Linkage', 'Linkage', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10150         ('370', '8', 'Field link and sequence number', 'Field link and sequence number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10151         ('370', 'c', 'Associated country', 'Associated country', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10152         ('370', 'f', 'Other associated place', 'Other associated place', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10153         ('370', 'g', 'Place of origin of work', 'Place of origin of work', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10154         ('370', 's', 'Start period', 'Start period', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10155         ('370', 't', 'End period', 'End period', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10156         ('370', 'u', 'Uniform Resource Identifier', 'Uniform Resource Identifier', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10157         ('370', 'v', 'Source of information', 'Source of information', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10158         ('377', 'l', 'Language term', 'Language term', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10159         ('382', 's', 'Total number of performers', 'Total number of performers', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10160         ('388', '0', 'Authority record control number or standard number', 'Authority record control number or standard number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10161         ('388', '2', 'Source of term', 'Source of term', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10162         ('388', '3', ' Materials specified', ' Materials specified', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10163         ('388', '6', ' Linkage', ' Linkage', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10164         ('388', '8', 'Field link and sequence number', 'Field link and sequence number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10165         ('388', 'a', 'Time period of creation term', 'Time period of creation term', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10166         ('650', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, '', 6, '', '', '', 0, -1, '', '', '', NULL),
10167         ('651', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, '', 6, '', '', '', 0, -1, '', '', '', NULL);
10168     });
10169
10170     $dbh->do(q{
10171         UPDATE IGNORE marc_subfield_structure SET repeatable = 1 WHERE tagsubfield = 'g' AND
10172         tagfield IN ('100','110','111','130','240','243','246','247','600','610','611','630','700','710','711','730','800','810','811','830');
10173     });
10174     }
10175
10176     print "Upgrade to $DBversion done (Bug 13322: Update MARC21 frameworks to Update No. 19 - October 2014)\n";
10177     SetVersion($DBversion);
10178 }
10179
10180 $DBversion = '3.19.00.027';
10181 if ( CheckVersion($DBversion) ) {
10182     $dbh->do("ALTER TABLE items ADD COLUMN itemnotes_nonpublic MEDIUMTEXT AFTER itemnotes");
10183     $dbh->do("ALTER TABLE deleteditems ADD COLUMN itemnotes_nonpublic MEDIUMTEXT AFTER itemnotes");
10184     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";
10185     SetVersion($DBversion);
10186 }
10187
10188 $DBversion = "3.19.00.028";
10189 if( CheckVersion($DBversion) ) {
10190     eval {
10191         local $dbh->{PrintError} = 0;
10192         $dbh->do(q{
10193             ALTER TABLE issues DROP PRIMARY KEY
10194         });
10195     };
10196
10197     $dbh->do(q{
10198         ALTER TABLE old_issues ADD issue_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10199     });
10200
10201     $dbh->do(q{
10202         ALTER TABLE old_issues CHANGE issue_id issue_id INT( 11 ) NOT NULL
10203     });
10204
10205     $dbh->do(q{
10206         ALTER TABLE issues ADD issue_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10207     });
10208
10209     $dbh->do(q{
10210         UPDATE issues SET issue_id = issue_id + ( SELECT COUNT(*) FROM old_issues ) ORDER BY issue_id DESC
10211     });
10212
10213     my $max_issue_id = $schema->resultset('Issue')->get_column('issue_id')->max();
10214     if ($max_issue_id) {
10215         $max_issue_id++;
10216         $dbh->do(qq{
10217             ALTER TABLE issues AUTO_INCREMENT = $max_issue_id
10218         });
10219     }
10220
10221     print "Upgrade to $DBversion done (Bug 13790: Add unique id issue_id to issues and oldissues tables)\n";
10222     SetVersion($DBversion);
10223 }
10224
10225 $DBversion = "3.19.00.029";
10226 if ( CheckVersion($DBversion) ) {
10227     $dbh->do(q|
10228          ALTER TABLE sessions CHANGE COLUMN a_session a_session MEDIUMTEXT
10229     |);
10230     print "Upgrade to $DBversion done (Bug 13606: Upgrade sessions.a_session to MEDIUMTEXT)\n";
10231     SetVersion($DBversion);
10232 }
10233
10234 $DBversion = "3.19.00.030";
10235 if ( CheckVersion($DBversion) ) {
10236     $dbh->do(q|
10237 UPDATE language_subtag_registry SET subtag = 'kn' WHERE subtag = 'ka' AND description = 'Kannada';
10238     |);
10239     $dbh->do(q|
10240 UPDATE language_rfc4646_to_iso639 SET rfc4646_subtag = 'kn' WHERE rfc4646_subtag = 'ka' AND iso639_2_code = 'kan';
10241     |);
10242     $dbh->do(q|
10243 UPDATE language_descriptions SET subtag = 'kn', lang = 'kn' WHERE subtag = 'ka' AND lang = 'ka' AND description = 'ಕನ್ನಡ';
10244     |);
10245     $dbh->do(q|
10246 UPDATE language_descriptions SET subtag = 'kn' WHERE subtag = 'ka' AND description = 'Kannada';
10247     |);
10248     $dbh->do(q|
10249 INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ka', 'language', 'Georgian','2015-04-20');
10250     |);
10251     $dbh->do(q|
10252 DELETE FROM language_subtag_registry
10253        WHERE NOT id IN
10254          (SELECT id FROM
10255            (SELECT MIN(id) as id,subtag,type,description,added
10256             FROM language_subtag_registry
10257             GROUP BY subtag,type,description,added)
10258            AS subtable);
10259     |);
10260     $dbh->do(q|
10261 INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ka', 'geo');
10262     |);
10263     $dbh->do(q|
10264 DELETE FROM language_rfc4646_to_iso639
10265        WHERE NOT id IN
10266          (SELECT id FROM
10267            (SELECT MIN(id) as id,rfc4646_subtag,iso639_2_code
10268             FROM language_rfc4646_to_iso639
10269             GROUP BY rfc4646_subtag,iso639_2_code)
10270            AS subtable);
10271     |);
10272     $dbh->do(q|
10273 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'ka', 'ქართული');
10274     |);
10275     $dbh->do(q|
10276 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'en', 'Georgian');
10277     |);
10278     $dbh->do(q|
10279 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'fr', 'Géorgien');
10280     |);
10281     $dbh->do(q|
10282 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'de', 'Georgisch');
10283     |);
10284     $dbh->do(q|
10285 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'es', 'Georgiano');
10286     |);
10287     $dbh->do(q|
10288 DELETE FROM language_descriptions
10289        WHERE NOT id IN
10290          (SELECT id FROM
10291            (SELECT MIN(id) as id,subtag,type,lang,description
10292             FROM language_descriptions GROUP BY subtag,type,lang,description)
10293            AS subtable);
10294     |);
10295     print "Upgrade to $DBversion done (Bug 14030: Add Georgian language and fix Kannada language code)\n";
10296     SetVersion($DBversion);
10297 }
10298
10299 $DBversion = "3.19.00.031";
10300 if ( CheckVersion($DBversion) ) {
10301     $dbh->do(q{
10302         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10303         VALUES('IdRef','0','Disable/enable the IdRef webservice from the OPAC detail page.',NULL,'YesNo')
10304     });
10305     print "Upgrade to $DBversion done (Bug 8992: Add system preference IdRef))\n";
10306     SetVersion($DBversion);
10307 }
10308
10309 $DBversion = "3.19.00.032";
10310 if ( CheckVersion($DBversion) ) {
10311     $dbh->do(q|
10312         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10313         VALUES('AddressFormat','us','Choose format to display postal addresses','','Choice')
10314     |);
10315     print "Upgrade to $DBversion done (Bug 4041: Address Format as a I18N/L10N system preference\n";
10316     SetVersion ($DBversion);
10317 }
10318
10319 $DBversion = "3.19.00.033";
10320 if ( CheckVersion($DBversion) ) {
10321     $dbh->do(q|
10322         ALTER TABLE auth_header
10323         CHANGE COLUMN datemodified modification_time TIMESTAMP NOT NULL default CURRENT_TIMESTAMP
10324     |);
10325     $dbh->do(q|
10326         ALTER TABLE auth_header
10327         CHANGE COLUMN modification_time modification_time TIMESTAMP NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP
10328     |);
10329     print "Upgrade to $DBversion done (Bug 11165: Update auth_header.datemodified when updated)\n";
10330     SetVersion ($DBversion);
10331 }
10332
10333 $DBversion = "3.19.00.034";
10334 if ( CheckVersion($DBversion) ) {
10335     $dbh->do(q|
10336         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10337         VALUES('CardnumberLength', '', '', 'Set a length for card numbers.', 'Free')
10338     |);
10339     print "Upgrade to $DBversion done (Bug 13984: CardnumberLength syspref missing on some setups\n";
10340     SetVersion ($DBversion);
10341 }
10342
10343 $DBversion = "3.19.00.035";
10344 if ( CheckVersion($DBversion) ) {
10345     $dbh->do(q|
10346         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('useDischarge','','Allows librarians to discharge borrowers and borrowers to request a discharge','','YesNo')
10347     |);
10348     $dbh->do(q|
10349         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.')
10350     |);
10351
10352     $dbh->do(q|
10353         ALTER TABLE borrower_debarments CHANGE type type ENUM('SUSPENSION','OVERDUES','MANUAL','DISCHARGE') NOT NULL DEFAULT 'MANUAL'
10354     |);
10355
10356     $dbh->do(q|
10357         CREATE TABLE discharges (
10358           borrower int(11) DEFAULT NULL,
10359           needed timestamp NULL DEFAULT NULL,
10360           validated timestamp NULL DEFAULT NULL,
10361           KEY borrower_discharges_ibfk1 (borrower),
10362           CONSTRAINT borrower_discharges_ibfk1 FOREIGN KEY (borrower) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
10363         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
10364     |);
10365
10366     print "Upgrade to $DBversion done (Bug 8007: Add System Preferences useDischarge, the discharge notice and the new table discharges)\n";
10367     SetVersion($DBversion);
10368 }
10369
10370 $DBversion = "3.19.00.036";
10371 if ( CheckVersion($DBversion) ) {
10372     $dbh->do(q|
10373         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10374         VALUES ('CronjobLog','0',NULL,'If ON, log information from cron jobs.','YesNo')
10375     |);
10376     print "Upgrade to $DBversion done (Bug 13889: Add cron jobs information to system log)\n";
10377     SetVersion ($DBversion);
10378 }
10379
10380 $DBversion = "3.19.00.037";
10381 if ( CheckVersion($DBversion) ) {
10382     $dbh->do(q|
10383         ALTER TABLE marc_subfield_structure
10384         MODIFY COLUMN tagsubfield varchar(1) COLLATE utf8_bin NOT NULL DEFAULT ''
10385     |);
10386     print "Upgrade to $DBversion done (Bug 13810: Change collate for tagsubfield (utf8_bin))\n";
10387     SetVersion ($DBversion);
10388 }
10389
10390 $DBversion = "3.19.00.038";
10391 if ( CheckVersion($DBversion) ) {
10392     $dbh->do(q|
10393         ALTER TABLE virtualshelves
10394         ADD COLUMN created_on DATETIME NOT NULL AFTER lastmodified
10395     |);
10396     # Set created_on = lastmodified
10397     # I would say it's better than 0000-00-00
10398     # Set modified to the existing value (do not get the current ts!)
10399     $dbh->do(q|
10400         UPDATE virtualshelves
10401         SET created_on = lastmodified, lastmodified = lastmodified
10402     |);
10403     print "Upgrade to $DBversion done (Bug 13421: Add DB field virtualshelves.created_on)\n";
10404     SetVersion ($DBversion);
10405 }
10406
10407 $DBversion = "3.19.00.039";
10408 if ( CheckVersion($DBversion) ) {
10409     print "Upgrade to $DBversion done (Koha 3.20 beta)\n";
10410     SetVersion ($DBversion);
10411 }
10412
10413 $DBversion = "3.19.00.040";
10414 if ( CheckVersion($DBversion) ) {
10415     $dbh->do(q|
10416         ALTER TABLE aqorders DROP COLUMN totalamount
10417     |);
10418     print "Upgrade to $DBversion done (Bug 11006: Drop column aqorders.totalamount)\n";
10419     SetVersion ($DBversion);
10420 }
10421
10422 $DBversion = "3.19.00.041";
10423 if ( CheckVersion($DBversion) ) {
10424     unless ( index_exists( 'suggestions', 'status' ) ) {
10425         $dbh->do(q|
10426             ALTER TABLE suggestions ADD KEY status (STATUS)
10427         |);
10428     }
10429     unless ( index_exists( 'suggestions', 'biblionumber' ) ) {
10430         $dbh->do(q|
10431             ALTER TABLE suggestions ADD KEY biblionumber (biblionumber)
10432         |);
10433     }
10434     unless ( index_exists( 'suggestions', 'branchcode' ) ) {
10435         $dbh->do(q|
10436             ALTER TABLE suggestions ADD KEY branchcode (branchcode)
10437         |);
10438     }
10439     print "Upgrade to $DBversion done (Bug 14132: suggestions table is missing indexes)\n";
10440     SetVersion ($DBversion);
10441 }
10442
10443 $DBversion = "3.19.00.042";
10444 if ( CheckVersion($DBversion) ) {
10445     $dbh->do(q{
10446         DELETE ass.*
10447         FROM auth_subfield_structure AS ass
10448         LEFT JOIN auth_types USING(authtypecode)
10449         WHERE auth_types.authtypecode IS NULL
10450     });
10451
10452     unless ( foreign_key_exists( 'auth_subfield_structure', 'auth_subfield_structure_ibfk_1' ) ) {
10453         $dbh->do(q{
10454             ALTER TABLE auth_subfield_structure
10455             ADD CONSTRAINT auth_subfield_structure_ibfk_1
10456             FOREIGN KEY (authtypecode) REFERENCES auth_types(authtypecode)
10457             ON DELETE CASCADE ON UPDATE CASCADE
10458         });
10459     }
10460
10461     print "Upgrade to $DBversion done (Bug 8480: Add foreign key on auth_subfield_structure.authtypecode)\n";
10462     SetVersion($DBversion);
10463 }
10464
10465 $DBversion = "3.19.00.043";
10466 if ( CheckVersion($DBversion) ) {
10467     $dbh->do(q|
10468         INSERT IGNORE INTO authorised_values (category, authorised_value, lib) VALUES
10469         ('REPORT_GROUP', 'SER', 'Serials')
10470     |);
10471
10472     print "Upgrade to $DBversion done (Bug 5338: Add Serial to the report groups if does not exist)\n";
10473     SetVersion ($DBversion);
10474 }
10475
10476 $DBversion = "3.20.00.000";
10477 if ( CheckVersion($DBversion) ) {
10478     print "Upgrade to $DBversion done (Koha 3.20)\n";
10479     SetVersion ($DBversion);
10480 }
10481
10482 $DBversion = "3.21.00.000";
10483 if ( CheckVersion($DBversion) ) {
10484     print "Upgrade to $DBversion done (El tiempo vuela, un nuevo ciclo comienza.)\n";
10485     SetVersion ($DBversion);
10486 }
10487
10488 $DBversion = "3.21.00.001";
10489 if ( CheckVersion($DBversion) ) {
10490     $dbh->do(q|
10491         UPDATE systempreferences SET variable='IntranetUserJS' where variable='intranetuserjs'
10492     |);
10493     print "Upgrade to $DBversion done (Bug 12160: Rename intranetuserjs to IntranetUserJS)\n";
10494     SetVersion ($DBversion);
10495 }
10496
10497 $DBversion = "3.21.00.002";
10498 if ( CheckVersion($DBversion) ) {
10499     $dbh->do(q|
10500         UPDATE systempreferences SET variable='OPACUserJS' where variable='opacuserjs'
10501     |);
10502     print "Upgrade to $DBversion done (Bug 12160: Rename opacuserjs to OPACUserJS)\n";
10503     SetVersion ($DBversion);
10504 }
10505
10506 $DBversion = "3.21.00.003";
10507 if ( CheckVersion($DBversion) ) {
10508     $dbh->do(q|
10509         INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added)
10510         VALUES ( 'IN', 'region', 'India','2015-05-28');
10511     |);
10512     $dbh->do(q|
10513         INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)
10514         VALUES ( 'IN', 'region', 'en', 'India');
10515     |);
10516     $dbh->do(q|
10517         INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)
10518         VALUES ( 'IN', 'region', 'bn', 'ভারত');
10519     |);
10520     print "Upgrade to $DBversion done (Bug 14285: Add new region India)\n";
10521     SetVersion ($DBversion);
10522 }
10523
10524 $DBversion = '3.21.00.004';
10525 if ( CheckVersion($DBversion) ) {
10526     my $OPACBaseURL = C4::Context->preference('OPACBaseURL');
10527     if (defined($OPACBaseURL) && substr($OPACBaseURL,0,4) ne "http") {
10528         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.};
10529         $OPACBaseURL = 'http://' . $OPACBaseURL;
10530         my $sth_OPACBaseURL = $dbh->prepare( q{
10531             UPDATE systempreferences SET value=?,explanation=?
10532             WHERE variable='OPACBaseURL'; } );
10533         $sth_OPACBaseURL->execute($OPACBaseURL,$explanation);
10534     }
10535     if (defined($OPACBaseURL)) {
10536         $dbh->do( q{ UPDATE letter
10537                      SET content=replace(content,
10538                                          'http://<<OPACBaseURL>>',
10539                                          '<<OPACBaseURL>>')
10540                      WHERE content LIKE "%http://<<OPACBaseURL>>%"; } );
10541     }
10542
10543     print "Upgrade to $DBversion done (Bug 5010: Fix OPACBaseURL to include protocol)\n";
10544     SetVersion($DBversion);
10545 }
10546
10547 $DBversion = "3.21.00.005";
10548 if ( CheckVersion($DBversion) ) {
10549     $dbh->do(q|
10550         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10551         VALUES ('ReportsLog','0',NULL,'If ON, log information about reports.','YesNo')
10552     |);
10553     print "Upgrade to $DBversion done (Bug 14024: Add reports to action logs)\n";
10554     SetVersion ($DBversion);
10555 }
10556
10557 $DBversion = "3.21.00.006";
10558 if ( CheckVersion($DBversion) ) {
10559     # Remove the borrow permission flag (bit 7)
10560     $dbh->do(q|
10561         UPDATE borrowers
10562         SET flags = flags - ( flags & (1<<7) )
10563         WHERE flags IS NOT NULL
10564             AND flags > 0
10565     |);
10566     $dbh->do(q|
10567         DELETE FROM userflags WHERE bit=7;
10568     |);
10569     print "Upgrade to $DBversion done (Bug 7976: Remove the 'borrow' permission)\n";
10570     SetVersion($DBversion);
10571 }
10572
10573 $DBversion = "3.21.00.007";
10574 if ( CheckVersion($DBversion) ) {
10575     unless ( index_exists( 'aqbasket', 'authorisedby' ) ) {
10576         $dbh->do(q|
10577             ALTER TABLE aqbasket
10578                 ADD KEY authorisedby (authorisedby)
10579         |);
10580     }
10581     unless ( index_exists( 'aqbooksellers', 'name' ) ) {
10582         $dbh->do(q|
10583             ALTER TABLE aqbooksellers
10584                 ADD KEY name (name(255))
10585         |);
10586     }
10587     unless ( index_exists( 'aqbudgets', 'budget_parent_id' ) ) {
10588         $dbh->do(q|
10589             ALTER TABLE aqbudgets
10590                 ADD KEY budget_parent_id (budget_parent_id)|);
10591         }
10592     unless ( index_exists( 'aqbudgets', 'budget_code' ) ) {
10593         $dbh->do(q|
10594             ALTER TABLE aqbudgets
10595                 ADD KEY budget_code (budget_code)|);
10596     }
10597     unless ( index_exists( 'aqbudgets', 'budget_branchcode' ) ) {
10598         $dbh->do(q|
10599             ALTER TABLE aqbudgets
10600                 ADD KEY budget_branchcode (budget_branchcode)|);
10601     }
10602     unless ( index_exists( 'aqbudgets', 'budget_period_id' ) ) {
10603         $dbh->do(q|
10604             ALTER TABLE aqbudgets
10605                 ADD KEY budget_period_id (budget_period_id)|);
10606     }
10607     unless ( index_exists( 'aqbudgets', 'budget_owner_id' ) ) {
10608         $dbh->do(q|
10609             ALTER TABLE aqbudgets
10610                 ADD KEY budget_owner_id (budget_owner_id)|);
10611     }
10612     unless ( index_exists( 'aqbudgets_planning', 'budget_period_id' ) ) {
10613         $dbh->do(q|
10614             ALTER TABLE aqbudgets_planning
10615                 ADD KEY budget_period_id (budget_period_id)|);
10616     }
10617     unless ( index_exists( 'aqorders', 'parent_ordernumber' ) ) {
10618         $dbh->do(q|
10619             ALTER TABLE aqorders
10620                 ADD KEY parent_ordernumber (parent_ordernumber)|);
10621     }
10622     unless ( index_exists( 'aqorders', 'orderstatus' ) ) {
10623         $dbh->do(q|
10624             ALTER TABLE aqorders
10625                 ADD KEY orderstatus (orderstatus)|);
10626     }
10627     print "Upgrade to $DBversion done (Bug 14053: Acquisition db tables are missing indexes)\n";
10628     SetVersion ($DBversion);
10629 }
10630
10631 $DBversion = "3.21.00.008";
10632 if ( CheckVersion($DBversion) ) {
10633     $dbh->do(q{
10634         DELETE IGNORE FROM systempreferences
10635         WHERE variable = 'HomeOrHoldingBranchReturn';
10636     });
10637     print "Upgrade to $DBversion done (Bug 7981: Transfer message on return. HomeOrHoldingBranchReturn syspref removed in favour of circulation rules.)\n";
10638     SetVersion($DBversion);
10639 }
10640
10641 $DBversion = "3.21.00.009";
10642 if ( CheckVersion($DBversion) ) {
10643
10644     sanitize_zero_date('aqorders', 'datecancellationprinted');
10645
10646     $dbh->do(q|
10647         UPDATE aqorders SET orderstatus='cancelled'
10648         WHERE (datecancellationprinted IS NOT NULL)
10649     |);
10650
10651     print "Upgrade to $DBversion done (Bug 13993: Correct orderstatus for transferred orders)\n";
10652     SetVersion($DBversion);
10653 }
10654
10655 $DBversion = "3.21.00.010";
10656 if ( CheckVersion($DBversion) ) {
10657     $dbh->do(q|
10658         ALTER TABLE message_queue
10659             DROP message_id
10660     |);
10661     $dbh->do(q|
10662         ALTER TABLE message_queue
10663             ADD message_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10664     |);
10665     print "Upgrade to $DBversion done (Bug 7793: redefine the field message_id as PRIMARY KEY of message_queue)\n";
10666     SetVersion ($DBversion);
10667 }
10668
10669 $DBversion = "3.21.00.011";
10670 if ( CheckVersion($DBversion) ) {
10671     $dbh->do(q{
10672         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10673         VALUES ('OpacLangSelectorMode','footer','top|both|footer','Select the location to display the language selector','Choice')
10674     });
10675     print "Upgrade to $DBversion done (Bug 14252: Make the OPAC language switcher available in the masthead navbar, footer, or both)\n";
10676     SetVersion ($DBversion);
10677 }
10678
10679 $DBversion = "3.21.00.012";
10680 if ( CheckVersion($DBversion) ) {
10681     $dbh->do(q|
10682         INSERT INTO letter (module, code, name, title, content, message_transport_type)
10683         VALUES
10684         ('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')
10685     |);
10686     print "Upgrade to $DBversion done (Bug 13014: Add the TO_PROCESS letter code)\n";
10687     SetVersion($DBversion);
10688 }
10689
10690 $DBversion = "3.21.00.013";
10691 if ( CheckVersion($DBversion) ) {
10692     my $msg;
10693     if ( C4::Context->preference('OPACPrivacy') ) {
10694         if ( my $anonymous_patron = C4::Context->preference('AnonymousPatron') ) {
10695             my $anonymous_patron_exists = $dbh->selectcol_arrayref(q|
10696                 SELECT COUNT(*)
10697                 FROM borrowers
10698                 WHERE borrowernumber=?
10699             |, {}, $anonymous_patron);
10700             unless ( $anonymous_patron_exists->[0] ) {
10701                 $msg = "Configuration WARNING: OPACPrivacy is set but AnonymousPatron is not linked to an existing patron";
10702             }
10703         }
10704         else {
10705             $msg = "Configuration WARNING: OPACPrivacy is set but AnonymousPatron is not";
10706         }
10707     }
10708     else {
10709         my $patrons_have_required_anonymity = $dbh->selectcol_arrayref(q|
10710             SELECT COUNT(*)
10711             FROM borrowers
10712             WHERE privacy = 2
10713         |, {} );
10714         if ( $patrons_have_required_anonymity->[0] ) {
10715             $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.";
10716         }
10717     }
10718
10719     $msg //= "Privacy is correctly set";
10720     print "Upgrade to $DBversion done (Bug 9942: $msg)\n";
10721     SetVersion ($DBversion);
10722 }
10723
10724 $DBversion = "3.21.00.014";
10725 if ( CheckVersion($DBversion) ) {
10726     $dbh->do(q{
10727         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10728         VALUES ('OAI-PMH:DeletedRecord','persistent','Koha\'s deletedbiblio table will never be deleted (persistent) or might be deleted (transient)','transient|persistent','Choice')
10729     });
10730
10731     if ( foreign_key_exists( 'oai_sets_biblios', 'oai_sets_biblios_ibfk_1' ) ) {
10732         $dbh->do(q|
10733             ALTER TABLE oai_sets_biblios DROP FOREIGN KEY oai_sets_biblios_ibfk_1
10734         |);
10735     }
10736     print "Upgrade to $DBversion done (Bug 3206: OAI repository deleted record support)\n";
10737     SetVersion ($DBversion);
10738 }
10739
10740 $DBversion = "3.21.00.015";
10741 if ( CheckVersion($DBversion) ) {
10742     $dbh->do(q{
10743         UPDATE systempreferences SET value='0' WHERE variable='CalendarFirstDayOfWeek' AND value='Sunday';
10744     });
10745     $dbh->do(q{
10746         UPDATE systempreferences SET value='1' WHERE variable='CalendarFirstDayOfWeek' AND value='Monday';
10747     });
10748     $dbh->do(q{
10749         UPDATE systempreferences SET options='0|1|2|3|4|5|6' WHERE variable='CalendarFirstDayOfWeek';
10750     });
10751
10752     print "Upgrade to $DBversion done (Bug 12137: Extend functionality of CalendarFirstDayOfWeek to be any day)\n";
10753     SetVersion($DBversion);
10754 }
10755
10756 $DBversion = "3.21.00.016";
10757 if ( CheckVersion($DBversion) ) {
10758     my $rs = $schema->resultset('Systempreference');
10759     $rs->find_or_create(
10760         {
10761             variable => 'DumpTemplateVarsIntranet',
10762             value    => 0,
10763             explanation => 'If enabled, dump all Template Toolkit variable to a comment in the html source for the staff intranet.',
10764             type => 'YesNo',
10765         }
10766     );
10767     $rs->find_or_create(
10768         {
10769             variable => 'DumpTemplateVarsOpac',
10770             value    => 0,
10771             explanation => 'If enabled, dump all Template Toolkit variable to a comment in the html source for the opac.',
10772             type => 'YesNo',
10773         }
10774     );
10775     print "Upgrade to $DBversion done (Bug 13948: Add ability to dump template toolkit variables to html comment)\n";
10776     SetVersion($DBversion);
10777 }
10778
10779 $DBversion = "3.21.00.017";
10780 if ( CheckVersion($DBversion) ) {
10781     $dbh->do("
10782         CREATE TABLE uploaded_files (
10783             id int(11) NOT NULL AUTO_INCREMENT,
10784             hashvalue CHAR(40) NOT NULL,
10785             filename TEXT NOT NULL,
10786             dir TEXT NOT NULL,
10787             filesize int(11),
10788             dtcreated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
10789             categorycode tinytext,
10790             owner int(11),
10791             PRIMARY KEY (id)
10792         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
10793     ");
10794
10795     print "Upgrade to $DBversion done (Bug 6874: New cataloging plugin upload.pl)\n";
10796     print "This plugin comes with a new config variable (upload_path) and a new table (uploaded_files)\n";
10797     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";
10798     SetVersion($DBversion);
10799 }
10800
10801 $DBversion = "3.21.00.018";
10802 if ( CheckVersion($DBversion) ) {
10803     $dbh->do(q{
10804         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10805         VALUES
10806             ('RestrictedPageLocalIPs','',NULL,'Beginning of IP addresses considered as local (comma separated ex: \"127.0.0,127.0.2\")','Free'),
10807             ('RestrictedPageContent','',NULL,'HTML content of the restricted page','TextArea'),
10808             ('RestrictedPageTitle','',NULL,'Title of the restricted page (breadcrumb and header)','Free')
10809     });
10810     print "Upgrade to $DBversion done (Bug 13485: Add a page to display links to restricted sites)\n";
10811     SetVersion ($DBversion);
10812 }
10813
10814 $DBversion = "3.21.00.019";
10815 if ( CheckVersion($DBversion) ) {
10816     if ( column_exists( 'reserves', 'constrainttype' ) ) {
10817         $dbh->do(q{
10818             ALTER TABLE reserves DROP constrainttype
10819         });
10820         $dbh->do(q{
10821             ALTER TABLE old_reserves DROP constrainttype
10822         });
10823     }
10824     $dbh->do(q{
10825         DROP TABLE IF EXISTS reserveconstraints
10826     });
10827     print "Upgrade to $DBversion done (Bug 9809: Get rid of reserveconstraints)\n";
10828     SetVersion ($DBversion);
10829 }
10830
10831 $DBversion = "3.21.00.020";
10832 if ( CheckVersion($DBversion) ) {
10833     $dbh->do(q{
10834         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`)
10835         VALUES ('FeeOnChangePatronCategory','1','','If set, when a patron changes to a category with enrolment fee, a fee is charged','YesNo')
10836     });
10837     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";
10838     SetVersion($DBversion);
10839 }
10840
10841 $DBversion = "3.21.00.021";
10842 if ( CheckVersion($DBversion) ) {
10843     $dbh->do(q{
10844         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10845         VALUES ('UseWYSIWYGinSystemPreferences','0','','Show WYSIWYG editor when editing certain HTML system preferences.','YesNo')
10846     });
10847     print "Upgrade to $DBversion done (Bug 11584: Add wysiwyg editor to system preferences dealing with HTML)\n";
10848     SetVersion($DBversion);
10849 }
10850
10851 $DBversion = "3.21.00.022";
10852 if ( CheckVersion($DBversion) ) {
10853     $dbh->do(q{
10854         DELETE cr.*
10855         FROM course_reserves AS cr
10856         LEFT JOIN course_items USING(ci_id)
10857         WHERE course_items.ci_id IS NULL
10858     });
10859
10860     my ($print_error) = $dbh->{PrintError};
10861     $dbh->{RaiseError} = 0;
10862     $dbh->{PrintError} = 0;
10863     if ( foreign_key_exists('course_reserves', 'course_reserves_ibfk_2') ) {
10864         $dbh->do(q{ALTER TABLE course_reserves DROP FOREIGN KEY course_reserves_ibfk_2});
10865         $dbh->do(q{ALTER TABLE course_reserves DROP INDEX course_reserves_ibfk_2});
10866     }
10867     $dbh->{PrintError} = $print_error;
10868
10869     $dbh->do(q{
10870         ALTER TABLE course_reserves
10871             ADD CONSTRAINT course_reserves_ibfk_2
10872                 FOREIGN KEY (ci_id) REFERENCES course_items (ci_id)
10873                 ON DELETE CASCADE ON UPDATE CASCADE
10874     });
10875     print "Upgrade to $DBversion done (Bug 14205: Deleting an Item/Record does not remove link to course reserve)\n";
10876     SetVersion($DBversion);
10877 }
10878
10879 $DBversion = "3.21.00.023";
10880 if ( CheckVersion($DBversion) ) {
10881
10882     sanitize_zero_date('borrowers', 'debarred');
10883     sanitize_zero_date('borrowers', 'dateexpiry');
10884     sanitize_zero_date('borrowers', 'dateofbirth');
10885     sanitize_zero_date('borrowers', 'dateenrolled');
10886
10887     print "Upgrade to $DBversion done (Bug 14717: Prevent 0000-00-00 dates in patron data)\n";
10888     SetVersion($DBversion);
10889 }
10890
10891 $DBversion = "3.21.00.024";
10892 if ( CheckVersion($DBversion) ) {
10893     $dbh->do(q{
10894         ALTER TABLE marc_modification_template_actions
10895         MODIFY COLUMN action
10896             ENUM('delete_field','update_field','move_field','copy_field','copy_and_replace_field')
10897             NOT NULL
10898     });
10899     print "Upgrade to $DBversion done (Bug 14098: Regression in Marc Modification Templates)\n";
10900     SetVersion($DBversion);
10901 }
10902
10903 $DBversion = "3.21.00.025";
10904 if ( CheckVersion($DBversion) ) {
10905     $dbh->do(q{
10906         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10907         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')
10908     });
10909     $dbh->do(q{
10910         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10911         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')
10912     });
10913     print "Upgrade to $DBversion done (Bug 12357: Enhancements to RIS and BibTeX exporting)\n";
10914     SetVersion($DBversion);
10915 }
10916
10917 $DBversion = "3.21.00.026";
10918 if ( CheckVersion($DBversion) ) {
10919     $dbh->do(q{
10920         UPDATE matchpoints
10921         SET search_index='issn'
10922         WHERE matcher_id IN (SELECT matcher_id FROM marc_matchers WHERE code = 'ISSN')
10923     });
10924     print "Upgrade to $DBversion done (Bug 14472: Wrong ISSN search index in record matching rules)\n";
10925     SetVersion($DBversion);
10926 }
10927
10928 $DBversion = "3.21.00.027";
10929 if ( CheckVersion($DBversion) ) {
10930     $dbh->do(q|
10931         INSERT IGNORE INTO permissions (module_bit, code, description)
10932         VALUES (1, 'self_checkout', 'Perform self checkout at the OPAC. It should be used for the patron matching the AutoSelfCheckID')
10933     |);
10934
10935     my $AutoSelfCheckID = C4::Context->preference('AutoSelfCheckID');
10936
10937     $dbh->do(q|
10938         UPDATE borrowers
10939         SET flags=0
10940         WHERE userid=?
10941     |, undef, $AutoSelfCheckID);
10942
10943     $dbh->do(q|
10944         DELETE FROM user_permissions
10945         WHERE borrowernumber=(SELECT borrowernumber FROM borrowers WHERE userid=?)
10946     |, undef, $AutoSelfCheckID);
10947
10948     $dbh->do(q|
10949         INSERT INTO user_permissions(borrowernumber, module_bit, code)
10950         SELECT borrowernumber, 1, 'self_checkout' FROM borrowers WHERE userid=?
10951     |, undef, $AutoSelfCheckID);
10952     print "Upgrade to $DBversion done (Bug 14298: AutoSelfCheckID user should only be able to access SCO)\n";
10953     SetVersion($DBversion);
10954 }
10955
10956 $DBversion = "3.21.00.028";
10957 if ( CheckVersion($DBversion) ) {
10958     unless ( column_exists('uploaded_files', 'public') ) {
10959         $dbh->do(q{
10960             ALTER TABLE uploaded_files
10961                 ADD COLUMN public tinyint,
10962                 ADD COLUMN permanent tinyint
10963         });
10964         $dbh->do(q{
10965             UPDATE uploaded_files SET public=1, permanent=1
10966         });
10967         $dbh->do(q{
10968             ALTER TABLE uploaded_files
10969                 CHANGE COLUMN categorycode uploadcategorycode tinytext
10970         });
10971     }
10972     print "Upgrade to $DBversion done (Bug 14321: Merge UploadedFile and UploadedFiles into Koha::Upload)\n";
10973     SetVersion($DBversion);
10974 }
10975
10976 $DBversion = "3.21.00.029";
10977 if ( CheckVersion($DBversion) ) {
10978     unless ( column_exists('discharges', 'discharge_id') ) {
10979         $dbh->do(q{
10980             ALTER TABLE discharges
10981                 ADD COLUMN discharge_id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10982         });
10983     }
10984     print "Upgrade to $DBversion done (Bug 14368: Add discharges history)\n";
10985     SetVersion($DBversion);
10986 }
10987
10988 $DBversion = "3.21.00.030";
10989 if ( CheckVersion($DBversion) ) {
10990     $dbh->do(q{
10991         UPDATE marc_subfield_structure
10992         SET value_builder='marc21_leader.pl'
10993         WHERE value_builder='marc21_leader_book.pl'
10994     });
10995     $dbh->do(q{
10996         UPDATE marc_subfield_structure
10997         SET value_builder='marc21_leader.pl'
10998         WHERE value_builder='marc21_leader_computerfile.pl'
10999     });
11000     $dbh->do(q{
11001         UPDATE marc_subfield_structure
11002         SET value_builder='marc21_leader.pl'
11003         WHERE value_builder='marc21_leader_video.pl'
11004     });
11005     print "Upgrade to $DBversion done (Bug 14201: Remove unused code or template from some MARC21 leader plugins )\n";
11006     SetVersion($DBversion);
11007 }
11008
11009 $DBversion = "3.21.00.031";
11010 if ( CheckVersion($DBversion) ) {
11011     $dbh->do(q{
11012         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
11013         VALUES
11014             ('SMSSendPassword', '', '', 'Password used to send SMS messages', 'free'),
11015             ('SMSSendUsername', '', '', 'Username/Login used to send SMS messages', 'free')
11016     });
11017     print "Upgrade to $DBversion done (Bug 14820: SMSSendUsername and SMSSendPassword are not listed in the system preferences)\n";
11018     SetVersion($DBversion);
11019 }
11020
11021 $DBversion = "3.21.00.032";
11022 if ( CheckVersion($DBversion) ) {
11023     $dbh->do(q{
11024         CREATE TABLE additional_fields (
11025             id int(11) NOT NULL AUTO_INCREMENT,
11026             tablename varchar(255) NOT NULL DEFAULT '',
11027             name varchar(255) NOT NULL DEFAULT '',
11028             authorised_value_category varchar(16) NOT NULL DEFAULT '',
11029             marcfield varchar(16) NOT NULL DEFAULT '',
11030             searchable tinyint(1) NOT NULL DEFAULT '0',
11031             PRIMARY KEY (id),
11032             UNIQUE KEY fields_uniq (tablename,name)
11033         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
11034     });
11035     $dbh->do(q{
11036         CREATE TABLE additional_field_values (
11037             id int(11) NOT NULL AUTO_INCREMENT,
11038             field_id int(11) NOT NULL,
11039             record_id int(11) NOT NULL,
11040             value varchar(255) NOT NULL DEFAULT '',
11041             PRIMARY KEY (id),
11042             UNIQUE KEY field_record (field_id,record_id),
11043             CONSTRAINT afv_fk FOREIGN KEY (field_id) REFERENCES additional_fields (id) ON DELETE CASCADE ON UPDATE CASCADE
11044         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
11045     });
11046     print "Upgrade to $DBversion done (Bug 10855: Additional fields for subscriptions)\n";
11047     SetVersion($DBversion);
11048 }
11049
11050 $DBversion = "3.21.00.033";
11051 if ( CheckVersion($DBversion) ) {
11052
11053     my $done = 0;
11054     my $count_ethnicity = $dbh->selectrow_arrayref(q|
11055         SELECT COUNT(*) FROM ethnicity
11056     |);
11057     my $count_borrower_modifications = $dbh->selectrow_arrayref(q|
11058         SELECT COUNT(*)
11059         FROM borrower_modifications
11060         WHERE ethnicity IS NOT NULL
11061             OR ethnotes IS NOT NULL
11062     |);
11063     my $count_borrowers = $dbh->selectrow_arrayref(q|
11064         SELECT COUNT(*)
11065         FROM borrowers
11066         WHERE ethnicity IS NOT NULL
11067             OR ethnotes IS NOT NULL
11068     |);
11069     # We don't care about the ethnicity of the deleted borrowers, right?
11070     if ( $count_ethnicity->[0] == 0
11071             and $count_borrower_modifications->[0] == 0
11072             and $count_borrowers->[0] == 0
11073     ) {
11074         $dbh->do(q|
11075             DROP TABLE ethnicity
11076         |);
11077         $dbh->do(q|
11078             ALTER TABLE borrower_modifications
11079             DROP COLUMN ethnicity,
11080             DROP COLUMN ethnotes
11081         |);
11082         $dbh->do(q|
11083             ALTER TABLE borrowers
11084             DROP COLUMN ethnicity,
11085             DROP COLUMN ethnotes
11086         |);
11087         $dbh->do(q|
11088             ALTER TABLE deletedborrowers
11089             DROP COLUMN ethnicity,
11090             DROP COLUMN ethnotes
11091         |);
11092         $done = 1;
11093     }
11094     if ( $done ) {
11095         print "Upgrade to $DBversion done (Bug 10020: Drop table ethnicity and columns ethnicity and ethnotes)\n";
11096     }
11097     else {
11098         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";
11099     }
11100
11101     SetVersion ($DBversion);
11102 }
11103
11104 $DBversion = "3.21.00.034";
11105 if ( CheckVersion($DBversion) ) {
11106     $dbh->do(q{
11107         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11108         VALUES('MembershipExpiryDaysNotice',NULL,'Send an account expiration notice that a patron''s card is about to expire after',NULL,'Integer')
11109     });
11110     $dbh->do(q{
11111         INSERT IGNORE INTO letter (module, code, branchcode, name, title, content, message_transport_type)
11112         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')
11113     });
11114     print "Upgrade to $DBversion done (Bug 6810: Send membership expiry reminder notices)\n";
11115     SetVersion($DBversion);
11116 }
11117
11118 $DBversion = "3.21.00.035";
11119 if ( CheckVersion($DBversion) ) {
11120     $dbh->do(q|
11121         ALTER TABLE branch_borrower_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11122     |);
11123     $dbh->do(q|
11124         UPDATE branch_borrower_circ_rules SET maxonsiteissueqty = maxissueqty;
11125     |);
11126     $dbh->do(q|
11127         ALTER TABLE default_borrower_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11128     |);
11129     $dbh->do(q|
11130         UPDATE default_borrower_circ_rules SET maxonsiteissueqty = maxissueqty;
11131     |);
11132     $dbh->do(q|
11133         ALTER TABLE default_branch_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11134     |);
11135     $dbh->do(q|
11136         UPDATE default_branch_circ_rules SET maxonsiteissueqty = maxissueqty;
11137     |);
11138     $dbh->do(q|
11139         ALTER TABLE default_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11140     |);
11141     $dbh->do(q|
11142         UPDATE default_circ_rules SET maxonsiteissueqty = maxissueqty;
11143     |);
11144     $dbh->do(q|
11145         ALTER TABLE issuingrules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11146     |);
11147     $dbh->do(q|
11148         UPDATE issuingrules SET maxonsiteissueqty = maxissueqty;
11149     |);
11150     $dbh->do(q|
11151         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11152         VALUES ('ConsiderOnSiteCheckoutsAsNormalCheckouts','1',NULL,'Consider on-site checkouts as normal checkouts','YesNo');
11153     |);
11154
11155     print "Upgrade to $DBversion done (Bug 14045: Add DB fields maxonsiteissueqty and pref ConsiderOnSiteCheckoutsAsNormalCheckouts)\n";
11156     SetVersion ($DBversion);
11157 }
11158
11159 $DBversion = "3.21.00.036";
11160 if ( CheckVersion($DBversion) ) {
11161    $dbh->do(q{
11162         ALTER TABLE authorised_values_branches
11163         DROP FOREIGN KEY authorised_values_branches_ibfk_1,
11164         DROP FOREIGN KEY authorised_values_branches_ibfk_2
11165     });
11166     $dbh->do(q{
11167         ALTER TABLE authorised_values_branches
11168         MODIFY av_id INT( 11 ) NOT NULL,
11169         MODIFY branchcode VARCHAR( 10 ) NOT NULL,
11170         ADD FOREIGN KEY (`av_id`) REFERENCES `authorised_values` (`id`) ON DELETE CASCADE,
11171         ADD FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE
11172    });
11173    print "Upgrade to $DBversion done (Bug 10363: There is no package for authorised values)\n";
11174    SetVersion($DBversion);
11175 }
11176
11177 $DBversion = "3.21.00.037";
11178 if ( CheckVersion($DBversion) ) {
11179    $dbh->do(q{
11180        INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11181        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')
11182    });
11183    $dbh->do(q{
11184        INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11185        VALUES ('RestrictionBlockRenewing','0','If patron is restricted, should renewal be allowed or blocked',NULL,'YesNo')
11186     });
11187    print "Upgrade to $DBversion done (Bug 8236: Prevent renewing if overdue or restriction)\n";
11188    SetVersion($DBversion);
11189 }
11190
11191 $DBversion = "3.21.00.038";
11192 if ( CheckVersion($DBversion) ) {
11193     $dbh->do(q|
11194         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11195         VALUES ('BatchCheckouts','0','','Enable or disable batch checkouts','YesNo')
11196     |);
11197     $dbh->do(q|
11198         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11199         VALUES ('BatchCheckoutsValidCategories','',NULL,'Patron categories allowed to checkout in a batch','Free')
11200     |);
11201     print "Upgrade to $DBversion done (Bug 11759: Add the batch checkout feature)\n";
11202     SetVersion($DBversion);
11203 }
11204
11205 $DBversion = "3.21.00.039";
11206 if ( CheckVersion($DBversion) ) {
11207     $dbh->do(q|
11208         ALTER TABLE creator_layouts ADD COLUMN oblique_title INT(1) NULL DEFAULT 1 AFTER guidebox
11209     |);
11210     print "Upgrade to $DBversion done (Bug 12194: Add column oblique_title to layouts)\n";
11211     SetVersion($DBversion);
11212 }
11213
11214 $DBversion = "3.21.00.040";
11215 if ( CheckVersion($DBversion) ) {
11216     $dbh->do(q{
11217         ALTER TABLE itemtypes
11218             ADD hideinopac TINYINT(1) NOT NULL DEFAULT 0
11219               AFTER sip_media_type,
11220             ADD searchcategory VARCHAR(80) DEFAULT NULL
11221               AFTER hideinopac;
11222     });
11223     print "Upgrade to $DBversion done (Bug 10937: Option to hide and group itemtypes from advanced search)\n";
11224     SetVersion($DBversion);
11225 }
11226
11227 $DBversion = "3.21.00.041";
11228 if ( CheckVersion($DBversion) ) {
11229     $dbh->do(q|
11230         ALTER TABLE issuingrules
11231             ADD chargeperiod_charge_at BOOLEAN NOT NULL DEFAULT  '0' AFTER chargeperiod
11232     |);
11233     print "Upgrade to $DBversion done (Bug 13590: Add ability to charge fines at start of charge period)\n";
11234     SetVersion($DBversion);
11235 }
11236
11237 $DBversion = "3.21.00.042";
11238 if ( CheckVersion($DBversion) ) {
11239     $dbh->do(q|
11240         ALTER TABLE items_search_fields
11241             MODIFY COLUMN authorised_values_category VARCHAR(32) DEFAULT NULL
11242     |);
11243     print "Upgrade to $DBversion done (Bug 15069: items_search_fields.authorised_values_category is still a varchar(32))\n";
11244     SetVersion($DBversion);
11245 }
11246
11247 $DBversion = "3.21.00.043";
11248 if ( CheckVersion($DBversion) ) {
11249     $dbh->do(q|
11250         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11251         VALUES ('EnableAdvancedCatalogingEditor','0','','Enable the Rancor advanced cataloging editor','YesNo')
11252     |);
11253     print "Upgrade to $DBversion done (Bug 11559: Professional cataloger's interface)\n";
11254     SetVersion($DBversion);
11255 }
11256
11257 $DBversion = "3.21.00.044";
11258 if ( CheckVersion($DBversion) ) {
11259     $dbh->do(q|
11260         CREATE TABLE localization (
11261             localization_id int(11) NOT NULL AUTO_INCREMENT,
11262             entity varchar(16) COLLATE utf8_unicode_ci NOT NULL,
11263             code varchar(64) COLLATE utf8_unicode_ci NOT NULL,
11264             lang varchar(25) COLLATE utf8_unicode_ci NOT NULL,
11265             translation text COLLATE utf8_unicode_ci,
11266             PRIMARY KEY (localization_id),
11267             UNIQUE KEY entity_code_lang (entity,code,lang)
11268         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
11269     |);
11270     print "Upgrade to $DBversion done (Bug 14100: Generic solution for language overlay)\n";
11271     SetVersion($DBversion);
11272 }
11273
11274 $DBversion = "3.21.00.045";
11275 if ( CheckVersion($DBversion) ) {
11276     $dbh->do(q|
11277         ALTER TABLE opac_news
11278             ADD borrowernumber int(11) default NULL
11279                 AFTER number
11280     |);
11281     $dbh->do(q|
11282         ALTER TABLE opac_news
11283             ADD CONSTRAINT borrowernumber_fk
11284                 FOREIGN KEY (borrowernumber)
11285                 REFERENCES borrowers (borrowernumber)
11286                 ON DELETE SET NULL ON UPDATE CASCADE
11287     |);
11288     print "Upgrade to $DBversion done (Bug 14246: (newsauthor) Add borrowernumber to koha_news)\n";
11289     SetVersion($DBversion);
11290 }
11291
11292 $DBversion = "3.21.00.046";
11293 if ( CheckVersion($DBversion) ) {
11294     $dbh->do(q{
11295         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11296         VALUES ('NewsAuthorDisplay','none','none|opac|staff|both','Display the author name for news items.','Choice')
11297     });
11298     print "Upgrade to $DBversion done (Bug 14247: (newsauthor) System preference for news author display)\n";
11299     SetVersion($DBversion);
11300 }
11301
11302 $DBversion = "3.21.00.047";
11303 if(CheckVersion($DBversion)) {
11304     $dbh->do(q{
11305         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11306         VALUES ('IndependentBranchesPatronModifications','0','Show only modification request for the logged in branch','','YesNo')
11307     });
11308     print "Upgrade to $DBversion done (Bug 10904: Limit patron update request management by branch)\n";
11309     SetVersion($DBversion);
11310 }
11311
11312 $DBversion = '3.21.00.048';
11313 if ( CheckVersion($DBversion) ) {
11314     my $create_table_issues = @{ $dbh->selectall_arrayref(q|SHOW CREATE TABLE issues|) }[0]->[1];
11315     if ($create_table_issues !~ m|UNIQUE KEY.*itemnumber| ) {
11316         $dbh->do(q|ALTER TABLE issues ADD CONSTRAINT UNIQUE KEY (itemnumber)|);
11317     }
11318     print "Upgrade to $DBversion done (Bug 14978: Make sure issues.itemnumber is a unique key)\n";
11319     SetVersion($DBversion);
11320 }
11321
11322 $DBversion = "3.21.00.049";
11323 if ( CheckVersion($DBversion) ) {
11324     $dbh->do(q{UPDATE systempreferences SET variable = 'AudioAlerts' WHERE variable = 'soundon'});
11325
11326     $dbh->do(q{
11327         CREATE TABLE audio_alerts (
11328             id int(11) NOT NULL AUTO_INCREMENT,
11329             precedence smallint(5) unsigned NOT NULL,
11330             selector varchar(255) NOT NULL,
11331             sound varchar(255) NOT NULL,
11332             PRIMARY KEY (id),
11333             KEY precedence (precedence)
11334         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
11335     });
11336
11337     $dbh->do(q{
11338         INSERT IGNORE INTO audio_alerts VALUES
11339         (1, 1, '.audio-alert-action', 'opening.ogg'),
11340         (2, 2, '.audio-alert-warning', 'critical.ogg'),
11341         (3, 3, '.audio-alert-success', 'beep.ogg');
11342     });
11343
11344     print "Upgrade to $DBversion done (Bug 11431: Add additional sound options for warnings)\n";
11345     SetVersion($DBversion);
11346 }
11347
11348 $DBversion = "3.21.00.050";
11349 if(CheckVersion($DBversion)) {
11350     $dbh->do(q{
11351         INSERT INTO letter ( module, code, branchcode, name, is_html, title, content, message_transport_type )
11352         VALUES ( 'circulation', 'OVERDUES_SLIP', '', 'Overdues Slip', '0', 'OVERDUES_SLIP', 'The following item(s) is/are currently overdue:
11353
11354 <item>"<<biblio.title>>" by <<biblio.author>>, <<items.itemcallnumber>>, Barcode: <<items.barcode>> Fine: <<items.fine>></item>
11355 ', 'print' )
11356     });
11357     print "Upgrade to $DBversion done (Bug 12933: Add ability to print overdue slip from staff intranet)\n";
11358     SetVersion($DBversion);
11359 }
11360
11361 $DBversion = "3.21.00.051";
11362 if ( CheckVersion($DBversion) ) {
11363     $dbh->do(q{
11364         ALTER TABLE virtualshelves
11365             CHANGE COLUMN sortfield sortfield VARCHAR(16) DEFAULT 'title'
11366     });
11367     $dbh->do(q{
11368         UPDATE virtualshelves
11369         SET sortfield='title'
11370             WHERE sortfield IS NULL;
11371     });
11372     print "Upgrade to $DBversion done (Bug 14544: Move the list related code to Koha::Virtualshelves)\n";
11373     SetVersion($DBversion);
11374 }
11375
11376 $DBversion = "3.21.00.052";
11377 if ( CheckVersion($DBversion) ) {
11378     $dbh->do(q{
11379         ALTER TABLE serial
11380             ADD COLUMN publisheddatetext VARCHAR(100) DEFAULT NULL AFTER publisheddate
11381     });
11382     print "Upgrade to $DBversion done (Bug 8296: Add descriptive (text) published date field for serials)\n";
11383     SetVersion($DBversion);
11384 }
11385
11386 $DBversion = "3.21.00.053";
11387 if ( CheckVersion($DBversion) ) {
11388     my $query = q{ SELECT * FROM itemtypes ORDER BY description };
11389     my $sth   = C4::Context->dbh->prepare($query);
11390     $sth->execute;
11391     my $suggestion_formats = $sth->fetchall_arrayref( {} );
11392
11393     foreach my $format (@$suggestion_formats) {
11394         $dbh->do(
11395             q|
11396             INSERT IGNORE INTO authorised_values (category, authorised_value, lib, lib_opac, imageurl)
11397             VALUES (?, ?, ?, ?, ?)
11398         |, {},
11399             'SUGGEST_FORMAT', $format->{itemtype}, $format->{description}, $format->{description},
11400             $format->{imageurl}
11401         );
11402     }
11403     print "Upgrade to $DBversion done (Bug 9468: create new SUGGEST_FORMAT authorised_value list)\n";
11404     SetVersion($DBversion);
11405 }
11406
11407 $DBversion = "3.21.00.054";
11408 if(CheckVersion($DBversion)) {
11409     $dbh->do(q{
11410         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11411         VALUES('MergeReportFields','','Displayed fields for deleted MARC records after merge',NULL,'Free')
11412     });
11413     print "Upgrade to $DBversion done (Bug 8064: Merge several biblio records)\n";
11414     SetVersion($DBversion);
11415 }
11416
11417 $DBversion = "3.21.00.055";
11418 if ( CheckVersion($DBversion) ) {
11419     print "Upgrade to $DBversion done (Koha 3.22 beta)\n";
11420     SetVersion($DBversion);
11421 }
11422
11423 $DBversion = "3.21.00.056";
11424 if(CheckVersion($DBversion)) {
11425     $dbh->do(q{
11426         UPDATE systempreferences
11427         SET
11428             options='metric|us|iso|dmydot',
11429             explanation='Define global date format (us mm/dd/yyyy, metric dd/mm/yyy, ISO yyyy-mm-dd, DMY separated by dots dd.mm.yyyy)'
11430         WHERE variable='dateformat'
11431     });
11432     print "Upgrade to $DBversion done (Bug 12072: New dateformat dd.mm.yyyy)\n";
11433     SetVersion($DBversion);
11434 }
11435
11436 $DBversion = "3.22.00.000";
11437 if ( CheckVersion($DBversion) ) {
11438     print "Upgrade to $DBversion done (Koha 3.22)\n";
11439     SetVersion($DBversion);
11440 }
11441
11442 $DBversion = "3.23.00.000";
11443 if ( CheckVersion($DBversion) ) {
11444     print "Upgrade to $DBversion done (The year of the monkey will be here soon.)\n";
11445     SetVersion ($DBversion);
11446 }
11447
11448 $DBversion = "3.23.00.001";
11449 if(CheckVersion($DBversion)) {
11450     $dbh->do(q{
11451         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11452         VALUES (
11453             'DefaultToLoggedInLibraryCircRules',  '0', NULL ,  'If enabled, circ rules editor will default to the logged in library''s rules, rather than the ''all libraries'' rules.',  'YesNo'
11454         ), (
11455             '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'
11456         )
11457     });
11458
11459     print "Upgrade to $DBversion done (Bug 11625 - Add pref DefaultToLoggedInLibraryCircRules and DefaultToLoggedInLibraryNoticesSlips)\n";
11460     SetVersion($DBversion);
11461 }
11462
11463 $DBversion = "3.23.00.002";
11464 if(CheckVersion($DBversion)) {
11465     $dbh->do(q{
11466         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11467         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')
11468     });
11469
11470     print "Upgrade to $DBversion done (Bug 11747 - add pref DefaultToLoggedInLibraryOverdueTriggers)\n";
11471     SetVersion($DBversion);
11472 }
11473
11474 $DBversion = "3.23.00.003";
11475 if(CheckVersion($DBversion)) {
11476     $dbh->do(q{
11477         UPDATE letter SET name = "Hold Slip" WHERE name = "Reserve Slip"
11478     });
11479     $dbh->do(q{
11480         UPDATE letter SET title = "Hold Slip" WHERE title = "Reserve Slip";
11481     });
11482
11483     print "Upgrade to $DBversion done (Bug 8085 - Rename 'Reserve slip' to 'Hold slip')\n";
11484     SetVersion($DBversion);
11485 }
11486
11487 $DBversion = "3.23.00.004";
11488 if ( CheckVersion($DBversion) ) {
11489     $dbh->do(q{
11490         DROP TABLE IF EXISTS `stopwords`;
11491     });
11492     print "Upgrade to $DBversion done (Bug 9819 - stopwords related code should be removed)\n";
11493     SetVersion($DBversion);
11494 }
11495
11496 $DBversion = "3.23.00.005";
11497 if ( CheckVersion($DBversion) ) {
11498     $dbh->do(q{
11499         UPDATE permissions SET description = 'Manage circulation rules' WHERE description = 'manage circulation rules'
11500     });
11501     $dbh->do(q{
11502         UPDATE permissions SET description = 'Manage staged MARC records, including completing and reversing imports' WHERE description = 'Managed staged MARC records, including completing and reversing imports'
11503     });
11504     print "Upgrade to $DBversion done (Bug 11569 - Typo in userpermissions.sql)\n";
11505     SetVersion($DBversion);
11506 }
11507 $DBversion = "3.23.00.006";
11508 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
11509    $dbh->do("
11510        ALTER TABLE serial
11511         ADD serialseq_x VARCHAR( 100 ) NULL DEFAULT NULL AFTER serialseq,
11512         ADD serialseq_y VARCHAR( 100 ) NULL DEFAULT NULL AFTER serialseq_x,
11513         ADD serialseq_z VARCHAR( 100 ) NULL DEFAULT NULL AFTER serialseq_y
11514    ");
11515
11516     my $sth = $dbh->prepare("SELECT * FROM subscription");
11517     $sth->execute();
11518
11519     my $sth2 = $dbh->prepare("SELECT * FROM subscription_numberpatterns WHERE id = ?");
11520
11521     my $sth3 = $dbh->prepare("UPDATE serial SET serialseq_x = ?, serialseq_y = ?, serialseq_z = ? WHERE serialid = ?");
11522
11523     foreach my $subscription ( $sth->fetchrow_hashref() ) {
11524         next if !defined($subscription);
11525         $sth2->execute( $subscription->{numberpattern} );
11526         my $number_pattern = $sth2->fetchrow_hashref();
11527
11528         my $numbering_method = $number_pattern->{numberingmethod};
11529         # Get all the data between the enumeration values, we need
11530         # to split each enumeration string based on these values.
11531         my @splits = split( /\{[XYZ]\}/, $numbering_method );
11532         # Get the order in which the X Y and Z values are used
11533         my %indexes;
11534         foreach my $i (qw(X Y Z)) {
11535             $indexes{$i} = index( $numbering_method, "{$i}" );
11536             delete $indexes{$i} if $indexes{$i} == -1;
11537         }
11538         my @indexes = sort { $indexes{$a} <=> $indexes{$b} } keys(%indexes);
11539
11540         my @serials = @{
11541             $dbh->selectall_arrayref(
11542                 "SELECT * FROM serial WHERE subscriptionid = $subscription->{subscriptionid}",
11543                 { Slice => {} }
11544             )
11545         };
11546
11547         foreach my $serial (@serials) {
11548             my $serialseq = $serial->{serialseq};
11549             my %enumeration_data;
11550
11551             ## We cannot split on multiple values at once,
11552             ## so let's replace each of those values with __SPLIT__
11553             if (@splits) {
11554                 for my $split_item (@splits) {
11555                     my $quoted_split = quotemeta($split_item);
11556                     $serialseq =~ s/$quoted_split/__SPLIT__/;
11557                 }
11558                 (
11559                     undef,
11560                     $enumeration_data{ $indexes[0] // q{} },
11561                     $enumeration_data{ $indexes[1] // q{} },
11562                     $enumeration_data{ $indexes[2] // q{} }
11563                 ) = split( /__SPLIT__/, $serialseq );
11564             }
11565             else
11566             {    ## Nothing to split on means the only thing in serialseq is a single placeholder e.g. {X}
11567                 $enumeration_data{ $indexes[0] } = $serialseq;
11568             }
11569
11570             $sth3->execute(
11571                     $enumeration_data{'X'},
11572                     $enumeration_data{'Y'},
11573                     $enumeration_data{'Z'},
11574                     $serial->{serialid},
11575             );
11576         }
11577     }
11578
11579     print "Upgrade to $DBversion done ( Bug 8956 - Split serials enumeration data into separate fields )\n";
11580     SetVersion($DBversion);
11581 }
11582
11583 $DBversion = "3.23.00.007";
11584 if ( CheckVersion($DBversion) ) {
11585     $dbh->do("SET FOREIGN_KEY_CHECKS=0");
11586     $dbh->do("ALTER TABLE overduerules RENAME old_overduerules");
11587     $dbh->do("CREATE TABLE overduerules (
11588         `overduerules_id` int(11) NOT NULL AUTO_INCREMENT,
11589         `branchcode` varchar(10) NOT NULL DEFAULT '',
11590         `categorycode` varchar(10) NOT NULL DEFAULT '',
11591         `delay1` int(4) DEFAULT NULL,
11592         `letter1` varchar(20) DEFAULT NULL,
11593         `debarred1` varchar(1) DEFAULT '0',
11594         `delay2` int(4) DEFAULT NULL,
11595         `debarred2` varchar(1) DEFAULT '0',
11596         `letter2` varchar(20) DEFAULT NULL,
11597         `delay3` int(4) DEFAULT NULL,
11598         `letter3` varchar(20) DEFAULT NULL,
11599         `debarred3` int(1) DEFAULT '0',
11600         PRIMARY KEY (`overduerules_id`),
11601         UNIQUE KEY `overduerules_branch_cat` (`branchcode`,`categorycode`)
11602         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
11603     $dbh->do("INSERT INTO overduerules(branchcode, categorycode, delay1, letter1, debarred1, delay2, debarred2, letter2, delay3, letter3, debarred3) SELECT * FROM old_overduerules");
11604     $dbh->do("DROP TABLE old_overduerules");
11605     $dbh->do("ALTER TABLE overduerules_transport_types
11606               ADD COLUMN overduerules_id int(11) NOT NULL");
11607     my $mtts = $dbh->selectall_arrayref("SELECT * FROM overduerules_transport_types", { Slice => {} });
11608     $dbh->do("DELETE FROM overduerules_transport_types");
11609     $dbh->do("ALTER TABLE overduerules_transport_types
11610               DROP FOREIGN KEY overduerules_fk,
11611               ADD FOREIGN KEY overduerules_transport_types_fk (overduerules_id) REFERENCES overduerules (overduerules_id) ON DELETE CASCADE ON UPDATE CASCADE,
11612               DROP COLUMN branchcode,
11613               DROP COLUMN categorycode");
11614     my $s = $dbh->prepare("INSERT INTO overduerules_transport_types (overduerules_id, id, letternumber, message_transport_type) "
11615                          ." VALUES((SELECT overduerules_id FROM overduerules WHERE branchcode = ? AND categorycode = ?),?,?,?)");
11616     foreach my $mtt(@$mtts){
11617         $s->execute($mtt->{branchcode}, $mtt->{categorycode}, $mtt->{id}, $mtt->{letternumber}, $mtt->{message_transport_type} );
11618     }
11619     $dbh->do("SET FOREIGN_KEY_CHECKS=1");
11620
11621     print "Upgrade to $DBversion done (Bug 13624 - Remove columns branchcode, categorytype from table overduerules_transport_types)\n";
11622     SetVersion($DBversion);
11623 }
11624
11625 $DBversion = "3.23.00.008";
11626 if ( CheckVersion($DBversion) ) {
11627
11628     $dbh->do(q{ALTER TABLE borrowers ADD privacy_guarantor_checkouts BOOLEAN NOT NULL DEFAULT '0' AFTER privacy});
11629
11630     $dbh->do(q{ALTER TABLE deletedborrowers ADD privacy_guarantor_checkouts BOOLEAN NOT NULL DEFAULT '0' AFTER privacy});
11631
11632     $dbh->do(q{
11633         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type )
11634         VALUES (
11635             'AllowStaffToSetCheckoutsVisibilityForGuarantor',  '0', NULL,
11636             'If enabled, library staff can set a patron''s checkouts to be visible to linked patrons from the opac.',  'YesNo'
11637         ), (
11638             'AllowPatronToSetCheckoutsVisibilityForGuarantor',  '0', NULL,
11639             'If enabled, the patron can set checkouts to be visible to  his or her guarantor',  'YesNo'
11640         )
11641     });
11642
11643     print "Upgrade to $DBversion done (Bug 9303 - relative's checkouts in the opac)\n";
11644     SetVersion($DBversion);
11645 }
11646
11647 $DBversion = "3.23.00.009";
11648 if ( CheckVersion($DBversion) ) {
11649     $dbh->do(q{
11650         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type ) VALUES
11651         ( 'EnablePayPalOpacPayments',  '0', NULL ,  'Enables the ability to pay fees and fines from  the OPAC via PayPal',  'YesNo' ),
11652         ( 'PayPalChargeDescription',  'Koha fee payment', NULL ,  'This preference defines what the user will see the charge listed as in PayPal',  'Free' ),
11653         ( 'PayPalPwd',  '', NULL ,  'Your PayPal API password',  'Free' ),
11654         ( 'PayPalSandboxMode',  '1', NULL ,  'If enabled, the system will use PayPal''s sandbox server for testing, rather than the production server.',  'YesNo' ),
11655         ( 'PayPalSignature',  '', NULL ,  'Your PayPal API signature',  'Free' ),
11656         ( 'PayPalUser',  '', NULL ,  'Your PayPal API username ( email address )',  'Free' )
11657     });
11658
11659     print "Upgrade to $DBversion done (Bug 11622 - Add ability to pay fees and fines from OPAC via PayPal)\n";
11660     SetVersion($DBversion);
11661 }
11662
11663 $DBversion = "3.23.00.010";
11664 if ( CheckVersion($DBversion) ) {
11665     $dbh->do(q{
11666         ALTER TABLE issuingrules ADD cap_fine_to_replacement_price BOOLEAN NOT NULL DEFAULT '0' AFTER overduefinescap
11667     });
11668
11669     print "Upgrade to $DBversion done (Bug 9129 - Add the ability to set the maximum fine for an item to its replacement price)\n";
11670     SetVersion($DBversion);
11671 }
11672
11673 $DBversion = "3.23.00.011";
11674 if ( CheckVersion($DBversion) ) {
11675     $dbh->do(q{
11676         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES ('HoldFeeMode','not_always','always|not_always','Set the hold fee mode','Choice')
11677     });
11678
11679     print "Upgrade to $DBversion done (Bug 13592 - Hold fee not being applied on placing a hold)\n";
11680     SetVersion($DBversion);
11681 }
11682
11683 $DBversion = "3.23.00.012";
11684 if ( CheckVersion($DBversion) ) {
11685     $dbh->do(q{
11686         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')
11687     });
11688
11689     print "Upgrade to $DBversion done (Bug 15380 - Move the authority types related code to Koha::Authority::Type[s] - part 1)\n";
11690     SetVersion($DBversion);
11691 }
11692
11693 $DBversion = "3.23.00.013";
11694 if ( CheckVersion($DBversion) ) {
11695     $dbh->do(q{
11696         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')
11697     });
11698     $dbh->do(q{
11699         CREATE TABLE IF NOT EXISTS `items_last_borrower` (
11700   `id` int(11) NOT NULL AUTO_INCREMENT,
11701   `itemnumber` int(11) NOT NULL,
11702   `borrowernumber` int(11) NOT NULL,
11703   `created_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
11704   PRIMARY KEY (`id`),
11705   UNIQUE KEY `itemnumber` (`itemnumber`),
11706   KEY `borrowernumber` (`borrowernumber`),
11707   CONSTRAINT `items_last_borrower_ibfk_2` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
11708   CONSTRAINT `items_last_borrower_ibfk_1` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE
11709 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
11710     });
11711
11712     print "Upgrade to $DBversion done (Bug 14945 - Add the ability to store the last patron to return an item)\n";
11713     SetVersion($DBversion);
11714
11715 }
11716
11717 $DBversion = "3.23.00.014";
11718 if ( CheckVersion($DBversion) ) {
11719     $dbh->do(q{
11720         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
11721 VALUES ('ClaimsBccCopy','0','','Bcc the ClaimAcquisition and ClaimIssues alerts','YesNo')
11722     });
11723
11724     print "Upgrade to $DBversion done (Bug 10076 - Add Bcc syspref for claimacquisition and clamissues)\n";
11725     SetVersion($DBversion);
11726 }
11727
11728 $DBversion = "3.23.00.015";
11729 if ( CheckVersion($DBversion) ) {
11730     $dbh->do(q{
11731         UPDATE letter SET code = "HOLD_SLIP" WHERE code = "RESERVESLIP";
11732     });
11733
11734     print "Upgrade to $DBversion done (Bug 15443 - Re-code RESERVESLIP as HOLD_SLIP)\n";
11735     SetVersion($DBversion);
11736 }
11737
11738 $DBversion = "3.23.00.016";
11739 if ( CheckVersion($DBversion) ) {
11740     $dbh->do(q{
11741     INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
11742     VALUES ('OpacResetPassword',  '0','','Shows the ''Forgot your password?'' link in the OPAC','YesNo');
11743 });
11744     $dbh->do(q{
11745     CREATE TABLE IF NOT EXISTS borrower_password_recovery (
11746       borrowernumber int(11) NOT NULL,
11747       uuid varchar(128) NOT NULL,
11748       valid_until timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
11749       PRIMARY KEY (borrowernumber),
11750       KEY borrowernumber (borrowernumber)
11751     ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
11752 });
11753     $dbh->do(q{
11754     INSERT IGNORE INTO `letter` (module, code, branchcode, name, is_html, title, content, message_transport_type)
11755     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');
11756
11757     });
11758
11759     print "Upgrade to $DBversion done (Bug 8753 - Add forgot password link to OPAC)\n";
11760     SetVersion($DBversion);
11761 }
11762
11763 $DBversion = "3.23.00.017";
11764 if ( CheckVersion($DBversion) ) {
11765
11766 $dbh->do(q{
11767     DELETE FROM uploaded_files
11768     WHERE COALESCE(permanent,0)=0 AND dir='koha_upload'
11769 });
11770
11771 my $tmp = C4::Context->temporary_directory . '/koha_upload';
11772 remove_tree( $tmp ) if -d $tmp;
11773
11774     print "Upgrade to $DBversion done (Bug 14893 - Separate temporary storage per instance in Upload.pm)\n";
11775     SetVersion($DBversion);
11776
11777 }
11778
11779 $DBversion = "3.23.00.018";
11780 if ( CheckVersion($DBversion) ) {
11781     $dbh->do(q{
11782         UPDATE systempreferences SET value="0" where type="YesNo" and value="";
11783     });
11784
11785     print "Upgrade to $DBversion done (Bug 15446 - Fix systempreferences rows where type=YesNo and value='')\n";
11786     SetVersion($DBversion);
11787 }
11788
11789 $DBversion = "3.23.00.019";
11790 if ( CheckVersion($DBversion) ) {
11791     $dbh->do(q{
11792         UPDATE `authorised_values` SET `lib`='Non-fiction' WHERE `lib`='Non Fiction';
11793     });
11794
11795     print "Upgrade to $DBversion done (Bug 15411 - Change Non Fiction to Non-fiction in authorised_values)\n";
11796     SetVersion($DBversion);
11797 }
11798
11799 $DBversion = "3.23.00.020";
11800 if ( CheckVersion($DBversion) ) {
11801     $dbh->do(q{
11802         CREATE TABLE  sms_providers (
11803            id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
11804            name VARCHAR( 255 ) NOT NULL ,
11805            domain VARCHAR( 255 ) NOT NULL ,
11806            UNIQUE (
11807                name
11808            )
11809         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
11810     });
11811
11812     $dbh->do(q{
11813         ALTER TABLE borrowers ADD sms_provider_id INT( 11 ) NULL DEFAULT NULL AFTER smsalertnumber;
11814     });
11815     $dbh->do(q{
11816         ALTER TABLE borrowers ADD FOREIGN KEY ( sms_provider_id ) REFERENCES sms_providers ( id ) ON UPDATE CASCADE ON DELETE SET NULL;
11817     });
11818     $dbh->do(q{
11819         ALTER TABLE deletedborrowers ADD sms_provider_id INT( 11 ) NULL DEFAULT NULL AFTER smsalertnumber;
11820     });
11821
11822     print "Upgrade to $DBversion done (Bug 9021 - Add SMS via email as an alternative to SMS services via SMS::Send drivers)\n";
11823     SetVersion($DBversion);
11824 }
11825
11826 $DBversion = "3.23.00.021";
11827 if ( CheckVersion($DBversion) ) {
11828     $dbh->do(q{
11829         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES ('ShowAllCheckins', '0', '', 'Show all checkins', 'YesNo');
11830     });
11831
11832     print "Upgrade to $DBversion done (Bug 15736 - Add a preference to control whether all items should be shown in checked-in items list)\n";
11833     SetVersion($DBversion);
11834 }
11835
11836 $DBversion = "3.23.00.022";
11837 if ( CheckVersion($DBversion) ) {
11838     $dbh->do(q{ ALTER TABLE tags_all MODIFY COLUMN borrowernumber INT(11) });
11839     $dbh->do(q{ ALTER TABLE tags_all drop FOREIGN KEY tags_borrowers_fk_1 });
11840     $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 });
11841     $dbh->do(q{ ALTER TABLE tags_approval DROP FOREIGN KEY tags_approval_borrowers_fk_1 });
11842     $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 });
11843
11844     print "Upgrade to $DBversion done (Bug 13534 - Deleting staff patron will delete tags approved by this patron)\n";
11845     SetVersion($DBversion);
11846 }
11847
11848 $DBversion = "3.23.00.023";
11849 if ( CheckVersion($DBversion) ) {
11850     $dbh->do(q{
11851         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11852         VALUES('OpenLibrarySearch','0','If Yes Open Library search results will show in OPAC',NULL,'YesNo');
11853     });
11854
11855     print "Upgrade to $DBversion done (Bug 6624 - Allow Koha to use the new read API from OpenLibrary)\n";
11856     SetVersion($DBversion);
11857 }
11858
11859 $DBversion = "3.23.00.024";
11860 if ( CheckVersion($DBversion) ) {
11861     $dbh->do(q{
11862         ALTER TABLE deletedborrowers MODIFY COLUMN userid VARCHAR(75) DEFAULT NULL;
11863     });
11864
11865     $dbh->do(q{
11866         ALTER TABLE deletedborrowers MODIFY COLUMN password VARCHAR(60) DEFAULT NULL;
11867     });
11868
11869     print "Upgrade to $DBversion done (Bug 15517 - Tables borrowers and deletedborrowers differ again)\n";
11870     SetVersion($DBversion);
11871 }
11872
11873 $DBversion = "3.23.00.025";
11874 if ( CheckVersion($DBversion) ) {
11875     $dbh->do(q{
11876         DROP TABLE IF EXISTS nozebra;
11877     });
11878
11879     print "Upgrade to $DBversion done (Bug 15526 - Drop nozebra database table)\n";
11880     SetVersion($DBversion);
11881 }
11882
11883 $DBversion = "3.23.00.026";
11884 if ( CheckVersion($DBversion) ) {
11885     $dbh->do(q{
11886         UPDATE systempreferences SET value = CONCAT_WS('|', IF(value='', NULL, value), "password") WHERE variable="PatronSelfRegistrationBorrowerUnwantedField" AND value NOT LIKE "%password%";
11887     });
11888
11889     print "Upgrade to $DBversion done (Bug 15343 - Allow patrons to choose their own password on self registration)\n";
11890     SetVersion($DBversion);
11891 }
11892
11893 $DBversion = "3.23.00.027";
11894 if ( CheckVersion($DBversion) ) {
11895     my ( $db_value ) = $dbh->selectrow_array(q|SELECT count(*) FROM branches|);
11896     my $pref_value = C4::Context->preference("singleBranchMode") || 0;
11897     if ( $db_value > 1 and $pref_value == 1 ) {
11898         warn "WARNING: You have more than 1 libraries in your branches tables but the singleBranchMode system preference is on.\n";
11899         warn "This configuration does not make sense. The system preference is going to be deleted,\n";
11900         warn "and this parameter will be based on the number of libraries defined.\n";
11901     }
11902     $dbh->do(q|DELETE FROM systempreferences WHERE variable="singleBranchMode"|);
11903
11904     print "Upgrade to $DBversion done (Bug 4941 - Can't set branch in staff client when singleBranchMode is enabled)\n";
11905     SetVersion($DBversion);
11906 }
11907
11908 $DBversion = "3.23.00.028";
11909 if ( CheckVersion($DBversion) ) {
11910     $dbh->do(q{
11911         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';
11912     });
11913
11914     print "Upgrade to $DBversion done (Bug 14658 - Split PatronSelfRegistrationBorrowerUnwantedField into two preferences for creating and editing)\n";
11915     SetVersion($DBversion);
11916 }
11917
11918 $DBversion = "3.23.00.029";
11919 if ( CheckVersion($DBversion) ) {
11920
11921     # move marc21_field_003.pl 040c and 040d to marc21_orgcode.pl
11922     $dbh->do(q{
11923         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' );
11924     });
11925     $dbh->do(q{
11926         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' );
11927     });
11928
11929     print "Upgrade to $DBversion done (Bug 14199 - Unify all organization code plugins)\n";
11930     SetVersion($DBversion);
11931 }
11932
11933 $DBversion = "3.23.00.030";
11934 if(CheckVersion($DBversion)) {
11935     $dbh->do(q{
11936         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
11937         VALUES ('OpacMaintenanceNotice','','','A user-defined block of HTML to appear on screen when OpacMaintenace is enabled','Textarea')
11938     });
11939
11940     print "Upgrade to $DBversion done (Bug 15311: Let libraries set text to display when OpacMaintenance = on)\n";
11941     SetVersion($DBversion);
11942 }
11943
11944 $DBversion = "3.23.00.031";
11945 if(CheckVersion($DBversion)) {
11946     $dbh->do(q{
11947         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11948         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')
11949     });
11950
11951     print "Upgrade to $DBversion done (Bug 14395 - Two different ways to calculate 'No renewal before')\n";
11952     SetVersion($DBversion);
11953 }
11954
11955 $DBversion = "3.23.00.032";
11956 if ( CheckVersion($DBversion) ) {
11957     $dbh->do(q{
11958    -- Add issue_id to accountlines table
11959     ALTER TABLE accountlines ADD issue_id INT(11) NULL DEFAULT NULL AFTER accountlines_id;
11960     });
11961
11962 ## Close out any accruing fines with no current issue
11963     $dbh->do(q{
11964     UPDATE accountlines LEFT JOIN issues USING ( itemnumber, borrowernumber ) SET accounttype = 'F' WHERE accounttype = 'FU' and issues.issue_id IS NULL;
11965     });
11966
11967 ## Close out any extra not really accruing fines, keep only the latest accring fine
11968     $dbh->do(q{
11969     UPDATE accountlines a1
11970     LEFT JOIN (SELECT MAX(accountlines_id) AS keeper,
11971                       borrowernumber,
11972                       itemnumber
11973                FROM   accountlines
11974                WHERE  accounttype = 'FU'
11975                GROUP BY borrowernumber, itemnumber
11976               ) a2 USING ( borrowernumber, itemnumber )
11977     SET    a1.accounttype = 'F'
11978     WHERE  a1.accounttype = 'FU'
11979     AND  a1.accountlines_id != a2.keeper;
11980     });
11981
11982 ## Update the unclosed fines to add the current issue_id to them
11983     $dbh->do(q{
11984     UPDATE accountlines LEFT JOIN issues USING ( itemnumber ) SET accountlines.issue_id = issues.issue_id WHERE accounttype = 'FU'; 
11985     });
11986
11987     print "Upgrade to $DBversion done (Bug 15675 - Add issue_id column to accountlines and use it for updating fines)\n";
11988     SetVersion($DBversion);
11989 }
11990
11991 $DBversion = "3.23.00.033";
11992 if ( CheckVersion($DBversion) ) {
11993     $dbh->do(q{
11994     UPDATE systempreferences SET value = CONCAT_WS('|', IF(value = '', NULL, value), 'cardnumber') WHERE variable = 'PatronSelfRegistrationBorrowerUnwantedField' AND value NOT LIKE '%cardnumber%';
11995     });
11996
11997     $dbh->do(q{
11998     UPDATE systempreferences SET value = CONCAT_WS('|', IF(value = '', NULL, value), 'categorycode') WHERE variable = 'PatronSelfRegistrationBorrowerUnwantedField' AND value NOT LIKE '%categorycode%';
11999     });
12000
12001     print "Upgrade to $DBversion done (Bug 14659 - Allow patrons to enter card number and patron category on OPAC registration page)\n";
12002     SetVersion($DBversion);
12003 }
12004
12005 $DBversion = "3.23.00.034";
12006 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12007     $dbh->do(q{
12008         ALTER TABLE `items` ADD `new` VARCHAR(32) NULL AFTER `stocknumber`;
12009     });
12010     $dbh->do(q{
12011         ALTER TABLE `deleteditems` ADD `new` VARCHAR(32) NULL AFTER `stocknumber`;
12012     });
12013     print "Upgrade to $DBversion done (Bug 11023: Adds field 'new' in items and deleteditems tables)\n";
12014     SetVersion($DBversion);
12015 }
12016
12017 $DBversion = "3.23.00.035";
12018 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12019     $dbh->do(q{
12020         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('HTML5MediaYouTube',0,'Embed|Don\'t embed','YouTube links as videos','YesNo');
12021     });
12022     print "Upgrade to $DBversion done (Bug 14168 - enhance streaming cataloging to include youtube)\n";
12023
12024     SetVersion($DBversion);
12025     }
12026
12027 $DBversion = "3.23.00.036";
12028 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12029     $dbh->do(q{
12030     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');
12031     });
12032     print "Upgrade to $DBversion done (Bug 12803 - Add ability to skip closed libraries when generating the holds queue)\n";
12033     SetVersion($DBversion);
12034     }
12035
12036 $DBversion = "3.23.00.037";
12037 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12038 ## Add the new currency.archived column
12039     $dbh->do(q{
12040     ALTER TABLE currency ADD column archived tinyint(1) DEFAULT 0;
12041     });
12042 ## Set currency=NULL if empty (just in case)
12043     $dbh->do(q{
12044     UPDATE aqorders SET currency=NULL WHERE currency="";
12045     });
12046 ## Insert the missing currency and mark them as archived before adding the FK
12047     $dbh->do(q{
12048     INSERT INTO currency(currency, archived) SELECT distinct currency, 1 FROM aqorders WHERE currency NOT IN (SELECT currency FROM currency);
12049     });
12050 ## Correct the field length in aqorders before adding FK too
12051     $dbh->do(q{ ALTER TABLE aqorders MODIFY COLUMN currency varchar(10) default NULL; });
12052 ## And finally add the FK
12053     $dbh->do(q{
12054     ALTER TABLE aqorders ADD FOREIGN KEY (currency) REFERENCES currency(currency) ON DELETE SET NULL ON UPDATE SET null;
12055     });
12056
12057     print "Upgrade to $DBversion done (Bug 15084 - Move the currency related code to Koha::Acquisition::Currenc[y|ies])\n";
12058     SetVersion($DBversion);
12059 }
12060
12061 $DBversion = "3.23.00.038";
12062 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12063     $dbh->do(q{
12064     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');
12065     });
12066     print "Upgrade to $DBversion done (Bug 14694 - Make decreaseloanHighHolds more flexible)\n";
12067     SetVersion($DBversion);
12068 }
12069
12070 $DBversion = "3.23.00.039";
12071 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12072
12073     $dbh->do(q{
12074     ALTER TABLE suggestions
12075     MODIFY COLUMN currency varchar(10) default NULL;
12076     });
12077     $dbh->do(q{
12078     ALTER TABLE aqbooksellers
12079     MODIFY COLUMN currency varchar(10) default NULL;
12080     });
12081     print "Upgrade to $DBversion done (Bug 15084 - Move the currency related code to Koha::Acquisition::Currenc[y|ies])\n";
12082     SetVersion($DBversion);
12083 }
12084
12085
12086 $DBversion = "3.23.00.040";
12087 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12088
12089     my $c = $dbh->selectrow_array('SELECT COUNT(*) FROM systempreferences WHERE variable="intranetcolorstylesheet" AND value="blue.css"');
12090
12091     if ( $c ) {
12092         print "WARNING: You are using a stylesheeet which has been removed from the Koha codebase.\n";
12093         print "Update your intranetcolorstylesheet.\n";
12094     }
12095     print "Upgrade to $DBversion done (Bug 16019 - Check intranetcolorstylesheet for blue.css)\n";
12096     SetVersion($DBversion);
12097 }
12098
12099 $DBversion = "3.23.00.041";
12100 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12101
12102     my $dbh = C4::Context->dbh;
12103     my ($print_error) = $dbh->{PrintError};
12104     $dbh->{RaiseError} = 0;
12105     $dbh->{PrintError} = 0;
12106     $dbh->do("ALTER TABLE overduerules_transport_types ADD COLUMN letternumber INT(1) NOT NULL DEFAULT 1 AFTER id");
12107     $dbh->{PrintError} = $print_error;
12108
12109     print "Upgrade to $DBversion done (Bug 16007: Make sure overduerules_transport_types.letternumber exists)\n";
12110     SetVersion($DBversion);
12111 }
12112
12113 $DBversion = "3.23.00.042";
12114 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12115
12116     $dbh->do(q{
12117             ALTER TABLE items CHANGE new new_status VARCHAR(32) NULL;
12118             });
12119     $dbh->do(q{
12120             ALTER TABLE deleteditems CHANGE new new_status VARCHAR(32) NULL;
12121             });
12122     $dbh->do(q{
12123             UPDATE systempreferences SET value=REPLACE(value, '"items.new"', '"items.new_status"') WHERE variable="automatic_item_modification_by_age_configuration";
12124             });
12125
12126     print "Upgrade to $DBversion done (Bug 16004 - Replace items.new with items.new_status)\n";
12127     SetVersion($DBversion);
12128 }
12129
12130 $DBversion = "3.23.00.043";
12131 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12132     $dbh->do(q{
12133             UPDATE systempreferences SET value="" WHERE value IS NULL;
12134             });
12135
12136     print "Upgrade to $DBversion done (Bug 16070 - Empty (undef) system preferences may cause some issues in combination with memcache)\n";
12137     SetVersion($DBversion);
12138 }
12139
12140 $DBversion = "3.23.00.044";
12141 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12142     $dbh->do(q{
12143             INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
12144             ('GoogleOpenIDConnect', '0', NULL, 'if ON, allows the use of Google OpenID Connect for login', 'YesNo'),
12145             ('GoogleOAuth2ClientID', '', NULL, 'Client ID for the web app registered with Google', 'Free'),
12146             ('GoogleOAuth2ClientSecret', '', NULL, 'Client Secret for the web app registered with Google', 'Free'),
12147             ('GoogleOpenIDConnectDomain', '', NULL, 'Restrict OpenID Connect to this domain (or subdomains of this domain). Leave blank for all Google domains', 'Free');
12148             });
12149
12150     print "Upgrade to $DBversion done (Bug 10988 - Allow login via Google OAuth2 (OpenID Connect))\n";
12151     SetVersion($DBversion);
12152 }
12153
12154 $DBversion = "3.23.00.045";
12155 if ( CheckVersion($DBversion) ) {
12156 ## Holds details for vendors supplying goods by EDI
12157    $dbh->do(q{
12158            CREATE TABLE IF NOT EXISTS vendor_edi_accounts (
12159                    id INT(11) NOT NULL auto_increment,
12160                    description TEXT NOT NULL,
12161                    host VARCHAR(40),
12162                    username VARCHAR(40),
12163                    password VARCHAR(40),
12164                    last_activity DATE,
12165                    vendor_id INT(11) REFERENCES aqbooksellers( id ),
12166                    download_directory TEXT,
12167                    upload_directory TEXT,
12168                    san VARCHAR(20),
12169                    id_code_qualifier VARCHAR(3) default '14',
12170                    transport VARCHAR(6) default 'FTP',
12171                    quotes_enabled TINYINT(1) not null default 0,
12172                    invoices_enabled TINYINT(1) not null default 0,
12173                    orders_enabled TINYINT(1) not null default 0,
12174                    responses_enabled TINYINT(1) not null default 0,
12175                    auto_orders TINYINT(1) not null default 0,
12176                    shipment_budget INTEGER(11) REFERENCES aqbudgets( budget_id ),
12177                    PRIMARY KEY  (id),
12178                    KEY vendorid (vendor_id),
12179                    KEY shipmentbudget (shipment_budget),
12180                    CONSTRAINT vfk_vendor_id FOREIGN KEY ( vendor_id ) REFERENCES aqbooksellers ( id ),
12181                    CONSTRAINT vfk_shipment_budget FOREIGN KEY ( shipment_budget ) REFERENCES aqbudgets ( budget_id )
12182                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
12183    });
12184
12185 ## Hold the actual edifact messages with links to associated baskets
12186    $dbh->do(q{
12187            CREATE TABLE IF NOT EXISTS edifact_messages (
12188                    id INT(11) NOT NULL auto_increment,
12189                    message_type VARCHAR(10) NOT NULL,
12190                    transfer_date DATE,
12191                    vendor_id INT(11) REFERENCES aqbooksellers( id ),
12192                    edi_acct  INTEGER REFERENCES vendor_edi_accounts( id ),
12193                    status TEXT,
12194                    basketno INT(11) REFERENCES aqbasket( basketno),
12195                    raw_msg MEDIUMTEXT,
12196                    filename TEXT,
12197                    deleted BOOLEAN NOT NULL DEFAULT 0,
12198                    PRIMARY KEY  (id),
12199                    KEY vendorid ( vendor_id),
12200                    KEY ediacct (edi_acct),
12201                    KEY basketno ( basketno),
12202                    CONSTRAINT emfk_vendor FOREIGN KEY ( vendor_id ) REFERENCES aqbooksellers ( id ),
12203                    CONSTRAINT emfk_edi_acct FOREIGN KEY ( edi_acct ) REFERENCES vendor_edi_accounts ( id ),
12204                    CONSTRAINT emfk_basketno FOREIGN KEY ( basketno ) REFERENCES aqbasket ( basketno )
12205                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
12206             });
12207
12208 ## invoices link back to the edifact message it was generated from
12209    $dbh->do(q{
12210            ALTER TABLE aqinvoices ADD COLUMN message_id INT(11) REFERENCES edifact_messages( id );
12211            });
12212
12213 ## clean up link on deletes
12214    $dbh->do(q{
12215            ALTER TABLE aqinvoices ADD CONSTRAINT edifact_msg_fk FOREIGN KEY ( message_id ) REFERENCES edifact_messages ( id ) ON DELETE SET NULL;
12216            });
12217
12218 ## Hold the supplier ids from quotes for ordering
12219 ## although this is an EAN-13 article number the standard says 35 characters ???
12220    $dbh->do(q{
12221            ALTER TABLE aqorders ADD COLUMN line_item_id VARCHAR(35);
12222            });
12223
12224 ## The suppliers unique reference usually a quotation line number ('QLI')
12225 ## Otherwise Suppliers unique orderline reference ('SLI')
12226    $dbh->do(q{
12227            ALTER TABLE aqorders ADD COLUMN suppliers_reference_number VARCHAR(35);
12228            });
12229    $dbh->do(q{
12230            ALTER TABLE aqorders ADD COLUMN suppliers_reference_qualifier VARCHAR(3);
12231            });
12232    $dbh->do(q{
12233            ALTER TABLE aqorders ADD COLUMN suppliers_report text;
12234            });
12235
12236 ## hold the EAN/SAN used in ordering
12237    $dbh->do(q{
12238            CREATE TABLE IF NOT EXISTS edifact_ean (
12239                    ee_id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
12240                    description VARCHAR(128) NULL DEFAULT NULL,
12241                    branchcode VARCHAR(10) NOT NULL REFERENCES branches (branchcode),
12242                    ean VARCHAR(15) NOT NULL,
12243                    id_code_qualifier VARCHAR(3) NOT NULL DEFAULT '14',
12244                    CONSTRAINT efk_branchcode FOREIGN KEY ( branchcode ) REFERENCES branches ( branchcode )
12245                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
12246            });
12247
12248 ## Add a permission for managing EDI
12249    $dbh->do(q{
12250            INSERT INTO permissions (module_bit, code, description) values (11, 'edi_manage', 'Manage EDIFACT transmissions');
12251            });
12252
12253    print "Upgrade to $DBversion done (Bug 7736 - Edifact QUOTE and ORDER functionality))\n";
12254    SetVersion($DBversion);
12255 }
12256
12257 $DBversion = "3.23.00.046";
12258 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12259
12260     $dbh->do(q{
12261     ALTER TABLE vendor_edi_accounts ADD COLUMN plugin VARCHAR(256) NOT NULL DEFAULT "";
12262     });
12263
12264     print "Upgrade to $DBversion done (Bug 15630 - Make Edifact module pluggable))\n";
12265     SetVersion($DBversion);
12266 }
12267
12268 $DBversion = "3.23.00.047";
12269 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12270
12271     $dbh->do(q{
12272          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');
12273          });
12274     $dbh->do(q{
12275          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');
12276          });
12277
12278     print "Upgrade to $DBversion done (Bug 15008 - Add custom HTML areas to circulation and reports home pages)\n";
12279     SetVersion($DBversion);
12280 }
12281
12282 $DBversion = "3.23.00.048";
12283 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12284     $dbh->do(q{
12285     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';
12286     });
12287
12288     print "Upgrade to $DBversion done (Bug 5979 - Add separate OPACISBD system preference)\n";
12289     SetVersion($DBversion);
12290 }
12291
12292
12293
12294 $DBversion = "3.23.00.049";
12295 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12296 my $dbh = C4::Context->dbh;
12297 my ( $column_has_been_used ) = $dbh->selectrow_array(q|
12298             SELECT COUNT(*)
12299                 FROM borrower_attributes
12300                     WHERE password IS NOT NULL
12301                     |);
12302
12303 if ( $column_has_been_used ) {
12304         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.|;
12305 } else {
12306         $dbh->do(q|
12307         ALTER TABLE borrower_attribute_types DROP column password_allowed
12308         |);
12309         $dbh->do(q|
12310         ALTER TABLE borrower_attributes DROP column password;
12311         |);
12312     }
12313     print "Upgrade to $DBversion done (Bug 12267 - Allow password option in Patron Attribute non functional)\n";
12314         SetVersion($DBversion);
12315 }
12316
12317
12318 $DBversion = "3.23.00.050";
12319 if ( CheckVersion($DBversion) ) {
12320
12321     $dbh->do(q|INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
12322                     VALUES('SearchEngine','Zebra','Choose Search Engine','','Choice')|);
12323
12324
12325     $dbh->do(q|DROP TABLE IF EXISTS search_marc_to_field|);
12326     $dbh->do(q|DROP TABLE IF EXISTS search_marc_map|);
12327     $dbh->do(q|DROP TABLE IF EXISTS search_field|);
12328
12329 # This specifies the fields that will be stored in the search engine.
12330  $dbh->do(q|
12331          CREATE TABLE `search_field` (
12332              `id` int(11) NOT NULL AUTO_INCREMENT, 
12333              `name` varchar(255) NOT NULL COMMENT 'the name of the field as it will be stored in the search engine',
12334              `label` varchar(255) NOT NULL COMMENT 'the human readable name of the field, for display', 
12335              `type` ENUM('', 'string', 'date', 'number', 'boolean', 'sum') NOT NULL COMMENT 'what type of data this holds, relevant when storing it in the search engine',
12336              PRIMARY KEY (`id`),
12337              UNIQUE KEY (`name`)
12338              ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
12339          |);
12340 # This contains a MARC field specifier for a given index, marc type, and marc
12341 # field.
12342 $dbh->do(q|
12343         CREATE TABLE `search_marc_map` (
12344             id int(11) NOT NULL AUTO_INCREMENT,
12345             index_name ENUM('biblios','authorities') NOT NULL COMMENT 'what storage index this map is for',
12346             marc_type ENUM('marc21', 'unimarc', 'normarc') NOT NULL COMMENT 'what MARC type this map is for',
12347             marc_field VARCHAR(255) NOT NULL COMMENT 'the MARC specifier for this field',
12348             PRIMARY KEY(`id`),
12349             unique key( index_name, marc_field, marc_type),
12350             INDEX (`index_name`)
12351             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
12352         |);
12353
12354 # This joins the two search tables together. We can have any combination:
12355 # one marc field could have many search fields (maybe you want one value
12356 # to go to 'author' and 'corporate-author) and many marc fields could go
12357 # to one search field (e.g. all the various author fields going into
12358 # 'author'.)
12359 #
12360 # a note about the sort field:
12361 # * if all the entries for a mapping are 'null', nothing special is done with that mapping.
12362 # * if any of the entries are not null, then a __sort field is created in ES for this mapping. In this case:
12363 #   * any mapping with sort == false WILL NOT get copied into a __sort field
12364 #   * any mapping with sort == true or is null WILL get copied into a __sort field
12365 #   * any sorts on the field name will be applied to $fieldname.'__sort' instead.
12366 # this means that we can have search for author that includes 1xx, 245$c, and 7xx, but the sort only applies to 1xx.
12367
12368 $dbh->do(q|
12369         CREATE TABLE `search_marc_to_field` (
12370             search_marc_map_id int(11) NOT NULL,
12371             search_field_id int(11) NOT NULL,
12372             facet boolean DEFAULT FALSE COMMENT 'true if a facet field should be generated for this',
12373             suggestible boolean DEFAULT FALSE COMMENT 'true if this field can be used to generate suggestions for browse',
12374             sort boolean DEFAULT NULL COMMENT 'true/false creates special sort handling, null doesn''t',
12375             PRIMARY KEY(search_marc_map_id, search_field_id),
12376             FOREIGN KEY(search_marc_map_id) REFERENCES search_marc_map(id) ON DELETE CASCADE ON UPDATE CASCADE,
12377             FOREIGN KEY(search_field_id) REFERENCES search_field(id) ON DELETE CASCADE ON UPDATE CASCADE
12378             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
12379         |);
12380
12381     print "WARNING: If you plan to use Elasticsearch you should go to 'Home › Administration › Search engine configuration' and reset the mappings\n";
12382     print "Upgrade to $DBversion done (Bug 12478 - Elasticsearch support for Koha)\n";
12383     SetVersion($DBversion);
12384 }
12385
12386
12387 $DBversion = "3.23.00.051";
12388 if ( CheckVersion($DBversion) ) {
12389 $dbh->do(q{
12390         ALTER TABLE edifact_messages
12391         DROP FOREIGN KEY emfk_vendor,
12392         DROP FOREIGN KEY emfk_edi_acct,
12393         DROP FOREIGN KEY emfk_basketno;
12394         });
12395
12396 $dbh->do(q{
12397         ALTER TABLE edifact_messages
12398         ADD CONSTRAINT emfk_vendor FOREIGN KEY ( vendor_id ) REFERENCES aqbooksellers ( id ) ON DELETE CASCADE ON UPDATE CASCADE,
12399         ADD CONSTRAINT emfk_edi_acct FOREIGN KEY ( edi_acct ) REFERENCES vendor_edi_accounts ( id ) ON DELETE CASCADE ON UPDATE CASCADE,
12400         ADD CONSTRAINT emfk_basketno FOREIGN KEY ( basketno ) REFERENCES aqbasket ( basketno ) ON DELETE CASCADE ON UPDATE CASCADE;
12401         });
12402
12403     print "Upgrade to $DBversion done (Bug 16354 - Fix FK constraints for edifact_messages table)\n";
12404     SetVersion($DBversion);
12405 }
12406
12407
12408 $DBversion = "3.23.00.052";
12409 if ( CheckVersion($DBversion) ) {
12410 ## Insert permission
12411
12412     $dbh->do(q{
12413         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
12414         (13, 'upload_general_files', 'Upload any file'),
12415         (13, 'upload_manage', 'Manage uploaded files');
12416         });
12417 ## Update user_permissions for current users (check count in uploaded_files)
12418 ## Note 9 == edit_catalogue and 13 == tools
12419 ## We do not insert if someone is superlibrarian, does not have edit_catalogue,
12420 ## or already has all tools
12421
12422         $dbh->do(q{
12423                 INSERT IGNORE INTO user_permissions (borrowernumber, module_bit, code)
12424                 SELECT borrowernumber, 13, 'upload_general_files'
12425                 FROM borrowers bo
12426                 WHERE flags<>1 AND flags & POW(2,13) = 0 AND
12427                 ( flags & POW(2,9) > 0 OR 
12428                   (SELECT COUNT(*) FROM user_permissions
12429                    WHERE borrowernumber=bo.borrowernumber AND module_bit=9 ) > 0 )
12430                 AND ( SELECT COUNT(*) FROM uploaded_files ) > 0
12431                 });
12432
12433     print "Upgrade to $DBversion done (Bug 14686 - New menu option and permission for file uploading)\n";
12434     SetVersion($DBversion);
12435 }
12436
12437 $DBversion = "3.23.00.053";
12438 if ( CheckVersion($DBversion) ) {
12439     my $letters = $dbh->selectall_arrayref(
12440         q|
12441         SELECT code, name
12442         FROM letter
12443         WHERE message_transport_type="email"
12444         |, { Slice => {} }
12445     );
12446     for my $letter (@$letters) {
12447         $dbh->do(
12448             q|
12449                 UPDATE letter
12450                 SET name = ?
12451                 WHERE code = ?
12452                 AND message_transport_type <> "email"
12453                 |, undef, $letter->{name}, $letter->{code}
12454         );
12455     }
12456
12457     print "Upgrade to $DBversion done (Bug 16217 - Notice' names may have diverged)\n";
12458     SetVersion($DBversion);
12459 }
12460
12461 $DBversion = "3.23.00.054";
12462 if ( CheckVersion($DBversion) ) {
12463     $dbh->do(q{
12464         ALTER TABLE branch_item_rules ADD COLUMN hold_fulfillment_policy ENUM('any', 'homebranch', 'holdingbranch') NOT NULL DEFAULT 'any' AFTER holdallowed;
12465     });
12466     $dbh->do(q{
12467         ALTER TABLE default_branch_circ_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_item_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_circ_rules ADD COLUMN hold_fulfillment_policy ENUM('any', 'homebranch', 'holdingbranch') NOT NULL DEFAULT 'any' AFTER holdallowed;
12474     });
12475
12476     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";
12477     SetVersion($DBversion);
12478 }
12479
12480 $DBversion = "3.23.00.055";
12481 if ( CheckVersion($DBversion) ) {
12482     $dbh->do(q{
12483         ALTER TABLE reserves ADD COLUMN itemtype VARCHAR(10) NULL DEFAULT NULL AFTER suspend_until;
12484     });
12485     $dbh->do(q{
12486         ALTER TABLE reserves ADD KEY `itemtype` (`itemtype`);
12487     });
12488     $dbh->do(q{
12489         ALTER TABLE reserves ADD CONSTRAINT `reserves_ibfk_5` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE;
12490     });
12491     $dbh->do(q{
12492         ALTER TABLE old_reserves ADD COLUMN itemtype VARCHAR(10) NULL DEFAULT NULL AFTER suspend_until;
12493     });
12494     $dbh->do(q{
12495         ALTER TABLE old_reserves ADD KEY `itemtype` (`itemtype`);
12496     });
12497     $dbh->do(q{
12498         ALTER TABLE old_reserves ADD CONSTRAINT `old_reserves_ibfk_4` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE;
12499     });
12500
12501     $dbh->do(q{
12502         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
12503         ('AllowHoldItemTypeSelection','0','','If enabled, patrons and staff will be able to select the itemtype when placing a hold','YesNo');
12504     });
12505
12506     print "Upgrade to $DBversion done (Bug 15533 - Allow patrons and librarians to select itemtype when placing hold)\n";
12507     SetVersion($DBversion);
12508 }
12509
12510 $DBversion = "3.23.00.056";
12511 if ( CheckVersion($DBversion) ) {
12512     $dbh->do(q{
12513         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
12514         ('NoIssuesChargeGuarantees','','','Define maximum amount withstanding before check outs are blocked','Integer');
12515     });
12516
12517     print "Upgrade to $DBversion done (Bug 14577 - Allow restriction of checkouts based on fines of guarantor/guarantee)\n";
12518     SetVersion($DBversion);
12519 }
12520
12521 $DBversion = "3.23.00.057";
12522 if ( CheckVersion($DBversion) ) {
12523     $dbh->do(q{
12524         ALTER TABLE aqbasket ADD COLUMN is_standing TINYINT(1) NOT NULL DEFAULT 0 AFTER branch;
12525     });
12526
12527     print "Upgrade to $DBversion done (Bug 15531 - Add support for standing orders)\n";
12528     SetVersion($DBversion);
12529 }
12530
12531 $DBversion = "3.23.00.058";
12532 if ( CheckVersion($DBversion) ) {
12533
12534     my ($count_imageurl) = $dbh->selectrow_array(q|
12535         SELECT COUNT(*)
12536         FROM authorised_values
12537         WHERE imageurl IS NOT NULL
12538             AND imageurl <> ""
12539     |);
12540
12541     unless ($count_imageurl) {
12542         if (   C4::Context->preference('AuthorisedValueImages')
12543             or C4::Context->preference('StaffAuthorisedValueImages') )
12544         {
12545             $dbh->do(q|
12546                 UPDATE systempreferences
12547                 SET value = 0
12548                 WHERE variable = "AuthorisedValueImages"
12549                    or variable = "StaffAuthorisedValueImages"
12550             |);
12551             warn "The system preferences AuthorisedValueImages and StaffAuthorisedValueImages have been turned off\n";
12552             warn "authorised_values.imageurl is not populated, that means you are not using this feature\n";
12553         }
12554     }
12555     else {
12556         warn "At least one authorised value has an icon defined (imageurl)\n";
12557         warn "The system preference AuthorisedValueImages or StaffAuthorisedValueImages could be turned off if you are not aware of this feature\n";
12558     }
12559
12560     print "Upgrade to $DBversion done (Bug 16041 - StaffAuthorisedValueImages & AuthorisedValueImages preferences - impact on search performance)\n";
12561     SetVersion($DBversion);
12562 }
12563
12564 $DBversion = "3.23.00.059";
12565 if ( CheckVersion($DBversion) ) {
12566     $dbh->do(q{
12567         DELETE FROM systempreferences WHERE variable="AuthorisedValueImages" OR variable="StaffAuthorisedValueImages";
12568     });
12569
12570     print "Upgrade to $DBversion done (Bug 16167 - Remove prefs to drive authorised value images)\n";
12571     SetVersion($DBversion);
12572 }
12573
12574 $DBversion = "3.23.00.060";
12575 if ( CheckVersion($DBversion) ) {
12576     $dbh->do(q{
12577         INSERT IGNORE INTO systempreferences ( value, variable, options, explanation,type )
12578         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';
12579     });
12580
12581     print "Upgrade to $DBversion done (Bug 12528 - Enable staff to deny message setting access to patrons on the OPAC)\n";
12582     SetVersion($DBversion);
12583 }
12584
12585 $DBversion = "3.23.00.061";
12586 if ( CheckVersion($DBversion) ) {
12587     my ( $cnt ) = $dbh->selectrow_array( q|
12588         SELECT COUNT(*) FROM items it
12589         LEFT JOIN biblio bi ON bi.biblionumber=it.biblionumber
12590         LEFT JOIN biblioitems bii USING (biblioitemnumber)
12591         WHERE bi.biblionumber IS NULL
12592     |);
12593     if( $cnt ) {
12594         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";
12595     } else {
12596         # now add FK
12597         $dbh->do( q|
12598             ALTER TABLE items
12599             ADD FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
12600         |);
12601         print "Upgrade to $DBversion done (Bug 16170 - Add FK for biblionumber in items)\n";
12602     }
12603     SetVersion($DBversion);
12604 }
12605
12606 $DBversion = "3.23.00.062";
12607 if ( CheckVersion($DBversion) ) {
12608     $dbh->do( q|
12609             ALTER TABLE aqorders DROP COLUMN budgetgroup_id;
12610             |);
12611     print "Upgrade to $DBversion done (Bug 16414 - aqorders.budgetgroup_id has never been used and can be removed)\n";
12612 SetVersion($DBversion);
12613 }
12614
12615 $DBversion = "3.23.00.063";
12616 if ( CheckVersion($DBversion) ) {
12617     $dbh->do(q{
12618         UPDATE letter SET branchcode='' WHERE branchcode IS NULL;
12619     });
12620     $dbh->do(q{
12621         ALTER TABLE letter MODIFY COLUMN branchcode varchar(10) NOT NULL DEFAULT ''
12622     });
12623     $dbh->do(q{
12624         ALTER TABLE permissions MODIFY COLUMN code varchar(64) NOT NULL DEFAULT '';
12625     });
12626     print "Upgrade to $DBversion done (Bug 16402: Fix DB structure to work on MySQL 5.7)\n";
12627     SetVersion($DBversion);
12628 }
12629
12630 $DBversion = "3.23.00.064";
12631 if ( CheckVersion($DBversion) ) {
12632     $dbh->do(q{
12633         ALTER TABLE creator_layouts MODIFY layout_name char(25) NOT NULL DEFAULT 'DEFAULT';
12634     });
12635     print "Upgrade to $DBversion done (Bug 15086 - Creators layout and template sql has warnings)\n";
12636     SetVersion($DBversion);
12637 }
12638
12639 $DBversion = "16.05.00.000";
12640 if ( CheckVersion($DBversion) ) {
12641     print "Upgrade to $DBversion done (Koha 16.05)\n";
12642     SetVersion($DBversion);
12643 }
12644
12645 $DBversion = "16.06.00.000";
12646 if ( CheckVersion($DBversion) ) {
12647     print "Upgrade to $DBversion done (Koha 16.06 - starting a new dev line at KohaCon16 in Thessaloniki, Greece! Koha is great!)\n";
12648     SetVersion($DBversion);
12649 }
12650
12651 $DBversion = "16.06.00.001";
12652 if ( CheckVersion($DBversion) ) {
12653     $dbh->do(q{
12654         UPDATE accountlines SET accounttype='HE', description=itemnumber WHERE (description REGEXP '^Hold waiting too long [0-9]+') AND accounttype='F';
12655     });
12656
12657     print "Upgrade to $DBversion done (Bug 16200 - 'Hold waiting too long' fee has a translation problem)\n";
12658     SetVersion($DBversion);
12659 }
12660
12661 $DBversion = "16.06.00.002";
12662 if ( CheckVersion($DBversion) ) {
12663     unless ( column_exists('borrowers', 'updated_on') ) {
12664         $dbh->do(q{
12665             ALTER TABLE borrowers
12666                 ADD COLUMN updated_on timestamp NULL DEFAULT CURRENT_TIMESTAMP
12667                 ON UPDATE CURRENT_TIMESTAMP
12668                 AFTER privacy_guarantor_checkouts;
12669         });
12670         $dbh->do(q{
12671             ALTER TABLE deletedborrowers
12672                 ADD COLUMN updated_on timestamp NULL DEFAULT CURRENT_TIMESTAMP
12673                 ON UPDATE CURRENT_TIMESTAMP
12674                 AFTER privacy_guarantor_checkouts;
12675         });
12676     }
12677
12678     print "Upgrade to $DBversion done (Bug 10459 - borrowers should have a timestamp)\n";
12679     SetVersion($DBversion);
12680 }
12681
12682 $DBversion = "16.06.00.003";
12683 if ( CheckVersion($DBversion) ) {
12684     $dbh->do(q{
12685         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
12686         SELECT 'MaxItemsToProcessForBatchMod', value, NULL, 'Process up to a given number of items in a single item modification batch.', 'Integer' FROM systempreferences WHERE variable='MaxItemsForBatch';
12687     });
12688     $dbh->do(q{
12689         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
12690         SELECT 'MaxItemsToDisplayForBatchDel', value, NULL, 'Display up to a given number of items in a single item deletionbatch.', 'Integer' FROM systempreferences WHERE variable='MaxItemsForBatch';
12691     });
12692     $dbh->do(q{
12693         DELETE FROM systempreferences WHERE variable="MaxItemsForBatch";
12694     });
12695
12696     print "Upgrade to $DBversion done (Bug 11490 - MaxItemsForBatch should be split into two new prefs)\n";
12697     SetVersion($DBversion);
12698 }
12699
12700 $DBversion = '16.06.00.004';
12701 if ( CheckVersion($DBversion) ) {
12702     $dbh->do(q{
12703         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
12704          SELECT 'OPACXSLTListsDisplay', COALESCE(value,''), '', 'Enable XSLT stylesheet control over lists pages display on OPAC', 'Free'
12705          FROM systempreferences WHERE variable='OPACXSLTResultsDisplay';
12706     });
12707
12708     $dbh->do(q{
12709         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
12710          SELECT 'XSLTListsDisplay', COALESCE(value,''), '', 'Enable XSLT stylesheet control over lists pages display on intranet', 'Free'
12711          FROM systempreferences WHERE variable='XSLTResultsDisplay';
12712     });
12713
12714     print "Upgrade to $DBversion done (Bug 15485: Allow choosing different XSLTs for lists)\n";
12715     SetVersion($DBversion);
12716 }
12717
12718 $DBversion = '16.06.00.005';
12719 if ( CheckVersion($DBversion) ) {
12720     $dbh->do(q{
12721         UPDATE `systempreferences` set options = 'US|FR|CH' where variable = 'CurrencyFormat';
12722     });
12723
12724     print "Upgrade to $DBversion done (Bug 16768 - Add official number format for Switzerland: 1'234'567.89)\n";
12725     SetVersion($DBversion);
12726 }
12727
12728 $DBversion = "16.06.00.006";
12729 if ( CheckVersion($DBversion) ) {
12730     $dbh->do(q{
12731         CREATE TABLE `refund_lost_item_fee_rules` (
12732           `branchcode` varchar(10) NOT NULL default '',
12733           `refund` tinyint(1) NOT NULL default 0,
12734           PRIMARY KEY  (`branchcode`)
12735         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
12736     });
12737     $dbh->do(q{
12738         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
12739         VALUES( 'RefundLostOnReturnControl',
12740                 'CheckinLibrary',
12741                 'If a lost item is returned, choose which branch to pick rules for refunding.',
12742                 'CheckinLibrary|PatronLibrary|ItemHomeBranch|ItemHoldingbranch',
12743                 'Choice')
12744     });
12745     # Pick the old syspref as the default rule
12746     $dbh->do(q{
12747         INSERT INTO refund_lost_item_fee_rules (branchcode,refund)
12748             SELECT '*', COALESCE(value,'1') FROM systempreferences WHERE variable='RefundLostItemFeeOnReturn'
12749     });
12750     # Delete the old syspref
12751     $dbh->do(q{
12752         DELETE IGNORE FROM systempreferences
12753         WHERE variable='RefundLostItemFeeOnReturn'
12754     });
12755
12756     print "Upgrade to $DBversion done (Bug 14048: Change RefundLostItemFeeOnReturn to be branch specific)\n";
12757     SetVersion($DBversion);
12758 }
12759
12760 $DBversion = '16.06.00.007';
12761 if ( CheckVersion($DBversion) ) {
12762     $dbh->do(q{
12763         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) 
12764         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');
12765     });
12766
12767     print "Upgrade to $DBversion done (Bug 3534 - Patron quick add form)\n";
12768     SetVersion($DBversion);
12769 }
12770
12771 $DBversion = '16.06.00.008';
12772 if ( CheckVersion($DBversion) ) {
12773     $dbh->do(q{
12774         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
12775         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');
12776     });
12777     $dbh->do(q{
12778         ALTER TABLE categories
12779         ADD COLUMN `checkprevcheckout` varchar(7) NOT NULL default 'inherit'
12780         AFTER `default_privacy`;
12781     });
12782     $dbh->do(q{
12783         ALTER TABLE borrowers
12784         ADD COLUMN `checkprevcheckout` varchar(7) NOT NULL default 'inherit'
12785         AFTER `privacy_guarantor_checkouts`;
12786     });
12787     $dbh->do(q{
12788         ALTER TABLE deletedborrowers
12789         ADD COLUMN `checkprevcheckout` varchar(7) NOT NULL default 'inherit'
12790         AFTER `privacy_guarantor_checkouts`;
12791     });
12792
12793     print "Upgrade to $DBversion done (Bug 6906 - show 'Borrower has previously issued \$ITEM' alert on checkout)\n";
12794     SetVersion($DBversion);
12795 }
12796
12797 $DBversion = '16.06.00.009';
12798 if ( CheckVersion($DBversion) ) {
12799     $dbh->do(q{
12800         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) 
12801         VALUES ('IntranetCatalogSearchPulldown','0',NULL,'Show a search field pulldown for \"Search the catalog\" boxes. ','YesNo');
12802     });
12803
12804     print "Upgrade to $DBversion done (Bug 14902 - Add qualifier menu to staff side 'Search the Catalog')\n";
12805     SetVersion($DBversion);
12806 }
12807
12808 $DBversion = '16.06.00.010';
12809 if ( CheckVersion($DBversion) ) {
12810     $dbh->do(q{
12811         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
12812         VALUES ('MaxOpenSuggestions','',NULL,'Limit the number of open suggestions a patron can have at once, unlimited if blank','Integer')
12813     });
12814
12815     print "Upgrade to $DBversion done (Bug 15128 - Add ability to limit the number of open purchase suggestions a patron can make)\n";
12816     SetVersion($DBversion);
12817 }
12818
12819 $DBversion = '16.06.00.011';
12820 if ( CheckVersion($DBversion) ) {
12821     $dbh->do(q{
12822         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
12823         ('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'),
12824         ('NovelistSelectStaffView','tab','tab|above|below','Where to display Novelist Select content','Choice');
12825     });
12826
12827     print "Upgrade to $DBversion done (Bug 11606 - Novelist Select in Staff Client)\n";
12828     SetVersion($DBversion);
12829 }
12830
12831 $DBversion = '16.06.00.012';
12832 if ( CheckVersion($DBversion) ) {
12833     $dbh->do(q{
12834         ALTER TABLE virtualshelves MODIFY COLUMN created_on DATETIME not NULL;
12835     });
12836
12837     print "Upgrade to $DBversion done (Bug 16573 - Web installer fails to load structure and sample data on MySQL 5.7)\n";
12838     SetVersion($DBversion);
12839 }
12840
12841 $DBversion = '16.06.00.013';
12842 if ( CheckVersion($DBversion) ) {
12843     $dbh->do(q{
12844         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES
12845         ('OPACResultsLibrary', 'homebranch', 'homebranch|holdingbranch', 'Defines whether the OPAC displays the holding or home branch in search results when using XSLT', 'Choice');
12846     });
12847
12848     print "Upgrade to $DBversion done (Bug 7441 - Search results showing wrong branch)\n";
12849     SetVersion($DBversion);
12850 }
12851
12852 $DBversion = "16.06.00.014";
12853 if ( CheckVersion($DBversion) ) {
12854     $dbh->do(q{
12855         ALTER TABLE `action_logs` ADD COLUMN `interface` VARCHAR(30) DEFAULT NULL AFTER `info`;
12856     });
12857
12858     $dbh->do(q{
12859         ALTER TABLE `action_logs` ADD KEY `interface` (`interface`);
12860     });
12861
12862     print "Upgrade to $DBversion done (Bug 16829: action_logs should have an 'interface' column)\n";
12863     SetVersion($DBversion);
12864 }
12865
12866 $DBversion = "16.06.00.015";
12867 if ( CheckVersion($DBversion) ) {
12868     $dbh->do(q{
12869         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type ) VALUES
12870         ('HoldsLog','0',NULL,'If ON, log create/cancel/suspend/resume actions on holds.','YesNo');
12871     });
12872
12873     print "Upgrade to $DBversion done (Bug 14642: Add logging of hold modifications)\n";
12874     SetVersion($DBversion);
12875 }
12876
12877 $DBversion = "16.06.00.016";
12878 if ( CheckVersion($DBversion) ) {
12879     $dbh->do(q{
12880         update marc_subfield_structure set defaultvalue=REPLACE(defaultvalue, 'YYYY', '<<YYYY>>') where defaultvalue like "%YYYY%" and defaultvalue not like "%<<YYYY>>%";
12881     });
12882     $dbh->do(q{
12883         update marc_subfield_structure set defaultvalue=REPLACE(defaultvalue, 'MM', '<<MM>>') where defaultvalue like "%MM%" and defaultvalue not like "%<<MM>>%";
12884     });
12885     $dbh->do(q{
12886         update marc_subfield_structure set defaultvalue=REPLACE(defaultvalue, 'DD', '<<DD>>') where defaultvalue like "%DD%" and defaultvalue not like "%<<DD>>%";
12887     });
12888     $dbh->do(q{
12889         update marc_subfield_structure set defaultvalue=REPLACE(defaultvalue, 'user', '<<USER>>') where defaultvalue like "%user%" and defaultvalue not like "%<<USER>>%";
12890     });
12891
12892     print "Upgrade to $DBversion done (Bug 7045 - Default-value substitution inconsistent)\n";
12893     SetVersion($DBversion);
12894 }
12895
12896 $DBversion = "16.06.00.017";
12897 if ( CheckVersion($DBversion) ) {
12898     $dbh->do(q{
12899         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');
12900     });
12901
12902     print "Upgrade to $DBversion done (Bug 10848 - Allow configuration of mandatory/required fields on the suggestion form in OPAC)\n";
12903     SetVersion($DBversion);
12904 }
12905
12906 $DBversion = "16.06.00.018";
12907 if ( CheckVersion($DBversion) ) {
12908     $dbh->do(q{
12909         ALTER TABLE issuingrules ADD COLUMN holds_per_record SMALLINT(6) NOT NULL DEFAULT 1 AFTER reservesallowed;
12910     });
12911
12912     print "Upgrade to $DBversion done (Bug 14695 - Add ability to place multiple item holds on a given record per patron)\n";
12913     SetVersion($DBversion);
12914 }
12915
12916 $DBversion = "16.06.00.019";
12917 if ( CheckVersion($DBversion) ) {
12918     $dbh->do(q{
12919         ALTER TABLE reviews CHANGE COLUMN approved approved tinyint(4) DEFAULT 0;
12920     });
12921     $dbh->do(q{
12922         UPDATE reviews SET approved=0 WHERE approved IS NULL;
12923     });
12924
12925     print "Upgrade to $DBversion done (Bug 15839 - Move the reviews related code to Koha::Reviews)\n";
12926     SetVersion($DBversion);
12927 }
12928
12929 $DBversion = "16.06.00.020";
12930 if ( CheckVersion($DBversion) ) {
12931     $dbh->do(q{
12932         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('SwitchOnSiteCheckouts', '0', 'Automatically switch an on-site checkout to a normal checkout', NULL, 'YesNo');
12933     });
12934
12935     print "Upgrade to $DBversion done (Bug 16272 - Transform checkout from on-site checkout to regular checkout)\n";
12936     SetVersion($DBversion);
12937 }
12938
12939 $DBversion = "16.06.00.021";
12940 if ( CheckVersion($DBversion) ) {
12941     $dbh->do(q{
12942         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');
12943     });
12944
12945     print "Upgrade to $DBversion done (Bug 16275 - Prevent patron self registration if the email already filled in borrowers.email)\n";
12946     SetVersion($DBversion);
12947 }
12948
12949 $DBversion = "16.06.00.022";
12950 if ( CheckVersion($DBversion) ) {
12951     $dbh->do(q{
12952         INSERT IGNORE INTO `permissions`
12953         (module_bit, code,             description) VALUES
12954         (16,         'delete_reports', 'Delete SQL reports');
12955     });
12956     $dbh->do(q{
12957         INSERT IGNORE INTO user_permissions
12958         (borrowernumber,      module_bit,code)
12959         SELECT borrowernumber,module_bit,'delete_reports'
12960             FROM user_permissions
12961             WHERE module_bit=16 AND code='create_reports';
12962     });
12963
12964     print "Upgrade to $DBversion done (Bug 16978 - Add delete reports user permission)\n";
12965     SetVersion($DBversion);
12966 }
12967
12968 $DBversion = "16.06.00.023";
12969 if ( CheckVersion($DBversion) ) {
12970     my $pref = C4::Context->preference('timeout');
12971     if( !$pref || $pref eq '12000000' ) {
12972         # update if pref is null or equals old default value
12973         $dbh->do(q|
12974             UPDATE systempreferences SET value = '1d', type = 'Free'
12975             WHERE variable = 'timeout'
12976         |);
12977         print "Upgrade to $DBversion done (Bug 17187)\nNote: Pref value for timeout has been adjusted.\n";
12978     } else {
12979         # only update pref type
12980         $dbh->do(q|
12981             UPDATE systempreferences SET type = 'Free'
12982             WHERE variable = 'timeout'
12983         |);
12984         print "Upgrade to $DBversion done (Bug 17187)\nNote: Pref value for timeout has not been adjusted.\n";
12985     }
12986     SetVersion($DBversion);
12987 }
12988
12989 $DBversion = "16.06.00.024";
12990 if ( CheckVersion($DBversion) ) {
12991     $dbh->do(q{
12992         UPDATE language_descriptions SET description = 'Română' WHERE subtag = 'ro' AND type = 'language' AND lang = 'ro';
12993     });
12994
12995     print "Upgrade to $DBversion done (Bug 16311 - Advanced search language limit typo for Romanian)\n";
12996     SetVersion($DBversion);
12997 }
12998
12999 $DBversion = "16.06.00.025";
13000 if ( CheckVersion($DBversion) ) {
13001     $dbh->do(q{
13002         ALTER TABLE `subscription` ADD `itemtype` VARCHAR( 10 ) NULL AFTER reneweddate, ADD `previousitemtype` VARCHAR( 10 ) NULL AFTER itemtype;
13003     });
13004     $dbh->do(q{
13005         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
13006         ('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');
13007     });
13008
13009     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";
13010     SetVersion($DBversion);
13011 }
13012
13013 $DBversion = "16.06.00.026";
13014 if ( CheckVersion($DBversion) ) {
13015     $dbh->do(q{
13016         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('PatronSelfRegistrationLibraryList', '', 'Only display libraries listed. If empty, all libraries are displayed.', NULL, 'Free');
13017     });
13018
13019     print "Upgrade to $DBversion done (Bug 16274 - Make the selfregistration branchcode selection configurable)\n";
13020     SetVersion($DBversion);
13021 }
13022
13023 $DBversion = "16.06.00.027";
13024 if ( CheckVersion($DBversion) ) {
13025     unless ( column_exists('borrowers', 'lastseen') ) {
13026         $dbh->do(q{
13027             ALTER TABLE borrowers ADD COLUMN lastseen datetime default NULL AFTER updated_on;
13028         });
13029         $dbh->do(q{
13030             ALTER TABLE deletedborrowers ADD COLUMN lastseen datetime default NULL AFTER updated_on;
13031         });
13032     }
13033     $dbh->do(q{
13034         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');
13035     });
13036
13037     print "Upgrade to $DBversion done (Bug 16276: Add a new pref TrackLastPatronActivity and new column borrowers.lastseen)\n";
13038     SetVersion($DBversion);
13039 }
13040
13041 $DBversion = '16.06.00.028';
13042 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
13043     {
13044         print "Attempting upgrade to $DBversion (Bug 17135) ...\n";
13045         my $maintenance_script = C4::Context->config("intranetdir") . "/installer/data/mysql/fix_unclosed_nonaccruing_fines_bug17135.pl";
13046         system("perl $maintenance_script --confirm");
13047
13048         print "Upgrade to $DBversion done (Bug 17135 - Fine for the previous overdue may get overwritten by the next one)\n";
13049
13050         unless ($original_version < TransformToNum("3.23.00.032")) { ## Bug 15675
13051             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";
13052             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";
13053         }
13054         SetVersion ($DBversion);
13055     }
13056 }
13057
13058 $DBversion = "16.06.00.029";
13059 if ( CheckVersion($DBversion) ) {
13060     $dbh->do(q{
13061         UPDATE systempreferences SET type="Choice" WHERE variable="UsageStatsLibraryType";
13062     });
13063     $dbh->do(q{
13064         UPDATE systempreferences SET value="Canada" WHERE variable="UsageStatsCountry" AND value="CANADA";
13065     });
13066     $dbh->do(q{
13067         UPDATE systempreferences SET value="Czech Republic" WHERE variable="UsageStatsCountry" AND value="CZ";
13068     });
13069     $dbh->do(q{
13070         UPDATE systempreferences SET value="United Kingdom" WHERE variable="UsageStatsCountry" AND (value="England" OR value="UK");
13071     });
13072     $dbh->do(q{
13073         UPDATE systempreferences SET value="Spain" WHERE variable="UsageStatsCountry" AND value="España";
13074     });
13075     $dbh->do(q{
13076         UPDATE systempreferences SET value="Greece" WHERE variable="UsageStatsCountry" AND value="GR";
13077     });
13078     $dbh->do(q{
13079         UPDATE systempreferences SET value="Ireland" WHERE variable="UsageStatsCountry" AND value="Irelanbd";
13080     });
13081     $dbh->do(q{
13082         UPDATE systempreferences SET value="Mexico" WHERE variable="UsageStatsCountry" AND value="México";
13083     });
13084     $dbh->do(q{
13085         UPDATE systempreferences SET value="Peru" WHERE variable="UsageStatsCountry" AND value="Perú";
13086     });
13087     $dbh->do(q{
13088         UPDATE systempreferences SET value="Dominican Rep." WHERE variable="UsageStatsCountry" AND value="República Dominicana";
13089     });
13090     $dbh->do(q{
13091         UPDATE systempreferences SET value="Trinidad & Tob." WHERE variable="UsageStatsCountry" AND value="Trinidad";
13092     });
13093     $dbh->do(q{
13094         UPDATE systempreferences SET value="Turkey" WHERE variable="UsageStatsCountry" AND value="Türkiye";
13095     });
13096     $dbh->do(q{
13097         UPDATE systempreferences SET value="USA" WHERE variable="UsageStatsCountry" AND (value="United States" OR value="United States of America" OR value="US");
13098     });
13099     $dbh->do(q{
13100         UPDATE systempreferences SET value="Zimbabwe" WHERE variable="UsageStatsCountry" AND value="Zimbabbwe";
13101     });
13102
13103     print "Upgrade to $DBversion done (Bug 14707 - Change UsageStatsCountry from free text to a dropdown list)\n";
13104     SetVersion($DBversion);
13105 }
13106
13107 $DBversion = "16.06.00.030";
13108 if ( CheckVersion($DBversion) ) {
13109     $dbh->do(q{
13110         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
13111         ('OPACHoldingsDefaultSortField','first_column','first_column|homebranch|holdingbranch','Default sort field for the holdings table at the OPAC','choice');
13112     });
13113
13114     print "Upgrade to $DBversion done (Bug 16552 - Add the ability to change the default holdings sort)\n";
13115     SetVersion($DBversion);
13116 }
13117
13118 $DBversion = "16.06.00.031";
13119 if ( CheckVersion($DBversion) ) {
13120     $dbh->do(q{
13121         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');
13122     });
13123
13124     print "Upgrade to $DBversion done (Bug 16273 - Prevent selfregistration from printing the borrower password and filling the logging form)\n";
13125     SetVersion($DBversion);
13126 }
13127
13128 $DBversion = "16.06.00.032";
13129 if ( CheckVersion($DBversion) ) {
13130     $dbh->do(q{
13131         UPDATE marc_subfield_structure SET authorised_value="WITHDRAWN" WHERE authorised_value="WTHDRAWN";
13132     });
13133
13134     print "Upgrade to $DBversion done (Bug 17357 - WTHDRAWN is still used in installer files)\n";
13135     SetVersion($DBversion);
13136 }
13137
13138
13139 $DBversion = "16.06.00.033";
13140 if ( CheckVersion($DBversion) ) {
13141     $dbh->do(q{
13142         CREATE TABLE authorised_value_categories (
13143         category_name VARCHAR(32) NOT NULL,
13144         primary key (category_name)
13145         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13146         });
13147 ## Add authorised value categories
13148     $dbh->do(q{
13149     INSERT INTO authorised_value_categories (category_name )
13150     SELECT DISTINCT category FROM authorised_values;
13151     });
13152     
13153 ## Add special categories
13154     $dbh->do(q{
13155     INSERT IGNORE INTO authorised_value_categories( category_name )
13156     VALUES
13157     ('Asort1'),
13158     ('Asort2'),
13159     ('Bsort1'),
13160     ('Bsort2'),
13161     ('SUGGEST'),
13162     ('DAMAGED'),
13163     ('LOST'),
13164     ('REPORT_GROUP'),
13165     ('REPORT_SUBGROUP'),
13166     ('DEPARTMENT'),
13167     ('TERM'),
13168     ('SUGGEST_STATUS'),
13169     ('ITEMTYPECAT');
13170     });
13171
13172 ## Add very special categories
13173     $dbh->do(q{
13174     INSERT IGNORE INTO authorised_value_categories( category_name )
13175     VALUES
13176     ('branches'),
13177     ('itemtypes'),
13178     ('cn_source');
13179     });
13180
13181     $dbh->do(q{
13182     INSERT IGNORE INTO authorised_value_categories( category_name )
13183     VALUES
13184     ('WITHDRAWN'),
13185     ('RESTRICTED'),
13186     ('NOT_LOAN'),
13187     ('CCODE'),
13188     ('LOC'),
13189     ('STACK');
13190     });
13191
13192 ## Update the FK
13193     $dbh->do(q{
13194     ALTER TABLE items_search_fields
13195     DROP FOREIGN KEY items_search_fields_authorised_values_category;
13196     });
13197
13198     $dbh->do(q{
13199     ALTER TABLE items_search_fields
13200     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;
13201     });
13202
13203     $dbh->do(q{
13204     ALTER TABLE authorised_values
13205     ADD CONSTRAINT `authorised_values_authorised_values_category` FOREIGN KEY (`category`) REFERENCES `authorised_value_categories` (`category_name`) ON DELETE CASCADE ON UPDATE CASCADE;
13206     });
13207
13208     $dbh->do(q{
13209             INSERT IGNORE INTO authorised_value_categories( category_name ) SELECT DISTINCT(authorised_value) FROM marc_subfield_structure;
13210             });
13211
13212     $dbh->do(q{
13213             UPDATE marc_subfield_structure SET authorised_value = NULL WHERE authorised_value = '';
13214             });
13215
13216     # 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)
13217     my $table_sth = $dbh->prepare(qq|SHOW CREATE TABLE marc_subfield_structure|);
13218     $table_sth->execute;
13219     my @table = $table_sth->fetchrow_array;
13220     if ( $table[1] !~ /COLLATE=utf8_unicode_ci/ and $table[1] !~ /COLLATE=utf8mb4_unicode_ci/ ) { #catches utf8mb4 collated tables
13221         $dbh->do(qq|ALTER TABLE marc_subfield_structure CHARACTER SET utf8 COLLATE utf8_unicode_ci|);
13222     }
13223     $dbh->do(q{
13224             ALTER TABLE marc_subfield_structure
13225             MODIFY COLUMN authorised_value VARCHAR(32) DEFAULT NULL,
13226             ADD CONSTRAINT marc_subfield_structure_ibfk_1 FOREIGN KEY (authorised_value) REFERENCES authorised_value_categories (category_name) ON UPDATE CASCADE ON DELETE SET NULL;
13227             });
13228
13229       print "Upgrade to $DBversion done (Bug 17216 - Add a new table to store authorized value categories)\n";
13230       SetVersion($DBversion);
13231 }
13232
13233 $DBversion = "16.06.00.034";
13234 if ( CheckVersion($DBversion) ) {
13235     $dbh->do(q{
13236         ALTER TABLE biblioitems DROP COLUMN marc;
13237     });
13238     $dbh->do(q{
13239         ALTER TABLE deletedbiblioitems DROP COLUMN marc;
13240     });
13241
13242     print "Upgrade to $DBversion done (Bug 10455 - remove redundant 'biblioitems.marc' field)\n";
13243     SetVersion($DBversion);
13244 }
13245
13246 $DBversion = '16.06.00.035';
13247 if ( CheckVersion($DBversion) ) {
13248     $dbh->do(q{
13249         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
13250          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'
13251          FROM systempreferences WHERE variable='AllowItemsOnHoldCheckout';
13252     });
13253
13254     print "Upgrade to $DBversion done (Bug 15131: Give SCO separate control for AllowItemsOnHoldCheckout)\n";
13255     SetVersion($DBversion);
13256 }
13257
13258 $DBversion = '16.06.00.036';
13259 if ( CheckVersion($DBversion) ) {
13260     $dbh->do(q{
13261         CREATE TABLE IF NOT EXISTS `housebound_profile` (
13262           `borrowernumber` int(11) NOT NULL, -- Number of the borrower associated with this profile.
13263           `day` text NOT NULL,  -- The preferred day of the week for delivery.
13264           `frequency` text NOT NULL, -- The Authorised_Value definining the pattern for delivery.
13265           `fav_itemtypes` text default NULL, -- Free text describing preferred itemtypes.
13266           `fav_subjects` text default NULL, -- Free text describing preferred subjects.
13267           `fav_authors` text default NULL, -- Free text describing preferred authors.
13268           `referral` text default NULL, -- Free text indicating how the borrower was added to the service.
13269           `notes` text default NULL, -- Free text for additional notes.
13270           PRIMARY KEY  (`borrowernumber`),
13271           CONSTRAINT `housebound_profile_bnfk`
13272             FOREIGN KEY (`borrowernumber`)
13273             REFERENCES `borrowers` (`borrowernumber`)
13274             ON UPDATE CASCADE ON DELETE CASCADE
13275         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13276     });
13277     $dbh->do(q{
13278         CREATE TABLE IF NOT EXISTS `housebound_visit` (
13279           `id` int(11) NOT NULL auto_increment, -- ID of the visit.
13280           `borrowernumber` int(11) NOT NULL, -- Number of the borrower, & the profile, linked to this visit.
13281           `appointment_date` date default NULL, -- Date of visit.
13282           `day_segment` varchar(10),  -- Rough time frame: 'morning', 'afternoon' 'evening'
13283           `chooser_brwnumber` int(11) default NULL, -- Number of the borrower to choose items  for delivery.
13284           `deliverer_brwnumber` int(11) default NULL, -- Number of the borrower to deliver items.
13285           PRIMARY KEY  (`id`),
13286           CONSTRAINT `houseboundvisit_bnfk`
13287             FOREIGN KEY (`borrowernumber`)
13288             REFERENCES `housebound_profile` (`borrowernumber`)
13289             ON UPDATE CASCADE ON DELETE CASCADE,
13290           CONSTRAINT `houseboundvisit_bnfk_1`
13291             FOREIGN KEY (`chooser_brwnumber`)
13292             REFERENCES `borrowers` (`borrowernumber`)
13293             ON UPDATE CASCADE ON DELETE CASCADE,
13294           CONSTRAINT `houseboundvisit_bnfk_2`
13295             FOREIGN KEY (`deliverer_brwnumber`)
13296             REFERENCES `borrowers` (`borrowernumber`)
13297             ON UPDATE CASCADE ON DELETE CASCADE
13298         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13299     });
13300     $dbh->do(q{
13301         CREATE TABLE IF NOT EXISTS `housebound_role` (
13302           `borrowernumber_id` int(11) NOT NULL, -- borrowernumber link
13303           `housebound_chooser` tinyint(1) NOT NULL DEFAULT 0, -- set to 1 to indicate this patron is a housebound chooser volunteer
13304           `housebound_deliverer` tinyint(1) NOT NULL DEFAULT 0, -- set to 1 to indicate this patron is a housebound deliverer volunteer
13305           PRIMARY KEY (`borrowernumber_id`),
13306           CONSTRAINT `houseboundrole_bnfk`
13307             FOREIGN KEY (`borrowernumber_id`)
13308             REFERENCES `borrowers` (`borrowernumber`)
13309             ON UPDATE CASCADE ON DELETE CASCADE
13310         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13311     });
13312     $dbh->do(q{
13313         INSERT IGNORE INTO systempreferences
13314                (variable,value,options,explanation,type) VALUES
13315                ('HouseboundModule',0,'',
13316                'If ON, enable housebound module functionality.','YesNo');
13317     });
13318     $dbh->do(q{
13319         INSERT IGNORE INTO authorised_value_categories( category_name ) VALUES
13320             ('HSBND_FREQ');
13321     });
13322     $dbh->do(q{
13323         INSERT IGNORE INTO authorised_values (category, authorised_value, lib) VALUES
13324                ('HSBND_FREQ','EW','Every week');
13325     });
13326
13327     print "Upgrade to $DBversion done (Bug 5670 - Housebound Readers Module)\n";
13328     SetVersion($DBversion);
13329 }
13330
13331 $DBversion = "16.06.00.037";
13332 if ( CheckVersion($DBversion) ) {
13333     $dbh->do(q{
13334         ALTER TABLE `issuingrules` ADD `article_requests` ENUM( 'no', 'yes', 'bib_only', 'item_only' ) NOT NULL DEFAULT 'no' AFTER `opacitemholds`;
13335     });
13336     $dbh->do(q{
13337         INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES
13338             ('ArticleRequests', '0', NULL, 'Enables the article request feature', 'YesNo'),
13339             ('ArticleRequestsMandatoryFields', '', NULL, 'Comma delimited list of required fields for bibs where article requests rule = ''yes''', 'multiple'),
13340             ('ArticleRequestsMandatoryFieldsItemsOnly', '', NULL, 'Comma delimited list of required fields for bibs where article requests rule = ''item_only''', 'multiple'),
13341             ('ArticleRequestsMandatoryFieldsRecordOnly', '', NULL, 'Comma delimited list of required fields for bibs where article requests rule = ''bib_only''', 'multiple');
13342     });
13343     $dbh->do(q{
13344         CREATE TABLE IF NOT EXISTS `article_requests` (
13345           `id` int(11) NOT NULL AUTO_INCREMENT,
13346           `borrowernumber` int(11) NOT NULL,
13347           `biblionumber` int(11) NOT NULL,
13348           `itemnumber` int(11) DEFAULT NULL,
13349           `branchcode` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
13350           `title` text,
13351           `author` text,
13352           `volume` text,
13353           `issue` text,
13354           `date` text,
13355           `pages` text,
13356           `chapters` text,
13357           `patron_notes` text,
13358           `status` enum('PENDING','PROCESSING','COMPLETED','CANCELED') NOT NULL DEFAULT 'PENDING',
13359           `notes` text,
13360           `created_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
13361           `updated_on` timestamp NULL DEFAULT NULL,
13362           PRIMARY KEY (`id`),
13363           KEY `borrowernumber` (`borrowernumber`),
13364           KEY `biblionumber` (`biblionumber`),
13365           KEY `itemnumber` (`itemnumber`),
13366           KEY `branchcode` (`branchcode`),
13367           CONSTRAINT `article_requests_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
13368           CONSTRAINT `article_requests_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
13369           CONSTRAINT `article_requests_ibfk_3` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE SET NULL ON UPDATE CASCADE,
13370           CONSTRAINT `article_requests_ibfk_4` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE SET NULL ON UPDATE CASCADE
13371         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13372     });
13373     $dbh->do(q{
13374         INSERT INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`) VALUES
13375         ('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'),
13376         ('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'),
13377         ('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'),
13378         ('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'),
13379         ('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');
13380     });
13381
13382     print "Upgrade to $DBversion done (Bug 14610 - Add ability to place article requests in Koha)\n";
13383     SetVersion($DBversion);
13384 }
13385
13386 $DBversion = '16.06.00.038';
13387 if ( CheckVersion($DBversion) ) {
13388     $dbh->do(q{
13389         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');
13390     });
13391
13392     print "Upgrade to $DBversion done (Bug 14874 - Add ability to search for patrons by date of birth from checkout and patron quick searches)\n";
13393     SetVersion($DBversion);
13394 }
13395
13396 $DBversion = "16.06.00.039";
13397 if ( CheckVersion($DBversion) ) {
13398
13399     my $sth = $dbh->prepare(q{
13400         SELECT s.itemnumber, i.itype, b.itemtype
13401         FROM
13402          ( SELECT DISTINCT itemnumber
13403            FROM statistics
13404            WHERE ( type = "return" OR type = "localuse" ) AND
13405                  itemtype IS NULL
13406          ) s
13407         LEFT JOIN
13408          ( SELECT itemnumber,biblionumber, itype
13409              FROM items
13410            UNION
13411            SELECT itemnumber,biblionumber, itype
13412              FROM deleteditems
13413          ) i
13414         ON (s.itemnumber=i.itemnumber)
13415         LEFT JOIN
13416          ( SELECT biblionumber, itemtype
13417              FROM biblioitems
13418            UNION
13419            SELECT biblionumber, itemtype
13420              FROM deletedbiblioitems
13421          ) b
13422         ON (i.biblionumber=b.biblionumber);
13423     });
13424     $sth->execute();
13425
13426     my $update_sth = $dbh->prepare(q{
13427         UPDATE statistics
13428         SET itemtype=?
13429         WHERE itemnumber=? AND itemtype IS NULL
13430     });
13431     my $ilevel_itypes = C4::Context->preference('item-level_itypes');
13432
13433     while ( my ($itemnumber,$item_itype,$biblio_itype) = $sth->fetchrow_array ) {
13434
13435         my $effective_itemtype = $ilevel_itypes
13436                                     ? $item_itype // $biblio_itype
13437                                     : $biblio_itype;
13438         warn "item-level_itypes set but no itype defined for item ($itemnumber)"
13439             if $ilevel_itypes and !defined $item_itype;
13440         $update_sth->execute( $effective_itemtype, $itemnumber );
13441     }
13442
13443     print "Upgrade to $DBversion done (Bug 14598: itemtype is not set on statistics by C4::Circulation::AddReturn)\n";
13444     SetVersion($DBversion);
13445 }
13446
13447 $DBversion = '16.06.00.040';
13448 if ( CheckVersion($DBversion) ) {
13449     $dbh->do(q{
13450         ALTER TABLE `aqcontacts` ADD `orderacquisition` BOOLEAN NOT NULL DEFAULT 0 AFTER `notes`;
13451     });
13452     $dbh->do(q{
13453         INSERT IGNORE INTO `letter` (module, code, name, title, content, message_transport_type) VALUES
13454         ('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');
13455     });
13456
13457     print "Upgrade to $DBversion done (Bug 5260 - Add option to send an order by e-mail to the acquisition module)\n";
13458     SetVersion($DBversion);
13459 }
13460
13461 $DBversion = '16.06.00.041';
13462 if ( CheckVersion($DBversion) ) {
13463     $dbh->do(q{
13464         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')
13465     });
13466
13467     print "Upgrade to $DBversion done (Bug 14629 - Add aggressive ISSN matching feature equivalent to the aggressive ISBN matcher)\n";
13468     SetVersion($DBversion);
13469 }
13470
13471 $DBversion = '16.06.00.042';
13472 if ( CheckVersion($DBversion) ) {
13473     $dbh->do(q|
13474         ALTER TABLE aqorders
13475             ADD COLUMN unitprice_tax_excluded decimal(28,6) default NULL AFTER unitprice,
13476             ADD COLUMN unitprice_tax_included decimal(28,6) default NULL AFTER unitprice_tax_excluded,
13477             ADD COLUMN rrp_tax_excluded decimal(28,6) default NULL AFTER rrp,
13478             ADD COLUMN rrp_tax_included decimal(28,6) default NULL AFTER rrp_tax_excluded,
13479             ADD COLUMN ecost_tax_excluded decimal(28,6) default NULL AFTER ecost,
13480             ADD COLUMN ecost_tax_included decimal(28,6) default NULL AFTER ecost_tax_excluded,
13481             ADD COLUMN tax_value decimal(6,4) default NULL AFTER gstrate
13482     |);
13483
13484     # rename gstrate with tax_rate
13485     $dbh->do(q|ALTER TABLE aqorders CHANGE COLUMN gstrate tax_rate decimal(6,4) DEFAULT NULL|);
13486     $dbh->do(q|ALTER TABLE aqbooksellers CHANGE COLUMN gstrate tax_rate decimal(6,4) DEFAULT NULL|);
13487
13488     # Fill the new columns
13489     my $orders = $dbh->selectall_arrayref(q|
13490         SELECT * FROM aqorders
13491     |, { Slice => {} } );
13492
13493     my $sth_update_order = $dbh->prepare(q|
13494         UPDATE aqorders
13495         SET unitprice_tax_excluded = ?,
13496             unitprice_tax_included = ?,
13497             rrp_tax_excluded = ?,
13498             rrp_tax_included = ?,
13499             ecost_tax_excluded = ?,
13500             ecost_tax_included = ?,
13501             tax_value = ?
13502         WHERE ordernumber = ?
13503     |);
13504
13505     my $sth_get_bookseller = $dbh->prepare(q|
13506         SELECT aqbooksellers.*
13507         FROM aqbooksellers
13508         LEFT JOIN aqbasket ON aqbasket.booksellerid = aqbooksellers.id
13509         LEFT JOIN aqorders ON aqorders.basketno = aqbasket.basketno
13510         WHERE ordernumber = ?
13511     |);
13512
13513     require Number::Format;
13514     my $format = Number::Format->new;
13515     my $precision = 2;
13516     for my $order ( @$orders ) {
13517         $sth_get_bookseller->execute( $order->{ordernumber} );
13518         my ( $bookseller ) = $sth_get_bookseller->fetchrow_hashref;
13519         $order->{rrp}   = $format->round( $order->{rrp}, $precision );
13520         $order->{ecost} = $format->round( $order->{ecost}, $precision );
13521         $order->{tax_rate} ||= 0 ; # tax_rate can be NULL in DB
13522         # Ordering
13523         if ( $bookseller->{listincgst} ) {
13524             $order->{rrp_tax_included} = $order->{rrp};
13525             $order->{rrp_tax_excluded} = $format->round(
13526                 $order->{rrp_tax_included} / ( 1 + $order->{tax_rate} ), $precision );
13527             $order->{ecost_tax_included} = $order->{ecost};
13528             $order->{ecost_tax_excluded} = $format->round(
13529                 $order->{ecost} / ( 1 + $order->{tax_rate} ), $precision );
13530         }
13531         else {
13532             $order->{rrp_tax_excluded} = $order->{rrp};
13533             $order->{rrp_tax_included} = $format->round(
13534                 $order->{rrp} * ( 1 + $order->{tax_rate} ), $precision );
13535             $order->{ecost_tax_excluded} = $order->{ecost};
13536             $order->{ecost_tax_included} = $format->round(
13537                 $order->{ecost} * ( 1 + $order->{tax_rate} ), $precision );
13538         }
13539
13540         #receiving
13541         if ( $bookseller->{listincgst} ) {
13542             $order->{unitprice_tax_included} = $format->round( $order->{unitprice}, $precision );
13543             $order->{unitprice_tax_excluded} = $format->round(
13544               $order->{unitprice_tax_included} / ( 1 + $order->{tax_rate} ), $precision );
13545         }
13546         else {
13547             $order->{unitprice_tax_excluded} = $format->round( $order->{unitprice}, $precision );
13548             $order->{unitprice_tax_included} = $format->round(
13549               $order->{unitprice_tax_excluded} * ( 1 + $order->{tax_rate} ), $precision );
13550         }
13551
13552         # If the order is received, the tax is calculated from the unit price
13553         if ( $order->{orderstatus} eq 'complete' ) {
13554             $order->{tax_value} = $format->round(
13555               ( $order->{unitprice_tax_included} - $order->{unitprice_tax_excluded} )
13556               * $order->{quantity}, $precision );
13557         } else {
13558             # otherwise the ecost is used
13559             $order->{tax_value} = $format->round(
13560                 ( $order->{ecost_tax_included} - $order->{ecost_tax_excluded} ) *
13561                   $order->{quantity}, $precision );
13562         }
13563
13564         $sth_update_order->execute(
13565             $order->{unitprice_tax_excluded},
13566             $order->{unitprice_tax_included},
13567             $order->{rrp_tax_excluded},
13568             $order->{rrp_tax_included},
13569             $order->{ecost_tax_excluded},
13570             $order->{ecost_tax_included},
13571             $order->{tax_value},
13572             $order->{ordernumber},
13573         );
13574     }
13575
13576     print "Upgrade to $DBversion done (Bug 13321 - Tax and prices calculation need to be fixed)\n";
13577     SetVersion($DBversion);
13578 }
13579
13580 $DBversion = '16.06.00.043';
13581 if ( CheckVersion($DBversion) ) {
13582     # Add the new columns
13583     $dbh->do(q|
13584         ALTER TABLE aqorders
13585             ADD COLUMN tax_rate_on_ordering   decimal(6,4) default NULL AFTER tax_rate,
13586             ADD COLUMN tax_rate_on_receiving  decimal(6,4) default NULL AFTER tax_rate_on_ordering,
13587             ADD COLUMN tax_value_on_ordering  decimal(28,6) default NULL AFTER tax_value,
13588             ADD COLUMN tax_value_on_receiving decimal(28,6) default NULL AFTER tax_value_on_ordering
13589     |);
13590
13591     my $orders = $dbh->selectall_arrayref(q|
13592         SELECT * FROM aqorders
13593     |, { Slice => {} } );
13594
13595     my $sth_update_order = $dbh->prepare(q|
13596         UPDATE aqorders
13597         SET tax_rate_on_ordering = tax_rate,
13598             tax_rate_on_receiving = tax_rate,
13599             tax_value_on_ordering = ?,
13600             tax_value_on_receiving = ?
13601         WHERE ordernumber = ?
13602     |);
13603
13604     for my $order (@$orders) {
13605         my $tax_value_on_ordering =
13606           $order->{quantity} *
13607           $order->{ecost_tax_excluded} *
13608           $order->{tax_rate};
13609
13610         my $tax_value_on_receiving =
13611           ( defined $order->{unitprice_tax_excluded} )
13612           ? $order->{quantity} * $order->{unitprice_tax_excluded} * $order->{tax_rate}
13613           : undef;
13614
13615         $sth_update_order->execute( $tax_value_on_ordering,
13616             $tax_value_on_receiving, $order->{ordernumber} );
13617     }
13618
13619     # Remove the old columns
13620     $dbh->do(q|
13621         ALTER TABLE aqorders
13622             CHANGE COLUMN tax_value tax_value_bak  decimal(28,6) default NULL,
13623             CHANGE COLUMN tax_rate tax_rate_bak decimal(6,4) default NULL
13624     |);
13625
13626     print "Upgrade to $DBversion done (Bug 13323 - Change the tax rate on receiving)\n";
13627     SetVersion($DBversion);
13628 }
13629
13630 $DBversion = '16.06.00.044';
13631 if ( CheckVersion($DBversion) ) {
13632     $dbh->do(q{
13633         ALTER TABLE `messages`
13634         ADD `manager_id` int(11) NULL,
13635         ADD FOREIGN KEY (`manager_id`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL;
13636     });
13637
13638     print "Upgrade to $DBversion done (Bug 17397 - Show name of librarian who created circulation message)\n";
13639     SetVersion($DBversion);
13640 }
13641
13642 $DBversion = '16.06.00.045';
13643 if ( CheckVersion($DBversion) ) {
13644     $dbh->do(q{
13645         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";
13646     });
13647
13648     print "Upgrade to $DBversion done (Bug 17443 - Make possible to renew patron by later of expiry and current date)\n";
13649     SetVersion($DBversion);
13650 }
13651
13652 $DBversion = '16.06.00.046';
13653 if ( CheckVersion($DBversion) ) {
13654     $dbh->do(q{
13655         ALTER TABLE issuingrules ADD COLUMN no_auto_renewal_after INT(4) DEFAULT NULL AFTER auto_renew;
13656     });
13657
13658     print "Upgrade to $DBversion done (Bug 15581 - Add a circ rule to not allow auto-renewals after defined loan period)\n";
13659     SetVersion($DBversion);
13660 }
13661
13662 $DBversion = '16.06.00.047';
13663 if ( CheckVersion($DBversion) ) {
13664     $dbh->do(q{
13665         UPDATE language_descriptions SET description = 'Čeština' WHERE subtag = 'cs' AND type = 'language' AND lang = 'cs'
13666     });
13667
13668     print "Upgrade to $DBversion done (Bug 17518: Displayed language name for Czech is wrong)\n";
13669     SetVersion($DBversion);
13670 }
13671
13672 $DBversion = '16.06.00.048';
13673 if( CheckVersion( $DBversion ) ) {
13674     $dbh->do(q|
13675         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
13676         (13, 'upload_general_files', 'Upload any file'),
13677         (13, 'upload_manage', 'Manage uploaded files');
13678     |);
13679
13680     # Update user_permissions for current users (check count in uploaded_files)
13681     # Note 9 == edit_catalogue and 13 == tools
13682     # We do not insert if someone is superlibrarian, does not have edit_catalogue,
13683     # or already has all tools
13684     $dbh->do(q|
13685         INSERT IGNORE INTO user_permissions (borrowernumber, module_bit, code)
13686         SELECT borrowernumber, 13, 'upload_general_files'
13687         FROM borrowers bo
13688         WHERE flags<>1 AND flags & POW(2,13) = 0 AND
13689             ( flags & POW(2,9) > 0 OR (
13690                 SELECT COUNT(*) FROM user_permissions
13691                 WHERE borrowernumber=bo.borrowernumber AND module_bit=9 ) > 0 )
13692             AND ( SELECT COUNT(*) FROM uploaded_files ) > 0;
13693     |);
13694
13695     SetVersion( $DBversion );
13696     print "Upgrade to $DBversion done (Bug 17663 - Forgotten userpermissions)\n";
13697 }
13698
13699 $DBversion = '16.06.00.049';
13700 if( CheckVersion( $DBversion ) ) {
13701     $dbh->do(q|
13702         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) 
13703         VALUES ('ReplytoDefault',  '',  NULL,  'The default email address to be set as replyto.',  'Free');
13704     |);
13705
13706     $dbh->do(q|
13707         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
13708         VALUES ('ReturnpathDefault',  '',  NULL,  'The default email address to be set as return-path',  'Free');
13709     |);
13710
13711     SetVersion( $DBversion );
13712     print "Upgrade to $DBversion done (Bug 17391 - ReturnpathDefault and ReplyToDefault missing from syspref.sql)\n";
13713 }
13714
13715 $DBversion = "16.06.00.050";
13716 if ( CheckVersion($DBversion) ) {
13717
13718     # If index issn_idx still exists, we assume that dbrev 3.15.00.049 failed,
13719     # and we repeat it (partially).
13720     # Note: the db rev only pertains to biblioitems and is not needed for
13721     # deletedbiblioitems.
13722
13723     my $temp = $dbh->selectall_arrayref( "SHOW INDEXES FROM biblioitems WHERE key_name = 'issn_idx'" );
13724
13725     if( @$temp > 0 ) {
13726         $dbh->do( "ALTER TABLE biblioitems DROP INDEX isbn" );
13727         $dbh->do( "ALTER TABLE biblioitems DROP INDEX issn" );
13728         $dbh->do( "ALTER TABLE biblioitems DROP INDEX issn_idx" );
13729         $dbh->do( "ALTER TABLE biblioitems CHANGE isbn isbn MEDIUMTEXT NULL DEFAULT NULL, CHANGE issn issn MEDIUMTEXT NULL DEFAULT NULL" );
13730         $dbh->do( "ALTER TABLE biblioitems ADD INDEX isbn ( isbn ( 255 ) ), ADD INDEX issn ( issn ( 255 ) )" );
13731         print "Upgrade to $DBversion done (Bug 8835). Removed issn_idx.\n";
13732     } else {
13733         print "Upgrade to $DBversion done (Bug 8835). Everything is fine.\n";
13734     }
13735
13736     SetVersion($DBversion);
13737 }
13738
13739 $DBversion = "16.11.00.000";
13740 if ( CheckVersion($DBversion) ) {
13741     print "Upgrade to $DBversion done (Koha 16.11)\n";
13742     SetVersion($DBversion);
13743 }
13744
13745 $DBversion = "16.12.00.000";
13746 if ( CheckVersion($DBversion) ) {
13747     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";
13748     SetVersion($DBversion);
13749 }
13750
13751 $DBversion = "16.12.00.001";
13752 if ( CheckVersion($DBversion) ) {
13753     $dbh->do(q{
13754         ALTER TABLE borrower_modifications
13755         ADD COLUMN extended_attributes text DEFAULT NULL
13756         AFTER privacy
13757     });
13758
13759     print "Upgrade to $DBversion done (Bug 17767 - Let Koha::Patron::Modification handle extended attributes)\n";
13760     SetVersion($DBversion);
13761 }
13762
13763 $DBversion = '16.12.00.002';
13764 if ( CheckVersion($DBversion) ) {
13765     unless (column_exists( 'branchtransfers', 'branchtransfer_id' )
13766         and index_exists( 'branchtransfers', 'PRIMARY' ) )
13767     {
13768         $dbh->do(
13769             "ALTER TABLE branchtransfers
13770                  ADD COLUMN branchtransfer_id int(12) NOT NULL auto_increment FIRST, ADD CONSTRAINT PRIMARY KEY (branchtransfer_id);"
13771         );
13772     }
13773
13774     SetVersion($DBversion);
13775     print "Upgrade to $DBversion done (Bug 14187 - branchtransfer needs a primary key (id) for DBIx and common sense.)\n";
13776 }
13777
13778 $DBversion = '16.12.00.003';
13779 if ( CheckVersion($DBversion) ) {
13780     $dbh->do(q{DELETE FROM systempreferences WHERE variable="Persona"});
13781     SetVersion($DBversion);
13782     print "Upgrade to $DBversion done (Bug 17486 - Remove 'Mozilla Persona' as an authentication method)\n";
13783 }
13784
13785 $DBversion = '16.12.00.004';
13786 if ( CheckVersion($DBversion) ) {
13787     $dbh->do(q{
13788         CREATE TABLE biblio_metadata (
13789             `id` INT(11) NOT NULL AUTO_INCREMENT,
13790             `biblionumber` INT(11) NOT NULL,
13791             `format` VARCHAR(16) NOT NULL,
13792             `marcflavour` VARCHAR(16) NOT NULL,
13793             `metadata` LONGTEXT NOT NULL,
13794             PRIMARY KEY(id),
13795             UNIQUE KEY `biblio_metadata_uniq_key` (`biblionumber`,`format`,`marcflavour`),
13796             CONSTRAINT `biblio_metadata_fk_1` FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
13797         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13798     });
13799     $dbh->do(q{
13800         CREATE TABLE deletedbiblio_metadata (
13801             `id` INT(11) NOT NULL AUTO_INCREMENT,
13802             `biblionumber` INT(11) NOT NULL,
13803             `format` VARCHAR(16) NOT NULL,
13804             `marcflavour` VARCHAR(16) NOT NULL,
13805             `metadata` LONGTEXT NOT NULL,
13806             PRIMARY KEY(id),
13807             UNIQUE KEY `deletedbiblio_metadata_uniq_key` (`biblionumber`,`format`,`marcflavour`),
13808             CONSTRAINT `deletedbiblio_metadata_fk_1` FOREIGN KEY (biblionumber) REFERENCES deletedbiblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
13809         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13810     });
13811     $dbh->do(q{
13812         INSERT INTO biblio_metadata ( biblionumber, format, marcflavour, metadata ) SELECT biblionumber, 'marcxml', 'CHANGEME', marcxml FROM biblioitems;
13813     });
13814     $dbh->do(q{
13815         INSERT INTO deletedbiblio_metadata ( biblionumber, format, marcflavour, metadata ) SELECT biblionumber, 'marcxml', 'CHANGEME', marcxml FROM deletedbiblioitems;
13816     });
13817     $dbh->do(q{
13818         UPDATE biblio_metadata SET marcflavour = (SELECT value FROM systempreferences WHERE variable="marcflavour");
13819     });
13820     $dbh->do(q{
13821         UPDATE deletedbiblio_metadata SET marcflavour = (SELECT value FROM systempreferences WHERE variable="marcflavour");
13822     });
13823     $dbh->do(q{
13824         ALTER TABLE biblioitems DROP COLUMN marcxml;
13825     });
13826     $dbh->do(q{
13827         ALTER TABLE deletedbiblioitems DROP COLUMN marcxml;
13828     });
13829     SetVersion($DBversion);
13830     print "Upgrade to $DBversion done (Bug 17196 - Move marcxml out of the biblioitems table)\n";
13831 }
13832
13833 $DBversion = '16.12.00.005';
13834 if( CheckVersion( $DBversion ) ) {
13835     $dbh->do( "INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('AuthorityMergeMode','loose','loose|strict','Authority merge mode','Choice')");
13836
13837     SetVersion( $DBversion );
13838     print "Upgrade to $DBversion done (Bug 17913 - AuthorityMergeMode)\n";
13839 }
13840
13841 $DBversion = "16.12.00.006";
13842 if ( CheckVersion($DBversion) ) {
13843     unless (     column_exists( 'borrower_attributes', 'id' )
13844              and index_exists( 'borrower_attributes', 'PRIMARY' ) )
13845     {
13846         $dbh->do(q{
13847             ALTER TABLE `borrower_attributes`
13848                 ADD `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
13849         });
13850     }
13851
13852     print "Upgrade to $DBversion done (Bug 17813: Table borrower_attributes needs a primary key\n";
13853     SetVersion($DBversion);
13854 }
13855
13856 $DBversion = "16.12.00.007";
13857 if( CheckVersion( $DBversion ) ) {
13858
13859     if ( column_exists('opac_news', 'new' ) ) {
13860         $dbh->do(q|ALTER TABLE opac_news CHANGE COLUMN new content text NOT NULL|);
13861     }
13862
13863     $dbh->do(q|
13864         UPDATE letter SET content = REPLACE(content, "<<opac_news.new>>", "<<opac_news.content>>") WHERE content LIKE "%<<opac_news.new>>%"
13865     |);
13866
13867     SetVersion( $DBversion );
13868     print "Upgrade to $DBversion done (Bug 17960 - Rename opac_news with opac_news.content (template notices have been updated!))\n";
13869 }
13870
13871 $DBversion = "16.12.00.008";
13872 if( CheckVersion( $DBversion ) ) {
13873     $dbh->do(q{
13874         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
13875         ('MarcItemFieldsToOrder','','Set the mapping values for new item records created from a MARC record in a staged file. In a YAML format.', NULL, 'textarea');
13876     });
13877
13878     SetVersion( $DBversion );
13879     print "Upgrade to $DBversion done (Bug 15503 - Grab Item Information from Order Files)\n";
13880 }
13881
13882 $DBversion = "16.12.00.009";
13883 if( CheckVersion( $DBversion ) ) {
13884     $dbh->do(q{
13885         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
13886         ('OPACHoldsIfAvailableAtPickup','1','','Allow to pickup up holds at libraries where the item is available','YesNo');
13887     });
13888
13889     $dbh->do(q{
13890         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
13891         ('OPACHoldsIfAvailableAtPickupExceptions','','','List the patron categories not affected by OPACHoldsIfAvailableAtPickup if off','Free');
13892     });
13893
13894     SetVersion( $DBversion );
13895     print "Upgrade to $DBversion done (Bug 17453 - Inter-site holds improvement)\n";
13896 }
13897
13898 $DBversion = "16.12.00.010";
13899 if( CheckVersion( $DBversion ) ) {
13900     $dbh->do(q{
13901         ALTER TABLE borrowers ADD overdrive_auth_token text default NULL AFTER lastseen;
13902     });
13903
13904     $dbh->do(q{
13905         ALTER TABLE deletedborrowers ADD overdrive_auth_token text default NULL AFTER lastseen;
13906     });
13907
13908     $dbh->do(q{
13909         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
13910         VALUES ('OverDriveCirculation','0','Enable client to see their OverDrive account','','YesNo');
13911     });
13912
13913     SetVersion( $DBversion );
13914     print "Upgrade to $DBversion done (Bug 16034 - Integration with OverDrive Patron API)\n";
13915 }
13916
13917 $DBversion = "16.12.00.011";
13918 if( CheckVersion( $DBversion ) ) {
13919     $dbh->do(q{
13920         ALTER TABLE search_field CHANGE COLUMN type type ENUM('', 'string', 'date', 'number', 'boolean', 'sum') NOT NULL
13921         COMMENT 'what type of data this holds, relevant when storing it in the search engine';
13922     });
13923
13924     SetVersion( $DBversion );
13925     print "Upgrade to $DBversion done (Bug 17260 - updatedatabase.pl fails on invalid entries in ENUM and BOOLEAN columns)\n";
13926 }
13927
13928 $DBversion = "16.12.00.012";
13929 if( CheckVersion( $DBversion ) ) {
13930     $dbh->do(q{
13931         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`)
13932         VALUES ('OpacNewsLibrarySelect', '0', '', 'Show selector for branches on OPAC news page', 'YesNo');
13933     });
13934
13935     SetVersion( $DBversion );
13936     print "Upgrade to $DBversion done (Bug 14764 - Add OPAC News branch selector)\n";
13937 }
13938
13939 $DBversion = "16.12.00.013";
13940 if( CheckVersion( $DBversion ) ) {
13941     $dbh->do(q{
13942         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
13943         VALUES ('CircSidebar','0','','Activate or deactivate the navigation sidebar on all Circulation pages','YesNo');
13944     });
13945
13946     SetVersion( $DBversion );
13947     print "Upgrade to $DBversion done (Bug 16530 - Add a circ sidebar navigation menu)\n";
13948 }
13949
13950 $DBversion = "16.12.00.014";
13951 if( CheckVersion( $DBversion ) ) {
13952     $dbh->do(q{
13953             INSERT INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
13954             ('LoadSearchHistoryToTheFirstLoggedUser', '1', NULL, 'If ON, the next user will automatically get the last searches in his history', 'YesNo');
13955             });
13956             SetVersion( $DBversion );
13957             print "Upgrade to $DBversion done (Bug 8010 - Search history can be added to the wrong patron)\n";
13958             }
13959
13960 $DBversion = "16.12.00.015";
13961 if( CheckVersion( $DBversion ) ) {
13962     unless( column_exists( 'branches', 'geolocation' ) ) {
13963         $dbh->do(q|
13964                 ALTER TABLE branches ADD COLUMN geolocation VARCHAR(255) DEFAULT NULL after opac_info
13965                 |);
13966     }
13967
13968     $dbh->do(q|
13969             INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type ) VALUES ('UsageStatsGeolocation', '', NULL, 'Geolocation of the main library', 'Free');
13970             |);
13971     $dbh->do(q|
13972             INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type ) VALUES ('UsageStatsLibrariesInfo', '', NULL, 'Share libraries information', 'YesNo');
13973             |);
13974     $dbh->do(q|
13975             INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type ) VALUES ('UsageStatsPublicID', '', NULL, 'Public ID for Hea website', 'Free');
13976             |);
13977         
13978         SetVersion( $DBversion );
13979     print "Upgrade to $DBversion done (Bug 18066 - Hea version 2)\n";
13980 }
13981
13982 $DBversion = "16.12.00.016";
13983 if ( CheckVersion($DBversion) ) {
13984     unless ( column_exists( 'borrower_attribute_types', 'opac_editable' ) )
13985     {
13986         $dbh->do(q{
13987             ALTER TABLE borrower_attribute_types
13988                 ADD COLUMN `opac_editable` tinyint(1) NOT NULL default 0 AFTER `opac_display`
13989         });
13990     }
13991
13992     print "Upgrade to $DBversion done (Bug 13757: Make patron attributes editable in the opac if set to 'editable in OPAC)'\n";
13993     SetVersion($DBversion);
13994 }
13995
13996 $DBversion = "16.12.00.017";
13997 if ( CheckVersion($DBversion) ) {
13998     $dbh->do(q{
13999         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
14000         VALUES ('CumulativeRestrictionPeriods',  0,  NULL,  'Cumulate the restriction periods instead of keeping the highest',  'YesNo')
14001     });
14002
14003     print "Upgrade to $DBversion done (Bug 14146 - Additional days are not added to restriction period when checking-in several overdues for same patron)'\n";
14004     SetVersion($DBversion);
14005 }
14006
14007 $DBversion = "16.12.00.018";
14008 if ( CheckVersion($DBversion) ) {
14009     $dbh->do(q{
14010         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
14011             SELECT 'ExportCircHistory', COUNT(*), NULL, "Display the export circulation options",  'YesNo'
14012             FROM systempreferences
14013             WHERE ( variable = 'ExportRemoveFields' AND value != "" AND value IS NOT NULL )
14014                 OR ( variable = 'ExportWithCsvProfile' AND value != "" AND value IS NOT NULL );
14015     });
14016
14017     $dbh->do(q{
14018         DELETE FROM systempreferences WHERE variable="ExportWithCsvProfile";
14019     });
14020
14021     print "Upgrade to $DBversion done (Bug 15498 - Replace ExportWithCsvProfile with ExportCircHistory)'\n";
14022     SetVersion($DBversion);
14023 }
14024
14025 $DBversion = "16.12.00.019";
14026 if( CheckVersion( $DBversion ) ) {
14027     if ( column_exists( 'issues', 'return' ) ) {
14028         $dbh->do(q|ALTER TABLE issues DROP column `return`|);
14029     }
14030
14031     if ( column_exists( 'old_issues', 'return' ) ) {
14032         $dbh->do(q|ALTER TABLE old_issues DROP column `return`|);
14033     }
14034
14035     SetVersion( $DBversion );
14036     print "Upgrade to $DBversion done (Bug 18173 - Remove issues.return DB field)\n";
14037 }
14038
14039 $DBversion = "16.12.00.020";
14040 if( CheckVersion( $DBversion ) ) {
14041     $dbh->do(q{
14042         UPDATE systempreferences SET options="any_time_is_placed|not_always|any_time_is_collected" WHERE variable="HoldFeeMode";
14043     });
14044
14045     $dbh->do(q{
14046         UPDATE systempreferences SET value="any_time_is_placed" WHERE variable="HoldFeeMode" AND value="always";
14047     });
14048
14049     SetVersion( $DBversion );
14050     print "Upgrade to $DBversion done (Bug 17560 - Hold fee placement at point of checkout)\n";
14051 }
14052
14053 $DBversion = "16.12.00.021";
14054 if( CheckVersion( $DBversion ) ) {
14055     $dbh->do(q{
14056         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14057         ('RenewalLog','0','','If ON, log information about renewals','YesNo');
14058     });
14059
14060     SetVersion( $DBversion );
14061     print "Upgrade to $DBversion done (Bug 17708 - Renewal log seems empty)\n";
14062 }
14063
14064 $DBversion = "16.12.00.022";
14065 if( CheckVersion( $DBversion ) ) {
14066     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";
14067     SetVersion( $DBversion );
14068     print "Upgrade to $DBversion done (Bug 17866 - Change sender for serial claim notifications)\n";
14069 }
14070
14071 $DBversion = '16.12.00.023';
14072 if( CheckVersion( $DBversion ) ) {
14073     my $oldval = C4::Context->preference('dontmerge');
14074     my $newval = $oldval ? 0 : 50;
14075
14076     # Remove dontmerge, add AuthorityMergeLimit
14077     $dbh->do(q{
14078         DELETE FROM systempreferences WHERE variable = 'dontmerge';
14079     });
14080     $dbh->do(qq{
14081         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');
14082     });
14083
14084     $dbh->do(q{
14085         ALTER TABLE need_merge_authorities
14086             ADD COLUMN authid_new BIGINT AFTER authid,
14087             ADD COLUMN reportxml text AFTER authid_new,
14088             ADD COLUMN timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
14089     });
14090
14091     $dbh->do(q{
14092         UPDATE need_merge_authorities SET authid_new=authid WHERE done <> 1
14093     });
14094
14095     SetVersion( $DBversion );
14096     if( $newval == 0 ) {
14097         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";
14098     }
14099     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";
14100     print "Upgrade to $DBversion done (Bug 9988 - Add AuthorityMergeLimit)\n";
14101 }
14102
14103 $DBversion = '16.12.00.024';
14104 if( CheckVersion( $DBversion ) ) {
14105     $dbh->do(q{
14106         UPDATE systempreferences SET variable="NoticeBcc" WHERE variable="OverdueNoticeBcc";
14107     });
14108
14109     SetVersion( $DBversion );
14110     print "Upgrade to $DBversion done (Bug 14537 - The system preference 'OverdueNoticeBcc' is mis-named.)\n";
14111 }
14112
14113 $DBversion = '16.12.00.025';
14114 if( CheckVersion( $DBversion ) ) {
14115     $dbh->do(q|
14116         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
14117         VALUES ('UploadPurgeTemporaryFilesDays','',NULL,'If not empty, number of days used when automatically deleting temporary uploads','integer');
14118     |);
14119
14120     my ( $cnt ) = $dbh->selectrow_array( "SELECT COUNT(*) FROM uploaded_files WHERE permanent IS NULL or permanent=0" );
14121     if( $cnt ) {
14122         print "NOTE: You have $cnt temporary uploads. You could benefit from setting pref UploadPurgeTemporaryFilesDays now to automatically delete them.\n";
14123     }
14124
14125     SetVersion( $DBversion );
14126     print "Upgrade to $DBversion done (Bug 17669 - Introduce preference for deleting temporary uploads)\n";
14127 }
14128
14129 $DBversion = '16.12.00.026';
14130 if( CheckVersion( $DBversion ) ) {
14131
14132     # In order to be overcomplete, we check if the situation is what we expect
14133     if( !index_exists( 'serialitems', 'PRIMARY' ) ) {
14134         if( index_exists( 'serialitems', 'serialitemsidx' ) ) {
14135             $dbh->do(q|
14136                 ALTER TABLE serialitems ADD PRIMARY KEY (itemnumber), DROP INDEX serialitemsidx;
14137             |);
14138         } else {
14139             $dbh->do(q|ALTER TABLE serialitems ADD PRIMARY KEY (itemnumber)|);
14140         }
14141     }
14142
14143     SetVersion( $DBversion );
14144     print "Upgrade to $DBversion done (Bug 18427 - Add a primary key to serialitems)\n";
14145 }
14146
14147 $DBversion = '16.12.00.027';
14148 if( CheckVersion( $DBversion ) ) {
14149
14150     $dbh->do(q{
14151         CREATE TABLE IF NOT EXISTS club_templates (
14152           id int(11) NOT NULL AUTO_INCREMENT,
14153           `name` tinytext NOT NULL,
14154           description text,
14155           is_enrollable_from_opac tinyint(1) NOT NULL DEFAULT '0',
14156           is_email_required tinyint(1) NOT NULL DEFAULT '0',
14157           branchcode varchar(10) NULL DEFAULT NULL,
14158           date_created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
14159           date_updated timestamp NULL DEFAULT NULL,
14160           is_deletable tinyint(1) NOT NULL DEFAULT '1',
14161           PRIMARY KEY (id),
14162           KEY ct_branchcode (branchcode),
14163           CONSTRAINT `club_templates_ibfk_1` FOREIGN KEY (branchcode) REFERENCES `branches` (branchcode) ON DELETE CASCADE ON UPDATE CASCADE
14164         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14165     });
14166
14167     $dbh->do(q{
14168         CREATE TABLE IF NOT EXISTS clubs (
14169           id int(11) NOT NULL AUTO_INCREMENT,
14170           club_template_id int(11) NOT NULL,
14171           `name` tinytext NOT NULL,
14172           description text,
14173           date_start date DEFAULT NULL,
14174           date_end date DEFAULT NULL,
14175           branchcode varchar(10) NULL DEFAULT NULL,
14176           date_created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
14177           date_updated timestamp NULL DEFAULT NULL,
14178           PRIMARY KEY (id),
14179           KEY club_template_id (club_template_id),
14180           KEY branchcode (branchcode),
14181           CONSTRAINT clubs_ibfk_1 FOREIGN KEY (club_template_id) REFERENCES club_templates (id) ON DELETE CASCADE ON UPDATE CASCADE,
14182           CONSTRAINT clubs_ibfk_2 FOREIGN KEY (branchcode) REFERENCES branches (branchcode)
14183         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14184     });
14185
14186     $dbh->do(q{
14187         CREATE TABLE IF NOT EXISTS club_enrollments (
14188           id int(11) NOT NULL AUTO_INCREMENT,
14189           club_id int(11) NOT NULL,
14190           borrowernumber int(11) NOT NULL,
14191           date_enrolled timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
14192           date_canceled timestamp NULL DEFAULT NULL,
14193           date_created timestamp NULL DEFAULT NULL,
14194           date_updated timestamp NULL DEFAULT NULL,
14195           branchcode varchar(10) NULL DEFAULT NULL,
14196           PRIMARY KEY (id),
14197           KEY club_id (club_id),
14198           KEY borrowernumber (borrowernumber),
14199           KEY branchcode (branchcode),
14200           CONSTRAINT club_enrollments_ibfk_1 FOREIGN KEY (club_id) REFERENCES clubs (id) ON DELETE CASCADE ON UPDATE CASCADE,
14201           CONSTRAINT club_enrollments_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE,
14202           CONSTRAINT club_enrollments_ibfk_3 FOREIGN KEY (branchcode) REFERENCES branches (branchcode) ON DELETE SET NULL ON UPDATE CASCADE
14203         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14204     });
14205
14206     $dbh->do(q{
14207         CREATE TABLE IF NOT EXISTS club_template_enrollment_fields (
14208           id int(11) NOT NULL AUTO_INCREMENT,
14209           club_template_id int(11) NOT NULL,
14210           `name` tinytext NOT NULL,
14211           description text,
14212           authorised_value_category varchar(16) DEFAULT NULL,
14213           PRIMARY KEY (id),
14214           KEY club_template_id (club_template_id),
14215           CONSTRAINT club_template_enrollment_fields_ibfk_1 FOREIGN KEY (club_template_id) REFERENCES club_templates (id) ON DELETE CASCADE ON UPDATE CASCADE
14216         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14217     });
14218
14219     $dbh->do(q{
14220         CREATE TABLE IF NOT EXISTS club_enrollment_fields (
14221           id int(11) NOT NULL AUTO_INCREMENT,
14222           club_enrollment_id int(11) NOT NULL,
14223           club_template_enrollment_field_id int(11) NOT NULL,
14224           `value` text NOT NULL,
14225           PRIMARY KEY (id),
14226           KEY club_enrollment_id (club_enrollment_id),
14227           KEY club_template_enrollment_field_id (club_template_enrollment_field_id),
14228           CONSTRAINT club_enrollment_fields_ibfk_1 FOREIGN KEY (club_enrollment_id) REFERENCES club_enrollments (id) ON DELETE CASCADE ON UPDATE CASCADE,
14229           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
14230         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14231     });
14232
14233     $dbh->do(q{
14234         CREATE TABLE IF NOT EXISTS club_template_fields (
14235           id int(11) NOT NULL AUTO_INCREMENT,
14236           club_template_id int(11) NOT NULL,
14237           `name` tinytext NOT NULL,
14238           description text,
14239           authorised_value_category varchar(16) DEFAULT NULL,
14240           PRIMARY KEY (id),
14241           KEY club_template_id (club_template_id),
14242           CONSTRAINT club_template_fields_ibfk_1 FOREIGN KEY (club_template_id) REFERENCES club_templates (id) ON DELETE CASCADE ON UPDATE CASCADE
14243         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14244     });
14245
14246     $dbh->do(q{
14247         CREATE TABLE IF NOT EXISTS club_fields (
14248           id int(11) NOT NULL AUTO_INCREMENT,
14249           club_template_field_id int(11) NOT NULL,
14250           club_id int(11) NOT NULL,
14251           `value` text,
14252           PRIMARY KEY (id),
14253           KEY club_template_field_id (club_template_field_id),
14254           KEY club_id (club_id),
14255           CONSTRAINT club_fields_ibfk_3 FOREIGN KEY (club_template_field_id) REFERENCES club_template_fields (id) ON DELETE CASCADE ON UPDATE CASCADE,
14256           CONSTRAINT club_fields_ibfk_4 FOREIGN KEY (club_id) REFERENCES clubs (id) ON DELETE CASCADE ON UPDATE CASCADE
14257         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14258     });
14259
14260     $dbh->do(q{
14261         INSERT IGNORE INTO userflags (bit, flag, flagdesc, defaulton) VALUES (21, 'clubs', 'Patron clubs', '0');
14262     });
14263
14264     $dbh->do(q{
14265         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
14266            (21, 'edit_templates', 'Create and update club templates'),
14267            (21, 'edit_clubs', 'Create and update clubs'),
14268            (21, 'enroll', 'Enroll patrons in clubs')
14269         ;
14270     });
14271
14272     SetVersion( $DBversion );
14273     print "Upgrade to $DBversion done (Bug 12461 - Add patron clubs feature)\n";
14274 }
14275
14276 $DBversion = '16.12.00.028';
14277 if( CheckVersion( $DBversion ) ) {
14278     $dbh->do(q{
14279         UPDATE systempreferences  SET options = 'us|de|fr' WHERE variable = 'AddressFormat';
14280     });
14281
14282     SetVersion( $DBversion );
14283     print "Upgrade to $DBversion done (Bug 18110 - Adds FR to the syspref AddressFormat)\n";
14284 }
14285
14286 $DBversion = '16.12.00.029';
14287 if( CheckVersion( $DBversion ) ) {
14288     unless( column_exists( 'issues', 'note' ) ) {
14289         $dbh->do(q|ALTER TABLE issues ADD note mediumtext default NULL AFTER onsite_checkout|);
14290     }
14291     unless( column_exists( 'issues', 'notedate' ) ) {
14292         $dbh->do(q|ALTER TABLE issues ADD notedate datetime default NULL AFTER note|);
14293     }
14294     unless( column_exists( 'old_issues', 'note' ) ) {
14295         $dbh->do(q|ALTER TABLE old_issues ADD note mediumtext default NULL AFTER onsite_checkout|);
14296     }
14297     unless( column_exists( 'old_issues', 'notedate' ) ) {
14298         $dbh->do(q|ALTER TABLE old_issues ADD notedate datetime default NULL AFTER note|);
14299     }
14300
14301     $dbh->do(q|
14302         INSERT IGNORE INTO letter (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`)
14303         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');
14304     |);
14305
14306     $dbh->do(q|
14307         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`,`type`)
14308         VALUES ('AllowCheckoutNotes', '0', NULL, 'Allow patrons to submit notes about checked out items.','YesNo');
14309     |);
14310
14311     SetVersion( $DBversion );
14312     print "Upgrade to $DBversion done (Bug 14224: Add column issues.note and issues.notedate)\n";
14313 }
14314
14315 $DBversion = '16.12.00.030';
14316 if( CheckVersion( $DBversion ) ) {
14317     unless( column_exists( 'issuingrules', 'no_auto_renewal_after_hard_limit' ) ) {
14318         $dbh->do(q{
14319             ALTER TABLE issuingrules ADD COLUMN no_auto_renewal_after_hard_limit DATE DEFAULT NULL AFTER no_auto_renewal_after;
14320         });
14321     }
14322
14323     SetVersion( $DBversion );
14324     print "Upgrade to $DBversion done (Bug 16344 - Add a circ rule to limit the auto renewals given a specific date)\n";
14325 }
14326
14327 $DBversion = '16.12.00.031';
14328 if( CheckVersion( $DBversion ) ) {
14329     if ( !index_exists( 'biblioitems', 'timestamp' ) ) {
14330         $dbh->do("ALTER TABLE biblioitems ADD KEY `timestamp` (`timestamp`);");
14331     }
14332     if ( !index_exists( 'deletedbiblioitems', 'timestamp' ) ) {
14333         $dbh->do("ALTER TABLE deletedbiblioitems ADD KEY `timestamp` (`timestamp`);");
14334     }
14335     if ( !index_exists( 'items', 'timestamp' ) ) {
14336         $dbh->do("ALTER TABLE items ADD KEY `timestamp` (`timestamp`);");
14337     }
14338     if ( !index_exists( 'deleteditems', 'timestamp' ) ) {
14339         $dbh->do("ALTER TABLE deleteditems ADD KEY `timestamp` (`timestamp`);");
14340     }
14341
14342     SetVersion( $DBversion );
14343     print "Upgrade to $DBversion done (Bug 15108: OAI-PMH provider improvements)\n";
14344 }
14345
14346 $DBversion = '16.12.00.032';
14347 if( CheckVersion( $DBversion ) ) {
14348     require Koha::Calendar;
14349
14350     $dbh->do(q{
14351         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) 
14352         VALUES ('ExcludeHolidaysFromMaxPickUpDelay', '0', 'If ON, reserves max pickup delay takes into account the closed days.', NULL, 'Integer');
14353     });
14354
14355     my $waiting_holds = $dbh->selectall_arrayref(q|
14356         SELECT expirationdate, waitingdate, branchcode
14357         FROM reserves
14358         WHERE found = 'W' AND priority = 0
14359     |, { Slice => {} });
14360     my $update_sth = $dbh->prepare(q|
14361         UPDATE reserves
14362         SET expirationdate = ?
14363         WHERE reserve_id = ?
14364     |);
14365     my $max_pickup_delay = C4::Context->preference("ReservesMaxPickUpDelay");
14366     for my $hold ( @$waiting_holds ) {
14367
14368         my $requested_expiration;
14369         if ($hold->{expirationdate}) {
14370             $requested_expiration = dt_from_string($hold->{expirationdate});
14371         }
14372
14373         my $expirationdate = dt_from_string($hold->{waitingdate});
14374         if ( C4::Context->preference("ExcludeHolidaysFromMaxPickUpDelay") ) {
14375             my $calendar = Koha::Calendar->new( branchcode => $hold->{branchcode}, days_mode => C4::Context->preference('useDaysMode') );
14376             $expirationdate = $calendar->days_forward( $expirationdate, $max_pickup_delay );
14377         } else {
14378             $expirationdate->add( days => $max_pickup_delay );
14379         }
14380
14381         my $cmp = $requested_expiration ? DateTime->compare($requested_expiration, $expirationdate) : 0;
14382         $update_sth->execute($cmp == -1 ? $requested_expiration->ymd : $expirationdate->ymd, $hold->{reserve_id});
14383     }
14384
14385     SetVersion( $DBversion );
14386     print "Upgrade to $DBversion done (Bug 12063 - Update reserves.expirationdate)\n";
14387 }
14388
14389 $DBversion = '16.12.00.033';
14390 if( CheckVersion( $DBversion ) ) {
14391
14392     if( !column_exists( 'letter', 'lang' ) ) {
14393         $dbh->do( "ALTER TABLE letter ADD COLUMN lang VARCHAR(25) NOT NULL DEFAULT 'default' AFTER message_transport_type" );
14394     }
14395
14396     if( !column_exists( 'borrowers', 'lang' ) ) {
14397         $dbh->do( "ALTER TABLE borrowers ADD COLUMN lang VARCHAR(25) NOT NULL DEFAULT 'default' AFTER lastseen" );
14398         $dbh->do( "ALTER TABLE deletedborrowers ADD COLUMN lang VARCHAR(25) NOT NULL DEFAULT 'default' AFTER lastseen" );
14399     }
14400
14401     # Add test on existene of this key
14402     $dbh->do( "ALTER TABLE message_transports DROP FOREIGN KEY message_transports_ibfk_3 ");
14403     $dbh->do( "ALTER TABLE letter DROP PRIMARY KEY ");
14404     $dbh->do( "ALTER TABLE letter ADD PRIMARY KEY (`module`, `code`, `branchcode`, `message_transport_type`, `lang`) ");
14405
14406     $dbh->do( "INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
14407         VALUES ('TranslateNotices',  '0',  NULL,  'Allow notices to be translated',  'YesNo') ");
14408
14409     SetVersion( $DBversion );
14410     print "Upgrade to $DBversion done (Bug 17762 - Add columns letter.lang and borrowers.lang to allow translation of notices)\n";
14411 }
14412
14413 $DBversion = '16.12.00.034';
14414 if( CheckVersion( $DBversion ) ) {
14415     $dbh->do(q{
14416         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
14417         VALUES ('OPACFineNoRenewalsBlockAutoRenew','0','','Block/Allow auto renewals if the patron owe more than OPACFineNoRenewals','YesNo')
14418     });
14419
14420     SetVersion( $DBversion );
14421     print "Upgrade to $DBversion done (Bug 15582 - Ability to block auto renewals if the OPACFineNoRenewals amount is reached)\n";
14422 }
14423
14424 $DBversion = '16.12.00.035';
14425 if( CheckVersion( $DBversion ) ) {
14426     if( !column_exists( 'issues', 'auto_renew_error' ) ) {
14427         $dbh->do(q{
14428            ALTER TABLE issues ADD COLUMN auto_renew_error VARCHAR(32) DEFAULT NULL AFTER auto_renew;
14429         });
14430     }
14431
14432     if( !column_exists( 'old_issues', 'auto_renew_error' ) ) {
14433         $dbh->do(q{
14434             ALTER TABLE old_issues ADD COLUMN auto_renew_error VARCHAR(32) DEFAULT NULL AFTER auto_renew;
14435         });
14436     }
14437
14438     $dbh->do(q{
14439             INSERT INTO letter (module, code, name, title, content, message_transport_type) VALUES ('circulation', 'AUTO_RENEWALS', 'Notification of automatic renewal', 'Automatic renewal notice',
14440         "Dear [% borrower.firstname %] [% borrower.surname %],
14441 [% IF checkout.auto_renew_error %]
14442 The following item, [% biblio.title %], has not been renewed because:
14443 [% IF checkout.auto_renew_error == 'too_many' %]
14444 You have reached the maximum number of checkouts possible.
14445 [% ELSIF checkout.auto_renew_error == 'on_reserve' %]
14446 This item is on hold for another patron.
14447 [% ELSIF checkout.auto_renew_error == 'restriction' %]
14448 You are currently restricted.
14449 [% ELSIF checkout.auto_renew_error == 'overdue' %]
14450 You have overdue items.
14451 [% ELSIF checkout.auto_renew_error == 'auto_too_late' %]
14452 It\'s too late to renew this item.
14453 [% ELSIF checkout.auto_renew_error == 'auto_too_much_oweing' %]
14454 Your total unpaid fines are too high.
14455 [% END %]
14456 [% ELSE %]
14457 The following item, [% biblio.title %], has correctly been renewed and is now due on [% checkout.date_due | $KohaDates as_due_date => 1 %]
14458 [% END %]", 'email');
14459     });
14460
14461     SetVersion( $DBversion );
14462     print "Upgrade to $DBversion done (Bug 15705 - Notify the user on auto renewing)\n";
14463 }
14464
14465 $DBversion = '16.12.00.036';
14466 if( CheckVersion( $DBversion ) ) {
14467     $dbh->do(q{
14468         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
14469         VALUES ('NumSavedReports', '20', NULL, 'By default, show this number of saved reports.', 'Integer');
14470     });
14471
14472     SetVersion( $DBversion );
14473     print "Upgrade to $DBversion done (Bug 17465 - Add a System Preference to control number of Saved Reports displayed)\n";
14474 }
14475
14476 $DBversion = '16.12.00.037';
14477 if( CheckVersion( $DBversion ) ) {
14478     $dbh->do( q|
14479         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
14480         VALUES ('FailedLoginAttempts','','','Number of login attempts before lockout the patron account','Integer');
14481     |);
14482
14483     unless( column_exists( 'borrowers', 'login_attempts' ) ) {
14484         $dbh->do(q|
14485             ALTER TABLE borrowers ADD COLUMN login_attempts INT(4) DEFAULT 0 AFTER lastseen
14486         |);
14487         $dbh->do(q|
14488             ALTER TABLE deletedborrowers ADD COLUMN login_attempts INT(4) DEFAULT 0 AFTER lastseen
14489         |);
14490     }
14491
14492     SetVersion( $DBversion );
14493     print "Upgrade to $DBversion done (Bug 18314 - Add FailedLoginAttempts and borrowers.login_attempts)\n";
14494 }
14495
14496 $DBversion = '16.12.00.038';
14497 if( CheckVersion( $DBversion ) ) {
14498     $dbh->do(q{
14499         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14500         ('ExportRemoveFields','',NULL,'List of fields for non export in circulation.pl (separated by a space)','Free');
14501     });
14502
14503     SetVersion( $DBversion );
14504     print "Upgrade to $DBversion done (Bug 18663 - Missing db update for ExportRemoveFields)\n";
14505 }
14506
14507 $DBversion = '16.12.00.039';
14508 if( CheckVersion( $DBversion ) ) {
14509     $dbh->do(q{
14510         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14511         ('TalkingTechItivaPhoneNotification','0',NULL,'If ON, enables Talking Tech I-tiva phone notifications','YesNo');
14512     });
14513
14514     SetVersion( $DBversion );
14515     print "Upgrade to $DBversion done (Bug 18600 - Missing db update for TalkingTechItivaPhoneNotification)\n";
14516 }
14517
14518 $DBversion = '17.05.00.000';
14519 if( CheckVersion( $DBversion ) ) {
14520
14521     SetVersion( $DBversion );
14522     print "Upgrade to $DBversion done (Koha 17.05)\n";
14523 }
14524
14525 $DBversion = '17.06.00.000';
14526 if( CheckVersion( $DBversion ) ) {
14527     SetVersion( $DBversion );
14528     print "Upgrade to $DBversion done (He pai ake te iti i te kore)\n";
14529 }
14530
14531 $DBversion = '17.06.00.001';
14532 if( CheckVersion( $DBversion ) ) {
14533
14534     unless ( column_exists( 'export_format', 'used_for' ) ) {
14535         $dbh->do(q|ALTER TABLE export_format ADD used_for varchar(255) DEFAULT 'export_records' AFTER type|);
14536
14537         $dbh->do(q|UPDATE export_format SET used_for = 'late_issues' WHERE type = 'sql'|);
14538         $dbh->do(q|UPDATE export_format SET used_for = 'export_records' WHERE type = 'marc'|);
14539     }
14540     SetVersion( $DBversion );
14541     print "Upgrade to $DBversion done (Bug 8612 - Add new column export_format.used_for)\n";
14542 }
14543
14544 $DBversion = '17.06.00.002';
14545 if ( CheckVersion($DBversion) ) {
14546
14547     unless ( column_exists('virtualshelves', 'allow_change_from_owner' ) ) {
14548         $dbh->do(q|
14549             ALTER TABLE virtualshelves
14550             ADD COLUMN allow_change_from_owner tinyint(1) default 1,
14551             ADD COLUMN allow_change_from_others tinyint(1) default 0
14552         |);
14553
14554         # Conversion:
14555         # Since we had no readonly lists, change_from_owner is set to true.
14556         # When adding or delete_other was granted, change_from_others is true.
14557         # Note: In my opinion the best choice; there is no exact match.
14558         $dbh->do(q|
14559             UPDATE virtualshelves
14560             SET allow_change_from_owner = 1,
14561                 allow_change_from_others = CASE WHEN allow_add=1 OR allow_delete_other=1 THEN 1 ELSE 0 END
14562         |);
14563
14564         # Remove the old columns
14565         $dbh->do(q|
14566             ALTER TABLE virtualshelves
14567             DROP COLUMN allow_add,
14568             DROP COLUMN allow_delete_own,
14569             DROP COLUMN allow_delete_other
14570         |);
14571     }
14572
14573     SetVersion($DBversion);
14574     print "Upgrade to $DBversion done (Bug 18228 - Alter table virtualshelves to simplify permissions)\n";
14575 }
14576
14577 $DBversion = '17.06.00.003';
14578 if ( CheckVersion($DBversion) ) {
14579
14580     # Fetch all auth types
14581     my $authtypes = $dbh->selectcol_arrayref(q|SELECT authtypecode FROM auth_types|);
14582
14583     if ( grep { $_ eq 'Default' } @$authtypes ) {
14584
14585         # If this exists as an authtypecode, we don't do anything
14586     }
14587     else {
14588         # Replace the incorrect Default by empty string
14589         $dbh->do(q|
14590             UPDATE auth_header SET authtypecode='' WHERE authtypecode='Default'
14591         |);
14592     }
14593
14594     SetVersion($DBversion);
14595     print "Upgrade to $DBversion done (Bug 18801 - Update incorrect Default auth type codes)\n";
14596 }
14597
14598 $DBversion = '17.06.00.004';
14599 if( CheckVersion( $DBversion ) ) {
14600     $dbh->do(q{
14601         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14602         ('GoogleOpenIDConnectAutoRegister',   '0',NULL,' Google OpenID Connect logins to auto-register patrons.','YesNo'),
14603         ('GoogleOpenIDConnectDefaultCategory','','','This category code will be used to create Google OpenID Connect patrons.','Textarea'),
14604         ('GoogleOpenIDConnectDefaultBranch',  '','','This branch code will be used to create Google OpenID Connect patrons.','Textarea');
14605     });
14606
14607     SetVersion( $DBversion );
14608     print "Upgrade to $DBversion done (Bug 16892: Add automatic patron registration via OAuth2 login)\n";
14609 }
14610
14611 $DBversion = '17.06.00.005';
14612 if( CheckVersion( $DBversion ) ) {
14613     $dbh->do(q{
14614         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')
14615         });
14616
14617     SetVersion( $DBversion );
14618     print "Upgrade to $DBversion done (Bug 18718 - Language selector in staff header menu similar to OPAC )\n";
14619 }
14620
14621 $DBversion = '17.06.00.006';
14622 if( CheckVersion( $DBversion ) ) {
14623     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.};
14624     print "\n";
14625
14626     SetVersion( $DBversion );
14627     print "Upgrade to $DBversion done (Bug 18811 - Visibility settings inconsistent between framework and authority editor)\n";
14628 }
14629
14630 $DBversion = '17.06.00.007';
14631 if( CheckVersion( $DBversion ) ) {
14632     if( !column_exists( 'branches', 'marcorgcode' ) ) {
14633         $dbh->do( "ALTER TABLE branches ADD COLUMN marcorgcode VARCHAR(16) default NULL AFTER geolocation" );
14634     }
14635
14636     SetVersion( $DBversion );
14637     print "Upgrade to $DBversion done (Bug 10132 - MARCOrgCode on branch level (branches.marcorgcode))\n";
14638 }
14639
14640 $DBversion = '17.06.00.008';
14641 if( CheckVersion( $DBversion ) ) {
14642     unless ( column_exists( 'borrowers', 'date_renewed' ) ) {
14643         $dbh->do(q{
14644             ALTER TABLE borrowers ADD COLUMN date_renewed DATE NULL DEFAULT NULL AFTER dateexpiry;
14645         });
14646     }
14647
14648     unless ( column_exists( 'deletedborrowers', 'date_renewed' ) ) {
14649         $dbh->do(q{
14650             ALTER TABLE deletedborrowers ADD COLUMN date_renewed DATE NULL DEFAULT NULL AFTER dateexpiry;
14651         });
14652     }
14653
14654     unless ( column_exists( 'borrower_modifications', 'date_renewed' ) ) {
14655         $dbh->do(q{
14656             ALTER TABLE borrower_modifications ADD COLUMN date_renewed DATE NULL DEFAULT NULL AFTER dateexpiry;
14657         });
14658     }
14659
14660     SetVersion( $DBversion );
14661     print "Upgrade to $DBversion done (Bug 6758 - Capture membership renewal date for reporting purposes (borrowers.date_renewed))\n";
14662 }
14663
14664 $DBversion = '17.06.00.009';
14665 if( CheckVersion( $DBversion ) ) {
14666     $dbh->do(q{
14667         ALTER TABLE borrowers MODIFY COLUMN login_attempts int(4) DEFAULT 0 AFTER lang;
14668     });
14669     $dbh->do(q{
14670         ALTER TABLE deletedborrowers MODIFY COLUMN login_attempts int(4) DEFAULT 0 AFTER lang;
14671     });
14672
14673     SetVersion( $DBversion );
14674     print "Upgrade to $DBversion done (Bug 19344 -  Reorder lang and login_attempts in the [deleted]borrowers tables)\n";
14675 }
14676
14677 $DBversion = '17.06.00.010';
14678 if ( CheckVersion($DBversion) ) {
14679     $dbh->do(q{
14680         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
14681         VALUES (
14682             'DefaultCountryField008','','',
14683             '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')
14684     });
14685     SetVersion($DBversion);
14686     print "Upgrade to $DBversion done (Bug 13912 - System preference for default place of publication (country code) for field 008, range 15-17)\n";
14687 }
14688
14689 $DBversion = '17.06.00.011';
14690 if ( CheckVersion($DBversion) ) {
14691     # Drop index that might exist because of bug 5337
14692     if( index_exists('biblioitems', 'ean')) {
14693         $dbh->do(q{ ALTER TABLE biblioitems DROP INDEX ean });
14694     }
14695     if( index_exists('deletedbiblioitems', 'ean')) {
14696         $dbh->do(q{ ALTER TABLE deletedbiblioitems DROP INDEX ean });
14697     }
14698
14699     # Change data type of column
14700     $dbh->do(q{ ALTER TABLE biblioitems MODIFY COLUMN ean MEDIUMTEXT default NULL });
14701     $dbh->do(q{ ALTER TABLE deletedbiblioitems MODIFY COLUMN ean MEDIUMTEXT default NULL });
14702
14703     # Add indexes
14704     $dbh->do(q{ ALTER TABLE biblioitems ADD INDEX ean ( ean(255) )});
14705     $dbh->do(q{ ALTER TABLE deletedbiblioitems ADD INDEX ean ( ean(255 ) )});
14706
14707     SetVersion($DBversion);
14708     print "Upgrade to $DBversion done (Bug 13766 - Make ean mediumtext and add ean indexes)\n";
14709 }
14710
14711 $DBversion = '17.06.00.012';
14712 if( CheckVersion( $DBversion ) ) {
14713     my $where = q|host='clio-db.cc.columbia.edu' AND port=7090|;
14714     my $sql = "SELECT COUNT(*) FROM z3950servers WHERE $where";
14715     my ( $cnt ) = $dbh->selectrow_array( $sql );
14716     if( $cnt ) {
14717         $dbh->do( "DELETE FROM z3950servers WHERE $where" );
14718         print "Removed $cnt Z39.50 target(s) for Columbia University\n";
14719     }
14720
14721     SetVersion( $DBversion );
14722     print "Upgrade to $DBversion done (Bug 19043 - Z39.50 target for Columbia University is no longer publicly available.)\n";
14723 }
14724
14725 $DBversion = '17.06.00.013';
14726 if( CheckVersion( $DBversion ) ) {
14727     $dbh->do( "UPDATE systempreferences SET value = CONCAT('http://', value) WHERE variable = 'staffClientBaseURL' AND value <> '' AND value NOT LIKE 'http%'" );
14728
14729     my ( $staffClientBaseURL_used_in_notices ) = $dbh->selectrow_array(q|
14730         SELECT COUNT(*) FROM letter where content like "%staffClientBaseURL%"
14731     |);
14732     if ( $staffClientBaseURL_used_in_notices ) {
14733         warn "\tYou may need to update one or more notice templates if they contain 'staffClientBaseURL'\n";
14734     }
14735
14736     SetVersion( $DBversion );
14737     print "Upgrade to $DBversion done (Bug 16401 - fix potentialy bad set staffClientBaseURL preference)\n";
14738 }
14739
14740 $DBversion = '17.06.00.014';
14741 if( CheckVersion( $DBversion ) ) {
14742     unless( column_exists('aqbasket','create_items') ){
14743         $dbh->do(q{
14744             ALTER TABLE aqbasket
14745                 ADD COLUMN create_items ENUM('ordering', 'receiving', 'cataloguing') default NULL AFTER is_standing
14746         });
14747     }
14748
14749     SetVersion( $DBversion );
14750     print "Upgrade to $DBversion done (Bug 15685 - Allow creation of items (AcqCreateItem) to be customizable per-basket)\n";
14751 }
14752
14753 $DBversion = '17.06.00.015';
14754 if( CheckVersion( $DBversion ) ) {
14755     $dbh->do(q{
14756         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES
14757         ('SelfCheckoutByLogin','0',NULL,'Have patrons login into the web-based self checkout system with their username/password or their cardnumber','YesNo')
14758     });
14759
14760     SetVersion( $DBversion );
14761     print "Upgrade to $DBversion done (Bug 19186 - Insert system preference SelfCheckoutByLogin if missing)\n";
14762 }
14763
14764 $DBversion = '17.06.00.016';
14765 if( CheckVersion( $DBversion ) ) {
14766     $dbh->do(q{
14767         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
14768         VALUES ('RequireStrongPassword','0','','Require a strong login password for staff and patrons','YesNo');
14769     });
14770
14771     SetVersion( $DBversion );
14772     print "Upgrade to $DBversion done (Bug 18298 - Allow enforcing password complexity (system preference RequireStrongPassword))\n";
14773 }
14774
14775 $DBversion = '17.06.00.017';
14776 if( CheckVersion( $DBversion ) ) {
14777     unless (TableExists('account_offsets')) {
14778         $dbh->do(q{
14779             DROP TABLE IF EXISTS `accountoffsets`;
14780         });
14781
14782         $dbh->do(q{
14783             CREATE TABLE IF NOT EXISTS `account_offset_types` (
14784               `type` varchar(16) NOT NULL, -- The type of offset this is
14785               PRIMARY KEY (`type`)
14786             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14787         });
14788
14789         $dbh->do(q{
14790             CREATE TABLE IF NOT EXISTS `account_offsets` (
14791               `id` int(11) NOT NULL auto_increment, -- unique identifier for each offset
14792               `credit_id` int(11) NULL DEFAULT NULL, -- The id of the accountline the increased the patron's balance
14793               `debit_id` int(11) NULL DEFAULT NULL, -- The id of the accountline that decreased the patron's balance
14794               `type` varchar(16) NOT NULL, -- The type of offset this is
14795               `amount` decimal(26,6) NOT NULL, -- The amount of the change
14796               `created_on` timestamp NOT NULL default CURRENT_TIMESTAMP,
14797               PRIMARY KEY (`id`),
14798               CONSTRAINT `account_offsets_ibfk_p` FOREIGN KEY (`credit_id`) REFERENCES `accountlines` (`accountlines_id`) ON DELETE CASCADE ON UPDATE CASCADE,
14799               CONSTRAINT `account_offsets_ibfk_f` FOREIGN KEY (`debit_id`) REFERENCES `accountlines` (`accountlines_id`) ON DELETE CASCADE ON UPDATE CASCADE,
14800               CONSTRAINT `account_offsets_ibfk_t` FOREIGN KEY (`type`) REFERENCES `account_offset_types` (`type`) ON DELETE CASCADE ON UPDATE CASCADE
14801             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14802         });
14803
14804         $dbh->do(q{
14805             INSERT IGNORE INTO account_offset_types ( type ) VALUES
14806             ('Writeoff'),
14807             ('Payment'),
14808             ('Lost Item'),
14809             ('Processing Fee'),
14810             ('Manual Debit'),
14811             ('Reverse Payment'),
14812             ('Forgiven'),
14813             ('Dropbox'),
14814             ('Rental Fee'),
14815             ('Fine Update'),
14816             ('Fine');
14817         });
14818     }
14819
14820     SetVersion( $DBversion );
14821     print "Upgrade to $DBversion done (Bug 14826 - Resurrect account offsets table (Add new tables account_offsets and account_offset_types))\n";
14822 }
14823
14824 $DBversion = '17.06.00.018';
14825 if( CheckVersion( $DBversion ) ) {
14826     $dbh->do(q{
14827         INSERT IGNORE INTO systempreferences (variable,value,explanation,type) VALUES ('useDefaultReplacementCost',0,'default replacement cost defined in item type','YesNo');
14828     });
14829     $dbh->do(q{
14830         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');
14831     });
14832     $dbh->do(q{
14833         ALTER TABLE `itemtypes` MODIFY COLUMN `rentalcharge` DECIMAL(28,6) NULL DEFAULT NULL;
14834     });
14835     unless ( column_exists( 'itemtypes', 'defaultreplacecost' ) ) {
14836         $dbh->do(q{
14837             ALTER TABLE `itemtypes` ADD `defaultreplacecost` DECIMAL(28,6) NULL DEFAULT NULL AFTER `rentalcharge`;
14838         });
14839     }
14840     unless ( column_exists( 'itemtypes', 'processfee' ) ) {
14841         $dbh->do(q{
14842             ALTER TABLE `itemtypes` ADD `processfee` DECIMAL(28,6) NULL DEFAULT NULL AFTER `defaultreplacecost`;
14843         });
14844
14845     }
14846     SetVersion( $DBversion );
14847     print "Upgrade to $DBversion done (Bug 12768 - Insert system preferences useDefaultReplacementCost and ProcessingFeeNote + Add new columns defaultreplacecost and processfee to the itemtypes table)\n";
14848 }
14849
14850 $DBversion = '17.06.00.019';
14851 if( CheckVersion( $DBversion ) ) {
14852     $dbh->do(q{
14853         INSERT IGNORE INTO account_offset_types ( type ) VALUES ( 'Processing Fee' );
14854     });
14855
14856     SetVersion( $DBversion );
14857     print "Upgrade to $DBversion done (Bug 12768 - Add 'Processing Fee' to the account_offset_types table if missing)\n";
14858 }
14859
14860 $DBversion = '17.06.00.020';
14861 if( CheckVersion( $DBversion ) ) {
14862     $dbh->do(q{
14863         UPDATE systempreferences
14864         SET
14865             variable='OpacLocationOnDetail',
14866             options='holding|home|both|column',
14867             explanation='In the OPAC detail, display the shelving location on its own column or under a library columns.'
14868         WHERE
14869             variable='OpacLocationBranchToDisplayShelving'
14870     });
14871
14872     SetVersion( $DBversion );
14873     print "Upgrade to $DBversion done (Bug 19028: Add 'shelving location' to holdings table in detail page (Rename syspref OpacLocationBranchToDisplayShelving with OpacLocationOnDetail))\n";
14874 }
14875
14876 $DBversion = '17.06.00.021';
14877 if( CheckVersion( $DBversion ) ) {
14878     $dbh->do(q{
14879         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')
14880     });
14881
14882     SetVersion( $DBversion );
14883     print "Upgrade to $DBversion done (Bug 17381 - Add system preference SCOMainUserBlock)\n";
14884 }
14885
14886 $DBversion = '17.06.00.022';
14887 if( CheckVersion( $DBversion ) ) {
14888     my $hide_barcode = C4::Context->preference('OPACShowBarcode') ? 0 : 1;
14889     $dbh->do(q{
14890         DELETE FROM systempreferences
14891         WHERE
14892             variable='OPACShowBarcode'
14893     });
14894
14895     # Configure column visibility if it isn't
14896     $dbh->do(q{
14897         INSERT IGNORE INTO columns_settings
14898             (module,page,tablename,columnname,cannot_be_toggled,is_hidden)
14899         VALUES
14900             ('opac','biblio-detail','holdingst','item_barcode',0,?)
14901     }, undef, $hide_barcode);
14902
14903     SetVersion( $DBversion );
14904     print "Upgrade to $DBversion done (Bug 19038: Remove OPACShowBarcode syspref)\n";
14905 }
14906
14907 $DBversion = '17.06.00.023';
14908 if( CheckVersion( $DBversion ) ) {
14909     $dbh->do(q{
14910         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14911         ('MarkLostItemsAsReturned','1','','Mark items as returned when flagged as lost','YesNo');
14912     });
14913
14914     SetVersion( $DBversion );
14915     print "Upgrade to $DBversion done (Bug 12363 - Add system preference MarkLostItemsAsReturned)\n";
14916 }
14917
14918 $DBversion = '17.06.00.024';
14919 if( CheckVersion( $DBversion ) ) {
14920     $dbh->do(q{
14921         INSERT IGNORE INTO systempreferences (`variable`,`value`,`options`,`explanation`,`type`) VALUES
14922         ('OPACUserSummary', 1, NULL, "Show the summary of a logged in user's checkouts, overdues, holds and fines on the mainpage", 'YesNo');
14923     });
14924
14925     SetVersion( $DBversion );
14926     print "Upgrade to $DBversion done (Bug 2093 - Add system preference OPACUserSummary)\n";
14927 }
14928
14929 $DBversion = '17.06.00.025';
14930 if( CheckVersion( $DBversion ) ) {
14931     $dbh->do(q{
14932         ALTER TABLE borrowers MODIFY cardnumber varchar(32);
14933     });
14934     $dbh->do(q{
14935         ALTER TABLE borrower_modifications MODIFY cardnumber varchar(32);
14936     });
14937     $dbh->do(q{
14938         ALTER TABLE deletedborrowers MODIFY cardnumber varchar(32);
14939     });
14940     $dbh->do(q{
14941         ALTER TABLE pending_offline_operations MODIFY cardnumber varchar(32);
14942     });
14943     $dbh->do(q{
14944         ALTER TABLE tmp_holdsqueue MODIFY cardnumber varchar(32);
14945     });
14946
14947     SetVersion( $DBversion );
14948     print "Upgrade to $DBversion done (Bug 13178 - Increase cardnumber fields to VARCHAR(32))\n";
14949 }
14950
14951 $DBversion = '17.06.00.026';
14952 if( CheckVersion( $DBversion ) ) {
14953     $dbh->do(q{
14954         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14955         ('BlockReturnOfLostItems','0','0','If enabled, items that are marked as lost cannot be returned.','YesNo');
14956     });
14957
14958     SetVersion( $DBversion );
14959     print "Upgrade to $DBversion done (Bug 10748 - Add system preference BlockReturnOfLostItems)\n";
14960 }
14961
14962 $DBversion = '17.06.00.027';
14963 if( CheckVersion( $DBversion ) ) {
14964     if ( !column_exists( 'statistics', 'location' ) ) {
14965         $dbh->do('ALTER TABLE statistics ADD COLUMN location VARCHAR(80) default NULL AFTER itemtype');
14966     }
14967
14968     SetVersion($DBversion);
14969     print "Upgrade to $DBversion done (Bug 18882 - Add location code to statistics table for checkouts and renewals)\n";
14970 }
14971
14972 $DBversion = '17.06.00.028';
14973 if( CheckVersion( $DBversion ) ) {
14974     if ( !TableExists( 'illrequests' ) ) {
14975         $dbh->do(q{
14976             CREATE TABLE illrequests (
14977                illrequest_id serial PRIMARY KEY,           -- ILL request number
14978                borrowernumber integer DEFAULT NULL,        -- Patron associated with request
14979                biblio_id integer DEFAULT NULL,             -- Potential bib linked to request
14980                branchcode varchar(50) NOT NULL,            -- The branch associated with the request
14981                status varchar(50) DEFAULT NULL,            -- Current Koha status of request
14982                placed date DEFAULT NULL,                   -- Date the request was placed
14983                replied date DEFAULT NULL,                  -- Last API response
14984                updated timestamp DEFAULT CURRENT_TIMESTAMP -- Last modification to request
14985                  ON UPDATE CURRENT_TIMESTAMP,
14986                completed date DEFAULT NULL,                -- Date the request was completed
14987                medium varchar(30) DEFAULT NULL,            -- The Koha request type
14988                accessurl varchar(500) DEFAULT NULL,        -- Potential URL for accessing item
14989                cost varchar(20) DEFAULT NULL,              -- Cost of request
14990                notesopac text DEFAULT NULL,                -- Patron notes attached to request
14991                notesstaff text DEFAULT NULL,               -- Staff notes attached to request
14992                orderid varchar(50) DEFAULT NULL,           -- Backend id attached to request
14993                backend varchar(20) DEFAULT NULL,           -- The backend used to create request
14994                CONSTRAINT `illrequests_bnfk`
14995                  FOREIGN KEY (`borrowernumber`)
14996                  REFERENCES `borrowers` (`borrowernumber`)
14997                  ON UPDATE CASCADE ON DELETE CASCADE,
14998                CONSTRAINT `illrequests_bcfk_2`
14999                  FOREIGN KEY (`branchcode`)
15000                  REFERENCES `branches` (`branchcode`)
15001                  ON UPDATE CASCADE ON DELETE CASCADE
15002            ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
15003         });
15004     }
15005
15006     if ( !TableExists( 'illrequestattributes' ) ) {
15007         $dbh->do(q{
15008             CREATE TABLE illrequestattributes (
15009                 illrequest_id bigint(20) unsigned NOT NULL, -- ILL request number
15010                 type varchar(200) NOT NULL,                 -- API ILL property name
15011                 value text NOT NULL,                        -- API ILL property value
15012                 PRIMARY KEY  (`illrequest_id`,`type`),
15013                 CONSTRAINT `illrequestattributes_ifk`
15014                   FOREIGN KEY (illrequest_id)
15015                   REFERENCES `illrequests` (`illrequest_id`)
15016                   ON UPDATE CASCADE ON DELETE CASCADE
15017             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
15018         });
15019     }
15020
15021     # System preferences
15022     $dbh->do(q{
15023         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
15024             ('ILLModule','0','If ON, enables the interlibrary loans module.','','YesNo');
15025     });
15026
15027     $dbh->do(q{
15028         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
15029             ('ILLModuleCopyrightClearance','','70|10','Enter text to enable the copyright clearance stage of request creation. Text will be displayed','Textarea');
15030     });
15031     # userflags
15032     $dbh->do(q{
15033         INSERT IGNORE INTO userflags (bit,flag,flagdesc,defaulton) VALUES
15034             (22,'ill','The Interlibrary Loans Module',0);
15035     });
15036
15037     SetVersion( $DBversion );
15038     print "Upgrade to $DBversion done (Bug 7317 - Add an Interlibrary Loan Module to Circulation and OPAC)\n";
15039 }
15040
15041 $DBversion = '17.11.00.000';
15042 if( CheckVersion( $DBversion ) ) {
15043     SetVersion( $DBversion );
15044     print "Upgrade to $DBversion done (Koha 17.11)\n";
15045 }
15046
15047 $DBversion = '17.12.00.000';
15048 if( CheckVersion( $DBversion ) ) {
15049     SetVersion( $DBversion );
15050     print "Upgrade to $DBversion done (Tē tōia, tē haumatia)\n";
15051 }
15052
15053 $DBversion = '17.12.00.001';
15054 if( CheckVersion( $DBversion ) ) {
15055     foreach my $table (qw(biblio_metadata deletedbiblio_metadata)) {
15056         if (!column_exists($table, 'timestamp')) {
15057             $dbh->do(qq{
15058                 ALTER TABLE `$table`
15059                 ADD COLUMN `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER `metadata`,
15060                 ADD KEY `timestamp` (`timestamp`)
15061             });
15062             $dbh->do(qq{
15063                 UPDATE $table metadata
15064                     LEFT JOIN biblioitems ON (biblioitems.biblionumber = metadata.biblionumber)
15065                     LEFT JOIN biblio ON (biblio.biblionumber = metadata.biblionumber)
15066                 SET metadata.timestamp = GREATEST(biblioitems.timestamp, biblio.timestamp);
15067             });
15068         }
15069     }
15070
15071     SetVersion( $DBversion );
15072     print "Upgrade to $DBversion done (Bug 19724 - Add [deleted]biblio_metadata.timestamp)\n";
15073 }
15074
15075 $DBversion = '17.12.00.002';
15076 if( CheckVersion( $DBversion ) ) {
15077
15078     my $msss = $dbh->selectall_arrayref(q|
15079         SELECT kohafield, tagfield, tagsubfield, frameworkcode
15080         FROM marc_subfield_structure
15081         WHERE   frameworkcode != ''
15082     |, { Slice => {} });
15083
15084
15085     my $sth = $dbh->prepare(q|
15086         SELECT kohafield
15087         FROM marc_subfield_structure
15088         WHERE frameworkcode = ''
15089         AND tagfield = ?
15090         AND tagsubfield = ?
15091     |);
15092
15093     my @exceptions;
15094     for my $mss ( @$msss ) {
15095         $sth->execute($mss->{tagfield}, $mss->{tagsubfield} );
15096         my ( $default_kohafield ) = $sth->fetchrow_array();
15097         if( $mss->{kohafield} ) {
15098             push @exceptions, { frameworkcode => $mss->{frameworkcode}, tagfield => $mss->{tagfield}, tagsubfield => $mss->{tagsubfield}, kohafield => $mss->{kohafield} } if not $default_kohafield or $default_kohafield ne $mss->{kohafield};
15099         } else {
15100             push @exceptions, { frameworkcode => $mss->{frameworkcode}, tagfield => $mss->{tagfield}, tagsubfield => $mss->{tagsubfield}, kohafield => q{} } if $default_kohafield;
15101         }
15102     }
15103
15104     if (@exceptions) {
15105         print "WARNING: The Default framework is now considered as authoritative for Koha to MARC mappings. We have found that your additional frameworks contained "
15106           . scalar(@exceptions)
15107           . " 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";
15108         for my $exception (@exceptions) {
15109             print "Field "
15110               . $exception->{tagfield} . '$'
15111               . $exception->{tagsubfield}
15112               . " in framework "
15113               . $exception->{frameworkcode} . ': ';
15114             if ( $exception->{kohafield} ) {
15115                 print "Mapping to "
15116                   . $exception->{kohafield}
15117                   . " has been adjusted.\n";
15118             }
15119             else {
15120                 print "Mapping has been reset.\n";
15121             }
15122         }
15123
15124         # Sync kohafield
15125
15126         # Clear the destination frameworks first
15127         $dbh->do(q|
15128             UPDATE marc_subfield_structure
15129             SET kohafield = NULL
15130             WHERE   frameworkcode > ''
15131                 AND     Kohafield > ''
15132         |);
15133
15134         # Now copy from Default
15135         my $msss = $dbh->selectall_arrayref(q|
15136             SELECT kohafield, tagfield, tagsubfield
15137             FROM marc_subfield_structure
15138             WHERE   frameworkcode = ''
15139                 AND     kohafield > ''
15140         |, { Slice => {} });
15141         my $sth = $dbh->prepare(q|
15142             UPDATE marc_subfield_structure
15143             SET kohafield = ?
15144             WHERE frameworkcode > ''
15145             AND tagfield = ?
15146             AND tagsubfield = ?
15147         |);
15148         for my $mss (@$msss) {
15149             $sth->execute( $mss->{kohafield}, $mss->{tagfield},
15150                 $mss->{tagsubfield} );
15151         }
15152
15153         # Clear the cache
15154         my @frameworkcodes = $dbh->selectall_arrayref(q|
15155             SELECT frameworkcode FROM biblio_framework WHERE frameworkcode > ''
15156         |);
15157         for my $frameworkcode (@frameworkcodes) {
15158             Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
15159         }
15160         Koha::Caches->get_instance->clear_from_cache("default_value_for_mod_marc-");
15161     }
15162
15163     SetVersion( $DBversion );
15164     print "Upgrade to $DBversion done (Bug 19096 - Make Default authoritative for Koha to MARC mappings)\n";
15165 }
15166
15167 $DBversion = '17.12.00.003';
15168 if( CheckVersion( $DBversion ) ) {
15169     $dbh->do(q|DROP TABLE IF EXISTS notifys|);
15170
15171     if( column_exists( 'accountlines', 'notify_id' ) ) {
15172         $dbh->do(q|ALTER TABLE accountlines DROP COLUMN notify_id|);
15173         $dbh->do(q|ALTER TABLE accountlines DROP COLUMN notify_level|);
15174     }
15175
15176     SetVersion( $DBversion );
15177     print "Upgrade to $DBversion done (Bug 10021 - Drop notifys-related table and columns)\n";
15178 }
15179
15180 $DBversion = '17.12.00.004';
15181 if( CheckVersion( $DBversion ) ) {
15182     $dbh->do(q{
15183         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
15184         VALUES
15185             ('RESTdefaultPageSize','20','','Set the default number of results returned by the REST API endpoints','Integer')
15186     });
15187
15188     SetVersion( $DBversion );
15189     print "Upgrade to $DBversion done (Bug 19278 - Add a configurable default page size for REST endpoints)\n";
15190 }
15191
15192 $DBversion = '17.12.00.005';
15193 if( CheckVersion( $DBversion ) ) {
15194     # For installations having the note already
15195     $dbh->do(q{
15196         UPDATE letter
15197         SET code    = 'CHECKOUT_NOTE',
15198             name    = 'Checkout note on item set by patron',
15199             title   = 'Checkout note',
15200             content = REPLACE(content, "<<biblio.item>>", "<<biblio.title>>")
15201         WHERE code = 'PATRON_NOTE'
15202     });
15203     # For installations coming from 17.11
15204     $dbh->do(q{
15205         INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`)
15206         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')
15207     });
15208
15209     SetVersion( $DBversion );
15210     print "Upgrade to $DBversion done (Bug 18915 - Correct CHECKOUT_NOTE notice template)\n";
15211 }
15212
15213 $DBversion = '17.12.00.006';
15214 if( CheckVersion( $DBversion ) ) {
15215     $dbh->do(q{
15216         UPDATE systempreferences SET value=replace(value, "http://www.scholar", "https://scholar") WHERE variable='OPACSearchForTitleIn';
15217     });
15218
15219     SetVersion( $DBversion );
15220     print "Upgrade to $DBversion done (Bug 17682 - Update URL for Google Scholar in OPACSearchForTitleIn)\n";
15221 }
15222
15223 $DBversion = '17.12.00.007';
15224 if( CheckVersion( $DBversion ) ) {
15225
15226     unless ( TableExists( 'library_groups' ) ) {
15227         $dbh->do(q{
15228             CREATE TABLE library_groups (
15229                 id INT(11) NOT NULL auto_increment,    -- unique id for each group
15230                 parent_id INT(11) NULL DEFAULT NULL,   -- if this is a child group, the id of the parent group
15231                 branchcode VARCHAR(10) NULL DEFAULT NULL, -- The branchcode of a branch belonging to the parent group
15232                 title VARCHAR(100) NULL DEFAULT NULL,     -- Short description of the goup
15233                 description TEXT NULL DEFAULT NULL,    -- Longer explanation of the group, if necessary
15234                 created_on TIMESTAMP NULL,             -- Date and time of creation
15235                 updated_on TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- Date and time of last
15236                 PRIMARY KEY id ( id ),
15237                 FOREIGN KEY (parent_id) REFERENCES library_groups(id) ON UPDATE CASCADE ON DELETE CASCADE,
15238                 FOREIGN KEY (branchcode) REFERENCES branches(branchcode) ON UPDATE CASCADE ON DELETE CASCADE,
15239                 UNIQUE KEY title ( title )
15240             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
15241         });
15242     }
15243
15244     SetVersion( $DBversion );
15245     print "Upgrade to $DBversion done (Bug 15707 - Add new table library_groups)\n";
15246 }
15247
15248 $DBversion = '17.12.00.008';
15249 if ( CheckVersion($DBversion) ) {
15250
15251     if ( TableExists( 'branchcategories' ) and TableExists('branchrelations' )) {
15252         $dbh->do(q{
15253             INSERT INTO library_groups ( title, description, created_on ) VALUES ( '__SEARCH_GROUPS__', 'Library search groups', NOW() )
15254         });
15255         my $search_groups_root_id = $dbh->last_insert_id(undef, undef, 'library_groups', undef);
15256
15257         my $sth = $dbh->prepare("SELECT * FROM branchcategories");
15258
15259         my $sth2 = $dbh->prepare("INSERT INTO library_groups ( parent_id, title, description, created_on ) VALUES ( ?, ?, ?, NOW() )");
15260
15261         my $sth3 = $dbh->prepare("SELECT * FROM branchrelations WHERE categorycode = ?");
15262
15263         my $sth4 = $dbh->prepare("INSERT INTO library_groups ( parent_id, branchcode, created_on ) VALUES ( ?, ?, NOW() )");
15264
15265         $sth->execute();
15266         while ( my $lc = $sth->fetchrow_hashref ) {
15267             my $description = $lc->{categorycode};
15268             $description .= " - " . $lc->{codedescription} if $lc->{codedescription};
15269
15270             $sth2->execute($search_groups_root_id, $lc->{categoryname}, $description);
15271
15272             my $subgroup_id = $dbh->last_insert_id(undef, undef, 'library_groups', undef);
15273
15274             $sth3->execute( $lc->{categorycode} );
15275
15276             while ( my $l = $sth3->fetchrow_hashref ) {
15277                 $sth4->execute( $subgroup_id, $l->{branchcode} );
15278             }
15279         }
15280
15281         $dbh->do("DROP TABLE branchrelations");
15282         $dbh->do("DROP TABLE branchcategories");
15283     }
15284
15285     print "Upgrade to $DBversion done (Bug 16735 - Migrate library search groups into the new hierarchical groups)\n";
15286     SetVersion($DBversion);
15287 }
15288
15289 $DBversion = '17.12.00.009';
15290 if ( CheckVersion($DBversion) ) {
15291     $dbh->do(q|
15292         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
15293         (4, 'edit_borrowers', 'Add, modify and view patron information'),
15294         (4, 'view_borrower_infos_from_any_libraries', 'View patron infos from any libraries');
15295     |);
15296
15297     # We are lucky here, there is nothing else to do: flags 4-borrowers did not contain sub permissions
15298
15299     SetVersion( $DBversion );
15300     print "Upgrade to $DBversion done (Bug 18403 - Add the view_borrower_infos_from_any_libraries permission )\n";
15301 }
15302
15303 $DBversion = '17.12.00.010';
15304 if( CheckVersion( $DBversion ) ) {
15305
15306     if( !column_exists( 'library_groups', 'ft_hide_patron_info' ) ) {
15307         $dbh->do( "ALTER TABLE library_groups ADD COLUMN ft_hide_patron_info tinyint(1) NOT NULL DEFAULT 0 AFTER description" );
15308     }
15309
15310     SetVersion( $DBversion );
15311     print "Upgrade to $DBversion done (Bug 20133 - Add library_groups.ft_hide_patron_info)\n";
15312 }
15313
15314 $DBversion = '17.12.00.011';
15315 if( CheckVersion( $DBversion ) ) {
15316
15317     if( !column_exists( 'library_groups', 'ft_search_groups_opac' ) ) {
15318         $dbh->do( "ALTER TABLE library_groups ADD COLUMN ft_search_groups_opac tinyint(1) NOT NULL DEFAULT 0 AFTER ft_hide_patron_info" );
15319         $dbh->do( "ALTER TABLE library_groups ADD COLUMN ft_search_groups_staff tinyint(1) NOT NULL DEFAULT 0 AFTER ft_search_groups_opac" );
15320         $dbh->do( "UPDATE library_groups SET ft_search_groups_staff = 1 AND ft_search_groups_opac = 1 WHERE title = '__SEARCH_GROUPS__'" );
15321     }
15322
15323     SetVersion( $DBversion );
15324     print "Upgrade to $DBversion done (Bug 20157 - Use group 'features' to decide which groups to use for group searching functionality)\n";
15325 }
15326
15327 $DBversion = '17.12.00.012';
15328 if( CheckVersion( $DBversion ) ) {
15329
15330     $dbh->do( q|
15331         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15332         VALUES ('AutoSwitchPatron', '0', '', 'Auto switch to patron', 'YesNo');
15333     |);
15334
15335     SetVersion( $DBversion );
15336     print "Upgrade to $DBversion done (Bug 15752 - Add system preference AutoSwitchPatron)\n";
15337 }
15338
15339 $DBversion = '17.12.00.013';
15340 if( CheckVersion( $DBversion ) ) {
15341
15342     $dbh->do(q|
15343         ALTER TABLE club_enrollments MODIFY date_created timestamp NULL DEFAULT NULL;
15344     |);
15345
15346     SetVersion( $DBversion );
15347     print "Upgrade to $DBversion done (Bug 20175 - Set DEFAULT NULL value for club_enrollments.date_created)\n";
15348 }
15349
15350 $DBversion = '17.12.00.014';
15351 if( CheckVersion( $DBversion ) ) {
15352     $dbh->do( "UPDATE marc_subfield_structure SET kohafield=NULL where kohafield='additionalauthors.author'" );
15353     SetVersion( $DBversion );
15354     print "Upgrade to $DBversion done (Bug 19790 - Remove additionalauthors.author from installer files)\n";
15355 }
15356
15357 $DBversion = '17.12.00.015';
15358 if( CheckVersion( $DBversion ) ) {
15359     $dbh->do(q|
15360         ALTER TABLE borrowers
15361         MODIFY surname MEDIUMTEXT,
15362         MODIFY address MEDIUMTEXT,
15363         MODIFY city MEDIUMTEXT
15364     |);
15365     $dbh->do(q|
15366         ALTER TABLE deletedborrowers
15367         MODIFY surname MEDIUMTEXT,
15368         MODIFY address MEDIUMTEXT,
15369         MODIFY city MEDIUMTEXT
15370     |);
15371
15372     $dbh->do(q|
15373         ALTER TABLE export_format
15374         MODIFY csv_separator VARCHAR(2) NOT NULL DEFAULT ',',
15375         MODIFY field_separator VARCHAR(2),
15376         MODIFY subfield_separator VARCHAR(2)
15377     |);
15378     $dbh->do(q|
15379         ALTER TABLE export_format MODIFY encoding VARCHAR(255) NOT NULL DEFAULT 'utf8'
15380     |);
15381
15382     $dbh->do(q|
15383         ALTER TABLE reserves MODIFY lowestPriority tinyint(1) NOT NULL DEFAULT 0
15384     |);
15385     $dbh->do(q|
15386         ALTER TABLE old_reserves MODIFY lowestPriority tinyint(1) NOT NULL DEFAULT 0
15387     |);
15388
15389     SetVersion( $DBversion );
15390     print "Upgrade to $DBversion done (Bug 20144 - Adapt DB structure to work with new SQL modes)\n";
15391 }
15392
15393 $DBversion = '17.12.00.016';
15394 if( CheckVersion( $DBversion ) ) {
15395     $dbh->do(q|SET foreign_key_checks = 0|);
15396     my $sth = $dbh->table_info( '','','','TABLE' );
15397
15398     while ( my ( $cat, $schema, $name, $type, $remarks ) = $sth->fetchrow_array ) {
15399         my $table_sth = $dbh->prepare(qq|SHOW CREATE TABLE $name|);
15400         $table_sth->execute;
15401         my @table = $table_sth->fetchrow_array;
15402         unless ( $table[1] =~ /COLLATE=utf8mb4_unicode_ci/ ) {
15403             # Some users might have done the upgrade to utf8mb4 on their own
15404             # to support supplemental chars (japanese, chinese, etc)
15405             if ( $name eq 'additional_fields' ) {
15406                 $dbh->do(qq|
15407                     ALTER TABLE $name
15408                         DROP KEY `fields_uniq`,
15409                         ADD UNIQUE KEY `fields_uniq` (`tablename` (191), `name` (191))
15410                 |);
15411                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15412             }
15413             elsif ( $name eq 'authorised_values' ) {
15414                 $dbh->do(qq|
15415                     ALTER TABLE $name
15416                         DROP KEY `lib`,
15417                         ADD KEY `lib` (`lib` (191))
15418                 |);
15419                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15420             }
15421             elsif ( $name eq 'borrower_modifications' ) {
15422                 $dbh->do(qq|
15423                     ALTER TABLE $name
15424                         DROP PRIMARY KEY,
15425                         DROP KEY `verification_token`,
15426                         ADD PRIMARY KEY (`verification_token` (191),`borrowernumber`),
15427                         ADD KEY `verification_token` (`verification_token` (191))
15428                 |);
15429                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15430             }
15431             elsif ( $name eq 'columns_settings' ) {
15432                 $dbh->do(qq|
15433                     ALTER TABLE $name
15434                         DROP PRIMARY KEY,
15435                         ADD PRIMARY KEY (`module` (191), `page` (191), `tablename` (191), `columnname` (191))
15436                 |);
15437                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15438             }
15439             elsif ( $name eq 'illrequestattributes' ) {
15440                 $dbh->do(qq|
15441                     ALTER TABLE $name
15442                         DROP PRIMARY KEY,
15443                         ADD PRIMARY KEY  (`illrequest_id`, `type` (191))
15444                 |);
15445                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15446             }
15447             elsif ( $name eq 'items_search_fields' ) {
15448                 $dbh->do(qq|
15449                     ALTER TABLE $name
15450                         DROP PRIMARY KEY,
15451                         ADD PRIMARY KEY (`name` (191))
15452                 |);
15453                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15454             }
15455             elsif ( $name eq 'marc_subfield_structure' ) {
15456                 # In this case we convert each column explicitly
15457                 # to preserve 'tagsubield' collation (utf8mb4_bin)
15458                 $dbh->do(qq|
15459                     ALTER TABLE $name
15460                         MODIFY COLUMN tagfield
15461                             VARCHAR(3) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
15462                         MODIFY COLUMN tagsubfield
15463                             VARCHAR(1) COLLATE utf8mb4_bin NOT NULL DEFAULT '',
15464                         MODIFY COLUMN liblibrarian
15465                             VARCHAR(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
15466                         MODIFY COLUMN libopac
15467                             VARCHAR(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
15468                         MODIFY COLUMN kohafield
15469                             VARCHAR(40) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15470                         MODIFY COLUMN authorised_value
15471                             VARCHAR(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15472                         MODIFY COLUMN authtypecode
15473                             VARCHAR(20) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15474                         MODIFY COLUMN value_builder
15475                             VARCHAR(80) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15476                         MODIFY COLUMN frameworkcode
15477                             VARCHAR(4) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
15478                         MODIFY COLUMN seealso
15479                             VARCHAR(1100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15480                         MODIFY COLUMN link
15481                             VARCHAR(80) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15482                         MODIFY COLUMN defaultvalue
15483                             MEDIUMTEXT COLLATE utf8mb4_unicode_ci default NULL
15484                 |);
15485                 $dbh->do(qq|ALTER TABLE $name CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15486             }
15487             elsif ( $name eq 'plugin_data' ) {
15488                 $dbh->do(qq|
15489                     ALTER TABLE $name
15490                         DROP PRIMARY KEY,
15491                         ADD PRIMARY KEY (`plugin_class` (191), `plugin_key` (191))
15492                 |);
15493                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15494             }
15495             elsif ( $name eq 'search_field' ) {
15496                 $dbh->do(qq|
15497                     ALTER TABLE $name
15498                         DROP KEY `name`,
15499                         ADD UNIQUE KEY `name` (`name` (191))
15500                 |);
15501                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15502             }
15503             elsif ( $name eq 'search_marc_map' ) {
15504                 $dbh->do(qq|
15505                     ALTER TABLE $name
15506                         DROP KEY `index_name`,
15507                         ADD UNIQUE KEY `index_name` (`index_name`, `marc_field` (191), `marc_type`)
15508                 |);
15509                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15510             }
15511             elsif ( $name eq 'sms_providers' ) {
15512                 $dbh->do(qq|
15513                     ALTER TABLE $name
15514                         DROP KEY `name`,
15515                         ADD UNIQUE KEY `name` (`name` (191))
15516                 |);
15517                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15518             }
15519             elsif ( $name eq 'tags' ) {
15520                 $dbh->do(qq|
15521                     ALTER TABLE $name
15522                         DROP PRIMARY KEY,
15523                         ADD PRIMARY KEY (`entry` (191))
15524                 |);
15525                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15526             }
15527             elsif ( $name eq 'tags_approval' ) {
15528                 $dbh->do(qq|
15529                     ALTER TABLE $name
15530                         MODIFY COLUMN `term` VARCHAR(191) NOT NULL
15531                 |);
15532                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15533             }
15534             elsif ( $name eq 'tags_index' ) {
15535                 $dbh->do(qq|
15536                     ALTER TABLE $name
15537                         MODIFY COLUMN `term` VARCHAR(191) NOT NULL
15538                 |);
15539                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15540             }
15541             else {
15542                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15543             }
15544         }
15545     }
15546     $dbh->do(q|SET foreign_key_checks = 1|);
15547
15548     print "Upgrade to $DBversion done (Bug 18336 - Convert DB tables to utf8mb4 🎁)\n";
15549     SetVersion($DBversion);
15550 }
15551
15552
15553 $DBversion = '17.12.00.017';
15554 if( CheckVersion( $DBversion ) ) {
15555
15556     if( !column_exists( 'items', 'damaged_on' ) ) {
15557         $dbh->do( "ALTER TABLE items ADD COLUMN damaged_on DATETIME NULL AFTER damaged");
15558     }
15559     if( !column_exists( 'deleteditems', 'damaged_on' ) ) {
15560         $dbh->do( "ALTER TABLE deleteditems ADD COLUMN damaged_on DATETIME NULL AFTER damaged");
15561     }
15562
15563     SetVersion( $DBversion );
15564     print "Upgrade to $DBversion done (Bug 17672 - Add damaged_on to items and deleteditems tables)\n";
15565 }
15566
15567 $DBversion = '17.12.00.018';
15568 if( CheckVersion( $DBversion ) ) {
15569
15570     $dbh->do( q|
15571         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')
15572     |);
15573
15574     SetVersion( $DBversion );
15575     print "Upgrade to $DBversion done (Bug 19290 - Add system preference BrowseResultSelection)\n";
15576 }
15577
15578 $DBversion = '17.12.00.019';
15579 if( CheckVersion( $DBversion ) ) {
15580
15581     $dbh->do(q|UPDATE auth_subfield_structure SET hidden=1 WHERE hidden<>0|);
15582
15583     SetVersion( $DBversion );
15584     print "Upgrade to $DBversion done (Bug 20074 - Auth_subfield_structure changes hidden attribute)\n";
15585 }
15586
15587 $DBversion = '17.12.00.020';
15588 if( CheckVersion( $DBversion ) ) {
15589
15590     $dbh->do(q|
15591         INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)
15592         VALUES ('vi', 'language', 'de', 'Vietnamesisch')
15593     |);
15594
15595     $dbh->do(q|
15596         UPDATE language_descriptions SET description = 'Tiếng Việt'
15597         WHERE subtag = 'vi' and type = 'language' and lang = 'vi'
15598     |);
15599
15600     SetVersion( $DBversion );
15601     print "Upgrade to $DBversion done (Bug 20082 - Update descriptions of Vietnamese language)\n";
15602 }
15603
15604 $DBversion = '17.12.00.021';
15605 if( CheckVersion( $DBversion ) ) {
15606
15607     $dbh->do(q|
15608         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
15609         ('PurgeSuggestionsOlderThan', '', NULL, 'Default value for cronjob purge_suggestions.pl', 'Integer');
15610     |);
15611
15612     SetVersion( $DBversion );
15613     print "Upgrade to $DBversion done (Bug 13287 - Add system preference PurgeSuggestionsOlderThan)\n";
15614 }
15615
15616 $DBversion = '17.12.00.022';
15617 if( CheckVersion( $DBversion ) ) {
15618
15619     if( !column_exists( 'currency', 'p_sep_by_space' ) ) {
15620         $dbh->do(q|
15621             ALTER TABLE currency ADD COLUMN p_sep_by_space tinyint(1) default 0 after archived
15622         |);
15623     }
15624
15625     SetVersion( $DBversion );
15626     print "Upgrade to $DBversion done (Bug 4078 - Add column currency.p_sep_by_space)\n";
15627 }
15628
15629 $DBversion = '17.12.00.023';
15630 if( CheckVersion( $DBversion ) ) {
15631     $dbh->do(q{
15632         DELETE FROM systempreferences
15633         WHERE variable='checkdigit'
15634     });
15635
15636     SetVersion( $DBversion );
15637     print "Upgrade to $DBversion done (Bug 20264 - Remove system preference 'checkdigit')\n";
15638 }
15639
15640 $DBversion = '17.12.00.024';
15641 if( CheckVersion( $DBversion ) ) {
15642
15643     $dbh->do(q{
15644         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15645         VALUES ('SelfCheckInMainUserBlock', '', '70|10', 'Add a block of HTML that will display on the self check-in screen.', 'Textarea');
15646     });
15647
15648     $dbh->do(q{
15649         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15650         VALUES ('SelfCheckInModule', 0, NULL, 'Enable the standalone self-checkin module.', 'YesNo');
15651     });
15652
15653     $dbh->do(q{
15654         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15655         VALUES ('SelfCheckInModuleUserID', NULL, NULL, 'Patron ID (borrowernumber) to be allowed on the self-checkin module.', 'Integer');
15656     });
15657
15658     $dbh->do(q{
15659         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15660         VALUES ('SelfCheckInTimeout', 120, NULL, 'Define the number of seconds before the self check-in module times out.', 'Integer');
15661     });
15662
15663     $dbh->do(q{
15664         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15665         VALUES ('SelfCheckInUserCSS', '', NULL, 'Add CSS to be included in the self check-in module in an embedded <style> tag.', 'free');
15666     });
15667
15668     $dbh->do(q{
15669         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15670         VALUES ('SelfCheckInUserJS', '', NULL, 'Define custom javascript for inclusion in the self check-in module.', 'free');
15671     });
15672
15673     # Add new userflag for self check
15674     $dbh->do(q{
15675         INSERT IGNORE INTO userflags (bit,flag,flagdesc,defaulton) VALUES
15676             (23,'self_check','Self check modules',0);
15677     });
15678
15679     # Add self check-in module subpermission
15680     $dbh->do(q{
15681         INSERT IGNORE INTO permissions (module_bit,code,description)
15682         VALUES (23, 'self_checkin_module', 'Log into the self check-in module');
15683     });
15684
15685     # Add self check-in module subpermission
15686     $dbh->do(q{
15687         INSERT IGNORE INTO permissions (module_bit,code,description)
15688         VALUES (23, 'self_checkout_module', 'Perform self checkout at the OPAC. It should be used for the patron matching the AutoSelfCheckID');
15689     });
15690
15691     # Update patrons with self_checkout permission
15692     # IMPORTANT: Needs to happen before removing the old subpermission
15693     $dbh->do(q{
15694         UPDATE user_permissions
15695         SET module_bit = 23,
15696                   code = 'self_checkout_module'
15697         WHERE module_bit = 1 AND code = 'self_checkout';
15698     });
15699
15700     # Remove old self_checkout permission
15701     $dbh->do(q{
15702         DELETE IGNORE FROM permissions
15703         WHERE  code='self_checkout';
15704     });
15705
15706     SetVersion( $DBversion );
15707     print "Upgrade to $DBversion done (Bug 15492 - Add a standalone self-checkin module)\n";
15708 }
15709
15710 $DBversion = '17.12.00.025';
15711 if( CheckVersion( $DBversion ) ) {
15712     $dbh->do(q|
15713         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
15714         VALUES ('StaffLoginInstructions','','HTML to go into the login box for the staff client',NULL,'Free')
15715     |);
15716     $dbh->do(q|
15717         UPDATE systempreferences
15718         SET variable = 'OpacLoginInstructions'
15719         WHERE variable = 'NoLoginInstructions'
15720     |);
15721
15722     SetVersion( $DBversion );
15723     print "Upgrade to $DBversion done (Bug 20291 - Add StaffLoginInstructions system preference and rename NoLoginInstructions with OpacLoginInstructions)\n";
15724 }
15725
15726 $DBversion = '17.12.00.026';
15727 if( CheckVersion( $DBversion ) ) {
15728     if( !column_exists( 'issuingrules', 'suspension_chargeperiod' ) ) {
15729         $dbh->do(q|
15730             ALTER TABLE issuingrules ADD COLUMN suspension_chargeperiod int(11) DEFAULT '1' AFTER maxsuspensiondays;
15731         |);
15732     }
15733
15734     SetVersion( $DBversion );
15735     print "Upgrade to $DBversion done (Bug 19804 - Add issuingrules.suspension_chargeperiod)\n";
15736 }
15737
15738 $DBversion = '17.12.00.027';
15739 if( CheckVersion( $DBversion ) ) {
15740     $dbh->do(q|
15741         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
15742         VALUES ('UseACQFrameworkForBiblioRecords','0','','Use the ACQ framework for the catalog details','YesNo')
15743     |);
15744
15745     SetVersion( $DBversion );
15746     print "Upgrade to $DBversion done (Bug 19289 - Add system preference UseACQFrameworkForBiblioRecords)\n";
15747 }
15748
15749 $DBversion = '17.12.00.028';
15750 if( CheckVersion( $DBversion ) ) {
15751     if( !column_exists( 'marc_tag_structure', 'ind1_defaultvalue' ) ) {
15752         $dbh->do(q|
15753             ALTER TABLE marc_tag_structure
15754             ADD COLUMN ind2_defaultvalue VARCHAR(1) NOT NULL DEFAULT '' AFTER authorised_value,
15755             ADD COLUMN ind1_defaultvalue VARCHAR(1) NOT NULL DEFAULT '' AFTER authorised_value;
15756         |);
15757     }
15758
15759     SetVersion( $DBversion );
15760     print "Upgrade to $DBversion done (Bug 9701 - Add default indicators (marc_tag_structure.indX_defaultvalue))\n";
15761 }
15762
15763 $DBversion = '17.12.00.029';
15764 if( CheckVersion( $DBversion ) ) {
15765     my $pref =
15766 q|# PERSO_NAME  100 600 696 700 796 800 896
15767 marc21, 100, ind1:auth1
15768 marc21, 600, ind1:auth1, ind2:thesaurus
15769 marc21, 696, ind1:auth1
15770 marc21, 700, ind1:auth1
15771 marc21, 796, ind1:auth1
15772 marc21, 800, ind1:auth1
15773 marc21, 896, ind1:auth1
15774 # CORPO_NAME  110 610 697 710 797 810 897
15775 marc21, 110, ind1:auth1
15776 marc21, 610, ind1:auth1, ind2:thesaurus
15777 marc21, 697, ind1:auth1
15778 marc21, 710, ind1:auth1
15779 marc21, 797, ind1:auth1
15780 marc21, 810, ind1:auth1
15781 marc21, 897, ind1:auth1
15782 # MEETI_NAME    111 611 698 711 798 811 898
15783 marc21, 111, ind1:auth1
15784 marc21, 611, ind1:auth1, ind2:thesaurus
15785 marc21, 698, ind1:auth1
15786 marc21, 711, ind1:auth1
15787 marc21, 798, ind1:auth1
15788 marc21, 811, ind1:auth1
15789 marc21, 898, ind1:auth1
15790 # UNIF_TITLE        130 440 630 699 730 799 830 899 / 240
15791 marc21, 130, ind1:auth2
15792 marc21, 240, , ind2:auth2
15793 marc21, 440, , ind2:auth2
15794 marc21, 630, ind1:auth2, ind2:thesaurus
15795 marc21, 699, ind1:auth2
15796 marc21, 730, ind1:auth2
15797 marc21, 799, ind1:auth2
15798 marc21, 830, , ind2:auth2
15799 marc21, 899, ind1:auth2
15800 # CHRON_TERM    648
15801 marc21, 648, , ind2:thesaurus
15802 # TOPIC_TERM      650 654 656 657 658 690
15803 marc21, 650, , ind2:thesaurus
15804 # GEOGR_NAME   651 662 691 / 751
15805 marc21, 651, , ind2:thesaurus
15806 # GENRE/FORM    655
15807 marc21, 655, , ind2:thesaurus
15808
15809 # UNIMARC: Always copy the indicators from the authority
15810 unimarc, *, ind1:auth1, ind2:auth2|;
15811
15812     $dbh->do( q|
15813         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
15814         VALUES ( 'AuthorityControlledIndicators', ?, 'Authority controlled indicators per biblio field', NULL, 'Free' );
15815     |, undef, $pref );
15816
15817     SetVersion( $DBversion );
15818     print "Upgrade to $DBversion done (Bug 14769 - Authorities merge: Set correct indicators in biblio field (new system preference AuthorityControlledIndicators))\n";
15819 }
15820
15821 $DBversion = '17.12.00.030';
15822 if( CheckVersion( $DBversion ) ) {
15823     $dbh->do(q|
15824         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
15825         VALUES ('NovelistSelectStaffProfile',NULL,'Novelist staff client user Profile',NULL,'free')
15826     |);
15827
15828     SetVersion( $DBversion );
15829     print "Upgrade to $DBversion done (Bug 19882 - Add system preference NovelistSelectStaffProfile)\n";
15830 }
15831
15832 $DBversion = '17.12.00.031';
15833 if( CheckVersion( $DBversion ) ) {
15834     $dbh->do(q|
15835         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
15836         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')
15837     |);
15838
15839     SetVersion( $DBversion );
15840     print "Upgrade to $DBversion done (Bug 11674 - Add system preference MarcFieldDocURL)\n";
15841 }
15842
15843 $DBversion = '17.12.00.032';
15844 if( CheckVersion( $DBversion ) ) {
15845     $dbh->do(q|
15846         UPDATE letter SET code = "SERIAL_ALERT" WHERE code = "RLIST";
15847     |);
15848     $dbh->do(q|
15849         UPDATE letter SET name = "New serial issue" WHERE name = "Routing List";
15850     |);
15851     $dbh->do(q|
15852         UPDATE subscription SET letter = "SERIAL_ALERT" WHERE letter = "RLIST";
15853     |);
15854
15855     SetVersion( $DBversion );
15856     print "Upgrade to $DBversion done (Bug 19794 - Rename RLIST notice to SERIAL_ALERT)\n";
15857 }
15858
15859 $DBversion = '17.12.00.033';
15860 if( CheckVersion( $DBversion ) ) {
15861     if ( !column_exists( 'accountlines', 'payment_type' ) ) {
15862         $dbh->do(q{
15863             ALTER TABLE accountlines ADD payment_type varchar(80) default NULL AFTER accounttype
15864         });
15865     }
15866
15867     $dbh->do(q{
15868         INSERT IGNORE INTO authorised_value_categories( category_name ) VALUES ('PAYMENT_TYPE')
15869     });
15870
15871     SetVersion( $DBversion );
15872     print "Upgrade to $DBversion done (Bug 18786 - Add ability to create custom payment types)\n";
15873 }
15874
15875 $DBversion = '17.12.00.034';
15876 if( CheckVersion( $DBversion ) ) {
15877
15878     $dbh->do( q{
15879         INSERT IGNORE INTO account_offset_types ( type ) VALUES ('Void Payment')
15880     } );
15881
15882     SetVersion( $DBversion );
15883     print "Upgrade to $DBversion done (Bug 18790 - Add ability to void payment)\n";
15884 }
15885
15886 $DBversion = '17.12.00.035';
15887 if( CheckVersion( $DBversion ) ) {
15888     my ( $original_value ) = $dbh->selectrow_array(q|
15889         SELECT value FROM systempreferences WHERE variable="MarkLostItemsAsReturned"
15890     |);
15891     if ( $original_value and $original_value eq '1' ) {
15892         $dbh->do(q{
15893             UPDATE systempreferences
15894             SET type="multiple",
15895                 options="batchmod|moredetail|cronjob|additem",
15896                 value="batchmod,moredetail,cronjob,additem"
15897             WHERE variable="MarkLostItemsAsReturned"
15898         });
15899     } else {
15900         $dbh->do(q{
15901             UPDATE systempreferences
15902             SET type="multiple",
15903                 options="batchmod|moredetail|cronjob|additem",
15904                 value=""
15905             WHERE variable="MarkLostItemsAsReturned"
15906         });
15907     }
15908
15909     SetVersion( $DBversion );
15910     print "Upgrade to $DBversion done (Bug 19974 - Make MarkLostItemsAsReturned multiple)\n";
15911 }
15912
15913 $DBversion = '17.12.00.036';
15914 if( CheckVersion( $DBversion ) ) {
15915
15916     $dbh->do( q{
15917         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');
15918     } );
15919     $dbh->do( q{
15920         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');
15921     } );
15922     $dbh->do( q{
15923         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');
15924     } );
15925     $dbh->do( q{
15926         UPDATE systempreferences SET options="batchmod|moredetail|cronjob|additem|pendingreserves" WHERE variable="MarkLostItemsAsReturned";
15927     } );
15928
15929     SetVersion( $DBversion );
15930     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";
15931 }
15932
15933 $DBversion = '17.12.00.037';
15934 if( CheckVersion( $DBversion ) ) {
15935
15936     SetVersion( $DBversion );
15937     print "Upgrade to $DBversion done (This change has been reverted, nothing done!)\n";
15938 }
15939
15940 $DBversion = '17.12.00.038';
15941 if( CheckVersion( $DBversion ) ) {
15942
15943     $dbh->do( q{
15944         UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'slo' WHERE iso639_2_code = 'slk' AND rfc4646_subtag = 'sk';
15945     } );
15946
15947     SetVersion( $DBversion );
15948     print "Upgrade to $DBversion done (Bug 20245 - Use Bibliographic code value for Slovak language)\n";
15949 }
15950
15951 $DBversion = '17.12.00.039';
15952 if( CheckVersion( $DBversion ) ) {
15953
15954     $dbh->do( q{
15955         UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'baq' WHERE iso639_2_code = 'eus' AND rfc4646_subtag = 'eu';
15956     } );
15957     $dbh->do( q{
15958         UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'mao' WHERE iso639_2_code = 'mri' AND rfc4646_subtag = 'mi';
15959     } );
15960     $dbh->do( q{
15961         UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'alb' WHERE iso639_2_code = 'sqi' AND rfc4646_subtag = 'sq';
15962     } );
15963
15964     SetVersion( $DBversion );
15965     print "Upgrade to $DBversion done (Bug 20482 - Use Bibliographic code value for Basque, Maori and Albanian languages)\n";
15966 }
15967
15968 $DBversion = '17.12.00.040';
15969 if( CheckVersion( $DBversion ) ) {
15970
15971     $dbh->do( q{
15972         INSERT IGNORE INTO systempreferences ( value, variable, options, explanation, type )
15973         VALUES ( '0', 'ProtectSuperlibrarianPrivileges', NULL, 'If enabled, non-superlibrarians cannot set superlibrarian privileges', 'YesNo' )
15974     } );
15975
15976     SetVersion( $DBversion );
15977     print "Upgrade to $DBversion done (Bug 20100 - Add new system preference ProtectSuperlibrarianPrivileges)\n";
15978 }
15979
15980 $DBversion = '17.12.00.041';
15981 if( CheckVersion( $DBversion ) ) {
15982
15983     $dbh->do( q{
15984         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES (13, 'access_files', 'Access to the files stored on the server');
15985     } );
15986
15987     SetVersion( $DBversion );
15988     print "Upgrade to $DBversion done (Bug 11317 - Add a new permission to access files stored on the server)\n";
15989 }
15990
15991 $DBversion = '17.12.00.042';
15992 if( CheckVersion( $DBversion ) ) {
15993
15994     if (!TableExists('oauth_access_tokens')) {
15995         $dbh->do(q{
15996             CREATE TABLE oauth_access_tokens (
15997                 `access_token` VARCHAR(191) NOT NULL,
15998                 `client_id`    VARCHAR(191) NOT NULL,
15999                 `expires`      INT NOT NULL,
16000                 PRIMARY KEY (`access_token`)
16001             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
16002         });
16003     }
16004
16005     SetVersion( $DBversion );
16006     print "Upgrade to $DBversion done (Bug 20402 - Implement OAuth2 authentication for REST API)\n";
16007 }
16008
16009 $DBversion = '17.12.00.043';
16010 if(CheckVersion($DBversion)) {
16011
16012     if (!TableExists('api_keys')) {
16013         $dbh->do(q{
16014             CREATE TABLE `api_keys` (
16015                 `client_id`   VARCHAR(191) NOT NULL,
16016                 `secret`      VARCHAR(191) NOT NULL,
16017                 `description` VARCHAR(255) NOT NULL,
16018                 `patron_id`   INT(11) NOT NULL,
16019                 `active`      TINYINT(1) DEFAULT 1 NOT NULL,
16020                 PRIMARY KEY `client_id` (`client_id`),
16021                 UNIQUE KEY `secret` (`secret`),
16022                 KEY `patron_id` (`patron_id`),
16023                 CONSTRAINT `api_keys_fk_patron_id`
16024                   FOREIGN KEY (`patron_id`)
16025                   REFERENCES `borrowers` (`borrowernumber`)
16026                   ON DELETE CASCADE ON UPDATE CASCADE
16027             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16028         });
16029     }
16030
16031     print "Upgrade to $DBversion done (Bug 20568 - Add API key management interface for patrons)\n";
16032     SetVersion($DBversion);
16033 }
16034
16035 $DBversion = '17.12.00.044';
16036 if(CheckVersion($DBversion)) {
16037
16038     $dbh->do(q{
16039         INSERT IGNORE INTO systempreferences (`variable`,`value`,`options`,`explanation`,`type`)
16040         VALUES
16041             ('RESTOAuth2ClientCredentials','0',NULL,'If enabled, the OAuth2 client credentials flow is enabled for the REST API.','YesNo');
16042     });
16043
16044     print "Upgrade to $DBversion done (Bug 20624 - Disable OAuth2 client credentials grant by default)\n";
16045     SetVersion($DBversion);
16046 }
16047
16048 $DBversion = '18.05.00.000';
16049 if( CheckVersion( $DBversion ) ) {
16050     SetVersion( $DBversion );
16051     print "Upgrade to $DBversion done (Koha 18.05)\n";
16052 }
16053
16054 $DBversion = '18.06.00.000';
16055 if( CheckVersion( $DBversion ) ) {
16056     SetVersion( $DBversion );
16057     print "Upgrade to $DBversion done (Koha 18.06 - It's Adventure time!)\n";
16058 }
16059
16060 $DBversion = '18.06.00.001';
16061 if( CheckVersion( $DBversion ) ) {
16062     $dbh->do(q{UPDATE permissions SET description = 'Manage budgets' WHERE code = 'period_manage';});
16063     $dbh->do(q{UPDATE permissions SET description = 'Manage funds' WHERE code = 'budget_manage';});
16064     $dbh->do(q{UPDATE permissions SET description = 'Modify funds (can''t create lines, but can modify existing ones)' WHERE code = 'budget_modify';});
16065     $dbh->do(q{UPDATE permissions SET description = 'Manage baskets and order lines' WHERE code = 'order_manage';});
16066     $dbh->do(q{UPDATE permissions SET description = 'Manage all baskets and order lines, regardless of restrictions on them' WHERE code = 'order_manage_all';});
16067     $dbh->do(q{UPDATE permissions SET description = 'Manage basket groups' WHERE code = 'group_manage';});
16068     $dbh->do(q{UPDATE permissions SET description = 'Receive orders and manage shipments' WHERE code = 'order_receive';});
16069     $dbh->do(q{UPDATE permissions SET description = 'Add and delete funds (but can''t modify funds)' WHERE code = 'budget_add_del';});
16070     $dbh->do(q{UPDATE permissions SET description = 'Manage all funds' WHERE code = 'budget_manage_all';});
16071     SetVersion( $DBversion );
16072     print "Upgrade to $DBversion done (Bug 3849- Improve descriptions of granular acquisition permissions)\n";
16073 }
16074
16075 $DBversion = '18.06.00.002';
16076 if( CheckVersion( $DBversion ) ) {
16077     $dbh->do(q{DELETE FROM userflags WHERE bit = 12 AND flag = 'management';});
16078     $dbh->do(q{UPDATE borrowers SET flags = flags - ( flags & (1<<12) ) WHERE flags & (1 << 12);});
16079     SetVersion( $DBversion );
16080     print "Upgrade to $DBversion done (Bug 2426 - Remove deprecated management permission)\n";
16081 }
16082
16083 $DBversion = '18.06.00.003';
16084 if( CheckVersion( $DBversion ) ) {
16085     $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'" );
16086     SetVersion( $DBversion );
16087     print "Upgrade to $DBversion done (Bug 20073 - Add new types for Elasticsearch fields)\n";
16088 }
16089
16090 $DBversion = '18.06.00.004';
16091 if( CheckVersion( $DBversion ) ) {
16092
16093     # Add 'Manual Credit' offset type
16094     $dbh->do(q{
16095         INSERT IGNORE INTO `account_offset_types` (`type`) VALUES ('Manual Credit');
16096     });
16097
16098     # Fix wrong account offsets / Manual credits
16099     $dbh->do(q{
16100         UPDATE account_offsets
16101         SET credit_id=debit_id,
16102             debit_id=NULL,
16103             type='Manual Credit'
16104         WHERE amount < 0 AND
16105               type='Manual Debit' AND
16106               debit_id IN
16107                 (SELECT accountlines_id AS debit_id
16108                  FROM accountlines
16109                  WHERE accounttype='C');
16110     });
16111
16112     # Fix wrong account offsets / Manually forgiven amounts
16113     $dbh->do(q{
16114         UPDATE account_offsets
16115         SET credit_id=debit_id,
16116             debit_id=NULL,
16117             type='Writeoff'
16118         WHERE amount < 0 AND
16119               type='Manual Debit' AND
16120               debit_id IN
16121                 (SELECT accountlines_id AS debit_id
16122                  FROM accountlines
16123                  WHERE accounttype='FOR');
16124     });
16125
16126     SetVersion( $DBversion );
16127     print "Upgrade to $DBversion done (Bug 20980 - Manual credit offsets are stored as debits)\n";
16128 }
16129
16130 $DBversion = '18.06.00.005';
16131 if( CheckVersion( $DBversion ) ) {
16132     unless ( column_exists('aqorders', 'created_by') ) {
16133         $dbh->do( "ALTER TABLE aqorders ADD COLUMN created_by int(11) NULL DEFAULT NULL AFTER quantityreceived;" );
16134         unless ( foreign_key_exists('aqorders', 'aqorders_created_by') ) {
16135             $dbh->do( "ALTER TABLE aqorders ADD CONSTRAINT aqorders_created_by FOREIGN KEY (created_by) REFERENCES borrowers (borrowernumber) ON DELETE SET NULL ON UPDATE CASCADE;" );
16136         }
16137         $dbh->do( "UPDATE aqbasket LEFT JOIN borrowers ON ( aqbasket.authorisedby = borrowers.borrowernumber ) SET aqbasket.authorisedby = NULL WHERE borrowers.borrowernumber IS NULL;" );
16138         $dbh->do( "UPDATE aqorders LEFT JOIN aqbasket ON ( aqorders.basketno = aqbasket.basketno ) SET aqorders.created_by = aqbasket.authorisedby WHERE aqorders.created_by IS NULL;" );
16139     }
16140     SetVersion( $DBversion );
16141     print "Upgrade to $DBversion done (Bug 12395 - Save order line's creator)\n";
16142 }
16143
16144 $DBversion = '18.06.00.006';
16145 if( CheckVersion( $DBversion ) ) {
16146     unless ( column_exists('patron_lists', 'shared') ) {
16147         $dbh->do( "ALTER TABLE patron_lists ADD COLUMN shared tinyint(1) default 0 AFTER owner;" );
16148     }
16149     SetVersion( $DBversion );
16150     print "Upgrade to $DBversion done (Bug 19524 - Share patron lists between staff)\n";
16151 }
16152
16153 $DBversion = '18.06.00.007';
16154 if( CheckVersion( $DBversion ) ) {
16155     $dbh->do( "INSERT IGNORE INTO permissions (module_bit, code, description) VALUES (11, 'currencies_manage', 'Manage currencies and exchange rates');" );
16156     $dbh->do(q{
16157         INSERT IGNORE INTO user_permissions (borrowernumber, module_bit, code)
16158             SELECT borrowernumber, 11, 'currencies_manage' FROM borrowers WHERE flags & (1 << 3) OR borrowernumber IN
16159             (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16160     });
16161     SetVersion( $DBversion );
16162     print "Upgrade to $DBversion done (Bug 7651 - Add separate permission for managing currencies and exchange rates)\n";
16163 }
16164
16165 $DBversion = '18.06.00.008';
16166 if( CheckVersion( $DBversion ) ) {
16167     $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')" );
16168     SetVersion( $DBversion );
16169     print "Upgrade to $DBversion done (Bug 13560 - need an add option in marc modification templates)\n";
16170 }
16171
16172 $DBversion = '18.06.00.009';
16173 if( CheckVersion( $DBversion ) ) {
16174     $dbh->do( "
16175         CREATE TABLE IF NOT EXISTS aqinvoice_adjustments (
16176             adjustment_id int(11) NOT NULL AUTO_INCREMENT,
16177             invoiceid int(11) NOT NULL,
16178             adjustment decimal(28,6),
16179             reason varchar(80) default NULL,
16180             note mediumtext default NULL,
16181             budget_id int(11) default NULL,
16182             encumber_open smallint(1) NOT NULL default 1,
16183             timestamp timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
16184             PRIMARY KEY (adjustment_id),
16185             CONSTRAINT aqinvoice_adjustments_fk_invoiceid FOREIGN KEY (invoiceid) REFERENCES aqinvoices (invoiceid) ON DELETE CASCADE ON UPDATE CASCADE,
16186             CONSTRAINT aqinvoice_adjustments_fk_budget_id FOREIGN KEY (budget_id) REFERENCES aqbudgets (budget_id) ON DELETE SET NULL ON UPDATE CASCADE
16187         ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
16188         " );
16189     $dbh->do("INSERT IGNORE INTO authorised_value_categories (category_name) VALUES ('ADJ_REASON')");
16190     SetVersion( $DBversion );
16191     print "Upgrade to $DBversion done (Bug 19166 - Add the ability to add adjustments to an invoice)\n";
16192 }
16193
16194 $DBversion = '18.06.00.010';
16195 if( CheckVersion( $DBversion ) ) {
16196     $dbh->do(q{
16197         INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`, `lang`)
16198         VALUES
16199             ('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'),
16200                 ('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');
16201     });
16202     $dbh->do(q{
16203         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
16204         VALUES ('UseEmailReceipts','0','','Send email receipts for payments and write-offs','YesNo')
16205     });
16206     SetVersion( $DBversion );
16207     print "Upgrade to $DBversion done (Bug 19191 - Add ability to email receipts for account payments and write-offs)\n";
16208 }
16209
16210 $DBversion = '18.06.00.011';
16211 if( CheckVersion( $DBversion ) ) {
16212     unless( column_exists( 'issues', 'noteseen' ) ) {
16213         $dbh->do(q|ALTER TABLE issues ADD COLUMN noteseen int(1) default NULL AFTER notedate|);
16214     }
16215
16216     unless( column_exists( 'old_issues', 'noteseen' ) ) {
16217         $dbh->do(q|ALTER TABLE old_issues ADD COLUMN noteseen int(1) default NULL AFTER notedate|);
16218     }
16219     $dbh->do(q|INSERT IGNORE INTO permissions (module_bit, code, description) VALUES ( 1, 'manage_checkout_notes', 'Mark checkout notes as seen/not seen');|);
16220     SetVersion( $DBversion );
16221     print "Upgrade to $DBversion done (Bug 17698: Add column issues.noteseen and old_issues.noteseen)\n";
16222 }
16223
16224 $DBversion = '18.06.00.012';
16225 if( CheckVersion( $DBversion ) ) {
16226     $dbh->do(q|INSERT IGNORE INTO permissions (module_bit, code, description) VALUES (11, 'suggestions_manage', 'Manage purchase suggestions');|);
16227     $dbh->do(q|INSERT IGNORE INTO user_permissions (borrowernumber, module_bit, code) SELECT borrowernumber, 11, 'suggestions_manage' FROM borrowers WHERE flags & (1 << 2);|);
16228     SetVersion( $DBversion );
16229     print "Upgrade to $DBversion done (Bug 11911 - Add separate permission for managing suggestions)\n";
16230 }
16231
16232 $DBversion = '18.06.00.013';
16233 if( CheckVersion( $DBversion ) ) {
16234     $dbh->do(q{
16235         INSERT IGNORE INTO `account_offset_types` (`type`) VALUES ('Credit Applied');
16236     });
16237     SetVersion( $DBversion );
16238     print "Upgrade to $DBversion done (Bug 20997 - Add Koha::Account::Line::apply)\n";
16239 }
16240
16241 $DBversion = '18.06.00.014';
16242 if( CheckVersion( $DBversion ) ) {
16243     $dbh->do(q{
16244             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');
16245     });
16246     SetVersion( $DBversion );
16247     print "Upgrade to $DBversion done (Bug 21121 - New syspref to allow hiding of private patron data in circulation page)\n";
16248 }
16249
16250 $DBversion = '18.06.00.015';
16251 if( CheckVersion( $DBversion ) ) {
16252     $dbh->do(q{DELETE FROM systempreferences where variable="OCLCAffiliateID";});
16253     $dbh->do(q{DELETE FROM systempreferences where variable="XISBN";});
16254     $dbh->do(q{DELETE FROM systempreferences where variable="XISBNDailyLimit";});
16255     SetVersion( $DBversion );
16256     print "Upgrade to $DBversion done (Bug 21226 - Remove prefs OCLCAffiliateID, XISBN and XISBNDailyLimit)\n";
16257 }
16258
16259 $DBversion = '18.06.00.016';
16260 if( CheckVersion( $DBversion ) ) {
16261     my $dtf  = Koha::Database->new->schema->storage->datetime_parser;
16262     my $days = C4::Context->preference('MaxPickupDelay') || 7;
16263     my $date = dt_from_string()->add( days => $days );
16264     my $sql  = q|UPDATE reserves SET expirationdate = ? WHERE expirationdate IS NULL AND waitingdate IS NOT NULL|;
16265     $dbh->do( $sql, undef, $dtf->format_datetime($date) );
16266     SetVersion( $DBversion );
16267     print "Upgrade to $DBversion done (Bug 20773 - expirationdate filled for waiting holds)\n";
16268 }
16269
16270 $DBversion = '18.06.00.017';
16271 if( CheckVersion( $DBversion ) ) {
16272     $dbh->do(q|INSERT IGNORE INTO authorised_value_categories (category_name) VALUES ('ROADTYPE');|);
16273     SetVersion( $DBversion );
16274     print "Upgrade to $DBversion done (Bug 21144: Add ROADTYPE to default authorised values categories)\n";
16275 }
16276
16277 $DBversion = '18.06.00.018';
16278 if( CheckVersion( $DBversion ) ) {
16279     $dbh->do( q|
16280 UPDATE items LEFT JOIN issues USING (itemnumber)
16281 SET items.onloan = NULL
16282 WHERE issues.itemnumber IS NULL
16283     |);
16284     SetVersion( $DBversion );
16285     print "Upgrade to $DBversion done (Bug 20487: Clear items.onloan for unissued items)\n";
16286 }
16287
16288 $DBversion = '18.06.00.019';
16289 if( CheckVersion( $DBversion ) ) {
16290     $dbh->do( q|
16291 INSERT IGNORE INTO columns_settings (module, page, tablename, columnname, cannot_be_toggled, is_hidden) VALUES
16292 ("circ", "circulation", "issues-table", "collection", 0, 1),
16293 ("members", "moremember", "issues-table", "collection", 0, 1);
16294     |);
16295     SetVersion( $DBversion );
16296     print "Upgrade to $DBversion done (Bug 19719: Default to hiding collection code column)\n";
16297 }
16298
16299 $DBversion = '18.06.00.020';
16300 if( CheckVersion( $DBversion ) ) {
16301     if( !column_exists( 'branch_borrower_circ_rules', 'max_holds' ) ) {
16302         $dbh->do(q{
16303             ALTER TABLE branch_borrower_circ_rules ADD COLUMN max_holds INT(4) NULL DEFAULT NULL AFTER maxonsiteissueqty
16304         });
16305     }
16306     if( !column_exists( 'default_borrower_circ_rules', 'max_holds' ) ) {
16307         $dbh->do(q{
16308             ALTER TABLE default_borrower_circ_rules ADD COLUMN max_holds INT(4) NULL DEFAULT NULL AFTER maxonsiteissueqty
16309         });
16310     }
16311     SetVersion( $DBversion );
16312     print "Upgrade to $DBversion done (Bug 15524 - Set limit on maximum possible holds per patron by category)\n";
16313 }
16314
16315 $DBversion = '18.06.00.021';
16316 if( CheckVersion( $DBversion ) ) {
16317     my $dbh = C4::Context->dbh;
16318     unless ( C4::Context->preference('NorwegianPatronDBEnable') ) {
16319         $dbh->do(q|
16320             DELETE FROM systempreferences
16321             WHERE variable IN ('NorwegianPatronDBEnable', 'NorwegianPatronDBEndpoint', 'NorwegianPatronDBUsername', 'NorwegianPatronDBPassword', 'NorwegianPatronDBSearchNLAfterLocalHit')
16322         |);
16323         if ( TableExists('borrower_sync') ) {
16324             $dbh->do(q|DROP TABLE borrower_sync|);
16325         }
16326     }
16327     SetVersion( $DBversion );
16328     print "Upgrade to $DBversion done (Bug 21068 - Remove system preferences NorwegianPatronDB*)\n";
16329 }
16330
16331 $DBversion = '18.06.00.022';
16332 if( CheckVersion( $DBversion ) ) {
16333     my $dbh = C4::Context->dbh;
16334     $dbh->do(q|
16335         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
16336         ('HoldsAutoFill','0',NULL,'If on, librarian will not be asked if hold should be filled, it will be filled automatically','YesNo'),
16337         ('HoldsAutoFillPrintSlip','0',NULL,'If on, hold slip print dialog will be displayed automatically','YesNo')
16338     |);
16339     SetVersion( $DBversion );
16340     print "Upgrade to $DBversion done (Bug 19383 - Add ability to print hold receipts automatically)\n";
16341 }
16342
16343 $DBversion = '18.06.00.023';
16344 if( CheckVersion( $DBversion ) ) {
16345     if( !column_exists( 'aqorders', 'replacementprice' ) ){
16346         $dbh->do( "ALTER TABLE aqorders ADD COLUMN replacementprice DECIMAL(28,6)" );
16347         $dbh->do( "UPDATE aqorders set replacementprice = rrp WHERE replacementprice IS NULL" );
16348     }
16349     SetVersion( $DBversion );
16350     print "Upgrade to $DBversion done (Bug 18639 - Add replacementprice field to aqorders table)\n";
16351 }
16352
16353 $DBversion = '18.06.00.024';
16354 if( CheckVersion( $DBversion ) ) {
16355     if( !column_exists( 'branches', 'pickup_location' ) ){
16356         $dbh->do( "ALTER TABLE branches ADD COLUMN pickup_location TINYINT(1) not null default 1" );
16357     }
16358     SetVersion( $DBversion );
16359     print "Upgrade to $DBversion done (Bug 7534 - Let libraries have configuration for pickup locations)\n";
16360 }
16361
16362 $DBversion = '18.06.00.025';
16363 if( CheckVersion( $DBversion ) ) {
16364     $dbh->do(q{
16365         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
16366         ('KohaManualBaseURL','https://koha-community.org/manual/','','Where is the Koha manual/documentation located?','Free'),
16367         ('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')
16368     });
16369     SetVersion( $DBversion );
16370     print "Upgrade to $DBversion done (Bug 19817: Add pref KohaManualLanguage and KohaManualBaseURL)\n";
16371 }
16372
16373 $DBversion = '18.06.00.026';
16374 if( CheckVersion( $DBversion ) ) {
16375     $dbh->do(q|
16376 INSERT IGNORE INTO  systempreferences (variable, value, options, explanation, type) VALUES ('ArticleRequestsLinkControl', 'always', 'always\|calc', 'Control display of article request link on search results', 'Choice')
16377     |);
16378     SetVersion( $DBversion );
16379     print "Upgrade to $DBversion done (Bug 17530 - Add pref ArticleRequestsLinkControl)\n";
16380 }
16381
16382 $DBversion = '18.06.00.027';
16383 if( CheckVersion( $DBversion ) ) {
16384     $dbh->do( "DROP TABLE IF EXISTS services_throttle" );
16385     SetVersion( $DBversion );
16386     print "Upgrade to $DBversion done (Bug 21235: Remove table services_throttle)\n";
16387 }
16388
16389 $DBversion = '18.06.00.028';
16390 if( CheckVersion( $DBversion ) ) {
16391     $dbh->do(q{
16392 INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
16393 ('HoldsSplitQueue','nothing','nothing|branch|itemtype|branch_itemtype','In the staff client, split the holds view by the given criteria','Choice'),
16394 ('HoldsSplitQueueNumbering', 'actual', 'actual|virtual', 'If the holds queue is split, decide if the acual priorities should be displayed', 'Choice');
16395 });
16396     SetVersion( $DBversion );
16397     print "Upgrade to $DBversion done (Bug 19469 - Add ability to split view of holds view on record by pickup library and/or itemtype)\n";
16398 }
16399
16400 $DBversion = '18.06.00.029';
16401 if( CheckVersion( $DBversion ) ) {
16402     unless ( index_exists( 'subscription', 'by_biblionumber' ) ) {
16403         $dbh->do(q{
16404             CREATE INDEX `by_biblionumber` ON `subscription` (`biblionumber`)
16405         });
16406     }
16407     SetVersion( $DBversion );
16408     print "Upgrade to $DBversion done (Bug 21288: Slowness in acquisition caused by GetInvoices\n";
16409 }
16410
16411 $DBversion = '18.06.00.030';
16412 if( CheckVersion( $DBversion ) ) {
16413     if ( column_exists( 'accountlines', 'dispute' ) ) {
16414         $dbh->do(q{
16415             ALTER TABLE `accountlines`
16416                 DROP COLUMN `dispute`
16417         });
16418     }
16419     SetVersion( $DBversion );
16420     print "Upgrade to $DBversion done (Bug 20777 - Remove unused field accountlines.dispute)\n";
16421 }
16422
16423 $DBversion = '18.06.00.031';
16424 if( CheckVersion( $DBversion ) ) {
16425     # Add table and add column
16426     unless (TableExists('patron_consent')) {
16427         $dbh->do(q|
16428     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 )
16429         |);
16430     }
16431     unless ( column_exists( 'borrower_modifications', 'gdpr_proc_consent' ) ) {
16432         $dbh->do(q|
16433     ALTER TABLE borrower_modifications ADD COLUMN gdpr_proc_consent datetime
16434         |);
16435     }
16436     # Add two sysprefs too
16437     $dbh->do(q|
16438 INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type ) VALUES ('PrivacyPolicyURL','',NULL,'This URL is used in messages about GDPR consents.', 'Free')
16439     |);
16440     $dbh->do(q|
16441 INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type ) VALUES ('GDPR_Policy','','Enforced\|Permissive\|Disabled','General Data Protection Regulation - policy', 'Choice')
16442     |);
16443     SetVersion( $DBversion );
16444     print "Upgrade to $DBversion done (Bug 20819: Add patron_consent)\n";
16445 }
16446
16447 $DBversion = '18.06.00.032';
16448 if( CheckVersion( $DBversion ) ) {
16449     $dbh->do(q|ALTER TABLE items                   CHANGE COLUMN ccode ccode varchar(80) default NULL|);
16450     $dbh->do(q|ALTER TABLE deleteditems            CHANGE COLUMN ccode ccode varchar(80) default NULL|);
16451     $dbh->do(q|ALTER TABLE branch_transfer_limits  CHANGE COLUMN ccode ccode varchar(80) default NULL|);
16452     $dbh->do(q|ALTER TABLE course_items            CHANGE COLUMN ccode ccode varchar(80) default NULL|);
16453     SetVersion( $DBversion );
16454     print "Upgrade to $DBversion done (Bug 5458: length of items.ccode disagrees with authorised_values.authorised_value)\n";
16455 }
16456
16457 $DBversion = '18.06.00.033';
16458 if( CheckVersion( $DBversion ) ) {
16459     $dbh->do(q|
16460         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')
16461     |);
16462     SetVersion( $DBversion );
16463     print "Upgrade to $DBversion done (Bug 12747 - Add AdditionalFieldsInZ3950ResultSearch system preference)\n";
16464 }
16465
16466 $DBversion = '18.06.00.034';
16467 if( CheckVersion( $DBversion ) ) {
16468     $dbh->do(q|
16469         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
16470         VALUES ('RecordedBooksClientSecret','','30','Client key for RecordedBooks integration','YesNo'),
16471                ('RecordedBooksLibraryID','','','Library ID for RecordedBooks integration','Integer'),
16472                ('RecordedBooksDomain','','','RecordedBooks domain','Free');
16473     |);
16474     SetVersion( $DBversion );
16475     print "Upgrade to $DBversion done (Bug 17602 - Integrate support for OneClickdigital/Recorded Books API)\n";
16476 }
16477
16478 $DBversion = '18.06.00.035';
16479 if( CheckVersion( $DBversion ) ) {
16480     $dbh->do(q{
16481         UPDATE `systempreferences` SET options = 'US|CA|DE|FR|IN|JP|UK' WHERE variable = 'AmazonLocale' AND options='US|CA|DE|FR|JP|UK';
16482     });
16483     SetVersion( $DBversion );
16484     print "Upgrade to $DBversion done (Bug 21403 - Add Indian Amazon Affiliate option to AmazonLocale setting)\n";
16485 }
16486
16487
16488 $DBversion = '18.06.00.036';
16489 if( CheckVersion( $DBversion ) ) {
16490     unless (TableExists('circulation_rules')){
16491         $dbh->do(q{
16492             CREATE TABLE `circulation_rules` (
16493               `id` int(11) NOT NULL auto_increment,
16494               `branchcode` varchar(10) NULL default NULL,
16495               `categorycode` varchar(10) NULL default NULL,
16496               `itemtype` varchar(10) NULL default NULL,
16497               `rule_name` varchar(32) NOT NULL,
16498               `rule_value` varchar(32) NOT NULL,
16499               PRIMARY KEY (`id`),
16500               CONSTRAINT `circ_rules_ibfk_1` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
16501               CONSTRAINT `circ_rules_ibfk_2` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`) ON DELETE CASCADE ON UPDATE CASCADE,
16502               CONSTRAINT `circ_rules_ibfk_3` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE,
16503               KEY `rule_name` (`rule_name`),
16504               UNIQUE (`branchcode`,`categorycode`,`itemtype`,`rule_name`)
16505             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16506         });
16507     }
16508     if (column_exists('branch_borrower_circ_rules', 'max_holds') ){
16509         $dbh->do(q{
16510             INSERT IGNORE INTO circulation_rules ( branchcode, categorycode, itemtype, rule_name, rule_value )
16511             SELECT branchcode, categorycode, NULL, 'max_holds', COALESCE( max_holds, '' ) FROM branch_borrower_circ_rules
16512         });
16513         $dbh->do(q{
16514             ALTER TABLE branch_borrower_circ_rules DROP COLUMN max_holds
16515         });
16516     }
16517     if (column_exists('default_borrower_circ_rules', 'max_holds') ){
16518         $dbh->do(q{
16519             INSERT IGNORE INTO circulation_rules ( branchcode, categorycode, itemtype, rule_name, rule_value )
16520             SELECT NULL, categorycode, NULL, 'max_holds', COALESCE( max_holds, '' ) FROM default_borrower_circ_rules
16521         });
16522         $dbh->do(q{
16523             ALTER TABLE default_borrower_circ_rules DROP COLUMN max_holds
16524         });
16525     }
16526     SetVersion( $DBversion );
16527     print "Upgrade to $DBversion done (Bug 18887 - Introduce new table 'circulation_rules', use for 'max_holds' rules)\n";
16528 }
16529
16530 $DBversion = '18.06.00.037';
16531 if( CheckVersion( $DBversion ) ) {
16532     unless (TableExists('branches_overdrive')){
16533         $dbh->do( q|
16534             CREATE TABLE branches_overdrive (
16535                 `branchcode` VARCHAR( 10 ) NOT NULL ,
16536                 `authname` VARCHAR( 255 ) NOT NULL ,
16537                 PRIMARY KEY (`branchcode`) ,
16538                 CONSTRAINT `branches_overdrive_ibfk_1` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
16539             ) ENGINE = INNODB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci |
16540         );
16541     }
16542     $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');");
16543     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('OverDriveWebsiteID','', 'WebsiteID provided by OverDrive', NULL, 'Free');");
16544     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('OverDrivePasswordRequired','', 'Does the library require passwords for OverDrive SIP authentication', NULL, 'YesNo');");
16545     SetVersion( $DBversion );
16546     print "Upgrade to $DBversion done (Bug 21082 - Add overdrive patron auth method)\n";
16547 }
16548
16549 $DBversion = '18.06.00.038';
16550 if( CheckVersion( $DBversion ) ) {
16551     $dbh->do( "ALTER TABLE edifact_ean MODIFY branchcode VARCHAR(10) NULL DEFAULT NULL" );
16552     SetVersion( $DBversion );
16553     print "Upgrade to $DBversion done (Bug 21417 - EDI ordering fails when basket and EAN libraries do not match)\n";
16554 }
16555
16556 $DBversion = '18.06.00.039';
16557 if( CheckVersion( $DBversion ) ) {
16558     $dbh->do(q{
16559         INSERT IGNORE INTO `permissions` (module_bit, code, description) VALUES(3, 'manage_circ_rules_from_any_libraries', 'Manage circ rules for any libraries');
16560     });
16561     SetVersion( $DBversion );
16562     print "Upgrade to $DBversion done (Bug 15520 - Add more granular permission for only editing own library's circ rules)\n";
16563 }
16564
16565 $DBversion = '18.06.00.040';
16566 if( CheckVersion( $DBversion ) ) {
16567     # Stock Rotation Rotas
16568     unless (TableExists('stockrotationrotas')){
16569         $dbh->do(q{
16570           CREATE TABLE `stockrotationrotas` (
16571             `rota_id` int(11) auto_increment,         -- Stockrotation rota ID
16572             `title` varchar(100) NOT NULL,            -- Title for this rota
16573             `description` text NOT NULL,              -- Description for this rota
16574             `cyclical` tinyint(1) NOT NULL default 0, -- Should items on this rota keep cycling?
16575             `active` tinyint(1) NOT NULL default 0,   -- Is this rota currently active?
16576             PRIMARY KEY (`rota_id`),
16577             CONSTRAINT `stockrotationrotas_title`
16578             UNIQUE (`title`)
16579           ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16580         });
16581     }
16582     # Stock Rotation Stages
16583     unless (TableExists('stockrotationstages')){
16584         $dbh->do(q{
16585           CREATE TABLE `stockrotationstages` (
16586               `stage_id` int(11) auto_increment,     -- Unique stage ID
16587               `position` int(11) NOT NULL,           -- The position of this stage within its rota
16588               `rota_id` int(11) NOT NULL,            -- The rota this stage belongs to
16589               `branchcode_id` varchar(10) NOT NULL,  -- Branch this stage relates to
16590               `duration` int(11) NOT NULL default 4, -- The number of days items shoud occupy this stage
16591               PRIMARY KEY (`stage_id`),
16592               CONSTRAINT `stockrotationstages_rifk`
16593                 FOREIGN KEY (`rota_id`)
16594                 REFERENCES `stockrotationrotas` (`rota_id`)
16595                 ON UPDATE CASCADE ON DELETE CASCADE,
16596               CONSTRAINT `stockrotationstages_bifk`
16597                 FOREIGN KEY (`branchcode_id`)
16598                 REFERENCES `branches` (`branchcode`)
16599                 ON UPDATE CASCADE ON DELETE CASCADE
16600           ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16601         });
16602     }
16603     # Stock Rotation Items
16604     unless (TableExists('stockrotationitems')){
16605         $dbh->do(q{
16606           CREATE TABLE `stockrotationitems` (
16607               `itemnumber_id` int(11) NOT NULL,         -- Itemnumber to link to a stage & rota
16608               `stage_id` int(11) NOT NULL,              -- stage ID to link the item to
16609               `indemand` tinyint(1) NOT NULL default 0, -- Should this item be skipped for rotation?
16610               `fresh` tinyint(1) NOT NULL default 0,    -- Flag showing item is only just added to rota
16611               PRIMARY KEY (itemnumber_id),
16612               CONSTRAINT `stockrotationitems_iifk`
16613                 FOREIGN KEY (`itemnumber_id`)
16614                 REFERENCES `items` (`itemnumber`)
16615                 ON UPDATE CASCADE ON DELETE CASCADE,
16616               CONSTRAINT `stockrotationitems_sifk`
16617                 FOREIGN KEY (`stage_id`)
16618                 REFERENCES `stockrotationstages` (`stage_id`)
16619                 ON UPDATE CASCADE ON DELETE CASCADE
16620           ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16621         });
16622     }
16623     # System preferences
16624     $dbh->do(q{
16625         INSERT IGNORE INTO `systempreferences` (`variable`,`value`,`explanation`,`options`,`type`)
16626         VALUES ('StockRotation','0','If ON, enables the stock rotation module','','YesNo'),
16627                ('RotationPreventTransfers','0','If ON, prevent any transfers for items on stock rotation rotas, except for stock rotation transfers','','YesNo');
16628     });
16629     # Permissions
16630     $dbh->do(q{
16631         INSERT IGNORE INTO `userflags` (`bit`, `flag`, `flagdesc`, `defaulton`)
16632         VALUES (24, 'stockrotation', 'Manage stockrotation operations', 0);
16633     });
16634     $dbh->do(q{
16635         INSERT IGNORE INTO `permissions` (`module_bit`, `code`, `description`)
16636         VALUES (24, 'manage_rotas', 'Create, edit and delete rotas'),
16637                (24, 'manage_rota_items', 'Add and remove items from rotas');
16638     });
16639     # Notices
16640     $dbh->do(q{
16641         INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`)
16642         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');
16643     });
16644     print "Upgrade to $DBversion done (Bug 11897 - Add Stock Rotation Feature)\n";
16645     SetVersion( $DBversion );
16646 }
16647
16648 $DBversion = '18.06.00.041';
16649 if( CheckVersion( $DBversion ) ) {
16650
16651      if( !column_exists( 'illrequests', 'price_paid' ) ) {
16652         $dbh->do(q{
16653             ALTER TABLE illrequests
16654                 ADD COLUMN price_paid varchar(20) DEFAULT NULL
16655                 AFTER cost
16656         });
16657      }
16658
16659      if( !column_exists( 'illrequestattributes', 'readonly' ) ) {
16660         $dbh->do(q{
16661             ALTER TABLE illrequestattributes
16662                 ADD COLUMN readonly tinyint(1) NOT NULL DEFAULT 1
16663                 AFTER value
16664         });
16665         $dbh->do(q{
16666             UPDATE illrequestattributes SET readonly = 1
16667         });
16668      }
16669
16670     SetVersion( $DBversion );
16671     print "Upgrade to $DBversion done (Bug 20772 - Add illrequestattributes.readonly and illrequest.price_paid columns)\n";
16672 }
16673
16674 $DBversion = '18.06.00.042';
16675 if( CheckVersion( $DBversion ) ) {
16676     $dbh->do( "alter table statistics change column ccode ccode varchar(80) default NULL" );
16677
16678     SetVersion( $DBversion );
16679     print "Upgrade to $DBversion done (Bug 21617: Make statistics.ccode longer)\n";
16680 }
16681
16682 $DBversion = "18.06.00.043";
16683 if ( CheckVersion($DBversion) ) {
16684     if ( !column_exists( 'issuingrules', 'holds_per_day' ) ) {
16685         $dbh->do(q{
16686             ALTER TABLE `issuingrules`
16687                 ADD COLUMN `holds_per_day` SMALLINT(6) DEFAULT NULL
16688                 AFTER `holds_per_record`
16689         });
16690     }
16691     print "Upgrade to $DBversion done (Bug 15486: Restrict number of holds placed by day)\n";
16692     SetVersion($DBversion);
16693 }
16694
16695 $DBversion = '18.06.00.044';
16696 if( CheckVersion( $DBversion ) ) {
16697     unless( column_exists( 'creator_batches', 'description' ) ) {
16698         $dbh->do(q|ALTER TABLE creator_batches ADD description mediumtext default NULL AFTER batch_id|);
16699     }
16700     SetVersion( $DBversion );
16701     print "Upgrade to $DBversion done (Bug 15766: Add column creator_batches.description)\n";
16702 }
16703
16704 $DBversion = '18.06.00.045';
16705 if( CheckVersion( $DBversion ) ) {
16706     $dbh->do(q(
16707         INSERT IGNORE INTO message_transports
16708         (message_attribute_id,message_transport_type,is_digest,letter_module,letter_code)
16709         VALUES
16710         (2, 'phone', 0, 'circulation', 'PREDUE'),
16711         (2, 'phone', 1, 'circulation', 'PREDUEDGST'),
16712         (4, 'phone', 0, 'reserves',    'HOLD')
16713         ));
16714     SetVersion( $DBversion );
16715     print "Upgrade to $DBversion done (Bug 21639 - Add phone transports by default)\n";
16716 }
16717
16718 $DBversion = '18.06.00.046';
16719 if( CheckVersion( $DBversion ) ) {
16720     unless (TableExists('illcomments')) {
16721         $dbh->do(q{
16722             CREATE TABLE illcomments (
16723                 illcomment_id int(11) NOT NULL AUTO_INCREMENT, -- Unique ID of the comment
16724                 illrequest_id bigint(20) unsigned NOT NULL,    -- ILL request number
16725                 borrowernumber integer DEFAULT NULL,           -- Link to the user who made the comment (could be librarian, patron or ILL partner library)
16726                 comment text DEFAULT NULL,                     -- The text of the comment
16727                 timestamp timestamp DEFAULT CURRENT_TIMESTAMP, -- Date and time when the comment was made
16728                 PRIMARY KEY  ( illcomment_id ),
16729                 CONSTRAINT illcomments_bnfk
16730                   FOREIGN KEY ( borrowernumber )
16731                   REFERENCES  borrowers  ( borrowernumber )
16732                   ON UPDATE CASCADE ON DELETE CASCADE,
16733                 CONSTRAINT illcomments_ifk
16734                   FOREIGN KEY (illrequest_id)
16735                   REFERENCES illrequests ( illrequest_id )
16736                   ON UPDATE CASCADE ON DELETE CASCADE
16737             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16738         });
16739     }
16740
16741     SetVersion( $DBversion );
16742     print "Upgrade to $DBversion done (Bug 18591 - Add comments to ILL requests)\n";
16743 }
16744
16745 $DBversion = '18.06.00.047';
16746 if( CheckVersion( $DBversion ) ) {
16747     # insert the authorized_value_category for CONTROL_NUM_SEQUENCE
16748     $dbh->do( "INSERT IGNORE INTO authorised_value_categories values ('CONTROL_NUM_SEQUENCE');" );
16749     SetVersion( $DBversion );
16750     print "Upgrade to $DBversion done (Bug 19263 - Advanced Editor - Rancor - Add auto control number (001) widget)\n";
16751 }
16752
16753 $DBversion = '18.06.00.048';
16754 if( CheckVersion( $DBversion ) ) {
16755     $dbh->do( "ALTER TABLE stockrotationrotas CHANGE COLUMN description description text" );
16756     SetVersion( $DBversion );
16757     print "Upgrade to $DBversion done (Bug 21682 - Remove default on stockrotationrotas.description)\n";
16758 }
16759
16760 $DBversion = '18.06.00.049';
16761 if( CheckVersion( $DBversion ) ) {
16762     $dbh->do(q{
16763         UPDATE letter SET content = REPLACE(content,"item.reason ne \'in-demand\'","item.reason != \'in-demand\'")
16764         WHERE code="SR_SLIP";
16765     });
16766     print "Upgrade to $DBversion done (Bug 21656 - Stock Rotation Notice, Template Toolkit Syntax Correction)\n";
16767     SetVersion( $DBversion );
16768 }
16769
16770 $DBversion = '18.06.00.050';
16771 if( CheckVersion( $DBversion ) ) {
16772     $dbh->do(q{
16773         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');
16774     });
16775     print "Upgrade to $DBversion done (Bug 14385 - Add OpacHiddenItemExceptions)\n";
16776     SetVersion( $DBversion );
16777 }
16778
16779 $DBversion = '18.06.00.051';
16780 if( CheckVersion( $DBversion ) ) {
16781     $dbh->do(q{
16782         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES
16783         ('AdlibrisCoversEnabled', '0', NULL, 'Display cover images in OPAC results and detail listing from Swedish retailer Adlibris.','YesNo'),
16784         ('AdlibrisCoversURL', 'http://www.adlibris.com/se/organisationer/showimagesafe.aspx', NULL, 'Base URL for Adlibris cover image web service.', 'Free');
16785     });
16786     print "Upgrade to $DBversion done (Bug 8630 - Add covers from AdLibris to the OPAC and Intranet)\n";
16787     SetVersion( $DBversion );
16788 }
16789
16790 $DBversion = '18.06.00.052';
16791 if( CheckVersion( $DBversion ) ) {
16792     $dbh->do(q{
16793         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
16794            ( 3, 'manage_sysprefs', 'Manage global system preferences'),
16795            ( 3, 'manage_libraries', 'Manage libraries and library groups'),
16796            ( 3, 'manage_itemtypes', 'Manage item types'),
16797            ( 3, 'manage_auth_values', 'Manage authorized values'),
16798            ( 3, 'manage_patron_categories', 'Manage patron categories'),
16799            ( 3, 'manage_patron_attributes', 'Manage extended patron attributes'),
16800            ( 3, 'manage_transfers', 'Manage library transfer limits and transport cost matrix'),
16801            ( 3, 'manage_item_circ_alerts', 'Manage item circulation alerts'),
16802            ( 3, 'manage_cities', 'Manage cities and towns'),
16803            ( 3, 'manage_marc_frameworks', 'Manage MARC bibliographic and authority frameworks'),
16804            ( 3, 'manage_keywords2koha_mappings', 'Manage keywords to Koha mappings'),
16805            ( 3, 'manage_classifications', 'Manage classification sources'),
16806            ( 3, 'manage_matching_rules', 'Manage record matching rules'),
16807            ( 3, 'manage_oai_sets', 'Manage OAI sets'),
16808            ( 3, 'manage_item_search_fields', 'Manage item search fields'),
16809            ( 3, 'manage_search_engine_config', 'Manage search engine configuration'),
16810            ( 3, 'manage_search_targets', 'Manage Z39.50 and SRU server configuration'),
16811            ( 3, 'manage_didyoumean', 'Manage Did you mean? configuration'),
16812            ( 3, 'manage_column_config', 'Manage column configuration'),
16813            ( 3, 'manage_sms_providers', 'Manage SMS cellular providers'),
16814            ( 3, 'manage_audio_alerts', 'Manage audio alerts'),
16815            ( 3, 'manage_usage_stats', 'Manage usage statistics settings');
16816     });
16817     $dbh->do(q{
16818         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16819             SELECT borrowernumber, 3, 'manage_sysprefs' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16820     });
16821     $dbh->do(q{
16822         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16823             SELECT borrowernumber, 3, 'manage_libraries' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16824     });
16825     $dbh->do(q{
16826         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16827             SELECT borrowernumber, 3, 'manage_itemtypes' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16828     });
16829     $dbh->do(q{
16830         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16831             SELECT borrowernumber, 3, 'manage_auth_values' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16832     });
16833     $dbh->do(q{
16834         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16835             SELECT borrowernumber, 3, 'manage_patron_categories' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16836     });
16837     $dbh->do(q{
16838         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16839             SELECT borrowernumber, 3, 'manage_patron_attributes' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16840     });
16841     $dbh->do(q{
16842         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16843             SELECT borrowernumber, 3, 'manage_transfers' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16844     });
16845     $dbh->do(q{
16846         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16847             SELECT borrowernumber, 3, 'manage_item_circ_alerts' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16848     });
16849     $dbh->do(q{
16850         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16851             SELECT borrowernumber, 3, 'manage_cities' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16852     });
16853     $dbh->do(q{
16854         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16855             SELECT borrowernumber, 3, 'manage_marc_frameworks' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16856     });
16857     $dbh->do(q{
16858         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16859             SELECT borrowernumber, 3, 'manage_keywords2koha_mappings' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16860     });
16861     $dbh->do(q{
16862         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16863             SELECT borrowernumber, 3, 'manage_classifications' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16864     });
16865     $dbh->do(q{
16866         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16867             SELECT borrowernumber, 3, 'manage_matching_rules' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16868     });
16869     $dbh->do(q{
16870         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16871             SELECT borrowernumber, 3, 'manage_oai_sets' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16872     });
16873     $dbh->do(q{
16874         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16875             SELECT borrowernumber, 3, 'manage_item_search_fields' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16876     });
16877     $dbh->do(q{
16878         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16879             SELECT borrowernumber, 3, 'manage_search_engine_config' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16880     });
16881     $dbh->do(q{
16882         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16883             SELECT borrowernumber, 3, 'manage_search_targets' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16884     });
16885     $dbh->do(q{
16886         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16887             SELECT borrowernumber, 3, 'manage_didyoumean' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16888     });
16889     $dbh->do(q{
16890         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16891             SELECT borrowernumber, 3, 'manage_column_config' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16892     });
16893     $dbh->do(q{
16894         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16895             SELECT borrowernumber, 3, 'manage_sms_providers' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16896     });
16897     $dbh->do(q{
16898         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16899             SELECT borrowernumber, 3, 'manage_audio_alerts' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16900     });
16901     $dbh->do(q{
16902         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16903             SELECT borrowernumber, 3, 'manage_usage_stats' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16904     });
16905     $dbh->do(q{
16906         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16907             SELECT borrowernumber, 3, 'manage_item_search_fields' FROM borrowers WHERE flags & (1 << 2);
16908     });
16909     SetVersion( $DBversion );
16910     print "Upgrade to $DBversion done (Bug 14391: Add granular permissions to the administration module)\n";
16911 }
16912
16913 $DBversion = '18.06.00.053';
16914 if( CheckVersion( $DBversion ) ) {
16915     $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')" );
16916     SetVersion( $DBversion );
16917     print "Upgrade to $DBversion done (Bug 15494 - Block renewals by arbitrary item values)\n";
16918 }
16919
16920 $DBversion = '18.06.00.054';
16921 if( CheckVersion( $DBversion ) ) {
16922     if( !column_exists( 'search_field', 'weight' ) ) {
16923         $dbh->do( "ALTER TABLE `search_field` ADD COLUMN `weight` decimal(5,2) DEFAULT NULL AFTER `type`" );
16924     }
16925     SetVersion( $DBversion );
16926     print "Upgrade to $DBversion done (Bug 18316 - Add column search_field.weight)\n";
16927 }
16928
16929 $DBversion = '18.06.00.055';
16930 if( CheckVersion( $DBversion ) ) {
16931     unless( column_exists( 'issuingrules', 'note' ) ) {
16932         $dbh->do(q|ALTER TABLE `issuingrules` ADD `note` varchar(100) default NULL AFTER `article_requests`|);
16933     }
16934     SetVersion( $DBversion );
16935     print "Upgrade to $DBversion done (Bug 12365: Add column issuingrules.note)\n";
16936 }
16937
16938 $DBversion = '18.06.00.056';
16939 if( CheckVersion( $DBversion ) ) {
16940
16941     # All attributes we're potentially interested in
16942     my $ff_req = $dbh->selectall_arrayref(
16943         'SELECT a.illrequest_id, a.type, a.value '.
16944         'FROM illrequests r, illrequestattributes a '.
16945         'WHERE r.illrequest_id = a.illrequest_id '.
16946         'AND r.backend = "FreeForm"',
16947         { Slice => {} }
16948     );
16949
16950     # Before we go any further, identify whether we've done
16951     # this before, we test for the presence of "container_title"
16952     # We stop as soon as we find one
16953     foreach my $req(@{$ff_req}) {
16954         if ($req->{type} eq 'container_title') {
16955             warn "Upgrade already carried out";
16956         }
16957     }
16958
16959     # Transform into a hashref with the key of the request ID
16960     my $requests = {};
16961     foreach my $request(@{$ff_req}) {
16962         my $id = $request->{illrequest_id};
16963         if (!exists $requests->{$id}) {
16964             $requests->{$id} = {};
16965         }
16966         $requests->{$id}->{$request->{type}} = $request->{value};
16967     }
16968
16969     # Transform any article requests
16970     my $transformed = {};
16971     foreach my $id(keys %{$requests}) {
16972         if (lc($requests->{$id}->{type}) eq 'article') {
16973             $transformed->{$id} = $requests->{$id};
16974             $transformed->{$id}->{type} = 'article';
16975             $transformed->{$id}->{container_title} = $transformed->{$id}->{title}
16976                 if defined $transformed->{$id}->{title} &&
16977                     length $transformed->{$id}->{title} > 0;
16978             $transformed->{$id}->{title} = $transformed->{$id}->{article_title}
16979                 if defined $transformed->{$id}->{article_title} &&
16980                     length $transformed->{$id}->{article_title} > 0;
16981             $transformed->{$id}->{author} = $transformed->{$id}->{article_author}
16982                 if defined $transformed->{$id}->{article_author} &&
16983                     length $transformed->{$id}->{article_author} > 0;
16984             $transformed->{$id}->{pages} = $transformed->{$id}->{article_pages}
16985                 if defined $transformed->{$id}->{article_pages} &&
16986                     length $transformed->{$id}->{article_pages} > 0;
16987         }
16988     }
16989
16990     # Now write back the transformed data
16991     # Rather than selectively replace, we just remove all attributes we've
16992     # transformed and re-write them
16993     my @changed = keys %{$transformed};
16994     my $changed_str = join(',', @changed);
16995
16996     if (scalar @changed > 0) {
16997         my ($raise_error) = $dbh->{RaiseError};
16998         $dbh->{AutoCommit} = 0;
16999         $dbh->{RaiseError} = 1;
17000         eval {
17001             my $del = $dbh->do(
17002                 "DELETE FROM illrequestattributes ".
17003                 "WHERE illrequest_id IN ($changed_str)"
17004             );
17005             foreach my $reqid(keys %{$transformed}) {
17006                 my $attr = $transformed->{$reqid};
17007                 foreach my $key(keys %{$attr}) {
17008                     my $sth = $dbh->prepare(
17009                         'INSERT INTO illrequestattributes '.
17010                         '(illrequest_id, type, value) '.
17011                         'VALUES '.
17012                         '(?, ?, ?)'
17013                     );
17014                     $sth->execute(
17015                         $reqid,
17016                         $key,
17017                         $attr->{$key}
17018                     );
17019                 }
17020             }
17021             $dbh->commit;
17022         };
17023
17024         if ($@) {
17025             warn "Upgrade to $DBversion failed: $@\n";
17026             eval { $dbh->rollback };
17027         } else {
17028             SetVersion( $DBversion );
17029             print "Upgrade to $DBversion done (Bug 21079 - Unify metadata schema across backends)\n";
17030         }
17031
17032         $dbh->{AutoCommit} = 1;
17033         $dbh->{RaiseError} = $raise_error;
17034     }
17035
17036 }
17037
17038 $DBversion = '18.06.00.057';
17039 if( CheckVersion( $DBversion ) ) {
17040     # System preferences
17041     $dbh->do(q{
17042         INSERT IGNORE INTO `systempreferences` (`variable`,`value`,`explanation`,`options`,`type`)
17043         VALUES ('showLastPatron','0','','If ON, enables the last patron feature in the intranet','YesNo');
17044     });
17045     SetVersion( $DBversion );
17046     print "Upgrade to $DBversion done (Bug 20312 - Add showLastPatron systempreference)\n";
17047 }
17048
17049 $DBversion = '18.06.00.058';
17050 if( CheckVersion( $DBversion ) ) {
17051     $dbh->do(q{
17052         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES
17053         ('MarcFieldForCreatorId','',NULL,'Where to store the borrowernumber of the record''s creator','Free'),
17054         ('MarcFieldForCreatorName','',NULL,'Where to store the name of the record''s creator','Free'),
17055         ('MarcFieldForModifierId','',NULL,'Where to store the borrowernumber of the record''s last modifier','Free'),
17056         ('MarcFieldForModifierName','',NULL,'Where to store the name of the record''s last modifier','Free')
17057     });
17058
17059     SetVersion( $DBversion );
17060     print "Upgrade to $DBversion done (Bug 19349 - Add system preferences MarcFieldForCreatorId, MarcFieldForCreatorName, MarcFieldForModifierId, MarcFieldForModifierName)\n";
17061 }
17062
17063 $DBversion = '18.06.00.059';
17064 if( CheckVersion( $DBversion ) ) {
17065     $dbh->do(q{
17066         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type`) VALUES  ('EmailSMSSendDriverFromAddress', '', '', 'Email SMS send driver from address override', 'Free');
17067     });
17068     SetVersion( $DBversion );
17069     print "Upgrade to $DBversion done (Bug 20356 - Add EmailSMSSendDriverFromAddress system preference)\n";
17070 }
17071
17072 $DBversion = '18.06.00.060';
17073 if( CheckVersion( $DBversion ) ) {
17074     unless( TableExists( 'class_split_rules' ) ) {
17075         $dbh->do(q|
17076             CREATE TABLE class_split_rules (
17077               class_split_rule varchar(10) NOT NULL default '',
17078               description LONGTEXT,
17079               split_routine varchar(30) NOT NULL default '',
17080               split_regex varchar(255) NOT NULL default '',
17081               PRIMARY KEY (class_split_rule),
17082               UNIQUE KEY class_split_rule_idx (class_split_rule)
17083             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
17084         |);
17085
17086         $dbh->do(q|
17087             ALTER TABLE class_sources
17088             ADD COLUMN class_split_rule varchar(10) NOT NULL default ''
17089             AFTER class_sort_rule
17090         |);
17091
17092         $dbh->do(q|
17093             UPDATE class_sources
17094             SET class_split_rule = class_sort_rule
17095         |);
17096
17097         $dbh->do(q|
17098             UPDATE class_sources
17099             SET class_split_rule = 'generic'
17100             WHERE class_split_rule NOT IN('dewey', 'generic', 'lcc')
17101         |);
17102
17103         $dbh->do(q|
17104             INSERT INTO class_split_rules(class_split_rule, description, split_routine)
17105             VALUES
17106             ('dewey', 'Default sorting rules for DDC', 'Dewey'),
17107             ('lcc', 'Default sorting rules for LCC', 'LCC'),
17108             ('generic', 'Generic call number sorting rules', 'Generic')
17109         |);
17110
17111         $dbh->do(q|
17112             ALTER TABLE class_sources
17113             ADD CONSTRAINT class_source_ibfk_2 FOREIGN KEY (class_split_rule)
17114             REFERENCES class_split_rules (class_split_rule)
17115         |);
17116     }
17117
17118     SetVersion( $DBversion );
17119     print "Upgrade to $DBversion done (Bug 15836 - Add class_sort_rules.split_routine and split_regex)\n";
17120 }
17121
17122 $DBversion = '18.06.00.061';
17123 if ( CheckVersion($DBversion) ) {
17124     $dbh->do(q{
17125         INSERT IGNORE INTO `systempreferences` (`variable`,`value`,`explanation`,`options`,`type`) VALUES
17126         ('ElasticsearchIndexStatus_biblios', '0', 'Biblios index status', NULL, NULL),
17127         ('ElasticsearchIndexStatus_authorities', '0', 'Authorities index status', NULL, NULL)
17128     });
17129     SetVersion($DBversion);
17130     print "Upgrade to $DBversion done (Bug 19893 - Add elasticsearch index status preferences)\n";
17131 }
17132
17133 $DBversion = '18.06.00.062';
17134 if( CheckVersion( $DBversion ) ) {
17135     $dbh->do( "INSERT IGNORE INTO authorised_value_categories (category_name) VALUES ('PA_CLASS');");
17136     SetVersion( $DBversion );
17137     print "Upgrade to $DBversion done (Bug 21730: Add new authorised value category PA_CLASS)\n";
17138 }
17139
17140 $DBversion = '18.11.00.000';
17141 if( CheckVersion( $DBversion ) ) {
17142     SetVersion( $DBversion );
17143     print "Upgrade to $DBversion done (18.11.00 release)\n";
17144 }
17145
17146 $DBversion = '18.12.00.000';
17147 if( CheckVersion( $DBversion ) ) {
17148     SetVersion( $DBversion );
17149     print "Upgrade to $DBversion done (...and Steven!)\n";
17150 }
17151
17152 $DBversion = '18.12.00.001';
17153 if( CheckVersion( $DBversion ) ) {
17154     $dbh->do(q{
17155         UPDATE permissions SET code = 'manage_didyoumean' WHERE code = 'manage_didyouean';
17156     });
17157     $dbh->do(q{
17158         UPDATE user_permissions SET code = 'manage_didyoumean' WHERE code = 'manage_didyouean';
17159     });
17160     SetVersion( $DBversion );
17161     print "Upgrade to $DBversion (Bug 21961 - Fix typo in manage_didyoumean permission)\n";
17162 }
17163
17164 $DBversion = '18.12.00.002';
17165 if( CheckVersion( $DBversion ) ) {
17166     my $sth = $dbh->prepare(q|SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_NAME='accountlines_ibfk_1'|);
17167     $sth->execute;
17168     if ($sth->fetchrow_hashref) {
17169         $dbh->do(q|
17170             ALTER TABLE accountlines DROP FOREIGN KEY accountlines_ibfk_1;
17171         |);
17172         $dbh->do(q|
17173             ALTER TABLE accountlines CHANGE COLUMN borrowernumber borrowernumber INT(11) DEFAULT NULL;
17174         |);
17175         $dbh->do(q|
17176             ALTER TABLE accountlines ADD CONSTRAINT accountlines_ibfk_borrowers FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE SET NULL ON UPDATE CASCADE;
17177         |);
17178     }
17179     SetVersion( $DBversion );
17180     print "Upgrade to $DBversion done (Bug 21065 - Set ON DELETE SET NULL on accountlines.borrowernumber)\n";
17181 }
17182
17183 $DBversion = '18.12.00.003';
17184 if( CheckVersion( $DBversion ) ) {
17185     # On a new installation the class_sources.sql will have failed, so we need to add all missing data
17186     my( $sort_cnt ) = $dbh->selectrow_array( q|SELECT COUNT(*) FROM class_sort_rules|);
17187     if( !$sort_cnt ) {
17188         $dbh->do(q|INSERT INTO `class_sort_rules` (`class_sort_rule`, `description`, `sort_routine`) VALUES
17189                                ('dewey', 'Default filing rules for DDC', 'Dewey'),
17190                                ('lcc', 'Default filing rules for LCC', 'LCC'),
17191                                ('generic', 'Generic call number filing rules', 'Generic')
17192             |);
17193     }
17194
17195     my ( $split_cnt ) = $dbh->selectrow_array( q|SELECT COUNT(*) FROM class_split_rules|);
17196     if( !$split_cnt ) {
17197         $dbh->do(q|INSERT INTO `class_split_rules` (`class_split_rule`, `description`, `split_routine`) VALUES
17198                                ('dewey', 'Default splitting rules for DDC', 'Dewey'),
17199                                ('lcc', 'Default splitting rules for LCC', 'LCC'),
17200                                ('generic', 'Generic call number splitting rules', 'Generic')
17201             |);
17202     }
17203
17204     my( $source_cnt ) = $dbh->selectrow_array( q|SELECT COUNT(*) FROM class_sources|);
17205     if( !$source_cnt ) {
17206         $dbh->do(q|INSERT INTO `class_sources` (`cn_source`, `description`, `used`, `class_sort_rule`, `class_split_rule`) VALUES
17207                             ('ddc', 'Dewey Decimal Classification', 1, 'dewey', 'dewey'),
17208                             ('lcc', 'Library of Congress Classification', 1, 'lcc', 'lcc'),
17209                             ('udc', 'Universal Decimal Classification', 0, 'generic', 'generic'),
17210                             ('sudocs', 'SuDoc Classification (U.S. GPO)', 0, 'generic', 'generic'),
17211                             ('anscr', 'ANSCR (Sound Recordings)', 0, 'generic', 'generic'),
17212                             ('z', 'Other/Generic Classification Scheme', 0, 'generic', 'generic')
17213             |);
17214
17215     }
17216
17217     SetVersion( $DBversion );
17218     print "Upgrade to $DBversion done (Bug 22024 - Add missing splitting rule definitions)\n";
17219 }
17220
17221 $DBversion = '18.12.00.004';
17222 if( CheckVersion( $DBversion ) ) {
17223     if( !column_exists( 'accountlines', 'branchcode' ) ) {
17224         $dbh->do("ALTER TABLE accountlines ADD branchcode VARCHAR( 10 ) NULL DEFAULT NULL AFTER manager_id");
17225         $dbh->do("ALTER TABLE accountlines ADD CONSTRAINT accountlines_ibfk_branches FOREIGN KEY (branchcode) REFERENCES branches (branchcode) ON DELETE SET NULL ON UPDATE CASCADE");
17226     }
17227     SetVersion( $DBversion );
17228     print "Upgrade to $DBversion done (Bug 19066 - Add branchcode to accountlines)\n";
17229 }
17230
17231 $DBversion = '18.12.00.005';
17232 if( CheckVersion( $DBversion ) ) {
17233     $dbh->do(q{
17234         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
17235         ('OverDriveUsername','cardnumber','cardnumber|userid','Which patron information should be passed as OverDrive username','Choice')
17236     });
17237     SetVersion( $DBversion );
17238     print "Upgrade to $DBversion done (Bug 22030: Add OverDriveUsername syspref)\n";
17239 }
17240
17241 $DBversion = '18.12.00.006';
17242 if( CheckVersion( $DBversion ) ) {
17243     $dbh->do(q{
17244         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
17245         ('AccountAutoReconcile','0','If enabled, patron balances will get reconciled automatically on each transaction.',NULL,'YesNo');
17246     });
17247     SetVersion($DBversion);
17248     print "Upgrade to $DBversion done (Bug 21915 - Add a way to automatically reconcile balance for patrons)\n";
17249 }
17250
17251 $DBversion = '18.12.00.007';
17252 if( CheckVersion( $DBversion ) ) {
17253     if( column_exists( 'issuingrules', 'chargename' ) ) {
17254         $dbh->do( "ALTER TABLE issuingrules DROP chargename" );
17255     }
17256     SetVersion( $DBversion );
17257     print "Upgrade to $DBversion done (Bug 21753: Drop chargename from issuingrules )\n";
17258 }
17259
17260 $DBversion = '18.12.00.008';
17261 if( CheckVersion( $DBversion ) ) {
17262     if( !column_exists( 'subscription', 'mana_id' ) ) {
17263         $dbh->do( "ALTER TABLE subscription ADD mana_id int(11) NULL DEFAULT NULL" );
17264     }
17265
17266     if( !column_exists( 'saved_sql', 'mana_id' ) ) {
17267         $dbh->do( "ALTER TABLE saved_sql ADD mana_id int(11) NULL DEFAULT NULL" );
17268     }
17269     $dbh->do(q{
17270         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
17271         ('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');
17272     });
17273     $dbh->do(q{
17274         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
17275         ('AutoShareWithMana','','','defines datas automatically shared with mana','multiple');
17276     });
17277     $dbh->do(q{
17278         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
17279         ('ManaToken','',NULL,'Security token used for authentication on Mana KB service (anti spam)','Textarea');
17280     });
17281     SetVersion( $DBversion );
17282     print "Upgrade to $DBversion done (Bug 17047 - Mana knowledge base)\n";
17283 }
17284
17285 $DBversion = '18.12.00.009';
17286 if( CheckVersion( $DBversion ) ) {
17287     $dbh->do(q{
17288         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');
17289     });
17290     SetVersion( $DBversion );
17291     print "Upgrade to $DBversion done (Bug 21241 - Add FallbackToSMSIfNoEmail syspref )\n";
17292 }
17293
17294 $DBversion = '18.12.00.010';
17295 if( CheckVersion( $DBversion ) ) {
17296     $dbh->do(q{
17297         INSERT IGNORE INTO systempreferences
17298             ( variable, value, options, explanation, type )
17299         VALUES
17300             ('RESTPublicAPI','1',NULL,'If enabled, the REST API will expose the /public endpoints.','YesNo')
17301     });
17302
17303     # Always end with this (adjust the bug info)
17304     SetVersion( $DBversion );
17305     print "Upgrade to $DBversion done (Bug 22061 - Add a /public namespace that can be switched on/off)\n";
17306 }
17307
17308 $DBversion = '18.12.00.011';
17309 if( CheckVersion( $DBversion ) ) {
17310     if ( column_exists( 'biblio_metadata', 'marcflavour' ) ) {
17311         $dbh->do(q{
17312             ALTER TABLE biblio_metadata
17313                 CHANGE COLUMN marcflavour `schema` VARCHAR(16)
17314         });
17315     }
17316     if ( column_exists( 'deletedbiblio_metadata', 'marcflavour' ) ) {
17317         $dbh->do(q{
17318             ALTER TABLE deletedbiblio_metadata
17319                 CHANGE COLUMN marcflavour `schema` VARCHAR(16)
17320         });
17321     }
17322     SetVersion( $DBversion );
17323     print "Upgrade to $DBversion done (Bug 22155 - biblio_metadata.marcflavour should be renamed 'schema')\n";
17324 }
17325
17326 $DBversion = '18.12.00.012';
17327 if( CheckVersion( $DBversion ) ) {
17328     $dbh->do(q{
17329         INSERT IGNORE INTO systempreferences
17330             (variable, value, options, explanation, type )
17331         VALUES
17332             ('RESTBasicAuth','0',NULL,'If enabled, Basic authentication is enabled for the REST API.','YesNo')
17333     });
17334     SetVersion( $DBversion );
17335     print "Upgrade to $DBversion done (Bug 22132 - Add Basic authentication)\n";
17336 }
17337
17338 $DBversion = '18.12.00.013';
17339 if( CheckVersion( $DBversion ) ) {
17340     $dbh->do(q{
17341         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES ( 3, 'manage_mana', 'Manage Mana KB content sharing');
17342     });
17343     SetVersion( $DBversion );
17344     print "Upgrade to $DBversion done (Bug 22198 - Add ghranular permission setting for Mana KB)\n";
17345 }
17346
17347 $DBversion = '18.12.00.014';
17348 if( CheckVersion( $DBversion ) ) {
17349     unless( foreign_key_exists( 'messages', 'messages_borrowernumber' ) ) {
17350         $dbh->do(q|
17351             DELETE m FROM messages m
17352             LEFT JOIN borrowers b ON m.borrowernumber=b.borrowernumber
17353             WHERE b.borrowernumber IS NULL
17354         |);
17355         $dbh->do(q|
17356             ALTER TABLE messages
17357             ADD CONSTRAINT messages_borrowernumber
17358             FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
17359         |);
17360     }
17361     SetVersion( $DBversion );
17362     print "Upgrade to $DBversion done (Bug 13515 - Add a FOREIGN KEY constaint on messages.borrowernumber)\n";
17363 }
17364
17365 $DBversion = '18.12.00.015';
17366 if( CheckVersion( $DBversion ) ) {
17367     $dbh->do( "UPDATE action_logs SET info = REPLACE(info,'cardnumber_replaced','cardnumber'), timestamp = timestamp WHERE module='MEMBERS' AND action='MODIFY'" );
17368     $dbh->do( "UPDATE action_logs SET info = REPLACE(info,'previous_cardnumber','before'), timestamp = timestamp WHERE module='MEMBERS' AND action='MODIFY'" );
17369     $dbh->do( "UPDATE action_logs SET info = REPLACE(info,'new_cardnumber','after'), timestamp = timestamp WHERE module='MEMBERS' AND action='MODIFY'" );
17370
17371     SetVersion( $DBversion );
17372     print "Upgrade to $DBversion done (Bug 3820 - Update patron modification logs)\n";
17373 }
17374
17375 $DBversion = '18.12.00.016';
17376 if( CheckVersion( $DBversion ) ) {
17377
17378     if ( !column_exists( 'illrequests', 'status_alias' ) ) {
17379         # Fresh upgrade, just add the column and constraint
17380         $dbh->do( "ALTER TABLE illrequests ADD COLUMN status_alias varchar(80) DEFAULT NULL AFTER status" );
17381     } else {
17382         # Migrate all existing foreign keys from referencing authorised_values.id
17383         # to referencing authorised_values.authorised_value
17384         # First remove the foreign key constraint and index
17385         if ( foreign_key_exists( 'illrequests', 'illrequests_safk' ) ) {
17386             $dbh->do( "ALTER TABLE illrequests DROP FOREIGN KEY illrequests_safk");
17387         }
17388         if ( index_exists( 'illrequests', 'illrequests_safk' ) ) {
17389             $dbh->do( "DROP INDEX illrequests_safk ON illrequests" );
17390         }
17391         # Now change the illrequests.status_alias column definition from int to varchar
17392         $dbh->do( "ALTER TABLE illrequests MODIFY COLUMN status_alias varchar(80)" );
17393         # Now replace all references to authorised_values.id with their
17394         # corresponding authorised_values.authorised_value
17395         my $sth = $dbh->prepare( "SELECT illrequest_id, status_alias FROM illrequests WHERE status_alias IS NOT NULL" );
17396         $sth->execute();
17397         while (my @row = $sth->fetchrow_array()) {
17398             my $r_id = $row[0];
17399             my $av_id = $row[1];
17400             # Get the authorised value's authorised_value value
17401             my ($av_val) = $dbh->selectrow_array( "SELECT authorised_value FROM authorised_values WHERE id = ?", {}, $av_id );
17402             # Now update illrequests.status_alias
17403             if ($av_val) {
17404                 $dbh->do( "UPDATE illrequests SET status_alias = ? WHERE illrequest_id = ?", {}, ($av_val, $r_id) );
17405             }
17406         }
17407     }
17408     if ( !foreign_key_exists( 'illrequests', 'illrequests_safk' ) ) {
17409         $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" );
17410     }
17411     $dbh->do( "INSERT IGNORE INTO authorised_value_categories SET category_name = 'ILLSTATUS'");
17412
17413     SetVersion( $DBversion );
17414     print "Upgrade to $DBversion done (Bug 20581 - Allow manual selection of custom ILL request statuses)\n";
17415 }
17416
17417 $DBversion = '18.12.00.017';
17418 if( CheckVersion( $DBversion ) ) {
17419     $dbh->do(q{
17420         INSERT IGNORE INTO account_offset_types ( type ) VALUES ( 'fine_increase' ), ( 'fine_decrease' );
17421     });
17422     $dbh->do(q{
17423         UPDATE account_offsets SET type = 'fine_increase' WHERE type = 'Fine Update' AND amount > 0;
17424     });
17425     $dbh->do(q{
17426         UPDATE account_offsets SET type = 'fine_decrease' WHERE type = 'Fine Update' AND amount < 0;
17427     });
17428
17429     $dbh->do(q{
17430         DELETE FROM account_offset_types WHERE type = 'Fine Update';
17431     });
17432     SetVersion( $DBversion );
17433     print "Upgrade to $DBversion done (Bug 21747 - Update account_offset_types to include 'fine_increase' and 'fine_decrease')\n";
17434 }
17435
17436 $DBversion = '18.12.00.018';
17437 if( CheckVersion( $DBversion ) ) {
17438   $dbh->do( "UPDATE `search_field` SET `name` = 'date-of-publication', `label` = 'date-of-publication' WHERE `name` = 'pubdate'" );
17439   $dbh->do( "UPDATE `search_field` SET `name` = 'title-series', `label` = 'title-series' WHERE `name` = 'se'" );
17440   $dbh->do( "UPDATE `search_field` SET `name` = 'identifier-standard', `label` = 'identifier-standard' WHERE `name` = 'identifier-standard'" );
17441   $dbh->do( "UPDATE `search_field` SET `name` = 'author', `label` = 'author' WHERE `name` = 'author'" );
17442   $dbh->do( "UPDATE `search_field` SET `name` = 'control-number', `label` = 'control-number' WHERE `name` = 'control-number'" );
17443   $dbh->do( "UPDATE `search_field` SET `name` = 'place-of-publication', `label` = 'place-of-publication' WHERE `name` = 'place'" );
17444   $dbh->do( "UPDATE `search_field` SET `name` = 'date-of-acquisition', `label` = 'date-of-acquisition' WHERE `name` = 'acqdate'" );
17445   $dbh->do( "UPDATE `search_field` SET `name` = 'isbn', `label` = 'isbn' WHERE `name` = 'isbn'" );
17446   $dbh->do( "UPDATE `search_field` SET `name` = 'koha-auth-number', `label` = 'koha-auth-number' WHERE `name` = 'an'" );
17447   $dbh->do( "UPDATE `search_field` SET `name` = 'subject', `label` = 'subject' WHERE `name` = 'subject'" );
17448   $dbh->do( "UPDATE `search_field` SET `name` = 'publisher', `label` = 'publisher' WHERE `name` = 'publisher'" );
17449   $dbh->do( "UPDATE `search_field` SET `name` = 'record-source', `label` = 'record-source' WHERE `name` = 'record-source'" );
17450   $dbh->do( "UPDATE `search_field` SET `name` = 'title', `label` = 'title' WHERE `name` = 'title'" );
17451   $dbh->do( "UPDATE `search_field` SET `name` = 'local-classification', `label` = 'local-classification' WHERE `name` = 'local-classification'" );
17452   $dbh->do( "UPDATE `search_field` SET `name` = 'bib-level', `label` = 'bib-level' WHERE `name` = 'bib-level'" );
17453   $dbh->do( "UPDATE `search_field` SET `name` = 'microform-generation', `label` = 'microform-generation' WHERE `name` = 'microform-generation'" );
17454   $dbh->do( "UPDATE `search_field` SET `name` = 'material-type', `label` = 'material-type' WHERE `name` = 'material-type'" );
17455   $dbh->do( "UPDATE `search_field` SET `name` = 'bgf-number', `label` = 'bgf-number' WHERE `name` = 'bgf-number'" );
17456   $dbh->do( "UPDATE `search_field` SET `name` = 'number-db', `label` = 'number-db' WHERE `name` = 'number-db'" );
17457   $dbh->do( "UPDATE `search_field` SET `name` = 'number-natl-biblio', `label` = 'number-natl-biblio' WHERE `name` = 'number-natl-biblio'" );
17458   $dbh->do( "UPDATE `search_field` SET `name` = 'number-legal-deposit', `label` = 'number-legal-deposit' WHERE `name` = 'number-legal-deposit'" );
17459   $dbh->do( "UPDATE `search_field` SET `name` = 'issn', `label` = 'issn' WHERE `name` = 'issn'" );
17460   $dbh->do( "UPDATE `search_field` SET `name` = 'local-number', `label` = 'local-number' WHERE `name` = 'local-number'" );
17461   $dbh->do( "UPDATE `search_field` SET `name` = 'suppress', `label` = 'supress' WHERE `name` = 'suppress'" );
17462   $dbh->do( "UPDATE `search_field` SET `name` = 'bnb-card-number', `label` = 'bnb-card-number' WHERE `name` = 'bnb-card-number'" );
17463   $dbh->do( "UPDATE `search_field` SET `name` = 'date/time-last-modified', `label` = 'date/time-last-modified' WHERE `name` = 'date-time-last-modified'" );
17464   $dbh->do( "DELETE FROM `search_field` WHERE `name` = 'lc-cardnumber'" );
17465   $dbh->do( "DELETE FROM `search_marc_map` WHERE `id` NOT IN(SELECT `search_marc_map_id` FROM `search_marc_to_field`)" );
17466   SetVersion( $DBversion );
17467   print "Upgrade to $DBversion done (Bug 19575 - Use canonical field names and resolve aliased fields)\n";
17468 }
17469
17470 $DBversion = '18.12.00.019';
17471 if( CheckVersion( $DBversion ) ) {
17472     $dbh->do(q{
17473         INSERT IGNORE INTO account_offset_types ( type ) VALUES ( 'Reserve Fee' );
17474     });
17475
17476     SetVersion( $DBversion );
17477     print "Upgrade to $DBversion done (Bug 21728 - Add 'Reserve Fee' to the account_offset_types table if missing)\n";
17478 }
17479
17480 $DBversion = '18.12.00.020';
17481 if( CheckVersion( $DBversion ) ) {
17482     if ( TableExists( 'branch_borrower_circ_rules' ) ) {
17483         if ( column_exists( 'branch_borrower_circ_rules', 'maxissueqty' ) ) {
17484             $dbh->do("
17485                 INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17486                 SELECT categorycode, branchcode, NULL, 'patron_maxissueqty', COALESCE( maxissueqty, '' )
17487                 FROM branch_borrower_circ_rules
17488             ");
17489             $dbh->do("
17490                 INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17491                 SELECT categorycode, branchcode, NULL, 'patron_maxonsiteissueqty', COALESCE( maxonsiteissueqty, '' )
17492                 FROM branch_borrower_circ_rules
17493             ");
17494             $dbh->do("DROP TABLE branch_borrower_circ_rules");
17495         }
17496     }
17497
17498     if ( TableExists( 'default_borrower_circ_rules' ) ) {
17499         if ( column_exists( 'default_borrower_circ_rules', 'maxissueqty' ) ) {
17500             $dbh->do("
17501                 INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17502                 SELECT categorycode, NULL, NULL, 'patron_maxissueqty', COALESCE( maxissueqty, '' )
17503                 FROM default_borrower_circ_rules
17504             ");
17505             $dbh->do("
17506                 INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17507                 SELECT categorycode, NULL, NULL, 'patron_maxonsiteissueqty', COALESCE( maxonsiteissueqty, '' )
17508                 FROM default_borrower_circ_rules
17509             ");
17510             $dbh->do("DROP TABLE default_borrower_circ_rules");
17511         }
17512     }
17513
17514     if ( column_exists( 'default_circ_rules', 'maxissueqty' ) ) {
17515         $dbh->do("
17516             INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17517             SELECT NULL, NULL, NULL, 'patron_maxissueqty', COALESCE( maxissueqty, '' )
17518             FROM default_circ_rules
17519         ");
17520         $dbh->do("
17521             INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17522             SELECT NULL, NULL, NULL, 'patron_maxonsiteissueqty', COALESCE( maxonsiteissueqty, '' )
17523             FROM default_circ_rules
17524         ");
17525         $dbh->do("ALTER TABLE default_circ_rules DROP COLUMN maxissueqty, DROP COLUMN maxonsiteissueqty");
17526     }
17527
17528     if ( column_exists( 'default_branch_circ_rules', 'maxissueqty' ) ) {
17529         $dbh->do("
17530             INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17531             SELECT NULL, branchcode, NULL, 'patron_maxissueqty', COALESCE( maxissueqty, '' )
17532             FROM default_branch_circ_rules
17533         ");
17534         $dbh->do("
17535             INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17536             SELECT NULL, NULL, NULL, 'patron_maxonsiteissueqty', COALESCE( maxonsiteissueqty, '' )
17537             FROM default_branch_circ_rules
17538         ");
17539         $dbh->do("ALTER TABLE default_branch_circ_rules DROP COLUMN maxissueqty, DROP COLUMN maxonsiteissueqty");
17540     }
17541
17542     if ( column_exists( 'issuingrules', 'maxissueqty' ) ) {
17543         # Cleaning invalid rules before, to avoid FK contraints to fail
17544         $dbh->do(q|
17545             DELETE FROM issuingrules WHERE categorycode != '*' AND categorycode NOT IN (SELECT categorycode FROM categories);
17546         |);
17547         $dbh->do(q|
17548             DELETE FROM issuingrules WHERE branchcode != '*' AND branchcode NOT IN (SELECT branchcode FROM branches);
17549         |);
17550         $dbh->do(q|
17551             DELETE FROM issuingrules WHERE itemtype != '*' AND itemtype NOT IN (SELECT itemtype FROM itemtypes);
17552         |);
17553
17554         $dbh->do("
17555             INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17556             SELECT IF(categorycode='*', NULL, categorycode),
17557                    IF(branchcode='*', NULL, branchcode),
17558                    IF(itemtype='*', NULL, itemtype),
17559                    'maxissueqty',
17560                    COALESCE( maxissueqty, '' )
17561             FROM issuingrules
17562         ");
17563         $dbh->do("
17564             INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17565             SELECT IF(categorycode='*', NULL, categorycode),
17566                    IF(branchcode='*', NULL, branchcode),
17567                    IF(itemtype='*', NULL, itemtype),
17568                    'maxonsiteissueqty',
17569                    COALESCE( maxonsiteissueqty, '' )
17570             FROM issuingrules
17571         ");
17572         $dbh->do("ALTER TABLE issuingrules DROP COLUMN maxissueqty, DROP COLUMN maxonsiteissueqty");
17573     }
17574
17575     SetVersion( $DBversion );
17576     print "Upgrade to $DBversion done (Bug 18925 - Move maxissueqty and maxonsiteissueqty to circulation_rules)\n";
17577 }
17578
17579 $DBversion = '18.12.00.021';
17580 if ( CheckVersion($DBversion) ) {
17581
17582     if ( !column_exists( 'itemtypes', 'rentalcharge_daily' ) ) {
17583         $dbh->do("ALTER TABLE `itemtypes` ADD COLUMN `rentalcharge_daily` decimal(28,6) default NULL AFTER `rentalcharge`");
17584     }
17585
17586     if ( !column_exists( 'itemtypes', 'rentalcharge_hourly' ) ) {
17587         $dbh->do("ALTER TABLE `itemtypes` ADD COLUMN `rentalcharge_hourly` decimal(28,6) default NULL AFTER `rentalcharge_daily`");
17588     }
17589
17590     if ( column_exists( 'itemtypes', 'rental_charge_daily' ) ) {
17591         $dbh->do("UPDATE `itemtypes` SET `rentalcharge_daily` = `rental_charge_daily`");
17592         $dbh->do("ALTER TABLE `itemtypes` DROP COLUMN `rental_charge_daily`");
17593     }
17594
17595     SetVersion($DBversion);
17596     print "Upgrade to $DBversion done (Bug 20912 - Support granular rental charges)\n";
17597 }
17598
17599 $DBversion = '18.12.00.022';
17600 if( CheckVersion( $DBversion ) ) {
17601     $dbh->do( q{
17602         INSERT IGNORE INTO permissions (module_bit,code,description)
17603         VALUES
17604         (3,'manage_additional_fields','Add, edit, or delete additional custom fields for baskets or subscriptions (also requires order_manage or edit_subscription permissions)')
17605     });
17606     $dbh->do( q{
17607         INSERT INTO user_permissions (borrowernumber, module_bit, code)
17608         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');
17609     });
17610     $dbh->do( q{
17611         INSERT INTO user_permissions (borrowernumber, module_bit, code)
17612         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);
17613     });
17614     SetVersion( $DBversion );
17615     print "Upgrade to $DBversion done (Bug 15774 - Add permission for managing additional fields)\n";
17616 }
17617
17618 $DBversion = '18.12.00.023';
17619 if( CheckVersion( $DBversion ) ) {
17620     $dbh->do(q|
17621       INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
17622       VALUES ('ILLOpacbackends',NULL,NULL,'ILL backends to enabled for OPAC initiated requests','multiple');
17623     |);
17624
17625     # Always end with this (adjust the bug info)
17626     SetVersion( $DBversion );
17627     print "Upgrade to $DBversion done (Bug 20639 - Add ILLOpacbackends syspref)\n";
17628 }
17629
17630 $DBversion = '18.12.00.024';
17631 if ( CheckVersion($DBversion) ) {
17632
17633     # Fixup any pre-existing bad suggestedby, manageddate, accepteddate dates
17634     eval {
17635         local $dbh->{PrintError} = 0;
17636         $dbh->do(
17637             "UPDATE suggestions SET suggesteddate = '1970-01-01' WHERE suggesteddate = '0000-00-00';"
17638         );
17639         $dbh->do(
17640             "UPDATE suggestions SET manageddate = '1970-01-01' WHERE manageddate = '0000-00-00';"
17641         );
17642         $dbh->do(
17643             "UPDATE suggestions SET accepteddate = '1970-01-01' WHERE accepteddate = '0000-00-00';"
17644         );
17645     };
17646
17647     # Add constraint for suggestedby
17648     unless ( foreign_key_exists( 'suggestions', 'suggestions_ibfk_suggestedby' ) )
17649     {
17650         $dbh->do(
17651 "ALTER TABLE suggestions CHANGE COLUMN suggestedby suggestedby INT(11) NULL DEFAULT NULL;"
17652         );
17653         $dbh->do(
17654 "UPDATE suggestions LEFT JOIN borrowers ON (suggestions.suggestedby = borrowers.borrowernumber) SET suggestedby = null WHERE borrowernumber IS null"
17655         );
17656         $dbh->do(
17657 "ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_suggestedby` FOREIGN KEY (`suggestedby`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE"
17658         );
17659     }
17660
17661     # Add constraint for managedby
17662     unless ( foreign_key_exists( 'suggestions', 'suggestions_ibfk_managedby' ) )
17663     {
17664         $dbh->do(
17665 "UPDATE suggestions LEFT JOIN borrowers ON (suggestions.managedby = borrowers.borrowernumber) SET managedby = null WHERE borrowernumber IS NULL"
17666         );
17667         $dbh->do(
17668 "ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_managedby` FOREIGN KEY (`managedby`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE"
17669         );
17670     }
17671
17672     # Add constraint for acceptedby
17673     unless (
17674         foreign_key_exists( 'suggestions', 'suggestions_ibfk_acceptedby' ) )
17675     {
17676         $dbh->do(
17677 "UPDATE suggestions LEFT JOIN borrowers ON (suggestions.acceptedby = borrowers.borrowernumber) SET acceptedby = null WHERE borrowernumber IS NULL"
17678         );
17679         $dbh->do(
17680 "ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_acceptedby` FOREIGN KEY (`acceptedby`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE"
17681         );
17682     }
17683
17684     # Add constraint for rejectedby
17685     unless (
17686         foreign_key_exists( 'suggestions', 'suggestions_ibfk_rejectedby' ) )
17687     {
17688         $dbh->do(
17689 "UPDATE suggestions LEFT JOIN borrowers ON (suggestions.rejectedby = borrowers.borrowernumber) SET rejectedby = null WHERE borrowernumber IS null"
17690         );
17691         $dbh->do(
17692 "ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_rejectedby` FOREIGN KEY (`rejectedby`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE"
17693         );
17694     }
17695
17696     # Add constraint for biblionumber
17697     unless (
17698         foreign_key_exists( 'suggestions', 'suggestions_ibfk_biblionumber' ) )
17699     {
17700         $dbh->do(
17701 "UPDATE suggestions s LEFT JOIN biblio b ON (s.biblionumber = b.biblionumber) SET s.biblionumber = null WHERE b.biblionumber IS null"
17702         );
17703         $dbh->do(
17704 "ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_biblionumber` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE SET NULL ON UPDATE CASCADE"
17705         );
17706     }
17707
17708     # Add constraint for branchcode
17709     unless (
17710         foreign_key_exists( 'suggestions', 'suggestions_ibfk_branchcode' ) )
17711     {
17712         $dbh->do(
17713 "UPDATE suggestions s LEFT JOIN branches b ON (s.branchcode = b.branchcode) SET s.branchcode = null WHERE b.branchcode IS null"
17714         );
17715         $dbh->do(
17716 "ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_branchcode` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE SET NULL ON UPDATE CASCADE"
17717         );
17718     }
17719
17720     SetVersion($DBversion);
17721     print
17722 "Upgrade to $DBversion done (Bug 22368 - Add missing constraints to suggestions)\n";
17723 }
17724
17725 $DBversion = '18.12.00.025';
17726 if( CheckVersion( $DBversion ) ) {
17727
17728     $dbh->do('SET FOREIGN_KEY_CHECKS=0');
17729
17730     # Change columns accordingly
17731     $dbh->do(q{
17732         ALTER TABLE tags_index
17733             MODIFY COLUMN term VARCHAR(191) COLLATE utf8mb4_bin NOT NULL;
17734     });
17735
17736     $dbh->do(q{
17737         ALTER TABLE tags_approval
17738             MODIFY COLUMN term VARCHAR(191) COLLATE utf8mb4_bin NOT NULL;
17739     });
17740
17741     $dbh->do(q{
17742         ALTER TABLE tags_all
17743             MODIFY COLUMN term VARCHAR(191) COLLATE utf8mb4_bin NOT NULL;
17744     });
17745
17746     $dbh->do('SET FOREIGN_KEY_CHECKS=1');
17747
17748     SetVersion( $DBversion );
17749     print "Upgrade to $DBversion done (Bug 21846 - Using emoji as tags has broken weights)\n";
17750     my $maintenance_script = C4::Context->config("intranetdir") . "/misc/maintenance/fix_tags_weight.pl";
17751     print "WARNING: (Bug 21846) You need to manually run $maintenance_script to fix possible issues with tags.\n";
17752 }
17753
17754 $DBversion = '18.12.00.026';
17755 if( CheckVersion( $DBversion ) ) {
17756     $dbh->do( "INSERT IGNORE INTO systempreferences (variable, value, explanation, type) VALUES ('IllLog', 0, 'If ON, log information about ILL requests', 'YesNo')" );
17757
17758     SetVersion( $DBversion );
17759     print "Upgrade to $DBversion done (Bug 20750 - Allow timestamped auditing of ILL request events)\n";
17760 }
17761
17762 $DBversion = '18.12.00.027';
17763 if( CheckVersion( $DBversion ) ) {
17764     $dbh->do(q{
17765 INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
17766        ('ILLModuleUnmediated','0','','If enabled, try to immediately progress newly placed ILL requests.','YesNo');
17767     });
17768     SetVersion( $DBversion );
17769     print "Upgrade to $DBversion done (Bug 18837: Add ILLModuleUnmediated Syspref)\n";
17770 }
17771
17772 $DBversion = '18.12.00.028';
17773 if( CheckVersion( $DBversion ) ) {
17774     $dbh->do(q{
17775         INSERT IGNORE INTO account_offset_types ( type ) VALUES ( 'Account Fee' );
17776     });
17777
17778     $dbh->do(q{
17779         INSERT IGNORE INTO account_offset_types ( type ) VALUES ( 'Hold Expired' );
17780     });
17781
17782     SetVersion( $DBversion );
17783     print "Upgrade to $DBversion done (Bug 21756 - Add 'Account Fee' and 'Hold Expired' to the account_offset_types table if missing)\n";
17784 }
17785
17786 $DBversion = '18.12.00.029';
17787 if( CheckVersion( $DBversion ) ) {
17788     $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')" );
17789
17790     SetVersion( $DBversion );
17791     print "Upgrade to $DBversion done (Bug 18736 - Add syspref to control order rounding)\n";
17792 }
17793
17794 $DBversion = '18.12.00.030';
17795 if( CheckVersion( $DBversion ) ) {
17796     if( column_exists( 'accountlines', 'accountno' ) ) {
17797         $dbh->do( "ALTER TABLE accountlines DROP COLUMN accountno" );
17798     }
17799     if( column_exists( 'statistics', 'proccode' ) ) {
17800         $dbh->do( "ALTER TABLE statistics DROP COLUMN proccode" );
17801     }
17802     SetVersion( $DBversion );
17803     print "Upgrade to $DBversion done (Bug 21683 - Remove accountlines.accountno and statistics.proccode fields)\n";
17804 }
17805
17806 $DBversion = '18.12.00.031';
17807 if( CheckVersion( $DBversion ) ) {
17808
17809     # Add constraint for manager_id
17810     unless( foreign_key_exists( 'accountlines', 'accountlines_ibfk_borrowers_2' ) ) {
17811         $dbh->do("ALTER TABLE accountlines CHANGE COLUMN manager_id manager_id INT(11) NULL DEFAULT NULL");
17812         $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");
17813         $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");
17814     }
17815
17816     # Rename accountlines_ibfk_2 to accountlines_ibfk_items
17817     if ( foreign_key_exists( 'accountlines', 'accountlines_ibfk_2' ) ) {
17818         $dbh->do("ALTER TABLE accountlines DROP FOREIGN KEY accountlines_ibfk_2");
17819     }
17820     unless ( foreign_key_exists( 'accountlines', 'accountlines_ibfk_items' ) ) {
17821         $dbh->do("ALTER TABLE accountlines ADD CONSTRAINT `accountlines_ibfk_items` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE SET NULL ON UPDATE CASCADE");
17822     }
17823
17824     SetVersion( $DBversion );
17825     print "Upgrade to $DBversion done (Bug 22008 - Add missing constraints for accountlines.manager_id)\n";
17826 }
17827
17828 $DBversion = '18.12.00.032';
17829 if( CheckVersion( $DBversion ) ) {
17830     if( !column_exists( 'search_field', 'facet_order' ) ) {
17831         $dbh->do("ALTER TABLE search_field ADD COLUMN facet_order TINYINT(4) DEFAULT NULL AFTER weight");
17832     }
17833     $dbh->do("UPDATE search_field SET facet_order=1 WHERE name='author'");
17834     $dbh->do("UPDATE search_field SET facet_order=2 WHERE name='itype'");
17835     $dbh->do("UPDATE search_field SET facet_order=3 WHERE name='location'");
17836     $dbh->do("UPDATE search_field SET facet_order=4 WHERE name='su-geo'");
17837     $dbh->do("UPDATE search_field SET facet_order=5 WHERE name='title-series'");
17838     $dbh->do("UPDATE search_field SET facet_order=6 WHERE name='subject'");
17839     $dbh->do("UPDATE search_field SET facet_order=7 WHERE name='ccode'");
17840     $dbh->do("UPDATE search_field SET facet_order=8 WHERE name='holdingbranch'");
17841     $dbh->do("UPDATE search_field SET facet_order=9 WHERE name='homebranch'");
17842     SetVersion( $DBversion );
17843     print "Upgrade to $DBversion done (Bug 18235 - Elastic search - make facets configurable)\n";
17844 }
17845
17846 $DBversion = '18.12.00.033';
17847 if( CheckVersion( $DBversion ) ) {
17848     $dbh->do( "UPDATE search_field SET facet_order=10 WHERE name='ln'" );
17849     SetVersion( $DBversion );
17850     print "Upgrade to $DBversion done (Bug 18213 - Add language facets to Elasticsearch)\n";
17851 }
17852
17853 $DBversion = '18.12.00.034';
17854 if( CheckVersion( $DBversion ) ) {
17855
17856     if ( column_exists( 'accountlines', 'lastincrement' ) ) {
17857         $dbh->do("ALTER TABLE `accountlines` DROP COLUMN `lastincrement`");
17858     }
17859
17860     SetVersion( $DBversion );
17861     print "Upgrade to $DBversion done (Bug 22516 - Drop deprecated accountlines.lastincrement field)\n";
17862 }
17863
17864 $DBversion = '18.12.00.035';
17865 if( CheckVersion( $DBversion ) ) {
17866     $dbh->do( "INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type)
17867                VALUES ('MaxItemsToDisplayForBatchMod','1000',NULL,'Display up to a given number of items in a single item modification batch.','Integer')"
17868             );
17869     SetVersion( $DBversion );
17870     print "Upgrade to $DBversion done (Bug 19722 - Add a MaxItemsToDisplayForBatchMod preference)\n";
17871 }
17872
17873 $DBversion = '18.12.00.036';
17874 if ( CheckVersion($DBversion) ) {
17875
17876     my $rows = $dbh->do(
17877         qq{
17878         UPDATE `accountlines`
17879         SET
17880           `accounttype` = 'FU'
17881         WHERE
17882           `accounttype` = 'O'
17883       }
17884     );
17885
17886     SetVersion($DBversion);
17887     printf "Upgrade to $DBversion done (Bug 22518 - Fix accounttype 'O' to 'FU' - %d updated)\n", $rows;
17888 }
17889
17890 $DBversion = '18.12.00.037';
17891 if( CheckVersion( $DBversion ) ) {
17892
17893     $dbh->do( "UPDATE issues SET renewals = 0 WHERE renewals IS NULL" );
17894     $dbh->do( "UPDATE old_issues SET renewals = 0 WHERE renewals IS NULL" );
17895
17896     $dbh->do( "ALTER TABLE issues MODIFY COLUMN renewals tinyint(4) NOT NULL default 0");
17897     $dbh->do( "ALTER TABLE old_issues MODIFY COLUMN renewals tinyint(4) NOT NULL default 0");
17898
17899     # Always end with this (adjust the bug info)
17900     SetVersion( $DBversion );
17901     print "Upgrade to $DBversion done (Bug 22607 - Set default value of issues.renewals to 0)\n";
17902 }
17903
17904 $DBversion = '18.12.00.038';
17905 if ( CheckVersion($DBversion) ) {
17906
17907     if ( !column_exists( 'accountlines', 'status' ) ) {
17908         $dbh->do(
17909             qq{
17910             ALTER TABLE `accountlines`
17911             ADD
17912               `status` varchar(16) DEFAULT NULL
17913             AFTER
17914               `accounttype`
17915           }
17916         );
17917     }
17918
17919     SetVersion($DBversion);
17920     print "Upgrade to $DBversion done (Bug 22512 - Add status to accountlines)\n";
17921 }
17922
17923 $DBversion = '18.12.00.039';
17924 if ( CheckVersion($DBversion) ) {
17925
17926     if ( !column_exists( 'accountlines', 'interface' ) ) {
17927         $dbh->do(
17928             qq{
17929             ALTER TABLE `accountlines`
17930             ADD
17931               `interface` varchar(16)
17932             AFTER
17933               `manager_id`;
17934           }
17935         );
17936     }
17937
17938     $dbh->do(qq{
17939         UPDATE
17940           `accountlines`
17941         SET
17942           interface = 'opac'
17943         WHERE
17944           borrowernumber = manager_id;
17945     });
17946
17947     $dbh->do(qq{
17948         UPDATE
17949           `accountlines`
17950         SET
17951           interface = 'cron'
17952         WHERE
17953           manager_id IS NULL
17954         AND
17955           branchcode IS NULL;
17956     });
17957
17958     $dbh->do(qq{
17959         UPDATE
17960           `accountlines`
17961         SET
17962           interface = 'intranet'
17963         WHERE
17964           interface IS NULL;
17965     });
17966
17967     $dbh->do(qq{
17968         ALTER TABLE `accountlines`
17969         MODIFY COLUMN `interface` varchar(16) NOT NULL;
17970     });
17971
17972     SetVersion($DBversion);
17973     print "Upgrade to $DBversion done (Bug 22600 - Add interface to accountlines)\n";
17974 }
17975
17976 $DBversion = '18.12.00.040';
17977 if( CheckVersion( $DBversion ) ) {
17978     $dbh->do("UPDATE accountlines SET description = REPLACE(description, 'Reserve Charge - ', '') WHERE description LIKE 'Reserve Charge - %'");
17979     SetVersion( $DBversion );
17980     print "Upgrade to $DBversion done (Bug 12166 - Remove 'Reserve Charge' text from accountlines description)\n";
17981 }
17982
17983 $DBversion = '18.12.00.041';
17984 if( CheckVersion( $DBversion ) ) {
17985     my $table_sth = $dbh->prepare('SHOW CREATE TABLE `search_marc_map`');
17986     $table_sth->execute();
17987     my @table = $table_sth->fetchrow_array();
17988     unless ( $table[1] =~ /`marc_field`.*COLLATE utf8mb4_bin/ ) { #catches utf8mb4 collated tables
17989         $dbh->do("ALTER TABLE `search_marc_map` MODIFY `marc_field` VARCHAR(255) NOT NULL COLLATE utf8mb4_bin COMMENT 'the MARC specifier for this field'");
17990     }
17991
17992     # Always end with this (adjust the bug info)
17993     SetVersion( $DBversion );
17994         print "Upgrade to $DBversion done (Bug 19670 - Change collation of marc_field to allow mixed case search field mappings)\n";
17995 }
17996
17997 $DBversion = '18.12.00.042';
17998 if( CheckVersion( $DBversion ) ) {
17999     $dbh->do( "UPDATE systempreferences SET value = 'default' WHERE variable = 'XSLTDetailsDisplay' AND value = ''" );
18000     SetVersion( $DBversion );
18001     print "Upgrade to $DBversion done (Bug 29891 - Remove non-XSLT detail view in the staff client)\n";
18002 }
18003
18004 $DBversion = '18.12.00.043';
18005 if ( CheckVersion($DBversion) ) {
18006     $dbh->do("UPDATE accountlines SET description = REPLACE(description, 'Lost Item ', '') WHERE description LIKE 'Lost Item %'");
18007     SetVersion($DBversion);
18008     print "Upgrade to $DBversion done (Bug 21953 - Remove 'Lost Item' text from accountlines description)\n";
18009 }
18010
18011 $DBversion = '18.12.00.044';
18012 if( CheckVersion( $DBversion ) ) {
18013
18014     if ( !column_exists( 'categories', 'reset_password' ) ) {
18015         $dbh->do(q{
18016             ALTER TABLE categories
18017                 ADD COLUMN reset_password TINYINT(1) NULL DEFAULT NULL
18018                 AFTER checkprevcheckout
18019         });
18020     }
18021
18022     SetVersion( $DBversion );
18023     print "Upgrade to $DBversion done (Bug 21890 - Patron password reset by category)\n";
18024 }
18025
18026 $DBversion = '18.12.00.045';
18027 if( CheckVersion( $DBversion ) ) {
18028
18029     if ( !column_exists( 'categories', 'change_password' ) ) {
18030         $dbh->do(q{
18031             ALTER TABLE categories
18032                 ADD COLUMN change_password TINYINT(1) NULL DEFAULT NULL
18033                 AFTER reset_password
18034         });
18035     }
18036
18037     SetVersion( $DBversion );
18038     print "Upgrade to $DBversion done (Bug 10796 - Patron password change by category)\n";
18039 }
18040
18041 $DBversion = '18.12.00.046';
18042 if( CheckVersion( $DBversion ) ) {
18043     $dbh->do( "UPDATE systempreferences SET value = 'default' WHERE variable = 'XSLTResultsDisplay' AND value = ''" );
18044     SetVersion( $DBversion );
18045     print "Upgrade to $DBversion done (Bug 22695 - Remove non-XSLT search results view from the staff client)\n";
18046 }
18047
18048 $DBversion = '18.12.00.047';
18049 if( CheckVersion( $DBversion ) ) {
18050     $dbh->do(q|
18051         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');
18052     |);
18053     $dbh->do(q|
18054         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');
18055     |);
18056     SetVersion( $DBversion );
18057     print "Upgrade to $DBversion done (Bug 14557: Add Libris spellchecking system preferences)\n";
18058 }
18059
18060 $DBversion = '18.12.00.048';
18061 if( CheckVersion( $DBversion ) ) {
18062     $dbh->do( q{
18063         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
18064         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');
18065     });
18066     $dbh->do("UPDATE systempreferences SET value='exact_time' WHERE variable='NoRenewalBeforePrecision' AND value IS NULL;" );
18067     SetVersion( $DBversion );
18068     print "Upgrade to $DBversion done (Bug 22044 - Set a default value for NoRenewalBeforePrecision)\n";
18069 }
18070
18071 $DBversion = '18.12.00.049';
18072 if( CheckVersion( $DBversion ) ) {
18073
18074     $dbh->do(q{
18075         ALTER TABLE borrowers
18076             ADD COLUMN flgAnonymized tinyint DEFAULT 0
18077             AFTER overdrive_auth_token
18078     }) if !column_exists('borrowers', 'flgAnonymized');
18079
18080     $dbh->do(q{
18081         ALTER TABLE deletedborrowers
18082             ADD COLUMN flgAnonymized tinyint DEFAULT 0
18083             AFTER overdrive_auth_token
18084     }) if !column_exists('deletedborrowers', 'flgAnonymized');
18085
18086     SetVersion( $DBversion );
18087     print "Upgrade to $DBversion done (Bug 21336 - Add field flgAnonymized)\n";
18088 }
18089
18090 $DBversion = '18.12.00.050';
18091 if( CheckVersion( $DBversion ) ) {
18092     $dbh->do( q|
18093 INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
18094 VALUES
18095 ('UnsubscribeReflectionDelay','',NULL,'Delay for locking unsubscribers', 'Integer'),
18096 ('PatronAnonymizeDelay','',NULL,'Delay for anonymizing patrons', 'Integer'),
18097 ('PatronRemovalDelay','',NULL,'Delay for removing anonymized patrons', 'Integer')
18098     |);
18099     SetVersion( $DBversion );
18100     print "Upgrade to $DBversion done (Bug 21336 - Add preferences)\n";
18101 }
18102
18103 $DBversion = '18.12.00.051';
18104 if( CheckVersion( $DBversion ) ) {
18105     my $failed_attempts = C4::Context->preference('FailedLoginAttempts');
18106     $dbh->do( "UPDATE borrowers SET login_attempts = ? WHERE login_attempts > ?", undef, $failed_attempts, $failed_attempts ) if $failed_attempts && $failed_attempts > 0;
18107     SetVersion( $DBversion );
18108     print "Upgrade to $DBversion done (Bug 21336 - Reset login_attempts)\n";
18109 }
18110
18111 $DBversion = '18.12.00.052';
18112 if( CheckVersion( $DBversion ) ) {
18113     $dbh->do(q{
18114         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
18115         ('OpacMoreSearches', '', NULL, 'Add additional elements to the OPAC more searches bar', 'Textarea')
18116     } );
18117
18118     SetVersion( $DBversion );
18119     print "Upgrade to $DBversion done (Bug 22311 - Add a SysPref to allow adding content to the #moresearches div in the opac)\n";
18120 }
18121
18122 $DBversion = '18.12.00.053';
18123 if( CheckVersion( $DBversion ) ) {
18124     $dbh->do(q{
18125         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES
18126         ('AutoReturnCheckedOutItems', '0', '', 'If disabled, librarian must confirm return of checked out item when checking out to another.', 'YesNo');
18127     });
18128
18129     SetVersion( $DBversion );
18130     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";
18131 }
18132
18133 $DBversion = '18.12.00.054';
18134 if( CheckVersion( $DBversion ) ) {
18135     $dbh->do(q{
18136         INSERT IGNORE permissions (module_bit, code, description)
18137         VALUES
18138         (9,'advanced_editor','Use the advanced cataloging editor')
18139     });
18140     if( C4::Context->preference('EnableAdvancedCatalogingEditor') ){
18141         $dbh->do(q{
18142             INSERT INTO user_permissions (borrowernumber, module_bit, code)
18143             SELECT borrowernumber, 9, 'advanced_editor' FROM borrowers WHERE borrowernumber IN (SELECT DISTINCT borrowernumber FROM user_permissions WHERE code = 'edit_catalogue');
18144         });
18145     }
18146     SetVersion( $DBversion );
18147     print "Upgrade to $DBversion done (Bug 20128: Add permission for Advanced Cataloging Editor)\n";
18148 }
18149
18150 $DBversion = '18.12.00.055';
18151 if ( CheckVersion($DBversion) ) {
18152
18153     $dbh->do(qq{
18154         UPDATE
18155           `account_offset_types`
18156         SET
18157           type = 'OVERDUE'
18158         WHERE
18159           type = 'Fine';
18160     });
18161
18162     $dbh->do(qq{
18163         UPDATE
18164           `account_offset_types`
18165         SET
18166           type = 'OVERDUE_INCREASE'
18167         WHERE
18168           type = 'fine_increase';
18169     });
18170
18171     $dbh->do(qq{
18172         UPDATE
18173           `account_offset_types`
18174         SET
18175           type = 'OVERDUE_DECREASE'
18176         WHERE
18177           type = 'fine_decrease';
18178     });
18179
18180     if ( column_exists( 'accountlines', 'accounttype' ) ) {
18181         $dbh->do(
18182             qq{
18183             ALTER TABLE `accountlines`
18184             CHANGE COLUMN `accounttype`
18185               `accounttype` varchar(16) DEFAULT NULL;
18186           }
18187         );
18188     }
18189
18190     $dbh->do(qq{
18191         UPDATE
18192           accountlines
18193         SET
18194           accounttype = 'OVERDUE',
18195           status = 'UNRETURNED'
18196         WHERE
18197           accounttype = 'FU';
18198     });
18199
18200     $dbh->do(qq{
18201         UPDATE
18202           accountlines
18203         SET
18204           accounttype = 'OVERDUE',
18205           status = 'FORGIVEN'
18206         WHERE
18207           accounttype = 'FFOR';
18208     });
18209
18210     $dbh->do(qq{
18211         UPDATE
18212           accountlines
18213         SET
18214           accounttype = 'OVERDUE',
18215           status = 'RETURNED'
18216         WHERE
18217           accounttype = 'F';
18218     });
18219     SetVersion($DBversion);
18220     print "Upgrade to $DBversion done (Bug 22521 - Update accountlines.accounttype to varchar(16), and map new statuses)\n";
18221 }
18222
18223 $DBversion = '18.12.00.056';
18224 if( CheckVersion( $DBversion ) ) {
18225     $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'");
18226     SetVersion( $DBversion );
18227     print "Upgrade to $DBversion done (Bug 8701 - Update OpacHiddenItems system preference description)\n";
18228 }
18229
18230 $DBversion = '18.12.00.057';
18231 if( CheckVersion( $DBversion ) ) {
18232     if( column_exists('statistics', 'associatedborrower') ) {
18233         $dbh->do(q{ ALTER TABLE statistics DROP COLUMN associatedborrower });
18234     }
18235     if( column_exists('statistics', 'usercode') ) {
18236         $dbh->do(q{ ALTER TABLE statistics DROP COLUMN usercode });
18237     }
18238
18239     SetVersion($DBversion);
18240     print "Upgrade to $DBversion done (Bug 13795 - Delete unused fields from statistics table)\n";
18241 }
18242
18243 $DBversion = '18.12.00.058';
18244 if( CheckVersion( $DBversion ) ) {
18245     my $opaclang = C4::Context->preference("opaclanguages");
18246     my @langs;
18247     push @langs, split ( '\,', $opaclang );
18248     # Get any existing value from the OpacNavRight system preference
18249     my ($OpacNavRight) = $dbh->selectrow_array( q|
18250         SELECT value FROM systempreferences WHERE variable='OpacNavRight';
18251     |);
18252     if( $OpacNavRight ){
18253         # If there is a value in the OpacNavRight preference, insert it into opac_news
18254         $dbh->do("INSERT INTO opac_news (branchcode, lang, title, content ) VALUES (NULL, ?, '', ?)", undef, "OpacNavRight_$langs[0]", $OpacNavRight);
18255     }
18256     # Remove the OpacNavRight system preference
18257     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacNavRight'");
18258     SetVersion ($DBversion);
18259     print "Upgrade to $DBversion done (Bug 22318: Move contents of OpacNavRight preference to Koha news system)\n";
18260 }
18261
18262 $DBversion = '18.12.00.059';
18263 if( CheckVersion( $DBversion ) ) {
18264     if( column_exists( 'import_records', 'z3950random' ) ) {
18265         $dbh->do( "ALTER TABLE import_records DROP COLUMN z3950random" );
18266     }
18267
18268     # Always end with this (adjust the bug info)
18269     SetVersion( $DBversion );
18270     print "Upgrade to $DBversion done (Bug 22532 - Remove import_records z3950random column)\n";
18271 }
18272
18273 $DBversion = '18.12.00.060';
18274 if ( CheckVersion($DBversion) ) {
18275
18276     my $rows = $dbh->do(
18277         qq{
18278         UPDATE `accountlines`
18279         SET
18280           `accounttype` = 'L',
18281           `status`      = 'REPLACED'
18282         WHERE
18283           `accounttype` = 'Rep'
18284       }
18285     );
18286
18287     SetVersion($DBversion);
18288     printf "Upgrade to $DBversion done (Bug 22564 - Fix accounttype 'Rep' - %d updated)\n", $rows;
18289 }
18290
18291 $DBversion = '18.12.00.061';
18292 if( CheckVersion( $DBversion ) ) {
18293
18294     if ( column_exists( 'borrowers', 'flgAnonymized' ) ) {
18295         $dbh->do(q{
18296             UPDATE borrowers SET flgAnonymized = 0 WHERE flgAnonymized IS NULL
18297         });
18298         $dbh->do(q{
18299             ALTER TABLE borrowers
18300                 CHANGE `flgAnonymized` `anonymized` TINYINT(1) NOT NULL DEFAULT 0
18301         });
18302     }
18303
18304     if ( column_exists( 'deletedborrowers', 'flgAnonymized' ) ) {
18305         $dbh->do(q{
18306             UPDATE deletedborrowers SET flgAnonymized = 0 WHERE flgAnonymized IS NULL
18307         });
18308         $dbh->do(q{
18309             ALTER TABLE deletedborrowers
18310                 CHANGE `flgAnonymized` `anonymized` TINYINT(1) NOT NULL DEFAULT 0
18311         });
18312     }
18313
18314     SetVersion( $DBversion );
18315     print "Upgrade to $DBversion done (Bug 21336 - (follow-up) Rename flgAnonymized column)\n";
18316 }
18317
18318 $DBversion = '18.12.00.062';
18319 if( CheckVersion( $DBversion ) ) {
18320     $dbh->do( q|
18321         UPDATE search_marc_map SET marc_field='007_/0'
18322           WHERE marc_type IN ('marc21', 'normarc') AND marc_field='007_/1' AND id IN
18323             (SELECT search_marc_map_id FROM search_marc_to_field WHERE search_field_id IN
18324               (SELECT id FROM search_field WHERE label='ff7-00')
18325             )
18326     |);
18327
18328     $dbh->do( q|
18329         UPDATE search_marc_map SET marc_field='007_/1'
18330           WHERE marc_type IN ('marc21', 'normarc') AND marc_field='007_/2' AND id IN
18331             (SELECT search_marc_map_id FROM search_marc_to_field WHERE search_field_id IN
18332               (SELECT id FROM search_field WHERE label='ff7-01')
18333             )
18334     |);
18335
18336     $dbh->do( q|
18337         UPDATE search_marc_map SET marc_field='007_/2'
18338           WHERE marc_type IN ('marc21', 'normarc') AND marc_field='007_/3' AND id IN
18339             (SELECT search_marc_map_id FROM search_marc_to_field WHERE search_field_id IN
18340               (SELECT id FROM search_field WHERE label='ff7-02')
18341             )
18342     |);
18343
18344     # N.B. ff7-01-02 really is 00-01!
18345     $dbh->do( q|
18346         UPDATE search_marc_map SET marc_field='007_/0-1'
18347           WHERE marc_type IN ('marc21', 'normarc') AND marc_field='007_/1-2' AND id IN
18348             (SELECT search_marc_map_id FROM search_marc_to_field WHERE search_field_id IN
18349               (SELECT id FROM search_field WHERE label='ff7-01-02')
18350             )
18351     |);
18352
18353     $dbh->do( q|
18354         UPDATE search_marc_map SET marc_field='008_/0-5'
18355           WHERE marc_type IN ('marc21', 'normarc') AND marc_field='008_/1-5' AND id IN
18356             (SELECT search_marc_map_id FROM search_marc_to_field WHERE search_field_id IN
18357               (SELECT id FROM search_field WHERE label='date-entered-on-file')
18358             )
18359     |);
18360
18361     $dbh->do( q|
18362         UPDATE search_marc_map SET marc_field='leader_/0-4'
18363           WHERE marc_type IN ('marc21', 'normarc') AND marc_field='leader_/1-5' AND id IN
18364             (SELECT search_marc_map_id FROM search_marc_to_field WHERE search_field_id IN
18365               (SELECT id FROM search_field WHERE label='llength')
18366             )
18367     |);
18368
18369     # Always end with this (adjust the bug info)
18370     SetVersion( $DBversion );
18371     print "Upgrade to $DBversion done (Bug 22339 - Fix search field mappings of MARC fixed fields)\n";
18372 }
18373
18374 $DBversion = '18.12.00.063';
18375 if ( CheckVersion($DBversion) ) {
18376
18377     my $types_map = {
18378         'Writeoff'      => 'W',
18379         'Payment'       => 'Pay',
18380         'Lost Item'     => 'CR',
18381         'Manual Credit' => 'C',
18382         'Forgiven'      => 'FOR'
18383     };
18384
18385     my $sth = $dbh->prepare( "SELECT accountlines_id FROM accountlines WHERE accounttype = 'VOID'" );
18386     my $sth2 = $dbh->prepare( "SELECT type FROM account_offsets WHERE credit_id = ? ORDER BY created_on LIMIT 1" );
18387     my $sth3 = $dbh->prepare( "UPDATE accountlines SET accounttype = ?, status = 'VOID' WHERE accountlines_id = ?" );
18388     $sth->execute();
18389     while (my $row = $sth->fetchrow_hashref) {
18390         $sth2->execute($row->{accountlines_id});
18391         my $result = $sth2->fetchrow_hashref;
18392         my $type = $types_map->{$result->{'type'}} // 'Pay';
18393         $sth3->execute($type,$row->{accountlines_id});
18394     }
18395
18396     SetVersion($DBversion);
18397     print "Upgrade to $DBversion done (Bug 22511 - Update existing VOID accountlines)\n";
18398 }
18399
18400 $DBversion = '18.12.00.064';
18401 if( CheckVersion( $DBversion ) ) {
18402     $dbh->do(q{
18403         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');
18404     });
18405     $dbh->do(q{
18406         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%';
18407     });
18408     $dbh->do(q{
18409         DELETE FROM systempreferences WHERE variable='InProcessingToShelvingCart';
18410     });
18411     $dbh->do(q{
18412         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%';
18413     });
18414     $dbh->do(q{
18415         DELETE FROM systempreferences WHERE variable='ReturnToShelvingCart';
18416     });
18417     SetVersion( $DBversion );
18418     print "Upgrade to $DBversion done (Bug 14576: Add UpdateItemLocationOnCheckin syspref)\n";
18419 }
18420
18421 $DBversion = '18.12.00.065';
18422 if( CheckVersion( $DBversion ) ) {
18423     $dbh->do( q{
18424         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
18425         SELECT 'IndependentBranchesTransfers', value, NULL, 'Allow non-superlibrarians to transfer items between libraries','YesNo'
18426         FROM systempreferences WHERE variable = 'IndependentBranches'
18427     });
18428     SetVersion( $DBversion );
18429     print "Upgrade to $DBversion done (Bug 10300 - Allow transferring of items to be have separate IndependentBranches syspref)\n";
18430 }
18431
18432 $DBversion = '18.12.00.066';
18433 if ( CheckVersion($DBversion) ) {
18434     $dbh->do(q{
18435         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `explanation`, `options`, `type`) VALUES
18436           ('OpenURLResolverURL', '', 'URL of OpenURL Resolver', NULL, 'Free'),
18437           ('OpenURLText', '', 'Text of OpenURL links (or image title if OpenURLImageLocation is defined)', NULL, 'Free'),
18438           ('OpenURLImageLocation', '', 'Location of image for OpenURL links', NULL, 'Free'),
18439           ('OPACShowOpenURL', '', 'Enable display of OpenURL links in OPAC search results and detail page', NULL, 'YesNo'),
18440           ('OPACOpenURLItemTypes', '', 'Show the OpenURL link only for these item types', NULL, 'Free');
18441     });
18442
18443     SetVersion($DBversion);
18444     print
18445 "Upgrade to $DBversion done (Bug 8995 - Add new preferences for OpenURLResolvers)\n";
18446 }
18447
18448 $DBversion = '18.12.00.067';
18449 if ( CheckVersion($DBversion) ) {
18450     $dbh->do(q{
18451         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
18452         VALUES ('SendAllEmailsTo','',NULL,'All emails will be redirected to this email if it is not empty','free');
18453     });
18454     SetVersion($DBversion);
18455     print
18456 "Upgrade to $DBversion done (Bug 8000 - Add new preferences for SendAllEmailsTo)\n";
18457 }
18458
18459 $DBversion = '18.12.00.068';
18460 if ( CheckVersion($DBversion) ) {
18461     $dbh->do(q{
18462         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
18463         ('AllowRenewalOnHoldOverride','0','','If on, allow items on hold to be renewed with a specified due date','YesNo');
18464     });
18465     SetVersion($DBversion);
18466     print "Upgrade to $DBversion done (Bug 7088: Cannot renew items on hold even with override)\n";
18467 }
18468
18469 $DBversion = '18.12.00.069';
18470 if( CheckVersion( $DBversion ) ) {
18471
18472     $dbh->do(q{
18473         INSERT INTO plugin_data
18474             (plugin_class, plugin_key, plugin_value)
18475         SELECT
18476             plugin_class,
18477             '__ENABLED__',
18478             1
18479         FROM plugin_data
18480         WHERE plugin_key='__INSTALLED_VERSION__'
18481     });
18482
18483     # Always end with this (adjust the bug info)
18484     SetVersion( $DBversion );
18485     print "Upgrade to $DBversion done (Bug 22053 - enable all plugins)\n";
18486 }
18487
18488 $DBversion = '18.12.00.070';
18489 if ( CheckVersion($DBversion) ) {
18490     $dbh->do(q{
18491         INSERT IGNORE INTO systempreferences
18492             ( `variable`, `value`, `options`, `explanation`, `type` )
18493         VALUES
18494         ('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');
18495     });
18496     SetVersion($DBversion);
18497     print "Upgrade to $DBversion done (Bug 14407 - Limit web-based self-checkout to specific IP addresses)\n";
18498 }
18499
18500 $DBversion = '18.12.00.071';
18501 if( CheckVersion( $DBversion ) ) {
18502     $dbh->do(q{
18503 INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`, `lang`) VALUES
18504 ('circulation', 'ACCOUNT_CREDIT', '', 'Account payment', 0, 'Account payment', '<table>
18505 [% IF ( LibraryName ) %]
18506  <tr>
18507     <th colspan="4" class="centerednames">
18508         <h3>[% LibraryName | html %]</h3>
18509     </th>
18510  </tr>
18511 [% END %]
18512  <tr>
18513     <th colspan="4" class="centerednames">
18514         <h2><u>Fee receipt</u></h2>
18515     </th>
18516  </tr>
18517  <tr>
18518     <th colspan="4" class="centerednames">
18519         <h2>[% Branches.GetName( patron.branchcode ) | html %]</h2>
18520     </th>
18521  </tr>
18522  <tr>
18523     <th colspan="4">
18524         Received with thanks from  [% patron.firstname | html %] [% patron.surname | html %] <br />
18525         Card number: [% patron.cardnumber | html %]<br />
18526     </th>
18527  </tr>
18528   <tr>
18529     <th>Date</th>
18530     <th>Description of charges</th>
18531     <th>Note</th>
18532     <th>Amount</th>
18533  </tr>
18534
18535   [% FOREACH account IN accounts %]
18536     <tr class="highlight">
18537       <td>[% account.date | $KohaDates %]</td>
18538       <td>
18539         [% PROCESS account_type_description account=account %]
18540         [%- IF account.description %], [% account.description | html %][% END %]
18541       </td>
18542       <td>[% account.note | html %]</td>
18543       [% IF ( account.amountcredit ) %]<td class="credit">[% ELSE %]<td class="debit">[% END %][% account.amount | $Price %]</td>
18544     </tr>
18545
18546   [% END %]
18547 <tfoot>
18548   <tr>
18549     <td colspan="3">Total outstanding dues as on date: </td>
18550     [% IF ( totalcredit ) %]<td class="credit">[% ELSE %]<td class="debit">[% END %][% total | $Price %]</td>
18551   </tr>
18552 </tfoot>
18553 </table>', 'print', 'default');
18554     });
18555     SetVersion( $DBversion );
18556     print "Upgrade to $DBversion done (Bug 22809 - Move 'ACCOUNT_CREDIT' from template to a slip)\n";
18557 }
18558
18559 $DBversion = '18.12.00.072';
18560 if( CheckVersion( $DBversion ) ) {
18561     $dbh->do(q{
18562 INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`, `lang`) VALUES
18563 ('circulation', 'ACCOUNT_DEBIT', '', 'Account fee', 0, 'Account fee', '<table>
18564   [% IF ( LibraryName ) %]
18565     <tr>
18566       <th colspan="5" class="centerednames">
18567         <h3>[% LibraryName | html %]</h3>
18568       </th>
18569     </tr>
18570   [% END %]
18571
18572   <tr>
18573     <th colspan="5" class="centerednames">
18574       <h2><u>INVOICE</u></h2>
18575     </th>
18576   </tr>
18577   <tr>
18578     <th colspan="5" class="centerednames">
18579       <h2>[% Branches.GetName( patron.branchcode ) | html %]</h2>
18580     </th>
18581   </tr>
18582   <tr>
18583     <th colspan="5" >
18584       Bill to: [% patron.firstname | html %] [% patron.surname | html %] <br />
18585       Card number: [% patron.cardnumber | html %]<br />
18586     </th>
18587   </tr>
18588   <tr>
18589     <th>Date</th>
18590     <th>Description of charges</th>
18591     <th>Note</th>
18592     <th style="text-align:right;">Amount</th>
18593     <th style="text-align:right;">Amount outstanding</th>
18594   </tr>
18595
18596   [% FOREACH account IN accounts %]
18597     <tr class="highlight">
18598       <td>[% account.date | $KohaDates%]</td>
18599       <td>
18600         [% PROCESS account_type_description account=account %]
18601         [%- IF account.description %], [% account.description | html %][% END %]
18602       </td>
18603       <td>[% account.note | html %]</td>
18604       [% IF ( account.amountcredit ) %]<td class="credit">[% ELSE %]<td class="debit">[% END %][% account.amount | $Price %]</td>
18605       [% IF ( account.amountoutstandingcredit ) %]<td class="credit">[% ELSE %]<td class="debit">[% END %][% account.amountoutstanding | $Price %]</td>
18606     </tr>
18607   [% END %]
18608
18609   <tfoot>
18610     <tr>
18611       <td colspan="4">Total outstanding dues as on date: </td>
18612       [% IF ( totalcredit ) %]<td class="credit">[% ELSE %]<td class="debit">[% END %][% total | $Price %]</td>
18613     </tr>
18614   </tfoot>
18615 </table>', 'print', 'default');
18616     });
18617     SetVersion( $DBversion );
18618     print "Upgrade to $DBversion done (Bug 22809 - Move 'INVOICE' from template to a slip)\n";
18619 }
18620
18621 $DBversion = '18.12.00.073';
18622 if( CheckVersion( $DBversion ) ) {
18623     $dbh->do( q{
18624             INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
18625             ('EmailPurchaseSuggestions','0','0|EmailAddressForSuggestions|BranchEmailAddress|KohaAdminEmailAddress','Choose email address that will be sent new purchase suggestions','Choice'),
18626             ('EmailAddressForSuggestions','','','If you choose EmailAddressForSuggestions you should enter a valid email address','free')
18627     });
18628
18629     $dbh->do( q{
18630             INSERT IGNORE INTO `letter` (module, code, name, title, content, is_html, message_transport_type) VALUES
18631             ('suggestions','NEW_SUGGESTION','New suggestion','New suggestion','<h3>Suggestion pending approval</h3>
18632                 <p><h4>Suggested by</h4>
18633                     <ul>
18634                         <li><<borrowers.firstname>> <<borrowers.surname>></li>
18635                         <li><<borrowers.cardnumber>></li>
18636                         <li><<borrowers.phone>></li>
18637                         <li><<borrowers.email>></li>
18638                     </ul>
18639                 </p>
18640                 <p><h4>Title suggested</h4>
18641                     <ul>
18642                         <li><b>Library:</b> <<branches.branchname>></li>
18643                         <li><b>Title:</b> <<suggestions.title>></li>
18644                         <li><b>Author:</b> <<suggestions.author>></li>
18645                         <li><b>Copyright date:</b> <<suggestions.copyrightdate>></li>
18646                         <li><b>Standard number (ISBN, ISSN or other):</b> <<suggestions.isbn>></li>
18647                         <li><b>Publisher:</b> <<suggestions.publishercode>></li>
18648                         <li><b>Collection title:</b> <<suggestions.collectiontitle>></li>
18649                         <li><b>Publication place:</b> <<suggestions.place>></li>
18650                         <li><b>Quantity:</b> <<suggestions.quantity>></li>
18651                         <li><b>Item type:</b> <<suggestions.itemtype>></li>
18652                         <li><b>Reason for suggestion:</b> <<suggestions.patronreason>></li>
18653                         <li><b>Notes:</b> <<suggestions.note>></li>
18654                     </ul>
18655                 </p>',1, 'email')
18656     });
18657
18658     SetVersion( $DBversion );
18659     print "Upgrade to $DBversion done (Bug 5770 - Email librarian when purchase suggestion made)\n";
18660 }
18661
18662 $DBversion = '18.12.00.074';
18663 if( CheckVersion( $DBversion ) ) {
18664     unless ( TableExists( 'keyboard_shortcuts' ) ) {
18665         $dbh->do(q|
18666             CREATE TABLE keyboard_shortcuts (
18667             shortcut_name varchar(80) NOT NULL,
18668             shortcut_keys varchar(80) NOT NULL,
18669             PRIMARY KEY (shortcut_name)
18670             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;|
18671         );
18672     }
18673     $dbh->do(q|
18674         INSERT IGNORE INTO keyboard_shortcuts (shortcut_name, shortcut_keys) VALUES
18675         ("insert_copyright","Alt-C"),
18676         ("insert_copyright_sound","Alt-P"),
18677         ("insert_delimiter","Ctrl-D"),
18678         ("subfield_help","Ctrl-H"),
18679         ("link_authorities","Shift-Ctrl-L"),
18680         ("delete_field","Ctrl-X"),
18681         ("delete_subfield","Shift-Ctrl-X"),
18682         ("new_line","Enter"),
18683         ("line_break","Shift-Enter"),
18684         ("next_position","Tab"),
18685         ("prev_position","Shift-Tab")
18686         ;|
18687     );
18688     $dbh->do(q|
18689         INSERT IGNORE permissions (module_bit, code, description)
18690         VALUES
18691         (3,'manage_keyboard_shortcuts','Manage keyboard shortcuts for advanced cataloging editor')
18692         ;|
18693     );
18694     SetVersion( $DBversion );
18695     print "Upgrade to $DBversion done (Bug 21411 - Add keyboard_shortcuts table)\n";
18696 }
18697
18698 $DBversion = '18.12.00.075';
18699 if( CheckVersion( $DBversion ) ) {
18700     # you can use $dbh here like:
18701     unless ( foreign_key_exists( 'tmp_holdsqueue', 'tmp_holdsqueue_ibfk_1' ) ) {
18702         $dbh->do(q{
18703             DELETE t FROM tmp_holdsqueue t
18704             LEFT JOIN items i ON t.itemnumber=i.itemnumber
18705             WHERE i.itemnumber IS NULL
18706         });
18707         $dbh->do(q{
18708             ALTER TABLE tmp_holdsqueue
18709             ADD CONSTRAINT `tmp_holdsqueue_ibfk_1` FOREIGN KEY (`itemnumber`)
18710             REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE
18711         });
18712     }
18713     SetVersion( $DBversion );
18714     print "Upgrade to $DBversion done (Bug 22899 - Add items constraint to tmp_holdsqueue)\n";
18715 }
18716
18717 $DBversion = '19.05.00.000';
18718 if( CheckVersion( $DBversion ) ) {
18719     SetVersion( $DBversion );
18720     print "Upgrade to $DBversion done (19.05.00 release)\n";
18721 }
18722
18723 $DBversion = '19.06.00.000';
18724 if( CheckVersion( $DBversion ) ) {
18725     SetVersion( $DBversion );
18726     print "Upgrade to $DBversion done (Wingardium Leviosa!)\n";
18727 }
18728
18729 $DBversion = '19.06.00.001'; 
18730 if( CheckVersion( $DBversion ) ) {
18731     $dbh->do( q{
18732         UPDATE systempreferences 
18733         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.' 
18734         WHERE variable = 'UpdateItemLocationOnCheckin'
18735     });
18736     SetVersion( $DBversion );
18737     print "Upgrade to $DBversion done (Bug 22960: Fix typo in syspref description)\n";
18738 }
18739
18740 $DBversion = '19.06.00.002';
18741 if ( CheckVersion($DBversion) ) {
18742
18743     $dbh->do(q{ALTER TABLE subscriptionhistory CHANGE opacnote opacnote LONGTEXT NULL});
18744     $dbh->do(q{ALTER TABLE subscriptionhistory CHANGE librariannote librariannote LONGTEXT NULL});
18745
18746     $dbh->do(q{UPDATE subscriptionhistory SET opacnote = NULL WHERE opacnote = ''});
18747     $dbh->do(q{UPDATE subscriptionhistory SET librariannote = NULL WHERE librariannote = ''});
18748
18749     SetVersion ($DBversion);
18750     print "Upgrade to $DBversion done (Bug 10215: Increase the size of opacnote and librariannote for table subscriptionhistory)\n";
18751 }
18752
18753 $DBversion = '19.06.00.003';
18754 if( CheckVersion( $DBversion ) ) {
18755     $dbh->do(q{UPDATE systempreferences SET value = REPLACE( value, ' ', '|' ) WHERE variable = 'UniqueItemFields'; });
18756
18757     SetVersion( $DBversion );
18758     print "Upgrade to $DBversion done (Bug 22867: UniqueItemFields preference value should be pipe-delimited)\n";
18759 }
18760
18761 $DBversion = '19.06.00.004';
18762 if( CheckVersion( $DBversion ) ) {
18763     $dbh->do( 'UPDATE language_descriptions SET description = "Griechisch (Modern 1453-)"
18764       WHERE subtag = "el" and type = "language" and lang ="de"' );
18765     SetVersion( $DBversion );
18766     print "Upgrade to $DBversion done (Bug 22770: Fix typo in language description for el in German)\n";
18767 }
18768
18769 $DBversion = '19.06.00.005';
18770 if( CheckVersion( $DBversion ) ) {
18771     unless ( column_exists( 'reserves', 'item_level_hold' ) ) {
18772         $dbh->do( "ALTER TABLE reserves ADD COLUMN item_level_hold BOOLEAN NOT NULL DEFAULT 0 AFTER itemtype" );
18773     }
18774     unless ( column_exists( 'old_reserves', 'item_level_hold' ) ) {
18775         $dbh->do( "ALTER TABLE old_reserves ADD COLUMN item_level_hold BOOLEAN NOT NULL DEFAULT 0 AFTER itemtype" );
18776     }
18777
18778     SetVersion( $DBversion );
18779     print "Upgrade to $DBversion done (Bug  9834: Add the reserves.item_level_hold column)\n";
18780 }
18781
18782 $DBversion = '19.06.00.006';
18783 if( CheckVersion( $DBversion ) ) {
18784
18785     unless ( TableExists('plugin_methods') ) {
18786         $dbh->do(q{
18787             CREATE TABLE plugin_methods (
18788               plugin_class varchar(255) NOT NULL,
18789               plugin_method varchar(255) NOT NULL,
18790               PRIMARY KEY ( `plugin_class` (191), `plugin_method` (191) )
18791             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
18792         });
18793     }
18794
18795     require Koha::Plugins;
18796     Koha::Plugins->new({ enable_plugins => 1 })->InstallPlugins;
18797
18798     SetVersion( $DBversion );
18799     print "Upgrade to $DBversion done (Bug 21073: Improve plugin performance)\n";
18800 }
18801
18802 $DBversion = '19.06.00.007';
18803 if( CheckVersion( $DBversion ) ) {
18804     $dbh->do( "DELETE FROM systempreferences WHERE variable = 'RotationPreventTransfers'" );
18805     SetVersion( $DBversion );
18806     print "Upgrade to $DBversion done (Bug 22653: Remove unimplemented RotationPreventTransfers system preference)\n";
18807 }
18808
18809 $DBversion = '19.06.00.008';
18810 if( CheckVersion( $DBversion ) ) {
18811     $dbh->do( "UPDATE userflags SET flagdesc = 'Allow staff members to modify permissions and passwords for other staff members' WHERE flag = 'staffaccess'" );
18812     SetVersion( $DBversion );
18813     print "Upgrade to $DBversion done (Bug 23109: Improve description of staffaccess permission)\n";
18814 }
18815
18816 $DBversion = '19.06.00.009';
18817 if( CheckVersion( $DBversion ) ) {
18818     $dbh->do(q{
18819         INSERT IGNORE INTO keyboard_shortcuts (shortcut_name, shortcut_keys)
18820             VALUES ("toggle_keyboard", "Shift-Ctrl-K")
18821     });
18822
18823     SetVersion( $DBversion );
18824     print "Upgrade to $DBversion done (Bug 17178: add shortcut to keyboard_shortcuts)\n";
18825 }
18826
18827 $DBversion = '19.06.00.010';
18828 if( CheckVersion( $DBversion ) ) {
18829
18830     if ( TableExists('default_circ_rules') ) {
18831         if ( column_exists( 'default_circ_rules', 'holdallowed' ) ) {
18832             $dbh->do("
18833                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18834                 SELECT NULL, NULL, NULL, 'holdallowed', holdallowed
18835                 FROM default_circ_rules
18836             ");
18837             $dbh->do("
18838                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18839                 SELECT NULL, NULL, NULL, 'hold_fulfillment_policy', hold_fulfillment_policy
18840                 FROM default_circ_rules
18841             ");
18842             $dbh->do("
18843                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18844                 SELECT NULL, NULL, NULL, 'returnbranch', returnbranch
18845                 FROM default_circ_rules
18846             ");
18847             $dbh->do("DROP TABLE default_circ_rules");
18848         }
18849     }
18850
18851     if ( TableExists('default_branch_circ_rules') ) {
18852         if ( column_exists( 'default_branch_circ_rules', 'holdallowed' ) ) {
18853             $dbh->do("
18854                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18855                 SELECT NULL, branchcode, NULL, 'holdallowed', holdallowed
18856                 FROM default_branch_circ_rules
18857             ");
18858             $dbh->do("
18859                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18860                 SELECT NULL, branchcode, NULL, 'hold_fulfillment_policy', hold_fulfillment_policy
18861                 FROM default_branch_circ_rules
18862             ");
18863             $dbh->do("
18864                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18865                 SELECT NULL, branchcode, NULL, 'returnbranch', returnbranch
18866                 FROM default_branch_circ_rules
18867             ");
18868             $dbh->do("DROP TABLE default_branch_circ_rules");
18869         }
18870     }
18871
18872     if ( TableExists('branch_item_rules') ) {
18873         if ( column_exists( 'branch_item_rules', 'holdallowed' ) ) {
18874             $dbh->do("
18875                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18876                 SELECT NULL, branchcode, itemtype, 'holdallowed', holdallowed
18877                 FROM branch_item_rules
18878             ");
18879             $dbh->do("
18880                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18881                 SELECT NULL, branchcode, itemtype, 'hold_fulfillment_policy', hold_fulfillment_policy
18882                 FROM branch_item_rules
18883             ");
18884             $dbh->do("
18885                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18886                 SELECT NULL, branchcode, itemtype, 'returnbranch', returnbranch
18887                 FROM branch_item_rules
18888             ");
18889             $dbh->do("DROP TABLE branch_item_rules");
18890         }
18891     }
18892
18893     if ( TableExists('default_branch_item_rules') ) {
18894         if ( column_exists( 'default_branch_item_rules', 'holdallowed' ) ) {
18895             $dbh->do("
18896                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18897                 SELECT NULL, NULL, itemtype, 'holdallowed', holdallowed
18898                 FROM default_branch_item_rules
18899             ");
18900             $dbh->do("
18901                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18902                 SELECT NULL, NULL, itemtype, 'hold_fulfillment_policy', hold_fulfillment_policy
18903                 FROM default_branch_item_rules
18904             ");
18905             $dbh->do("
18906                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18907                 SELECT NULL, NULL, itemtype, 'returnbranch', returnbranch
18908                 FROM default_branch_item_rules
18909             ");
18910             $dbh->do("DROP TABLE default_branch_item_rules");
18911         }
18912     }
18913
18914     SetVersion( $DBversion );
18915     print "Upgrade to $DBversion done (Bug 18928: Move holdallowed, hold_fulfillment_policy, returnbranch to circulation_rules)\n";
18916 }
18917
18918 $DBversion = '19.06.00.011';
18919 if( CheckVersion( $DBversion ) ) {
18920
18921     if ( TableExists('refund_lost_item_fee_rules') ) {
18922         if ( column_exists( 'refund_lost_item_fee_rules', 'refund' ) ) {
18923             $dbh->do("
18924                 INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18925                 SELECT NULL, IF(branchcode='*', NULL, branchcode), NULL, 'refund', refund
18926                 FROM refund_lost_item_fee_rules
18927             ");
18928             $dbh->do("DROP TABLE refund_lost_item_fee_rules");
18929         }
18930     }
18931
18932     SetVersion( $DBversion );
18933     print "Upgrade to $DBversion done (Bug 18930: Move lost item refund rules to circulation_rules table)\n";
18934 }
18935
18936 $DBversion = '19.06.00.012';
18937 if ( CheckVersion($DBversion) ) {
18938
18939     # Find and correct pathological cases of LR becoming a credit
18940     my $sth = $dbh->prepare( "SELECT accountlines_id, issue_id, borrowernumber, itemnumber, amount, manager_id FROM accountlines WHERE accounttype = 'LR' AND amount < 0" );
18941     $sth->execute();
18942     while ( my $row = $sth->fetchrow_hashref ) {
18943         $dbh->do(
18944             "INSERT INTO accountlines (accounttype, issue_id, borrowernumber, itemnumber, amount, manager_id, interface) VALUES ( ?, ?, ?, ?, ?, ?, ? );",
18945             {},
18946             (
18947                 'CR',                   $row->{issue_id},
18948                 $row->{borrowernumber}, $row->{itemnumber},
18949                 $row->{amount},         $row->{manager_id},
18950                 'upgrade'
18951             )
18952         );
18953         my $credit_id = $dbh->last_insert_id(undef, undef, 'accountlines', undef);
18954         my $amount = $row->{amount} * -1;
18955         $dbh->do("INSERT INTO account_offsets (credit_id, debit_id, type, amount) VALUES (?,?,?,?);",{},($credit_id, $row->{accountlines_id}, 'Lost Item', $amount));
18956         $dbh->do("UPDATE accountlines SET amount = '$amount' WHERE accountlines_id = '$row->{accountlines_id}';");
18957     }
18958
18959     $dbh->do(qq{
18960         UPDATE
18961           accountlines
18962         SET
18963           accounttype = 'LOST',
18964           status = 'RETURNED'
18965         WHERE
18966           accounttype = 'LR';
18967     });
18968
18969     # Find and correct pathalogical cases of L having been converted to W
18970     $sth = $dbh->prepare( "SELECT accountlines_id, issue_id, borrowernumber, itemnumber, amount, manager_id FROM accountlines WHERE accounttype = 'W' AND itemnumber IS NOT NULL" );
18971     $sth->execute();
18972     while ( my $row = $sth->fetchrow_hashref ) {
18973         my $amount = $row->{amount} * -1;
18974         $dbh->do(
18975             "INSERT INTO accountlines (accounttype, issue_id, borrowernumber, itemnumber, amount, manager_id, interface) VALUES ( ?, ?, ?, ?, ?, ?, ? );",
18976             {},
18977             (
18978                 'LOST', $row->{issue_id}, $row->{borrowernumber},
18979                 $row->{itemnumber}, $amount, $row->{manager_id},
18980                 'upgrade'
18981             )
18982         );
18983         my $debit_id = $dbh->last_insert_id(undef, undef, 'accountlines', undef);
18984         $dbh->do(
18985             "INSERT INTO account_offsets (credit_id, debit_id, type, amount) VALUES (?,?,?,?);",
18986             {},
18987             (
18988                 $row->{accountlines_id}, $debit_id,
18989                 'Lost Item',    $amount
18990             )
18991         );
18992     }
18993
18994     $dbh->do(qq{
18995         UPDATE
18996           accountlines
18997         SET
18998           accounttype = 'LOST'
18999         WHERE
19000           accounttype = 'L';
19001     });
19002
19003     $dbh->do(qq{
19004         UPDATE
19005           accountlines
19006         SET
19007           accounttype = 'LOST_RETURN'
19008         WHERE
19009           accounttype = 'CR';
19010     });
19011
19012     SetVersion($DBversion);
19013     print "Upgrade to $DBversion done (Bug 22563: Fix accounttypes for 'L', 'LR' and 'CR')\n";
19014 }
19015
19016 $DBversion = '19.06.00.013';
19017 if ( CheckVersion( $DBversion ) ) {
19018     unless ( column_exists( 'borrower_modifications', 'changed_fields' ) ) {
19019         $dbh->do("ALTER TABLE borrower_modifications ADD changed_fields MEDIUMTEXT AFTER verification_token;");
19020     }
19021     SetVersion( $DBversion );
19022     print "Upgrade to $DBversion done (Bug 23151: Add borrower_modifications.changed_fields column)\n";
19023 }
19024
19025 $DBversion = '19.06.00.014';
19026 if ( CheckVersion($DBversion) ) {
19027
19028     $dbh->do(qq{
19029         UPDATE
19030           accountlines
19031         SET
19032           accounttype = 'RENT_DAILY_RENEW'
19033         WHERE
19034           accounttype = 'Rent'
19035         AND
19036           description LIKE 'Renewal of Daily Rental Item%';
19037     });
19038
19039     $dbh->do(qq{
19040         UPDATE
19041           accountlines
19042         SET
19043           accounttype = 'RENT_DAILY'
19044         WHERE
19045           accounttype = 'Rent'
19046         AND
19047           description LIKE 'Daily rental';
19048     });
19049
19050
19051     $dbh->do(qq{
19052         UPDATE
19053           accountlines
19054         SET
19055           accounttype = 'RENT_RENEW'
19056         WHERE
19057           accounttype = 'Rent'
19058         AND
19059           description LIKE 'Renewal of Rental Item%';
19060     });
19061
19062     $dbh->do(qq{
19063         UPDATE
19064           accountlines
19065         SET
19066           accounttype = 'RENT'
19067         WHERE
19068           accounttype = 'Rent';
19069     });
19070
19071     SetVersion($DBversion);
19072     print "Upgrade to $DBversion done (Bug 11573: Fix accounttypes for 'Rent')\n";
19073 }
19074
19075 $DBversion = '19.06.00.015';
19076 if( CheckVersion( $DBversion ) ) {
19077     $dbh->do( "UPDATE `search_field` SET `name` = 'date-time-last-modified', `label` = 'date-time-last-modified' WHERE `name` = 'date/time-last-modified'" );
19078
19079     SetVersion( $DBversion );
19080     print "Upgrade to $DBversion done (Bug 22524: Fix date/time-last-modified search with Elasticsearch)\n";
19081 }
19082
19083 $DBversion = '19.06.00.016';
19084 if( CheckVersion( $DBversion ) ) {
19085
19086     $dbh->do(q|
19087         INSERT IGNORE INTO keyboard_shortcuts (shortcut_name, shortcut_keys) VALUES
19088             ("insert_copyright","Alt-C"),
19089             ("insert_copyright_sound","Alt-P"),
19090             ("insert_delimiter","Ctrl-D"),
19091             ("subfield_help","Ctrl-H"),
19092             ("link_authorities","Shift-Ctrl-L"),
19093             ("delete_field","Ctrl-X"),
19094             ("delete_subfield","Shift-Ctrl-X"),
19095             ("new_line","Enter"),
19096             ("line_break","Shift-Enter"),
19097             ("next_position","Tab"),
19098             ("prev_position","Shift-Tab"),
19099             ("toggle_keyboard", "Shift-Ctrl-K")
19100     ;|);
19101
19102     SetVersion( $DBversion );
19103     print "Upgrade to $DBversion done (Bug 23396: Fix missing keyboard_shortcuts table)\n";
19104 }
19105
19106 $DBversion = '19.06.00.017';
19107 if ( CheckVersion($DBversion) ) {
19108
19109     $dbh->do(qq{
19110         INSERT INTO
19111           authorised_values (category,authorised_value,lib)
19112         VALUES
19113           ('PAYMENT_TYPE','SIP00','Cash via SIP2'),
19114           ('PAYMENT_TYPE','SIP01','VISA via SIP2'),
19115           ('PAYMENT_TYPE','SIP02','Creditcard via SIP2')
19116     });
19117
19118     $dbh->do(qq{
19119         UPDATE
19120           accountlines
19121         SET
19122           accounttype  = 'Pay',
19123           payment_type = 'SIP00'
19124         WHERE
19125           accounttype = 'Pay00';
19126     });
19127
19128     $dbh->do(qq{
19129         UPDATE
19130           accountlines
19131         SET
19132           accounttype  = 'Pay',
19133           payment_type = 'SIP01'
19134         WHERE
19135           accounttype = 'Pay01';
19136     });
19137
19138     $dbh->do(qq{
19139         UPDATE
19140           accountlines
19141         SET
19142           accounttype  = 'Pay',
19143           payment_type = 'SIP02'
19144         WHERE
19145           accounttype = 'Pay02';
19146     });
19147
19148     my $sth = $dbh->prepare( q{SELECT * FROM accountlines WHERE accounttype REGEXP '^Pay[[:digit:]]{2}$' } );
19149     $sth->execute();
19150     my $seen = {};
19151     while (my $row = $sth->fetchrow_hashref) {
19152         my $type = $row->{accounttype};
19153         my $sipcode = $type;
19154         $sipcode =~ s/Pay/SIP/g;
19155         unless ($seen->{$sipcode}) {
19156             $dbh->do(qq{
19157                 INSERT INTO
19158                   authorised_values (category,authorised_value,lib)
19159                 VALUES
19160                   ('PAYMENT_TYPE',"$sipcode",'Unrecognised SIP2 payment type')
19161             });
19162
19163              $dbh->do(qq{
19164                 UPDATE
19165                   accountlines
19166                 SET
19167                   accounttype  = 'Pay',
19168                   payment_type = "$sipcode"
19169                 WHERE
19170                   accounttype = "$type";
19171             });
19172
19173             $seen->{$sipcode} = 1;
19174         }
19175     }
19176
19177     SetVersion($DBversion);
19178     print "Upgrade to $DBversion done (Bug 22610: Fix accounttypes for SIP2 payments)\n";
19179 }
19180
19181 $DBversion = '19.06.00.018';
19182 if( CheckVersion( $DBversion ) ) {
19183     if( !column_exists( 'biblio', 'subtitle' ) ) {
19184         $dbh->do( "ALTER TABLE biblio ADD COLUMN medium LONGTEXT AFTER title" );
19185         $dbh->do( "ALTER TABLE biblio ADD COLUMN subtitle LONGTEXT AFTER medium" );
19186         $dbh->do( "ALTER TABLE biblio ADD COLUMN part_number LONGTEXT AFTER subtitle" );
19187         $dbh->do( "ALTER TABLE biblio ADD COLUMN part_name LONGTEXT AFTER part_number" );
19188
19189         $dbh->do( "ALTER TABLE deletedbiblio ADD COLUMN medium LONGTEXT AFTER title" );
19190         $dbh->do( "ALTER TABLE deletedbiblio ADD COLUMN subtitle LONGTEXT AFTER medium" );
19191         $dbh->do( "ALTER TABLE deletedbiblio ADD COLUMN part_number LONGTEXT AFTER subtitle" );
19192         $dbh->do( "ALTER TABLE deletedbiblio ADD COLUMN part_name LONGTEXT AFTER part_number" );
19193     }
19194
19195     $dbh->do( "UPDATE marc_subfield_structure SET kohafield='biblio.subtitle' WHERE kohafield='bibliosubtitle.subtitle'" );
19196
19197     my $marcflavour = C4::Context->preference('marcflavour');
19198
19199     if ( $marcflavour eq 'UNIMARC' ) {
19200         $dbh->do(qq{
19201             UPDATE marc_subfield_structure SET kohafield='biblio.medium'
19202             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='200' AND tagsubfield='b'
19203         });
19204         $dbh->do(qq{
19205             UPDATE marc_subfield_structure SET kohafield='biblio.subtitle'
19206             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='200' AND tagsubfield='e'
19207         });
19208         $dbh->do(qq{
19209             UPDATE marc_subfield_structure SET kohafield='biblio.part_number'
19210             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='200' AND tagsubfield='h'
19211         });
19212         $dbh->do(qq{
19213             UPDATE marc_subfield_structure SET kohafield='biblio.part_name'
19214             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='200' AND tagsubfield='i'
19215         });
19216     } else {
19217         $dbh->do(qq{
19218             UPDATE marc_subfield_structure SET kohafield='biblio.medium'
19219             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='245' AND tagsubfield='h'
19220         });
19221         $dbh->do(qq{
19222             UPDATE marc_subfield_structure SET kohafield='biblio.subtitle'
19223             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='245' AND tagsubfield='b'
19224         });
19225         $dbh->do(qq{
19226             UPDATE marc_subfield_structure SET kohafield='biblio.part_number'
19227             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='245' AND tagsubfield='n'
19228         });
19229         $dbh->do(qq{
19230             UPDATE marc_subfield_structure SET kohafield='biblio.part_name'
19231             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='245' AND tagsubfield='p'
19232         });
19233     }
19234
19235     $sth = $dbh->prepare("SELECT * FROM fieldmapping");
19236     $sth->execute;
19237     my @fails_11529;
19238     if ( $sth->rows ) {
19239         while ( my $value = $sth->fetchrow_hashref() ) {
19240             my $framework =
19241               $value->{frameworkcode} eq ""
19242               ? "Default"
19243               : $value->{frameworkcode};
19244             push @fails_11529,
19245               {
19246                 field        => $value->{field},
19247                 fieldcode    => $value->{fieldcode},
19248                 subfieldcode => $value->{subfieldcode},
19249                 framework    => $framework
19250               };
19251         }
19252     }
19253
19254     $dbh->do( "DROP TABLE IF EXISTS fieldmapping" );
19255
19256     $dbh->do( "DELETE FROM user_permissions WHERE code='manage_keywords2koha_mappings'" );
19257
19258     $dbh->do( "DELETE FROM permissions WHERE code='manage_keywords2koha_mappings'" );
19259
19260     # Always end with this (adjust the bug info)
19261     SetVersion( $DBversion );
19262     print "Upgrade to $DBversion done (Bug 11529: Add medium, subtitle and part information to biblio table)\n";
19263     if ( @fails_11529 ) {
19264         print "WARNING: Keyword to MARC Mappings:\n";
19265         for my $fail_11529 ( @fails_11529 ) {
19266             print "    keyword: "
19267               . $fail_11529->{field}
19268               . " to field: "
19269               . $fail_11529->{fieldcode} . "\$"
19270               . $fail_11529->{subfieldcode} . " for "
19271               . $fail_11529->{framework}
19272               . " framework\n";
19273         }
19274         print "The keyword to marc mapping feature is no longer supported. Above find the\n";
19275         print "mappings that had been defined in your system. You will need to remap any\n";
19276         print "desired MARC fields to the Koha field you desire in the Koha to MARC mappings\n";
19277         print "page under Administration\n";
19278     }
19279     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"
19280 }
19281
19282 $DBversion = '19.06.00.019';
19283 if ( CheckVersion($DBversion) ) {
19284     $dbh->do(q{
19285         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type)
19286         VALUES
19287           (
19288             'FinePaymentAutoPopup',
19289             '0',
19290             NULL,
19291             'If enabled, automatically display a print dialog for a payment receipt when making a payment.',
19292             'YesNo'
19293           )
19294     });
19295
19296     SetVersion($DBversion);
19297     print
19298 "Upgrade to $DBversion done (Bug 23228: Add option to automatically display payment receipt for printing after making a payment)\n";
19299 }
19300
19301 $DBversion = '19.06.00.020';
19302 if( CheckVersion( $DBversion ) ) {
19303     $dbh->do(q|
19304         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
19305         ('PreserveSerialNotes','1','','When a new "Expected" issue is generated, should it be prefilled with last created issue notes?','YesNo');
19306     |);
19307
19308     SetVersion( $DBversion );
19309     print "Upgrade to $DBversion done (Bug 23416: Add PreserveSerialNotes syspref)\n";
19310 }
19311
19312 $DBversion = '19.06.00.021';
19313 if( CheckVersion( $DBversion ) ) {
19314
19315     $dbh->do(q|
19316         ALTER TABLE marc_subfield_structure CHANGE COLUMN hidden hidden TINYINT(1) DEFAULT 8 NOT NULL;
19317     |);
19318     # Always end with this (adjust the bug info)
19319     SetVersion( $DBversion );
19320     print "Upgrade to $DBversion done (Bug 23309: Can't add new subfields to bibliographic frameworks in strict mode)\n";
19321 }
19322
19323 $DBversion = '19.06.00.022';
19324 if ( CheckVersion($DBversion) ) {
19325
19326     unless ( TableExists('borrower_relationships') ) {
19327         $dbh->do(q{
19328             CREATE TABLE `borrower_relationships` (
19329                   id INT(11) NOT NULL AUTO_INCREMENT,
19330                   guarantor_id INT(11) NOT NULL,
19331                   guarantee_id INT(11) NOT NULL,
19332                   relationship VARCHAR(100) NOT NULL,
19333                   PRIMARY KEY (id),
19334                   UNIQUE KEY `guarantor_guarantee_idx` ( `guarantor_id`, `guarantee_id` ),
19335                   CONSTRAINT r_guarantor FOREIGN KEY ( guarantor_id ) REFERENCES borrowers ( borrowernumber ) ON UPDATE CASCADE ON DELETE CASCADE,
19336                   CONSTRAINT r_guarantee FOREIGN KEY ( guarantee_id ) REFERENCES borrowers ( borrowernumber ) ON UPDATE CASCADE ON DELETE CASCADE
19337             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
19338         });
19339
19340         $dbh->do(q{
19341             UPDATE borrowers
19342             LEFT JOIN borrowers guarantor ON ( borrowers.guarantorid = guarantor.borrowernumber )
19343             SET borrowers.guarantorid = NULL WHERE guarantor.borrowernumber IS NULL;
19344         });
19345
19346         # Bad data handling: guarantorid IS NOT NULL AND relationship IS NULL
19347         $dbh->do(q{
19348             UPDATE borrowers
19349             SET relationship = '_bad_data'
19350             WHERE guarantorid IS NOT NULL AND
19351                   relationship IS NULL
19352         });
19353
19354         $dbh->do(q{
19355             INSERT INTO borrower_relationships ( guarantor_id, guarantee_id, relationship )
19356             SELECT guarantorid, borrowernumber, relationship FROM borrowers WHERE guarantorid IS NOT NULL;
19357         });
19358
19359         # Clean migrated guarantor data
19360         $dbh->do(q{
19361             UPDATE borrowers
19362             SET contactname=NULL,
19363                 contactfirstname=NULL,
19364                 relationship=NULL
19365             WHERE guarantorid IS NOT NULL
19366         });
19367     }
19368
19369     if ( column_exists( 'borrowers', 'guarantorid' ) ) {
19370         $dbh->do(q{
19371             ALTER TABLE borrowers DROP guarantorid;
19372         });
19373     }
19374
19375     if ( column_exists( 'deletedborrowers', 'guarantorid' ) ) {
19376         $dbh->do(q{
19377             ALTER TABLE deletedborrowers DROP guarantorid;
19378         });
19379     }
19380
19381     if ( column_exists( 'borrower_modifications', 'guarantorid' ) ) {
19382         $dbh->do(q{
19383             ALTER TABLE borrower_modifications DROP guarantorid;
19384         });
19385     }
19386
19387     SetVersion($DBversion);
19388     print "Upgrade to $DBversion done (Bug 14570: Make it possible to add multiple guarantors to a record)\n";
19389 }
19390
19391 $DBversion = '19.06.00.023';
19392 if( CheckVersion( $DBversion ) ) {
19393     $dbh->do(q{
19394         INSERT IGNORE INTO `systempreferences` (`variable`,`value`,`explanation`,`options`,`type`) VALUES
19395         ('ElasticsearchMARCFormat', 'ISO2709', 'ISO2709|ARRAY', 'Elasticsearch MARC format. ISO2709 format is recommended as it is faster and takes less space, whereas array is searchable.', 'Choice')
19396     });
19397
19398     SetVersion( $DBversion );
19399     print "Upgrade to $DBversion done (Bug 22258: Add ElasticsearchMARCFormat preference)\n";
19400 }
19401
19402 $DBversion = '19.06.00.024';
19403 if( CheckVersion( $DBversion ) ) {
19404     $dbh->do(q{ALTER TABLE accountlines CHANGE COLUMN accounttype accounttype varchar(80) default NULL});
19405
19406     SetVersion( $DBversion );
19407     print "Upgrade to $DBversion done (Bug 23539: accountlines.accounttype should match authorised_values.authorised_value in size)\n";
19408 }
19409
19410 $DBversion = '19.06.00.025';
19411 if( CheckVersion( $DBversion ) ) {
19412     $dbh->do( q/INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES (?, ?, ?, ?, ?)/, undef, 'BarcodeSeparators','\s\r\n','','Splitting characters for barcodes','Free' );
19413     SetVersion( $DBversion );
19414     print "Upgrade to $DBversion done (Bug 22996: Add pref BarcodeSeparators)\n";
19415 }
19416
19417 $DBversion = '19.06.00.026';
19418 if( CheckVersion( $DBversion ) ) {
19419
19420     unless ( column_exists( 'borrowers', 'privacy_guarantor_fines' ) ) {
19421         $dbh->do(q{
19422             ALTER TABLE borrowers
19423                 ADD privacy_guarantor_fines TINYINT(1) NOT NULL DEFAULT '0' AFTER privacy;
19424         });
19425     }
19426
19427     unless ( column_exists( 'deletedborrowers', 'privacy_guarantor_fines' ) ) {
19428         $dbh->do(q{
19429             ALTER TABLE deletedborrowers
19430                 ADD privacy_guarantor_fines TINYINT(1) NOT NULL DEFAULT '0' AFTER privacy;
19431         });
19432     }
19433
19434     $dbh->do(q{
19435         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type )
19436         VALUES (
19437             'AllowStaffToSetFinesVisibilityForGuarantor',  '0', NULL,
19438             'If enabled, library staff can set a patron''s fines to be visible to linked patrons from the opac.',  'YesNo'
19439         ), (
19440             'AllowPatronToSetFinesVisibilityForGuarantor',  '0', NULL,
19441             'If enabled, the patron can set fines to be visible to  his or her guarantor',  'YesNo'
19442         )
19443     });
19444
19445     SetVersion( $DBversion );
19446     print "Upgrade to $DBversion done (Bug 20691: Add ability for guarantors to view guarantee's fines in OPAC)\n";
19447 }
19448
19449 $DBversion = '19.06.00.027';
19450 if( CheckVersion( $DBversion ) ) {
19451
19452     if( !TableExists( 'itemtypes_branches' ) ) {
19453        $dbh->do( "
19454             CREATE TABLE itemtypes_branches( -- association table between authorised_values and branches
19455                 itemtype VARCHAR(10) NOT NULL,
19456                 branchcode VARCHAR(10) NOT NULL,
19457                 FOREIGN KEY (itemtype) REFERENCES itemtypes(itemtype) ON DELETE CASCADE,
19458                 FOREIGN KEY (branchcode) REFERENCES branches(branchcode) ON DELETE CASCADE
19459             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
19460         ");
19461     }
19462
19463     SetVersion( $DBversion );
19464     print "Upgrade to $DBversion done (Bug 15497: Add itemtypes_branches table)\n";
19465 }
19466
19467 $DBversion = '19.06.00.028';
19468 if ( CheckVersion($DBversion) ) {
19469
19470     $dbh->do(qq{
19471         UPDATE
19472           accountlines
19473         SET
19474           accounttype = 'ACCOUNT'
19475         WHERE
19476           accounttype = 'A';
19477     });
19478
19479     SetVersion($DBversion);
19480     print "Upgrade to $DBversion done (Bug 11573: Fix accounttypes for 'A')\n";
19481 }
19482
19483 $DBversion = '19.06.00.029';
19484 if ( CheckVersion($DBversion) ) {
19485
19486     unless ( TableExists( 'cash_registers' ) ) {
19487         $dbh->do(qq{
19488     CREATE TABLE `cash_registers` (
19489     `id` int(11) NOT NULL auto_increment, -- unique identifier for each account register
19490     `name` varchar(24) NOT NULL, -- the user friendly identifier for each account register
19491     `description` longtext NOT NULL, -- the user friendly description for each account register
19492     `branch` varchar(10) NOT NULL, -- the foreign key the library this account register belongs
19493     `branch_default` tinyint(1) NOT NULL DEFAULT 0, -- boolean flag to denote that this till is the branch default
19494     `starting_float` decimal(28, 6), -- the starting float this account register should be assigned
19495     `archived` tinyint(1) NOT NULL DEFAULT 0, -- boolean flag to denote if this till is archived or not
19496     PRIMARY KEY (`id`),
19497     UNIQUE KEY `name` (`name`,`branch`),
19498     CONSTRAINT cash_registers_branch FOREIGN KEY (branch) REFERENCES branches (branchcode) ON UPDATE CASCADE ON DELETE CASCADE
19499     ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
19500         });
19501     }
19502
19503     unless ( column_exists( 'accountlines', 'register_id' ) ) {
19504         $dbh->do(qq{ALTER TABLE `accountlines` ADD `register_id` int(11) NULL DEFAULT NULL AFTER `manager_id`});
19505         $dbh->do(qq{
19506             ALTER TABLE `accountlines`
19507             ADD CONSTRAINT `accountlines_ibfk_registers` FOREIGN KEY (`register_id`)
19508             REFERENCES `cash_registers` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
19509         });
19510     }
19511
19512     $dbh->do(qq{
19513         INSERT IGNORE INTO `userflags` (`bit`, `flag`, `flagdesc`, `defaulton`)
19514         VALUES (25, 'cash_management', 'Cash management', 0)
19515     });
19516
19517     $dbh->do(qq{
19518         INSERT IGNORE permissions (module_bit, code, description)
19519         VALUES
19520         (25, 'manage_cash_registers', 'Add and remove cash registers')
19521     });
19522
19523     $dbh->do(qq{
19524         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
19525         ('UseCashRegisters','0','','Use cash registers with the accounting system and assign patron transactions to them.','YesNo')
19526     });
19527
19528     SetVersion($DBversion);
19529     print "Upgrade to $DBversion done (Bug 23321: Add cash_registers table, permissions and preferences)\n";
19530 }
19531
19532 $DBversion = '19.06.00.030';
19533 if( CheckVersion( $DBversion ) ) {
19534
19535     if ( !TableExists('club_holds') ) {
19536         $dbh->do(q|
19537             CREATE TABLE club_holds (
19538                 id        INT(11) NOT NULL AUTO_INCREMENT,
19539                 club_id   INT(11) NOT NULL, -- id for the club the hold was generated for
19540                 biblio_id INT(11) NOT NULL, -- id for the bibliographic record the hold has been placed against
19541                 item_id   INT(11) NULL DEFAULT NULL, -- If item-level, the id for the item the hold has been placed agains
19542                 date_created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, -- Timestamp for the placed hold
19543                 PRIMARY KEY (id),
19544                 -- KEY club_id (club_id),
19545                 CONSTRAINT clubs_holds_ibfk_1 FOREIGN KEY (club_id)   REFERENCES clubs  (id) ON DELETE CASCADE ON UPDATE CASCADE,
19546                 CONSTRAINT clubs_holds_ibfk_2 FOREIGN KEY (biblio_id) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE,
19547                 CONSTRAINT clubs_holds_ibfk_3 FOREIGN KEY (item_id)   REFERENCES items  (itemnumber) ON DELETE CASCADE ON UPDATE CASCADE
19548             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
19549         |);
19550     }
19551
19552     if ( !TableExists('club_holds_to_patron_holds') ) {
19553         $dbh->do(q|
19554             CREATE TABLE club_holds_to_patron_holds (
19555                 id              INT(11) NOT NULL AUTO_INCREMENT,
19556                 club_hold_id    INT(11) NOT NULL,
19557                 patron_id       INT(11) NOT NULL,
19558                 hold_id         INT(11),
19559                 error_code      ENUM ( 'damaged', 'ageRestricted', 'itemAlreadyOnHold',
19560                                     'tooManyHoldsForThisRecord', 'tooManyReservesToday',
19561                                     'tooManyReserves', 'notReservable', 'cannotReserveFromOtherBranches',
19562                                     'libraryNotFound', 'libraryNotPickupLocation', 'cannotBeTransferred'
19563                                 ) NULL DEFAULT NULL,
19564                 error_message   varchar(100) NULL DEFAULT NULL,
19565                 PRIMARY KEY (id),
19566                 -- KEY club_hold_id (club_hold_id),
19567                 CONSTRAINT clubs_holds_paton_holds_ibfk_1 FOREIGN KEY (club_hold_id) REFERENCES club_holds (id) ON DELETE CASCADE ON UPDATE CASCADE,
19568                 CONSTRAINT clubs_holds_paton_holds_ibfk_2 FOREIGN KEY (patron_id) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE,
19569                 CONSTRAINT clubs_holds_paton_holds_ibfk_3 FOREIGN KEY (hold_id) REFERENCES reserves (reserve_id) ON DELETE CASCADE ON UPDATE CASCADE
19570             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
19571         |);
19572     }
19573
19574     # Always end with this (adjust the bug info)
19575     SetVersion( $DBversion );
19576     print "Upgrade to $DBversion done (Bug 19618: add club_holds tables)\n";
19577 }
19578
19579 $DBversion = '19.06.00.031';
19580 if( CheckVersion( $DBversion ) ) {
19581     $dbh->do(q|
19582         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
19583         ('OPACDetailQRCode','0','','Enable the display of a QR Code on the OPAC detail page','YesNo');
19584     |);
19585
19586     SetVersion( $DBversion );
19587     print "Upgrade to $DBversion done (Bug 23566: Add OPACDetailQRCode system preference)\n";
19588 }
19589
19590 $DBversion = '19.06.00.032';
19591 if ( CheckVersion($DBversion) ) {
19592     if ( !column_exists( 'search_marc_to_field', 'search' ) ) {
19593         $dbh->do(q|
19594             ALTER TABLE `search_marc_to_field` ADD COLUMN `search` tinyint(1) NOT NULL DEFAULT 1
19595         |);
19596     }
19597     if ( !column_exists( 'search_field', 'staff_client' ) ) {
19598         $dbh->do(q|
19599             ALTER TABLE `search_field` ADD COLUMN `staff_client` tinyint(1) NOT NULL DEFAULT 1
19600         |);
19601     }
19602     if ( !column_exists( 'search_field', 'opac' ) ) {
19603         $dbh->do(q|
19604             ALTER TABLE `search_field` ADD COLUMN `opac` tinyint(1) NOT NULL DEFAULT 1
19605         |);
19606     }
19607
19608     SetVersion($DBversion);
19609     print
19610 "Upgrade to $DBversion done (Bug 20589: Add field boosting and use elastic query fields parameter instead of depricated _all)\n";
19611 }
19612
19613 $DBversion = '19.06.00.033';
19614 if( CheckVersion( $DBversion ) ) {
19615
19616     $dbh->do(qq{
19617         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
19618         ('OnSiteCheckoutAutoCheck','0','','Enable/Do not enable onsite checkout by default if last checkout was an onsite checkout','YesNo')
19619     });
19620     SetVersion( $DBversion );
19621     print "Upgrade to $DBversion done (Bug 23686: Add OnSiteCheckoutAutoCheck system preference)\n";
19622 }
19623
19624 $DBversion = '19.06.00.034';
19625 if( CheckVersion( $DBversion ) ) {
19626     $dbh->do(q{
19627         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
19628         ('TransfersBlockCirc','1',NULL,'Should the transfer modal block circulation staff from continuing scanning items','YesNo')
19629     });
19630     SetVersion( $DBversion );
19631     print "Upgrade to $DBversion done (Bug 23007: Make transfer modals optionally block circ)\n";
19632 }
19633
19634 $DBversion = '19.06.00.035';
19635 if( CheckVersion( $DBversion ) ) {
19636
19637     $dbh->do(q{
19638         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
19639         ( 'IntranetCoce','0', NULL, 'If on, enables cover retrieval from the configured Coce server in the staff client', 'YesNo')
19640     });
19641
19642     $dbh->do(qq{
19643         UPDATE systempreferences SET 
19644           variable = 'OpacCoce', 
19645           explanation = 'If on, enables cover retrieval from the configured Coce server in the OPAC'
19646         WHERE 
19647           variable = 'Coce'
19648     });
19649
19650     SetVersion( $DBversion );
19651     print "Upgrade to $DBversion done (Bug 18421: Add Coce image cache to the Intranet)\n";
19652 }
19653
19654 $DBversion = '19.06.00.036';
19655 if( CheckVersion( $DBversion ) ) {
19656
19657     $dbh->do(q{
19658         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type`) VALUES  
19659         ('QueryRegexEscapeOptions', 'escape', 'dont_escape|escape|unescape_escaped', 'Escape option for regexps delimiters in Elasicsearch queries.', 'Choice')
19660     });
19661
19662     SetVersion( $DBversion );
19663     print "Upgrade to $DBversion done (Bug 20334: Add elasticsearch escape options preference)\n";
19664 }
19665
19666 $DBversion = '19.06.00.037';
19667 if( CheckVersion( $DBversion ) ) {
19668     $dbh->do(q{
19669         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
19670         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')
19671     });
19672
19673     SetVersion( $DBversion );
19674     print "Upgrade to $DBversion done (Bug 21701: PayPal return URL option)\n";
19675 }
19676
19677 $DBversion = '19.06.00.038';
19678 if( CheckVersion( $DBversion ) ) {
19679     $dbh->do( "UPDATE systempreferences SET variable='PatronAutoComplete' WHERE variable='CircAutocompl' LIMIT 1" );
19680     SetVersion( $DBversion );
19681     print "Upgrade to $DBversion done (Bug 23697: Rename CircAutocompl system preference to PatronAutoComplete)\n";
19682 }
19683
19684 $DBversion = '19.06.00.039';
19685 if( CheckVersion( $DBversion ) ) {
19686     $dbh->do(q|
19687         INSERT IGNORE INTO keyboard_shortcuts (shortcut_name, shortcut_keys) VALUES
19688         ("copy_line","Ctrl-C"),
19689         ("copy_subfield","Shift-Ctrl-C"),
19690         ("paste_line","Ctrl-P"),
19691         ("insert_line","Ctrl-I")
19692         ;
19693     |);
19694     SetVersion( $DBversion );
19695     print "Upgrade to $DBversion done (Bug 17179: Add additional keyboard_shortcuts)\n";
19696 }
19697
19698 $DBversion = '19.06.00.040';
19699 if( CheckVersion( $DBversion ) ) {
19700     $dbh->do(q|
19701         INSERT IGNORE INTO systempreferences
19702         (variable,value,explanation,options,type)
19703         VALUES
19704         ('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')
19705     |);
19706
19707     SetVersion( $DBversion );
19708     print "Upgrade to $DBversion done (Bug 17140: Add pref to allow rounding fines at payment)\n";
19709 }
19710
19711 $DBversion = '19.06.00.041';
19712 if( CheckVersion( $DBversion ) ) {
19713     my ($socialnetworks) = $dbh->selectrow_array( q|
19714         SELECT value FROM systempreferences WHERE variable='socialnetworks';
19715     |);
19716     if( $socialnetworks ){
19717         # If the socialnetworks preference is enabled, enable all social networks
19718         $dbh->do("UPDATE systempreferences SET value = 'email,facebook,linkedin,twitter', explanation = 'email|facebook|linkedin|twitter', type = 'multiple'  WHERE variable = 'SocialNetworks'");
19719     } else {
19720         $dbh->do("UPDATE systempreferences SET value = '', explanation = 'email|facebook|linkedin|twitter', type = 'multiple'  WHERE variable = 'SocialNetworks'");
19721     }
19722     SetVersion ($DBversion);
19723     print "Upgrade to $DBversion done (Bug 22880: Allow granular control of socialnetworks preference)\n";
19724 }
19725
19726 $DBversion = '19.06.00.042';
19727 if( CheckVersion( $DBversion ) ) {
19728     $dbh->do(q{
19729         INSERT IGNORE INTO systempreferences
19730             ( variable, value, options, explanation, type )
19731         VALUES
19732             ('CustomCoverImages','0',NULL,'If enabled, the custom cover images will be displayed in the staff client. CustomCoverImagesURL must be defined.','YesNo'),
19733             ('OPACCustomCoverImages','0',NULL,'If enabled, the custom cover images will be displayed at the OPAC. CustomCoverImagesURL must be defined.','YesNo'),
19734             ('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')
19735     });
19736
19737     SetVersion( $DBversion );
19738     print "Upgrade to $DBversion done (Bug 22445: Add new pref *CustomCoverImages*)\n";
19739 }
19740
19741 $DBversion = '19.06.00.043';
19742 if ( CheckVersion($DBversion) ) {
19743
19744     # Adding account_debit_types
19745     if ( !TableExists('account_debit_types') ) {
19746         $dbh->do(
19747             qq{
19748                 CREATE TABLE account_debit_types (
19749                   code varchar(80) NOT NULL,
19750                   description varchar(200) NULL,
19751                   can_be_added_manually tinyint(4) NOT NULL DEFAULT 1,
19752                   default_amount decimal(28, 6) NULL,
19753                   is_system tinyint(1) NOT NULL DEFAULT 0,
19754                   archived tinyint(1) NOT NULL DEFAULT 0,
19755                   PRIMARY KEY (code)
19756                 ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci
19757               }
19758         );
19759     }
19760
19761     # Adding account_debit_types_branches
19762     if ( !TableExists('account_debit_types_branches') ) {
19763         $dbh->do(
19764             qq{
19765                 CREATE TABLE account_debit_types_branches (
19766                     debit_type_code VARCHAR(80),
19767                     branchcode VARCHAR(10),
19768                     FOREIGN KEY (debit_type_code) REFERENCES account_debit_types(code) ON DELETE CASCADE,
19769                     FOREIGN KEY (branchcode) REFERENCES branches(branchcode) ON DELETE CASCADE
19770                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
19771             }
19772         );
19773     }
19774
19775     # Populating account_debit_types
19776     $dbh->do(
19777         qq{
19778             INSERT IGNORE INTO account_debit_types (
19779               code,
19780               description,
19781               can_be_added_manually,
19782               default_amount,
19783               is_system
19784             )
19785             VALUES
19786               ('ACCOUNT', 'Account creation fee', 0, NULL, 1),
19787               ('ACCOUNT_RENEW', 'Account renewal fee', 0, NULL, 1),
19788               ('RESERVE_EXPIRED', 'Hold waiting too long', 0, NULL, 1),
19789               ('LOST', 'Lost item', 1, NULL, 1),
19790               ('MANUAL', 'Manual fee', 1, NULL, 0),
19791               ('NEW_CARD', 'New card fee', 1, NULL, 1),
19792               ('OVERDUE', 'Overdue fine', 0, NULL, 1),
19793               ('PROCESSING', 'Lost item processing fee', 0, NULL, 1),
19794               ('RENT', 'Rental fee', 0, NULL, 1),
19795               ('RENT_DAILY', 'Daily rental fee', 0, NULL, 1),
19796               ('RENT_RENEW', 'Renewal of rental item', 0, NULL, 1),
19797               ('RENT_DAILY_RENEW', 'Renewal of daily rental item', 0, NULL, 1),
19798               ('RESERVE', 'Hold fee', 0, NULL, 1)
19799         }
19800     );
19801
19802     # Update accountype 'Res' to 'RESERVE'
19803     $dbh->do(
19804         qq{
19805           UPDATE accountlines SET accounttype = 'RESERVE' WHERE accounttype = 'Res'
19806         }
19807     );
19808
19809     # Update accountype 'PF' to 'PROCESSING'
19810     $dbh->do(
19811         qq{
19812           UPDATE accountlines SET accounttype = 'PROCESSING' WHERE accounttype = 'PF'
19813         }
19814     );
19815
19816     # Update accountype 'HE' to 'RESERVE_EXPIRED'
19817     $dbh->do(
19818         qq{
19819           UPDATE accountlines SET accounttype = 'RESERVE_EXPIRED' WHERE accounttype = 'HE'
19820         }
19821     );
19822
19823     # Update accountype 'N' to 'NEW_CARD'
19824     $dbh->do(
19825         qq{
19826           UPDATE accountlines SET accounttype = 'NEW_CARD' WHERE accounttype = 'N'
19827         }
19828     );
19829
19830     # Update accountype 'M' to 'MANUAL'
19831     $dbh->do(
19832         qq{
19833           UPDATE accountlines SET accounttype = 'MANUAL' WHERE accounttype = 'M'
19834         }
19835     );
19836
19837     # Catch 'F' cases introduced since bug 22521
19838     $dbh->do(qq{
19839         UPDATE
19840           accountlines
19841         SET
19842           accounttype = 'OVERDUE',
19843           status = 'RETURNED'
19844         WHERE
19845           accounttype = 'F';
19846     });
19847
19848     # Moving MANUAL_INV to account_debit_types
19849     $dbh->do(
19850         qq{
19851             INSERT IGNORE INTO account_debit_types (
19852               code,
19853               default_amount,
19854               description,
19855               can_be_added_manually,
19856               is_system
19857             )
19858             SELECT
19859               authorised_value,
19860               lib,
19861               authorised_value,
19862               1,
19863               0
19864             FROM
19865               authorised_values
19866             WHERE
19867               category = 'MANUAL_INV'
19868           }
19869     );
19870
19871     # Update uncaught partial accounttypes left behind after bugs 23539 and 22521
19872     my $sth = $dbh->prepare( "SELECT code, SUBSTR(code, 1,5) AS subcode FROM account_debit_types" );
19873     $sth->execute();
19874     while ( my $row = $sth->fetchrow_hashref ) {
19875         $dbh->do(
19876             qq{
19877               UPDATE accountlines SET accounttype = ? WHERE accounttype = ?
19878             },
19879             {},
19880             (
19881                 $row->{code},
19882                 $row->{subcode}
19883             )
19884         );
19885     }
19886
19887     # Add any unexpected accounttype codes to debit_types as appropriate
19888     $dbh->do(
19889         qq{
19890           INSERT IGNORE INTO account_debit_types (
19891             code,
19892             description,
19893             can_be_added_manually,
19894             default_amount,
19895             is_system
19896           )
19897           SELECT
19898             DISTINCT(accounttype),
19899             "Unexpected type found during upgrade",
19900             1,
19901             NULL,
19902             0
19903           FROM
19904             accountlines
19905           WHERE
19906             amount >= 0
19907         }
19908     );
19909
19910     # Adding debit_type_code to accountlines
19911     unless ( column_exists('accountlines', 'debit_type_code') ) {
19912         $dbh->do(
19913             qq{
19914                 ALTER TABLE accountlines
19915                 ADD
19916                   debit_type_code varchar(80) DEFAULT NULL
19917                 AFTER
19918                   accounttype
19919               }
19920         );
19921     }
19922
19923     # Linking debit_type_code in accountlines to code in account_debit_types
19924     unless ( foreign_key_exists( 'accountlines', 'accountlines_ibfk_debit_type' ) ) {
19925         $dbh->do(
19926             qq{
19927             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
19928               }
19929         );
19930     }
19931
19932     # Populating debit_type_code
19933     $dbh->do(
19934         qq{
19935         UPDATE accountlines SET debit_type_code = accounttype, accounttype = NULL WHERE accounttype IN (SELECT code from account_debit_types) AND amount >= 0
19936         }
19937     );
19938
19939     # Remove MANUAL_INV
19940     $dbh->do(
19941         qq{
19942         DELETE FROM authorised_values WHERE category = 'MANUAL_INV'
19943         }
19944     );
19945     $dbh->do(
19946         qq{
19947         DELETE FROM authorised_value_categories WHERE category_name = 'MANUAL_INV'
19948         }
19949     );
19950
19951     # Add new permission
19952     $dbh->do(
19953         q{
19954             INSERT IGNORE INTO permissions (module_bit, code, description)
19955             VALUES
19956               (
19957                 3,
19958                 'manage_accounts',
19959                 'Manage Account Debit and Credit Types'
19960               )
19961         }
19962     );
19963
19964     SetVersion($DBversion);
19965     print "Upgrade to $DBversion done (Bug 23049: Add account debit_types)\n";
19966 }
19967
19968 $DBversion = '19.06.00.044';
19969 if ( CheckVersion($DBversion) ) {
19970
19971     # Adding account_credit_types
19972     if ( !TableExists('account_credit_types') ) {
19973         $dbh->do(
19974             qq{
19975                 CREATE TABLE account_credit_types (
19976                   code varchar(80) NOT NULL,
19977                   description varchar(200) NULL,
19978                   can_be_added_manually tinyint(4) NOT NULL DEFAULT 1,
19979                   is_system tinyint(1) NOT NULL DEFAULT 0,
19980                   PRIMARY KEY (code)
19981                 ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci
19982               }
19983         );
19984     }
19985
19986     # Adding account_credit_types_branches
19987     if ( !TableExists('account_credit_types_branches') ) {
19988         $dbh->do(
19989             qq{
19990                 CREATE TABLE account_credit_types_branches (
19991                     credit_type_code VARCHAR(80),
19992                     branchcode VARCHAR(10),
19993                     FOREIGN KEY (credit_type_code) REFERENCES account_credit_types(code) ON DELETE CASCADE,
19994                     FOREIGN KEY (branchcode) REFERENCES branches(branchcode) ON DELETE CASCADE
19995                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
19996             }
19997         );
19998     }
19999
20000     # Populating account_credit_types
20001     $dbh->do(
20002         qq{
20003             INSERT IGNORE INTO account_credit_types (
20004               code,
20005               description,
20006               can_be_added_manually,
20007               is_system
20008             )
20009             VALUES
20010               ('PAYMENT', 'Payment', 0, 1),
20011               ('WRITEOFF', 'Writeoff', 0, 1),
20012               ('FORGIVEN', 'Forgiven', 1, 1),
20013               ('CREDIT', 'Credit', 1, 1),
20014               ('LOST_RETURN', 'Lost item fee refund', 0, 1)
20015         }
20016     );
20017
20018     # Adding credit_type_code to accountlines
20019     unless ( column_exists('accountlines', 'credit_type_code') ) {
20020         $dbh->do(
20021             qq{
20022                 ALTER TABLE accountlines
20023                 ADD
20024                   credit_type_code varchar(80) DEFAULT NULL
20025                 AFTER
20026                   accounttype
20027               }
20028         );
20029     }
20030
20031     # Catch LOST_RETURNED cases from original bug 22563 update
20032     $dbh->do(
20033         qq{
20034             UPDATE accountlines
20035             SET accounttype = 'LOST_RETURN'
20036             WHERE accounttype = 'LOST_RETURNED'
20037     });
20038
20039     # Linking credit_type_code in accountlines to code in account_credit_types
20040     unless ( foreign_key_exists( 'accountlines', 'accountlines_ibfk_credit_type' ) ) {
20041         $dbh->do(
20042             qq{
20043                 ALTER TABLE accountlines
20044                 ADD CONSTRAINT
20045                   `accountlines_ibfk_credit_type`
20046                 FOREIGN KEY (`credit_type_code`) REFERENCES `account_credit_types` (`code`)
20047                 ON DELETE RESTRICT
20048                 ON UPDATE CASCADE
20049               }
20050         );
20051     }
20052
20053     # Update accountype 'C' to 'CREDIT'
20054     $dbh->do(
20055         qq{
20056           UPDATE accountlines SET accounttype = 'CREDIT' WHERE accounttype = 'C' OR accounttype = 'CR'
20057         }
20058     );
20059
20060     # Update accountype 'FOR' to 'FORGIVEN'
20061     $dbh->do(
20062         qq{
20063           UPDATE accountlines SET accounttype = 'FORGIVEN' WHERE accounttype = 'FOR' OR accounttype = 'FORW'
20064         }
20065     );
20066
20067     # Update accountype 'Pay' to 'PAYMENT'
20068     $dbh->do(
20069         qq{
20070           UPDATE accountlines SET accounttype = 'PAYMENT' WHERE accounttype = 'Pay' OR accounttype = 'PAY'
20071         }
20072     );
20073
20074     # Update accountype 'W' to 'WRITEOFF'
20075     $dbh->do(
20076         qq{
20077           UPDATE accountlines SET accounttype = 'WRITEOFF' WHERE accounttype = 'W' OR accounttype = 'WO'
20078         }
20079     );
20080
20081     # Add any unexpected accounttype codes to credit_types as appropriate
20082     $dbh->do(
20083         qq{
20084           INSERT IGNORE INTO account_credit_types (
20085             code,
20086             description,
20087             can_be_added_manually,
20088             is_system
20089           )
20090           SELECT
20091             DISTINCT(accounttype),
20092             "Unexpected type found during upgrade",
20093             1,
20094             0
20095           FROM
20096             accountlines
20097           WHERE
20098             amount < 0
20099         }
20100     );
20101
20102     # Populating credit_type_code
20103     $dbh->do(
20104         qq{
20105           UPDATE
20106             accountlines 
20107           SET
20108             credit_type_code = accounttype, accounttype = NULL
20109           WHERE accounttype IN (SELECT code from account_credit_types)
20110         }
20111     );
20112
20113     # Drop accounttype field
20114     $dbh->do(
20115         qq{
20116           ALTER TABLE accountlines
20117           DROP COLUMN `accounttype`
20118         }
20119     );
20120
20121     SetVersion($DBversion);
20122     print "Upgrade to $DBversion done (Bug 23805: Add account credit_types)\n";
20123 }
20124
20125 $DBversion = '19.06.00.045';
20126 if( CheckVersion( $DBversion ) ) {
20127     $dbh->do( "UPDATE systempreferences SET value = '2' WHERE value = '0' AND variable = 'UsageStats'" );
20128
20129     SetVersion( $DBversion );
20130     print "Upgrade to $DBversion done (Bug 23866: Set HEA syspref to prompt for review)\n";
20131 }
20132
20133 $DBversion = '19.06.00.046';
20134 if( CheckVersion( $DBversion ) ) {
20135     $dbh->do(qq{
20136         UPDATE systempreferences
20137         SET 
20138           options = "Calendar|Days|Datedue|Dayweek", 
20139           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"
20140         WHERE
20141           variable = "useDaysMode"
20142     });
20143
20144     # Always end with this (adjust the bug info)
20145     SetVersion( $DBversion );
20146     print "Upgrade to $DBversion done (Bug 15260: Option for extended loan with useDaysMode)\n";
20147 }
20148
20149 $DBversion = '19.06.00.047';
20150 if ( CheckVersion($DBversion) ) {
20151     if ( !TableExists('return_claims') ) {
20152         $dbh->do(
20153             q{
20154             CREATE TABLE return_claims (
20155                 id int(11) auto_increment,                             -- Unique ID of the return claim
20156                 itemnumber int(11) NOT NULL,                           -- ID of the item
20157                 issue_id int(11) NULL DEFAULT NULL,                    -- ID of the checkout that triggered the claim
20158                 borrowernumber int(11) NOT NULL,                       -- ID of the patron
20159                 notes MEDIUMTEXT DEFAULT NULL,                         -- Notes about the claim
20160                 created_on TIMESTAMP NULL,                             -- Time and date the claim was created
20161                 created_by int(11) NULL DEFAULT NULL,                  -- ID of the staff member that registered the claim
20162                 updated_on TIMESTAMP NULL ON UPDATE CURRENT_TIMESTAMP, -- Time and date of the latest change on the claim (notes)
20163                 updated_by int(11) NULL DEFAULT NULL,                  -- ID of the staff member that updated the claim
20164                 resolution  varchar(80) NULL DEFAULT NULL,             -- Resolution code (RETURN_CLAIM_RESOLUTION AVs)
20165                 resolved_on TIMESTAMP NULL DEFAULT NULL,               -- Time and date the claim was resolved
20166                 resolved_by int(11) NULL DEFAULT NULL,                 -- ID of the staff member that resolved the claim
20167                 PRIMARY KEY (`id`),
20168                 KEY `itemnumber` (`itemnumber`),
20169                 CONSTRAINT UNIQUE `issue_id` ( issue_id ),
20170                 CONSTRAINT `issue_id` FOREIGN KEY (`issue_id`) REFERENCES `issues` (`issue_id`) ON DELETE SET NULL ON UPDATE CASCADE,
20171                 CONSTRAINT `rc_items_ibfk` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
20172                 CONSTRAINT `rc_borrowers_ibfk` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
20173                 CONSTRAINT `rc_created_by_ibfk` FOREIGN KEY (`created_by`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE,
20174                 CONSTRAINT `rc_updated_by_ibfk` FOREIGN KEY (`updated_by`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE,
20175                 CONSTRAINT `rc_resolved_by_ibfk` FOREIGN KEY (`resolved_by`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE
20176             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
20177         }
20178         );
20179     }
20180
20181     $dbh->do(
20182         q{
20183         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
20184         ('ClaimReturnedChargeFee', 'ask', 'ask|charge|no_charge', 'Controls whether or not a lost item fee is charged for return claims', 'Choice'),
20185         ('ClaimReturnedLostValue', '', '', 'Sets the LOST AV value that represents "Claims returned" as a lost value', 'Free'),
20186         ('ClaimReturnedWarningThreshold', '', '', 'Sets the number of return claims past which the librarian will be warned the patron has many return claims', 'Integer');
20187     }
20188     );
20189
20190     $dbh->do(
20191         q{
20192         INSERT IGNORE INTO authorised_value_categories ( category_name ) VALUES
20193             ('RETURN_CLAIM_RESOLUTION');
20194     }
20195     );
20196
20197     $dbh->do(
20198         q{
20199         INSERT IGNORE INTO `authorised_values` ( category, authorised_value, lib )
20200         VALUES
20201           ('RETURN_CLAIM_RESOLUTION', 'RET_BY_PATRON', 'Returned by patron'),
20202           ('RETURN_CLAIM_RESOLUTION', 'FOUND_IN_LIB', 'Found in library');
20203     }
20204     );
20205
20206     SetVersion($DBversion);
20207     print
20208 "Upgrade to $DBversion done (Bug 14697: Extend and enhance 'Claims returned' lost status)\n";
20209 }
20210
20211 $DBversion = '19.06.00.048';
20212 if( CheckVersion( $DBversion ) ) {
20213     # you can use $dbh here like:
20214     $dbh->do( qq{
20215         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
20216         VALUES  ('OPACShowMusicalInscripts','0','','Display musical inscripts on the OPAC record details page when available.','YesNo'),
20217                 ('OPACPlayMusicalInscripts','0','','If displayed musical inscripts, play midi conversion on the OPAC record details page.','YesNo')
20218     } );
20219
20220     SetVersion( $DBversion );
20221     print "Upgrade to $DBversion done (Bug 22581: add new OPACShowMusicalInscripts and OPACPlayMusicalInscripts system preferences)\n";
20222 }
20223
20224 $DBversion = '19.06.00.049';
20225 if( CheckVersion( $DBversion ) ) {
20226
20227     $dbh->do(q{
20228         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
20229         SELECT
20230             'SuspensionsCalendar',
20231             IF( value='noFinesWhenClosed', 'noSuspensionsWhenClosed', 'ignoreCalendar'),
20232             'ignoreCalendar|noSuspensionsWhenClosed',
20233             'Specify whether to use the Calendar in calculating suspensions',
20234             'Choice'
20235         FROM systempreferences
20236         WHERE variable='finesCalendar';
20237     });
20238
20239     SetVersion( $DBversion );
20240     print "Upgrade to $DBversion done (Bug 13958: Add a SuspensionsCalendar syspref)\n";
20241 }
20242
20243 $DBversion = '19.06.00.050';
20244 if( CheckVersion( $DBversion ) ) {
20245     $dbh->do( q{
20246             INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
20247             VALUES ('OPACFineNoRenewalsIncludeCredits','1',NULL,'If enabled the value specified in OPACFineNoRenewals should include any unapplied account credits in the calculation','YesNo')
20248     });
20249
20250     SetVersion( $DBversion );
20251     print "Upgrade to $DBversion done (Bug 23293: Add 'OPACFineNoRenewalsIncludeCredits' system preference)\n";
20252 }
20253
20254 $DBversion = '19.11.00.000';
20255 if( CheckVersion( $DBversion ) ) {
20256     NewVersion( $DBversion, undef, '19.11.00 release' );
20257 }
20258
20259 $DBversion = '19.12.00.000';
20260 if( CheckVersion( $DBversion ) ) {
20261     NewVersion( $DBversion, undef, 'Dobbie is a free elf...' );
20262 }
20263
20264 $DBversion = '19.12.00.001';
20265 if( CheckVersion( $DBversion ) ) {
20266     $dbh->do( "UPDATE marc_subfield_structure SET kohafield = NULL WHERE kohafield = 'bibliosubject.subject';" );
20267     NewVersion( $DBversion, 17831, 'Remove non-existing bibliosubject.subject from frameworks' );
20268 }
20269
20270 $DBversion = '19.12.00.002';
20271 if( CheckVersion( $DBversion ) ) {
20272     $dbh->do(q{
20273         UPDATE systempreferences SET
20274         variable = 'AllowItemsOnHoldCheckoutSIP',
20275         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.'
20276         WHERE variable = 'AllowItemsOnHoldCheckout'
20277     });
20278
20279     NewVersion( $DBversion, 23233, 'Rename AllowItemsOnHoldCheckout syspref' );
20280 }
20281
20282 $DBversion = '19.12.00.003';
20283 if( CheckVersion( $DBversion ) ) {
20284
20285     if( !column_exists( 'library_groups', 'ft_local_hold_group' ) ) {
20286         $dbh->do( "ALTER TABLE library_groups ADD COLUMN ft_local_hold_group tinyint(1) NOT NULL DEFAULT 0 AFTER ft_search_groups_staff" );
20287     }
20288
20289     NewVersion( $DBversion, 22284, 'Add ft_local_hold_group column to library_groups' );
20290 }
20291
20292 $DBversion = '19.12.00.004';
20293 if ( CheckVersion($DBversion) ) {
20294
20295     $dbh->do(
20296         qq{
20297             INSERT IGNORE INTO account_debit_types (
20298               code,
20299               description,
20300               can_be_added_manually,
20301               default_amount,
20302               is_system
20303             )
20304             VALUES
20305               ('PAYOUT', 'Payment from library to patron', 0, NULL, 1)
20306         }
20307     );
20308
20309     $dbh->do(qq{
20310         INSERT IGNORE INTO account_offset_types ( type ) VALUES ('PAYOUT');
20311     });
20312
20313     $dbh->do(qq{
20314         INSERT IGNORE permissions (module_bit, code, description)
20315         VALUES
20316         (10, 'payout', 'Perform account payout action')
20317     });
20318
20319     NewVersion( $DBversion, 24080, ['Add PAYOUT account_debit_type', 'Add PAYOUT account_offset_type', 'Add accounts payout permission'] );
20320 }
20321
20322 $DBversion = '19.12.00.005';
20323 if( CheckVersion( $DBversion ) ) {
20324     $dbh->do( "ALTER TABLE action_logs MODIFY COLUMN `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP" );
20325
20326     NewVersion( $DBversion, 24329, 'Do not update action_log.timestamp' );
20327 }
20328
20329 $DBversion = '19.12.00.006';
20330 if( CheckVersion( $DBversion ) ) {
20331     $dbh->do( q|
20332         UPDATE borrowers SET relationship = NULL
20333         WHERE relationship = ""
20334     |);
20335
20336     NewVersion( $DBversion, 24263, 'Replace relationship with NULL when empty string' );
20337 }
20338
20339 $DBversion = '19.12.00.007';
20340 if ( CheckVersion($DBversion) ) {
20341
20342     $dbh->do(
20343         qq{
20344             INSERT IGNORE INTO account_credit_types (code, description, can_be_added_manually, is_system)
20345             VALUES
20346               ('REFUND', 'A refund applied to a patrons fine', 0, 1)
20347         }
20348     );
20349
20350     $dbh->do(qq{
20351         INSERT IGNORE INTO account_offset_types ( type ) VALUES ('REFUND');
20352     });
20353
20354     $dbh->do(qq{
20355         INSERT IGNORE permissions (module_bit, code, description)
20356         VALUES
20357         (10, 'refund', 'Perform account refund action')
20358     });
20359
20360     NewVersion( $DBversion, 23442, ['Add REFUND to account_credit_types', 'Add REFUND to account_offset_types', 'Add accounts refund permission'] );
20361 }
20362
20363 $DBversion = '19.12.00.008';
20364 if( CheckVersion( $DBversion ) ) {
20365     $dbh->do( 'UPDATE systempreferences SET value = REPLACE(value, "http://worldcat.org", "https://worldcat.org") WHERE variable = "OPACSearchForTitleIn"' );
20366     $dbh->do( 'UPDATE systempreferences SET value = REPLACE(value, "http://www.bookfinder.com", "https://www.bookfinder.com") WHERE variable = "OPACSearchForTitleIn"' );
20367     $dbh->do( 'UPDATE systempreferences SET value = REPLACE(value, "https://openlibrary.org/search/?", "https://openlibrary.org/search?") WHERE variable = "OPACSearchForTitleIn"' );
20368
20369     NewVersion( $DBversion, 24206, 'Update OpacSearchForTitleIn system preference' );
20370 }
20371
20372 $DBversion = '19.12.00.009';
20373 if( CheckVersion( $DBversion ) ) {
20374
20375     $dbh->do(q{
20376         INSERT IGNORE INTO account_offset_types ( type ) VALUES ( 'Purchase' );
20377     });
20378
20379     $dbh->do(q{
20380         INSERT IGNORE INTO account_credit_types ( code, description, can_be_added_manually, is_system )
20381         VALUES ('PURCHASE', 'Purchase', 0, 1);
20382     });
20383
20384     my $sth = $dbh->prepare(q{
20385         SELECT COUNT(*) FROM authorised_values WHERE category = 'PAYMENT_TYPE' AND authorised_value = 'CASH'
20386     });
20387     $sth->execute;
20388     my $already_exists = $sth->fetchrow;
20389     if ( not $already_exists ) {
20390         $dbh->do(q{
20391            INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('PAYMENT_TYPE','CASH','Cash')
20392         });
20393     }
20394
20395     # Updating field in account_debit_types
20396     unless ( column_exists('account_debit_types', 'can_be_invoiced') ) {
20397         $dbh->do(
20398             qq{
20399                 ALTER TABLE account_debit_types
20400                 CHANGE COLUMN
20401                   can_be_added_manually can_be_invoiced tinyint(1) NOT NULL DEFAULT 1
20402               }
20403         );
20404     }
20405     unless ( column_exists('account_debit_types', 'can_be_sold') ) {
20406         $dbh->do(
20407             qq{
20408                 ALTER TABLE account_debit_types
20409                 ADD
20410                   can_be_sold tinyint(1) DEFAULT 0
20411                 AFTER
20412                   can_be_invoiced
20413               }
20414         );
20415     }
20416
20417     $dbh->do(q{
20418 INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`, `lang`) VALUES
20419 ('pos', 'RECEIPT', '', 'Point of sale receipt', 0, 'Receipt', '[% PROCESS "accounts.inc" %]
20420 <table>
20421 [% IF ( LibraryName ) %]
20422  <tr>
20423     <th colspan="2" class="centerednames">
20424         <h3>[% LibraryName | html %]</h3>
20425     </th>
20426  </tr>
20427 [% END %]
20428  <tr>
20429     <th colspan="2" class="centerednames">
20430         <h2>[% Branches.GetName( payment.branchcode ) | html %]</h2>
20431     </th>
20432  </tr>
20433 <tr>
20434     <th colspan="2" class="centerednames">
20435         <h3>[% payment.date | $KohaDates %]</h3>
20436 </tr>
20437 <tr>
20438   <td>Transaction ID: </td>
20439   <td>[% payment.accountlines_id %]</td>
20440 </tr>
20441 <tr>
20442   <td>Operator ID: </td>
20443   <td>[% payment.manager_id %]</td>
20444 </tr>
20445 <tr>
20446   <td>Payment type: </td>
20447   <td>[% payment.payment_type %]</td>
20448 </tr>
20449  <tr></tr>
20450  <tr>
20451     <th colspan="2" class="centerednames">
20452         <h2><u>Fee receipt</u></h2>
20453     </th>
20454  </tr>
20455  <tr></tr>
20456  <tr>
20457     <th>Description of charges</th>
20458     <th>Amount</th>
20459   </tr>
20460
20461   [% FOREACH offset IN offsets %]
20462     <tr>
20463         <td>[% PROCESS account_type_description account=offset.debit %]</td>
20464         <td>[% offset.amount * -1 | $Price %]</td>
20465     </tr>
20466   [% END %]
20467
20468 <tfoot>
20469   <tr class="highlight">
20470     <td>Total: </td>
20471     <td>[% payment.amount * -1| $Price %]</td>
20472   </tr>
20473   <tr>
20474     <td>Tendered: </td>
20475     <td>[% collected | $Price %]</td>
20476   </tr>
20477   <tr>
20478     <td>Change: </td>
20479     <td>[% change | $Price %]</td>
20480     </tr>
20481 </tfoot>
20482 </table>', 'print', 'default');
20483     });
20484
20485     $dbh->do(qq{
20486         INSERT IGNORE permissions (module_bit, code, description)
20487         VALUES
20488         (25, 'takepayment', 'Access the point of sale page and take payments')
20489     });
20490
20491     NewVersion( $DBversion, 23354, [q|Add 'Purchase' account offset type|, q|Add 'RECEIPT' notice for Point of Sale|, q|Add point of sale permissions|] );
20492 }
20493
20494 $DBversion = '19.12.00.010';
20495 if( CheckVersion( $DBversion ) ) {
20496     if( !column_exists( 'oai_sets_mappings', 'rule_order' ) ) {
20497         $dbh->do( "ALTER TABLE oai_sets_mappings ADD COLUMN rule_order INT AFTER set_id, ADD COLUMN rule_operator VARCHAR(3) AFTER rule_order" );
20498         $dbh->do( "UPDATE oai_sets_mappings SET rule_operator='or'" );
20499         my $sets = $dbh->selectall_arrayref("SELECT * from oai_sets_mappings ORDER BY set_id", { Slice => {} });
20500         my $i = 0;
20501         my $previous_set_id;
20502         for my $set ( @{$sets}) {
20503             my $set_id = $set->{set_id};
20504     
20505             if ($previous_set_id && $previous_set_id != $set_id) {
20506                 $i = 0;
20507             }
20508     
20509             if ($i == 0) {
20510                 $dbh->do("UPDATE oai_sets_mappings SET rule_operator=NULL WHERE set_id=? LIMIT 1", {}, $set_id);
20511             }
20512     
20513             $dbh->do("UPDATE oai_sets_mappings SET rule_order=? WHERE set_id=? AND rule_order IS NULL LIMIT 1", {}, $i, $set_id);
20514     
20515             $i++;
20516             $previous_set_id = $set_id;
20517         }
20518     }
20519
20520     NewVersion( $DBversion, 21520, 'Add rule_order and rule_operator fields to oai_sets_mappings table' );
20521 }
20522
20523 $DBversion = '19.12.00.011';
20524 if( CheckVersion( $DBversion ) ) {
20525     if( !foreign_key_exists( 'repeatable_holidays', 'repeatable_holidays_ibfk_1' ) ) {
20526         $dbh->do(q|
20527             DELETE h
20528             FROM repeatable_holidays h
20529             LEFT JOIN branches b ON h.branchcode=b.branchcode
20530             WHERE b.branchcode IS NULL;
20531         |);
20532         $dbh->do(q|
20533             ALTER TABLE repeatable_holidays
20534             ADD FOREIGN KEY repeatable_holidays_ibfk_1 (branchcode) REFERENCES branches (branchcode) ON DELETE CASCADE ON UPDATE CASCADE
20535         |);
20536     }
20537
20538     if( !foreign_key_exists( 'special_holidays', 'special_holidays_ibfk_1' ) ) {
20539         $dbh->do(q|
20540             DELETE h
20541             FROM special_holidays h
20542             LEFT JOIN branches b ON h.branchcode=b.branchcode
20543             WHERE b.branchcode IS NULL;
20544         |);
20545         $dbh->do(q|
20546             ALTER TABLE special_holidays
20547             ADD FOREIGN KEY special_holidays_ibfk_1 (branchcode) REFERENCES branches (branchcode) ON DELETE CASCADE ON UPDATE CASCADE
20548         |);
20549     }
20550
20551     NewVersion( $DBversion, 24289, 'Adding foreign keys on *_holidays.branchcode tables' );
20552 }
20553
20554 $DBversion = '19.12.00.012';
20555 if( CheckVersion( $DBversion ) ) {
20556
20557     $dbh->do(qq{
20558         UPDATE
20559           `permissions`
20560         SET
20561           `module_bit` = 3
20562         WHERE
20563           `code` = 'manage_cash_registers'
20564     });
20565
20566     NewVersion( $DBversion, 24481, 'Move permission to correct module_bit' );
20567 }
20568
20569 $DBversion = '19.12.00.013';
20570 if( CheckVersion( $DBversion ) ) {
20571     $dbh->do(qq{
20572         INSERT IGNORE INTO 
20573           systempreferences (variable,value,options,explanation,type)
20574         VALUES
20575           ('EnablePointOfSale','0',NULL,'Enable the point of sale feature to allow anonymous transactions with the accounting system. (Requires UseCashRegisters)','YesNo')
20576     });
20577
20578     NewVersion( $DBversion, 24478, 'Add `EnablePointOfSale` system preference to allow disabling the point of sale feature)' );
20579 }
20580
20581 $DBversion = '19.12.00.014';
20582 if( CheckVersion( $DBversion ) ) {
20583     unless ( column_exists('branchtransfers', 'reason') ) {
20584         $dbh->do(
20585             qq{
20586                 ALTER TABLE branchtransfers
20587                 ADD
20588                   `reason` enum('Manual')
20589                 AFTER
20590                   comments
20591               }
20592         );
20593     }
20594
20595     NewVersion( $DBversion, 24287, q|Add 'reason' field to transfers table| );
20596 }
20597
20598 $DBversion = '19.12.00.015';
20599 if( CheckVersion( $DBversion ) ) {
20600
20601     # Add stockrotation states to reason enum
20602     $dbh->do(
20603         qq{
20604             ALTER TABLE
20605                 `branchtransfers`
20606             MODIFY COLUMN
20607                 `reason` enum(
20608                     'Manual',
20609                     'StockrotationAdvance',
20610                     'StockrotationRepatriation'
20611                 )
20612             AFTER `comments`
20613           }
20614     );
20615
20616     # Move stockrotation states to reason field
20617     $dbh->do(
20618         qq{
20619             UPDATE
20620               `branchtransfers`
20621             SET
20622               `reason` = 'StockrotationAdvance',
20623               `comments` = NULL
20624             WHERE
20625               `comments` = 'StockrotationAdvance'
20626           }
20627     );
20628     $dbh->do(
20629         qq{
20630             UPDATE
20631               `branchtransfers`
20632             SET
20633               `reason` = 'StockrotationRepatriation',
20634               `comments` = NULL
20635             WHERE
20636               `comments` = 'StockrotationRepatriation'
20637           }
20638     );
20639
20640     NewVersion( $DBversion, 24296, q|Update stockrotation to use 'reason' field in transfers table| );
20641 }
20642
20643 $DBversion = '19.12.00.016';
20644 if( CheckVersion( $DBversion ) ) {
20645     $dbh->do(q{
20646         INSERT IGNORE INTO `userflags` (`bit`, `flag`, `flagdesc`, `defaulton`)
20647         VALUES (12, 'suggestions', 'Suggestion management', 0)
20648     });
20649
20650     $dbh->do(q{
20651         UPDATE permissions SET module_bit=12
20652         WHERE code="suggestions_manage"
20653     });
20654
20655     $dbh->do(q{
20656         UPDATE borrowers SET flags = flags | (1<<12) WHERE flags & (1 << 11)
20657     });
20658
20659     NewVersion( $DBversion, 22868, 'Move suggestions_manage subpermission out of acquisition permission' );
20660 }
20661
20662 $DBversion = '19.12.00.017';
20663 if( CheckVersion( $DBversion ) ) {
20664     if( !index_exists( 'library_groups', 'library_groups_uniq_2' ) ) {
20665         $dbh->do(q|
20666             DELETE FROM library_groups
20667             WHERE id NOT IN (
20668                 SELECT MIN(id)
20669                 FROM ( SELECT * FROM library_groups ) AS lg
20670                 GROUP BY parent_id, branchcode
20671             )
20672             AND NOT(parent_id IS NULL OR branchcode IS NULL);
20673         |);
20674         $dbh->do(q|
20675             ALTER TABLE library_groups
20676             ADD UNIQUE KEY library_groups_uniq_2 (parent_id, branchcode)
20677         |);
20678     }
20679
20680     NewVersion( $DBversion, 21674, 'Add unique key (parent_id, branchcode) to library_group' );
20681 }
20682
20683 $DBversion = '19.12.00.018';
20684 if( CheckVersion( $DBversion ) ) {
20685     my @columns = qw(
20686         restrictedtype
20687         rentaldiscount
20688         fine
20689         finedays
20690         maxsuspensiondays
20691         suspension_chargeperiod
20692         firstremind
20693         chargeperiod
20694         chargeperiod_charge_at
20695         accountsent
20696         issuelength
20697         lengthunit
20698         hardduedate
20699         hardduedatecompare
20700         renewalsallowed
20701         renewalperiod
20702         norenewalbefore
20703         auto_renew
20704         no_auto_renewal_after
20705         no_auto_renewal_after_hard_limit
20706         reservesallowed
20707         holds_per_record
20708         holds_per_day
20709         onshelfholds
20710         opacitemholds
20711         overduefinescap
20712         cap_fine_to_replacement_price
20713         article_requests
20714         note
20715     );
20716
20717     $dbh->do(q|
20718         DELETE i FROM issuingrules i
20719         LEFT JOIN itemtypes it ON i.itemtype=it.itemtype
20720         WHERE it.itemtype IS NULL AND i.itemtype!='*'
20721     |);
20722     $dbh->do(q|
20723         DELETE i FROM issuingrules i
20724         LEFT JOIN branches b ON i.branchcode=b.branchcode
20725         WHERE b.branchcode IS NULL AND i.branchcode!='*'
20726     |);
20727     $dbh->do(q|
20728         DELETE i FROM issuingrules i
20729         LEFT JOIN categories c ON i.categorycode=c.categorycode
20730         WHERE c.categorycode IS NULL AND i.categorycode!='*'
20731     |);
20732     if ( column_exists( 'issuingrules', 'categorycode' ) ) {
20733         foreach my $column ( @columns ) {
20734             $dbh->do("
20735                 INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
20736                 SELECT IF(categorycode='*', NULL, categorycode), IF(branchcode='*', NULL, branchcode), IF(itemtype='*', NULL, itemtype), \'$column\', COALESCE( $column, '' )
20737                 FROM issuingrules
20738             ");
20739         }
20740         $dbh->do("
20741             DELETE FROM circulation_rules WHERE rule_name='holdallowed' AND rule_value='';
20742         ");
20743         $dbh->do("DROP TABLE issuingrules");
20744     }
20745
20746     NewVersion( $DBversion, 18936, 'Convert issuingrules fields to circulation_rules' );
20747 }
20748
20749 $DBversion = '19.12.00.019';
20750 if( CheckVersion( $DBversion ) ) {
20751
20752     $dbh->do("ALTER TABLE message_queue MODIFY time_queued timestamp NULL");
20753
20754     if( !column_exists( 'message_queue', 'updated_on' ) ) {
20755         $dbh->do("ALTER TABLE message_queue ADD COLUMN updated_on timestamp NOT NULL default CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER time_queued");
20756         $dbh->do("UPDATE message_queue SET updated_on=time_queued");
20757     }
20758
20759     NewVersion( $DBversion, 23673, 'modify time_queued and add updated_on to message_queue' );
20760 }
20761
20762 $DBversion = '19.12.00.020';
20763 if ( CheckVersion($DBversion) ) {
20764     if ( !column_exists( 'marc_subfield_structure', 'important') ){
20765         $dbh->do("ALTER TABLE marc_subfield_structure ADD COLUMN important TINYINT(4) NOT NULL DEFAULT 0  AFTER mandatory");
20766     }
20767     if ( !column_exists( 'marc_tag_structure', 'important') ){
20768         $dbh->do("ALTER TABLE marc_tag_structure ADD COLUMN important TINYINT(4) NOT NULL DEFAULT 0  AFTER mandatory");
20769     }
20770
20771     NewVersion( $DBversion, 8643, 'Add important constraint to marc subfields' );
20772 }
20773
20774 $DBversion = '19.12.00.021';
20775 if( CheckVersion( $DBversion ) ) {
20776
20777     # Add LOST_FOUND debit type
20778     $dbh->do(qq{
20779         INSERT IGNORE INTO
20780           account_credit_types ( code, description, can_be_added_manually, is_system )
20781         VALUES
20782           ('LOST_FOUND', 'Lost item fee refund', 0, 1)
20783     });
20784
20785     # Migrate LOST_RETURN to LOST_FOUND
20786     $dbh->do(qq{
20787         UPDATE
20788           accountlines
20789         SET
20790           credit_type_code = 'LOST_FOUND'
20791         WHERE
20792           credit_type_code = 'LOST_RETURN'
20793         OR
20794           credit_type_code = 'LOST_RETURNED'
20795     });
20796
20797     # Migrate LOST + RETURNED to LOST + FOUND
20798     $dbh->do(qq{
20799         UPDATE
20800           accountlines
20801         SET
20802           status = 'FOUND'
20803         WHERE
20804           debit_type_code = 'LOST'
20805         AND
20806           status = 'RETURNED'
20807     });
20808
20809     # Drop LOST_RETURNED credit type
20810     $dbh->do(qq{
20811         DELETE FROM account_credit_types WHERE code = 'LOST_RETURNED'
20812     });
20813
20814     # Drop LOST_RETURN credit type
20815     $dbh->do(qq{
20816         DELETE FROM account_credit_types WHERE code = 'LOST_RETURN'
20817     });
20818
20819     # Add Lost Item Found offset type
20820     $dbh->do(qq{
20821         INSERT IGNORE INTO
20822           account_offset_types ( type )
20823         VALUES
20824           ( 'Lost Item Found' )
20825     });
20826
20827     NewVersion( $DBversion, 24592, 'Update LOST_RETURN to LOST_FOUND');
20828 }
20829
20830 $DBversion = '19.12.00.022';
20831 if( CheckVersion( $DBversion ) ) {
20832     $dbh->do( "ALTER TABLE items MODIFY COLUMN uri MEDIUMTEXT" );
20833     $dbh->do( "ALTER TABLE deleteditems MODIFY COLUMN uri MEDIUMTEXT" );
20834
20835     NewVersion( $DBversion, 20882, 'items.uri to MEDIUMTEXT');
20836 }
20837
20838 $DBversion = '19.12.00.023';
20839 if( CheckVersion( $DBversion ) ) {
20840     $dbh->do( "ALTER TABLE quotes MODIFY timestamp datetime NULL" );
20841
20842     NewVersion( $DBversion, 24640, 'Allow quotes.timestamp to be NULL');
20843 }
20844
20845 $DBversion = '19.12.00.024';
20846 if( CheckVersion( $DBversion ) ) {
20847     $dbh->do(q{
20848         UPDATE systempreferences SET value = 'off'
20849         WHERE variable = 'finesMode' AND (value <> 'production' OR value IS NULL)
20850     });
20851     $dbh->do(q{
20852         UPDATE systempreferences SET options = 'off|production',
20853         explanation = "Choose the fines mode, 'off' (do not accrue fines) or 'production' (accrue overdue fines).  Requires accruefines cronjob or CalculateFinesOnReturn system preference."
20854         WHERE variable = 'finesMode'
20855     });
20856
20857     NewVersion( $DBversion, 21633, 'Remove finesMode "test"');
20858 }
20859
20860 $DBversion = '19.12.00.025';
20861 if( CheckVersion( $DBversion ) ) {
20862     $dbh->do(q{
20863         INSERT IGNORE INTO `systempreferences` (variable,value,options,explanation,type)
20864         VALUES ('DumpSearchQueryTemplate',0,'','Add the search query being passed to the search engine into the template for debugging','YesNo')
20865     });
20866
20867     NewVersion( $DBversion, 24103, 'add DumpSearchQueryTemplate syspref');
20868 }
20869
20870 $DBversion = '19.12.00.026';
20871 if( CheckVersion( $DBversion ) ) {
20872     if( !column_exists( 'z3950servers', 'attributes' ) ) {
20873         $dbh->do( "ALTER TABLE z3950servers ADD COLUMN attributes VARCHAR(255) after add_xslt" );
20874     }
20875
20876     NewVersion( $DBversion, 11297, 'Add support for custom PQF attributes for Z39.50 server searches');
20877 }
20878
20879 $DBversion = '19.12.00.027';
20880 if( CheckVersion( $DBversion ) ) {
20881
20882     # Add any pathalogical incorrect debit_types as credit_types as appropriate
20883     $dbh->do(
20884         qq{
20885           INSERT IGNORE INTO account_credit_types (
20886             code,
20887             description,
20888             can_be_added_manually,
20889             is_system
20890           )
20891           SELECT
20892             DISTINCT(debit_type_code),
20893             "Unexpected type found during upgrade",
20894             1,
20895             0
20896           FROM
20897             accountlines
20898           WHERE
20899             amount < 0
20900           AND
20901             debit_type_code IS NOT NULL
20902         }
20903     );
20904
20905     # Correct any pathalogical cases
20906     $dbh->do( qq{
20907       UPDATE
20908         accountlines
20909       SET
20910         credit_type_code = debit_type_code,
20911         debit_type_code = NULL
20912       WHERE
20913         amount < 0
20914       AND
20915         debit_type_code IS NOT NULL
20916     });
20917
20918     NewVersion( $DBversion, 24532, 'Fix pathological cases of negative debits');
20919 }
20920
20921 $DBversion = '19.12.00.028';
20922 if( CheckVersion( $DBversion ) ) {
20923     $dbh->do(q{
20924         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
20925         VALUES
20926         ('OpacBrowseSearch', '0',NULL, "Elasticsearch only: add a page allowing users to 'browse' all items in the collection",'YesNo')
20927     });
20928
20929     NewVersion( $DBversion, 14567, 'Add OpacBrowseSearch syspref');
20930 }
20931
20932 $DBversion = '19.12.00.029';
20933 if( CheckVersion( $DBversion ) ) {
20934     if (!column_exists('account_credit_types', 'archived')) {
20935         $dbh->do('ALTER TABLE account_credit_types ADD COLUMN archived tinyint(1) NOT NULL DEFAULT 0 AFTER is_system');
20936     }
20937
20938     NewVersion( $DBversion, 17702, 'Add column account_credit_types.archived');
20939 }
20940
20941 $DBversion = '19.12.00.030';
20942 if( CheckVersion( $DBversion ) ) {
20943
20944     # get list of installed translations
20945     require C4::Languages;
20946     my @langs;
20947     my $tlangs = C4::Languages::getTranslatedLanguages('opac','bootstrap');
20948
20949     foreach my $language ( @$tlangs ) {
20950         foreach my $sublanguage ( @{$language->{'sublanguages_loop'}} ) {
20951             push @langs, $sublanguage->{'rfc4646_subtag'};
20952         }
20953     }
20954
20955     # Get any existing value from the opacheader system preference
20956     my ($opacheader) = $dbh->selectrow_array( q|
20957         SELECT value FROM systempreferences WHERE variable='opacheader';
20958     |);
20959
20960     my @detail;
20961     if( $opacheader ){
20962         foreach my $lang ( @langs ) {
20963             # If there is a value in the opacheader preference, insert it into opac_news
20964             $dbh->do("INSERT INTO opac_news (branchcode, lang, title, content ) VALUES (NULL, ?, '', ?)", undef, "opacheader_$lang", $opacheader);
20965             push @detail, "Inserted opacheader contents into $lang news item...";
20966         }
20967     }
20968     # Remove the opacheader system preference
20969     $dbh->do("DELETE FROM systempreferences WHERE variable='opacheader'");
20970
20971     unshift @detail, 'Move contents of opacheader preference to Koha news system';
20972     NewVersion( $DBversion, 22880, \@detail);
20973 }
20974
20975 $DBversion = '19.12.00.031';
20976 if( CheckVersion( $DBversion ) ) {
20977     $dbh->do( q|
20978 ALTER TABLE article_requests MODIFY COLUMN created_on timestamp NULL, MODIFY COLUMN updated_on timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
20979     |);
20980
20981     NewVersion( $DBversion, 22273, "Column article_requests.created_on should not be updated" );
20982 }
20983
20984 $DBversion = '19.12.00.032';
20985 if( CheckVersion( $DBversion ) ) {
20986     $dbh->do( q|
20987         DELETE FROM systempreferences WHERE variable="UseQueryParser"
20988     |);
20989
20990     NewVersion( $DBversion, 24735, "Remove UseQueryParser system preference" );
20991 }
20992
20993 $DBversion = '19.12.00.033';
20994 if ( CheckVersion($DBversion) ) {
20995
20996     # Add cash_register_actions table
20997     if ( !TableExists('cash_register_actions') ) {
20998         $dbh->do(qq{
20999             CREATE TABLE `cash_register_actions` (
21000               `id` int(11) NOT NULL auto_increment, -- unique identifier for each account register action
21001               `code` varchar(24) NOT NULL, -- action code denoting the type of action recorded (enum),
21002               `register_id` int(11) NOT NULL, -- id of cash_register this action belongs to,
21003               `manager_id` int(11) NOT NULL, -- staff member performing the action
21004               `amount` decimal(28,6) DEFAULT NULL, -- amount recorded in action (signed)
21005               `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
21006               PRIMARY KEY (`id`),
21007               CONSTRAINT `cash_register_actions_manager` FOREIGN KEY (`manager_id`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
21008               CONSTRAINT `cash_register_actions_register` FOREIGN KEY (`register_id`) REFERENCES `cash_registers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
21009             ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
21010         });
21011     }
21012
21013     # Add cashup permission
21014     $dbh->do(qq{
21015         INSERT IGNORE permissions (module_bit, code, description)
21016         VALUES
21017         (25, 'cashup', 'Perform cash register cashup action')
21018     });
21019
21020     NewVersion( $DBversion, 23355, [ "Add cash_register_actions table", "Add cash register cashup permissions" ] );
21021 }
21022
21023 $DBversion = '19.12.00.034';
21024 if ( CheckVersion($DBversion) ) {
21025
21026     $dbh->do(
21027         qq{
21028             INSERT IGNORE INTO account_credit_types (code, description, can_be_added_manually, is_system)
21029             VALUES
21030               ('DISCOUNT', 'A discount applied to a patrons fine', 0, 1)
21031         }
21032     );
21033
21034     $dbh->do(
21035         qq{
21036         INSERT IGNORE INTO account_offset_types ( type ) VALUES ('DISCOUNT');
21037     }
21038     );
21039
21040     $dbh->do(
21041         qq{
21042         INSERT IGNORE permissions (module_bit, code, description)
21043         VALUES
21044         (10, 'discount', 'Perform account discount action')
21045     }
21046     );
21047
21048     NewVersion( $DBversion, 24081, "Add DISCOUNT to account_credit_types and account_offset_types, Add accounts discount permission");
21049 }
21050
21051 $DBversion = '19.12.00.035';
21052 if ( CheckVersion($DBversion) ) {
21053
21054     $dbh->do(qq{
21055         INSERT IGNORE permissions (module_bit, code, description)
21056         VALUES
21057         (25, 'anonymous_refund', 'Perform refund actions from cash registers')
21058     });
21059
21060     NewVersion( $DBversion, 23442, "Add a refund option to the point of sale system" );
21061 }
21062
21063 $DBversion = '19.12.00.036';
21064 if( CheckVersion( $DBversion ) ) {
21065     $dbh->do(q{
21066         INSERT IGNORE INTO `systempreferences`
21067             (`variable`, `value`, `options`, `explanation`, `type`)
21068         VALUES
21069             ('AccessControlAllowOrigin', '', NULL, 'Set the Access-Control-Allow-Origin header to the specified value', 'Free');
21070     });
21071
21072     NewVersion( $DBversion, 24369, "Add CORS support to Koha");
21073 }
21074
21075 $DBversion = '19.12.00.037';
21076 if( CheckVersion( $DBversion ) ) {
21077
21078     $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'); | );
21079     
21080     $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'); | );
21081
21082     NewVersion( $DBversion, 23051, [ "Add RenewAccruingItemInOpac syspref", "Add RenewAccruingItemWhenPaid syspref" ]);
21083 }
21084
21085 $DBversion = '19.12.00.038';
21086 if( CheckVersion( $DBversion ) ) {
21087     $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'); | );
21088
21089     NewVersion( $DBversion, 23112, "Add CirculateILL syspref");
21090 }
21091
21092 $DBversion = '19.12.00.039';
21093 if( CheckVersion( $DBversion ) ) {
21094     $dbh->do( "DROP TABLE IF EXISTS printers" );
21095
21096     if( column_exists( 'branches', 'branchprinter' ) ) {
21097         $dbh->do( "ALTER TABLE branches DROP COLUMN branchprinter" );
21098     }
21099
21100     $dbh->do(qq{ DELETE FROM systempreferences WHERE variable = "printcirculationslips"} );
21101
21102     NewVersion( $DBversion, 17845, "Drop unused table printers and branchprinter column");
21103 }
21104
21105 $DBversion = '19.12.00.040';
21106 if( CheckVersion( $DBversion ) ) {
21107     $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' " );
21108
21109     NewVersion( $DBversion, 17374, "Update description of DefaultPatronSearchFields");
21110 }
21111
21112 $DBversion = '19.12.00.041';
21113 if( CheckVersion( $DBversion ) ) {
21114
21115     # Update existing NULL priorities
21116     $dbh->do(q|
21117         UPDATE reserves SET priority = 1 WHERE priority IS NULL
21118     |);
21119
21120     $dbh->do(q|
21121         ALTER TABLE reserves MODIFY priority SMALLINT(6) NOT NULL DEFAULT 1
21122     |);
21123
21124     $dbh->do(q|
21125         UPDATE old_reserves SET priority = 1 WHERE priority IS NULL
21126     |);
21127
21128     $dbh->do(q|
21129         ALTER TABLE old_reserves MODIFY priority SMALLINT(6) NOT NULL DEFAULT 1
21130     |);
21131
21132     NewVersion( $DBversion, 24722, "Enforce NOT NULL constraint for reserves.priority");
21133 }
21134
21135 $DBversion = '19.12.00.042';
21136 if( CheckVersion( $DBversion ) ) {
21137     if (!column_exists('message_queue', 'reply_address')) {
21138         $dbh->do('ALTER TABLE message_queue ADD COLUMN reply_address LONGTEXT AFTER from_address');
21139     }
21140
21141     NewVersion( $DBversion, 22821, "Add reply_address to message_queue");
21142 }
21143
21144 $DBversion = '19.12.00.043';
21145 if( CheckVersion( $DBversion ) ) {
21146
21147     # Add return reasons to enum
21148     $dbh->do(
21149         qq{
21150             ALTER TABLE
21151                 `branchtransfers`
21152             MODIFY COLUMN
21153                 `reason` enum(
21154                     'Manual',
21155                     'StockrotationAdvance',
21156                     'StockrotationRepatriation',
21157                     'ReturnToHome',
21158                     'ReturnToHolding'
21159                 )
21160             AFTER `comments`
21161           }
21162     );
21163
21164     NewVersion( $DBversion, 24296, "Add 'return' reasons to branchtransfers enum");
21165 }
21166
21167 $DBversion = '19.12.00.044';
21168 if( CheckVersion( $DBversion ) ) {
21169     $dbh->do(qq{
21170         INSERT IGNORE permissions (module_bit, code, description)
21171         VALUES
21172         (13, 'batch_extend_due_dates', 'Perform batch extend due dates')
21173     });
21174
21175     NewVersion( $DBversion, 24846, "Add a new permission for new tool batch extend due dates");
21176 }
21177
21178 $DBversion = '19.12.00.045';
21179 if( CheckVersion( $DBversion ) ) {
21180     $dbh->do(q{
21181         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) 
21182         VALUES
21183         ('CollapseFieldsPatronAddForm','',NULL,'Collapse these fields by default when adding a new patron. These fields can still be expanded.','Multiple') 
21184     });
21185
21186     NewVersion( $DBversion, 4461, "Add CollapseFieldsPatronAddForm system preference");
21187 }
21188
21189 $DBversion = '19.12.00.046';
21190 if( CheckVersion( $DBversion ) ) {
21191
21192     $dbh->do( "ALTER TABLE accountlines MODIFY COLUMN date TIMESTAMP NULL" );
21193
21194     NewVersion( $DBversion, 24818, "Update 'accountlines.date' from DATE to TIMESTAMP");
21195 }
21196
21197 $DBversion = '19.12.00.047';
21198 if( CheckVersion( $DBversion ) ) {
21199     $dbh->do(q{
21200         ALTER TABLE biblioimages
21201         ADD `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
21202         AFTER `thumbnail`;
21203     });
21204
21205     NewVersion( $DBversion, 22987, "Add biblioimages.timestamp");
21206 }
21207
21208 $DBversion = '19.12.00.048';
21209 if( CheckVersion( $DBversion ) ) {
21210
21211     # Add rotating collection states to reason enum
21212     $dbh->do(
21213         qq{
21214             ALTER TABLE
21215                 `branchtransfers`
21216             MODIFY COLUMN
21217                 `reason` enum(
21218                     'Manual',
21219                     'StockrotationAdvance',
21220                     'StockrotationRepatriation',
21221                     'ReturnToHome',
21222                     'ReturnToHolding',
21223                     'RotatingCollection'
21224                 )
21225             AFTER `comments`
21226           }
21227     );
21228
21229     NewVersion( $DBversion, 24299, "Add 'collection' reasons to branchtransfers enum");
21230 }
21231
21232 $DBversion = '19.12.00.049';
21233 if( CheckVersion( $DBversion ) ) {
21234
21235     # Add reserve reasons enum
21236     $dbh->do(
21237         qq{
21238             ALTER TABLE
21239                 `branchtransfers`
21240             MODIFY COLUMN
21241                 `reason` enum(
21242                     'Manual',
21243                     'StockrotationAdvance',
21244                     'StockrotationRepatriation',
21245                     'ReturnToHome',
21246                     'ReturnToHolding',
21247                     'RotatingCollection',
21248                     'Reserve',
21249                     'LostReserve',
21250                     'CancelReserve'
21251                 )
21252             AFTER `comments`
21253           }
21254     );
21255
21256     NewVersion( $DBversion, 24299, "Add 'reserve' reasons to branchtransfers enum");
21257 }
21258
21259 $DBversion = '19.12.00.050';
21260 if( CheckVersion( $DBversion ) ) {
21261     $dbh->do( "DELETE FROM systempreferences WHERE variable in ('IDreamBooksReadometer','IDreamBooksResults','IDreamBooksReviews')" );
21262
21263     NewVersion( $DBversion, 24854, "Remove IDreamBooks* system preferences");
21264 }
21265
21266 $DBversion = '19.12.00.051';
21267 if( CheckVersion( $DBversion ) ) {
21268     $dbh->do(q{
21269         UPDATE systempreferences SET options = 'itemhomebranch|patronhomebranch|checkoutbranch|none' WHERE variable='OpacRenewalBranch'
21270     });
21271     $dbh->do(q{
21272         UPDATE systempreferences SET value = "none" WHERE variable='OpacRenewalBranch'
21273         AND value = 'NULL'
21274     });
21275     $dbh->do(q{
21276         UPDATE systempreferences SET value = 'opacrenew' WHERE variable='OpacRenewalBranch'
21277         AND value NOT IN ('checkoutbranch','itemhomebranch','opacrenew','patronhomebranch','none')
21278     });
21279
21280     NewVersion( $DBversion, 24759, "Cleanup OpacRenewalBranch");
21281 }
21282
21283 $DBversion = '19.12.00.052';
21284 if( CheckVersion( $DBversion ) ) {
21285     my $finesCalendar = C4::Context->preference('finesCalendar');
21286     my $value = $finesCalendar eq 'noFinesWhenClosed' ? 1 : 0;
21287
21288     if( !column_exists( 'itemtypes', 'rentalcharge_daily_calendar' ) ) {
21289         $dbh->do(q{
21290             ALTER TABLE itemtypes ADD COLUMN
21291             rentalcharge_daily_calendar tinyint(1) NOT NULL DEFAULT 1
21292             AFTER rentalcharge_daily;
21293         });
21294
21295         $dbh->do("UPDATE itemtypes SET rentalcharge_daily_calendar = $value");
21296     }
21297
21298     if( !column_exists( 'itemtypes', 'rentalcharge_hourly_calendar' ) ) {
21299         $dbh->do(q{
21300             ALTER TABLE itemtypes ADD COLUMN
21301             rentalcharge_hourly_calendar tinyint(1) NOT NULL DEFAULT 1
21302             AFTER rentalcharge_hourly;
21303         });
21304
21305         $dbh->do("UPDATE itemtypes SET rentalcharge_hourly_calendar = $value");
21306     }
21307
21308     NewVersion( $DBversion, 21443, "Add ability to exclude holidays when calculating rentals fees by time period");
21309 }
21310
21311 $DBversion = '19.12.00.053';
21312 if( CheckVersion( $DBversion ) ) {
21313     unless( column_exists('borrowers','autorenew_checkouts') ){
21314         $dbh->do( "ALTER TABLE borrowers ADD COLUMN autorenew_checkouts TINYINT(1) NOT NULL DEFAULT 1 AFTER anonymized" );
21315     }
21316     unless( column_exists('deletedborrowers','autorenew_checkouts') ){
21317         $dbh->do( "ALTER TABLE deletedborrowers ADD COLUMN autorenew_checkouts TINYINT(1) NOT NULL DEFAULT 1 AFTER anonymized" );
21318     }
21319     $dbh->do(q{
21320         INSERT IGNORE INTO systempreferences
21321         ( `variable`, `value`, `options`, `explanation`, `type` )
21322         VALUES
21323         ('AllowPatronToControlAutorenewal','0',NULL,'If enabled, patrons will have a field in their account to choose whether their checkouts are auto renewed or not','YesNo')
21324     });
21325
21326     NewVersion( $DBversion, 24476, "Allow patrons to opt-out of autorenewal");
21327 }
21328
21329 $DBversion = '19.12.00.054';
21330 if( CheckVersion( $DBversion ) ) {
21331
21332     if ( !TableExists('desks') ) {
21333         $dbh->do(qq{
21334              CREATE TABLE `desks` ( -- desks available in a library
21335                `desk_id` int(11) NOT NULL auto_increment, -- unique identifier added by Koha
21336                `desk_name` varchar(100) NOT NULL default '', -- name of the desk
21337                `branchcode` varchar(10) NOT NULL,       -- library the desk is located at
21338                PRIMARY KEY (`desk_id`),
21339                KEY `fk_desks_branchcode` (`branchcode`),
21340                CONSTRAINT `fk_desks_branchcode` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
21341              ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
21342         });
21343     }
21344
21345     NewVersion( $DBversion, 13881, "Add desk management");
21346 }
21347
21348 $DBversion = '19.12.00.055';
21349 if( CheckVersion( $DBversion ) ) {
21350     if( !column_exists( 'suggestions', 'lastmodificationby' ) ) {
21351         $dbh->do(q|
21352             ALTER TABLE suggestions ADD COLUMN lastmodificationby INT(11) DEFAULT NULL AFTER rejecteddate
21353         |);
21354
21355         $dbh->do(q|
21356             ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_lastmodificationby` FOREIGN KEY (`lastmodificationby`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE
21357         |);
21358     }
21359
21360     if( !column_exists( 'suggestions', 'lastmodificationdate' ) ) {
21361         $dbh->do(q|
21362             ALTER TABLE suggestions ADD COLUMN lastmodificationdate DATE DEFAULT NULL AFTER lastmodificationby
21363         |);
21364
21365         my $suggestions = $dbh->selectall_arrayref(q|
21366             SELECT suggestionid, managedby, manageddate, acceptedby, accepteddate, rejectedby, rejecteddate
21367             FROM suggestions
21368         |, { Slice => {} });
21369         for my $suggestion ( @$suggestions ) {
21370             my ( $max_date ) = sort ( $suggestion->{manageddate} || (), $suggestion->{accepteddate} || (), $suggestion->{rejecteddate} || () );
21371             next unless $max_date;
21372             my $last_modif_by = ( defined $suggestion->{manageddate} and $max_date eq $suggestion->{manageddate} )
21373               ? $suggestion->{managedby}
21374               : ( defined $suggestion->{accepteddate} and $max_date eq $suggestion->{accepteddate} )
21375               ? $suggestion->{acceptedby}
21376               : ( defined $suggestion->{rejecteddate} and $max_date eq $suggestion->{rejecteddate} )
21377               ? $suggestion->{rejectedby}
21378               : undef;
21379             next unless $last_modif_by;
21380             $dbh->do(q|
21381                 UPDATE suggestions
21382                 SET lastmodificationdate = ?, lastmodificationby = ?
21383                 WHERE suggestionid = ?
21384             |, undef, $max_date, $last_modif_by, $suggestion->{suggestionid});
21385         }
21386
21387     }
21388
21389     $dbh->do( q|
21390         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');
21391     | );
21392
21393     NewVersion( $DBversion, 23590, "Add lastmodificationby and lastmodificationdate to the suggestions table");
21394 }
21395
21396 $DBversion = '19.12.00.056';
21397 if( CheckVersion( $DBversion ) ) {
21398
21399     $dbh->do( "DELETE FROM systempreferences WHERE variable='UseKohaPlugins'" );
21400
21401     NewVersion( $DBversion, 20415, "Remove UseKohaPlugins preference");
21402 }
21403
21404 $DBversion = '19.12.00.057';
21405 if( CheckVersion( $DBversion ) ) {
21406
21407     $dbh->do( "DELETE FROM systempreferences WHERE variable='INTRAdidyoumean'" );
21408
21409     NewVersion( $DBversion, 20399, "Remove INTRAdidyoumean preference");
21410 }
21411
21412 $DBversion = '19.12.00.058';
21413 if( CheckVersion( $DBversion ) ) {
21414     $dbh->do(q{
21415         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`,`type`) VALUES
21416         ('OPACnumSearchResultsDropdown', 0, NULL, 'Enable option list of number of results per page to show in OPAC search results','YesNo'),
21417         ('numSearchResultsDropdown', 0, NULL, 'Enable option list of number of results per page to show in staff client search results','YesNo')
21418     });
21419
21420     NewVersion( $DBversion, 14715, "Add sysprefs numSearchResultsDropdown and OPACnumSearchResultsDropdown");
21421 }
21422
21423 $DBversion = '19.12.00.059';
21424 if( CheckVersion( $DBversion ) ) {
21425
21426     for my $column ( qw(othersupplier booksellerfax booksellerurl bookselleremail currency) ) {
21427         if( column_exists( 'aqbooksellers', $column ) ) {
21428             my ($count) = $dbh->selectrow_array(qq|
21429                 SELECT COUNT(*)
21430                 FROM aqbooksellers
21431                 WHERE $column IS NOT NULL AND $column <> ""
21432             |);
21433             if ( $count ) {
21434                 warn "Warning - Cannot remove column aqbooksellers.$column. At least one value exists";
21435             } else {
21436                 $dbh->do(qq|
21437                     ALTER TABLE aqbooksellers
21438                     DROP COLUMN $column
21439                 |);
21440             }
21441         }
21442     }
21443
21444     NewVersion( $DBversion, 18177, "Remove some unused columns from aqbooksellers");
21445 }
21446
21447 $DBversion = '19.12.00.060';
21448 if( CheckVersion( $DBversion ) ) {
21449     $dbh->do(q{
21450         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';
21451     });
21452     NewVersion( $DBversion, 23204, "Change enum order for marc_type in search_marc_map to fix sorting");
21453 }
21454
21455 $DBversion = '19.12.00.061';
21456 if ( CheckVersion($DBversion) ) {
21457     $dbh->do(q{
21458         UPDATE
21459           systempreferences
21460         SET
21461           options = "batchmod|moredetail|cronjob|additem|pendingreserves|onpayment"
21462         WHERE
21463           variable = "MarkLostItemsAsReturned"
21464     });
21465
21466     my $lost_item_returned = C4::Context->preference("MarkLostItemsAsReturned");
21467     my @set = split( ",", $lost_item_returned );
21468     push @set, 'onpayment';
21469     $lost_item_returned = join( ",", @set );
21470
21471     $dbh->do(qq{
21472         UPDATE
21473           systempreferences
21474         SET
21475           value = "$lost_item_returned"
21476         WHERE
21477           variable = "MarkLostItemsAsReturned"
21478     });
21479
21480     NewVersion( $DBversion, 24474, "Add `onpayment` option to MarkLostItemsAsReturned");
21481 }
21482
21483 $DBversion = '19.12.00.062';
21484 if( CheckVersion( $DBversion ) ) {
21485     $dbh->do( "UPDATE account_debit_types SET description = REPLACE(description,'Rewewal','Renewal') WHERE description like '%Rewewal%'" );
21486
21487     NewVersion( $DBversion, 25010, "Fix typo in account_debit_type description");
21488 }
21489
21490 $DBversion = '19.12.00.063';
21491 if( CheckVersion( $DBversion ) ) {
21492     $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') });
21493
21494     NewVersion( $DBversion, 22534, "Add PreFillGuaranteeField syspref");
21495 }
21496
21497 $DBversion = '19.12.00.064';
21498 if( CheckVersion( $DBversion ) ) {
21499
21500     $dbh->do( q|
21501         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
21502             SELECT 'OpacNoItemTypeImages', value, NULL, 'If ON, disables itemtype images in the OPAC','YesNo'
21503             FROM (SELECT value FROM systempreferences WHERE variable="NoItemTypeImages") tmp
21504     | );
21505     $dbh->do( "UPDATE systempreferences SET explanation = 'If ON, disables itemtype images in the staff interface'
21506         WHERE variable = 'noItemTypeImages' ");
21507
21508     NewVersion( $DBversion, 4944, "Add new system preference OpacNoItemTypeImages");
21509 }
21510
21511 $DBversion = '19.12.00.065';
21512 if( CheckVersion( $DBversion ) ) {
21513
21514     $dbh->do( q| 
21515         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type) 
21516         VALUES ('ILLCheckAvailability', '0', 'If enabled, during the ILL request process third party sources will be checked for current availability', '', 'YesNo')
21517     | );
21518
21519     NewVersion( $DBversion, 23173, "Add ILLCheckAvailability syspref");
21520 }
21521
21522 $DBversion = '19.12.00.066';
21523 if ( CheckVersion($DBversion) ) {
21524     $dbh->do(
21525 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') }
21526     );
21527     $dbh->do(
21528 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') }
21529     );
21530     if ( !TableExists('problem_reports') ) {
21531         $dbh->do(
21532             q{ CREATE TABLE problem_reports (
21533             reportid int(11) NOT NULL auto_increment, -- unique identifier assigned by Koha
21534             title varchar(40) NOT NULL default '', -- report subject line
21535             content varchar(255) NOT NULL default '', -- report message content
21536             borrowernumber int(11) NOT NULL default 0, -- the user who created the problem report
21537             branchcode varchar(10) NOT NULL default '', -- borrower's branch
21538             username varchar(75) default NULL, -- OPAC username
21539             problempage TEXT default NULL, -- page the user triggered the problem report form from
21540             recipient enum('admin','library') NOT NULL default 'library', -- the 'to-address' of the problem report
21541             created_on timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of report submission
21542             status varchar(6) NOT NULL default 'New', -- status of the report. New, Viewed, Closed
21543             PRIMARY KEY (reportid),
21544             CONSTRAINT problem_reports_ibfk1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE,
21545             CONSTRAINT problem_reports_ibfk2 FOREIGN KEY (branchcode) REFERENCES branches (branchcode) ON DELETE CASCADE ON UPDATE CASCADE
21546         ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci }
21547         );
21548     }
21549     $dbh->do(
21550 q{INSERT IGNORE INTO userflags (bit, flag, flagdesc, defaulton) VALUES (26, 'problem_reports', 'Manage problem reports', 0) }
21551     );
21552     $dbh->do(
21553 q{INSERT IGNORE INTO permissions (module_bit, code, description) VALUES (26, 'manage_problem_reports', 'Manage OPAC problem reports') }
21554     );
21555
21556     NewVersion(
21557         $DBversion,
21558         4461,
21559         [
21560             "Add OPACReportProblem system preference",
21561             "Adding PROBLEM_REPORT notice",
21562             "Add problem reports table",
21563             "Add user permissions for managing OPAC problem reports"
21564         ]
21565     );
21566 }
21567
21568 $DBversion = '19.12.00.067';
21569 if( CheckVersion( $DBversion ) ) {
21570     # From: https://stackoverflow.com/questions/3311903/remove-duplicate-rows-in-mysql
21571     $dbh->do(q|
21572         DELETE a
21573         FROM virtualshelfshares as a, virtualshelfshares as b
21574         WHERE
21575           a.id < b.id 
21576         AND
21577           a.borrowernumber IS NOT NULL
21578         AND
21579           a.borrowernumber=b.borrowernumber
21580         AND
21581           a.shelfnumber=b.shelfnumber
21582     |);
21583
21584     NewVersion( $DBversion, 20754, "Remove double accepted list shares" );
21585 }
21586
21587 $DBversion = '19.12.00.068';
21588 if( CheckVersion( $DBversion ) ) {
21589     $dbh->do(q|
21590         INSERT IGNORE INTO systempreferences
21591           (variable,value,explanation,options,type)
21592         VALUES
21593           ('AuthFailureLog','','If enabled, log authentication failures',NULL,'YesNo'),
21594           ('AuthSuccessLog','','If enabled, log successful authentications',NULL,'YesNo')
21595     |);
21596
21597     NewVersion( $DBversion, 21190, "Add prefs AuthFailureLog and AuthSuccessLog");
21598 }
21599
21600 $DBversion = '19.12.00.069';
21601 if( CheckVersion( $DBversion ) ) {
21602     if( !column_exists( 'suggestions', 'archived' ) ) {
21603         $dbh->do(q|
21604             ALTER TABLE suggestions ADD COLUMN archived TINYINT(1) NOT NULL DEFAULT 0 AFTER `STATUS`;
21605         |);
21606     }
21607
21608     NewVersion( $DBversion, 22784, "Add a new suggestions.archived column");
21609 }
21610
21611 $DBversion = '19.12.00.070';
21612 if( CheckVersion( $DBversion ) ) {
21613
21614     $dbh->do( q{
21615             INSERT IGNORE INTO systempreferences (variable,value,explanation,type) VALUES
21616                 ('MaxTotalSuggestions','','Number of total suggestions used for time limit with NumberOfSuggestionDays','Free'),
21617                 ('NumberOfSuggestionDays','','Number of days that will be used to determine the MaxTotalSuggestions limit','Free')
21618             });
21619
21620     NewVersion( $DBversion, 22774, "Limit purchase suggestion in a specified time period");
21621 }
21622
21623 $DBversion = '19.12.00.071';
21624 if( CheckVersion( $DBversion ) ) {
21625     my @description = ("Add unique constraint to authorised_values");
21626     unless ( index_exists('authorised_values', 'av_uniq') ) {
21627         $dbh->do(q|
21628             DELETE FROM authorised_values
21629             WHERE category="COUNTRY" AND authorised_value="CC" AND lib="Keeling"
21630         |);
21631         my $duplicates = $dbh->selectall_arrayref(q|
21632             SELECT category, authorised_value, COUNT(concat(category, ':', authorised_value)) AS c
21633             FROM authorised_values
21634             GROUP BY category, authorised_value
21635             HAVING COUNT(concat(category, ':', authorised_value)) > 1
21636         |, { Slice => {} });
21637         if ( @$duplicates ) {
21638             push @description, "WARNING - Cannot create unique constraint on authorised_value(category, authorised_value)";
21639             push @description, "The following entries are duplicated: " . join(
21640                 ', ',
21641                 map {
21642                     sprintf "%s:%s (%s)", $_->{category},
21643                       $_->{authorised_value}, $_->{c}
21644                 } @$duplicates
21645             );
21646             for my $warning (@description) {
21647                 warn $warning;
21648             }
21649         } else {
21650             $dbh->do( q{ALTER TABLE `authorised_values` ADD CONSTRAINT `av_uniq` UNIQUE (category, authorised_value)} );
21651         }
21652     }
21653
21654     NewVersion( $DBversion, 22887, \@description );
21655 }
21656
21657 $DBversion = '19.12.00.072';
21658 if( CheckVersion( $DBversion ) ) {
21659     $dbh->do(q{
21660         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
21661             SELECT 'CalculateFinesOnBackdate',value,'','Switch to control if overdue fines are calculated on return when backdating','YesNo'
21662             FROM ( SELECT value FROM systempreferences WHERE variable = 'CalculateFinesOnReturn' ) tmp
21663     });
21664
21665     NewVersion( $DBversion, 24380, "Add syspref CalculateFinesOnBackdate");
21666 }
21667
21668 $DBversion = '19.12.00.073';
21669 if( CheckVersion( $DBversion ) ) {
21670     $dbh->do( "ALTER TABLE subscription MODIFY COLUMN closed tinyint(1) not null default 0" );
21671
21672     NewVersion( $DBversion, 25152, "Update subscription.closed to tinyint(1) as per guidelines");
21673 }
21674
21675 $DBversion = '19.12.00.074';
21676 if( CheckVersion( $DBversion ) ) {
21677     $dbh->do( "UPDATE systempreferences SET variable = 'SCOAllowCheckin' WHERE variable = 'AllowSelfCheckReturns'" );
21678
21679     # Always end with this (adjust the bug info)
21680     NewVersion( $DBversion, 25147, "Rename AllowSelfCheckReturns to SCOAllowCheckin for consistency");
21681 }
21682
21683 $DBversion = '19.12.00.075';
21684 if( CheckVersion( $DBversion ) ) {
21685
21686     $dbh->do( "ALTER TABLE borrower_modifications MODIFY changed_fields MEDIUMTEXT DEFAULT NULL" );
21687
21688     NewVersion( $DBversion, 25086, "Set changed_fields column of borrower_modifications as nullable");
21689 }
21690
21691 $DBversion = '19.12.00.076';
21692 if( CheckVersion( $DBversion ) ) {
21693     my @warnings;
21694
21695     sanitize_zero_date('serial', 'planneddate');
21696     sanitize_zero_date('serial', 'publisheddate');
21697     sanitize_zero_date('serial', 'claimdate');
21698
21699     $dbh->do(q|
21700         ALTER TABLE serial
21701         MODIFY COLUMN biblionumber INT(11) NOT NULL
21702     |);
21703
21704     unless ( foreign_key_exists( 'serial', 'serial_ibfk_1' ) ) {
21705         my $serials = $dbh->selectall_arrayref(q|
21706             SELECT serialid FROM serial WHERE biblionumber NOT IN (SELECT biblionumber FROM biblio)
21707         |, { Slice => {} });
21708         if ( @$serials ) {
21709             push @warnings, q|WARNING - The following serials are deleted, they were not attached to an existing bibliographic record (serialid): | . join ", ", map { $_->{serialid} } @$serials;
21710             $dbh->do(q|
21711                 DELETE FROM serial WHERE biblionumber NOT IN (SELECT biblionumber FROM biblio)
21712             |);
21713         }
21714         $dbh->do(q|
21715             ALTER TABLE serial
21716             ADD CONSTRAINT serial_ibfk_1 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
21717         |);
21718     }
21719
21720     $dbh->do(q|
21721         ALTER TABLE serial
21722         MODIFY COLUMN subscriptionid INT(11) NOT NULL
21723     |);
21724
21725     unless ( foreign_key_exists( 'serial', 'serial_ibfk_2' ) ) {
21726         my $serials = $dbh->selectall_arrayref(q|
21727             SELECT serialid FROM serial WHERE subscriptionid NOT IN (SELECT subscriptionid FROM subscription)
21728         |, { Slice => {} });
21729         if ( @$serials ) {
21730             push @warnings, q|WARNING - The following serials are deleted, they were not attached to an existing subscription (serialid): | . join ", ", map { $_->{serialid} } @$serials;
21731             $dbh->do(q|
21732                 DELETE FROM serial WHERE subscriptionid NOT IN (SELECT subscriptionid FROM subscription)
21733             |);
21734         }
21735         $dbh->do(q|
21736             ALTER TABLE serial
21737             ADD CONSTRAINT serial_ibfk_2 FOREIGN KEY (subscriptionid) REFERENCES subscription (subscriptionid) ON DELETE CASCADE ON UPDATE CASCADE
21738         |);
21739     }
21740
21741     $dbh->do(q|
21742         ALTER TABLE subscriptionhistory
21743         MODIFY COLUMN biblionumber int(11) NOT NULL,
21744         MODIFY COLUMN subscriptionid int(11) NOT NULL
21745     |);
21746
21747     unless ( foreign_key_exists( 'subscriptionhistory', 'subscription_history_ibfk_1' ) ) {
21748         $dbh->do(q|
21749             DELETE FROM subscriptionhistory WHERE biblionumber NOT IN (SELECT biblionumber FROM biblio)
21750         |);
21751         $dbh->do(q|
21752             ALTER TABLE subscriptionhistory
21753             ADD CONSTRAINT subscription_history_ibfk_1 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
21754         |);
21755     }
21756
21757     unless ( foreign_key_exists( 'subscriptionhistory', 'subscription_history_ibfk_2' ) ) {
21758         $dbh->do(q|
21759             DELETE FROM subscriptionhistory WHERE subscriptionid NOT IN (SELECT subscriptionid FROM subscription)
21760         |);
21761         $dbh->do(q|
21762             ALTER TABLE subscriptionhistory
21763             ADD CONSTRAINT subscription_history_ibfk_2 FOREIGN KEY (subscriptionid) REFERENCES subscription (subscriptionid) ON DELETE CASCADE ON UPDATE CASCADE
21764         |);
21765     }
21766
21767     $dbh->do(q|
21768         ALTER TABLE subscription
21769         MODIFY COLUMN biblionumber int(11) NOT NULL
21770     |);
21771
21772     unless ( foreign_key_exists( 'subscription', 'subscription_ibfk_3' ) ) {
21773         my $subscriptions = $dbh->selectall_arrayref(q|
21774             SELECT subscriptionid FROM subscription WHERE biblionumber NOT IN (SELECT biblionumber FROM biblio)
21775         |, { Slice => {} });
21776         if ( @$subscriptions ) {
21777             push @warnings, q|WARNING - The following subscriptions are deleted, they were not attached to an existing bibliographic record (subscriptionid): | . join ", ", map { $_->{subscriptionid} } @$subscriptions;
21778
21779             $dbh->do(q|
21780                 DELETE FROM subscription WHERE biblionumber NOT IN (SELECT biblionumber FROM biblio)
21781             |);
21782         }
21783         $dbh->do(q|
21784             ALTER TABLE subscription
21785             ADD CONSTRAINT subscription_ibfk_3 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
21786         |);
21787     }
21788
21789     for my $warning (@warnings) {
21790         warn $warning;
21791     }
21792
21793     my $description = [ "Add foreign key constraints on serial", @warnings ];
21794     NewVersion( $DBversion, 21901, $description);
21795 }
21796
21797 $DBversion = '19.12.00.077';
21798 if( CheckVersion( $DBversion ) ) {
21799     if ( !column_exists( 'course_items', 'itype_enabled' ) ) {
21800         $dbh->do(q{
21801             ALTER TABLE course_items
21802             ADD COLUMN itype_enabled tinyint(1) NOT NULL DEFAULT 0 AFTER itype,
21803             ADD COLUMN ccode_enabled tinyint(1) NOT NULL DEFAULT 0 AFTER ccode,
21804             ADD COLUMN holdingbranch_enabled tinyint(1) NOT NULL DEFAULT 0 AFTER holdingbranch,
21805             ADD COLUMN location_enabled tinyint(1) NOT NULL DEFAULT 0 AFTER location,
21806             ADD COLUMN itype_storage varchar(10) DEFAULT NULL AFTER itype_enabled,
21807             ADD COLUMN ccode_storage varchar(80) DEFAULT NULL AFTER ccode_enabled,
21808             ADD COLUMN holdingbranch_storage varchar(10) DEFAULT NULL AFTER ccode_enabled,
21809             ADD COLUMN location_storage varchar(80) DEFAULT NULL AFTER location_enabled
21810         });
21811
21812         my $item_level_items = C4::Context->preference('item-level_itypes');
21813         my $itype_field = $item_level_items ? 'i.itype' : 'bi.itemtype';
21814         $dbh->do(qq{
21815             UPDATE course_items ci
21816             LEFT JOIN items i USING ( itemnumber )
21817             LEFT JOIN biblioitems bi USING ( biblioitemnumber )
21818             SET
21819
21820             -- Assume the column is enabled if the course item is active and i.itype/bi.itemtype is set,
21821             -- or if the course item is not enabled and ci.itype is set
21822             ci.itype_enabled = IF( ci.enabled = 'yes', IF( $itype_field IS NULL, 0, 1 ), IF(  ci.itype IS NULL, 0, 1  ) ),
21823             ci.ccode_enabled = IF( ci.enabled = 'yes', IF( i.ccode IS NULL, 0, 1 ), IF(  ci.ccode IS NULL, 0, 1  ) ),
21824             ci.holdingbranch_enabled = IF( ci.enabled = 'yes', IF( i.holdingbranch IS NULL, 0, 1 ), IF(  ci.holdingbranch IS NULL, 0, 1  ) ),
21825             ci.location_enabled = IF( ci.enabled = 'yes', IF( i.location IS NULL, 0, 1 ), IF(  ci.location IS NULL, 0, 1  ) ),
21826
21827             -- If the course item is enabled, copy the value from the item.
21828             -- If the course item is not enabled, keep the existing value
21829             ci.itype = IF( ci.enabled = 'yes', $itype_field, ci.itype ),
21830             ci.ccode = IF( ci.enabled = 'yes', i.ccode, ci.ccode ),
21831             ci.holdingbranch = IF( ci.enabled = 'yes', i.holdingbranch, ci.holdingbranch ),
21832             ci.location = IF( ci.enabled = 'yes', i.location, ci.location ),
21833
21834             -- If the course is enabled, copy the value from the item to storage.
21835             -- If it is not enabled, copy the value from the course item to storage
21836             ci.itype_storage = IF( ci.enabled = 'no', $itype_field, ci.itype ),
21837             ci.ccode_storage = IF( ci.enabled = 'no', i.ccode, ci.ccode ),
21838             ci.holdingbranch_storage = IF( ci.enabled = 'no', i.holdingbranch, ci.holdingbranch ),
21839             ci.location_storage = IF( ci.enabled = 'no', i.location, ci.location );
21840         });
21841
21842         # Clean up the storage columns
21843         $dbh->do(q{
21844             UPDATE course_items SET
21845                 itype_storage = NULL,
21846                 ccode_storage = NULL,
21847                 holdingbranch_storage = NULL,
21848                 location_storage = NULL
21849             WHERE enabled = 'no';
21850         });
21851
21852         # Clean up the course enabled value columns
21853         $dbh->do(q{
21854             UPDATE course_items SET
21855                 itype = IF( itype_enabled = 'no', NULL, itype ),
21856                 ccode = IF( ccode_enabled = 'no', NULL, ccode ),
21857                 holdingbranch = IF( holdingbranch_enabled = 'no', NULL, holdingbranch ),
21858                 location = IF( location_enabled = 'no', NULL, location )
21859             WHERE enabled = 'no';
21860         });
21861     }
21862
21863     NewVersion( $DBversion, 23727, "Editing course reserve items is broken");
21864 }
21865
21866 $DBversion = '19.12.00.078';
21867 if( CheckVersion( $DBversion ) ) {
21868     $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') });
21869
21870     NewVersion( $DBversion, 24913, "Add PatronSelfRegistrationConfirmEmail syspref");
21871 }
21872
21873 $DBversion = '19.12.00.079';
21874 if( CheckVersion( $DBversion ) ) {
21875
21876     # Default to the homologous OpacPublic syspref
21877     my $opac_public = C4::Context->preference('OpacPublic') ? 1 : 0;
21878
21879     $dbh->do(qq{
21880         INSERT IGNORE INTO `systempreferences`
21881             (`variable`,`value`,`explanation`,`options`,`type`)
21882         VALUES
21883             ('RESTPublicAnonymousRequests', $opac_public, NULL,'If enabled, the API will allow anonymous access to public routes that do not require authenticated access.','YesNo');
21884     });
21885
21886     NewVersion( $DBversion, 25045, "Add a way to restrict anonymous access to public routes (OpacPublic behaviour)");
21887 }
21888
21889 $DBversion = '19.12.00.080';
21890 if( CheckVersion( $DBversion ) ) {
21891      $dbh->do( "UPDATE items set issues=0 where issues is null" );
21892      $dbh->do( "UPDATE deleteditems set issues=0 where issues is null" );
21893      $dbh->do( "ALTER TABLE items ALTER issues set default 0" );
21894      $dbh->do( "ALTER TABLE deleteditems ALTER issues set default 0" );
21895
21896     NewVersion( $DBversion, 23081, "Set default to 0 for items.issues");
21897 }
21898
21899 $DBversion = '19.12.00.081';
21900 if (CheckVersion($DBversion)) {
21901     if (!column_exists('course_items', 'homebranch')) {
21902         $dbh->do(q{
21903             ALTER TABLE course_items
21904             ADD COLUMN homebranch VARCHAR(10) NULL DEFAULT NULL AFTER ccode_storage
21905         });
21906     }
21907
21908     if (!foreign_key_exists('course_items', 'fk_course_items_homebranch')) {
21909         $dbh->do(q{
21910             ALTER TABLE course_items
21911             ADD CONSTRAINT fk_course_items_homebranch
21912               FOREIGN KEY (homebranch) REFERENCES branches (branchcode)
21913               ON DELETE CASCADE ON UPDATE CASCADE
21914         });
21915     }
21916
21917     if (!column_exists('course_items', 'homebranch_enabled')) {
21918         $dbh->do(q{
21919             ALTER TABLE course_items
21920             ADD COLUMN homebranch_enabled tinyint(1) NOT NULL DEFAULT 0 AFTER homebranch
21921         });
21922     }
21923
21924     if (!column_exists('course_items', 'homebranch_storage')) {
21925         $dbh->do(q{
21926             ALTER TABLE course_items
21927             ADD COLUMN homebranch_storage VARCHAR(10) NULL DEFAULT NULL AFTER homebranch_enabled
21928         });
21929     }
21930
21931     if (!foreign_key_exists('course_items', 'fk_course_items_homebranch_storage')) {
21932         $dbh->do(q{
21933             ALTER TABLE course_items
21934             ADD CONSTRAINT fk_course_items_homebranch_storage
21935               FOREIGN KEY (homebranch_storage) REFERENCES branches (branchcode)
21936               ON DELETE CASCADE ON UPDATE CASCADE
21937         });
21938     }
21939
21940     NewVersion( $DBversion, 22630, "Add course_items.homebranch");
21941 }
21942
21943 $DBversion = '19.12.00.082';
21944 if( CheckVersion( $DBversion ) ) {
21945
21946     # get list of installed translations
21947     require C4::Languages;
21948     my @langs;
21949     my $tlangs = C4::Languages::getTranslatedLanguages('opac','bootstrap');
21950
21951     foreach my $language ( @$tlangs ) {
21952         foreach my $sublanguage ( @{$language->{'sublanguages_loop'}} ) {
21953             push @langs, $sublanguage->{'rfc4646_subtag'};
21954         }
21955     }
21956
21957     # Get any existing value from the OpacMainUserBlock system preference
21958     my ($opacmainuserblock) = $dbh->selectrow_array( q|
21959         SELECT value FROM systempreferences WHERE variable='OpacMainUserBlock';
21960     |);
21961
21962     my @detail;
21963     if( $opacmainuserblock ){
21964         foreach my $lang ( @langs ) {
21965             # If there is a value in the OpacMainUserBlock preference, insert it into opac_news
21966             $dbh->do("INSERT INTO opac_news (branchcode, lang, title, content ) VALUES (NULL, ?, '', ?)", undef, "OpacMainUserBlock_$lang", $opacmainuserblock);
21967             push @detail, "Inserting OpacMainUserBlock contents into $lang news item...";
21968         }
21969     }
21970     # Remove the OpacMainUserBlock system preference
21971     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacMainUserBlock'");
21972
21973     unshift @detail, "Move contents of OpacMainUserBlock preference to Koha news system";
21974     NewVersion( $DBversion, 23794, \@detail);
21975 }
21976
21977 $DBversion = '19.12.00.083';
21978 if( CheckVersion( $DBversion ) ) {
21979
21980     unless ( column_exists( 'authorised_value_categories', 'is_system' ) ) {
21981         $dbh->do(q|
21982             ALTER TABLE authorised_value_categories
21983             ADD COLUMN is_system TINYINT(1) DEFAULT 0 AFTER category_name
21984         |);
21985     }
21986
21987     $dbh->do(q|
21988         UPDATE authorised_value_categories
21989         SET is_system = 1
21990         WHERE category_name IN ('LOC', 'LOST', 'WITHDRAWN', 'Bsort1', 'Bsort2', 'Asort1', 'Asort2', 'SUGGEST', 'DAMAGED', 'LOST', 'BOR_NOTES', 'CCODE', 'NOT_LOAN')
21991     |);
21992
21993     $dbh->do(q|
21994         UPDATE authorised_value_categories
21995         SET is_system = 1
21996         WHERE category_name IN ('branches', 'itemtypes', 'cn_source')
21997     |);
21998
21999     NewVersion( $DBversion, 17355, "Add is_system to authorised_value_categories table");
22000 }
22001
22002 $DBversion = '19.12.00.084';
22003 if( CheckVersion( $DBversion ) ) {
22004     unless ( TableExists('advanced_editor_macros') ) {
22005         $dbh->do(q|
22006             CREATE TABLE advanced_editor_macros (
22007             id INT(11) NOT NULL AUTO_INCREMENT,
22008             name varchar(80) NOT NULL,
22009             macro longtext NULL,
22010             borrowernumber INT(11) default NULL,
22011             shared TINYINT(1) default 0,
22012             PRIMARY KEY (id),
22013             CONSTRAINT borrower_macro_fk FOREIGN KEY ( borrowernumber ) REFERENCES borrowers ( borrowernumber ) ON UPDATE CASCADE ON DELETE CASCADE
22014             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;|
22015         );
22016     }
22017     $dbh->do(q|
22018         INSERT IGNORE INTO permissions (module_bit, code, description)
22019         VALUES (9, 'create_shared_macros', 'Create public macros')
22020     |);
22021     $dbh->do(q|
22022         INSERT IGNORE INTO permissions (module_bit, code, description)
22023         VALUES (9, 'delete_shared_macros', 'Delete public macros')
22024     |);
22025
22026     NewVersion( $DBversion, 17682, "Add macros db table and permissions");
22027 }
22028
22029 $DBversion = '19.12.00.085';
22030 if( CheckVersion( $DBversion ) ) {
22031     unless ( TableExists( 'aqorders_claims' ) ) {
22032         $dbh->do(q|
22033             CREATE TABLE aqorders_claims (
22034                 id int(11) AUTO_INCREMENT,
22035                 ordernumber INT(11) NOT NULL,
22036                 claimed_on TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
22037                 PRIMARY KEY (id),
22038                 CONSTRAINT aqorders_claims_ibfk_1 FOREIGN KEY (ordernumber) REFERENCES aqorders (ordernumber) ON DELETE CASCADE ON UPDATE CASCADE
22039             ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci
22040         |);
22041
22042         my $orders = $dbh->selectall_arrayref(q|
22043             SELECT ordernumber, claims_count, claimed_date
22044             FROM aqorders
22045             WHERE claims_count > 0
22046         |, { Slice => {} });
22047         my $insert_claim_sth = $dbh->prepare(q|
22048             INSERT INTO aqorders_claims (ordernumber, claimed_on)
22049             VALUES (?,?)
22050         |);
22051
22052         for my $order ( @$orders ) {
22053             for my $claim (1..$order->{claims_count}) {
22054                 $insert_claim_sth->execute($order->{ordernumber}, $order->{claimed_on});
22055             }
22056         }
22057
22058         $dbh->do(q|ALTER TABLE aqorders DROP COLUMN claims_count, DROP COLUMN claimed_date|);
22059     }
22060
22061     NewVersion( $DBversion, 24161, "Add new join table aqorders_claims to keep track of claims");
22062 }
22063
22064 $DBversion = '19.12.00.086';
22065 if( CheckVersion( $DBversion ) ) {
22066     $dbh->do(q{
22067         INSERT IGNORE INTO export_format( profile, description, content, csv_separator, type, used_for ) VALUES
22068         ("Late orders (CSV profile)", "Default CSV export for late orders", 'Title[% separator %]Author[% separator %]Publication year[% separator %]ISBN[% separator %]Quantity[% separator %]Number of claims
22069         [% FOR order IN orders ~%]
22070         [%~ SET biblio = order.biblio ~%]
22071         "[% biblio.title %]"[% separator ~%]
22072         "[% biblio.author %]"[% separator ~%]
22073         "[% bibio.biblioitem.publicationyear %]"[% separator ~%]
22074         "[% biblio.biblioitem.isbn %]"[% separator ~%]
22075         "[% order.quantity%]"[% separator ~%]
22076         "[% order.claims.count%][% IF order.claims.count %]([% FOR c IN order.claims %][% c.claimed_on | $KohaDates %][% UNLESS loop.last %], [% END %][% END %])[% END %]"
22077         [% END %]', ",", "sql", "late_orders")
22078     });
22079
22080     NewVersion( $DBversion, 24163, "Define a default CSV profile for late orders");
22081 }
22082
22083 $DBversion = '19.12.00.087';
22084 if( CheckVersion( $DBversion ) ) {
22085     $dbh->do(q{
22086         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
22087         ('TrapHoldsOnOrder','1',NULL,'If enabled, Koha will trap holds for on order items ( notforloan < 0 )','YesNo')
22088     });
22089
22090     NewVersion( $DBversion, 25184, "Items with a negative notforloan status should not be captured for holds");
22091 }
22092
22093 $DBversion = '19.12.00.088';
22094 if( CheckVersion( $DBversion ) ) {
22095
22096     $dbh->do(q{
22097         UPDATE letter SET
22098         name = REPLACE(name, "notification on auto renewing", "Notification of automatic renewal"),
22099         title = REPLACE(title, "Auto renewals", "Automatic renewal notice"),
22100         content = REPLACE(content, "You have reach the maximum of checkouts possible.", "You have reached the maximum number of checkouts possible.")
22101         WHERE code = 'AUTO_RENEWALS';
22102     });
22103     $dbh->do(q{
22104         UPDATE letter SET
22105         content = REPLACE(content, "You have overdues.", "You have overdue items.")
22106         WHERE code = 'AUTO_RENEWALS';
22107     });
22108     $dbh->do(q{
22109         UPDATE letter SET
22110         content = REPLACE(content, "It's too late to renew this checkout.", "It's too late to renew this item.")
22111         WHERE code = 'AUTO_RENEWALS';
22112     });
22113     $dbh->do(q{
22114         UPDATE letter SET
22115         content = REPLACE(content, "You have too much unpaid fines.", "Your total unpaid fines are too high.")
22116         WHERE code = 'AUTO_RENEWALS';
22117     });
22118     $dbh->do(q{
22119         UPDATE letter SET
22120         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 as_due_date => 1 %]
22121 ")
22122         WHERE code = 'AUTO_RENEWALS';
22123     });
22124
22125     NewVersion( $DBversion, 24378, "Fix some grammatical errors in default auto renewal notice");
22126 }
22127
22128 $DBversion = '19.12.00.089';
22129 if( CheckVersion( $DBversion ) ) {
22130
22131     # Migrate LOST_RETURNED to LOST_FOUND
22132     $dbh->do(qq{
22133         UPDATE
22134           accountlines
22135         SET
22136           credit_type_code = 'LOST_FOUND'
22137         WHERE
22138           credit_type_code = 'LOST_RETURNED'
22139     });
22140
22141     # Drop LOST_RETURNED credit type
22142     $dbh->do(qq{
22143         DELETE FROM account_credit_types WHERE code = 'LOST_RETURNED'
22144     });
22145
22146     NewVersion( $DBversion, 25389, "Catch errant cases of LOST_RETURNED");
22147 }
22148
22149 $DBversion = '19.12.00.090';
22150 if ( CheckVersion($DBversion) ) {
22151
22152     $dbh->do(
22153         qq{
22154           INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
22155           ('UseIssueDesks','0','','Use issue desks with circulation.','YesNo')
22156       }
22157     );
22158
22159     NewVersion( $DBversion, 13881, "Add issue desks system preference");
22160 }
22161
22162 $DBversion = '19.12.00.091';
22163 if ( CheckVersion($DBversion) ) {
22164
22165     $dbh->do(qq{
22166         UPDATE systempreferences SET variable = 'UseCirculationDesks' WHERE variable = 'UseIssueDesks'
22167     });
22168
22169     NewVersion( $DBversion, 13881, "Correction to preference terminology");
22170 }
22171
22172 $DBversion = '20.05.00.000';
22173 if( CheckVersion( $DBversion ) ) {
22174     NewVersion( $DBversion, undef, '20.05.00 alpha release' );
22175 }
22176
22177 $DBversion = '20.06.00.000';
22178 if( CheckVersion( $DBversion ) ) {
22179     NewVersion( $DBversion, undef, 'All our codebase are belong to everybody' );
22180 }
22181
22182 $DBversion = '20.06.00.001';
22183 if( CheckVersion( $DBversion ) ) {
22184     for my $f (qw( streetnumber streettype zipcode mobile B_streetnumber B_streettype B_zipcode ) ) {
22185         $dbh->do(qq|
22186             ALTER TABLE borrowers MODIFY $f TINYTEXT DEFAULT NULL
22187         |);
22188         $dbh->do(qq|
22189             ALTER TABLE deletedborrowers MODIFY $f TINYTEXT DEFAULT NULL
22190         |);
22191     }
22192     for my $f ( qw( B_address altcontactfirstname altcontactsurname altcontactaddress1 altcontactaddress2 altcontactaddress3 altcontactzipcode altcontactphone ) ) {
22193         $dbh->do(qq|
22194             ALTER TABLE borrowers MODIFY $f MEDIUMTEXT DEFAULT NULL
22195         |);
22196         $dbh->do(qq|
22197             ALTER TABLE deletedborrowers MODIFY $f MEDIUMTEXT DEFAULT NULL
22198         |);
22199     }
22200
22201     NewVersion( $DBversion, 24986, "Switch borrowers address related fields to TINYTEXT or MEDIUMTEXT");
22202 }
22203
22204 $DBversion = '20.06.00.002';
22205 if( CheckVersion( $DBversion ) ) {
22206     $dbh->do(q{
22207         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
22208         ('SkipHoldTrapOnNotForLoanValue','',NULL,'If set, Koha will never trap items for hold with this notforloan value','Integer')
22209     });
22210
22211     NewVersion( $DBversion, 25184, "Items with a negative notforloan status should not be captured for holds");
22212 }
22213
22214 $DBversion = '20.06.00.003';
22215 if( CheckVersion( $DBversion ) ) {
22216     unless ( TableExists( 'tables_settings' ) ) {
22217         $dbh->do(q|
22218             CREATE TABLE tables_settings (
22219                 module varchar(255) NOT NULL,
22220                 page varchar(255) NOT NULL,
22221                 tablename varchar(255) NOT NULL,
22222                 default_display_length smallint(6) NOT NULL DEFAULT 20,
22223                 default_sort_order varchar(255),
22224                 PRIMARY KEY(module (191), page (191), tablename (191) )
22225             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
22226         |);
22227     }
22228
22229     NewVersion( $DBversion, 24156, "Add new table tables_settings" );
22230 }
22231
22232 $DBversion = '20.06.00.004';
22233 if( CheckVersion( $DBversion ) ) {
22234     $dbh->do("
22235         DELETE FROM circulation_rules WHERE rule_name='holdallowed' AND rule_value='';
22236     ");
22237     NewVersion( $DBversion, 25851, "Remove holdallowed rule if value is an empty string");
22238 }
22239
22240 $DBversion = '20.06.00.005';
22241 if( CheckVersion( $DBversion ) ) {
22242     $dbh->do( "UPDATE borrowers SET login_attempts=0 WHERE login_attempts IS NULL" );
22243     $dbh->do( "ALTER TABLE borrowers MODIFY COLUMN login_attempts int(4) NOT NULL DEFAULT 0" );
22244     $dbh->do( "UPDATE deletedborrowers SET login_attempts=0 WHERE login_attempts IS NULL" );
22245     $dbh->do( "ALTER TABLE deletedborrowers MODIFY COLUMN login_attempts int(4) NOT NULL DEFAULT 0" );
22246     NewVersion( $DBversion, 24379, "Set login_attempts NOT NULL" );
22247 }
22248
22249 $DBversion = '20.06.00.006';
22250 if( CheckVersion( $DBversion ) ) {
22251     unless( TableExists( 'pseudonymized_transactions' ) ) {
22252         $dbh->do(q|
22253             CREATE TABLE `pseudonymized_transactions` (
22254               `id` INT(11) NOT NULL AUTO_INCREMENT,
22255               `hashed_borrowernumber` VARCHAR(60) NOT NULL,
22256               `has_cardnumber` TINYINT(1) NOT NULL DEFAULT 0,
22257               `title` LONGTEXT,
22258               `city` LONGTEXT,
22259               `state` MEDIUMTEXT default NULL,
22260               `zipcode` varchar(25) default NULL,
22261               `country` MEDIUMTEXT,
22262               `branchcode` varchar(10) NOT NULL default '',
22263               `categorycode` varchar(10) NOT NULL default '',
22264               `dateenrolled` date default NULL,
22265               `sex` varchar(1) default NULL,
22266               `sort1` varchar(80) default NULL,
22267               `sort2` varchar(80) default NULL,
22268               `datetime` datetime default NULL,
22269               `transaction_branchcode` varchar(10) default NULL,
22270               `transaction_type` varchar(16) default NULL,
22271               `itemnumber` int(11) default NULL,
22272               `itemtype` varchar(10) default NULL,
22273               `holdingbranch` varchar(10) default null,
22274               `homebranch` varchar(10) default null,
22275               `location` varchar(80) default NULL,
22276               `itemcallnumber` varchar(255) default NULL,
22277               `ccode` varchar(80) default NULL,
22278               PRIMARY KEY (`id`),
22279               CONSTRAINT `pseudonymized_transactions_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`),
22280               CONSTRAINT `pseudonymized_transactions_borrowers_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`),
22281               CONSTRAINT `pseudonymized_transactions_borrowers_ibfk_3` FOREIGN KEY (`transaction_branchcode`) REFERENCES `branches` (`branchcode`)
22282             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
22283         |);
22284     }
22285
22286     $dbh->do(q|
22287         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
22288         VALUES ('Pseudonymization','0',NULL,'If enabled patrons and transactions will be copied in a separate table for statistics purpose','YesNo')
22289     |);
22290     $dbh->do(q|
22291         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
22292         VALUES ('PseudonymizationPatronFields','','title,city,state,zipcode,country,branchcode,categorycode,dateenrolled,sex,sort1,sort2','Patron fields to copy to the pseudonymized_transactions table','multiple')
22293     |);
22294     $dbh->do(q|
22295         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
22296         VALUES ('PseudonymizationTransactionFields','','datetime,transaction_branchcode,transaction_type,itemnumber,itemtype,holdingbranch,homebranch,location,itemcallnumber,ccode','Transaction fields to copy to the pseudonymized_transactions table','multiple')
22297     |);
22298
22299     unless( TableExists( 'pseudonymized_borrower_attributes' ) ) {
22300         $dbh->do(q|
22301             CREATE TABLE pseudonymized_borrower_attributes (
22302               `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, -- Row id field
22303               `transaction_id` int(11) NOT NULL,
22304               `code` varchar(10) NOT NULL,
22305               `attribute` varchar(255) default NULL,
22306               CONSTRAINT `pseudonymized_borrower_attributes_ibfk_1` FOREIGN KEY (`transaction_id`) REFERENCES `pseudonymized_transactions` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
22307               CONSTRAINT `anonymized_borrower_attributes_ibfk_2` FOREIGN KEY (`code`) REFERENCES `borrower_attribute_types` (`code`) ON DELETE CASCADE ON UPDATE CASCADE
22308             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
22309         |);
22310     }
22311
22312     unless( column_exists('borrower_attribute_types', 'keep_for_pseudonymization') ) {
22313         $dbh->do(q|
22314             ALTER TABLE borrower_attribute_types ADD COLUMN `keep_for_pseudonymization` TINYINT(1) NOT NULL DEFAULT 0 AFTER `class`
22315         |);
22316     }
22317
22318     NewVersion( $DBversion, 24151, "Add pseudonymized_transactions tables and sysprefs for Pseudonymization" );
22319 }
22320
22321 $DBversion = '20.06.00.007';
22322 if( CheckVersion( $DBversion ) ) {
22323     if( !column_exists( 'borrower_attribute_types', 'mandatory' ) ) {
22324         $dbh->do(q|
22325             ALTER TABLE borrower_attribute_types
22326             ADD COLUMN mandatory TINYINT(1) NOT NULL DEFAULT 0
22327             AFTER keep_for_pseudonymization
22328         |);
22329     }
22330
22331     NewVersion( $DBversion, 22844, "Add borrower_attribute_types.mandatory" );
22332 }
22333
22334 $DBversion = '20.06.00.008';
22335 if( CheckVersion( $DBversion ) ) {
22336     $dbh->do( "UPDATE itemtypes SET imageurl = REPLACE (imageurl, '.gif', '.png') WHERE imageurl LIKE 'bridge/%'" );
22337
22338     NewVersion( $DBversion, 23148, "Replace Bridge icons with transparent PNG files" );
22339 }
22340
22341 $DBversion = '20.06.00.009';
22342 if( CheckVersion( $DBversion ) ) {
22343     $dbh->do( q{
22344             INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
22345             VALUES ('ILLHiddenRequestStatuses',NULL,NULL,'ILL statuses that are considered finished and should not be displayed in the ILL module','multiple')
22346     });
22347
22348     NewVersion( $DBversion, 23391, "Hide finished ILL requests" );
22349 }
22350
22351 $DBversion = '20.06.00.010';
22352 if( CheckVersion( $DBversion ) ) {
22353     $dbh->do(q{
22354         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
22355         ('NoRefundOnLostReturnedItemsAge','','','Do not refund lost item fees if item is lost for more than this number of days','Integer')
22356     });
22357
22358     NewVersion( $DBversion, 20815, "Add NoRefundOnLostReturnedItemsAge system preference" );
22359 }
22360
22361 $DBversion = '20.06.00.011';
22362 if( CheckVersion( $DBversion ) ) {
22363     unless( column_exists( 'export_format', 'staff_only' ) ) {
22364         $dbh->do(q|
22365             ALTER TABLE export_format
22366                 ADD staff_only TINYINT(1) NOT NULL DEFAULT 0 AFTER used_for,
22367                 ADD KEY `staff_only_idx` (`staff_only`);
22368         |);
22369     }
22370
22371     unless ( index_exists( 'export_format', 'used_for_idx' ) ) {
22372         $dbh->do(q|
22373             ALTER TABLE export_format
22374                 ADD KEY `used_for_idx` (`used_for` (191));
22375         |);
22376     }
22377
22378     NewVersion( $DBversion, 5087, "Add export_format.staff_only" );
22379 }
22380
22381 $DBversion = '20.06.00.012';
22382 if( CheckVersion( $DBversion ) ) {
22383
22384     # get list of installed translations
22385     require C4::Languages;
22386     my @langs;
22387     my $tlangs = C4::Languages::getTranslatedLanguages('opac','bootstrap');
22388
22389     foreach my $language ( @$tlangs ) {
22390         foreach my $sublanguage ( @{$language->{'sublanguages_loop'}} ) {
22391             push @langs, $sublanguage->{'rfc4646_subtag'};
22392         }
22393     }
22394
22395     # Get any existing value from the opaccredits system preference
22396     my ($opaccredits) = $dbh->selectrow_array( q|
22397         SELECT value FROM systempreferences WHERE variable='opaccredits';
22398     |);
22399     if( $opaccredits ){
22400         foreach my $lang ( @langs ) {
22401             # If there is a value in the opaccredits preference, insert it into opac_news
22402             $dbh->do("INSERT IGNORE INTO opac_news (branchcode, lang, title, content ) VALUES (NULL, ?, '', ?)", undef, "opaccredits_$lang", $opaccredits);
22403         }
22404     }
22405     # Remove the opaccredits system preference
22406     $dbh->do("DELETE FROM systempreferences WHERE variable='opaccredits'");
22407
22408     NewVersion( $DBversion, 23795, "Convert OpacCredits system preference to news block" );
22409 }
22410
22411 $DBversion = '20.06.00.013';
22412 if( CheckVersion( $DBversion ) ) {
22413
22414     # get list of installed translations
22415     require C4::Languages;
22416     my @langs;
22417     my $tlangs = C4::Languages::getTranslatedLanguages('opac','bootstrap');
22418
22419     foreach my $language ( @$tlangs ) {
22420         foreach my $sublanguage ( @{$language->{'sublanguages_loop'}} ) {
22421             push @langs, $sublanguage->{'rfc4646_subtag'};
22422         }
22423     }
22424
22425     # Get any existing value from the OpacCustomSearch system preference
22426     my ($OpacCustomSearch) = $dbh->selectrow_array( q|
22427         SELECT value FROM systempreferences WHERE variable='OpacCustomSearch';
22428     |);
22429     if( $OpacCustomSearch ){
22430         foreach my $lang ( @langs ) {
22431             # If there is a value in the OpacCustomSearch preference, insert it into opac_news
22432             $dbh->do("INSERT INTO opac_news (branchcode, lang, title, content ) VALUES (NULL, ?, '', ?)", undef, "OpacCustomSearch_$lang", $OpacCustomSearch);
22433         }
22434     }
22435     # Remove the OpacCustomSearch system preference
22436     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacCustomSearch'");
22437
22438     NewVersion( $DBversion, 23795, "Convert OpacCustomSearch system preference to news block" );
22439 }
22440
22441 $DBversion = '20.06.00.014';
22442 if( CheckVersion( $DBversion ) ) {
22443
22444     $dbh->do( "ALTER TABLE opac_news CHANGE lang lang VARCHAR(50) NOT NULL DEFAULT ''" );
22445
22446     NewVersion( $DBversion, 23797, "Extend the opac_news lang column to accommodate longer values" );
22447 }
22448
22449 $DBversion = '20.06.00.015';
22450 if( CheckVersion( $DBversion ) ) {
22451
22452     # get list of installed translations
22453     require C4::Languages;
22454     my @langs;
22455     my $tlangs = C4::Languages::getTranslatedLanguages('opac','bootstrap');
22456
22457     foreach my $language ( @$tlangs ) {
22458         foreach my $sublanguage ( @{$language->{'sublanguages_loop'}} ) {
22459             push @langs, $sublanguage->{'rfc4646_subtag'};
22460         }
22461     }
22462
22463     # Get any existing value from the OpacLoginInstructions system preference
22464     my ($opaclogininstructions) = $dbh->selectrow_array( q|
22465         SELECT value FROM systempreferences WHERE variable='OpacLoginInstructions';
22466     |);
22467     if( $opaclogininstructions ){
22468         foreach my $lang ( @langs ) {
22469             # If there is a value in the OpacLoginInstructions preference, insert it into opac_news
22470             $dbh->do("INSERT INTO opac_news (branchcode, lang, title, content ) VALUES (NULL, ?, '', ?)", undef, "OpacLoginInstructions_$lang", $opaclogininstructions);
22471         }
22472     }
22473     # Remove the OpacLoginInstructions system preference
22474     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacLoginInstructions'");
22475
22476     NewVersion( $DBversion, 23797, "Convert OpacLoginInstructions system preference to news block" );
22477 }
22478
22479 $DBversion = '20.06.00.016';
22480 if( CheckVersion( $DBversion ) ) {
22481
22482     unless ( column_exists('branchtransfers', 'daterequested') ) {
22483         $dbh->do(
22484             qq{
22485                 ALTER TABLE branchtransfers
22486                 ADD
22487                   `daterequested` timestamp NOT NULL default CURRENT_TIMESTAMP
22488                 AFTER
22489                   `itemnumber`
22490               }
22491         );
22492     }
22493
22494     NewVersion( $DBversion, 23092, "Add 'daterequested' field to transfers table" );
22495 }
22496
22497 $DBversion = '20.06.00.017';
22498 if( CheckVersion( $DBversion ) ) {
22499     $dbh->do( "UPDATE systempreferences SET variable='NotesToHide' WHERE variable = 'NotesBlacklist'" );
22500     NewVersion( $DBversion, 25709, "Rename systempreference to NotesToHide");
22501 }
22502
22503 $DBversion = '20.06.00.018';
22504 if( CheckVersion( $DBversion ) ) {
22505     $dbh->do(q|
22506         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
22507         (11, 'reopen_closed_invoices', 'Reopen closed invoices')
22508     |);
22509
22510     $dbh->do(q|
22511         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
22512         (11, 'edit_invoices', 'Edit invoices')
22513     |);
22514
22515     $dbh->do(q|
22516         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
22517         (11, 'delete_baskets', 'Delete baskets')
22518     |);
22519
22520     $dbh->do(q|
22521         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
22522         (11, 'delete_invoices', 'Delete invoices')
22523     |);
22524
22525     $dbh->do(q|
22526         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
22527         (11, 'merge_invoices', 'Merge invoices')
22528     |);
22529
22530     NewVersion( $DBversion, 24157, "Add new permissions reopen_closed_invoices, edit_invoices, delete_invoices, merge_invoices, delete_basket");
22531 }
22532
22533 $DBversion = '20.06.00.019';
22534 if( CheckVersion( $DBversion ) ) {
22535     $dbh->do( "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('NewsToolEditor','tinymce', 'Choose tool for editing News','tinymce|codemirror','Choice')" );
22536
22537     NewVersion( $DBversion, 22660, "Adds NewsToolEditor system preference");
22538 }
22539
22540 $DBversion = '20.06.00.020';
22541 if( CheckVersion( $DBversion ) ) {
22542     # Remove from the systempreferences table
22543     $dbh->do("DELETE FROM systempreferences WHERE variable = 'GoogleIndicTransliteration'");
22544
22545     NewVersion( $DBversion, 26070, "Remove references to deprecated Google Transliterate API");
22546 }
22547
22548 $DBversion = '20.06.00.021';
22549 if( CheckVersion( $DBversion ) ) {
22550     $dbh->do(q{
22551         UPDATE systempreferences SET options = "callnum|ccode|location|library"
22552         WHERE variable = "OpacItemLocation"
22553     });
22554     NewVersion( $DBversion, 25871, "Add library option to OpacItemLocation");
22555 }
22556
22557 $DBversion = '20.06.00.022';
22558 if( CheckVersion( $DBversion ) ) {
22559     unless ( column_exists('itemtypes', 'parent_type') ) {
22560         $dbh->do(q{
22561             ALTER TABLE itemtypes
22562                 ADD COLUMN parent_type VARCHAR(10) NULL DEFAULT NULL
22563                 AFTER itemtype;
22564
22565         });
22566     }
22567     unless ( foreign_key_exists( 'itemtypes', 'itemtypes_ibfk_1') ){
22568         $dbh->do(q{
22569             ALTER TABLE itemtypes
22570             ADD CONSTRAINT itemtypes_ibfk_1
22571             FOREIGN KEY (parent_type) REFERENCES itemtypes (itemtype)
22572         });
22573     }
22574
22575     NewVersion( $DBversion, 21946, "Add parent type to itemtypes" );
22576 }
22577
22578 $DBversion = '20.06.00.023';
22579 if( CheckVersion( $DBversion ) ) {
22580
22581     my ( $QuoteOfTheDay ) = $dbh->selectrow_array(q|
22582         SELECT value FROM systempreferences WHERE variable='QuoteOfTheDay'
22583     |);
22584     my $options = $QuoteOfTheDay ? 'opac' : '';
22585     $dbh->do( q|
22586         UPDATE systempreferences
22587         SET value = ?,
22588             options = 'intranet,opac',
22589             explanation = 'Enable or disable display of Quote of the Day on the OPAC and staff interface home page',
22590             type = 'multiple'
22591         WHERE variable = 'QuoteOfTheDay'
22592     |, undef, $options );
22593
22594     NewVersion( $DBversion, 16371, "Quote of the Day (QOTD) for the staff interface " );
22595 }
22596
22597 $DBversion = '20.06.00.024';
22598 if( CheckVersion( $DBversion ) ) {
22599
22600     $dbh->do( "UPDATE marc_subfield_structure SET liblibrarian = 'Home library' WHERE liblibrarian = 'Permanent location'
22601         AND tagfield = 952 and tagsubfield = 'a'" );
22602     $dbh->do( "UPDATE marc_subfield_structure SET libopac = 'Home library' WHERE libopac = 'Permanent location'
22603         AND tagfield = 952 and tagsubfield = 'a'" );
22604     $dbh->do( "UPDATE marc_subfield_structure SET liblibrarian = 'Current library' WHERE liblibrarian = 'Current location'
22605         AND tagfield = 952 and tagsubfield = 'b'" );
22606     $dbh->do( "UPDATE marc_subfield_structure SET libopac = 'Current library' WHERE libopac = 'Current location'
22607         AND tagfield = 952 and tagsubfield = 'b'" );
22608
22609     NewVersion( $DBversion, 25867, "Update subfield descriptions for 952\$a and 952\$b");
22610 }
22611
22612 $DBversion = '20.06.00.025';
22613 if( CheckVersion( $DBversion ) ) {
22614
22615     $dbh->do( q{
22616         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
22617         ('PatronDuplicateMatchingAddFields','surname|firstname|dateofbirth', NULL,'A list of fields separated by "|" to deduplicate patrons when created','Free')
22618     });
22619
22620     NewVersion( $DBversion, 6725, "Adds PatronDuplicateMatchingAddFields system preference");
22621 }
22622
22623 $DBversion = '20.06.00.026';
22624 if (CheckVersion($DBversion)) {
22625     unless (column_exists('accountlines', 'credit_number')) {
22626         $dbh->do('ALTER TABLE accountlines ADD COLUMN credit_number VARCHAR(20) NULL DEFAULT NULL COMMENT "autogenerated number for credits" AFTER debit_type_code');
22627     }
22628
22629     unless (column_exists('account_credit_types', 'credit_number_enabled')) {
22630         $dbh->do(q{
22631             ALTER TABLE account_credit_types
22632             ADD COLUMN credit_number_enabled TINYINT(1) NOT NULL DEFAULT 0
22633                 COMMENT "Is autogeneration of credit number enabled for this credit type"
22634                 AFTER can_be_added_manually
22635         });
22636     }
22637
22638     $dbh->do('INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES(?, ?, ?, ?, ?)', undef, 'AutoCreditNumber', '', '', 'Automatically generate a number for account credits', 'Choice');
22639
22640     NewVersion( $DBversion, 19036, "Add accountlines.credit_number, account_credit_types.credit_number_enabled and syspref AutoCreditNumber" );
22641 }
22642
22643 $DBversion = '20.06.00.027';
22644 if( CheckVersion( $DBversion ) ) {
22645     $dbh->do( "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('BiblioItemtypeInfo', '0','Control whether biblio level itemtype image displays','0','YesNo')" );
22646
22647     NewVersion( $DBversion, 8732, 'Add new BiblioItemtypeInfo to system preferences' );
22648 }
22649
22650 $DBversion = '20.06.00.028';
22651 if( CheckVersion( $DBversion ) ) {
22652     $dbh->do(q{
22653         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
22654         ('DefaultLongOverdueSkipLostStatuses', '', NULL, 'Skip these lost statuses by default in longoverdue.pl', 'Free')
22655     });
22656
22657     NewVersion( $DBversion, 25958, "Allow LongOverdue cron to exclude specified lost values");
22658 }
22659
22660 $DBversion = '20.06.00.029';
22661 if ( CheckVersion( $DBversion ) ) {
22662     $dbh->do(q{
22663         INSERT IGNORE INTO authorised_value_categories( category_name, is_system ) VALUES ('HOLD_CANCELLATION', 0);
22664     });
22665
22666     if ( !column_exists( 'reserves', 'cancellation_reason' ) ) {
22667         $dbh->do(q{
22668             ALTER TABLE reserves ADD COLUMN `cancellation_reason` varchar(80) default NULL AFTER cancellationdate;
22669         });
22670     }
22671
22672     if ( !column_exists( 'old_reserves', 'cancellation_reason' ) ) {
22673         $dbh->do(q{
22674             ALTER TABLE old_reserves ADD COLUMN `cancellation_reason` varchar(80) default NULL AFTER cancellationdate;
22675         });
22676     }
22677
22678     NewVersion( $DBversion, 25534, "Add ability to send an email specifying a reason when canceling a hold");
22679 }
22680
22681 $DBversion = '20.06.00.030';
22682 if ( CheckVersion( $DBversion ) ) {
22683
22684     $dbh->do(q{
22685         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type`) VALUES
22686         ('AutoApprovePatronProfileSettings', '0', '', 'Automatically approve patron profile changes from the OPAC.', 'YesNo');
22687     });
22688
22689     NewVersion( $DBversion, 20057, "Add new system preference 'AutoApprovePatronProfileSettings'");
22690 }
22691
22692 $DBversion = '20.06.00.031';
22693 if( CheckVersion( $DBversion ) ) {
22694
22695     if( !column_exists( 'reserves', 'non_priority' ) ) {
22696         $dbh->do("ALTER TABLE reserves ADD COLUMN `non_priority` tinyint(1) NOT NULL DEFAULT 0 AFTER `item_level_hold`");
22697     }
22698
22699     if( !column_exists( 'old_reserves', 'non_priority' ) ) {
22700         $dbh->do("ALTER TABLE old_reserves ADD COLUMN `non_priority` tinyint(1) NOT NULL DEFAULT 0 AFTER `item_level_hold`");
22701     }
22702
22703     NewVersion( $DBversion, 22789, "Add non_priority column on reserves and old_reserves tables");
22704 }
22705
22706 $DBversion = '20.06.00.032';
22707 if( CheckVersion( $DBversion ) ) {
22708     if( !column_exists( 'items', 'exclude_from_local_holds_priority' ) ) {
22709         $dbh->do(q{
22710             ALTER TABLE `items` ADD COLUMN `exclude_from_local_holds_priority` tinyint(1) default NULL AFTER `new_status`
22711         });
22712     }
22713
22714     if( !column_exists( 'deleteditems', 'exclude_from_local_holds_priority' ) ) {
22715         $dbh->do(q{
22716             ALTER TABLE `deleteditems` ADD COLUMN `exclude_from_local_holds_priority` tinyint(1) default NULL AFTER `new_status`
22717         });
22718     }
22719
22720     if( !column_exists( 'categories', 'exclude_from_local_holds_priority' ) ) {
22721         $dbh->do(q{
22722             ALTER TABLE `categories` ADD COLUMN `exclude_from_local_holds_priority` tinyint(1) default NULL AFTER `change_password`
22723         });
22724     }
22725     NewVersion( $DBversion, 19889, "Add exclude_from_local_holds_priority column to items, deleteditems and categories tables");
22726 }
22727
22728 $DBversion = '20.06.00.033';
22729 if( CheckVersion( $DBversion ) ) {
22730     if( column_exists( 'opac_news', 'timestamp' ) ) {
22731         $dbh->do(q|
22732             ALTER TABLE opac_news
22733             CHANGE COLUMN timestamp published_on date DEFAULT NULL
22734         |);
22735     }
22736     if( !column_exists( 'opac_news', 'updated_on' ) ) {
22737         $dbh->do(q|
22738             ALTER TABLE opac_news
22739             ADD COLUMN updated_on timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER published_on
22740         |);
22741     }
22742
22743     $dbh->do(q|
22744         UPDATE letter
22745         SET content = REPLACE(content,?,?)
22746         WHERE content LIKE ?
22747     |, undef, 'opac_news.timestamp', 'opac_news.published_on', '%opac_news.timestamp%' );
22748
22749     NewVersion( $DBversion, 21066, ["Rename column opac_news.timestamp with published_on", "Add new column opac_news.updated_on", "Replace timestamp references in letters table"] );
22750 }
22751
22752 $DBversion = '20.06.00.034';
22753 if( CheckVersion( $DBversion ) ) {
22754     $dbh->do(q|
22755         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type)
22756         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')
22757     |);
22758
22759     NewVersion( $DBversion, 24197, "Add new system preference 'AddressForFailedOverdueNotices'" );
22760 }
22761
22762 $DBversion = '20.06.00.035';
22763 if ( CheckVersion( $DBversion ) ) {
22764     $dbh->do(q{
22765         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
22766         ('EdifactInvoiceImport', 'automatic', 'automatic|manual', "If on, don't auto-import EDI invoices, just keep them in the database with the status 'new'", 'Choice')
22767     });
22768
22769     NewVersion( $DBversion, 23682, "Add new system preference 'EdifactInvoiceImport'" );
22770 }
22771
22772 $DBversion = '20.06.00.036';
22773 if( CheckVersion( $DBversion ) ) {
22774     # Fix the markup in the OPACSearchForTitleIn system preference
22775     $dbh->do("UPDATE systempreferences SET VALUE = replace( value, '</li>', ''), value = REPLACE( value, '<li>', '') WHERE VARIABLE = 'OPACSearchForTitleIn';");
22776
22777     NewVersion( $DBversion, 20168, "Update OPACSearchForTitleIn to work with Bootstrap 4");
22778 }
22779
22780 $DBversion = '20.06.00.037';
22781 if( CheckVersion( $DBversion ) ) {
22782     if( !column_exists( 'categories', 'min_password_length' ) ) {
22783         $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");
22784     }
22785     if( !column_exists( 'categories', 'require_strong_password' ) ) {
22786         $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");
22787     }
22788
22789     NewVersion( $DBversion, 23816, "Add min_password_length and require_strong_password columns in categories table");
22790 }
22791
22792 $DBversion = '20.06.00.038';
22793 if( CheckVersion( $DBversion ) ) {
22794     $dbh->do( "ALTER TABLE `search_field` MODIFY COLUMN `type` enum('','string','date','number','boolean','sum','isbn','stdno','year') NOT NULL" );
22795     $dbh->do( "UPDATE `search_field` SET type = 'year' WHERE name = 'date-of-publication'" );
22796
22797     NewVersion( $DBversion, 24807, "Add 'year' type to improve sorting behaviour" );
22798 }
22799
22800 $DBversion = '20.06.00.039';
22801 if( CheckVersion( $DBversion ) ) {
22802
22803     if( !column_exists( 'hold_fill_targets', 'reserve_id' ) ) {
22804         $dbh->do( "ALTER TABLE hold_fill_targets ADD COLUMN reserve_id int(11) DEFAULT NULL AFTER item_level_request" );
22805     }
22806
22807     NewVersion( $DBversion, 18958, "Add reserve_id to hold_fill_targets");
22808 }
22809
22810 $DBversion = '20.06.00.040';
22811 if( CheckVersion( $DBversion ) ) {
22812     $dbh->do( "INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES ('OpacMetaDescription','','','This description will show in search engine results (160 characters).','Textarea');" );
22813
22814     NewVersion( $DBversion, 26454, "Add system preference to set meta description for the OPAC");
22815 }
22816
22817 $DBversion = '20.06.00.041';
22818 if ( CheckVersion($DBversion) ) {
22819
22820     if ( column_exists( 'items', 'paidfor' ) ) {
22821         my ($count) = $dbh->selectrow_array(
22822             q|
22823                 SELECT COUNT(*)
22824                 FROM items
22825                 WHERE paidfor IS NOT NULL AND paidfor <> ""
22826             |
22827         );
22828         if ($count) {
22829             warn "Warning - Cannot remove column items.paidfor. At least one value exists";
22830         }
22831         else {
22832             $dbh->do(q|ALTER TABLE items DROP COLUMN paidfor|);
22833             $dbh->do(q|UPDATE marc_subfield_structure SET kohafield = '' WHERE kohafield = 'items.paidfor'|);
22834         }
22835     }
22836
22837     if ( column_exists( 'deleteditems', 'paidfor' ) ) {
22838         my ($count) = $dbh->selectrow_array(
22839             q|
22840                 SELECT COUNT(*)
22841                 FROM deleteditems
22842                 WHERE paidfor IS NOT NULL AND paidfor <> ""
22843             |
22844         );
22845         if ($count) {
22846             warn "Warning - Cannot remove column deleteditems.paidfor. At least one value exists";
22847         }
22848         else {
22849             $dbh->do(q|ALTER TABLE deleteditems DROP COLUMN paidfor|);
22850         }
22851     }
22852
22853     NewVersion( $DBversion, 26268, "Remove items.paidfor field" );
22854 }
22855
22856 $DBversion = '20.06.00.042';
22857 if( CheckVersion( $DBversion ) ) {
22858     unless ( column_exists('letter', 'updated_on') ) {
22859         $dbh->do(q|
22860             ALTER TABLE letter ADD COLUMN updated_on timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER lang
22861         |);
22862     }
22863
22864     NewVersion( $DBversion, 25776, "Add letter.updated_on");
22865 }
22866
22867 $DBversion = '20.06.00.043';
22868 if( CheckVersion( $DBversion ) ) {
22869     $dbh->do(q{
22870         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')
22871     });
22872
22873     NewVersion( $DBversion, 25261, "Add CircConfirmItemParts syspref");
22874 }
22875
22876 $DBversion = '20.06.00.044';
22877 if( CheckVersion( $DBversion ) ) {
22878
22879     unless (TableExists('smtp_servers')) {
22880
22881         # Create the table
22882         $dbh->do(q{
22883             CREATE TABLE `smtp_servers` (
22884                 `id` INT(11) NOT NULL AUTO_INCREMENT,
22885                 `name` VARCHAR(80) NOT NULL,
22886                 `host` VARCHAR(80) NOT NULL DEFAULT 'localhost',
22887                 `port` INT(11) NOT NULL DEFAULT 25,
22888                 `timeout` INT(11) NOT NULL DEFAULT 120,
22889                 `ssl_mode` ENUM('disabled', 'ssl', 'starttls') NOT NULL,
22890                 `user_name` VARCHAR(80) NULL DEFAULT NULL,
22891                 `password` VARCHAR(80) NULL DEFAULT NULL,
22892                 `debug` TINYINT(1) NOT NULL DEFAULT 0,
22893                 PRIMARY KEY (`id`),
22894                 KEY `host_idx` (`host`)
22895             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
22896         });
22897     }
22898
22899     unless (TableExists('library_smtp_servers')) {
22900         $dbh->do(q{
22901             CREATE TABLE `library_smtp_servers` (
22902                 `id` INT(11) NOT NULL AUTO_INCREMENT,
22903                 `library_id` VARCHAR(10) NOT NULL,
22904                 `smtp_server_id` INT(11) NOT NULL,
22905                 PRIMARY KEY (`id`),
22906                 UNIQUE KEY `library_id_idx` (`library_id`),
22907                 KEY `smtp_server_id_idx` (`smtp_server_id`),
22908                 CONSTRAINT `library_smtp_servers_library_fk` FOREIGN KEY (`library_id`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
22909                 CONSTRAINT `library_smtp_servers_smtp_servers_fk` FOREIGN KEY (`smtp_server_id`) REFERENCES `smtp_servers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
22910             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
22911         });
22912     }
22913
22914     $dbh->do(q{
22915         INSERT IGNORE INTO permissions
22916             (module_bit, code, description)
22917         VALUES ( 3, 'manage_smtp_servers', 'Manage SMTP servers configuration');
22918     });
22919
22920     NewVersion( $DBversion, 22343, "Add SMTP configuration options");
22921 }
22922
22923 $DBversion = '20.06.00.045';
22924 if( CheckVersion( $DBversion ) ) {
22925
22926     unless ( TableExists('background_jobs') ) {
22927         $dbh->do(q|
22928             CREATE TABLE background_jobs (
22929                 id INT(11) NOT NULL AUTO_INCREMENT,
22930                 status VARCHAR(32),
22931                 progress INT(11),
22932                 size INT(11),
22933                 borrowernumber INT(11),
22934                 type VARCHAR(64),
22935                 data TEXT,
22936                 enqueued_on DATETIME DEFAULT NULL,
22937                 started_on DATETIME DEFAULT NULL,
22938                 ended_on DATETIME DEFAULT NULL,
22939                 PRIMARY KEY (id)
22940             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
22941         |);
22942     }
22943
22944     $dbh->do(qq{
22945         INSERT IGNORE permissions (module_bit, code, description)
22946         VALUES
22947         (3, 'manage_background_jobs', 'Manage background jobs')
22948     });
22949
22950     NewVersion( $DBversion, 22417, "Add new table background_jobs");
22951 }
22952
22953 $DBversion = '20.06.00.046';
22954 if( CheckVersion( $DBversion ) ) {
22955     unless ( foreign_key_exists( 'alert', 'alert_ibfk_1' ) ) {
22956         $dbh->do(q|
22957             DELETE a FROM alert a
22958             LEFT JOIN borrowers b ON a.borrowernumber=b.borrowernumber
22959             WHERE b.borrowernumber IS NULL
22960         |);
22961         $dbh->do(q|
22962             ALTER TABLE alert
22963             ADD CONSTRAINT alert_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON UPDATE CASCADE ON DELETE CASCADE
22964         |);
22965     }
22966     NewVersion( $DBversion, 13535, "Add FK constraint on borrowernumber to alert table" );
22967 }
22968
22969 $DBversion = '20.06.00.047';
22970 if ( CheckVersion($DBversion) ) {
22971
22972     #Get value from AllowPurchaseSuggestionBranchChoice system preference
22973     my ($allowpurchasesuggestionbranchchoice) =
22974       C4::Context->preference('AllowPurchaseSuggestionBranchChoice');
22975     if ($allowpurchasesuggestionbranchchoice) {
22976         $dbh->do(q{
22977             INSERT IGNORE INTO systempreferences
22978             (`variable`, `value`, `options`, `explanation`, `type`)
22979             VALUES
22980             ('OPACSuggestionUnwantedFields','branch', NULL,'Define the hidden fields for a patron purchase suggestions made via OPAC.','multiple');
22981         });
22982     }
22983     else {
22984         $dbh->do(q{
22985             INSERT IGNORE INTO systempreferences
22986             (`variable`, `value`, `options`, `explanation`, `type`)
22987             VALUES
22988             ('OPACSuggestionUnwantedFields','', NULL,'Define the hidden fields for a patron purchase suggestions made via OPAC.','multiple');
22989         });
22990     }
22991
22992     #Remove the  AllowPurchaseSuggestionBranchChoice system preference
22993     $dbh->do(
22994         "DELETE FROM systempreferences WHERE variable='AllowPurchaseSuggestionBranchChoice'"
22995     );
22996     NewVersion( $DBversion, 23420, "Allow configuration of hidden fields on the suggestion form in OPAC" );
22997 }
22998
22999 $DBversion = '20.06.00.048';
23000 if( CheckVersion( $DBversion ) ) {
23001     $dbh->do(q{
23002         DELETE FROM circulation_rules WHERE
23003         rule_name IN ('holdallowed','hold_fulfillment_policy','returnbranch') AND
23004         rule_value = ''
23005     });
23006     NewVersion( $DBversion, 26529, "Remove blank default branch rules");
23007 }
23008
23009 $DBversion = '20.06.00.049';
23010 if( CheckVersion( $DBversion ) ) {
23011
23012     if( TableExists('biblioimages') && !column_exists( 'biblioimages', 'itemnumber' ) ) {
23013         $dbh->do(q|
23014             ALTER TABLE biblioimages
23015             ADD COLUMN itemnumber INT(11) DEFAULT NULL
23016             AFTER biblionumber;
23017         |);
23018         $dbh->do(q|
23019             ALTER TABLE biblioimages
23020             ADD FOREIGN KEY bibliocoverimage_fk2 (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE
23021         |);
23022         $dbh->do(q|
23023             ALTER TABLE biblioimages MODIFY biblionumber INT(11) DEFAULT NULL
23024         |)
23025     }
23026
23027     if( !TableExists('cover_images') ) {
23028         $dbh->do(q|
23029             ALTER TABLE biblioimages RENAME cover_images
23030         |);
23031     }
23032
23033     NewVersion( $DBversion, '26145', ["Add the biblioimages.itemnumber column", "Rename table biblioimages with cover_images"] );
23034 }
23035
23036 $DBversion = '20.06.00.050';
23037 if ( CheckVersion($DBversion) ) {
23038     $dbh->do(q{
23039         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
23040         ('NoIssuesChargeGuarantorsWithGuarantees','','','Define maximum amount withstanding before checkouts are blocked including guarantors and their other guarantees','Integer');
23041     });
23042
23043     NewVersion( $DBversion, 19382, "Add ability to block guarantees based on fees owed by guarantor and other guarantee - new system preference 'NoIssuesChargeGuarantorsWithGuarantees'");
23044 }
23045
23046 $DBversion = '20.06.00.051';
23047 if( CheckVersion( $DBversion ) ) {
23048     $dbh->do(q{
23049         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
23050         ('HoldsNeedProcessingSIP', '0', NULL, 'Require staff to check-in before hold is set to waiting state', 'YesNo' )
23051     });
23052
23053     NewVersion( $DBversion, 12556, "Add new syspref HoldsNeedProcessingSIP");
23054 }
23055
23056 $DBversion = '20.06.00.052';
23057 if ( CheckVersion($DBversion) ) {
23058     $dbh->do(q{
23059         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')
23060     });
23061
23062     $dbh->do(q{
23063         UPDATE systempreferences SET explanation = 'Automatically update OAI sets when a bibliographic or item record is created or updated' WHERE variable = 'OAI-PMH:AutoUpdateSets'
23064     });
23065
23066     NewVersion( $DBversion, 25460, "Update OAI set when adding/editing/deleting item records" );
23067 }
23068
23069 $DBversion = '20.06.00.053';
23070 if( CheckVersion( $DBversion ) ) {
23071     $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'" );
23072     $dbh->do( "UPDATE systempreferences SET explanation='If enabled, the patron can set checkouts to be visible to their guarantor' WHERE variable='AllowPatronToSetCheckoutsVisibilityForGuarantor'" );
23073     $dbh->do( "UPDATE systempreferences SET explanation='If enabled, the patron can set fines to be visible to their guarantor' WHERE variable='AllowPatronToSetFinesVisibilityForGuarantor'" );
23074     $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'" );
23075     $dbh->do( "UPDATE systempreferences SET explanation='If ON, the next user will automatically get the last searches in their history' WHERE variable='LoadSearchHistoryToTheFirstLoggedUser'" );
23076     $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'" );
23077
23078     NewVersion( $DBversion, 26569, "Use gender neutral pronouns in system preference explanations" );
23079 }
23080
23081 $DBversion = '20.06.00.054';
23082 if ( CheckVersion($DBversion) ) {
23083
23084     $dbh->do(
23085         qq{
23086             INSERT IGNORE INTO account_credit_types (code, description, can_be_added_manually, is_system)
23087             VALUES
23088               ('OVERPAYMENT', 'Overpayment refund', 0, 1)
23089         }
23090     );
23091
23092     $dbh->do(
23093         qq{
23094             INSERT IGNORE INTO account_offset_types ( type ) VALUES ('Overpayment');
23095         }
23096     );
23097
23098     $dbh->do(
23099         qq{
23100             UPDATE accountlines SET credit_type_code = 'OVERPAYMENT' WHERE credit_type_code = 'CREDIT' AND description = 'Overpayment refund'
23101         }
23102     );
23103
23104     NewVersion( $DBversion, 25596, "Add OVERPAYMENT credit type" );
23105 }
23106
23107 $DBversion = '20.06.00.055';
23108 if( CheckVersion( $DBversion ) ) {
23109     my $count_missing_budget = $dbh->selectrow_arrayref(q|
23110         SELECT COUNT(*) FROM aqbudgets ab WHERE NOT EXISTS
23111             (SELECT * FROM aqbudgetperiods abp WHERE abp.budget_period_id = ab.budget_period_id)
23112             AND budget_period_id IS NOT NULL;
23113
23114     |);
23115
23116     my $message = "";
23117     if($count_missing_budget->[0] > 0) {
23118         $dbh->do(q|
23119             CREATE TABLE _bug_18050_aqbudgets AS
23120             SELECT * FROM aqbudgets ab WHERE NOT EXISTS
23121                 (SELECT * FROM aqbudgetperiods abp WHERE abp.budget_period_id = ab.budget_period_id)
23122         |);
23123
23124         $dbh->do(q|
23125             UPDATE aqbudgets ab SET budget_period_id = NULL
23126             WHERE NOT EXISTS
23127                 (SELECT * FROM aqbudgetperiods abp WHERE abp.budget_period_id = ab.budget_period_id)
23128         |);
23129         $message = ". There are $count_missing_budget->[0] funds in your database that are not linked
23130         to a valid budget. Setting invalid budget id (budget_period_id) to null. The table _bug_18050_aqbudgets
23131         was created with original data. Please check that table and place valid ids in aqbudget table as soon as possible."
23132
23133     }
23134
23135     if ( !foreign_key_exists( 'aqbudgets', 'aqbudgetperiods_ibfk_1' ) ) {
23136         $dbh->do(q|
23137             ALTER TABLE aqbudgets ADD CONSTRAINT `aqbudgetperiods_ibfk_1` FOREIGN KEY (`budget_period_id`) REFERENCES `aqbudgetperiods` (`budget_period_id`) ON UPDATE CASCADE ON DELETE CASCADE
23138         |);
23139         NewVersion( $DBversion, 18050, "Add FK constraint on aqbudgets.budget_period_id$message");
23140     } else {
23141         NewVersion( $DBversion, 18050, "FK constraint on aqbudgets.budget already exists");
23142     }
23143
23144 }
23145
23146 $DBversion = '20.06.00.056';
23147 if( CheckVersion( $DBversion ) ) {
23148
23149     $dbh->do("DROP INDEX title ON import_biblios");
23150     $dbh->do("DROP INDEX isbn ON import_biblios");
23151     $dbh->do("ALTER TABLE import_biblios MODIFY title LONGTEXT");
23152     $dbh->do("ALTER TABLE import_biblios MODIFY author LONGTEXT");
23153     $dbh->do("ALTER TABLE import_biblios MODIFY isbn LONGTEXT");
23154     $dbh->do("ALTER TABLE import_biblios MODIFY issn LONGTEXT");
23155     $dbh->do("CREATE INDEX title ON import_biblios (title(191));");
23156     $dbh->do("CREATE INDEX isbn ON import_biblios (isbn(191));");
23157
23158     NewVersion( $DBversion, 26853, "Update import_biblios columns and indexes" );
23159 }
23160
23161 $DBversion = '20.06.00.057';
23162 if( CheckVersion( $DBversion ) ) {
23163     $dbh->do(q{
23164         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES
23165             ('ArticleRequestsMandatoryFieldsItemOnly', '', NULL, 'Comma delimited list of required fields for bibs where article requests rule = ''item_only''', 'multiple')
23166     });
23167     $dbh->do(q{
23168         DELETE FROM systempreferences WHERE variable = "ArticleRequestsMandatoryFieldsItemsOnly"
23169     });
23170
23171     NewVersion( $DBversion, 26638, "Add missing system preference ArticleRequestsMandatoryFieldsItemOnly");
23172 }
23173
23174 $DBversion = '20.06.00.058';
23175 if( CheckVersion( $DBversion ) ) {
23176
23177     # Adding the ON DELETE CASCASE ON UPDATE CASCADE, in case it's missing (from 9016 - 3.15.00.039)
23178     $dbh->do( q{
23179         ALTER TABLE letter DROP FOREIGN KEY message_transport_type_fk
23180     } );
23181
23182     $dbh->do( q{
23183         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
23184     } );
23185
23186     $dbh->do(q{
23187         UPDATE message_transport_types SET message_transport_type = "itiva" WHERE message_transport_type = "phone"
23188     });
23189
23190     NewVersion( $DBversion, 25333, q{Change message transport type for Talking Tech from "phone" to "itiva"});
23191 }
23192
23193 $DBversion = '20.06.00.059';
23194 if( CheckVersion( $DBversion ) ) {
23195
23196     if( !column_exists( 'search_field', 'mandatory' ) ) {
23197         $dbh->do( "ALTER TABLE search_field ADD COLUMN mandatory tinyint(1) NULL DEFAULT NULL AFTER opac" );
23198     }
23199
23200     NewVersion( $DBversion, 19482, "Add mandatory column to search_field for ES mapping" );
23201 }
23202
23203 $DBversion = '20.06.00.060';
23204 if( CheckVersion( $DBversion ) ) {
23205     $dbh->do(q{
23206         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
23207         ('PhoneNotification','0',NULL,'If ON, enables generation of phone notifications to be sent by plugins','YesNo')
23208     });
23209
23210     $dbh->do(q{
23211         INSERT IGNORE INTO message_transport_types (message_transport_type) VALUES ('phone')
23212     });
23213
23214     $dbh->do(q{
23215         INSERT IGNORE INTO `message_transports`
23216         (`message_attribute_id`, `message_transport_type`, `is_digest`, `letter_module`, `letter_code`)
23217         VALUES
23218         (1, 'phone',       0, 'circulation', 'DUE'),
23219         (1, 'phone',       1, 'circulation', 'DUEDGST'),
23220         (2, 'phone',       0, 'circulation', 'PREDUE'),
23221         (2, 'phone',       1, 'circulation', 'PREDUEDGST'),
23222         (4, 'phone',       0, 'reserves',    'HOLD'),
23223         (5, 'phone',       0, 'circulation', 'CHECKIN'),
23224         (6, 'phone',       0, 'circulation', 'CHECKOUT');
23225     });
23226
23227     NewVersion( $DBversion, 25334, "Add generic 'phone' message transport type");
23228 }
23229
23230 $DBversion = '20.06.00.061';
23231 if( CheckVersion( $DBversion ) ) {
23232     if ( !column_exists( 'reserves', 'desk_id' ) ) {
23233         $dbh->do(q{
23234              ALTER TABLE reserves ADD COLUMN desk_id INT(11) DEFAULT NULL AFTER branchcode,
23235              ADD KEY desk_id (`desk_id`),
23236              ADD CONSTRAINT `reserves_ibfk_6` FOREIGN KEY (`desk_id`) REFERENCES `desks` (`desk_id`) ON DELETE SET NULL ON UPDATE CASCADE ;
23237         });
23238         $dbh->do(q{
23239              ALTER TABLE old_reserves ADD COLUMN desk_id INT(11) DEFAULT NULL AFTER branchcode,
23240              ADD KEY `old_desk_id` (`desk_id`);
23241         });
23242     }
23243
23244     NewVersion( $DBversion, 24412, "Attach waiting reserve to desk" );
23245 }
23246
23247 $DBversion = '20.06.00.062';
23248 if( CheckVersion( $DBversion ) ) {
23249     $dbh->do( "UPDATE circulation_rules SET rule_name = 'lostreturn' WHERE rule_name = 'refund'" );
23250     $dbh->do( "UPDATE circulation_rules SET rule_value = 'refund' WHERE rule_name = 'lostreturn' AND rule_value = 1" );
23251
23252     NewVersion( $DBversion, 23091, "Update refund rules");
23253 }
23254
23255 $DBversion = '20.06.00.063';
23256 if( CheckVersion( $DBversion ) ) {
23257     $dbh->do(q{INSERT IGNORE INTO circulation_rules (branchcode, categorycode, itemtype, rule_name, rule_value) VALUES (NULL, NULL, NULL, 'decreaseloanholds', NULL) });
23258
23259     NewVersion( $DBversion, 14866, "Add decreaseloanholds circulation rule" );
23260 }
23261
23262 $DBversion = '20.06.00.064';
23263 if ( CheckVersion($DBversion) ) {
23264
23265     $dbh->do(q{
23266         INSERT IGNORE INTO account_credit_types (code, description, can_be_added_manually, is_system)
23267         VALUES ('CANCELLATION', 'Cancelled charge', 0, 1)
23268     });
23269
23270     $dbh->do(q{
23271         INSERT IGNORE INTO account_offset_types ( type ) VALUES ('CANCELLATION');
23272     });
23273
23274     NewVersion( $DBversion, 24603, "Add CANCELLATION credit_type_code" );
23275 }
23276
23277 $DBversion = '20.06.00.065';
23278 if( CheckVersion( $DBversion ) ) {
23279     if( !column_exists( 'issues', 'issuer_id' ) ) {
23280         $dbh->do( q| ALTER TABLE issues ADD issuer_id INT(11) DEFAULT NULL AFTER borrowernumber | );
23281     }
23282     if (!foreign_key_exists( 'issues', 'issues_ibfk_borrowers_borrowernumber' )) {
23283         $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 | );
23284     }
23285     if( !column_exists( 'old_issues', 'issuer_id' ) ) {
23286         $dbh->do( q| ALTER TABLE old_issues ADD issuer_id INT(11) DEFAULT NULL AFTER borrowernumber | );
23287     }
23288     if (!foreign_key_exists( 'old_issues', 'old_issues_ibfk_borrowers_borrowernumber' )) {
23289         $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 | );
23290     }
23291
23292     $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'); | );
23293
23294     NewVersion( $DBversion, 23916, [ "Add new [old_]issues.issuer DB fields", "Add new syspref RecordStaffUserOnCheckout" ] );
23295 }
23296
23297 $DBversion = '20.06.00.066';
23298 if( CheckVersion( $DBversion ) ) {
23299     if( !column_exists( 'branches', 'branchillemail' ) ) {
23300         $dbh->do( q| ALTER TABLE branches ADD branchillemail LONGTEXT AFTER branchemail | );
23301     }
23302     # Add new sysprefs
23303     $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'); | );
23304     $dbh->do( q| INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type) VALUES ('ILLSendStaffNotices', NULL, 'Send these ILL notices to staff', NULL, 'multiple'); | );
23305     # Add new notices
23306     $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'); | );
23307     $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'); | );
23308     $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'); | );
23309     $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'); | );
23310     $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'); | );
23311     $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'); | );
23312     $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'); | );
23313     $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'); | );
23314     $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'); | );
23315     $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'); | );
23316     # Add patron messaging preferences
23317     $dbh->do( q| INSERT IGNORE INTO message_attributes (message_name, takes_days) VALUES ('Ill_ready', 0); | );
23318     my $ready_id = $dbh->last_insert_id(undef, undef, 'message_attributes', undef);
23319     if (defined $ready_id) {
23320         $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');) );
23321         $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');) );
23322         $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');) );
23323     }
23324     $dbh->do( q| INSERT IGNORE INTO message_attributes (message_name, takes_days) VALUES ('Ill_unavailable', 0); | );
23325     my $unavail_id = $dbh->last_insert_id(undef, undef, 'message_attributes', undef);
23326     if (defined $unavail_id) {
23327         $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');) );
23328         $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');) );
23329         $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');) );
23330     }
23331
23332     NewVersion( $DBversion, 22818, "Add ILL notices" );
23333 }
23334
23335 $DBversion = '20.06.00.067';
23336 if( CheckVersion( $DBversion ) ) {
23337     $dbh->do(q{
23338         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
23339         ('OPACHoldsHistory','0','','If ON, enables display of Patron Holds History in OPAC','YesNo')
23340     });
23341
23342     NewVersion( $DBversion, 20936, "Add new system preference OPACHoldsHistory");
23343 }
23344
23345 $DBversion = '20.06.00.068';
23346 if( CheckVersion( $DBversion ) ) {
23347   if( !TableExists( 'import_batch_profiles' ) ) {
23348     $dbh->do(q{
23349       CREATE TABLE `import_batch_profiles` ( -- profile for batches of marc records to be imported
23350         `id` int(11) NOT NULL auto_increment, -- unique identifier and primary key
23351         `name` varchar(100) NOT NULL, -- name of this profile
23352         `matcher_id` int(11) default NULL, -- the id of the match rule used (matchpoints.matcher_id)
23353         `template_id` int(11) default NULL, -- the id of the marc modification template
23354         `overlay_action` varchar(50) default NULL, -- how to handle duplicate records
23355         `nomatch_action` varchar(50) default NULL, -- how to handle records where no match is found
23356         `item_action` varchar(50) default NULL, -- what to do with item records
23357         `parse_items` tinyint(1) default NULL, -- should items be parsed
23358         `record_type` varchar(50) default NULL, -- type of record in the batch
23359         `encoding` varchar(50) default NULL, -- file encoding
23360         `format` varchar(50) default NULL, -- marc format
23361         `comments` LONGTEXT, -- any comments added when the file was uploaded
23362         PRIMARY KEY (`id`),
23363         UNIQUE KEY `u_import_batch_profiles__name` (`name`)
23364       ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
23365     });
23366   }
23367
23368   if(!column_exists('import_batches', 'profile_id')) {
23369     $dbh->do(q{
23370       ALTER TABLE import_batches ADD COLUMN `profile_id` int(11) default NULL AFTER comments
23371     });
23372
23373     $dbh->do(q{
23374       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
23375     });
23376   }
23377
23378   NewVersion( $DBversion, 23019, "Add import_batch_profiles table and profile_id column in import_batches" );
23379 }
23380
23381 $DBversion = '20.06.00.069';
23382 if( CheckVersion( $DBversion ) ) {
23383     my ($count) = $dbh->selectrow_array(
23384         q|
23385             SELECT COUNT(*)
23386             FROM circulation_rules
23387             WHERE rule_name = 'unseen_renewals_allowed'
23388         |
23389     );
23390     if ($count == 0) {
23391         $dbh->do( q|
23392             INSERT INTO circulation_rules (rule_name, rule_value)
23393             VALUES ('unseen_renewals_allowed', '')
23394         | );
23395     }
23396
23397     if( !column_exists( 'issues', 'unseen_renewals' ) ) {
23398         $dbh->do( q| ALTER TABLE issues ADD unseen_renewals TINYINT(4) DEFAULT 0 NOT NULL AFTER renewals | );
23399     }
23400     if( !column_exists( 'old_issues', 'unseen_renewals' ) ) {
23401         $dbh->do( q| ALTER TABLE old_issues ADD unseen_renewals TINYINT(4) DEFAULT 0 NOT NULL AFTER renewals | );
23402     }
23403
23404     $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'); | );
23405
23406     NewVersion( $DBversion, 24083, ["Add circulation_rules 'unseen_renewals_allowed'", "Add issues.unseen_renewals & old_issues.unseen_renewals)", "Add new system preference UnseenRenewals"] );
23407 }
23408
23409 $DBversion = '20.11.00.000';
23410 if( CheckVersion( $DBversion ) ) {
23411     NewVersion( $DBversion, "", "Koha 20.11.00 release" );
23412 }
23413
23414 $DBversion = '20.12.00.000';
23415 if( CheckVersion( $DBversion ) ) {
23416     NewVersion( $DBversion, "", "Sorry, this is my first life, I am still learning!" );
23417 }
23418
23419 $DBversion = '20.12.00.001';
23420 if( CheckVersion( $DBversion ) ) {
23421     $dbh->do(q{
23422         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
23423        ('ElasticsearchCrossFields', '1', '', 'Enable "cross_fields" option for searches using Elastic search.', 'YesNo')
23424     });
23425     NewVersion( $DBversion, 27252, "Add ElasticsearchCrossFields system preference");
23426 }
23427
23428 $DBversion = '20.12.00.002';
23429 if( CheckVersion( $DBversion ) ) {
23430     $dbh->do(q{UPDATE systempreferences SET `type` = 'Choice' WHERE `variable` = 'UsageStatsCountry'});
23431     NewVersion( $DBversion, 27351, "Set type for UsageStatsCountry to Choice");
23432 }
23433
23434 $DBversion = '20.12.00.003';
23435 if( CheckVersion( $DBversion ) ) {
23436     $dbh->do(q{UPDATE systempreferences SET `type` = 'Choice' WHERE `variable` = 'Mana'});
23437     NewVersion( $DBversion, 27349, "Update type for Mana system preference to Choice");
23438 }
23439
23440 $DBversion = '20.12.00.004';
23441 if( CheckVersion( $DBversion ) ) {
23442     $dbh->do(q{UPDATE systempreferences set variable="TaxRates" WHERE variable="gist"});
23443     NewVersion( $DBversion, 27485, "Rename system preference 'gist' to 'TaxRates'");
23444 }
23445
23446 $DBversion = '20.12.00.005';
23447 if( CheckVersion( $DBversion ) ) {
23448     $dbh->do(q{UPDATE systempreferences set variable="OPACLanguages" WHERE variable="opaclanguages"});
23449     NewVersion( $DBversion, 27491, "Rename system preference 'opaclanguages' to 'OPACLanguages'");
23450 }
23451
23452 $DBversion = '20.12.00.006';
23453 if( CheckVersion( $DBversion ) ) {
23454     $dbh->do(q{UPDATE systempreferences SET variable="OPACComments" WHERE variable="reviewson" });
23455     NewVersion( $DBversion, 27487, "Rename system preference 'reviewson' to 'OPACComments");
23456 }
23457
23458 $DBversion = '20.12.00.007';
23459 if( CheckVersion( $DBversion ) ) {
23460     $dbh->do(q{UPDATE systempreferences set variable="CSVDelimiter" WHERE variable="delimiter"});
23461     NewVersion( $DBversion, 27486, "Renaming system preference 'delimiter' to 'CSVDelimiter'");
23462 }
23463
23464 $DBversion = '20.12.00.008';
23465 if( CheckVersion( $DBversion ) ) {
23466     $dbh->do(q{
23467         UPDATE systempreferences
23468         SET options = "claim_returned|batchmod|moredetail|cronjob|additem|pendingreserves|onpayment"
23469         WHERE variable = "MarkLostItemsAsReturned";
23470     });
23471     NewVersion( $DBversion, 25552, "Add missing Claims Returned option to MarkLostItemsAsReturned");
23472 }
23473
23474 $DBversion = '20.12.00.009';
23475 if( CheckVersion( $DBversion ) ) {
23476     $dbh->do( "UPDATE systempreferences SET variable = 'UseICUStyleQUotes' WHERE variable = 'UseICU'" );
23477     NewVersion( $DBversion, 27581, "Rename system preference 'UseICU' to 'UseICUStyleQuotes'");
23478 }
23479
23480 $DBversion = '20.12.00.010';
23481 if( CheckVersion( $DBversion ) ) {
23482     $dbh->do( q{
23483         DELETE FROM systempreferences WHERE variable="OpacGroupResults"
23484     });
23485
23486     NewVersion( $DBversion, 20410, "Remove OpacGroupResults");
23487 }
23488
23489 $DBversion = '20.12.00.011';
23490 if ( CheckVersion($DBversion) ) {
23491     $dbh->do( q{
23492         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
23493         VALUES
23494         ('OPACShibOnly','0','If ON enables shibboleth only authentication for the opac','','YesNo'),
23495         ('staffShibOnly','0','If ON enables shibboleth only authentication for the staff client','','YesNo')
23496     } );
23497     NewVersion( $DBversion, 18506, "Add OPACShibOnly and staffShibOnly system preferences" );
23498 }
23499
23500 $DBversion = '20.12.00.012';
23501 if( CheckVersion( $DBversion ) ) {
23502     my $category_exists = $dbh->selectrow_array("SELECT count(category_name) FROM authorised_value_categories WHERE category_name='UPLOAD'");
23503     my $description;
23504     if( $category_exists ){
23505         $description = "The UPLOAD authorized value category exists. Update the 'is_system' value to 1.";
23506         $dbh->do( "UPDATE authorised_value_categories SET is_system = 1 WHERE category_name = 'UPLOAD'" );
23507     } else {
23508         $description = "The UPLOAD authorized value category does not exist. Create it.";
23509         $dbh->do( "INSERT IGNORE INTO authorised_value_categories (category_name, is_system) VALUES ('UPLOAD', 1)" );
23510     }
23511
23512     NewVersion( $DBversion, 27598, ["Add UPLOAD as a built-in system authorized value category", $description] );
23513 }
23514
23515 $DBversion = '20.12.00.013';
23516 if( CheckVersion( $DBversion ) ) {
23517     $dbh->do(q{
23518          INSERT IGNORE INTO systempreferences
23519          (variable, value, explanation, options, type) VALUES
23520          ('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')
23521     });
23522     NewVersion( $DBversion, 24108, "Add system preference DefaultSaveRecordFileID");
23523 }
23524
23525 $DBversion = '20.12.00.014';
23526 if( CheckVersion( $DBversion ) ) {
23527
23528     sanitize_zero_date('aqorders', 'datecancellationprinted');
23529     sanitize_zero_date('old_issues', 'returndate');
23530
23531     NewVersion( $DBversion, 7806, "Remove remaining possible 0000-00-00 values");
23532 }
23533
23534 $DBversion = '20.12.00.015';
23535 if( CheckVersion( $DBversion ) ) {
23536     $dbh->do( "UPDATE search_marc_to_field SET sort = 1 WHERE sort IS NULL" );
23537     $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'" );
23538     NewVersion( $DBversion, 27316, "In Elastisearch mappings convert NULL (Undef) for sort to 1 (Yes)");
23539 }
23540
23541 $DBversion = '20.12.00.016';
23542 if( CheckVersion( $DBversion ) ) {
23543
23544     unless ( column_exists( 'marc_subfield_structure', 'display_order' ) ) {
23545         $dbh->do(q{
23546             ALTER TABLE marc_subfield_structure
23547             ADD COLUMN display_order INT(2) NOT NULL DEFAULT 0 AFTER maxlength
23548         });
23549     }
23550
23551     unless ( column_exists( 'auth_subfield_structure', 'display_order' ) ) {
23552         $dbh->do(q{
23553             ALTER TABLE auth_subfield_structure
23554             ADD COLUMN display_order INT(2) NOT NULL DEFAULT 0 AFTER defaultvalue
23555         });
23556     }
23557
23558     NewVersion( $DBversion, 8976, "Allow setting a default sequence of subfields in cataloguing editor" );
23559 }
23560
23561 $DBversion = '20.12.00.017';
23562 if( CheckVersion( $DBversion ) ) {
23563     $dbh->do(q|
23564         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
23565         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')
23566     |);
23567
23568     NewVersion( $DBversion, 26937, "Add CheckPrevCheckoutDelay system preference)" );
23569 }
23570
23571 $DBversion = '20.12.00.018';
23572 if( CheckVersion( $DBversion ) ) {
23573
23574     $dbh->do(q|
23575         UPDATE items
23576         LEFT JOIN issues ON issues.itemnumber=items.itemnumber
23577         SET items.onloan=CAST(issues.date_due AS DATE)
23578         WHERE items.onloan IS NULL AND issues.issue_id IS NOT NULL
23579     |);
23580
23581     NewVersion( $DBversion, 27808, "Adjust items.onloan if needed" );
23582 }
23583
23584 $DBversion = '20.12.00.019';
23585 if( CheckVersion( $DBversion ) ) {
23586
23587     if( !column_exists( 'branchtransfers', 'datecancelled' ) ) {
23588         $dbh->do(q|
23589             ALTER TABLE `branchtransfers`
23590             ADD COLUMN `datecancelled` datetime default NULL AFTER `datearrived`
23591         |);
23592     }
23593
23594     if( !column_exists( 'branchtransfers', 'cancellation_reason' ) ) {
23595         $dbh->do(q|
23596             ALTER TABLE `branchtransfers`
23597             ADD COLUMN `cancellation_reason` ENUM('Manual', 'StockrotationAdvance', 'StockrotationRepatriation', 'ReturnToHome', 'ReturnToHolding', 'RotatingCollection', 'Reserve', 'LostReserve', 'CancelReserve') DEFAULT NULL AFTER `reason`
23598         |);
23599     }
23600
23601     NewVersion( $DBversion, 26057, "Add datecancelled field to branchtransfers");
23602 }
23603
23604 $DBversion = '20.12.00.020';
23605 if ( CheckVersion($DBversion) ) {
23606
23607     # Update daterequested from datesent for stockrotation
23608     $dbh->do(q|
23609             UPDATE `branchtransfers`
23610             SET
23611               `daterequested` = `datesent`,
23612               `datesent` = NULL
23613             WHERE `reason` LIKE 'Stockrotation%'
23614             AND   `datearrived` IS NULL
23615     |);
23616
23617     NewVersion( $DBversion, 24446, "Update stockrotation 'daterequested' field in transfers table" );
23618 }
23619
23620 $DBversion = '20.12.00.021';
23621 if( CheckVersion( $DBversion ) ) {
23622     $dbh->do(q{
23623         UPDATE systempreferences SET type="Free" WHERE variable="OverDriveClientSecret" OR variable="RecordedBooksClientSecret"
23624     });
23625     $dbh->do(q{
23626         UPDATE systempreferences SET type="integer" WHERE variable="UsageStats"
23627     });
23628     $dbh->do(q{
23629         UPDATE systempreferences
23630         SET value="0"
23631         WHERE ( ( type = "YesNo" AND ( value NOT IN ( "1", "0" ) OR value IS NULL ) ) )
23632     });
23633
23634     NewVersion( $DBversion, 22824, "Update syspref values for YesNo");
23635 }
23636
23637 $DBversion = '20.12.00.022';
23638 if( CheckVersion( $DBversion ) ) {
23639     $dbh->do(q{ INSERT IGNORE INTO letter (module, code, branchcode, name, is_html, title, content, message_transport_type) VALUES
23640         ('circulation','CHECKINSLIP','','Checkin slip',1,'Checkin slip',
23641 "<h3>[% branch.branchname %]</h3>
23642 Checked in items for [% borrower.title %] [% borrower.firstname %] [% borrower.initials %] [% borrower.surname %] <br />
23643 ([% borrower.cardnumber %]) <br />
23644
23645 [% today | $KohaDates %]<br />
23646
23647 <h4>Checked in today</h4>
23648 [% FOREACH checkin IN old_checkouts %]
23649 [% SET item = checkin.item %]
23650 <p>
23651 [% item.biblio.title %] <br />
23652 Barcode: [% item.barcode %] <br />
23653 </p>
23654 [% END %]",
23655         'print')
23656     });
23657
23658     NewVersion( $DBversion, 12224, "Add CHECKINSLIP notice" );
23659 }
23660
23661 $DBversion = '20.12.00.023';
23662 if( CheckVersion( $DBversion ) ) {
23663
23664     $dbh->do(q{
23665         UPDATE systempreferences
23666         SET value=REPLACE(value, '|', ',')
23667         WHERE variable="OPACHoldsIfAvailableAtPickupExceptions"
23668            OR variable="BatchCheckoutsValidCategories"
23669     });
23670     NewVersion( $DBversion, 27652, "Separate values for OPACHoldsIfAvailableAtPickupExceptions and BatchCheckoutsValidCategories with comma");
23671 }
23672
23673 $DBversion = '20.12.00.024';
23674 if( CheckVersion( $DBversion ) ) {
23675
23676     $dbh->do( q{
23677         INSERT IGNORE INTO letter (module, code, name, title, content, message_transport_type) VALUES ('circulation', 'AUTO_RENEWALS_DGST', 'Notification on auto renewals', 'Auto renewals (Digest)',
23678         "Dear [% borrower.firstname %] [% borrower.surname %],
23679         [% IF error %]
23680             There were [% error %] items that were not renewed.
23681         [% END %]
23682         [% IF success %]
23683             There were [% success %] items that were renewed.
23684         [% END %]
23685         [% FOREACH checkout IN checkouts %]
23686             [% checkout.item.biblio.title %] : [% checkout.item.barcode %]
23687             [% IF !checkout.auto_renew_error %]
23688                 was renewed until [% checkout.date_due | $KohaDates as_due_date => 1%]
23689             [% ELSIF checkout.auto_renew_error == 'too_many' %]
23690                 You have reached the maximum number of checkouts possible.
23691             [% ELSIF checkout.auto_renew_error == 'on_reserve' %]
23692                 This item is on hold for another patron.
23693             [% ELSIF checkout.auto_renew_error == 'restriction' %]
23694                 You are currently restricted.
23695             [% ELSIF checkout.auto_renew_error == 'overdue' %]
23696                 You have overdue items.
23697             [% ELSIF checkout.auto_renew_error == 'auto_too_late' %]
23698                 It's too late to renew this item.
23699             [% ELSIF checkout.auto_renew_error == 'auto_too_much_oweing' %]
23700                 Your total unpaid fines are too high.
23701             [% ELSIF checkout.auto_renew_error == 'too_unseen' %]
23702                 This item must be renewed at the library.
23703             [% END %]
23704         [% END %]
23705         ", 'email');
23706     });
23707
23708     $dbh->do( q{
23709         INSERT IGNORE INTO `message_attributes`
23710             (`message_attribute_id`, message_name, `takes_days`)
23711         VALUES (9, 'Auto_Renewals', 0)
23712     });
23713
23714     $dbh->do( q{
23715         INSERT IGNORE INTO `message_transports`
23716             (`message_attribute_id`, `message_transport_type`, `is_digest`, `letter_module`, `letter_code`)
23717         VALUES  (9, 'email', 0, 'circulation', 'AUTO_RENEWALS'),
23718                 (9, 'sms', 0, 'circulation', 'AUTO_RENEWALS'),
23719                 (9, 'email', 1, 'circulation', 'AUTO_RENEWALS_DGST'),
23720                 (9, 'sms', 1, 'circulation', 'AUTO_RENEWALS_DGST')
23721     });
23722
23723      $dbh->do(q{
23724          INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
23725          VALUES ('AutoRenewalNotices','cron','cron|preferences|never','How should Koha determine whether to end autorenewal notices','Choice')
23726      });
23727
23728     NewVersion( $DBversion, 18532, 'Messaging preferences for auto renewals' );
23729 }
23730
23731 $DBversion = '20.12.00.025';
23732 if( CheckVersion( $DBversion ) ) {
23733
23734     $dbh->do(q|
23735         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
23736         VALUES ('ChargeFinesOnClosedDays', '0', NULL, 'Charge fines on days the library is closed.', 'YesNo')
23737     |);
23738
23739     NewVersion( $DBversion, 27835, "Add new system preference ChargeFinesOnClosedDays");
23740 }
23741
23742 $DBversion = '20.12.00.026';
23743 if( CheckVersion( $DBversion ) ) {
23744
23745     $dbh->do(q{INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('DefaultHoldExpirationdate','0','','Automatically set default expiration date for holds','YesNo') });
23746     $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') });
23747     $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') });
23748
23749     NewVersion( $DBversion, 26498, "Bug 26498 - Add option to set a default expire date for holds at reservation time");
23750 }
23751
23752 $DBversion = '20.12.00.027';
23753 if( CheckVersion( $DBversion ) ) {
23754
23755     $dbh->do(q{
23756         UPDATE circulation_rules
23757         SET
23758             rule_value = CASE
23759                 WHEN rule_value='0' THEN 'not_allowed'
23760                 WHEN rule_value='1' THEN 'from_home_library'
23761                 WHEN rule_value='2' THEN 'from_any_library'
23762                 WHEN rule_value='3' THEN 'from_local_hold_group'
23763             END
23764         WHERE rule_name='holdallowed' AND rule_value >= 0 AND rule_value <= 3;
23765     });
23766
23767     NewVersion( $DBversion, 27069, "Change holdallowed values from numbers to strings");
23768 }
23769
23770 $DBversion = '20.12.00.028';
23771 if ( CheckVersion($DBversion) ) {
23772
23773     if ( !column_exists( 'letter', 'id' ) ) {
23774         $dbh->do(q{
23775             ALTER TABLE letter DROP PRIMARY KEY
23776         });
23777         $dbh->do(q{
23778             ALTER TABLE letter ADD COLUMN `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
23779         });
23780         $dbh->do(q{
23781             ALTER TABLE letter ADD UNIQUE KEY letter_uniq_1 (`module`,`code`,`branchcode`,`message_transport_type`,`lang`)
23782         });
23783     }
23784
23785     $dbh->do(q{
23786         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
23787         VALUES ('NoticesLog','0',NULL,'If enabled, log changes to notice templates','YesNo')
23788     });
23789
23790     NewVersion( $DBversion, 14233, "Add id field to letter table" );
23791 }
23792
23793 $DBversion = '20.12.00.029';
23794 if( CheckVersion( $DBversion ) ) {
23795     $dbh->do("ALTER TABLE problem_reports MODIFY content TEXT NOT NULL");
23796
23797     NewVersion( $DBversion, 27726, "Increase field size for problem_reports.content");
23798 }
23799
23800 $DBversion = '20.12.00.030';
23801 if( CheckVersion( $DBversion ) ) {
23802     $dbh->do(q|
23803         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
23804         VALUES ('LockExpiredDelay','','','Delay for locking expired patrons (empty means no locking)','Integer')
23805     |);
23806
23807     NewVersion( $DBversion, 21549, "Add new system preference LockExpiredDelay");
23808 }
23809
23810 $DBversion = '20.12.00.031';
23811 if( CheckVersion( $DBversion ) ) {
23812     $dbh->do(q{
23813         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
23814         VALUES ('Reference_NFL_Statuses','1|2',NULL,'Contains not for loan statuses considered as available for reference','Free')
23815     });
23816
23817     NewVersion( $DBversion, 21260, "Add new system preference Reference_NFL_Statuses");
23818 }
23819
23820 $DBversion = '20.12.00.032';
23821 if( CheckVersion( $DBversion ) ) {
23822     $dbh->do(q{
23823         INSERT IGNORE INTO letter
23824         (module,code,branchcode,name,is_html,title,content,message_transport_type,lang)
23825         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')
23826     });
23827
23828     NewVersion( $DBversion, 15986, "Add sample HOLD_REMINDER notice");
23829 }
23830
23831 $DBversion = '20.12.00.033';
23832 if( CheckVersion( $DBversion ) ) {
23833     my $debar = $dbh->selectall_arrayref(q|
23834         SELECT d.borrowernumber, GROUP_CONCAT(comment SEPARATOR '\n') AS comment
23835         FROM borrower_debarments d
23836         LEFT JOIN borrowers b ON b.borrowernumber=d.borrowernumber
23837         WHERE ( b.debarredcomment IS NULL OR b.debarredcomment = "" ) AND ( expiration > CURRENT_DATE() OR expiration IS NULL )
23838         GROUP BY d.borrowernumber
23839     |, { Slice => {} });
23840
23841
23842     my $update_sth = $dbh->prepare(q|
23843         UPDATE borrowers
23844         SET debarredcomment=?
23845         WHERE borrowernumber=?
23846     |);
23847     for my $d ( @$debar ) {
23848         $update_sth->execute($d->{comment}, $d->{borrowernumber});
23849     }
23850
23851     NewVersion( $DBversion, 26940, "Put in sync borrowers.debarredcomment with comments from borrower_debarments");
23852 }
23853
23854 $DBversion = '20.12.00.034';
23855 if( CheckVersion( $DBversion ) ) {
23856
23857     $dbh->do(q{
23858         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type)
23859         VALUES ('casServerVersion', '2', '2|3', 'Version of the CAS server Koha will connect to.', 'Choice');
23860     });
23861
23862     NewVersion( $DBversion, 20854, "Add new system preference casServerVersion");
23863 }
23864
23865 $DBversion = '20.12.00.035';
23866 if( CheckVersion( $DBversion ) ) {
23867     if( !column_exists( 'itemtypes', 'automatic_checkin' ) ) {
23868         $dbh->do(q{
23869             ALTER TABLE itemtypes
23870                 ADD COLUMN `automatic_checkin` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'If automatic checkin is enabled for items of this type' AFTER `searchcategory`
23871         });
23872     }
23873
23874     NewVersion( $DBversion, 23207, "Add automatic_checkin to itemtypes table");
23875 }
23876
23877 $DBversion = '20.12.00.036';
23878 if( CheckVersion( $DBversion ) ) {
23879     $dbh->do(q{
23880         ALTER TABLE club_holds_to_patron_holds
23881         MODIFY COLUMN error_code
23882         ENUM ( 'damaged', 'ageRestricted', 'itemAlreadyOnHold',
23883             'tooManyHoldsForThisRecord', 'tooManyReservesToday',
23884             'tooManyReserves', 'notReservable', 'cannotReserveFromOtherBranches',
23885             'libraryNotFound', 'libraryNotPickupLocation', 'cannotBeTransferred',
23886             'noReservesAllowed'
23887         )
23888     });
23889
23890     NewVersion( $DBversion, 16787, "Add noReservesAllowed to club holds error codes");
23891 }
23892
23893 $DBversion = '20.12.00.037';
23894 if( CheckVersion( $DBversion ) ) {
23895     $dbh->do( q{
23896         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
23897         VALUES ('AcquisitionLog', '0', 'If enabled, log acquisition activity', '', 'YesNo');
23898     });
23899
23900     NewVersion( $DBversion, 23971, "Add new system preference AcquisitionLog");
23901 }
23902
23903 $DBversion = '20.12.00.038';
23904 if( CheckVersion( $DBversion ) ) {
23905
23906     # Add 'ItemLost' to reserves cancellation_reason enum
23907     $dbh->do(
23908         q{
23909             ALTER TABLE
23910                 `branchtransfers`
23911             MODIFY COLUMN
23912                 `cancellation_reason` enum(
23913                     'Manual',
23914                     'StockrotationAdvance',
23915                     'StockrotationRepatriation',
23916                     'ReturnToHome',
23917                     'ReturnToHolding',
23918                     'RotatingCollection',
23919                     'Reserve',
23920                     'LostReserve',
23921                     'CancelReserve',
23922                     'ItemLost'
23923                 )
23924             AFTER `comments`
23925           }
23926     );
23927
23928     NewVersion( $DBversion, 27281, "Add 'ItemLost' to branchtransfers.cancellation_reason enum");
23929 }
23930
23931 $DBversion = '20.12.00.039';
23932 if( CheckVersion( $DBversion ) ) {
23933
23934     $dbh->do(
23935         q{
23936             ALTER TABLE
23937                 `branchtransfers`
23938             MODIFY COLUMN
23939                 `reason` enum(
23940                     'Manual',
23941                     'StockrotationAdvance',
23942                     'StockrotationRepatriation',
23943                     'ReturnToHome',
23944                     'ReturnToHolding',
23945                     'RotatingCollection',
23946                     'Reserve',
23947                     'LostReserve',
23948                     'CancelReserve',
23949                     'TransferCancellation'
23950                 )
23951             AFTER `comments`
23952           }
23953     );
23954
23955     NewVersion( $DBversion, 12362, "Add 'TransferCancellation' to branchtransfers.reason enum");
23956 }
23957
23958 $DBversion = '20.12.00.040';
23959 if( CheckVersion( $DBversion ) ) {
23960     $dbh->do(
23961         q{
23962             INSERT IGNORE INTO account_debit_types (
23963               code,
23964               description,
23965               can_be_invoiced,
23966               can_be_sold,
23967               default_amount,
23968               is_system
23969             )
23970             VALUES
23971               ('VOID', 'Credit has been voided', 0, 0, NULL, 1)
23972         }
23973     );
23974
23975     $dbh->do(q{
23976         INSERT IGNORE INTO account_offset_types ( type ) VALUES ('VOID');
23977     });
23978
23979     NewVersion( $DBversion, 27971, "Add VOID debit type code");
23980 }
23981
23982 # SEE bug 13068
23983 # if there is anything in the atomicupdate, read and execute it.
23984 my $update_dir = C4::Context->config('intranetdir') . '/installer/data/mysql/atomicupdate/';
23985 opendir( my $dirh, $update_dir );
23986 foreach my $file ( sort readdir $dirh ) {
23987     next if $file !~ /\.(sql|perl)$/;  #skip other files
23988     next if $file eq 'skeleton.perl'; # skip the skeleton file
23989     print "DEV atomic update: $file\n";
23990     if ( $file =~ /\.sql$/ ) {
23991         my $installer = C4::Installer->new();
23992         my $rv = $installer->load_sql( $update_dir . $file ) ? 0 : 1;
23993     } elsif ( $file =~ /\.perl$/ ) {
23994         my $code = read_file( $update_dir . $file );
23995         eval $code; ## no critic (StringyEval)
23996         say "Atomic update generated errors: $@" if $@;
23997     }
23998 }
23999
24000 =head1 FUNCTIONS
24001
24002 =head2 DropAllForeignKeys($table)
24003
24004 Drop all foreign keys of the table $table
24005
24006 =cut
24007
24008 sub DropAllForeignKeys {
24009     my ($table) = @_;
24010     # get the table description
24011     my $sth = $dbh->prepare("SHOW CREATE TABLE $table");
24012     $sth->execute;
24013     my $vsc_structure = $sth->fetchrow;
24014     # split on CONSTRAINT keyword
24015     my @fks = split /CONSTRAINT /,$vsc_structure;
24016     # parse each entry
24017     foreach (@fks) {
24018         # isolate what is before FOREIGN KEY, if there is something, it's a foreign key to drop
24019         $_ = /(.*) FOREIGN KEY.*/;
24020         my $id = $1;
24021         if ($id) {
24022             # we have found 1 foreign, drop it
24023             $dbh->do("ALTER TABLE $table DROP FOREIGN KEY $id");
24024             $id="";
24025         }
24026     }
24027 }
24028
24029
24030 =head2 TransformToNum
24031
24032 Transform the Koha version from a 4 parts string
24033 to a number, with just 1 .
24034
24035 =cut
24036
24037 sub TransformToNum {
24038     my $version = shift;
24039     # remove the 3 last . to have a Perl number
24040     $version =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
24041     # three X's at the end indicate that you are testing patch with dbrev
24042     # change it into 999
24043     # prevents error on a < comparison between strings (should be: lt)
24044     $version =~ s/XXX$/999/;
24045     return $version;
24046 }
24047
24048 =head2 SetVersion
24049
24050 set the DBversion in the systempreferences
24051
24052 =cut
24053
24054 sub SetVersion {
24055     return if $_[0]=~ /XXX$/;
24056       #you are testing a patch with a db revision; do not change version
24057     my $kohaversion = TransformToNum($_[0]);
24058     if (C4::Context->preference('Version')) {
24059       my $finish=$dbh->prepare("UPDATE systempreferences SET value=? WHERE variable='Version'");
24060       $finish->execute($kohaversion);
24061     } else {
24062       my $finish=$dbh->prepare("INSERT into systempreferences (variable,value,explanation) values ('Version',?,'The Koha database version. WARNING: Do not change this value manually, it is maintained by the webinstaller')");
24063       $finish->execute($kohaversion);
24064     }
24065     C4::Context::clear_syspref_cache(); # invalidate cached preferences
24066 }
24067
24068 sub NewVersion {
24069     my ( $DBversion, $bug_number, $descriptions ) = @_;
24070
24071     SetVersion($DBversion);
24072
24073     unless ( ref($descriptions) ) {
24074         $descriptions = [ $descriptions ];
24075     }
24076     my $first = 1;
24077     my $time = POSIX::strftime("%H:%M:%S",localtime);
24078     for my $description ( @$descriptions ) {
24079         if ( @$descriptions > 1 ) {
24080             if ( $first ) {
24081                 unless ( $bug_number ) {
24082                     say sprintf "Upgrade to %s done [%s]: %s", $DBversion, $time, $description;
24083                 } else {
24084                     say sprintf "Upgrade to %s done [%s]: Bug %5s - %s", $DBversion, $time, $bug_number, $description;
24085                 }
24086             } else {
24087                 say sprintf "\t\t\t\t\t\t   - %s", $description;
24088             }
24089         } else {
24090             unless ( $bug_number ) {
24091                 say sprintf "Upgrade to %s done [%s]: %s", $DBversion, $time, $description;
24092             } else {
24093                 say sprintf "Upgrade to %s done [%s]: Bug %5s - %s", $DBversion, $time, $bug_number, $description;
24094             }
24095         }
24096         $first = 0;
24097     }
24098 }
24099
24100 =head2 CheckVersion
24101
24102 Check whether a given update should be run when passed the proposed version
24103 number. The update will always be run if the proposed version is greater
24104 than the current database version and less than or equal to the version in
24105 kohaversion.pl. The update is also run if the version contains XXX, though
24106 this behavior will be changed following the adoption of non-linear updates
24107 as implemented in bug 7167.
24108
24109 =cut
24110
24111 sub CheckVersion {
24112     my ($proposed_version) = @_;
24113     my $version_number = TransformToNum($proposed_version);
24114
24115     # The following line should be deleted when bug 7167 is pushed
24116     return 1 if ( $proposed_version =~ m/XXX/ );
24117
24118     if ( C4::Context->preference("Version") < $version_number
24119         && $version_number <= TransformToNum( $Koha::VERSION ) )
24120     {
24121         return 1;
24122     }
24123     else {
24124         return 0;
24125     }
24126 }
24127
24128 sub sanitize_zero_date {
24129     my ( $table_name, $column_name ) = @_;
24130
24131     my (undef, $datatype) = $dbh->selectrow_array(qq|
24132         SHOW COLUMNS FROM $table_name WHERE Field = ?|, undef, $column_name);
24133
24134     if ( $datatype eq 'date' ) {
24135         $dbh->do(qq|
24136             UPDATE $table_name
24137             SET $column_name = NULL
24138             WHERE CAST($column_name AS CHAR(10)) = '0000-00-00';
24139         |);
24140     } else {
24141         $dbh->do(qq|
24142             UPDATE $table_name
24143             SET $column_name = NULL
24144             WHERE CAST($column_name AS CHAR(19)) = '0000-00-00 00:00:00';
24145         |);
24146     }
24147 }
24148
24149 exit;