Bug 26997: Fix upgrade process under MySQL 8
[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, $sti,
57     $query,
58     %existingtables,    # tables already in database
59     %types,
60     $table,
61     $column,
62     $type, $null, $key, $default, $extra,
63     $prefitem,          # preference item in systempreferences table
64 );
65
66 my $schema = Koha::Database->new()->schema();
67
68 my $silent;
69 GetOptions(
70     's' =>\$silent
71     );
72 my $dbh = C4::Context->dbh;
73 $|=1; # flushes output
74
75 local $dbh->{RaiseError} = 0;
76
77 # Record the version we are coming from
78
79 my $original_version = C4::Context->preference("Version");
80
81 # Deal with virtualshelves
82 my $DBversion = "3.00.00.001";
83 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
84     # update virtualshelves table to
85     #
86     $dbh->do("ALTER TABLE `bookshelf` RENAME `virtualshelves`");
87     $dbh->do("ALTER TABLE `shelfcontents` RENAME `virtualshelfcontents`");
88     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD `biblionumber` INT( 11 ) NOT NULL default '0' AFTER shelfnumber");
89     $dbh->do("UPDATE `virtualshelfcontents` SET biblionumber=(SELECT biblionumber FROM items WHERE items.itemnumber=virtualshelfcontents.itemnumber)");
90     # drop all foreign keys : otherwise, we can't drop itemnumber field.
91     DropAllForeignKeys('virtualshelfcontents');
92     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD KEY biblionumber (biblionumber)");
93     # create the new foreign keys (on biblionumber)
94     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD CONSTRAINT `virtualshelfcontents_ibfk_1` FOREIGN KEY (`shelfnumber`) REFERENCES `virtualshelves` (`shelfnumber`) ON DELETE CASCADE ON UPDATE CASCADE");
95     # re-create the foreign key on virtualshelf
96     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD CONSTRAINT `shelfcontents_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE");
97     $dbh->do("ALTER TABLE `virtualshelfcontents` DROP `itemnumber`");
98     print "Upgrade to $DBversion done (virtualshelves)\n";
99     SetVersion ($DBversion);
100 }
101
102
103 $DBversion = "3.00.00.002";
104 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
105     $dbh->do("DROP TABLE sessions");
106     $dbh->do("CREATE TABLE `sessions` (
107   `id` varchar(32) NOT NULL,
108   `a_session` text NOT NULL,
109   UNIQUE KEY `id` (`id`)
110 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
111     print "Upgrade to $DBversion done (sessions uses CGI::session, new table structure for sessions)\n";
112     SetVersion ($DBversion);
113 }
114
115
116 $DBversion = "3.00.00.003";
117 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
118     if (C4::Context->preference("opaclanguages") eq "fr") {
119         $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')");
120     } else {
121         $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')");
122     }
123     print "Upgrade to $DBversion done (adding ReservesNeedReturns systempref, in circulation)\n";
124     SetVersion ($DBversion);
125 }
126
127
128 $DBversion = "3.00.00.004";
129 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
130     $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')");
131     print "Upgrade to $DBversion done (adding DebugLevel systempref, in 'Admin' tab)\n";
132     SetVersion ($DBversion);
133 }
134
135 $DBversion = "3.00.00.005";
136 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
137     $dbh->do("CREATE TABLE `tags` (
138                     `entry` varchar(255) NOT NULL default '',
139                     `weight` bigint(20) NOT NULL default 0,
140                     PRIMARY KEY  (`entry`)
141                     ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
142                 ");
143         $dbh->do("CREATE TABLE `nozebra` (
144                 `server` varchar(20)     NOT NULL,
145                 `indexname` varchar(40)  NOT NULL,
146                 `value` varchar(250)     NOT NULL,
147                 `biblionumbers` longtext NOT NULL,
148                 KEY `indexname` (`server`,`indexname`),
149                 KEY `value` (`server`,`value`))
150                 ENGINE=InnoDB DEFAULT CHARSET=utf8;
151                 ");
152     print "Upgrade to $DBversion done (adding tags and nozebra tables )\n";
153     SetVersion ($DBversion);
154 }
155
156 $DBversion = "3.00.00.006";
157 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
158     $dbh->do("UPDATE issues SET issuedate=timestamp WHERE issuedate='0000-00-00'");
159     print "Upgrade to $DBversion done (filled issues.issuedate with timestamp)\n";
160     SetVersion ($DBversion);
161 }
162
163 $DBversion = "3.00.00.007";
164 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
165     $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')");
166     print "Upgrade to $DBversion done (set SessionStorage variable)\n";
167     SetVersion ($DBversion);
168 }
169
170 $DBversion = "3.00.00.008";
171 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
172     $dbh->do("ALTER TABLE `biblio` ADD `datecreated` DATE NOT NULL AFTER `timestamp` ;");
173     $dbh->do("UPDATE biblio SET datecreated=timestamp");
174     print "Upgrade to $DBversion done (biblio creation date)\n";
175     SetVersion ($DBversion);
176 }
177
178 $DBversion = "3.00.00.009";
179 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
180
181     # Create backups of call number columns
182     # in case default migration needs to be customized
183     #
184     # UPGRADE NOTE: temp_upg_biblioitems_call_num should be dropped
185     #               after call numbers have been transformed to the new structure
186     #
187     # Not bothering to do the same with deletedbiblioitems -- assume
188     # default is good enough.
189     $dbh->do("CREATE TABLE `temp_upg_biblioitems_call_num` AS
190               SELECT `biblioitemnumber`, `biblionumber`,
191                      `classification`, `dewey`, `subclass`,
192                      `lcsort`, `ccode`
193               FROM `biblioitems`");
194
195     # biblioitems changes
196     $dbh->do("ALTER TABLE `biblioitems` CHANGE COLUMN `volumeddesc` `volumedesc` TEXT,
197                                     ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
198                                     ADD `cn_class` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
199                                     ADD `cn_item` VARCHAR(10) DEFAULT NULL AFTER `cn_class`,
200                                     ADD `cn_suffix` VARCHAR(10) DEFAULT NULL AFTER `cn_item`,
201                                     ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_suffix`,
202                                     ADD `totalissues` INT(10) AFTER `cn_sort`");
203
204     # default mapping of call number columns:
205     #   cn_class = concatentation of classification + dewey,
206     #              trimmed to fit -- assumes that most users do not
207     #              populate both classification and dewey in a single record
208     #   cn_item  = subclass
209     #   cn_source = left null
210     #   cn_sort = lcsort
211     #
212     # After upgrade, cn_sort will have to be set based on whatever
213     # default call number scheme user sets as a preference.  Misc
214     # script will be added at some point to do that.
215     #
216     $dbh->do("UPDATE `biblioitems`
217               SET cn_class = SUBSTR(TRIM(CONCAT_WS(' ', `classification`, `dewey`)), 1, 30),
218                     cn_item = subclass,
219                     `cn_sort` = `lcsort`
220             ");
221
222     # Now drop the old call number columns
223     $dbh->do("ALTER TABLE `biblioitems` DROP COLUMN `classification`,
224                                         DROP COLUMN `dewey`,
225                                         DROP COLUMN `subclass`,
226                                         DROP COLUMN `lcsort`,
227                                         DROP COLUMN `ccode`");
228
229     # deletedbiblio changes
230     $dbh->do("ALTER TABLE `deletedbiblio` ALTER COLUMN `frameworkcode` SET DEFAULT '',
231                                         DROP COLUMN `marc`,
232                                         ADD `datecreated` DATE NOT NULL AFTER `timestamp`");
233     $dbh->do("UPDATE deletedbiblio SET datecreated = timestamp");
234
235     # deletedbiblioitems changes
236     $dbh->do("ALTER TABLE `deletedbiblioitems`
237                         MODIFY `publicationyear` TEXT,
238                         CHANGE `volumeddesc` `volumedesc` TEXT,
239                         MODIFY `collectiontitle` MEDIUMTEXT DEFAULT NULL AFTER `volumedesc`,
240                         MODIFY `collectionissn` TEXT DEFAULT NULL AFTER `collectiontitle`,
241                         MODIFY `collectionvolume` MEDIUMTEXT DEFAULT NULL AFTER `collectionissn`,
242                         MODIFY `editionstatement` TEXT DEFAULT NULL AFTER `collectionvolume`,
243                         MODIFY `editionresponsibility` TEXT DEFAULT NULL AFTER `editionstatement`,
244                         MODIFY `place` VARCHAR(255) DEFAULT NULL AFTER `size`,
245                         MODIFY `marc` LONGBLOB,
246                         ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `url`,
247                         ADD `cn_class` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
248                         ADD `cn_item` VARCHAR(10) DEFAULT NULL AFTER `cn_class`,
249                         ADD `cn_suffix` VARCHAR(10) DEFAULT NULL AFTER `cn_item`,
250                         ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_suffix`,
251                         ADD `totalissues` INT(10) AFTER `cn_sort`,
252                         ADD `marcxml` LONGTEXT NOT NULL AFTER `totalissues`,
253                         ADD KEY `isbn` (`isbn`),
254                         ADD KEY `publishercode` (`publishercode`)
255                     ");
256
257     $dbh->do("UPDATE `deletedbiblioitems`
258                 SET `cn_class` = SUBSTR(TRIM(CONCAT_WS(' ', `classification`, `dewey`)), 1, 30),
259                `cn_item` = `subclass`,
260                 `cn_sort` = `lcsort`
261             ");
262     $dbh->do("ALTER TABLE `deletedbiblioitems`
263                         DROP COLUMN `classification`,
264                         DROP COLUMN `dewey`,
265                         DROP COLUMN `subclass`,
266                         DROP COLUMN `lcsort`,
267                         DROP COLUMN `ccode`
268             ");
269
270     # deleteditems changes
271     $dbh->do("ALTER TABLE `deleteditems`
272                         MODIFY `barcode` VARCHAR(20) DEFAULT NULL,
273                         MODIFY `price` DECIMAL(8,2) DEFAULT NULL,
274                         MODIFY `replacementprice` DECIMAL(8,2) DEFAULT NULL,
275                         DROP `bulk`,
276                         MODIFY `itemcallnumber` VARCHAR(30) DEFAULT NULL AFTER `wthdrawn`,
277                         MODIFY `holdingbranch` VARCHAR(10) DEFAULT NULL,
278                         DROP `interim`,
279                         MODIFY `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP AFTER `paidfor`,
280                         DROP `cutterextra`,
281                         ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `onloan`,
282                         ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
283                         ADD `ccode` VARCHAR(10) DEFAULT NULL AFTER `cn_sort`,
284                         ADD `materials` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
285                         ADD `uri` VARCHAR(255) DEFAULT NULL AFTER `materials`,
286                         MODIFY `marc` LONGBLOB AFTER `uri`,
287                         DROP KEY `barcode`,
288                         DROP KEY `itembarcodeidx`,
289                         DROP KEY `itembinoidx`,
290                         DROP KEY `itembibnoidx`,
291                         ADD UNIQUE KEY `delitembarcodeidx` (`barcode`),
292                         ADD KEY `delitembinoidx` (`biblioitemnumber`),
293                         ADD KEY `delitembibnoidx` (`biblionumber`),
294                         ADD KEY `delhomebranch` (`homebranch`),
295                         ADD KEY `delholdingbranch` (`holdingbranch`)");
296     $dbh->do("UPDATE deleteditems SET `ccode` = `itype`");
297     $dbh->do("ALTER TABLE deleteditems DROP `itype`");
298     $dbh->do("UPDATE `deleteditems` SET `cn_sort` = `itemcallnumber`");
299
300     # items changes
301     $dbh->do("ALTER TABLE `items` ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `onloan`,
302                                 ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
303                                 ADD `ccode` VARCHAR(10) DEFAULT NULL AFTER `cn_sort`,
304                                 ADD `materials` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
305                                 ADD `uri` VARCHAR(255) DEFAULT NULL AFTER `materials`
306             ");
307     $dbh->do("ALTER TABLE `items`
308                         DROP KEY `itembarcodeidx`,
309                         ADD UNIQUE KEY `itembarcodeidx` (`barcode`)");
310
311     # map items.itype to items.ccode and
312     # set cn_sort to itemcallnumber -- as with biblioitems.cn_sort,
313     # will have to be subsequently updated per user's default
314     # classification scheme
315     $dbh->do("UPDATE `items` SET `cn_sort` = `itemcallnumber`,
316                             `ccode` = `itype`");
317
318     $dbh->do("ALTER TABLE `items` DROP `cutterextra`,
319                                 DROP `itype`");
320
321     print "Upgrade to $DBversion done (major changes to biblio, biblioitems, items, and deleted* versions of same\n";
322     SetVersion ($DBversion);
323 }
324
325 $DBversion = "3.00.00.010";
326 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
327     $dbh->do("CREATE INDEX `userid` ON borrowers (`userid`) ");
328     print "Upgrade to $DBversion done (userid index added)\n";
329     SetVersion ($DBversion);
330 }
331
332 $DBversion = "3.00.00.011";
333 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
334     $dbh->do("ALTER TABLE `branchcategories` CHANGE `categorycode` `categorycode` varchar(10) ");
335     $dbh->do("ALTER TABLE `branchcategories` CHANGE `categoryname` `categoryname` varchar(32) ");
336     $dbh->do("ALTER TABLE `branchcategories` ADD COLUMN `categorytype` varchar(16) ");
337     $dbh->do("UPDATE `branchcategories` SET `categorytype` = 'properties'");
338     $dbh->do("ALTER TABLE `branchrelations` CHANGE `categorycode` `categorycode` varchar(10) ");
339     print "Upgrade to $DBversion done (added branchcategory type)\n";
340     SetVersion ($DBversion);
341 }
342
343 $DBversion = "3.00.00.012";
344 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
345     $dbh->do("CREATE TABLE `class_sort_rules` (
346                                `class_sort_rule` varchar(10) NOT NULL default '',
347                                `description` mediumtext,
348                                `sort_routine` varchar(30) NOT NULL default '',
349                                PRIMARY KEY (`class_sort_rule`),
350                                UNIQUE KEY `class_sort_rule_idx` (`class_sort_rule`)
351                              ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
352     $dbh->do("CREATE TABLE `class_sources` (
353                                `cn_source` varchar(10) NOT NULL default '',
354                                `description` mediumtext,
355                                `used` tinyint(4) NOT NULL default 0,
356                                `class_sort_rule` varchar(10) NOT NULL default '',
357                                PRIMARY KEY (`cn_source`),
358                                UNIQUE KEY `cn_source_idx` (`cn_source`),
359                                KEY `used_idx` (`used`),
360                                CONSTRAINT `class_source_ibfk_1` FOREIGN KEY (`class_sort_rule`)
361                                           REFERENCES `class_sort_rules` (`class_sort_rule`)
362                              ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
363     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type)
364               VALUES('DefaultClassificationSource','ddc',
365                      'Default classification scheme used by the collection. E.g., Dewey, LCC, etc.', NULL,'free')");
366     $dbh->do("INSERT INTO `class_sort_rules` (`class_sort_rule`, `description`, `sort_routine`) VALUES
367                                ('dewey', 'Default filing rules for DDC', 'Dewey'),
368                                ('lcc', 'Default filing rules for LCC', 'LCC'),
369                                ('generic', 'Generic call number filing rules', 'Generic')");
370     $dbh->do("INSERT INTO `class_sources` (`cn_source`, `description`, `used`, `class_sort_rule`) VALUES
371                             ('ddc', 'Dewey Decimal Classification', 1, 'dewey'),
372                             ('lcc', 'Library of Congress Classification', 1, 'lcc'),
373                             ('udc', 'Universal Decimal Classification', 0, 'generic'),
374                             ('sudocs', 'SuDoc Classification (U.S. GPO)', 0, 'generic'),
375                             ('z', 'Other/Generic Classification Scheme', 0, 'generic')");
376     print "Upgrade to $DBversion done (classification sources added)\n";
377     SetVersion ($DBversion);
378 }
379
380 $DBversion = "3.00.00.013";
381 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
382     $dbh->do("CREATE TABLE `import_batches` (
383               `import_batch_id` int(11) NOT NULL auto_increment,
384               `template_id` int(11) default NULL,
385               `branchcode` varchar(10) default NULL,
386               `num_biblios` int(11) NOT NULL default 0,
387               `num_items` int(11) NOT NULL default 0,
388               `upload_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
389               `overlay_action` enum('replace', 'create_new', 'use_template') NOT NULL default 'create_new',
390               `import_status` enum('staging', 'staged', 'importing', 'imported', 'reverting', 'reverted', 'cleaned') NOT NULL default 'staging',
391               `batch_type` enum('batch', 'z3950') NOT NULL default 'batch',
392               `file_name` varchar(100),
393               `comments` mediumtext,
394               PRIMARY KEY (`import_batch_id`),
395               KEY `branchcode` (`branchcode`)
396               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
397     $dbh->do("CREATE TABLE `import_records` (
398               `import_record_id` int(11) NOT NULL auto_increment,
399               `import_batch_id` int(11) NOT NULL,
400               `branchcode` varchar(10) default NULL,
401               `record_sequence` int(11) NOT NULL default 0,
402               `upload_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
403               `import_date` DATE default NULL,
404               `marc` longblob NOT NULL,
405               `marcxml` longtext NOT NULL,
406               `marcxml_old` longtext NOT NULL,
407               `record_type` enum('biblio', 'auth', 'holdings') NOT NULL default 'biblio',
408               `overlay_status` enum('no_match', 'auto_match', 'manual_match', 'match_applied') NOT NULL default 'no_match',
409               `status` enum('error', 'staged', 'imported', 'reverted', 'items_reverted') NOT NULL default 'staged',
410               `import_error` mediumtext,
411               `encoding` varchar(40) NOT NULL default '',
412               `z3950random` varchar(40) default NULL,
413               PRIMARY KEY (`import_record_id`),
414               CONSTRAINT `import_records_ifbk_1` FOREIGN KEY (`import_batch_id`)
415                           REFERENCES `import_batches` (`import_batch_id`) ON DELETE CASCADE ON UPDATE CASCADE,
416               KEY `branchcode` (`branchcode`),
417               KEY `batch_sequence` (`import_batch_id`, `record_sequence`)
418               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
419     $dbh->do("CREATE TABLE `import_record_matches` (
420               `import_record_id` int(11) NOT NULL,
421               `candidate_match_id` int(11) NOT NULL,
422               `score` int(11) NOT NULL default 0,
423               CONSTRAINT `import_record_matches_ibfk_1` FOREIGN KEY (`import_record_id`)
424                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
425               KEY `record_score` (`import_record_id`, `score`)
426               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
427     $dbh->do("CREATE TABLE `import_biblios` (
428               `import_record_id` int(11) NOT NULL,
429               `matched_biblionumber` int(11) default NULL,
430               `control_number` varchar(25) default NULL,
431               `original_source` varchar(25) default NULL,
432               `title` varchar(128) default NULL,
433               `author` varchar(80) default NULL,
434               `isbn` varchar(14) default NULL,
435               `issn` varchar(9) default NULL,
436               `has_items` tinyint(1) NOT NULL default 0,
437               CONSTRAINT `import_biblios_ibfk_1` FOREIGN KEY (`import_record_id`)
438                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
439               KEY `matched_biblionumber` (`matched_biblionumber`),
440               KEY `title` (`title`),
441               KEY `isbn` (`isbn`)
442               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
443     $dbh->do("CREATE TABLE `import_items` (
444               `import_items_id` int(11) NOT NULL auto_increment,
445               `import_record_id` int(11) NOT NULL,
446               `itemnumber` int(11) default NULL,
447               `branchcode` varchar(10) default NULL,
448               `status` enum('error', 'staged', 'imported', 'reverted') NOT NULL default 'staged',
449               `marcxml` longtext NOT NULL,
450               `import_error` mediumtext,
451               PRIMARY KEY (`import_items_id`),
452               CONSTRAINT `import_items_ibfk_1` FOREIGN KEY (`import_record_id`)
453                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
454               KEY `itemnumber` (`itemnumber`),
455               KEY `branchcode` (`branchcode`)
456               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
457
458     $dbh->do("INSERT INTO `import_batches`
459                 (`overlay_action`, `import_status`, `batch_type`, `file_name`)
460               SELECT distinct 'create_new', 'staged', 'z3950', `file`
461               FROM   `marc_breeding`");
462
463     $dbh->do("INSERT INTO `import_records`
464                 (`import_batch_id`, `import_record_id`, `record_sequence`, `marc`, `record_type`, `status`,
465                 `encoding`, `z3950random`, `marcxml`, `marcxml_old`)
466               SELECT `import_batch_id`, `id`, 1, `marc`, 'biblio', 'staged', `encoding`, `z3950random`, '', ''
467               FROM `marc_breeding`
468               JOIN `import_batches` ON (`file_name` = `file`)");
469
470     $dbh->do("INSERT INTO `import_biblios`
471                 (`import_record_id`, `title`, `author`, `isbn`)
472               SELECT `import_record_id`, `title`, `author`, `isbn`
473               FROM   `marc_breeding`
474               JOIN   `import_records` ON (`import_record_id` = `id`)");
475
476     $dbh->do("UPDATE `import_batches`
477               SET `num_biblios` = (
478               SELECT COUNT(*)
479               FROM `import_records`
480               WHERE `import_batch_id` = `import_batches`.`import_batch_id`
481               )");
482
483     $dbh->do("DROP TABLE `marc_breeding`");
484
485     print "Upgrade to $DBversion done (import_batches et al. added)\n";
486     SetVersion ($DBversion);
487 }
488
489 $DBversion = "3.00.00.014";
490 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
491     $dbh->do("ALTER TABLE subscription ADD lastbranch VARCHAR(4)");
492     print "Upgrade to $DBversion done (userid index added)\n";
493     SetVersion ($DBversion);
494 }
495
496 $DBversion = "3.00.00.015";
497 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
498     $dbh->do("CREATE TABLE `saved_sql` (
499            `id` int(11) NOT NULL auto_increment,
500            `borrowernumber` int(11) default NULL,
501            `date_created` datetime default NULL,
502            `last_modified` datetime default NULL,
503            `savedsql` text,
504            `last_run` datetime default NULL,
505            `report_name` varchar(255) default NULL,
506            `type` varchar(255) default NULL,
507            `notes` text,
508            PRIMARY KEY  (`id`),
509            KEY boridx (`borrowernumber`)
510         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
511     $dbh->do("CREATE TABLE `saved_reports` (
512            `id` int(11) NOT NULL auto_increment,
513            `report_id` int(11) default NULL,
514            `report` longtext,
515            `date_run` datetime default NULL,
516            PRIMARY KEY  (`id`)
517         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
518     print "Upgrade to $DBversion done (saved_sql and saved_reports added)\n";
519     SetVersion ($DBversion);
520 }
521
522 $DBversion = "3.00.00.016";
523 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
524     $dbh->do(" CREATE TABLE reports_dictionary (
525           id int(11) NOT NULL auto_increment,
526           name varchar(255) default NULL,
527           description text,
528           date_created datetime default NULL,
529           date_modified datetime default NULL,
530           saved_sql text,
531           area int(11) default NULL,
532           PRIMARY KEY  (id)
533         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
534     print "Upgrade to $DBversion done (reports_dictionary) added)\n";
535     SetVersion ($DBversion);
536 }
537
538 $DBversion = "3.00.00.017";
539 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
540     $dbh->do("ALTER TABLE action_logs DROP PRIMARY KEY");
541     $dbh->do("ALTER TABLE action_logs ADD KEY  timestamp (timestamp,user)");
542     $dbh->do("ALTER TABLE action_logs ADD action_id INT(11) NOT NULL FIRST");
543     $dbh->do("UPDATE action_logs SET action_id = if (\@a, \@a:=\@a+1, \@a:=1)");
544     $dbh->do("ALTER TABLE action_logs MODIFY action_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY");
545     print "Upgrade to $DBversion done (added column to action_logs)\n";
546     SetVersion ($DBversion);
547 }
548
549 $DBversion = "3.00.00.018";
550 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
551     $dbh->do("ALTER TABLE `zebraqueue`
552                     ADD `done` INT NOT NULL DEFAULT '0',
553                     ADD `time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ;
554             ");
555     print "Upgrade to $DBversion done (adding timestamp and done columns to zebraque table to improve problem tracking) added)\n";
556     SetVersion ($DBversion);
557 }
558
559 $DBversion = "3.00.00.019";
560 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
561     $dbh->do("ALTER TABLE biblio MODIFY biblionumber INT(11) NOT NULL AUTO_INCREMENT");
562     $dbh->do("ALTER TABLE biblioitems MODIFY biblioitemnumber INT(11) NOT NULL AUTO_INCREMENT");
563     $dbh->do("ALTER TABLE items MODIFY itemnumber INT(11) NOT NULL AUTO_INCREMENT");
564     print "Upgrade to $DBversion done (made bib/item PKs auto_increment)\n";
565     SetVersion ($DBversion);
566 }
567
568 $DBversion = "3.00.00.020";
569 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
570     $dbh->do("ALTER TABLE deleteditems
571               DROP KEY `delitembarcodeidx`,
572               ADD KEY `delitembarcodeidx` (`barcode`)");
573     print "Upgrade to $DBversion done (dropped uniqueness of key on deleteditems.barcode)\n";
574     SetVersion ($DBversion);
575 }
576
577 $DBversion = "3.00.00.021";
578 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
579     $dbh->do("ALTER TABLE items CHANGE homebranch homebranch VARCHAR(10)");
580     $dbh->do("ALTER TABLE deleteditems CHANGE homebranch homebranch VARCHAR(10)");
581     $dbh->do("ALTER TABLE statistics CHANGE branch branch VARCHAR(10)");
582     $dbh->do("ALTER TABLE subscription CHANGE lastbranch lastbranch VARCHAR(10)");
583     print "Upgrade to $DBversion done (extended missed branchcode columns to 10 chars)\n";
584     SetVersion ($DBversion);
585 }
586
587 $DBversion = "3.00.00.022";
588 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
589     $dbh->do("ALTER TABLE items
590                 ADD `damaged` tinyint(1) default NULL AFTER notforloan");
591     $dbh->do("ALTER TABLE deleteditems
592                 ADD `damaged` tinyint(1) default NULL AFTER notforloan");
593     print "Upgrade to $DBversion done (adding damaged column to items table)\n";
594     SetVersion ($DBversion);
595 }
596
597 $DBversion = "3.00.00.023";
598 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
599      $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
600          VALUES ('yuipath','http://yui.yahooapis.com/2.3.1/build','Insert the path to YUI libraries','','free')");
601     print "Upgrade to $DBversion done (adding new system preference for controlling YUI path)\n";
602     SetVersion ($DBversion);
603 }
604 $DBversion = "3.00.00.024";
605 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
606     $dbh->do("ALTER TABLE biblioitems CHANGE  itemtype itemtype VARCHAR(10)");
607     print "Upgrade to $DBversion done (changing itemtype to (10))\n";
608     SetVersion ($DBversion);
609 }
610
611 $DBversion = "3.00.00.025";
612 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
613     $dbh->do("ALTER TABLE items ADD COLUMN itype VARCHAR(10)");
614     $dbh->do("ALTER TABLE deleteditems ADD COLUMN itype VARCHAR(10) AFTER uri");
615     if(C4::Context->preference('item-level_itypes')){
616         $dbh->do('update items,biblioitems set items.itype=biblioitems.itemtype where items.biblionumber=biblioitems.biblionumber and itype is null');
617     }
618     print "Upgrade to $DBversion done (reintroduce items.itype - fill from itemtype)\n ";
619     SetVersion ($DBversion);
620 }
621
622 $DBversion = "3.00.00.026";
623 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
624     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
625        VALUES ('HomeOrHoldingBranch','homebranch','homebranch|holdingbranch','With independent branches turned on this decides whether to check the items holdingbranch or homebranch at circulatilon','choice')");
626     print "Upgrade to $DBversion done (adding new system preference for choosing whether homebranch or holdingbranch is checked in circulation)\n";
627     SetVersion ($DBversion);
628 }
629
630 $DBversion = "3.00.00.027";
631 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
632     $dbh->do("CREATE TABLE `marc_matchers` (
633                 `matcher_id` int(11) NOT NULL auto_increment,
634                 `code` varchar(10) NOT NULL default '',
635                 `description` varchar(255) NOT NULL default '',
636                 `record_type` varchar(10) NOT NULL default 'biblio',
637                 `threshold` int(11) NOT NULL default 0,
638                 PRIMARY KEY (`matcher_id`),
639                 KEY `code` (`code`),
640                 KEY `record_type` (`record_type`)
641               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
642     $dbh->do("CREATE TABLE `matchpoints` (
643                 `matcher_id` int(11) NOT NULL,
644                 `matchpoint_id` int(11) NOT NULL auto_increment,
645                 `search_index` varchar(30) NOT NULL default '',
646                 `score` int(11) NOT NULL default 0,
647                 PRIMARY KEY (`matchpoint_id`),
648                 CONSTRAINT `matchpoints_ifbk_1` FOREIGN KEY (`matcher_id`)
649                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE
650               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
651     $dbh->do("CREATE TABLE `matchpoint_components` (
652                 `matchpoint_id` int(11) NOT NULL,
653                 `matchpoint_component_id` int(11) NOT NULL auto_increment,
654                 sequence int(11) NOT NULL default 0,
655                 tag varchar(3) NOT NULL default '',
656                 subfields varchar(40) NOT NULL default '',
657                 offset int(4) NOT NULL default 0,
658                 length int(4) NOT NULL default 0,
659                 PRIMARY KEY (`matchpoint_component_id`),
660                 KEY `by_sequence` (`matchpoint_id`, `sequence`),
661                 CONSTRAINT `matchpoint_components_ifbk_1` FOREIGN KEY (`matchpoint_id`)
662                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
663               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
664     $dbh->do("CREATE TABLE `matchpoint_component_norms` (
665                 `matchpoint_component_id` int(11) NOT NULL,
666                 `sequence`  int(11) NOT NULL default 0,
667                 `norm_routine` varchar(50) NOT NULL default '',
668                 KEY `matchpoint_component_norms` (`matchpoint_component_id`, `sequence`),
669                 CONSTRAINT `matchpoint_component_norms_ifbk_1` FOREIGN KEY (`matchpoint_component_id`)
670                            REFERENCES `matchpoint_components` (`matchpoint_component_id`) ON DELETE CASCADE ON UPDATE CASCADE
671               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
672     $dbh->do("CREATE TABLE `matcher_matchpoints` (
673                 `matcher_id` int(11) NOT NULL,
674                 `matchpoint_id` int(11) NOT NULL,
675                 CONSTRAINT `matcher_matchpoints_ifbk_1` FOREIGN KEY (`matcher_id`)
676                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE,
677                 CONSTRAINT `matcher_matchpoints_ifbk_2` FOREIGN KEY (`matchpoint_id`)
678                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
679               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
680     $dbh->do("CREATE TABLE `matchchecks` (
681                 `matcher_id` int(11) NOT NULL,
682                 `matchcheck_id` int(11) NOT NULL auto_increment,
683                 `source_matchpoint_id` int(11) NOT NULL,
684                 `target_matchpoint_id` int(11) NOT NULL,
685                 PRIMARY KEY (`matchcheck_id`),
686                 CONSTRAINT `matcher_matchchecks_ifbk_1` FOREIGN KEY (`matcher_id`)
687                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE,
688                 CONSTRAINT `matcher_matchchecks_ifbk_2` FOREIGN KEY (`source_matchpoint_id`)
689                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE,
690                 CONSTRAINT `matcher_matchchecks_ifbk_3` FOREIGN KEY (`target_matchpoint_id`)
691                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
692               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
693     print "Upgrade to $DBversion done (added C4::Matcher serialization tables)\n ";
694     SetVersion ($DBversion);
695 }
696
697 $DBversion = "3.00.00.028";
698 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
699     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
700        VALUES ('canreservefromotherbranches','1','','With Independent branches on, can a user from one library reserve an item from another library','YesNo')");
701     print "Upgrade to $DBversion done (adding new system preference for changing reserve/holds behaviour with independent branches)\n";
702     SetVersion ($DBversion);
703 }
704
705
706 $DBversion = "3.00.00.029";
707 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
708     $dbh->do("ALTER TABLE `import_batches` ADD `matcher_id` int(11) NULL AFTER `import_batch_id`");
709     print "Upgrade to $DBversion done (adding matcher_id to import_batches)\n";
710     SetVersion ($DBversion);
711 }
712
713 $DBversion = "3.00.00.030";
714 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
715     $dbh->do("
716 CREATE TABLE services_throttle (
717   service_type varchar(10) NOT NULL default '',
718   service_count varchar(45) default NULL,
719   PRIMARY KEY  (service_type)
720 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
721 ");
722     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
723        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')");
724  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
725        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')");
726  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
727        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')");
728  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
729        VALUES ('XISBNDailyLimit',499,'','The xISBN Web service is free for non-commercial use when usage does not exceed 500 requests per day','free')");
730  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
731        VALUES ('PINESISBN',0,'','Use with FRBRizeEditions. If ON, Koha will use PINES OISBN web service in the Editions tab on the detail pages.','YesNo')");
732  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
733        VALUES ('ThingISBN',0,'','Use with FRBRizeEditions. If ON, Koha will use the ThingISBN web service in the Editions tab on the detail pages.','YesNo')");
734     print "Upgrade to $DBversion done (adding services throttle table and sysprefs for xISBN)\n";
735     SetVersion ($DBversion);
736 }
737
738 $DBversion = "3.00.00.031";
739 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
740
741 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryStemming',1,'If ON, enables query stemming',NULL,'YesNo')");
742 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryFuzzy',1,'If ON, enables fuzzy option for searches',NULL,'YesNo')");
743 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryWeightFields',1,'If ON, enables field weighting',NULL,'YesNo')");
744 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('WebBasedSelfCheck',0,'If ON, enables the web-based self-check system',NULL,'YesNo')");
745 $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')");
746 $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')");
747 $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')");
748 $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')");
749 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('defaultSortOrder',NULL,'Specify the default sort order','asc|dsc|az|za','Choice')");
750 $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')");
751 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACdefaultSortOrder',NULL,'Specify the default sort order','asc|dsc|za|az','Choice')");
752 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('staffClientBaseURL','','Specify the base URL of the staff client',NULL,'free')");
753 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('minPasswordLength',3,'Specify the minimum length of a patron/staff password',NULL,'free')");
754 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('noItemTypeImages',0,'If ON, disables item-type images',NULL,'YesNo')");
755 $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')");
756 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('holdCancelLength','','Specify how many days before a hold is canceled',NULL,'free')");
757 $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')");
758 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('finesMode','test','Choose the fines mode, test or production','test|production','Choice')");
759 $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')");
760 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('itemBarcodeInputFilter','','If set, allows specification of a item barcode input filter','cuecat','Choice')");
761 $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')");
762 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('URLLinkText','','Text to display as the link anchor in the OPAC',NULL,'free')");
763 $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')");
764 $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')");
765 $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')");
766 $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')");
767 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACUserCSS',0,'Add CSS to be included in the OPAC',NULL,'free')");
768
769     print "Upgrade to $DBversion done (adding additional system preference)\n";
770     SetVersion ($DBversion);
771 }
772
773 $DBversion = "3.00.00.032";
774 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
775     $dbh->do("UPDATE `marc_subfield_structure` SET `kohafield` = 'items.wthdrawn' WHERE `kohafield` = 'items.withdrawn'");
776     print "Upgrade to $DBversion done (fixed MARC framework references to items.withdrawn)\n";
777     SetVersion ($DBversion);
778 }
779
780 $DBversion = "3.00.00.033";
781 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
782     $dbh->do("INSERT INTO `userflags` VALUES(17,'staffaccess','Modify login / permissions for staff users',0)");
783     print "Upgrade to $DBversion done (Adding permissions flag for staff member access modification.  )\n";
784     SetVersion ($DBversion);
785 }
786
787 $DBversion = "3.00.00.034";
788 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
789     $dbh->do("ALTER TABLE `virtualshelves` ADD COLUMN `sortfield` VARCHAR(16) ");
790     print "Upgrade to $DBversion done (Adding sortfield for Virtual Shelves.  )\n";
791     SetVersion ($DBversion);
792 }
793
794 $DBversion = "3.00.00.035";
795 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
796     $dbh->do("UPDATE marc_subfield_structure
797               SET authorised_value = 'cn_source'
798               WHERE kohafield IN ('items.cn_source', 'biblioitems.cn_source')
799               AND (authorised_value is NULL OR authorised_value = '')");
800     print "Upgrade to $DBversion done (MARC frameworks: make classification source a drop-down)\n";
801     SetVersion ($DBversion);
802 }
803
804 $DBversion = "3.00.00.036";
805 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
806     $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');");
807     print "Upgrade to $DBversion done (OPACItemsResultsDisplay systempreference added)\n";
808     SetVersion ($DBversion);
809 }
810
811 $DBversion = "3.00.00.037";
812 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
813     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactfirstname` varchar(255)");
814     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactsurname` varchar(255)");
815     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress1` varchar(255)");
816     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress2` varchar(255)");
817     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress3` varchar(255)");
818     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactzipcode` varchar(50)");
819     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactphone` varchar(50)");
820     print "Upgrade to $DBversion done (Adding Alternative Contact Person information to borrowers table)\n";
821     SetVersion ($DBversion);
822 }
823
824 $DBversion = "3.00.00.038";
825 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
826     $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'");
827     $dbh->do("DELETE FROM `systempreferences` WHERE variable='hideBiblioNumber'");
828     print "Upgrade to $DBversion done ('alter finesMode systempreference, remove superfluous syspref.')\n";
829     SetVersion ($DBversion);
830 }
831
832 $DBversion = "3.00.00.039";
833 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
834     $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')");
835     $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')");
836     $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')");
837     # $dbh->do("DELETE FROM `systempreferences` WHERE variable='HomeOrHoldingBranch'"); # Bug #2752
838     print "Upgrade to $DBversion done ('add circ sysprefs CircControl, finesCalendar, and uppercasesurnames, and delete HomeOrHoldingBranch.')\n";
839     SetVersion ($DBversion);
840 }
841
842 $DBversion = "3.00.00.040";
843 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
844         $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')");
845         $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')");
846         print "Upgrade to $DBversion done ('add circ sysprefs todaysIssuesDefaultSortOrder and previousIssuesDefaultSortOrder.')\n";
847     SetVersion ($DBversion);
848 }
849
850
851 $DBversion = "3.00.00.041";
852 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
853     # Strictly speaking it is not necessary to explicitly change
854     # NULL values to 0, because the ALTER TABLE statement will do that.
855     # However, setting them first avoids a warning.
856     $dbh->do("UPDATE items SET notforloan = 0 WHERE notforloan IS NULL");
857     $dbh->do("UPDATE items SET damaged = 0 WHERE damaged IS NULL");
858     $dbh->do("UPDATE items SET itemlost = 0 WHERE itemlost IS NULL");
859     $dbh->do("UPDATE items SET wthdrawn = 0 WHERE wthdrawn IS NULL");
860     $dbh->do("ALTER TABLE items
861                 MODIFY notforloan tinyint(1) NOT NULL default 0,
862                 MODIFY damaged    tinyint(1) NOT NULL default 0,
863                 MODIFY itemlost   tinyint(1) NOT NULL default 0,
864                 MODIFY wthdrawn   tinyint(1) NOT NULL default 0");
865     $dbh->do("UPDATE deleteditems SET notforloan = 0 WHERE notforloan IS NULL");
866     $dbh->do("UPDATE deleteditems SET damaged = 0 WHERE damaged IS NULL");
867     $dbh->do("UPDATE deleteditems SET itemlost = 0 WHERE itemlost IS NULL");
868     $dbh->do("UPDATE deleteditems SET wthdrawn = 0 WHERE wthdrawn IS NULL");
869     $dbh->do("ALTER TABLE deleteditems
870                 MODIFY notforloan tinyint(1) NOT NULL default 0,
871                 MODIFY damaged    tinyint(1) NOT NULL default 0,
872                 MODIFY itemlost   tinyint(1) NOT NULL default 0,
873                 MODIFY wthdrawn   tinyint(1) NOT NULL default 0");
874         print "Upgrade to $DBversion done (disallow NULL in several item status columns)\n";
875     SetVersion ($DBversion);
876 }
877
878 $DBversion = "3.00.00.04";
879 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
880     $dbh->do("ALTER TABLE aqbooksellers CHANGE name name mediumtext NOT NULL");
881         print "Upgrade to $DBversion done (disallow NULL in aqbooksellers.name; part of fix for bug 1251)\n";
882     SetVersion ($DBversion);
883 }
884
885 $DBversion = "3.00.00.043";
886 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
887     $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");
888         print "Upgrade to $DBversion done (currency table: add symbol and timestamp columns)\n";
889     SetVersion ($DBversion);
890 }
891
892 $DBversion = "3.00.00.044";
893 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
894     $dbh->do("ALTER TABLE deletedborrowers
895   ADD `altcontactfirstname` varchar(255) default NULL,
896   ADD `altcontactsurname` varchar(255) default NULL,
897   ADD `altcontactaddress1` varchar(255) default NULL,
898   ADD `altcontactaddress2` varchar(255) default NULL,
899   ADD `altcontactaddress3` varchar(255) default NULL,
900   ADD `altcontactzipcode` varchar(50) default NULL,
901   ADD `altcontactphone` varchar(50) default NULL
902   ");
903   $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES
904 ('OPACBaseURL',NULL,'Specify the Base URL of the OPAC, e.g., opac.mylibrary.com, the http:// will be added automatically by Koha.',NULL,'Free'),
905 ('language','en','Set the default language in the staff client.',NULL,'Languages'),
906 ('QueryAutoTruncate',1,'If ON, query truncation is enabled by default',NULL,'YesNo'),
907 ('QueryRemoveStopwords',0,'If ON, stopwords listed in the Administration area will be removed from queries',NULL,'YesNo')
908   ");
909         print "Upgrade to $DBversion done (syncing deletedborrowers table with borrowers table)\n";
910     SetVersion ($DBversion);
911 }
912
913 #-- http://www.w3.org/International/articles/language-tags/
914
915 #-- RFC4646
916 $DBversion = "3.00.00.045";
917 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
918     $dbh->do("
919 CREATE TABLE language_subtag_registry (
920         subtag varchar(25),
921         type varchar(25), -- language-script-region-variant-extension-privateuse
922         description varchar(25), -- only one of the possible descriptions for ease of reference, see language_descriptions for the complete list
923         added date,
924         KEY `subtag` (`subtag`)
925 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
926
927 #-- TODO: add suppress_scripts
928 #-- this maps three letter codes defined in iso639.2 back to their
929 #-- two letter equivilents in rfc4646 (LOC maintains iso639+)
930  $dbh->do("CREATE TABLE language_rfc4646_to_iso639 (
931         rfc4646_subtag varchar(25),
932         iso639_2_code varchar(25),
933         KEY `rfc4646_subtag` (`rfc4646_subtag`)
934 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
935
936  $dbh->do("CREATE TABLE language_descriptions (
937         subtag varchar(25),
938         type varchar(25),
939         lang varchar(25),
940         description varchar(255),
941         KEY `lang` (`lang`)
942 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
943
944 #-- bi-directional support, keyed by script subcode
945  $dbh->do("CREATE TABLE language_script_bidi (
946         rfc4646_subtag varchar(25), -- script subtag, Arab, Hebr, etc.
947         bidi varchar(3), -- rtl ltr
948         KEY `rfc4646_subtag` (`rfc4646_subtag`)
949 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
950
951 #-- BIDI Stuff, Arabic and Hebrew
952  $dbh->do("INSERT INTO language_script_bidi(rfc4646_subtag,bidi)
953 VALUES( 'Arab', 'rtl')");
954  $dbh->do("INSERT INTO language_script_bidi(rfc4646_subtag,bidi)
955 VALUES( 'Hebr', 'rtl')");
956
957 #-- TODO: need to map language subtags to script subtags for detection
958 #-- of bidi when script is not specified (like ar, he)
959  $dbh->do("CREATE TABLE language_script_mapping (
960         language_subtag varchar(25),
961         script_subtag varchar(25),
962         KEY `language_subtag` (`language_subtag`)
963 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
964
965 #-- Default mappings between script and language subcodes
966  $dbh->do("INSERT INTO language_script_mapping(language_subtag,script_subtag)
967 VALUES( 'ar', 'Arab')");
968  $dbh->do("INSERT INTO language_script_mapping(language_subtag,script_subtag)
969 VALUES( 'he', 'Hebr')");
970
971         print "Upgrade to $DBversion done (adding language subtag registry and basic BiDi support NOTE: You should import the subtag registry SQL)\n";
972     SetVersion ($DBversion);
973 }
974
975 $DBversion = "3.00.00.046";
976 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
977     $dbh->do("ALTER TABLE `subscription` CHANGE `numberlength` `numberlength` int(11) default '0' ,
978                  CHANGE `weeklength` `weeklength` int(11) default '0'");
979     $dbh->do("CREATE TABLE `serialitems` (`serialid` int(11) NOT NULL, `itemnumber` int(11) NOT NULL, UNIQUE KEY `serialididx` (`serialid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
980     $dbh->do("INSERT INTO `serialitems` SELECT `serialid`,`itemnumber` from serial where NOT ISNULL(itemnumber) && itemnumber <> '' && itemnumber NOT LIKE '%,%'");
981         print "Upgrade to $DBversion done (Add serialitems table to link serial issues to items. )\n";
982     SetVersion ($DBversion);
983 }
984
985 $DBversion = "3.00.00.047";
986 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
987     $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');");
988         print "Upgrade to $DBversion done ( Added OpacRenewalAllowed syspref )\n";
989     SetVersion ($DBversion);
990 }
991
992 $DBversion = "3.00.00.048";
993 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
994     $dbh->do("ALTER TABLE `items` ADD `more_subfields_xml` longtext default NULL AFTER `itype`");
995         print "Upgrade to $DBversion done (added items.more_subfields_xml)\n";
996     SetVersion ($DBversion);
997 }
998
999 $DBversion = "3.00.00.049";
1000 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1001         $dbh->do("ALTER TABLE `z3950servers` ADD `encoding` text default NULL AFTER type ");
1002         print "Upgrade to $DBversion done ( Added encoding field to z3950servers table )\n";
1003     SetVersion ($DBversion);
1004 }
1005
1006 $DBversion = "3.00.00.050";
1007 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1008     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacHighlightedWords','0','If Set, query matched terms are highlighted in OPAC',NULL,'YesNo');");
1009         print "Upgrade to $DBversion done ( Added OpacHighlightedWords syspref )\n";
1010     SetVersion ($DBversion);
1011 }
1012
1013 $DBversion = "3.00.00.051";
1014 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1015     $dbh->do("UPDATE systempreferences SET explanation = 'Define the current theme for the OPAC interface.' WHERE variable = 'opacthemes';");
1016         print "Upgrade to $DBversion done ( Corrected opacthemes explanation. )\n";
1017     SetVersion ($DBversion);
1018 }
1019
1020 $DBversion = "3.00.00.052";
1021 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1022     $dbh->do("ALTER TABLE `deleteditems` ADD `more_subfields_xml` LONGTEXT DEFAULT NULL AFTER `itype`");
1023         print "Upgrade to $DBversion done ( Adding missing column to deleteditems table. )\n";
1024     SetVersion ($DBversion);
1025 }
1026
1027 $DBversion = "3.00.00.053";
1028 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1029     $dbh->do("CREATE TABLE `printers_profile` (
1030             `prof_id` int(4) NOT NULL auto_increment,
1031             `printername` varchar(40) NOT NULL,
1032             `tmpl_id` int(4) NOT NULL,
1033             `paper_bin` varchar(20) NOT NULL,
1034             `offset_horz` float default NULL,
1035             `offset_vert` float default NULL,
1036             `creep_horz` float default NULL,
1037             `creep_vert` float default NULL,
1038             `unit` char(20) NOT NULL default 'POINT',
1039             PRIMARY KEY  (`prof_id`),
1040             UNIQUE KEY `printername` (`printername`,`tmpl_id`,`paper_bin`),
1041             CONSTRAINT `printers_profile_pnfk_1` FOREIGN KEY (`tmpl_id`) REFERENCES `labels_templates` (`tmpl_id`) ON DELETE CASCADE ON UPDATE CASCADE
1042             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1043     $dbh->do("CREATE TABLE `labels_profile` (
1044             `tmpl_id` int(4) NOT NULL,
1045             `prof_id` int(4) NOT NULL,
1046             UNIQUE KEY `tmpl_id` (`tmpl_id`),
1047             UNIQUE KEY `prof_id` (`prof_id`)
1048             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1049     print "Upgrade to $DBversion done ( Printer Profile tables added )\n";
1050     SetVersion ($DBversion);
1051 }
1052
1053 $DBversion = "3.00.00.054";
1054 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1055     $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';");
1056         print "Upgrade to $DBversion done ( Added another barcode autogeneration sequence to barcode.pl. )\n";
1057     SetVersion ($DBversion);
1058 }
1059
1060 $DBversion = "3.00.00.055";
1061 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1062     $dbh->do("ALTER TABLE `zebraqueue` ADD KEY `zebraqueue_lookup` (`server`, `biblio_auth_number`, `operation`, `done`)");
1063         print "Upgrade to $DBversion done ( Added index on zebraqueue. )\n";
1064     SetVersion ($DBversion);
1065 }
1066 $DBversion = "3.00.00.056";
1067 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1068     if (C4::Context->preference("marcflavour") eq 'UNIMARC') {
1069         $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) ");
1070     } else {
1071         $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) ");
1072     }
1073     $dbh->do("ALTER TABLE `items` ADD `enumchron` VARCHAR(80) DEFAULT NULL;");
1074     print "Upgrade to $DBversion done ( Added item.enumchron column, and framework map to 952h )\n";
1075     SetVersion ($DBversion);
1076 }
1077
1078 $DBversion = "3.00.00.057";
1079 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1080     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH','0','if ON, OAI-PMH server is enabled',NULL,'YesNo');");
1081     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH:archiveID','KOHA-OAI-TEST','OAI-PMH archive identification',NULL,'Free');");
1082     $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');");
1083     $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');");
1084     $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');");
1085     SetVersion ($DBversion);
1086 }
1087
1088 $DBversion = "3.00.00.058";
1089 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1090     $dbh->do("ALTER TABLE `opac_news`
1091                 CHANGE `lang` `lang` VARCHAR( 25 )
1092                 CHARACTER SET utf8
1093                 COLLATE utf8_general_ci
1094                 NOT NULL default ''");
1095         print "Upgrade to $DBversion done ( lang field in opac_news made longer )\n";
1096     SetVersion ($DBversion);
1097 }
1098
1099 $DBversion = "3.00.00.059";
1100 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1101
1102     $dbh->do("CREATE TABLE IF NOT EXISTS `labels_templates` (
1103             `tmpl_id` int(4) NOT NULL auto_increment,
1104             `tmpl_code` char(100)  default '',
1105             `tmpl_desc` char(100) default '',
1106             `page_width` float default '0',
1107             `page_height` float default '0',
1108             `label_width` float default '0',
1109             `label_height` float default '0',
1110             `topmargin` float default '0',
1111             `leftmargin` float default '0',
1112             `cols` int(2) default '0',
1113             `rows` int(2) default '0',
1114             `colgap` float default '0',
1115             `rowgap` float default '0',
1116             `active` int(1) default NULL,
1117             `units` char(20)  default 'PX',
1118             `fontsize` int(4) NOT NULL default '3',
1119             PRIMARY KEY  (`tmpl_id`)
1120             ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1121     $dbh->do("CREATE TABLE  IF NOT EXISTS `printers_profile` (
1122             `prof_id` int(4) NOT NULL auto_increment,
1123             `printername` varchar(40) NOT NULL,
1124             `tmpl_id` int(4) NOT NULL,
1125             `paper_bin` varchar(20) NOT NULL,
1126             `offset_horz` float default NULL,
1127             `offset_vert` float default NULL,
1128             `creep_horz` float default NULL,
1129             `creep_vert` float default NULL,
1130             `unit` char(20) NOT NULL default 'POINT',
1131             PRIMARY KEY  (`prof_id`),
1132             UNIQUE KEY `printername` (`printername`,`tmpl_id`,`paper_bin`),
1133             CONSTRAINT `printers_profile_pnfk_1` FOREIGN KEY (`tmpl_id`) REFERENCES `labels_templates` (`tmpl_id`) ON DELETE CASCADE ON UPDATE CASCADE
1134             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1135     print "Upgrade to $DBversion done ( Added labels_templates table if it did not exist. )\n";
1136     SetVersion ($DBversion);
1137 }
1138
1139 $DBversion = "3.00.00.060";
1140 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1141     $dbh->do("CREATE TABLE IF NOT EXISTS `patronimage` (
1142             `cardnumber` varchar(16) NOT NULL,
1143             `mimetype` varchar(15) NOT NULL,
1144             `imagefile` mediumblob NOT NULL,
1145             PRIMARY KEY  (`cardnumber`),
1146             CONSTRAINT `patronimage_fk1` FOREIGN KEY (`cardnumber`) REFERENCES `borrowers` (`cardnumber`) ON DELETE CASCADE ON UPDATE CASCADE
1147             ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1148         print "Upgrade to $DBversion done ( Added patronimage table. )\n";
1149     SetVersion ($DBversion);
1150 }
1151
1152 $DBversion = "3.00.00.061";
1153 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1154     $dbh->do("ALTER TABLE labels_templates ADD COLUMN font char(10) NOT NULL DEFAULT 'TR';");
1155         print "Upgrade to $DBversion done ( Added font column to labels_templates )\n";
1156     SetVersion ($DBversion);
1157 }
1158
1159 $DBversion = "3.00.00.062";
1160 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1161     $dbh->do("CREATE TABLE `old_issues` (
1162                 `borrowernumber` int(11) default NULL,
1163                 `itemnumber` int(11) default NULL,
1164                 `date_due` date default NULL,
1165                 `branchcode` varchar(10) default NULL,
1166                 `issuingbranch` varchar(18) default NULL,
1167                 `returndate` date default NULL,
1168                 `lastreneweddate` date default NULL,
1169                 `return` varchar(4) default NULL,
1170                 `renewals` tinyint(4) default NULL,
1171                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1172                 `issuedate` date default NULL,
1173                 KEY `old_issuesborridx` (`borrowernumber`),
1174                 KEY `old_issuesitemidx` (`itemnumber`),
1175                 KEY `old_bordate` (`borrowernumber`,`timestamp`),
1176                 CONSTRAINT `old_issues_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1177                     ON DELETE SET NULL ON UPDATE SET NULL,
1178                 CONSTRAINT `old_issues_ibfk_2` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`)
1179                     ON DELETE SET NULL ON UPDATE SET NULL
1180                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1181     $dbh->do("CREATE TABLE `old_reserves` (
1182                 `borrowernumber` int(11) default NULL,
1183                 `reservedate` date default NULL,
1184                 `biblionumber` int(11) default NULL,
1185                 `constrainttype` varchar(1) default NULL,
1186                 `branchcode` varchar(10) default NULL,
1187                 `notificationdate` date default NULL,
1188                 `reminderdate` date default NULL,
1189                 `cancellationdate` date default NULL,
1190                 `reservenotes` mediumtext,
1191                 `priority` smallint(6) default NULL,
1192                 `found` varchar(1) default NULL,
1193                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1194                 `itemnumber` int(11) default NULL,
1195                 `waitingdate` date default NULL,
1196                 KEY `old_reserves_borrowernumber` (`borrowernumber`),
1197                 KEY `old_reserves_biblionumber` (`biblionumber`),
1198                 KEY `old_reserves_itemnumber` (`itemnumber`),
1199                 KEY `old_reserves_branchcode` (`branchcode`),
1200                 CONSTRAINT `old_reserves_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1201                     ON DELETE SET NULL ON UPDATE SET NULL,
1202                 CONSTRAINT `old_reserves_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`)
1203                     ON DELETE SET NULL ON UPDATE SET NULL,
1204                 CONSTRAINT `old_reserves_ibfk_3` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`)
1205                     ON DELETE SET NULL ON UPDATE SET NULL
1206                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1207
1208     # move closed transactions to old_* tables
1209     $dbh->do("INSERT INTO old_issues SELECT * FROM issues WHERE returndate IS NOT NULL");
1210     $dbh->do("DELETE FROM issues WHERE returndate IS NOT NULL");
1211     $dbh->do("INSERT INTO old_reserves SELECT * FROM reserves WHERE cancellationdate IS NOT NULL OR found = 'F'");
1212     $dbh->do("DELETE FROM reserves WHERE cancellationdate IS NOT NULL OR found = 'F'");
1213
1214         print "Upgrade to $DBversion done ( Added old_issues and old_reserves tables )\n";
1215     SetVersion ($DBversion);
1216 }
1217
1218 $DBversion = "3.00.00.063";
1219 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1220     $dbh->do("ALTER TABLE deleteditems
1221                 CHANGE COLUMN booksellerid booksellerid MEDIUMTEXT DEFAULT NULL,
1222                 ADD COLUMN enumchron VARCHAR(80) DEFAULT NULL AFTER more_subfields_xml,
1223                 ADD COLUMN copynumber SMALLINT(6) DEFAULT NULL AFTER enumchron;");
1224     $dbh->do("ALTER TABLE items
1225                 CHANGE COLUMN booksellerid booksellerid MEDIUMTEXT,
1226                 ADD COLUMN copynumber SMALLINT(6) DEFAULT NULL AFTER enumchron;");
1227         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";
1228     SetVersion ($DBversion);
1229 }
1230
1231 $DBversion = "3.00.00.064";
1232 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1233     $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');");
1234     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AWSAccessKeyID','','See:  http://aws.amazon.com','','free');");
1235     $dbh->do("DELETE FROM `systempreferences` WHERE variable='AmazonDevKey';");
1236     $dbh->do("DELETE FROM `systempreferences` WHERE variable='XISBNAmazonSimilarItems';");
1237     $dbh->do("DELETE FROM `systempreferences` WHERE variable='OPACXISBNAmazonSimilarItems';");
1238     print "Upgrade to $DBversion done (IMPORTANT: Upgrading to Amazon.com Associates Web Service 4.0 ) \n";
1239     SetVersion ($DBversion);
1240 }
1241
1242 $DBversion = "3.00.00.065";
1243 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1244     $dbh->do("CREATE TABLE `patroncards` (
1245                 `cardid` int(11) NOT NULL auto_increment,
1246                 `batch_id` varchar(10) NOT NULL default '1',
1247                 `borrowernumber` int(11) NOT NULL,
1248                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1249                 PRIMARY KEY  (`cardid`),
1250                 KEY `patroncards_ibfk_1` (`borrowernumber`),
1251                 CONSTRAINT `patroncards_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE
1252                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1253     print "Upgrade to $DBversion done (Adding patroncards table for patroncards generation feature. ) \n";
1254     SetVersion ($DBversion);
1255 }
1256
1257 $DBversion = "3.00.00.066";
1258 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1259     $dbh->do("ALTER TABLE `virtualshelfcontents` MODIFY `dateadded` timestamp NOT NULL
1260 DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP;
1261 ");
1262     print "Upgrade to $DBversion done (fix for bug 1873: virtualshelfcontents dateadded column empty. ) \n";
1263     SetVersion ($DBversion);
1264 }
1265
1266 $DBversion = "3.00.00.067";
1267 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1268     $dbh->do("UPDATE systempreferences SET explanation = 'Enable patron images for the Staff Client', type = 'YesNo' WHERE variable = 'patronimages'");
1269     print "Upgrade to $DBversion done (Updating patronimages syspref to reflect current kohastructure.sql. ) \n";
1270     SetVersion ($DBversion);
1271 }
1272
1273 $DBversion = "3.00.00.068";
1274 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1275     $dbh->do("CREATE TABLE `permissions` (
1276                 `module_bit` int(11) NOT NULL DEFAULT 0,
1277                 `code` varchar(30) DEFAULT NULL,
1278                 `description` varchar(255) DEFAULT NULL,
1279                 PRIMARY KEY  (`module_bit`, `code`),
1280                 CONSTRAINT `permissions_ibfk_1` FOREIGN KEY (`module_bit`) REFERENCES `userflags` (`bit`)
1281                     ON DELETE CASCADE ON UPDATE CASCADE
1282               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1283     $dbh->do("CREATE TABLE `user_permissions` (
1284                 `borrowernumber` int(11) NOT NULL DEFAULT 0,
1285                 `module_bit` int(11) NOT NULL DEFAULT 0,
1286                 `code` varchar(30) DEFAULT NULL,
1287                 CONSTRAINT `user_permissions_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1288                     ON DELETE CASCADE ON UPDATE CASCADE,
1289                 CONSTRAINT `user_permissions_ibfk_2` FOREIGN KEY (`module_bit`, `code`)
1290                     REFERENCES `permissions` (`module_bit`, `code`)
1291                     ON DELETE CASCADE ON UPDATE CASCADE
1292               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1293
1294     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
1295     (13, 'edit_news', 'Write news for the OPAC and staff interfaces'),
1296     (13, 'label_creator', 'Create printable labels and barcodes from catalog and patron data'),
1297     (13, 'edit_calendar', 'Define days when the library is closed'),
1298     (13, 'moderate_comments', 'Moderate patron comments'),
1299     (13, 'edit_notices', 'Define notices'),
1300     (13, 'edit_notice_status_triggers', 'Set notice/status triggers for overdue items'),
1301     (13, 'view_system_logs', 'Browse the system logs'),
1302     (13, 'inventory', 'Perform inventory (stocktaking) of your catalogue'),
1303     (13, 'stage_marc_import', 'Stage MARC records into the reservoir'),
1304     (13, 'manage_staged_marc', 'Managed staged MARC records, including completing and reversing imports'),
1305     (13, 'export_catalog', 'Export bibliographic and holdings data'),
1306     (13, 'import_patrons', 'Import patron data'),
1307     (13, 'delete_anonymize_patrons', 'Delete old borrowers and anonymize circulation history (deletes borrower reading history)'),
1308     (13, 'batch_upload_patron_images', 'Upload patron images in batch or one at a time'),
1309     (13, 'schedule_tasks', 'Schedule tasks to run')");
1310
1311     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('GranularPermissions','0','Use detailed staff user permissions',NULL,'YesNo')");
1312
1313     print "Upgrade to $DBversion done (adding permissions and user_permissions tables and GranularPermissions syspref) \n";
1314     SetVersion ($DBversion);
1315 }
1316 $DBversion = "3.00.00.069";
1317 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1318     $dbh->do("ALTER TABLE labels_conf CHANGE COLUMN class classification int(1) DEFAULT NULL;");
1319         print "Upgrade to $DBversion done ( Correcting columname in labels_conf )\n";
1320     SetVersion ($DBversion);
1321 }
1322
1323 $DBversion = "3.00.00.070";
1324 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1325     $sth = $dbh->prepare("SELECT value FROM systempreferences WHERE variable='yuipath'");
1326     $sth->execute;
1327     my ($value) = $sth->fetchrow;
1328     $value =~ s/2.3.1/2.5.1/;
1329     $dbh->do("UPDATE systempreferences SET value='$value' WHERE variable='yuipath';");
1330         print "Update yuipath syspref to 2.5.1 if necessary\n";
1331     SetVersion ($DBversion);
1332 }
1333
1334 $DBversion = "3.00.00.071";
1335 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1336     $dbh->do(" ALTER TABLE `subscription` ADD `serialsadditems` TINYINT( 1 ) NOT NULL DEFAULT '0';");
1337     # fill the new field with the previous systempreference value, then drop the syspref
1338     my $sth = $dbh->prepare("SELECT value FROM systempreferences WHERE variable='serialsadditems'");
1339     $sth->execute;
1340     my ($serialsadditems) = $sth->fetchrow();
1341     $dbh->do("UPDATE subscription SET serialsadditems=$serialsadditems");
1342     $dbh->do("DELETE FROM systempreferences WHERE variable='serialsadditems'");
1343     print "Upgrade to $DBversion done ( moving serialsadditems from syspref to subscription )\n";
1344     SetVersion ($DBversion);
1345 }
1346
1347 $DBversion = "3.00.00.072";
1348 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1349     $dbh->do("ALTER TABLE labels_conf ADD COLUMN formatstring mediumtext DEFAULT NULL AFTER printingtype");
1350         print "Upgrade to $DBversion done ( Adding format string to labels generator. )\n";
1351     SetVersion ($DBversion);
1352 }
1353
1354 $DBversion = "3.00.00.073";
1355 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1356         $dbh->do("DROP TABLE IF EXISTS `tags_all`;");
1357         $dbh->do(q#
1358         CREATE TABLE `tags_all` (
1359           `tag_id`         int(11) NOT NULL auto_increment,
1360           `borrowernumber` int(11) NOT NULL,
1361           `biblionumber`   int(11) NOT NULL,
1362           `term`      varchar(255) NOT NULL,
1363           `language`       int(4) default NULL,
1364           `date_created` datetime  NOT NULL,
1365           PRIMARY KEY  (`tag_id`),
1366           KEY `tags_borrowers_fk_1` (`borrowernumber`),
1367           KEY `tags_biblionumber_fk_1` (`biblionumber`),
1368           CONSTRAINT `tags_borrowers_fk_1` FOREIGN KEY (`borrowernumber`)
1369                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1370           CONSTRAINT `tags_biblionumber_fk_1` FOREIGN KEY (`biblionumber`)
1371                 REFERENCES `biblio`     (`biblionumber`)  ON DELETE CASCADE ON UPDATE CASCADE
1372         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1373         #);
1374         $dbh->do("DROP TABLE IF EXISTS `tags_approval`;");
1375         $dbh->do(q#
1376         CREATE TABLE `tags_approval` (
1377           `term`   varchar(255) NOT NULL,
1378           `approved`     int(1) NOT NULL default '0',
1379           `date_approved` datetime       default NULL,
1380           `approved_by` int(11)          default NULL,
1381           `weight_total` int(9) NOT NULL default '1',
1382           PRIMARY KEY  (`term`),
1383           KEY `tags_approval_borrowers_fk_1` (`approved_by`),
1384           CONSTRAINT `tags_approval_borrowers_fk_1` FOREIGN KEY (`approved_by`)
1385                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE
1386         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1387         #);
1388         $dbh->do("DROP TABLE IF EXISTS `tags_index`;");
1389         $dbh->do(q#
1390         CREATE TABLE `tags_index` (
1391           `term`    varchar(255) NOT NULL,
1392           `biblionumber` int(11) NOT NULL,
1393           `weight`        int(9) NOT NULL default '1',
1394           PRIMARY KEY  (`term`,`biblionumber`),
1395           KEY `tags_index_biblionumber_fk_1` (`biblionumber`),
1396           CONSTRAINT `tags_index_term_fk_1` FOREIGN KEY (`term`)
1397                 REFERENCES `tags_approval` (`term`)  ON DELETE CASCADE ON UPDATE CASCADE,
1398           CONSTRAINT `tags_index_biblionumber_fk_1` FOREIGN KEY (`biblionumber`)
1399                 REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
1400         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1401         #);
1402         $dbh->do(q#
1403         INSERT INTO `systempreferences` VALUES
1404                 ('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=',''),
1405                 ('BakerTaylorEnabled','0','','Enable or disable all Baker & Taylor features.','YesNo'),
1406                 ('BakerTaylorPassword','','','Baker & Taylor Password for Content Cafe (external content)','Textarea'),
1407                 ('BakerTaylorUsername','','','Baker & Taylor Username for Content Cafe (external content)','Textarea'),
1408                 ('TagsEnabled','1','','Enables or disables all tagging features.  This is the main switch for tags.','YesNo'),
1409                 ('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.',''),
1410                 ('TagsInputOnDetail','1','','Allow users to input tags from the detail page.',         'YesNo'),
1411                 ('TagsInputOnList',  '0','','Allow users to input tags from the search results list.', 'YesNo'),
1412                 ('TagsModeration',  NULL,'','Require tags from patrons to be approved before becoming visible.','YesNo'),
1413                 ('TagsShowOnDetail','10','','Number of tags to display on detail page.  0 is off.',        'Integer'),
1414                 ('TagsShowOnList',   '6','','Number of tags to display on search results list.  0 is off.','Integer')
1415         #);
1416         print "Upgrade to $DBversion done (Baker/Taylor,Tags: sysprefs and tables (tags_all, tags_index, tags_approval)) \n";
1417         SetVersion ($DBversion);
1418 }
1419
1420 $DBversion = "3.00.00.074";
1421 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1422     $dbh->do( q(update itemtypes set imageurl = concat( 'npl/', imageurl )
1423                   where imageurl not like 'http%'
1424                     and imageurl is not NULL
1425                     and imageurl != '') );
1426     print "Upgrade to $DBversion done (updating imagetype.imageurls to reflect new icon locations.)\n";
1427     SetVersion ($DBversion);
1428 }
1429
1430 $DBversion = "3.00.00.075";
1431 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1432     $dbh->do( q(alter table authorised_values add imageurl varchar(200) default NULL) );
1433     print "Upgrade to $DBversion done (adding imageurl field to authorised_values table)\n";
1434     SetVersion ($DBversion);
1435 }
1436
1437 $DBversion = "3.00.00.076";
1438 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1439     $dbh->do("ALTER TABLE import_batches
1440               ADD COLUMN nomatch_action enum('create_new', 'ignore') NOT NULL default 'create_new' AFTER overlay_action");
1441     $dbh->do("ALTER TABLE import_batches
1442               ADD COLUMN item_action enum('always_add', 'add_only_for_matches', 'add_only_for_new', 'ignore')
1443                   NOT NULL default 'always_add' AFTER nomatch_action");
1444     $dbh->do("ALTER TABLE import_batches
1445               MODIFY overlay_action  enum('replace', 'create_new', 'use_template', 'ignore')
1446                   NOT NULL default 'create_new'");
1447     $dbh->do("ALTER TABLE import_records
1448               MODIFY status  enum('error', 'staged', 'imported', 'reverted', 'items_reverted',
1449                                   'ignored') NOT NULL default 'staged'");
1450     $dbh->do("ALTER TABLE import_items
1451               MODIFY status enum('error', 'staged', 'imported', 'reverted', 'ignored') NOT NULL default 'staged'");
1452
1453         print "Upgrade to $DBversion done (changes to import_batches and import_records)\n";
1454         SetVersion ($DBversion);
1455 }
1456
1457 $DBversion = "3.00.00.077";
1458 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1459     # drop these tables only if they exist and none of them are empty
1460     # these tables are not defined in the packaged 2.2.9, but since it is believed
1461     # that at least one library may be using them in a post-2.2.9 but pre-3.0 Koha,
1462     # some care is taken.
1463     my ($print_error) = $dbh->{PrintError};
1464     $dbh->{PrintError} = 0;
1465     my ($raise_error) = $dbh->{RaiseError};
1466     $dbh->{RaiseError} = 1;
1467
1468     my $count = 0;
1469     my $do_drop = 1;
1470     eval { $count = $dbh->do("SELECT 1 FROM categorytable"); };
1471     if ($count > 0) {
1472         $do_drop = 0;
1473     }
1474     eval { $count = $dbh->do("SELECT 1 FROM mediatypetable"); };
1475     if ($count > 0) {
1476         $do_drop = 0;
1477     }
1478     eval { $count = $dbh->do("SELECT 1 FROM subcategorytable"); };
1479     if ($count > 0) {
1480         $do_drop = 0;
1481     }
1482
1483     if ($do_drop) {
1484         $dbh->do("DROP TABLE IF EXISTS `categorytable`");
1485         $dbh->do("DROP TABLE IF EXISTS `mediatypetable`");
1486         $dbh->do("DROP TABLE IF EXISTS `subcategorytable`");
1487     }
1488
1489     $dbh->{PrintError} = $print_error;
1490     $dbh->{RaiseError} = $raise_error;
1491         print "Upgrade to $DBversion done (drop categorytable, subcategorytable, and mediatypetable)\n";
1492         SetVersion ($DBversion);
1493 }
1494
1495 $DBversion = "3.00.00.078";
1496 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1497     my ($print_error) = $dbh->{PrintError};
1498     $dbh->{PrintError} = 0;
1499
1500     unless ($dbh->do("SELECT 1 FROM browser")) {
1501         $dbh->{PrintError} = $print_error;
1502         $dbh->do("CREATE TABLE `browser` (
1503                     `level` int(11) NOT NULL,
1504                     `classification` varchar(20) NOT NULL,
1505                     `description` varchar(255) NOT NULL,
1506                     `number` bigint(20) NOT NULL,
1507                     `endnode` tinyint(4) NOT NULL
1508                   ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1509     }
1510     $dbh->{PrintError} = $print_error;
1511         print "Upgrade to $DBversion done (add browser table if not already present)\n";
1512         SetVersion ($DBversion);
1513 }
1514
1515 $DBversion = "3.00.00.079";
1516 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1517  my ($print_error) = $dbh->{PrintError};
1518     $dbh->{PrintError} = 0;
1519
1520     $dbh->do("INSERT INTO `systempreferences` (variable, value,options,type, explanation)VALUES
1521         ('AddPatronLists','categorycode','categorycode|category_type','Choice','Allow user to choose what list to pick up from when adding patrons')");
1522     print "Upgrade to $DBversion done (add browser table if not already present)\n";
1523         SetVersion ($DBversion);
1524 }
1525
1526 $DBversion = "3.00.00.080";
1527 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1528     $dbh->do("ALTER TABLE subscription CHANGE monthlength monthlength int(11) default '0'");
1529     $dbh->do("ALTER TABLE deleteditems MODIFY marc LONGBLOB AFTER copynumber");
1530     $dbh->do("ALTER TABLE aqbooksellers CHANGE name name mediumtext NOT NULL");
1531         print "Upgrade to $DBversion done (catch up on DB schema changes since alpha and beta)\n";
1532         SetVersion ($DBversion);
1533 }
1534
1535 $DBversion = "3.00.00.081";
1536 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1537     $dbh->do("CREATE TABLE `borrower_attribute_types` (
1538                 `code` varchar(10) NOT NULL,
1539                 `description` varchar(255) NOT NULL,
1540                 `repeatable` tinyint(1) NOT NULL default 0,
1541                 `unique_id` tinyint(1) NOT NULL default 0,
1542                 `opac_display` tinyint(1) NOT NULL default 0,
1543                 `password_allowed` tinyint(1) NOT NULL default 0,
1544                 `staff_searchable` tinyint(1) NOT NULL default 0,
1545                 `authorised_value_category` varchar(10) default NULL,
1546                 PRIMARY KEY  (`code`)
1547               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1548     $dbh->do("CREATE TABLE `borrower_attributes` (
1549                 `borrowernumber` int(11) NOT NULL,
1550                 `code` varchar(10) NOT NULL,
1551                 `attribute` varchar(30) default NULL,
1552                 `password` varchar(30) default NULL,
1553                 KEY `borrowernumber` (`borrowernumber`),
1554                 KEY `code_attribute` (`code`, `attribute`),
1555                 CONSTRAINT `borrower_attributes_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1556                     ON DELETE CASCADE ON UPDATE CASCADE,
1557                 CONSTRAINT `borrower_attributes_ibfk_2` FOREIGN KEY (`code`) REFERENCES `borrower_attribute_types` (`code`)
1558                     ON DELETE CASCADE ON UPDATE CASCADE
1559             ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1560     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('ExtendedPatronAttributes','0','Use extended patron IDs and attributes',NULL,'YesNo')");
1561     print "Upgrade to $DBversion done (added borrower_attributes and  borrower_attribute_types)\n";
1562  SetVersion ($DBversion);
1563 }
1564
1565 $DBversion = "3.00.00.082";
1566 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1567     $dbh->do( q(alter table accountlines add column lastincrement decimal(28,6) default NULL) );
1568     print "Upgrade to $DBversion done (adding lastincrement column to accountlines table)\n";
1569     SetVersion ($DBversion);
1570 }
1571
1572 $DBversion = "3.00.00.083";
1573 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1574     $dbh->do( qq(UPDATE systempreferences SET value='local' where variable='yuipath' and value like "%/intranet-tmpl/prog/%"));
1575     print "Upgrade to $DBversion done (Changing yuipath behaviour in managing a local value)\n";
1576     SetVersion ($DBversion);
1577 }
1578 $DBversion = "3.00.00.084";
1579     if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1580     $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')");
1581     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('GoogleJackets','0','if ON, displays jacket covers from Google Books API',NULL,'YesNo')");
1582     print "Upgrade to $DBversion done (add new sysprefs)\n";
1583     SetVersion ($DBversion);
1584 }
1585
1586 $DBversion = "3.00.00.085";
1587 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1588     if (C4::Context->preference("marcflavour") eq 'MARC21') {
1589         $dbh->do("UPDATE marc_subfield_structure SET tab = 0 WHERE tab =  9 AND tagfield = '037'");
1590         $dbh->do("UPDATE marc_subfield_structure SET tab = 1 WHERE tab =  6 AND tagfield in ('100', '110', '111', '130')");
1591         $dbh->do("UPDATE marc_subfield_structure SET tab = 2 WHERE tab =  6 AND tagfield in ('240', '243')");
1592         $dbh->do("UPDATE marc_subfield_structure SET tab = 4 WHERE tab =  6 AND tagfield in ('400', '410', '411', '440')");
1593         $dbh->do("UPDATE marc_subfield_structure SET tab = 5 WHERE tab =  9 AND tagfield = '584'");
1594         $dbh->do("UPDATE marc_subfield_structure SET tab = 7 WHERE tab = -6 AND tagfield = '760'");
1595     }
1596     print "Upgrade to $DBversion done (move editing tab of various MARC21 subfields)\n";
1597     SetVersion ($DBversion);
1598 }
1599
1600 $DBversion = "3.00.00.086";
1601 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1602         $dbh->do(
1603         "CREATE TABLE `tmp_holdsqueue` (
1604         `biblionumber` int(11) default NULL,
1605         `itemnumber` int(11) default NULL,
1606         `barcode` varchar(20) default NULL,
1607         `surname` mediumtext NOT NULL,
1608         `firstname` text,
1609         `phone` text,
1610         `borrowernumber` int(11) NOT NULL,
1611         `cardnumber` varchar(16) default NULL,
1612         `reservedate` date default NULL,
1613         `title` mediumtext,
1614         `itemcallnumber` varchar(30) default NULL,
1615         `holdingbranch` varchar(10) default NULL,
1616         `pickbranch` varchar(10) default NULL,
1617         `notes` text
1618         ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1619
1620         $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')");
1621         $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')");
1622
1623         print "Upgrade to $DBversion done (Table structure for table `tmp_holdsqueue`)\n";
1624         SetVersion ($DBversion);
1625 }
1626
1627 $DBversion = "3.00.00.087";
1628 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1629     $dbh->do("INSERT INTO `systempreferences` VALUES ('AutoEmailOpacUser','0','','Sends notification emails containing new account details to patrons - when account is created.','YesNo')" );
1630     $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')");
1631     print "Upgrade to $DBversion done (added 2 new 'AutoEmailOpacUser' sysprefs)\n";
1632     SetVersion ($DBversion);
1633 }
1634
1635 $DBversion = "3.00.00.088";
1636 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1637         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('OPACShelfBrowser','1','','Enable/disable Shelf Browser on item details page','YesNo')");
1638         $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')");
1639         $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')");
1640         $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')");
1641         print "Upgrade to $DBversion done (added 2 new 'AutoEmailOpacUser' sysprefs)\n";
1642     SetVersion ($DBversion);
1643 }
1644
1645 $DBversion = "3.00.00.089";
1646 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1647         $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')");
1648         print "Upgrade to $DBversion done (added new AdvancedSearchTypes syspref)\n";
1649     SetVersion ($DBversion);
1650 }
1651
1652 $DBversion = "3.00.00.090";
1653 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1654     $dbh->do("
1655         CREATE TABLE `branch_borrower_circ_rules` (
1656           `branchcode` VARCHAR(10) NOT NULL,
1657           `categorycode` VARCHAR(10) NOT NULL,
1658           `maxissueqty` int(4) default NULL,
1659           PRIMARY KEY (`categorycode`, `branchcode`),
1660           CONSTRAINT `branch_borrower_circ_rules_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
1661             ON DELETE CASCADE ON UPDATE CASCADE,
1662           CONSTRAINT `branch_borrower_circ_rules_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`)
1663             ON DELETE CASCADE ON UPDATE CASCADE
1664         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1665     ");
1666     $dbh->do("
1667         CREATE TABLE `default_borrower_circ_rules` (
1668           `categorycode` VARCHAR(10) NOT NULL,
1669           `maxissueqty` int(4) default NULL,
1670           PRIMARY KEY (`categorycode`),
1671           CONSTRAINT `borrower_borrower_circ_rules_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
1672             ON DELETE CASCADE ON UPDATE CASCADE
1673         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1674     ");
1675     $dbh->do("
1676         CREATE TABLE `default_branch_circ_rules` (
1677           `branchcode` VARCHAR(10) NOT NULL,
1678           `maxissueqty` int(4) default NULL,
1679           PRIMARY KEY (`branchcode`),
1680           CONSTRAINT `default_branch_circ_rules_ibfk_1` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`)
1681             ON DELETE CASCADE ON UPDATE CASCADE
1682         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1683     ");
1684     $dbh->do("
1685         CREATE TABLE `default_circ_rules` (
1686             `singleton` enum('singleton') NOT NULL default 'singleton',
1687             `maxissueqty` int(4) default NULL,
1688             PRIMARY KEY (`singleton`)
1689         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1690     ");
1691     print "Upgrade to $DBversion done (added several circ rules tables)\n";
1692     SetVersion ($DBversion);
1693 }
1694
1695
1696 $DBversion = "3.00.00.091";
1697 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1698     $dbh->do(<<'END_SQL');
1699 ALTER TABLE borrowers
1700 ADD `smsalertnumber` varchar(50) default NULL
1701 END_SQL
1702
1703     $dbh->do(<<'END_SQL');
1704 CREATE TABLE `message_attributes` (
1705   `message_attribute_id` int(11) NOT NULL auto_increment,
1706   `message_name` varchar(20) NOT NULL default '',
1707   `takes_days` tinyint(1) NOT NULL default '0',
1708   PRIMARY KEY  (`message_attribute_id`),
1709   UNIQUE KEY `message_name` (`message_name`)
1710 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1711 END_SQL
1712
1713     $dbh->do(<<'END_SQL');
1714 CREATE TABLE `message_transport_types` (
1715   `message_transport_type` varchar(20) NOT NULL,
1716   PRIMARY KEY  (`message_transport_type`)
1717 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1718 END_SQL
1719
1720     $dbh->do(<<'END_SQL');
1721 CREATE TABLE `message_transports` (
1722   `message_attribute_id` int(11) NOT NULL,
1723   `message_transport_type` varchar(20) NOT NULL,
1724   `is_digest` tinyint(1) NOT NULL default '0',
1725   `letter_module` varchar(20) NOT NULL default '',
1726   `letter_code` varchar(20) NOT NULL default '',
1727   PRIMARY KEY  (`message_attribute_id`,`message_transport_type`,`is_digest`),
1728   KEY `message_transport_type` (`message_transport_type`),
1729   KEY `letter_module` (`letter_module`,`letter_code`),
1730   CONSTRAINT `message_transports_ibfk_1` FOREIGN KEY (`message_attribute_id`) REFERENCES `message_attributes` (`message_attribute_id`) ON DELETE CASCADE ON UPDATE CASCADE,
1731   CONSTRAINT `message_transports_ibfk_2` FOREIGN KEY (`message_transport_type`) REFERENCES `message_transport_types` (`message_transport_type`) ON DELETE CASCADE ON UPDATE CASCADE,
1732   CONSTRAINT `message_transports_ibfk_3` FOREIGN KEY (`letter_module`, `letter_code`) REFERENCES `letter` (`module`, `code`) ON DELETE CASCADE ON UPDATE CASCADE
1733 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1734 END_SQL
1735
1736     $dbh->do(<<'END_SQL');
1737 CREATE TABLE `borrower_message_preferences` (
1738   `borrower_message_preference_id` int(11) NOT NULL auto_increment,
1739   `borrowernumber` int(11) NOT NULL default '0',
1740   `message_attribute_id` int(11) default '0',
1741   `days_in_advance` int(11) default '0',
1742   `wants_digets` tinyint(1) NOT NULL default '0',
1743   PRIMARY KEY  (`borrower_message_preference_id`),
1744   KEY `borrowernumber` (`borrowernumber`),
1745   KEY `message_attribute_id` (`message_attribute_id`),
1746   CONSTRAINT `borrower_message_preferences_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1747   CONSTRAINT `borrower_message_preferences_ibfk_2` FOREIGN KEY (`message_attribute_id`) REFERENCES `message_attributes` (`message_attribute_id`) ON DELETE CASCADE ON UPDATE CASCADE
1748 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1749 END_SQL
1750
1751     $dbh->do(<<'END_SQL');
1752 CREATE TABLE `borrower_message_transport_preferences` (
1753   `borrower_message_preference_id` int(11) NOT NULL default '0',
1754   `message_transport_type` varchar(20) NOT NULL default '0',
1755   PRIMARY KEY  (`borrower_message_preference_id`,`message_transport_type`),
1756   KEY `message_transport_type` (`message_transport_type`),
1757   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,
1758   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
1759 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1760 END_SQL
1761
1762     $dbh->do(<<'END_SQL');
1763 CREATE TABLE `message_queue` (
1764   `message_id` int(11) NOT NULL auto_increment,
1765   `borrowernumber` int(11) NOT NULL,
1766   `subject` text,
1767   `content` text,
1768   `message_transport_type` varchar(20) NOT NULL,
1769   `status` enum('sent','pending','failed','deleted') NOT NULL default 'pending',
1770   `time_queued` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1771   KEY `message_id` (`message_id`),
1772   KEY `borrowernumber` (`borrowernumber`),
1773   KEY `message_transport_type` (`message_transport_type`),
1774   CONSTRAINT `messageq_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1775   CONSTRAINT `messageq_ibfk_2` FOREIGN KEY (`message_transport_type`) REFERENCES `message_transport_types` (`message_transport_type`) ON DELETE RESTRICT ON UPDATE CASCADE
1776 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1777 END_SQL
1778
1779     $dbh->do(<<'END_SQL');
1780 INSERT INTO `systempreferences`
1781   (variable,value,explanation,options,type)
1782 VALUES
1783 ('EnhancedMessagingPreferences',0,'If ON, allows patrons to select to receive additional messages about items due or nearly due.','','YesNo')
1784 END_SQL
1785
1786     $dbh->do( <<'END_SQL');
1787 INSERT INTO `letter`
1788 (module, code, name, title, content)
1789 VALUES
1790 ('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>>'),
1791 ('circulation','DUEDGST','Item Due Reminder (Digest)','Item Due Reminder','You have <<count>> items due'),
1792 ('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>>'),
1793 ('circulation','PREDUEDGST','Advance Notice of Item Due (Digest)','Advance Notice of Item Due','You have <<count>> items due soon'),
1794 ('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.');
1795 END_SQL
1796
1797     my @sql_scripts = (
1798         'installer/data/mysql/en/mandatory/message_transport_types.sql',
1799         'installer/data/mysql/en/optional/sample_notices_message_attributes.sql',
1800         'installer/data/mysql/en/optional/sample_notices_message_transports.sql',
1801     );
1802
1803     my $installer = C4::Installer->new();
1804     foreach my $script ( @sql_scripts ) {
1805         my $full_path = $installer->get_file_path_from_name($script);
1806         my $error = $installer->load_sql($full_path);
1807         warn $error if $error;
1808     }
1809
1810     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";
1811     SetVersion ($DBversion);
1812 }
1813
1814 $DBversion = "3.00.00.092";
1815 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1816     $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')");
1817     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES('AllowHoldsOnDamagedItems', '1', '', 'Allow hold requests to be placed on damaged items', 'YesNo')");
1818         print "Upgrade to $DBversion done (added new AllowOnShelfHolds syspref)\n";
1819     SetVersion ($DBversion);
1820 }
1821
1822 $DBversion = "3.00.00.093";
1823 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1824     $dbh->do("ALTER TABLE `items` MODIFY COLUMN `copynumber` VARCHAR(32) DEFAULT NULL");
1825     $dbh->do("ALTER TABLE `deleteditems` MODIFY COLUMN `copynumber` VARCHAR(32) DEFAULT NULL");
1826         print "Upgrade to $DBversion done (Change data type of items.copynumber to allow free text)\n";
1827     SetVersion ($DBversion);
1828 }
1829
1830 $DBversion = "3.00.00.094";
1831 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1832     $dbh->do("ALTER TABLE `marc_subfield_structure` MODIFY `tagsubfield` VARCHAR(1) NOT NULL DEFAULT '' COLLATE utf8_bin");
1833         print "Upgrade to $DBversion done (Change Collation of marc_subfield_structure to allow mixed case in subfield labels.)\n";
1834     SetVersion ($DBversion);
1835 }
1836
1837 $DBversion = "3.00.00.095";
1838 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1839     if (C4::Context->preference("marcflavour") eq 'MARC21') {
1840         $dbh->do("UPDATE marc_subfield_structure SET authtypecode = 'MEETI_NAME' WHERE authtypecode = 'Meeting Name'");
1841         $dbh->do("UPDATE marc_subfield_structure SET authtypecode = 'CORPO_NAME' WHERE authtypecode = 'CORP0_NAME'");
1842     }
1843         print "Upgrade to $DBversion done (fix invalid authority types in MARC21 frameworks [bug 2254])\n";
1844     SetVersion ($DBversion);
1845 }
1846
1847 $DBversion = "3.00.00.096";
1848 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1849     $sth = $dbh->prepare("SHOW COLUMNS FROM borrower_message_preferences LIKE 'wants_digets'");
1850     $sth->execute();
1851     if (my $row = $sth->fetchrow_hashref) {
1852         $dbh->do("ALTER TABLE borrower_message_preferences CHANGE wants_digets wants_digest tinyint(1) NOT NULL default 0");
1853     }
1854         print "Upgrade to $DBversion done (fix name borrower_message_preferences.wants_digest)\n";
1855     SetVersion ($DBversion);
1856 }
1857
1858 $DBversion = '3.00.00.097';
1859 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1860
1861     $dbh->do('ALTER TABLE message_queue ADD to_address   mediumtext default NULL');
1862     $dbh->do('ALTER TABLE message_queue ADD from_address mediumtext default NULL');
1863     $dbh->do('ALTER TABLE message_queue ADD content_type text');
1864     $dbh->do('ALTER TABLE message_queue CHANGE borrowernumber borrowernumber int(11) default NULL');
1865
1866     print "Upgrade to $DBversion done (updating 4 fields in message_queue table)\n";
1867     SetVersion($DBversion);
1868 }
1869
1870 $DBversion = '3.00.00.098';
1871 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1872
1873     $dbh->do(q(DELETE FROM message_transport_types WHERE message_transport_type = 'rss'));
1874     $dbh->do(q(DELETE FROM message_transports WHERE message_transport_type = 'rss'));
1875
1876     print "Upgrade to $DBversion done (removing unused RSS message_transport_type)\n";
1877     SetVersion($DBversion);
1878 }
1879
1880 $DBversion = '3.00.00.099';
1881 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1882     $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')");
1883     print "Upgrade to $DBversion done (Adding OpacSuppression syspref)\n";
1884     SetVersion($DBversion);
1885 }
1886
1887 $DBversion = '3.00.00.100';
1888 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1889         $dbh->do('ALTER TABLE virtualshelves ADD COLUMN lastmodified timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP');
1890     print "Upgrade to $DBversion done (Adding lastmodified column to virtualshelves)\n";
1891     SetVersion($DBversion);
1892 }
1893
1894 $DBversion = '3.00.00.101';
1895 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1896         $dbh->do('ALTER TABLE `overduerules` CHANGE `categorycode` `categorycode` VARCHAR(10) NOT NULL');
1897         $dbh->do('ALTER TABLE `deletedborrowers` CHANGE `categorycode` `categorycode` VARCHAR(10) NOT NULL');
1898     print "Upgrade to $DBversion done (Updating columnd definitions for patron category codes in notice/statsu triggers and deletedborrowers tables.)\n";
1899     SetVersion($DBversion);
1900 }
1901
1902 $DBversion = '3.00.00.102';
1903 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1904         $dbh->do('ALTER TABLE serialitems MODIFY `serialid` int(11) NOT NULL AFTER itemnumber' );
1905         $dbh->do('ALTER TABLE serialitems DROP KEY serialididx' );
1906         $dbh->do('ALTER TABLE serialitems ADD CONSTRAINT UNIQUE KEY serialitemsidx (itemnumber)' );
1907         # before setting constraint, delete any unvalid data
1908         $dbh->do('DELETE from serialitems WHERE serialid not in (SELECT serial.serialid FROM serial)');
1909         $dbh->do('ALTER TABLE serialitems ADD CONSTRAINT serialitems_sfk_1 FOREIGN KEY (serialid) REFERENCES serial (serialid) ON DELETE CASCADE ON UPDATE CASCADE' );
1910     print "Upgrade to $DBversion done (Updating serialitems table to allow for multiple items per serial fixing kohabug 2380)\n";
1911     SetVersion($DBversion);
1912 }
1913
1914 $DBversion = "3.00.00.103";
1915 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1916     $dbh->do("DELETE FROM systempreferences WHERE variable='serialsadditems'");
1917     print "Upgrade to $DBversion done ( Verifying the removal of serialsadditems from syspref fixing kohabug 2219)\n";
1918     SetVersion ($DBversion);
1919 }
1920
1921 $DBversion = "3.00.00.104";
1922 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1923     $dbh->do("DELETE FROM systempreferences WHERE variable='noOPACHolds'");
1924     print "Upgrade to $DBversion done (remove superseded 'noOPACHolds' system preference per bug 2413)\n";
1925     SetVersion ($DBversion);
1926 }
1927
1928 $DBversion = '3.00.00.105';
1929 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
1930
1931     # it is possible that this syspref is already defined since the feature was added some time ago.
1932     unless ( $dbh->do(q(SELECT variable FROM systempreferences WHERE variable = 'SMSSendDriver')) ) {
1933         $dbh->do(<<'END_SQL');
1934 INSERT INTO `systempreferences`
1935   (variable,value,explanation,options,type)
1936 VALUES
1937 ('SMSSendDriver','','Sets which SMS::Send driver is used to send SMS messages.','','free')
1938 END_SQL
1939     }
1940     print "Upgrade to $DBversion done (added SMSSendDriver system preference)\n";
1941     SetVersion($DBversion);
1942 }
1943
1944 $DBversion = "3.00.00.106";
1945 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1946     $dbh->do("DELETE FROM systempreferences WHERE variable='noOPACHolds'");
1947
1948 # db revision 105 didn't apply correctly, so we're rolling this into 106
1949         $dbh->do("INSERT INTO `systempreferences`
1950    (variable,value,explanation,options,type)
1951         VALUES
1952         ('SMSSendDriver','','Sets which SMS::Send driver is used to send SMS messages.','','free')");
1953
1954     print "Upgrade to $DBversion done (remove default '0000-00-00' in subscriptionhistory.enddate field)\n";
1955     $dbh->do("ALTER TABLE `subscriptionhistory` CHANGE `enddate` `enddate` DATE NULL DEFAULT NULL ");
1956     $dbh->do("UPDATE subscriptionhistory SET enddate=NULL WHERE enddate='0000-00-00'");
1957     SetVersion ($DBversion);
1958 }
1959
1960 $DBversion = '3.00.00.107';
1961 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1962     $dbh->do(<<'END_SQL');
1963 UPDATE systempreferences
1964   SET explanation = CONCAT( explanation, '. WARNING: this feature is very resource consuming on collections with large numbers of items.' )
1965   WHERE variable = 'OPACShelfBrowser'
1966     AND explanation NOT LIKE '%WARNING%'
1967 END_SQL
1968     $dbh->do(<<'END_SQL');
1969 UPDATE systempreferences
1970   SET explanation = CONCAT( explanation, '. WARNING: this feature is very resource consuming.' )
1971   WHERE variable = 'CataloguingLog'
1972     AND explanation NOT LIKE '%WARNING%'
1973 END_SQL
1974     $dbh->do(<<'END_SQL');
1975 UPDATE systempreferences
1976   SET explanation = CONCAT( explanation, '. WARNING: using NoZebra on even modest sized collections is very slow.' )
1977   WHERE variable = 'NoZebra'
1978     AND explanation NOT LIKE '%WARNING%'
1979 END_SQL
1980     print "Upgrade to $DBversion done (warning added to OPACShelfBrowser system preference)\n";
1981     SetVersion ($DBversion);
1982 }
1983
1984 $DBversion = '3.01.00.000';
1985 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1986     print "Upgrade to $DBversion done (start of 3.1)\n";
1987     SetVersion ($DBversion);
1988 }
1989
1990 $DBversion = '3.01.00.001';
1991 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1992     $dbh->do("
1993         CREATE TABLE hold_fill_targets (
1994             `borrowernumber` int(11) NOT NULL,
1995             `biblionumber` int(11) NOT NULL,
1996             `itemnumber` int(11) NOT NULL,
1997             `source_branchcode`  varchar(10) default NULL,
1998             `item_level_request` tinyint(4) NOT NULL default 0,
1999             PRIMARY KEY `itemnumber` (`itemnumber`),
2000             KEY `bib_branch` (`biblionumber`, `source_branchcode`),
2001             CONSTRAINT `hold_fill_targets_ibfk_1` FOREIGN KEY (`borrowernumber`)
2002                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
2003             CONSTRAINT `hold_fill_targets_ibfk_2` FOREIGN KEY (`biblionumber`)
2004                 REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
2005             CONSTRAINT `hold_fill_targets_ibfk_3` FOREIGN KEY (`itemnumber`)
2006                 REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
2007             CONSTRAINT `hold_fill_targets_ibfk_4` FOREIGN KEY (`source_branchcode`)
2008                 REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
2009         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2010     ");
2011     $dbh->do("
2012         ALTER TABLE tmp_holdsqueue
2013             ADD item_level_request tinyint(4) NOT NULL default 0
2014     ");
2015
2016     print "Upgrade to $DBversion done (add hold_fill_targets table and a column to tmp_holdsqueue)\n";
2017     SetVersion($DBversion);
2018 }
2019
2020 $DBversion = '3.01.00.002';
2021 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2022     # use statistics where available
2023     $dbh->do("
2024         ALTER TABLE statistics ADD KEY  tmp_stats (type, itemnumber, borrowernumber)
2025     ");
2026     $dbh->do("
2027         UPDATE issues iss
2028         SET issuedate = (
2029             SELECT max(datetime)
2030             FROM statistics
2031             WHERE type = 'issue'
2032             AND itemnumber = iss.itemnumber
2033             AND borrowernumber = iss.borrowernumber
2034         )
2035         WHERE issuedate IS NULL;
2036     ");
2037     $dbh->do("ALTER TABLE statistics DROP KEY tmp_stats");
2038
2039     # default to last renewal date
2040     $dbh->do("
2041         UPDATE issues
2042         SET issuedate = lastreneweddate
2043         WHERE issuedate IS NULL
2044         and lastreneweddate IS NOT NULL
2045     ");
2046
2047     my $num_bad_issuedates = $dbh->selectrow_array("SELECT COUNT(*) FROM issues WHERE issuedate IS NULL");
2048     if ($num_bad_issuedates > 0) {
2049         print STDERR "After the upgrade to $DBversion, there are still $num_bad_issuedates loan(s) with a NULL (blank) loan date. ",
2050                      "Please check the issues table in your database.";
2051     }
2052     print "Upgrade to $DBversion done (bug 2582: set null issues.issuedate to lastreneweddate)\n";
2053     SetVersion($DBversion);
2054 }
2055
2056 $DBversion = "3.01.00.003";
2057 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2058     $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')");
2059     print "Upgrade to $DBversion done (add new syspref)\n";
2060     SetVersion ($DBversion);
2061 }
2062
2063 $DBversion = '3.01.00.004';
2064 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2065     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACDisplayRequestPriority','0','Show patrons the priority level on holds in the OPAC','','YesNo')");
2066     print "Upgrade to $DBversion done (added OPACDisplayRequestPriority system preference)\n";
2067     SetVersion ($DBversion);
2068 }
2069
2070 $DBversion = '3.01.00.005';
2071 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2072     $dbh->do("
2073         INSERT INTO `letter` (module, code, name, title, content)
2074         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>>')
2075     ");
2076     $dbh->do("INSERT INTO `message_attributes` (message_attribute_id, message_name, takes_days) values(4, 'Hold Filled', 0)");
2077     $dbh->do("INSERT INTO `message_transports` (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) values(4, 'sms', 0, 'reserves', 'HOLD')");
2078     $dbh->do("INSERT INTO `message_transports` (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) values(4, 'email', 0, 'reserves', 'HOLD')");
2079     print "Upgrade to $DBversion done (Add letter for holds notifications)\n";
2080     SetVersion ($DBversion);
2081 }
2082
2083 $DBversion = '3.01.00.006';
2084 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2085     $dbh->do("ALTER TABLE `biblioitems` ADD KEY issn (issn)");
2086     print "Upgrade to $DBversion done (add index on biblioitems.issn)\n";
2087     SetVersion ($DBversion);
2088 }
2089
2090 $DBversion = "3.01.00.007";
2091 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2092     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='intranetmainUserblock'");
2093     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='intranetuserjs'");
2094     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='opacheader'");
2095     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='OpacMainUserBlock'");
2096     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='OpacNav'");
2097     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='opacuserjs'");
2098     $dbh->do("UPDATE `systempreferences` SET options='30|10', type='Textarea' WHERE variable='OAI-PMH:Set'");
2099     $dbh->do("UPDATE `systempreferences` SET options='50' WHERE variable='intranetstylesheet'");
2100     $dbh->do("UPDATE `systempreferences` SET options='50' WHERE variable='intranetcolorstylesheet'");
2101     $dbh->do("UPDATE `systempreferences` SET options='10' WHERE variable='globalDueDate'");
2102     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='numSearchResults'");
2103     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='OPACnumSearchResults'");
2104     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='ReservesMaxPickupDelay'");
2105     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='TransfersMaxDaysWarning'");
2106     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='StaticHoldsQueueWeight'");
2107     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='holdCancelLength'");
2108     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='XISBNDailyLimit'");
2109     $dbh->do("UPDATE `systempreferences` SET type='Float' WHERE variable='gist'");
2110     $dbh->do("UPDATE `systempreferences` SET type='Free' WHERE variable='BakerTaylorUsername'");
2111     $dbh->do("UPDATE `systempreferences` SET type='Free' WHERE variable='BakerTaylorPassword'");
2112     $dbh->do("UPDATE `systempreferences` SET type='Textarea', options='70|10' WHERE variable='ISBD'");
2113     $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'");
2114     print "Upgrade to $DBversion done (fix display of many sysprefs)\n";
2115     SetVersion ($DBversion);
2116 }
2117
2118 $DBversion = '3.01.00.008';
2119 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2120
2121     $dbh->do("CREATE TABLE branch_transfer_limits (
2122                           limitId int(8) NOT NULL auto_increment,
2123                           toBranch varchar(4) NOT NULL,
2124                           fromBranch varchar(4) NOT NULL,
2125                           itemtype varchar(4) NOT NULL,
2126                           PRIMARY KEY  (limitId)
2127                           ) ENGINE=InnoDB DEFAULT CHARSET=utf8"
2128                         );
2129
2130     $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')");
2131
2132     print "Upgrade to $DBversion done (added branch_transfer_limits table and UseBranchTransferLimits system preference)\n";
2133     SetVersion ($DBversion);
2134 }
2135
2136 $DBversion = "3.01.00.009";
2137 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2138     $dbh->do("ALTER TABLE permissions MODIFY `code` varchar(64) DEFAULT NULL");
2139     $dbh->do("ALTER TABLE user_permissions MODIFY `code` varchar(64) DEFAULT NULL");
2140     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'circulate_remaining_permissions', 'Remaining circulation permissions')");
2141     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'override_renewals', 'Override blocked renewals')");
2142     print "Upgrade to $DBversion done (added subpermissions for circulate permission)\n";
2143 }
2144
2145 $DBversion = '3.01.00.010';
2146 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2147     $dbh->do("ALTER TABLE `borrower_attributes` MODIFY COLUMN `attribute` VARCHAR(64) DEFAULT NULL");
2148     $dbh->do("ALTER TABLE `borrower_attributes` MODIFY COLUMN `password` VARCHAR(64) DEFAULT NULL");
2149     print "Upgrade to $DBversion done (bug 2687: increase length of borrower attribute fields)\n";
2150     SetVersion ($DBversion);
2151 }
2152
2153 $DBversion = '3.01.00.011';
2154 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2155
2156     # Yes, the old value was ^M terminated.
2157     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);";
2158
2159     my $intranetuserjs = C4::Context->preference('intranetuserjs');
2160     if ($intranetuserjs  and  $intranetuserjs eq $bad_value) {
2161         my $sql = <<'END_SQL';
2162 UPDATE systempreferences
2163 SET value = ''
2164 WHERE variable = 'intranetuserjs'
2165 END_SQL
2166         $dbh->do($sql);
2167     }
2168     print "Upgrade to $DBversion done (removed bogus intranetuserjs syspref)\n";
2169     SetVersion($DBversion);
2170 }
2171
2172 $DBversion = "3.01.00.012";
2173 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2174     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowHoldPolicyOverride', '0', 'Allow staff to override hold policies when placing holds',NULL,'YesNo')");
2175     $dbh->do("
2176         CREATE TABLE `branch_item_rules` (
2177           `branchcode` varchar(10) NOT NULL,
2178           `itemtype` varchar(10) NOT NULL,
2179           `holdallowed` tinyint(1) default NULL,
2180           PRIMARY KEY  (`itemtype`,`branchcode`),
2181           KEY `branch_item_rules_ibfk_2` (`branchcode`),
2182           CONSTRAINT `branch_item_rules_ibfk_1` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE,
2183           CONSTRAINT `branch_item_rules_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
2184         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2185     ");
2186     $dbh->do("
2187         CREATE TABLE `default_branch_item_rules` (
2188           `itemtype` varchar(10) NOT NULL,
2189           `holdallowed` tinyint(1) default NULL,
2190           PRIMARY KEY  (`itemtype`),
2191           CONSTRAINT `default_branch_item_rules_ibfk_1` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE
2192         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2193     ");
2194     $dbh->do("
2195         ALTER TABLE default_branch_circ_rules
2196             ADD COLUMN holdallowed tinyint(1) NULL
2197     ");
2198     $dbh->do("
2199         ALTER TABLE default_circ_rules
2200             ADD COLUMN holdallowed tinyint(1) NULL
2201     ");
2202     print "Upgrade to $DBversion done (Add tables and system preferences for holds policies)\n";
2203     SetVersion ($DBversion);
2204 }
2205
2206 $DBversion = '3.01.00.013';
2207 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2208     $dbh->do("
2209         CREATE TABLE item_circulation_alert_preferences (
2210             id           int(11) AUTO_INCREMENT,
2211             branchcode   varchar(10) NOT NULL,
2212             categorycode varchar(10) NOT NULL,
2213             item_type    varchar(10) NOT NULL,
2214             notification varchar(16) NOT NULL,
2215             PRIMARY KEY (id),
2216             KEY (branchcode, categorycode, item_type, notification)
2217         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2218     ");
2219
2220     $dbh->do(q{ ALTER TABLE `message_queue` ADD metadata text DEFAULT NULL           AFTER content;  });
2221     $dbh->do(q{ ALTER TABLE `message_queue` ADD letter_code varchar(64) DEFAULT NULL AFTER metadata; });
2222
2223     $dbh->do(q{
2224         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
2225         ('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.');
2226     });
2227     $dbh->do(q{
2228         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
2229         ('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>>.');
2230     });
2231
2232     $dbh->do(q{INSERT INTO message_attributes (message_attribute_id, message_name, takes_days) VALUES (5, 'Item Check-in', 0);});
2233     $dbh->do(q{INSERT INTO message_attributes (message_attribute_id, message_name, takes_days) VALUES (6, 'Item Checkout', 0);});
2234
2235     $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');});
2236     $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');});
2237     $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');});
2238     $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');});
2239
2240     print "Upgrade to $DBversion done (data for Email Checkout Slips project)\n";
2241          SetVersion ($DBversion);
2242 }
2243
2244 $DBversion = "3.01.00.014";
2245 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2246     $dbh->do("ALTER TABLE `branch_transfer_limits` CHANGE `itemtype` `itemtype` VARCHAR( 4 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL");
2247     $dbh->do("ALTER TABLE `branch_transfer_limits` ADD `ccode` VARCHAR( 10 ) NULL ;");
2248     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2249     VALUES (
2250     'BranchTransferLimitsType', 'ccode', 'itemtype|ccode', 'When using branch transfer limits, choose whether to limit by itemtype or collection code.', 'Choice'
2251     );");
2252
2253     print "Upgrade to $DBversion done ( Updated table for Branch Transfer Limits)\n";
2254     SetVersion ($DBversion);
2255 }
2256
2257 $DBversion = '3.01.00.015';
2258 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2259     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsClientCode', '0', 'Client Code for using Syndetics Solutions content','','free')");
2260
2261     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsEnabled', '0', 'Turn on Syndetics Enhanced Content','','YesNo')");
2262
2263     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsCoverImages', '0', 'Display Cover Images from Syndetics','','YesNo')");
2264
2265     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsTOC', '0', 'Display Table of Content information from Syndetics','','YesNo')");
2266
2267     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsSummary', '0', 'Display Summary Information from Syndetics','','YesNo')");
2268
2269     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsEditions', '0', 'Display Editions from Syndetics','','YesNo')");
2270
2271     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsExcerpt', '0', 'Display Excerpts and first chapters on OPAC from Syndetics','','YesNo')");
2272
2273     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsReviews', '0', 'Display Reviews on OPAC from Syndetics','','YesNo')");
2274
2275     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsAuthorNotes', '0', 'Display Notes about the Author on OPAC from Syndetics','','YesNo')");
2276
2277     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsAwards', '0', 'Display Awards on OPAC from Syndetics','','YesNo')");
2278
2279     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsSeries', '0', 'Display Series information on OPAC from Syndetics','','YesNo')");
2280
2281     $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')");
2282
2283     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAmazonCoverImages', '0', 'Display cover images on OPAC from Amazon Web Services','','YesNo')");
2284
2285     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AmazonCoverImages', '0', 'Display Cover Images in Staff Client from Amazon Web Services','','YesNo')");
2286
2287     $dbh->do("UPDATE systempreferences SET variable='AmazonEnabled' WHERE variable = 'AmazonContent'");
2288
2289     $dbh->do("UPDATE systempreferences SET variable='OPACAmazonEnabled' WHERE variable = 'OPACAmazonContent'");
2290
2291     print "Upgrade to $DBversion done (added Syndetics Enhanced Content system preferences)\n";
2292     SetVersion ($DBversion);
2293 }
2294
2295 $DBversion = "3.01.00.016";
2296 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2297     $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')");
2298     print "Upgrade to $DBversion done (Added Babeltheque syspref)\n";
2299     SetVersion ($DBversion);
2300 }
2301
2302 $DBversion = "3.01.00.017";
2303 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2304     $dbh->do("ALTER TABLE `subscription` ADD `staffdisplaycount` VARCHAR(10) NULL;");
2305     $dbh->do("ALTER TABLE `subscription` ADD `opacdisplaycount` VARCHAR(10) NULL;");
2306     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2307     VALUES (
2308     'StaffSerialIssueDisplayCount', '3', '', 'Number of serial issues to display per subscription in the Staff client', 'Integer'
2309     );");
2310         $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2311     VALUES (
2312     'OPACSerialIssueDisplayCount', '3', '', 'Number of serial issues to display per subscription in the OPAC', 'Integer'
2313     );");
2314
2315     print "Upgrade to $DBversion done ( Updated table for Serials Display)\n";
2316     SetVersion ($DBversion);
2317 }
2318
2319 $DBversion = "3.01.00.018";
2320 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2321     $dbh->do("ALTER TABLE deletedborrowers ADD `smsalertnumber` varchar(50) default NULL");
2322     print "Upgrade to $DBversion done (added deletedborrowers.smsalertnumber, missed in 3.00.00.091)\n";
2323     SetVersion ($DBversion);
2324 }
2325
2326 $DBversion = "3.01.00.019";
2327 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2328         $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')");
2329     print "Upgrade to $DBversion done (adding OPACShowCheckoutName systempref)\n";
2330     SetVersion ($DBversion);
2331 }
2332
2333 $DBversion = "3.01.00.020";
2334 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2335     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesID','','See:http://librarything.com/forlibraries/','','free')");
2336     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesEnabled','0','Enable or Disable Library Thing for Libraries Features','','YesNo')");
2337     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesTabbedView','0','Put LibraryThingForLibraries Content in Tabs.','','YesNo')");
2338     print "Upgrade to $DBversion done (adding LibraryThing for Libraries sysprefs)\n";
2339     SetVersion ($DBversion);
2340 }
2341
2342 $DBversion = "3.01.00.021";
2343 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2344     my $enable_reviews = C4::Context->preference('OPACAmazonEnabled') ? '1' : '0';
2345     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAmazonReviews', '$enable_reviews', 'Display Amazon readers reviews on OPAC','','YesNo')");
2346     print "Upgrade to $DBversion done (adding OPACAmazonReviews syspref)\n";
2347     SetVersion ($DBversion);
2348 }
2349
2350 $DBversion = '3.01.00.022';
2351 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2352     $dbh->do("ALTER TABLE `labels_conf` MODIFY COLUMN `formatstring` mediumtext DEFAULT NULL");
2353     print "Upgrade to $DBversion done (bug 2945: increase size of labels_conf.formatstring)\n";
2354     SetVersion ($DBversion);
2355 }
2356
2357 $DBversion = '3.01.00.023';
2358 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2359     $dbh->do("ALTER TABLE biblioitems        MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2360     $dbh->do("ALTER TABLE deletedbiblioitems MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2361     $dbh->do("ALTER TABLE import_biblios     MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2362     $dbh->do("ALTER TABLE suggestions        MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2363     print "Upgrade to $DBversion done (bug 2765: increase width of isbn column in several tables)\n";
2364     SetVersion ($DBversion);
2365 }
2366
2367 $DBversion = "3.01.00.024";
2368 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2369     $dbh->do("ALTER TABLE labels MODIFY COLUMN batch_id int(10) NOT NULL default 1;");
2370     print "Upgrade to $DBversion done (change labels.batch_id from varchar to int)\n";
2371     SetVersion ($DBversion);
2372 }
2373
2374 $DBversion = '3.01.00.025';
2375 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2376     $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')");
2377
2378     print "Upgrade to $DBversion done (added ceilingDueDate system preference)\n";
2379     SetVersion ($DBversion);
2380 }
2381
2382 $DBversion = '3.01.00.026';
2383 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2384     $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')");
2385
2386     print "Upgrade to $DBversion done (added numReturnedItemsToShow system preference)\n";
2387     SetVersion ($DBversion);
2388 }
2389
2390 $DBversion = '3.01.00.027';
2391 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2392     $dbh->do("ALTER TABLE zebraqueue CHANGE `biblio_auth_number` `biblio_auth_number` bigint(20) unsigned NOT NULL default 0");
2393     print "Upgrade to $DBversion done (Increased size of zebraqueue biblio_auth_number to address bug 3148.)\n";
2394     SetVersion ($DBversion);
2395 }
2396
2397 $DBversion = '3.01.00.028';
2398 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2399     my $enable_reviews = C4::Context->preference('AmazonEnabled') ? '1' : '0';
2400     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AmazonReviews', '$enable_reviews', 'Display Amazon reviews on staff interface','','YesNo')");
2401     print "Upgrade to $DBversion done (added AmazonReviews)\n";
2402     SetVersion ($DBversion);
2403 }
2404
2405 $DBversion = '3.01.00.029';
2406 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2407     $dbh->do(q( UPDATE language_rfc4646_to_iso639
2408                 SET iso639_2_code = 'spa'
2409                 WHERE rfc4646_subtag = 'es'
2410                 AND   iso639_2_code = 'rus' )
2411             );
2412     print "Upgrade to $DBversion done (fixed bug 2599: using Spanish search limit retrieves Russian results)\n";
2413     SetVersion ($DBversion);
2414 }
2415
2416 $DBversion = "3.01.00.030";
2417 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2418     $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')");
2419     print "Upgrade to $DBversion done (added AllowNotForLoanOverride system preference)\n";
2420     SetVersion ($DBversion);
2421 }
2422
2423 $DBversion = "3.01.00.031";
2424 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2425     $dbh->do("ALTER TABLE branch_transfer_limits
2426               MODIFY toBranch   varchar(10) NOT NULL,
2427               MODIFY fromBranch varchar(10) NOT NULL,
2428               MODIFY itemtype   varchar(10) NULL");
2429     print "Upgrade to $DBversion done (fix column widths in branch_transfer_limits)\n";
2430     SetVersion ($DBversion);
2431 }
2432
2433 $DBversion = "3.01.00.032";
2434 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2435     $dbh->do(<<ENDOFRENEWAL);
2436 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');
2437 ENDOFRENEWAL
2438     print "Upgrade to $DBversion done (Change the field)\n";
2439     SetVersion ($DBversion);
2440 }
2441
2442 $DBversion = "3.01.00.033";
2443 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2444     $dbh->do(q/
2445         ALTER TABLE borrower_message_preferences
2446         MODIFY borrowernumber int(11) default NULL,
2447         ADD    categorycode varchar(10) default NULL AFTER borrowernumber,
2448         ADD KEY `categorycode` (`categorycode`),
2449         ADD CONSTRAINT `borrower_message_preferences_ibfk_3`
2450                        FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
2451                        ON DELETE CASCADE ON UPDATE CASCADE
2452     /);
2453     print "Upgrade to $DBversion done (DB changes to allow patron category defaults for messaging preferences)\n";
2454     SetVersion ($DBversion);
2455 }
2456
2457 $DBversion = "3.01.00.034";
2458 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2459     $dbh->do("ALTER TABLE `subscription` ADD COLUMN `graceperiod` INT(11) NOT NULL default '0';");
2460     print "Upgrade to $DBversion done (Adding graceperiod column to subscription table)\n";
2461     SetVersion ($DBversion);
2462 }
2463
2464 $DBversion = '3.01.00.035';
2465 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2466     $dbh->do(q{ ALTER TABLE `subscription` ADD location varchar(80) NULL DEFAULT '' AFTER callnumber; });
2467    print "Upgrade to $DBversion done (Adding location to subscription table)\n";
2468     SetVersion ($DBversion);
2469 }
2470
2471 $DBversion = '3.01.00.036';
2472 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2473     $dbh->do("UPDATE systempreferences SET explanation = 'Choose the default detail view in the staff interface; choose between normal, labeled_marc, marc or isbd'
2474               WHERE variable = 'IntranetBiblioDefaultView'
2475               AND   explanation = 'IntranetBiblioDefaultView'");
2476     $dbh->do("UPDATE systempreferences SET type = 'Choice', options = 'normal|marc|isbd|labeled_marc'
2477               WHERE variable = 'IntranetBiblioDefaultView'");
2478     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewISBD','1','Allow display of ISBD view of bibiographic records','','YesNo')");
2479     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewLabeledMARC','0','Allow display of labeled MARC view of bibiographic records','','YesNo')");
2480     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewMARC','1','Allow display of MARC view of bibiographic records','','YesNo')");
2481     print "Upgrade to $DBversion done (new viewISBD, viewLabeledMARC, viewMARC sysprefs and tweak IntranetBiblioDefaultView)\n";
2482     SetVersion ($DBversion);
2483 }
2484
2485 $DBversion = '3.01.00.037';
2486 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2487     $dbh->do('ALTER TABLE authorised_values ADD KEY `lib` (`lib`)');
2488     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('FilterBeforeOverdueReport','0','Do not run overdue report until filter selected','','YesNo')");
2489     SetVersion ($DBversion);
2490     print "Upgrade to $DBversion done (added FilterBeforeOverdueReport syspref and new index on authorised_values)\n";
2491 }
2492
2493 $DBversion = "3.01.00.038";
2494 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2495     # update branches table
2496     #
2497     $dbh->do("ALTER TABLE branches ADD `branchzip` varchar(25) default NULL AFTER `branchaddress3`");
2498     $dbh->do("ALTER TABLE branches ADD `branchcity` mediumtext AFTER `branchzip`");
2499     $dbh->do("ALTER TABLE branches ADD `branchcountry` text AFTER `branchcity`");
2500     $dbh->do("ALTER TABLE branches ADD `branchurl` mediumtext AFTER `branchemail`");
2501     $dbh->do("ALTER TABLE branches ADD `branchnotes` mediumtext AFTER `branchprinter`");
2502     print "Upgrade to $DBversion done (add ZIP, city, country, URL, and notes column to branches)\n";
2503     SetVersion ($DBversion);
2504 }
2505
2506 $DBversion = '3.01.00.039';
2507 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2508     $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')");
2509     $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')");
2510     SetVersion ($DBversion);
2511     print "Upgrade to $DBversion done (added SpineLabelFormat and SpineLabelAutoPrint sysprefs)\n";
2512 }
2513
2514 $DBversion = '3.01.00.040';
2515 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2516     $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')");
2517     $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')");
2518     SetVersion ($DBversion);
2519     print "Upgrade to $DBversion done (AllowHoldDateInFuture and OPACAllowHoldDateInFuture sysprefs)\n";
2520 }
2521
2522 $DBversion = '3.01.00.041';
2523 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2524     $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')");
2525     SetVersion ($DBversion);
2526     print "Upgrade to $DBversion done (added AWSPrivateKey syspref - note that if you use enhanced content from Amazon, this should be set right away.)\n";
2527 }
2528
2529 $DBversion = '3.01.00.042';
2530 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2531     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACFineNoRenewals','99999','Fine Limit above which user canmot renew books via OPAC','','Integer')");
2532     SetVersion ($DBversion);
2533     print "Upgrade to $DBversion done (added OPACFineNoRenewals syspref)\n";
2534 }
2535
2536 $DBversion = '3.01.00.043';
2537 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2538     $dbh->do('ALTER TABLE items ADD COLUMN permanent_location VARCHAR(80) DEFAULT NULL AFTER location');
2539     $dbh->do('UPDATE items SET permanent_location = location');
2540     $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 )', '')");
2541     $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')");
2542     $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')");
2543     SetVersion ($DBversion);
2544     print "Upgrade to $DBversion done (amended Item added NewItemsDefaultLocation, InProcessingToShelvingCart, ReturnToShelvingCart sysprefs)\n";
2545 }
2546
2547 $DBversion = '3.01.00.044';
2548 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2549     $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')");
2550     SetVersion ($DBversion);
2551     print "Upgrade to $DBversion done (added DisplayClearScreenButton system preference)\n";
2552 }
2553
2554 $DBversion = '3.01.00.045';
2555 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2556     $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')");
2557     SetVersion ($DBversion);
2558     print "Upgrade to $DBversion done (added a preference to hide the patrons name in the staff catalog)\n";
2559 }
2560
2561 $DBversion = "3.01.00.046";
2562 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2563     # update borrowers table
2564     #
2565     $dbh->do("ALTER TABLE borrowers ADD `country` text AFTER zipcode");
2566     $dbh->do("ALTER TABLE borrowers ADD `B_country` text AFTER B_zipcode");
2567     $dbh->do("ALTER TABLE deletedborrowers ADD `country` text AFTER zipcode");
2568     $dbh->do("ALTER TABLE deletedborrowers ADD `B_country` text AFTER B_zipcode");
2569     print "Upgrade to $DBversion done (add country and B_country to borrowers)\n";
2570     SetVersion ($DBversion);
2571 }
2572
2573 $DBversion = '3.01.00.047';
2574 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2575     $dbh->do("ALTER TABLE items MODIFY itemcallnumber varchar(255);");
2576     $dbh->do("ALTER TABLE deleteditems MODIFY itemcallnumber varchar(255);");
2577     $dbh->do("ALTER TABLE tmp_holdsqueue MODIFY itemcallnumber varchar(255);");
2578     SetVersion ($DBversion);
2579     print " Upgrade to $DBversion done (bug 2761: change max length of itemcallnumber to 255 from 30)\n";
2580 }
2581
2582 $DBversion = '3.01.00.048';
2583 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2584     $dbh->do("UPDATE userflags SET flagdesc='View Catalog (Librarian Interface)' WHERE bit=2;");
2585     $dbh->do("UPDATE userflags SET flagdesc='Edit Catalog (Modify bibliographic/holdings data)' WHERE bit=9;");
2586     $dbh->do("UPDATE userflags SET flagdesc='Allow to edit authorities' WHERE bit=14;");
2587     $dbh->do("UPDATE userflags SET flagdesc='Allow to access to the reports module' WHERE bit=16;");
2588     $dbh->do("UPDATE userflags SET flagdesc='Allow to manage serials subscriptions' WHERE bit=15;");
2589     SetVersion ($DBversion);
2590     print " Upgrade to $DBversion done (bug 2611: fix spelling/capitalization in permission flag descriptions)\n";
2591 }
2592
2593 $DBversion = '3.01.00.049';
2594 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2595     $dbh->do("UPDATE permissions SET description = 'Perform inventory (stocktaking) of your catalog' WHERE code = 'inventory';");
2596      SetVersion ($DBversion);
2597     print "Upgrade to $DBversion done (bug 2611: changed catalogue to catalog per the standard)\n";
2598 }
2599
2600 $DBversion = '3.01.00.050';
2601 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2602     $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');");
2603     SetVersion ($DBversion);
2604     print "Upgrade to $DBversion done (bug 1934: Add OPACSearchForTitleIn syspref)\n";
2605 }
2606
2607 $DBversion = '3.01.00.051';
2608 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2609     $dbh->do("UPDATE systempreferences SET explanation='Fine limit above which user cannot renew books via OPAC' WHERE variable='OPACFineNoRenewals';");
2610     $dbh->do("UPDATE systempreferences SET explanation='If set to ON, a clear screen button will appear on the circulation page.' WHERE variable='DisplayClearScreenButton';");
2611     SetVersion ($DBversion);
2612     print "Upgrade to $DBversion done (fixed typos in new sysprefs)\n";
2613 }
2614
2615 $DBversion = '3.01.00.052';
2616 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2617     $dbh->do('ALTER TABLE deleteditems ADD COLUMN permanent_location VARCHAR(80) DEFAULT NULL AFTER location');
2618     SetVersion ($DBversion);
2619     print "Upgrade to $DBversion done (bug 3481: add permanent_location column to deleteditems)\n";
2620 }
2621
2622 $DBversion = '3.01.00.053';
2623 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2624     my $upgrade_script = C4::Context->config("intranetdir") . "/installer/data/mysql/labels_upgrade.pl";
2625     system("perl $upgrade_script");
2626     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";
2627     SetVersion ($DBversion);
2628 }
2629
2630 $DBversion = '3.01.00.054';
2631 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2632     $dbh->do("ALTER TABLE borrowers ADD `B_address2` text AFTER B_address");
2633     $dbh->do("ALTER TABLE borrowers ADD `altcontactcountry` text AFTER altcontactzipcode");
2634     $dbh->do("ALTER TABLE deletedborrowers ADD `B_address2` text AFTER B_address");
2635     $dbh->do("ALTER TABLE deletedborrowers ADD `altcontactcountry` text AFTER altcontactzipcode");
2636     SetVersion ($DBversion);
2637     print "Upgrade to $DBversion done (bug 1600, bug 3454: add altcontactcountry and B_address2 to borrowers and deletedborrowers)\n";
2638 }
2639
2640 $DBversion = '3.01.00.055';
2641 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2642     $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'|);
2643     SetVersion ($DBversion);
2644     print "Upgrade to $DBversion done (changed OPACSearchForTitleIn per requests in bug 1934)\n";
2645 }
2646
2647 $DBversion = '3.01.00.056';
2648 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2649     $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');");
2650     SetVersion ($DBversion);
2651     print "Upgrade to $DBversion done (Bug 1172 : Add OPACPatronDetails syspref)\n";
2652 }
2653
2654 $DBversion = '3.01.00.057';
2655 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2656     $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');");
2657     SetVersion ($DBversion);
2658     print "Upgrade to $DBversion done (Bug 2576 : Add OPACFinesTab syspref)\n";
2659 }
2660
2661 $DBversion = '3.01.00.058';
2662 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2663     $dbh->do("ALTER TABLE `language_subtag_registry` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2664     $dbh->do("ALTER TABLE `language_rfc4646_to_iso639` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2665     $dbh->do("ALTER TABLE `language_descriptions` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2666     SetVersion ($DBversion);
2667     print "Upgrade to $DBversion done (Added primary keys to language tables)\n";
2668 }
2669
2670 $DBversion = '3.01.00.059';
2671 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2672     $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')");
2673     SetVersion ($DBversion);
2674     print "Upgrade to $DBversion done (added DisplayOPACiconsXSLT sysprefs)\n";
2675 }
2676
2677 $DBversion = '3.01.00.060';
2678 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2679     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowAllMessageDeletion','0','Allow any Library to delete any message','','YesNo');");
2680     $dbh->do('DROP TABLE IF EXISTS messages');
2681     $dbh->do("CREATE TABLE messages ( `message_id` int(11) NOT NULL auto_increment,
2682         `borrowernumber` int(11) NOT NULL,
2683         `branchcode` varchar(4) default NULL,
2684         `message_type` varchar(1) NOT NULL,
2685         `message` text NOT NULL,
2686         `message_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
2687         PRIMARY KEY (`message_id`)
2688         ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
2689
2690         print "Upgrade to $DBversion done ( Added AllowAllMessageDeletion syspref and messages table )\n";
2691     SetVersion ($DBversion);
2692 }
2693
2694 $DBversion = '3.01.00.061';
2695 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2696     $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')");
2697         print "Upgrade to $DBversion done ( Added ShowPatronImageInWebBasedSelfCheck system preference )\n";
2698     SetVersion ($DBversion);
2699 }
2700
2701 $DBversion = "3.01.00.062";
2702 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2703     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'manage_csv_profiles', 'Manage CSV export profiles')");
2704     $dbh->do(q/
2705         CREATE TABLE `export_format` (
2706           `export_format_id` int(11) NOT NULL auto_increment,
2707           `profile` varchar(255) NOT NULL,
2708           `description` mediumtext NOT NULL,
2709           `marcfields` mediumtext NOT NULL,
2710           PRIMARY KEY  (`export_format_id`)
2711         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Used for CSV export';
2712     /);
2713     print "Upgrade to $DBversion done (added csv export profiles)\n";
2714 }
2715
2716 $DBversion = "3.01.00.063";
2717 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2718     $dbh->do("
2719         CREATE TABLE `fieldmapping` (
2720           `id` int(11) NOT NULL auto_increment,
2721           `field` varchar(255) NOT NULL,
2722           `frameworkcode` char(4) NOT NULL default '',
2723           `fieldcode` char(3) NOT NULL,
2724           `subfieldcode` char(1) NOT NULL,
2725           PRIMARY KEY  (`id`)
2726         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2727              ");
2728     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";
2729 }
2730
2731 $DBversion = '3.01.00.065';
2732 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2733     $dbh->do('ALTER TABLE issuingrules ADD COLUMN `renewalsallowed` smallint(6) NOT NULL default "0" AFTER `issuelength`;');
2734     $sth = $dbh->prepare("SELECT itemtype, renewalsallowed FROM itemtypes");
2735     $sth->execute();
2736
2737     my $sthupd = $dbh->prepare("UPDATE issuingrules SET renewalsallowed = ? WHERE itemtype = ?");
2738
2739     while(my $row = $sth->fetchrow_hashref){
2740         $sthupd->execute($row->{renewalsallowed}, $row->{itemtype});
2741     }
2742
2743     $dbh->do('ALTER TABLE itemtypes DROP COLUMN `renewalsallowed`;');
2744
2745     SetVersion ($DBversion);
2746     print "Upgrade to $DBversion done (Moving allowed renewals from itemtypes to issuingrule)\n";
2747 }
2748
2749 $DBversion = '3.01.00.066';
2750 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2751     $dbh->do('ALTER TABLE issuingrules ADD COLUMN `reservesallowed` smallint(6) NOT NULL default "0" AFTER `renewalsallowed`;');
2752
2753     my $maxreserves = C4::Context->preference('maxreserves');
2754     $sth = $dbh->prepare('UPDATE issuingrules SET reservesallowed = ?;');
2755     $sth->execute($maxreserves);
2756
2757     $dbh->do('DELETE FROM systempreferences WHERE variable = "maxreserves";');
2758
2759     $dbh->do("INSERT INTO systempreferences (variable,value, options, explanation, type) VALUES('ReservesControlBranch','PatronLibrary','ItemHomeLibrary|PatronLibrary','Branch checked for members reservations rights','Choice')");
2760
2761     SetVersion ($DBversion);
2762     print "Upgrade to $DBversion done (Moving max allowed reserves from system preference to issuingrule)\n";
2763 }
2764
2765 $DBversion = "3.01.00.067";
2766 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2767     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'batchmod', 'Perform batch modification of items')");
2768     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'batchdel', 'Perform batch deletion of items')");
2769     print "Upgrade to $DBversion done (added permissions for batch modification and deletion)\n";
2770     SetVersion ($DBversion);
2771 }
2772
2773 $DBversion = "3.01.00.068";
2774 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2775         $dbh->do("ALTER TABLE issuingrules ADD COLUMN `finedays` int(11) default NULL AFTER `fine` ");
2776         print "Upgrade to $DBversion done (Adding finedays in issuingrules table)\n";
2777     SetVersion ($DBversion);
2778 }
2779
2780
2781 $DBversion = "3.01.00.069";
2782 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2783         $dbh->do("INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('EnableOpacSearchHistory', '1', '', 'Enable or disable opac search history', 'YesNo')");
2784
2785         my $create = <<SEARCHHIST;
2786 CREATE TABLE IF NOT EXISTS `search_history` (
2787   `userid` int(11) NOT NULL,
2788   `sessionid` varchar(32) NOT NULL,
2789   `query_desc` varchar(255) NOT NULL,
2790   `query_cgi` varchar(255) NOT NULL,
2791   `total` int(11) NOT NULL,
2792   `time` timestamp NOT NULL default CURRENT_TIMESTAMP,
2793   KEY `userid` (`userid`),
2794   KEY `sessionid` (`sessionid`)
2795 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Opac search history results';
2796 SEARCHHIST
2797         $dbh->do($create);
2798
2799         print "Upgrade to $DBversion done (added OPAC search history preference and table)\n";
2800 }
2801
2802 $DBversion = "3.01.00.070";
2803 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2804         $dbh->do("ALTER TABLE authorised_values ADD COLUMN `lib_opac` VARCHAR(80) default NULL AFTER `lib`");
2805         print "Upgrade to $DBversion done (Added a lib_opac field in authorised_values table)\n";
2806 }
2807
2808 $DBversion = "3.01.00.071";
2809 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2810         $dbh->do("ALTER TABLE `subscription` ADD `enddate` date default NULL");
2811         $dbh->do("ALTER TABLE subscriptionhistory CHANGE enddate histenddate DATE default NULL");
2812         print "Upgrade to $DBversion done ( Adding enddate to subscription)\n";
2813 }
2814
2815 # Acquisitions update
2816
2817 $DBversion = "3.01.00.072";
2818 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2819     $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')");
2820     # create a new syspref for the 'Mr anonymous' patron
2821     $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,'')");
2822     # fill AnonymousPatron with AnonymousSuggestion value (copy)
2823     my $sth=$dbh->prepare("SELECT value FROM systempreferences WHERE variable='AnonSuggestions'");
2824     $sth->execute;
2825     my ($value) = $sth->fetchrow() || 0;
2826     $dbh->do("UPDATE systempreferences SET value='$value' WHERE variable='AnonymousPatron'");
2827     # set AnonymousSuggestion do YesNo
2828     # 1st, set the value (1/True if it had a borrowernumber)
2829     $dbh->do("UPDATE systempreferences SET value=1 WHERE variable='AnonSuggestions' AND value>0");
2830     # 2nd, change the type to Choice
2831     $dbh->do("UPDATE systempreferences SET type='YesNo' WHERE variable='AnonSuggestions'");
2832         # borrower reading record privacy : 0 : forever, 1 : laws, 2 : don't keep at all
2833     $dbh->do("ALTER TABLE `borrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
2834     print "Upgrade to $DBversion done (add new syspref and column in borrowers)\n";
2835     SetVersion ($DBversion);
2836 }
2837
2838 $DBversion = '3.01.00.073';
2839 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2840     $dbh->do('SET FOREIGN_KEY_CHECKS=0 ');
2841     $dbh->do(<<'END_SQL');
2842 CREATE TABLE IF NOT EXISTS `aqcontract` (
2843   `contractnumber` int(11) NOT NULL auto_increment,
2844   `contractstartdate` date default NULL,
2845   `contractenddate` date default NULL,
2846   `contractname` varchar(50) default NULL,
2847   `contractdescription` mediumtext,
2848   `booksellerid` int(11) not NULL,
2849     PRIMARY KEY  (`contractnumber`),
2850         CONSTRAINT `booksellerid_fk1` FOREIGN KEY (`booksellerid`)
2851         REFERENCES `aqbooksellers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
2852 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
2853 END_SQL
2854     $dbh->do('SET FOREIGN_KEY_CHECKS=1 ');
2855     print "Upgrade to $DBversion done (adding aqcontract table)\n";
2856     SetVersion ($DBversion);
2857 }
2858
2859 $DBversion = '3.01.00.074';
2860 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2861     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `basketname` varchar(50) default NULL AFTER `basketno`");
2862     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `note` mediumtext AFTER `basketname`");
2863     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `booksellernote` mediumtext AFTER `note`");
2864     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `contractnumber` int(11) AFTER `booksellernote`");
2865     $dbh->do("ALTER TABLE `aqbasket` ADD FOREIGN KEY (`contractnumber`) REFERENCES `aqcontract` (`contractnumber`)");
2866     print "Upgrade to $DBversion done (edit aqbasket table done)\n";
2867     SetVersion ($DBversion);
2868 }
2869
2870 $DBversion = '3.01.00.075';
2871 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2872     $dbh->do("ALTER TABLE `aqorders` ADD COLUMN `uncertainprice` tinyint(1)");
2873
2874     print "Upgrade to $DBversion done (adding uncertainprices)\n";
2875     SetVersion ($DBversion);
2876 }
2877
2878 $DBversion = '3.01.00.076';
2879 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2880     $dbh->do('SET FOREIGN_KEY_CHECKS=0 ');
2881     $dbh->do("CREATE TABLE IF NOT EXISTS `aqbasketgroups` (
2882                          `id` int(11) NOT NULL auto_increment,
2883                          `name` varchar(50) default NULL,
2884                          `closed` tinyint(1) default NULL,
2885                          `booksellerid` int(11) NOT NULL,
2886                          PRIMARY KEY (`id`),
2887                          KEY `booksellerid` (`booksellerid`),
2888                          CONSTRAINT `aqbasketgroups_ibfk_1` FOREIGN KEY (`booksellerid`) REFERENCES `aqbooksellers` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
2889                          ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
2890     $dbh->do("ALTER TABLE aqbasket ADD COLUMN `basketgroupid` int(11)");
2891     $dbh->do("ALTER TABLE aqbasket ADD FOREIGN KEY (`basketgroupid`) REFERENCES `aqbasketgroups` (`id`) ON UPDATE CASCADE ON DELETE SET NULL");
2892     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('pdfformat','pdfformat::layout2pages','Controls what script is used for printing (basketgroups)','','free')");
2893     $dbh->do('SET FOREIGN_KEY_CHECKS=1 ');
2894     print "Upgrade to $DBversion done (adding basketgroups)\n";
2895     SetVersion ($DBversion);
2896 }
2897 $DBversion = '3.01.00.077';
2898 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2899
2900     $dbh->do("SET FOREIGN_KEY_CHECKS=0 ");
2901     # create a mapping table holding the info we need to match orders to budgets
2902     $dbh->do('DROP TABLE IF EXISTS fundmapping');
2903     $dbh->do(
2904         q|CREATE TABLE fundmapping AS
2905         SELECT aqorderbreakdown.ordernumber, branchcode, bookfundid, budgetdate, entrydate
2906         FROM aqorderbreakdown JOIN aqorders ON aqorderbreakdown.ordernumber = aqorders.ordernumber|);
2907     # match the new type of the corresponding field
2908     $dbh->do('ALTER TABLE fundmapping modify column bookfundid varchar(30)');
2909     # System did not ensure budgetdate was valid historically
2910     $dbh->do(q|UPDATE fundmapping SET budgetdate = entrydate WHERE budgetdate = '0000-00-00' OR budgetdate IS NULL|);
2911     # We save the map in fundmapping in case you need later processing
2912     $dbh->do(q|ALTER TABLE fundmapping add column aqbudgetid integer|);
2913     # these can speed processing up
2914     $dbh->do(q|CREATE INDEX fundmaporder ON fundmapping (ordernumber)|);
2915     $dbh->do(q|CREATE INDEX fundmapid ON fundmapping (bookfundid)|);
2916
2917     $dbh->do("DROP TABLE IF EXISTS `aqbudgetperiods` ");
2918
2919     $dbh->do(qq|
2920                     CREATE TABLE `aqbudgetperiods` (
2921                     `budget_period_id` int(11) NOT NULL auto_increment,
2922                     `budget_period_startdate` date NOT NULL,
2923                     `budget_period_enddate` date NOT NULL,
2924                     `budget_period_active` tinyint(1) default '0',
2925                     `budget_period_description` mediumtext,
2926                     `budget_period_locked` tinyint(1) default NULL,
2927                     `sort1_authcat` varchar(10) default NULL,
2928                     `sort2_authcat` varchar(10) default NULL,
2929                     PRIMARY KEY  (`budget_period_id`)
2930                     ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 |);
2931
2932    $dbh->do(<<ADDPERIODS);
2933 INSERT INTO aqbudgetperiods (budget_period_startdate,budget_period_enddate,budget_period_active,budget_period_description,budget_period_locked)
2934 SELECT DISTINCT startdate, enddate, NOW() BETWEEN startdate and enddate, concat(startdate," ",enddate),NOT NOW() BETWEEN startdate AND enddate from aqbudget
2935 ADDPERIODS
2936 # SORRY , NO AQBUDGET/AQBOOKFUND -> AQBUDGETS IMPORT JUST YET,
2937 # BUT A NEW CLEAN AQBUDGETS TABLE CREATE FOR NOW..
2938 # DROP TABLE IF EXISTS `aqbudget`;
2939 #CREATE TABLE `aqbudget` (
2940 #  `bookfundid` varchar(10) NOT NULL default ',
2941 #    `startdate` date NOT NULL default 0,
2942 #         `enddate` date default NULL,
2943 #           `budgetamount` decimal(13,2) default NULL,
2944 #                 `aqbudgetid` tinyint(4) NOT NULL auto_increment,
2945 #                   `branchcode` varchar(10) default NULL,
2946     DropAllForeignKeys('aqbudget');
2947   #$dbh->do("drop table aqbudget;");
2948
2949
2950     my $maxbudgetid = $dbh->selectcol_arrayref(<<IDsBUDGET);
2951 SELECT MAX(aqbudgetid) from aqbudget
2952 IDsBUDGET
2953
2954 $$maxbudgetid[0] = 0 if !$$maxbudgetid[0];
2955
2956     $dbh->do(<<BUDGETAUTOINCREMENT);
2957 ALTER TABLE aqbudget AUTO_INCREMENT=$$maxbudgetid[0]
2958 BUDGETAUTOINCREMENT
2959
2960     $dbh->do(<<BUDGETNAME);
2961 ALTER TABLE aqbudget RENAME `aqbudgets`
2962 BUDGETNAME
2963
2964     $dbh->do(<<BUDGETS);
2965 ALTER TABLE `aqbudgets`
2966    CHANGE  COLUMN aqbudgetid `budget_id` int(11) NOT NULL AUTO_INCREMENT,
2967    CHANGE  COLUMN branchcode `budget_branchcode` varchar(10) default NULL,
2968    CHANGE  COLUMN budgetamount `budget_amount` decimal(28,6) NOT NULL default '0.00',
2969    CHANGE  COLUMN bookfundid   `budget_code` varchar(30) default NULL,
2970    ADD     COLUMN `budget_parent_id` int(11) default NULL,
2971    ADD     COLUMN `budget_name` varchar(80) default NULL,
2972    ADD     COLUMN `budget_encumb` decimal(28,6) default '0.00',
2973    ADD     COLUMN `budget_expend` decimal(28,6) default '0.00',
2974    ADD     COLUMN `budget_notes` mediumtext,
2975    ADD     COLUMN `budget_description` mediumtext,
2976    ADD     COLUMN `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
2977    ADD     COLUMN `budget_amount_sublevel`  decimal(28,6) AFTER `budget_amount`,
2978    ADD     COLUMN `budget_period_id` int(11) default NULL,
2979    ADD     COLUMN `sort1_authcat` varchar(80) default NULL,
2980    ADD     COLUMN `sort2_authcat` varchar(80) default NULL,
2981    ADD     COLUMN `budget_owner_id` int(11) default NULL,
2982    ADD     COLUMN `budget_permission` int(1) default '0';
2983 BUDGETS
2984
2985     $dbh->do(<<BUDGETCONSTRAINTS);
2986 ALTER TABLE `aqbudgets`
2987    ADD CONSTRAINT `aqbudgets_ifbk_1` FOREIGN KEY (`budget_period_id`) REFERENCES `aqbudgetperiods` (`budget_period_id`) ON DELETE CASCADE ON UPDATE CASCADE
2988 BUDGETCONSTRAINTS
2989 #    $dbh->do(<<BUDGETPKDROP);
2990 #ALTER TABLE `aqbudgets`
2991 #   DROP PRIMARY KEY
2992 #BUDGETPKDROP
2993 #    $dbh->do(<<BUDGETPKADD);
2994 #ALTER TABLE `aqbudgets`
2995 #   ADD PRIMARY KEY budget_id
2996 #BUDGETPKADD
2997
2998
2999         my $query_period= $dbh->prepare(qq|SELECT budget_period_id from aqbudgetperiods where budget_period_startdate=? and budget_period_enddate=?|);
3000         my $query_bookfund= $dbh->prepare(qq|SELECT * from aqbookfund where bookfundid=?|);
3001         my $selectbudgets=$dbh->prepare(qq|SELECT * from aqbudgets|);
3002         my $updatebudgets=$dbh->prepare(qq|UPDATE aqbudgets SET budget_period_id= ? , budget_name=?, budget_branchcode=? where budget_id=?|);
3003         $selectbudgets->execute;
3004         while (my $databudget=$selectbudgets->fetchrow_hashref){
3005                 $query_period->execute ($$databudget{startdate},$$databudget{enddate});
3006                 my ($budgetperiodid)=$query_period->fetchrow;
3007                 $query_bookfund->execute ($$databudget{budget_code});
3008                 my $databf=$query_bookfund->fetchrow_hashref;
3009                 my $branchcode=$$databudget{budget_branchcode}||$$databf{branchcode};
3010                 $updatebudgets->execute($budgetperiodid,$$databf{bookfundname},$branchcode,$$databudget{budget_id});
3011         }
3012     $dbh->do(<<BUDGETDROPDATES);
3013 ALTER TABLE `aqbudgets`
3014    DROP startdate,
3015    DROP enddate
3016 BUDGETDROPDATES
3017
3018
3019     $dbh->do("DROP TABLE IF EXISTS `aqbudgets_planning` ");
3020     $dbh->do("CREATE TABLE  `aqbudgets_planning` (
3021                     `plan_id` int(11) NOT NULL auto_increment,
3022                     `budget_id` int(11) NOT NULL,
3023                     `budget_period_id` int(11) NOT NULL,
3024                     `estimated_amount` decimal(28,6) default NULL,
3025                     `authcat` varchar(30) NOT NULL,
3026                     `authvalue` varchar(30) NOT NULL,
3027                                         `display` tinyint(1) DEFAULT 1,
3028                         PRIMARY KEY  (`plan_id`),
3029                         CONSTRAINT `aqbudgets_planning_ifbk_1` FOREIGN KEY (`budget_id`) REFERENCES `aqbudgets` (`budget_id`) ON DELETE CASCADE ON UPDATE CASCADE
3030                         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
3031
3032     $dbh->do("ALTER TABLE `aqorders`
3033                     ADD COLUMN `budget_id` tinyint(4) NOT NULL,
3034                     ADD COLUMN `budgetgroup_id` int(11) NOT NULL,
3035                     ADD COLUMN  `sort1_authcat` varchar(10) default NULL,
3036                     ADD COLUMN  `sort2_authcat` varchar(10) default NULL" );
3037                 # We need to map the orders to the budgets
3038                 # For Historic reasons this is more complex than it should be on occasions
3039                 my $budg_arr = $dbh->selectall_arrayref(
3040                     q|SELECT aqbudgets.budget_id, aqbudgets.budget_code, aqbudgetperiods.budget_period_startdate,
3041                     aqbudgetperiods.budget_period_enddate
3042                     FROM aqbudgets JOIN aqbudgetperiods ON aqbudgets.budget_period_id = aqbudgetperiods.budget_period_id
3043                     ORDER BY budget_code, budget_period_startdate|, { Slice => {} });
3044                 # We arbitarily order on start date, this means if you have overlapping periods the order will be
3045                 # linked to the latest matching budget YMMV
3046                 my $b_sth = $dbh->prepare(
3047                     'UPDATE fundmapping set aqbudgetid = ? where bookfundid =? AND budgetdate >= ? AND budgetdate <= ?');
3048                 for my $b ( @{$budg_arr}) {
3049                     $b_sth->execute($b->{budget_id}, $b->{budget_code}, $b->{budget_period_startdate}, $b->{budget_period_enddate});
3050                 }
3051                 # move the budgetids to aqorders
3052                 $dbh->do(q|UPDATE aqorders, fundmapping SET aqorders.budget_id = fundmapping.aqbudgetid
3053                     WHERE aqorders.ordernumber = fundmapping.ordernumber AND fundmapping.aqbudgetid IS NOT NULL|);
3054                 # NB fundmapping is left as an accontants trail also if you have budgetids that werent set
3055                 # you can decide what to do with them
3056
3057      $dbh->do(
3058          q|UPDATE aqorders, aqbudgets SET aqorders.budgetgroup_id = aqbudgets.budget_period_id
3059          WHERE aqorders.budget_id = aqbudgets.budget_id|);
3060                 # cannot do until aqorderbreakdown removed
3061 #    $dbh->do("DROP TABLE aqbookfund ");
3062 #    $dbh->do("ALTER TABLE aqorders  ADD FOREIGN KEY (`budget_id`) REFERENCES `aqbudgets` (`budget_id`) ON UPDATE CASCADE  " ); ????
3063     $dbh->do("SET FOREIGN_KEY_CHECKS=1 ");
3064
3065     print "Upgrade to $DBversion done (Adding new aqbudgetperiods, aqbudgets and aqbudget_planning tables  )\n";
3066     SetVersion ($DBversion);
3067 }
3068
3069
3070
3071 $DBversion = '3.01.00.078';
3072 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3073     $dbh->do("ALTER TABLE aqbudgetperiods ADD COLUMN budget_period_total decimal(28,6)");
3074     print "Upgrade to $DBversion done (adds 'budget_period_total' column to aqbudgetperiods table)\n";
3075     SetVersion($DBversion);
3076 }
3077
3078
3079 $DBversion = '3.01.00.079';
3080 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3081     $dbh->do("ALTER TABLE currency ADD COLUMN active  tinyint(1)");
3082
3083     print "Upgrade to $DBversion done (adds 'active' column to currencies table)\n";
3084     SetVersion($DBversion);
3085 }
3086
3087 $DBversion = '3.01.00.080';
3088 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3089     $dbh->do(<<BUDG_PERM );
3090 INSERT INTO permissions (module_bit, code, description) VALUES
3091             (11, 'vendors_manage', 'Manage vendors'),
3092             (11, 'contracts_manage', 'Manage contracts'),
3093             (11, 'period_manage', 'Manage periods'),
3094             (11, 'budget_manage', 'Manage budgets'),
3095             (11, 'budget_modify', "Modify budget (can't create lines but can modify existing ones)"),
3096             (11, 'planning_manage', 'Manage budget plannings'),
3097             (11, 'order_manage', 'Manage orders & basket'),
3098             (11, 'group_manage', 'Manage orders & basketgroups'),
3099             (11, 'order_receive', 'Manage orders & basket'),
3100             (11, 'budget_add_del', "Add and delete budgets (but can't modify budgets)");
3101 BUDG_PERM
3102
3103     print "Upgrade to $DBversion done (adds permissions for the acquisitions module)\n";
3104     SetVersion($DBversion);
3105 }
3106
3107
3108 $DBversion = '3.01.00.081';
3109 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3110     $dbh->do("ALTER TABLE aqbooksellers ADD COLUMN `gstrate` decimal(6,4) default NULL");
3111     if (my $gist=C4::Context->preference("gist")){
3112                 my $sql=$dbh->prepare("UPDATE aqbooksellers set `gstrate`=? ");
3113         $sql->execute($gist) ;
3114         }
3115     print "Upgrade to $DBversion done (added per-supplier gstrate setting)\n";
3116     SetVersion($DBversion);
3117 }
3118
3119 $DBversion = "3.01.00.082";
3120 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3121     if (C4::Context->preference("opaclanguages") eq "fr") {
3122         $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')#);
3123     } else {
3124         $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')");
3125     }
3126     print "Upgrade to $DBversion done (adding ReservesNeedReturns systempref, in circulation)\n";
3127     SetVersion ($DBversion);
3128 }
3129
3130 $DBversion = "3.01.00.083";
3131 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3132     $dbh->do(qq|
3133  CREATE TABLE `aqorders_items` (
3134   `ordernumber` int(11) NOT NULL,
3135   `itemnumber` int(11) NOT NULL,
3136   `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
3137   PRIMARY KEY  (`itemnumber`),
3138   KEY `ordernumber` (`ordernumber`)
3139 ) ENGINE=InnoDB DEFAULT CHARSET=utf8   |
3140     );
3141
3142     $dbh->do(qq| DROP TABLE aqorderbreakdown |);
3143     $dbh->do('DROP TABLE aqbookfund');
3144     print "Upgrade to $DBversion done (New aqorders_items table for acqui)\n";
3145     SetVersion ($DBversion);
3146 }
3147
3148 $DBversion = "3.01.00.084";
3149 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3150     $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')  #);
3151
3152     print "Upgrade to $DBversion done (CurrencyFormat syspref added)\n";
3153     SetVersion ($DBversion);
3154 }
3155
3156 $DBversion = "3.01.00.085";
3157 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3158     $dbh->do("ALTER table aqorders drop column title");
3159     $dbh->do("ALTER TABLE `aqorders` CHANGE `budget_id` `budget_id` INT( 11 ) NOT NULL");
3160     print "Upgrade to $DBversion done update budget_id size that should not be a tinyint\n";
3161     SetVersion ($DBversion);
3162 }
3163
3164 $DBversion = "3.01.00.086";
3165 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3166     $dbh->do(<<SUGGESTIONS);
3167 ALTER table suggestions
3168     ADD budgetid INT(11),
3169     ADD branchcode VARCHAR(10) default NULL,
3170     ADD acceptedby INT(11) default NULL,
3171     ADD accepteddate date default NULL,
3172     ADD suggesteddate date default NULL,
3173     ADD manageddate date default NULL,
3174     ADD rejectedby INT(11) default NULL,
3175     ADD rejecteddate date default NULL,
3176     ADD collectiontitle text default NULL,
3177     ADD itemtype VARCHAR(30) default NULL
3178     ;
3179 SUGGESTIONS
3180     print "Upgrade to $DBversion done (Suggestions)\n";
3181     SetVersion ($DBversion);
3182 }
3183
3184 $DBversion = "3.01.00.087";
3185 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3186     $dbh->do("ALTER table aqbudgets drop column budget_amount_sublevel;");
3187     print "Upgrade to $DBversion done (Drop column budget_amount_sublevel from aqbudgets)\n";
3188     SetVersion ($DBversion);
3189 }
3190
3191 $DBversion = "3.01.00.088";
3192 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3193     $dbh->do(  qq# INSERT INTO `systempreferences` VALUES ('intranetbookbag','1','','If ON, enables display of Cart feature in the intranet','YesNo')  #);
3194
3195     print "Upgrade to $DBversion done (intranetbookbag syspref added)\n";
3196     SetVersion ($DBversion);
3197 }
3198
3199 $DBversion = "3.01.00.090";
3200 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3201 $dbh->do("
3202        INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3203                 (16, 'execute_reports', 'Execute SQL reports'),
3204                 (16, 'create_reports', 'Create SQL Reports')
3205         ");
3206
3207     print "Upgrade to $DBversion done (granular permissions for guided reports added)\n";
3208     SetVersion ($DBversion);
3209 }
3210
3211 $DBversion = "3.01.00.091";
3212 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3213 $dbh->do("
3214         UPDATE `systempreferences` SET `options` = 'holdings|serialcollection|subscriptions'
3215         WHERE `systempreferences`.`variable` = 'opacSerialDefaultTab' LIMIT 1
3216         ");
3217
3218     print "Upgrade to $DBversion done (opac-detail default tag updated)\n";
3219     SetVersion ($DBversion);
3220 }
3221
3222 $DBversion = "3.01.00.092";
3223 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3224     if (C4::Context->preference("opaclanguages") =~ /fr/) {
3225         $dbh->do(qq{
3226 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');
3227         });
3228         }else{
3229         $dbh->do(qq{
3230 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');
3231         });
3232         }
3233     print "Upgrade to $DBversion done (Added RoutingListAddReserves syspref)\n";
3234     SetVersion ($DBversion);
3235 }
3236
3237 $DBversion = "3.01.00.093";
3238 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3239         $dbh->do(qq{
3240         ALTER TABLE biblioitems ADD INDEX issn_idx (issn);
3241         });
3242     print "Upgrade to $DBversion done (added index to ISSN)\n";
3243     SetVersion ($DBversion);
3244 }
3245
3246 $DBversion = "3.01.00.094";
3247 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3248         $dbh->do(qq{
3249         ALTER TABLE aqbasketgroups ADD deliveryplace VARCHAR(10) default NULL, ADD deliverycomment VARCHAR(255) default NULL;
3250         });
3251
3252     print "Upgrade to $DBversion done (adding deliveryplace deliverycomment to basketgroups)\n";
3253     SetVersion ($DBversion);
3254 }
3255
3256 $DBversion = "3.01.00.095";
3257 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3258         $dbh->do(qq{
3259         ALTER TABLE items ADD stocknumber VARCHAR(32) DEFAULT NULL COMMENT "stores the inventory number";
3260         });
3261         $dbh->do(qq{
3262         ALTER TABLE items ADD UNIQUE INDEX itemsstocknumberidx (stocknumber);
3263         });
3264         $dbh->do(qq{
3265         ALTER TABLE deleteditems ADD stocknumber VARCHAR(32) DEFAULT NULL COMMENT "stores the inventory number of deleted items";
3266         });
3267         $dbh->do(qq{
3268         ALTER TABLE deleteditems ADD UNIQUE INDEX deleteditemsstocknumberidx (stocknumber);
3269         });
3270         if (C4::Context->preference('marcflavour') eq 'UNIMARC'){
3271                 $dbh->do(qq{
3272         INSERT IGNORE INTO marc_subfield_structure (frameworkcode,tagfield, tagsubfield, tab, repeatable, mandatory,kohafield)
3273         SELECT DISTINCT (frameworkcode),995,"j",10,0,0,"items.stocknumber" from biblio_framework ;
3274                 });
3275                 #Previously, copynumber was used as stocknumber
3276                 $dbh->do(qq{
3277         UPDATE items set stocknumber=copynumber;
3278                 });
3279                 $dbh->do(qq{
3280         UPDATE items set copynumber=NULL;
3281                 });
3282         }
3283     print "Upgrade to $DBversion done (stocknumber field added)\n";
3284     SetVersion ($DBversion);
3285 }
3286
3287 $DBversion = "3.01.00.096";
3288 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3289     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OrderPdfTemplate','','Uploads a PDF template to use for printing baskets','NULL','Upload')");
3290     $dbh->do("UPDATE systempreferences SET variable='OrderPdfFormat' WHERE variable='pdfformat'");
3291     print "Upgrade to $DBversion done (PDF orders system preferences added and updated)\n";
3292     SetVersion ($DBversion);
3293 }
3294
3295 $DBversion = "3.01.00.097";
3296 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3297         $dbh->do(qq{
3298         ALTER TABLE aqbasketgroups ADD billingplace VARCHAR(10) NOT NULL AFTER deliverycomment;
3299         });
3300
3301     print "Upgrade to $DBversion done (Adding billingplace to aqbasketgroups)\n";
3302     SetVersion ($DBversion);
3303 }
3304
3305 $DBversion = "3.01.00.098";
3306 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3307         $dbh->do(qq{
3308         ALTER TABLE auth_subfield_structure MODIFY frameworkcode VARCHAR(10) NULL;
3309         });
3310
3311     print "Upgrade to $DBversion done (changing frameworkcode length in auth_subfield_structure)\n";
3312     SetVersion ($DBversion);
3313 }
3314
3315 $DBversion = "3.01.00.099";
3316 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3317         $dbh->do(qq{
3318                 INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3319                 (9, 'edit_catalogue', 'Edit catalogue'),
3320                 (9, 'fast_cataloging', 'Fast cataloging')
3321         });
3322
3323     print "Upgrade to $DBversion done (granular permissions for cataloging added)\n";
3324     SetVersion ($DBversion);
3325 }
3326
3327 $DBversion = "3.01.00.100";
3328 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3329         $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')");
3330         print "Upgrade to $DBversion done (added CAS authentication system preferences)\n";
3331     SetVersion ($DBversion);
3332 }
3333
3334 $DBversion = "3.01.00.101";
3335 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3336         $dbh->do(
3337         "INSERT INTO systempreferences
3338            (variable, value, options, explanation, type)
3339          VALUES (
3340             'OverdueNoticeBcc', '', '',
3341             'Email address to Bcc outgoing notices sent by email',
3342             'free')
3343          ");
3344         print "Upgrade to $DBversion done (added OverdueNoticeBcc system preferences)\n";
3345     SetVersion ($DBversion);
3346 }
3347 $DBversion = "3.01.00.102";
3348 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3349     $dbh->do(
3350     "UPDATE permissions set description = 'Edit catalog (Modify bibliographic/holdings data)' where module_bit = 9 and code = 'edit_catalogue'"
3351     );
3352         print "Upgrade to $DBversion done (fixed spelling error in edit_catalogue permission)\n";
3353     SetVersion ($DBversion);
3354 }
3355
3356 $DBversion = "3.01.00.103";
3357 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3358         $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES (13, 'moderate_tags', 'Moderate patron tags')");
3359         print "Upgrade to $DBversion done (adding patron permissions for tags tool)\n";
3360     SetVersion ($DBversion);
3361 }
3362
3363 $DBversion = "3.01.00.104";
3364 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3365
3366     my ($maninv_count, $borrnotes_count);
3367     eval { $maninv_count = $dbh->do("SELECT 1 FROM authorised_values WHERE category='MANUAL_INV'"); };
3368     if ($maninv_count == 0) {
3369         $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('MANUAL_INV','Copier Fees','.25')");
3370     }
3371     eval { $borrnotes_count = $dbh->do("SELECT 1 FROM authorised_values WHERE category='BOR_NOTES'"); };
3372     if ($borrnotes_count == 0) {
3373         $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('BOR_NOTES','ADDR','Address Notes')");
3374     }
3375
3376     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('LOC','CART','Book Cart')");
3377     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('LOC','PROC','Processing Center')");
3378
3379         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";
3380         SetVersion ($DBversion);
3381 }
3382
3383
3384 $DBversion = "3.01.00.105";
3385 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3386     $dbh->do("
3387       CREATE TABLE `collections` (
3388         `colId` int(11) NOT NULL auto_increment,
3389         `colTitle` varchar(100) NOT NULL default '',
3390         `colDesc` text NOT NULL,
3391         `colBranchcode` varchar(4) default NULL COMMENT 'branchcode for branch where item should be held.',
3392         PRIMARY KEY  (`colId`)
3393       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3394     ");
3395
3396     $dbh->do("
3397       CREATE TABLE `collections_tracking` (
3398         `ctId` int(11) NOT NULL auto_increment,
3399         `colId` int(11) NOT NULL default '0' COMMENT 'collections.colId',
3400         `itemnumber` int(11) NOT NULL default '0' COMMENT 'items.itemnumber',
3401         PRIMARY KEY  (`ctId`)
3402       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3403     ");
3404     $dbh->do("
3405         INSERT INTO permissions (module_bit, code, description)
3406         VALUES ( 13, 'rotating_collections', 'Manage Rotating collections')" );
3407         print "Upgrade to $DBversion done (added collection and collection_tracking tables for rotating collections functionality)\n";
3408     SetVersion ($DBversion);
3409 }
3410 $DBversion = "3.01.00.106";
3411 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3412         $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' )");
3413         print "Upgrade to $DBversion done (added OpacAddMastheadLibraryPulldown system preferences)\n";
3414     SetVersion ($DBversion);
3415 }
3416
3417 $DBversion = '3.01.00.107';
3418 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3419     my $upgrade_script = C4::Context->config("intranetdir") . "/installer/data/mysql/patroncards_upgrade.pl";
3420     system("perl $upgrade_script");
3421     print "Upgrade to $DBversion done (Migrated labels and patroncards tables and data to new schema.)\n";
3422     SetVersion ($DBversion);
3423 }
3424
3425 $DBversion = '3.01.00.108';
3426 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3427         $dbh->do(qq{
3428     ALTER TABLE `export_format` ADD `csv_separator` VARCHAR( 2 ) NOT NULL AFTER `marcfields` ,
3429     ADD `field_separator` VARCHAR( 2 ) NOT NULL AFTER `csv_separator` ,
3430     ADD `subfield_separator` VARCHAR( 2 ) NOT NULL AFTER `field_separator`
3431     });
3432         print "Upgrade to $DBversion done (added separators for csv export)\n";
3433     SetVersion ($DBversion);
3434 }
3435
3436 $DBversion = "3.01.00.109";
3437 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3438         $dbh->do(qq{
3439         ALTER TABLE `export_format` ADD `encoding` VARCHAR(255) NOT NULL AFTER `subfield_separator`
3440         });
3441         print "Upgrade to $DBversion done (added encoding for csv export)\n";
3442     SetVersion ($DBversion);
3443 }
3444
3445 $DBversion = '3.01.00.110';
3446 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3447     $dbh->do('ALTER TABLE `categories` ADD COLUMN `enrolmentperioddate` DATE NULL DEFAULT NULL AFTER `enrolmentperiod`');
3448     print "Upgrade to $DBversion done (Add enrolment period date support)\n";
3449     SetVersion ($DBversion);
3450 }
3451
3452 $DBversion = '3.01.00.111';
3453 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3454     print "Upgrade to $DBversion done (mark DBrev for 3.2-alpha release)\n";
3455     SetVersion ($DBversion);
3456 }
3457
3458 $DBversion = '3.01.00.112';
3459 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3460         $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');");
3461         print "Upgrade to $DBversion done ( added Show Spine Label Printer on Bib Items Details preferences )\n";
3462     SetVersion ($DBversion);
3463 }
3464
3465 $DBversion = '3.01.00.113';
3466 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3467     my $value = C4::Context->preference("XSLTResultsDisplay");
3468     $dbh->do(
3469         "INSERT INTO systempreferences (variable,value,type)
3470          VALUES('OPACXSLTResultsDisplay',?,'YesNo')", {}, $value ? 1 : 0);
3471     $value = C4::Context->preference("XSLTDetailsDisplay");
3472     $dbh->do(
3473         "INSERT INTO systempreferences (variable,value,type)
3474          VALUES('OPACXSLTDetailsDisplay',?,'YesNo')", {}, $value ? 1 : 0);
3475     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";
3476     SetVersion ($DBversion);
3477 }
3478
3479 $DBversion = '3.01.00.114';
3480 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3481     $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')");
3482     $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')");
3483     $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')");
3484         print "Upgrade to $DBversion done ( Added AutoSelfCheckAllowed, AutoSelfCheckID, and AutoShelfCheckPass system preference )\n";
3485     SetVersion ($DBversion);
3486 }
3487
3488 $DBversion = '3.01.00.115';
3489 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3490     $dbh->do('UPDATE aqorders SET quantityreceived = 0 WHERE quantityreceived IS NULL');
3491     $dbh->do('ALTER TABLE aqorders MODIFY COLUMN quantityreceived smallint(6) NOT NULL DEFAULT 0');
3492         print "Upgrade to $DBversion done ( Default aqorders.quantityreceived to 0 )\n";
3493     SetVersion ($DBversion);
3494 }
3495
3496 $DBversion = '3.01.00.116';
3497 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3498         if (C4::Context->preference('OrderPdfFormat') eq 'pdfformat::example'){
3499                 $dbh->do("UPDATE `systempreferences` set value='pdfformat::layout2pages' WHERE variable='OrderPdfFormat'");
3500         }
3501         print "Upgrade to $DBversion done (corrected default OrderPdfFormat value if still set wrong )\n";
3502     SetVersion ($DBversion);
3503 }
3504
3505 $DBversion = '3.01.00.117';
3506 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3507     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'por' WHERE rfc4646_subtag='pt' ");
3508     print "Upgrade to $DBversion done (corrected ISO 639-2 language code for Portuguese)\n";
3509     SetVersion ($DBversion);
3510 }
3511
3512 $DBversion = '3.01.00.118';
3513 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3514     my ($count) = $dbh->selectrow_array("SELECT count(*) FROM information_schema.columns
3515                                          WHERE table_name = 'aqbudgets_planning'
3516                                          AND column_name = 'display'");
3517     if ($count < 1) {
3518         $dbh->do("ALTER TABLE aqbudgets_planning ADD COLUMN display tinyint(1) DEFAULT 1");
3519     }
3520     print "Upgrade to $DBversion done (bug 4203: add display column to aqbudgets_planning if missing)\n";
3521     SetVersion ($DBversion);
3522 }
3523
3524 $DBversion = '3.01.00.119';
3525 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3526     eval{require Locale::Currency::Format};
3527     if (!$@) {
3528         print "Upgrade to $DBversion done (Locale::Currency::Format installed.)\n";
3529         SetVersion ($DBversion);
3530     }
3531     else {
3532         print "Upgrade to $DBversion done.\n";
3533         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";
3534         SetVersion ($DBversion);
3535     }
3536 }
3537
3538 $DBversion = '3.01.00.120';
3539 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3540     $dbh->do(q{
3541 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');
3542 });
3543     print "Upgrade to $DBversion done (bug 1080: add soundon system preference for circulation sounds)\n";
3544     SetVersion ($DBversion);
3545 }
3546
3547 $DBversion = '3.01.00.121';
3548 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3549     $dbh->do("ALTER TABLE `reserves` ADD `expirationdate` DATE DEFAULT NULL");
3550     $dbh->do("ALTER TABLE `reserves` ADD `lowestPriority` tinyint(1) NOT NULL");
3551     $dbh->do("ALTER TABLE `old_reserves` ADD `expirationdate` DATE DEFAULT NULL");
3552     $dbh->do("ALTER TABLE `old_reserves` ADD `lowestPriority` tinyint(1) NOT NULL");
3553     print "Upgrade to $DBversion done ( Added Additional Fields to Reserves tables )\n";
3554     SetVersion ($DBversion);
3555 }
3556
3557 $DBversion = '3.01.00.122';
3558 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3559     $dbh->do(q{
3560       INSERT INTO systempreferences (variable,value,explanation,options,type)
3561       VALUES ('OAI-PMH:ConfFile', '', 'If empty, Koha OAI Server operates in normal mode, otherwise it operates in extended mode.','','File');
3562 });
3563     print "Upgrade to $DBversion done. — Add a new system preference OAI-PMF:ConfFile\n";
3564     SetVersion ($DBversion);
3565 }
3566
3567 $DBversion = "3.01.00.123";
3568 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3569     $dbh->do("INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3570         (6, 'place_holds', 'Place holds for patrons')");
3571     $dbh->do("INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3572         (6, 'modify_holds_priority', 'Modify holds priority')");
3573     $dbh->do("UPDATE `userflags` SET `flagdesc` = 'Place and modify holds for patrons' WHERE `flag` = 'reserveforothers'");
3574     print "Upgrade to $DBversion done (Add granular permission for holds modification and update description of reserveforothers permission)\n";
3575     SetVersion ($DBversion);
3576 }
3577
3578 $DBversion = '3.01.00.124';
3579 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3580     $dbh->do("
3581         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>>).');
3582     ");
3583     print "Upgrade to $DBversion done (bug 3242: add HOLDPLACED letter template, which is used when emailLibrarianWhenHoldIsPlaced is enabled)\n";
3584     SetVersion ($DBversion);
3585 }
3586
3587 $DBversion = '3.01.00.125';
3588 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3589     $dbh->do("
3590         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' );
3591     ");
3592     $dbh->do("
3593         INSERT INTO message_transport_types (message_transport_type) values ('print');
3594     ");
3595     print "Upgrade to $DBversion done (bug 3482: Printable hold and overdue notices)\n";
3596     SetVersion ($DBversion);
3597 }
3598
3599 $DBversion = "3.01.00.126";
3600 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3601         $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')");
3602         $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')");
3603
3604     print "Upgrade to $DBversion done (Adding ILS-DI updates and ILS-DI:AuthorizedIPs)\n";
3605     SetVersion ($DBversion);
3606 }
3607
3608 $DBversion = '3.01.00.127';
3609 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3610     $dbh->do("ALTER TABLE messages CHANGE branchcode branchcode varchar(10);");
3611     print "Upgrade to $DBversion done (bug 4190: messages in patron account did not work with branchcodes > 4)\n";
3612     SetVersion ($DBversion);
3613 }
3614
3615 $DBversion = '3.01.00.128';
3616 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3617     $dbh->do('CREATE INDEX budget_id ON aqorders (budget_id );');
3618     print "Upgrade to $DBversion done (bug 4331: index orders by budget_id)\n";
3619     SetVersion ($DBversion);
3620 }
3621
3622 $DBversion = "3.01.00.129";
3623 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3624         $dbh->do("UPDATE `permissions` SET `code` = 'items_batchdel' WHERE `permissions`.`module_bit` =13 AND `permissions`.`code` = 'batchdel' LIMIT 1 ;");
3625         $dbh->do("UPDATE `permissions` SET `code` = 'items_batchmod' WHERE `permissions`.`module_bit` =13 AND `permissions`.`code` = 'batchmod' LIMIT 1 ;");
3626         print "Upgrade to $DBversion done (Change permissions names for item batch modification / deletion)\n";
3627
3628     SetVersion ($DBversion);
3629 }
3630
3631 $DBversion = "3.01.00.130";
3632 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3633     $dbh->do("UPDATE reserves SET expirationdate = NULL WHERE expirationdate = '0000-00-00'");
3634     print "Upgrade to $DBversion done (change reserves.expirationdate values of 0000-00-00 to NULL (bug 1532)\n";
3635     SetVersion ($DBversion);
3636 }
3637
3638 $DBversion = "3.01.00.131";
3639 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3640         $dbh->do(q{
3641 INSERT IGNORE INTO message_transport_types (message_transport_type) VALUES ('print'),('feed');
3642     });
3643     print "Upgrade to $DBversion done (adding print and feed message transport types)\n";
3644     SetVersion ($DBversion);
3645 }
3646
3647 $DBversion = "3.01.00.132";
3648 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3649         $dbh->do(q{
3650     ALTER TABLE language_descriptions ADD INDEX subtag_type_lang (subtag, type, lang);
3651     });
3652     print "Upgrade to $DBversion done (Adding index to language_descriptions table)\n";
3653     SetVersion ($DBversion);
3654 }
3655
3656 $DBversion = '3.01.00.133';
3657 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3658     $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')");
3659     print "Upgrade to $DBversion done (bug 4405: added OverduesBlockCirc syspref to control whether circulation is blocked if a borrower has overdues)\n";
3660     SetVersion ($DBversion);
3661 }
3662
3663 $DBversion = '3.01.00.134';
3664 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3665     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('DisplayMultiPlaceHold','1','Display the ability to place multiple holds or not','','YesNo')");
3666     print "Upgrade to $DBversion done (adding syspref DisplayMultiPlaceHold to control whether multiple holds can be placed from the search results page)\n";
3667     SetVersion ($DBversion);
3668 }
3669
3670 $DBversion = '3.01.00.135';
3671 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3672     $dbh->do("
3673         INSERT INTO `letter` (module, code, name, title, content) VALUES
3674 ('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')
3675 ");
3676     print "Upgrade to $DBversion done (bug 4377: added HOLD_PRINT message template)\n";
3677     SetVersion ($DBversion);
3678 }
3679
3680 $DBversion = '3.01.00.136';
3681 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3682     $dbh->do(qq{
3683 INSERT INTO permissions (module_bit, code, description) VALUES
3684    ( 9, 'edit_items', 'Edit Items');});
3685     print "Upgrade to $DBversion done (Adding a new permission to edit items)\n";
3686     SetVersion ($DBversion);
3687 }
3688
3689 $DBversion = "3.01.00.137";
3690 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3691         $dbh->do("
3692           INSERT INTO permissions (module_bit, code, description) VALUES
3693           (15, 'check_expiration', 'Check the expiration of a serial'),
3694           (15, 'claim_serials', 'Claim missing serials'),
3695           (15, 'create_subscription', 'Create a new subscription'),
3696           (15, 'delete_subscription', 'Delete an existing subscription'),
3697           (15, 'edit_subscription', 'Edit an existing subscription'),
3698           (15, 'receive_serials', 'Serials receiving'),
3699           (15, 'renew_subscription', 'Renew a subscription'),
3700           (15, 'routing', 'Routing');
3701                  ");
3702     print "Upgrade to $DBversion done (adding granular permissions for serials)\n";
3703     SetVersion ($DBversion);
3704 }
3705
3706 $DBversion = "3.01.00.138";
3707 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3708     $dbh->do("DELETE FROM systempreferences WHERE variable = 'GranularPermissions'");
3709     print "Upgrade to $DBversion done (bug 4896: removing GranularPermissions syspref; use of granular permissions is now the default)\n";
3710     SetVersion ($DBversion);
3711 }
3712
3713 $DBversion = '3.01.00.139';
3714 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3715     $dbh->do("ALTER TABLE message_attributes CHANGE message_name message_name varchar(40);");
3716     print "Upgrade to $DBversion done (bug 3682: change message_name from varchar(20) to varchar(40))\n";
3717     SetVersion ($DBversion);
3718 }
3719
3720 $DBversion = '3.01.00.140';
3721 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3722     $dbh->do("UPDATE systempreferences SET value = '0' WHERE variable = 'TagsModeration' AND value is NULL");
3723     print "Upgrade to $DBversion done (bug 4312 TagsModeration changed from NULL to 0)\n";
3724     SetVersion ($DBversion);
3725 }
3726
3727 $DBversion = '3.01.00.141';
3728 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3729     $dbh->do(qq{DELETE FROM message_attributes WHERE message_attribute_id=3;});
3730     $dbh->do(qq{DELETE FROM letter WHERE code='EVENT' AND title='Upcoming Library Event';});
3731     print "Upgrade to $DBversion done Remove upcoming events messaging option (bug 2434)\n";
3732     SetVersion ($DBversion);
3733 }
3734
3735 $DBversion = '3.01.00.142';
3736 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3737     $dbh->do(qq{DELETE FROM message_transports WHERE message_attribute_id=3;});
3738     print "Upgrade to $DBversion done (Remove upcoming events messaging option part 2 (bug 2434))\n";
3739     SetVersion ($DBversion);
3740 }
3741
3742 $DBversion = '3.01.00.143';
3743 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3744     $dbh->do(qq{CREATE INDEX auth_value_idx ON authorised_values (authorised_value)});
3745     $dbh->do(qq{CREATE INDEX auth_val_cat_idx ON borrower_attribute_types (authorised_value_category)});
3746     print "Upgrade to $DBversion done (Create index on authorised_values and borrower_attribute_types (bug 4139))\n";
3747     SetVersion ($DBversion);
3748 }
3749
3750 $DBversion = '3.01.00.144';
3751 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3752     $dbh->do(qq{UPDATE systempreferences SET value='normal' where value='default' and variable='IntranetBiblioDefaultView'});
3753     print "Upgrade to $DBversion done (Update the 'default' to 'normal' for the IntranetBiblioDefaultView syspref (bug 5007))\n";
3754     SetVersion ($DBversion);
3755 }
3756
3757 $DBversion = "3.01.00.145";
3758 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3759     $dbh->do("ALTER TABLE borrowers ADD KEY `guarantorid` (guarantorid);");
3760     print "Upgrade to $DBversion done (Add index on guarantorid)\n";
3761     SetVersion ($DBversion);
3762 }
3763
3764 $DBversion = '3.01.00.999';
3765 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3766     print "Upgrade to $DBversion done (3.2.0 release candidate)\n";
3767     SetVersion ($DBversion);
3768 }
3769
3770 $DBversion = "3.02.00.000";
3771 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3772     my $value = $dbh->selectrow_array("SELECT value FROM systempreferences WHERE variable = 'HomeOrHoldingBranch'");
3773     $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');");
3774     print "Upgrade to $DBversion done (Add HomeOrHoldingBranchReturn system preference)\n";
3775     SetVersion ($DBversion);
3776 }
3777
3778 $DBversion = "3.02.00.001";
3779 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3780     $dbh->do(q{DELETE FROM systempreferences WHERE variable IN (
3781                 'holdCancelLength',
3782                 'PINESISBN',
3783                 'sortbynonfiling',
3784                 'TemplateEncoding',
3785                 'OPACSubscriptionDisplay',
3786                 'OPACDisplayExtendedSubInfo',
3787                 'OAI-PMH:Set',
3788                 'OAI-PMH:Subset',
3789                 'libraryAddress',
3790                 'kohaspsuggest',
3791                 'OrderPdfTemplate',
3792                 'marc',
3793                 'acquisitions',
3794                 'MIME')
3795                }
3796     );
3797     print "Upgrade to $DBversion done (bug 3756: remove disused system preferences)\n";
3798     SetVersion ($DBversion);
3799 }
3800
3801 $DBversion = "3.02.00.002";
3802 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3803     $dbh->do(q{DELETE FROM systempreferences WHERE variable = 'OpacPrivacy'});
3804     print "Upgrade to $DBversion done (bug 3881: remove unused OpacPrivacy system preference)\n";
3805     SetVersion ($DBversion);
3806 }
3807
3808 $DBversion = "3.02.00.003";
3809 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3810     $dbh->do(q{UPDATE systempreferences SET variable = 'ILS-DI:AuthorizedIPs' WHERE variable = 'ILS-DI:Authorized_IPs'});
3811     print "Upgrade to $DBversion done (correct ILS-DI:AuthorizedIPs)\n";
3812     SetVersion ($DBversion);
3813 }
3814
3815 $DBversion = "3.02.00.004";
3816 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3817     print "Upgrade to $DBversion done (3.2.0 general release)\n";
3818     SetVersion ($DBversion);
3819 }
3820 # This is the point where 3.2.x and master diverged, we can use $original_version to make sure we don't
3821
3822 # apply updates that have already been done
3823
3824 $DBversion = "3.03.00.001";
3825 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.005")) {
3826     $dbh->do("DELETE FROM subscriptionroutinglist WHERE borrowernumber IS NULL;");
3827     $dbh->do("ALTER TABLE subscriptionroutinglist MODIFY COLUMN `borrowernumber` int(11) NOT NULL;");
3828     $dbh->do("DELETE FROM subscriptionroutinglist WHERE subscriptionid IS NULL;");
3829     $dbh->do("ALTER TABLE subscriptionroutinglist MODIFY COLUMN `subscriptionid` int(11) NOT NULL;");
3830     $dbh->do("CREATE TEMPORARY TABLE del_subscriptionroutinglist
3831               SELECT s1.routingid FROM subscriptionroutinglist s1
3832               WHERE EXISTS (SELECT * FROM subscriptionroutinglist s2
3833                             WHERE s2.borrowernumber = s1.borrowernumber
3834                             AND   s2.subscriptionid = s1.subscriptionid
3835                             AND   s2.routingid < s1.routingid);");
3836     $dbh->do("DELETE FROM subscriptionroutinglist
3837               WHERE routingid IN (SELECT routingid FROM del_subscriptionroutinglist);");
3838     $dbh->do("ALTER TABLE subscriptionroutinglist ADD UNIQUE (subscriptionid, borrowernumber);");
3839     $dbh->do("ALTER TABLE subscriptionroutinglist
3840                 ADD CONSTRAINT `subscriptionroutinglist_ibfk_1` FOREIGN KEY (`borrowernumber`)
3841                 REFERENCES `borrowers` (`borrowernumber`)
3842                 ON DELETE CASCADE ON UPDATE CASCADE");
3843     $dbh->do("ALTER TABLE subscriptionroutinglist
3844                 ADD CONSTRAINT `subscriptionroutinglist_ibfk_2` FOREIGN KEY (`subscriptionid`)
3845                 REFERENCES `subscription` (`subscriptionid`)
3846                 ON DELETE CASCADE ON UPDATE CASCADE");
3847     print "Upgrade to $DBversion done (Make subscriptionroutinglist more strict)\n";
3848     SetVersion ($DBversion);
3849 }
3850
3851 $DBversion = '3.03.00.002';
3852 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.006")) {
3853     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='arm' WHERE rfc4646_subtag='hy';");
3854     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='eng' WHERE rfc4646_subtag='en';");
3855     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'fi','fin');");
3856     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='fre' WHERE rfc4646_subtag='fr';");
3857     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'lo','lao');");
3858     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='ita' WHERE rfc4646_subtag='it';");
3859     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'sr','srp');");
3860     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'tet','tet');");
3861     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'ur','urd');");
3862
3863     print "Upgrade to $DBversion done (Correct language mappings)\n";
3864     SetVersion ($DBversion);
3865 }
3866
3867 $DBversion = '3.03.00.003';
3868 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.007")) {
3869     $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');");
3870     print "Upgrade to $DBversion done (Add UseTablesortForCirc syspref)\n";
3871     SetVersion ($DBversion);
3872 }
3873
3874 $DBversion = '3.03.00.004';
3875 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.001")) {
3876     my $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'ACCEPTED');
3877     $dbh->do(q/
3878 INSERT INTO `letter`
3879 (module, code, name, title, content)
3880 VALUES
3881 ('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>>')
3882 /) unless $count > 0;
3883     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'AVAILABLE');
3884     $dbh->do(q/
3885 INSERT INTO `letter`
3886 (module, code, name, title, content)
3887 VALUES
3888 ('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>>')
3889 /) unless $count > 0;
3890     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'ORDERED');
3891     $dbh->do(q/
3892 INSERT INTO `letter`
3893 (module, code, name, title, content)
3894 VALUES
3895 ('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>>')
3896 /) unless $count > 0;
3897     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'REJECTED');
3898     $dbh->do(q/
3899 INSERT INTO `letter`
3900 (module, code, name, title, content)
3901 VALUES
3902 ('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>>')
3903 /) unless $count > 0;
3904     print "Upgrade to $DBversion done (bug 5127: add default templates for suggestion status change notifications)\n";
3905     SetVersion ($DBversion);
3906 };
3907
3908 $DBversion = '3.03.00.005';
3909 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3910     $dbh->do("update `systempreferences` set options='whitespace|T-prefix|cuecat|libsuite8' where variable='itemBarcodeInputFilter'");
3911     print "Upgrade to $DBversion done (Add itemBarcodeInputFilter choice libsuite8)\n";
3912 }
3913
3914 $DBversion = '3.03.00.006';
3915 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.002")) {
3916     $dbh->do("ALTER TABLE deletedborrowers ADD `privacy` int(11) AFTER smsalertnumber;");
3917     $dbh->do("ALTER TABLE deletedborrowers CHANGE `cardnumber` `cardnumber` varchar(16);");
3918     print "Upgrade to $DBversion done (Fix differences between borrowers and deletedborrowers)\n";
3919     SetVersion ($DBversion);
3920 }
3921
3922 $DBversion = '3.03.00.007';
3923 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3924     $dbh->do("ALTER table suggestions ADD quantity SMALLINT(6) default NULL,
3925                 ADD currency VARCHAR(3) default NULL,
3926                 ADD price DECIMAL(28,6) default NULL,
3927                 ADD total DECIMAL(28,6) default NULL;
3928                 ");
3929     print "Upgrade to $DBversion done (Added acq related columns to suggestions)\n";
3930     SetVersion ($DBversion);
3931 }
3932
3933 $DBversion = '3.03.00.008';
3934 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3935     $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')");
3936     print "Upgrade to $DBversion done (adding syspref OPACNoResultsFound to control what displays when no results are found for a search in the OPAC.)\n";
3937     SetVersion ($DBversion);
3938 }
3939
3940 $DBversion = '3.03.00.009';
3941 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.003")) {
3942     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('IntranetUserCSS','','Add CSS to be included in the Intranet',NULL,'free')");
3943     print "Upgrade to $DBversion done (Add IntranetUserCSS syspref)\n";
3944     SetVersion ($DBversion);
3945 }
3946
3947 $DBversion = "3.03.00.010";
3948 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.02.001")) {
3949     $dbh->do("UPDATE `marc_subfield_structure` SET liblibrarian = 'Distance from earth' WHERE liblibrarian = 'Distrance from earth' AND tagfield = '034' AND tagsubfield = 'r';");
3950     $dbh->do("UPDATE `marc_subfield_structure` SET libopac = 'Distance from earth' WHERE libopac = 'Distrance from earth' AND tagfield = '034' AND tagsubfield = 'r';");
3951     print "Upgrade to $DBversion done (Fix misspelled 034r subfield in MARC21 Frameworks)\n";
3952     SetVersion ($DBversion);
3953 }
3954
3955 $DBversion = "3.03.00.011";
3956 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3957     $dbh->do("UPDATE aqbooksellers SET gstrate=NULL WHERE gstrate=0.0");
3958     print "Upgrade to $DBversion done (Bug 5186: allow GST rate to be set to 0)\n";
3959     SetVersion ($DBversion);
3960 }
3961
3962 $DBversion = "3.03.00.012";
3963 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3964    $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')");
3965    print "Upgrade to $DBversion done (Bug 2142: maxItemsInSearchResults syspref resurrected)\n";
3966    SetVersion ($DBversion);
3967 }
3968
3969 $DBversion = "3.03.00.013";
3970 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3971     $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')");
3972     print "Upgrade to $DBversion done (added 'OpacPublic' syspref)\n";
3973    SetVersion ($DBversion);
3974 }
3975
3976 $DBversion = "3.03.00.014";
3977 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3978     $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')");
3979     $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')");
3980     $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')");
3981     print "Upgrade to $DBversion done (Add flexible shelf browser constraints)\n";
3982     SetVersion ($DBversion);
3983 }
3984
3985 $DBversion = "3.03.00.015";
3986 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3987     if ( C4::Context->preference("marcflavour") eq "MARC21" ) {
3988         my $sth = $dbh->prepare(
3989 "INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`,
3990                              `tab`, `authorised_value`, `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`)
3991                              VALUES ( ?, '9', '9 (RLIN)', '9 (RLIN)', 0, 0, '', 6, '', '', '', 0, -5, '', '', '', NULL)"
3992         );
3993         $sth->execute('648');
3994         $sth->execute('654');
3995         $sth->execute('655');
3996         $sth->execute('656');
3997         $sth->execute('657');
3998         $sth->execute('658');
3999         $sth->execute('662');
4000         $sth->finish;
4001         print
4002 "Upgrade to $DBversion done (Bug 5619: Add subfield 9 to marc21 648,654,655,656,657,658,662)\n";
4003     }
4004     SetVersion($DBversion);
4005 }
4006
4007 $DBversion = '3.03.00.016';
4008 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4009     # reimplement OpacPrivacy system preference
4010     $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')");
4011     $dbh->do("ALTER TABLE `borrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
4012     $dbh->do("ALTER TABLE `deletedborrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
4013     print "Upgrade to $DBversion done (OpacPrivacy reimplementation)\n";
4014     SetVersion($DBversion);
4015 };
4016
4017 $DBversion = '3.03.00.017';
4018 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.001")) {
4019     $dbh->do("ALTER TABLE  `currency` CHANGE `rate` `rate` FLOAT( 15, 5 ) NULL DEFAULT NULL;");
4020     print "Upgrade to $DBversion done (Enable currency rates >= 100)\n";
4021     SetVersion ($DBversion);
4022 }
4023
4024 $DBversion = '3.03.00.018';
4025 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.002")) {
4026     $dbh->do( q|update language_descriptions set description = 'Nederlands' where lang = 'nl' and subtag = 'nl'|);
4027     $dbh->do( q|update language_descriptions set description = 'Dansk' where lang = 'da' and subtag = 'da'|);
4028     print "Upgrade to $DBversion done (Correct language descriptions)\n";
4029     SetVersion ($DBversion);
4030 }
4031
4032 $DBversion = '3.03.00.019';
4033 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.003")) {
4034     # Fix bokmål
4035     $dbh->do("UPDATE language_subtag_registry SET description = 'Norwegian bokm&#229;l' WHERE subtag = 'nb';");
4036     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'nb','nob');");
4037     $dbh->do("UPDATE language_descriptions SET description = 'Norsk bokm&#229;l' WHERE subtag = 'nb' AND lang = 'nb';");
4038     $dbh->do("UPDATE language_descriptions SET description = 'Norwegian bokm&#229;l' WHERE subtag = 'nb' AND lang = 'en';");
4039     $dbh->do("UPDATE language_descriptions SET description = 'Norvégien bokm&#229;l' WHERE subtag = 'nb' AND lang = 'fr';");
4040     # Add nynorsk
4041     $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'nn', 'language', 'Norwegian nynorsk','2011-02-14' )");
4042     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'nn','nno')");
4043     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'nb', 'Norsk nynorsk')");
4044     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'nn', 'Norsk nynorsk')");
4045     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'en', 'Norwegian nynorsk')");
4046     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'fr', 'Norvégien nynorsk')");
4047     print "Upgrade to $DBversion done (Correct language descriptions for Norwegian)\n";
4048     SetVersion ($DBversion);
4049 }
4050
4051 $DBversion = '3.03.00.020';
4052 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4053     $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')");
4054     $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')");
4055     print "Upgrade to $DBversion done (Bug 5811: Add sysprefs controlling overriding fines)\n";
4056     SetVersion($DBversion);
4057 };
4058
4059 $DBversion = '3.03.00.021';
4060 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.001")) {
4061     $dbh->do("ALTER TABLE items MODIFY enumchron TEXT");
4062     $dbh->do("ALTER TABLE deleteditems MODIFY enumchron TEXT");
4063     print "Upgrade to $DBversion done (bug 5642: longer serial enumeration)\n";
4064     SetVersion ($DBversion);
4065 }
4066
4067 $DBversion = '3.03.00.022';
4068 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4069     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('AuthoritiesLog','0','If ON, log edit/create/delete actions on authorities.','','YesNo');");
4070     print "Upgrade to $DBversion done (Add AuthoritiesLog syspref)\n";
4071     SetVersion ($DBversion);
4072 }
4073
4074 # due to a mismatch in kohastructure.sql some koha will have missing columns in aqbasketgroup
4075 # this attempts to fix that
4076 $DBversion = '3.03.00.023';
4077 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.002")) {
4078     my $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'billingplace'");
4079     $sth->execute;
4080     $dbh->do("ALTER TABLE aqbasketgroups ADD billingplace VARCHAR(10)") if ! $sth->fetchrow_hashref;
4081     $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'deliveryplace'");
4082     $sth->execute;
4083     $dbh->do("ALTER TABLE aqbasketgroups ADD deliveryplace VARCHAR(10)") if ! $sth->fetchrow_hashref;
4084     $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'deliverycomment'");
4085     $sth->execute;
4086     $dbh->do("ALTER TABLE aqbasketgroups ADD deliverycomment VARCHAR(255)") if ! $sth->fetchrow_hashref;
4087     print "Upgrade to $DBversion done (Reconcile aqbasketgroups)\n";
4088     SetVersion ($DBversion);
4089 }
4090
4091 $DBversion = '3.03.00.024';
4092 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4093     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('TraceCompleteSubfields','0','Force subject tracings to only match complete subfields.','0','YesNo')");
4094     $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')");
4095     print "Upgrade to $DBversion done (Add syspref to force whole-subfield matching on subject tracings)\n";
4096     SetVersion($DBversion);
4097 };
4098
4099 $DBversion = "3.03.00.025";
4100 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4101     $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')");
4102     print "Upgrade to $DBversion done (Add syspref to control if user can choose pickup branch for holds)\n";
4103     SetVersion ($DBversion);
4104 }
4105
4106 $DBversion = '3.03.00.026';
4107 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.003")) {
4108     $dbh->do("UPDATE `message_attributes` SET message_name='Item Due' WHERE message_attribute_id=1 AND message_name LIKE 'Item DUE'");
4109         print "Upgrade to $DBversion done ( fix capitalization in message type )\n";
4110     SetVersion ($DBversion);
4111 }
4112
4113 $DBversion = '3.03.00.027';
4114 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4115     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('displayFacetCount', '0', NULL, NULL, 'YesNo')");
4116     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('maxRecordsForFacets', '20', NULL, NULL, 'Integer')");
4117     print "Upgrade to $DBversion done (Preferences for facet count)\n";
4118     SetVersion ($DBversion);
4119 }
4120
4121 $DBversion = "3.03.00.028";
4122 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4123     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('FacetLabelTruncationLength', 20, 'Truncate facets length to','','free')");
4124     print "Upgrade to $DBversion done (Add FacetLabelTruncationLength syspref to control facets displayed length)\n";
4125     SetVersion ($DBversion);
4126 }
4127
4128 $DBversion = "3.03.00.029";
4129 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4130     $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')");
4131     print "Upgrade to $DBversion done (Add syspref to control if user can choose branch when making purchase suggestion)\n";
4132     SetVersion ($DBversion);
4133 }
4134
4135 $DBversion = "3.03.00.030";
4136 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4137     $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')");
4138     $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')");
4139     print "Upgrade to $DBversion done (Add sysprefs to control custom favicons)\n";
4140     SetVersion ($DBversion);
4141 }
4142
4143 $DBversion = "3.03.00.031";
4144 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4145     $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');");
4146     print "Upgrade to $DBversion done (Add syspref FineNotifyAtCheckin)\n";
4147     SetVersion ($DBversion);
4148 }
4149
4150 $DBversion = '3.03.00.032';
4151 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4152     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('TraceSubjectSubdivisions', 1, 'Create searches on all subdivisions for subject tracings.','1','YesNo')");
4153     print "Upgrade to $DBversion done ( include subdivisions when generating subject tracing searches )\n";
4154 }
4155
4156
4157 $DBversion = '3.03.00.033';
4158 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4159     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('StaffAuthorisedValueImages', '1', '', NULL, 'YesNo')");
4160     print "Upgrade to $DBversion done (System pref StaffAuthorisedValueImages)\n";
4161     SetVersion ($DBversion);
4162 }
4163
4164 $DBversion = '3.03.00.034';
4165 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4166     $dbh->do("ALTER TABLE `categories` ADD `hidelostitems` tinyint(1) NOT NULL default '0' AFTER `reservefee`");
4167     print "Upgrade to $DBversion done (Add hidelostitems preference to borrower categories)\n";
4168     SetVersion ($DBversion);
4169 }
4170
4171 $DBversion = '3.03.00.035';
4172 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4173     $dbh->do("ALTER TABLE `issuingrules` ADD hardduedate date default NULL AFTER issuelength");
4174     $dbh->do("ALTER TABLE `issuingrules` ADD hardduedatecompare tinyint NOT NULL default 0 AFTER hardduedate");
4175     my $duedate;
4176     if (C4::Context->preference("globalDueDate")) {
4177       $duedate = eval { output_pref( { dt => dt_from_string( C4::Context->preference("globalDueDate") ), dateonly => 1, dateformat => 'iso' } ); };
4178       $dbh->do("UPDATE `issuingrules` SET hardduedate = '$duedate', hardduedatecompare = 0");
4179     } elsif (C4::Context->preference("ceilingDueDate")) {
4180       $duedate = eval { output_pref( { dt => dt_from_string( C4::Context->preference("ceilingDueDate") ), dateonly => 1, dateformat => 'iso' } ); };
4181       $dbh->do("UPDATE `issuingrules` SET hardduedate = '$duedate', hardduedatecompare = -1");
4182     }
4183     $dbh->do("DELETE FROM `systempreferences` WHERE variable = 'globalDueDate' OR variable = 'ceilingDueDate'");
4184     print "Upgrade to $DBversion done (Move global and ceiling due dates to Circ Rules level)\n";
4185     SetVersion ($DBversion);
4186 }
4187
4188 $DBversion = '3.03.00.036';
4189 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4190     $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')");
4191     print "Upgrade to $DBversion done ( Make COinS optional in OPAC search results )\n";
4192     SetVersion ($DBversion);
4193 }
4194
4195 $DBversion = '3.03.00.037';
4196 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4197     $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')");
4198     $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')");
4199     print "Upgrade to $DBversion done (Add 'Display856uAsImage' and 'OPACDisplay856uAsImage' syspref)\n";
4200     SetVersion ($DBversion);
4201 }
4202
4203 $DBversion = '3.03.00.038';
4204 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4205     $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')");
4206     $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')");
4207     $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')");
4208     print "Upgrade to $DBversion done ( Add Self-checkout by Login system preferences )\n";
4209 }
4210
4211 $DBversion = "3.03.00.039";
4212 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4213     $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');");
4214     print "Upgrade to $DBversion done (Add syspref ShowReviewer)\n";
4215 }
4216
4217 $DBversion = "3.03.00.040";
4218 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4219     $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');");
4220     print "Upgrade to $DBversion done (Add syspref UseControlNumber)\n";
4221 }
4222
4223 $DBversion = "3.03.00.041";
4224 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4225     $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')");
4226     $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')");
4227     print "Upgrade to $DBversion done (Add sysprefs to control alternate holdings information display)\n";
4228     SetVersion ($DBversion);
4229 }
4230
4231 $DBversion = '3.03.00.042';
4232 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4233     stocknumber_checker();
4234     print "Upgrade to $DBversion done (5860 Index itemstocknumber)\n";
4235     SetVersion ($DBversion);
4236 }
4237
4238 sub stocknumber_checker { #code reused later on
4239   my @row;
4240   #drop the obsolete itemSStocknumber idx if it exists
4241   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemsstocknumberidx'");
4242   $dbh->do("ALTER TABLE `items` DROP INDEX `itemsstocknumberidx`;") if @row;
4243
4244   #check itemstocknumber idx; remove it if it is unique
4245   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemstocknumberidx' AND non_unique=0");
4246   $dbh->do("ALTER TABLE `items` DROP INDEX `itemstocknumberidx`;") if @row;
4247
4248   #add itemstocknumber index non-unique IF it still not exists
4249   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemstocknumberidx'");
4250   $dbh->do("ALTER TABLE items ADD INDEX itemstocknumberidx (stocknumber);") unless @row;
4251 }
4252
4253 $DBversion = "3.03.00.043";
4254 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4255
4256     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib,lib_opac) VALUES ('YES_NO','0','No','No')");
4257     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib,lib_opac) VALUES ('YES_NO','1','Yes','Yes')");
4258
4259         print "Upgrade to $DBversion done ( add generic boolean YES_NO authorised_values pair )\n";
4260         SetVersion ($DBversion);
4261 }
4262
4263 $DBversion = '3.03.00.044';
4264 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4265     $dbh->do("ALTER TABLE `aqbasketgroups` ADD `freedeliveryplace` TEXT NULL AFTER `deliveryplace`;");
4266     print "Upgrade to $DBversion done (adding freedeliveryplace to basketgroups)\n";
4267 }
4268
4269 $DBversion = '3.03.00.045';
4270 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4271     #Remove obsolete columns from aqbooksellers if needed
4272     my $a = $dbh->selectall_hashref('SHOW columns from aqbooksellers','Field');
4273     my $sqldrop="ALTER TABLE aqbooksellers DROP COLUMN ";
4274     foreach(qw/deliverydays followupdays followupscancel invoicedisc nocalc specialty/) {
4275       $dbh->do($sqldrop.$_) if exists $a->{$_};
4276     }
4277     #Remove obsolete column from aqbudgets if needed
4278     #The correct column is budget_notes
4279     $a = $dbh->selectall_hashref('SHOW columns from aqbudgets','Field');
4280     if(exists $a->{budget_description}) {
4281       $dbh->do("ALTER TABLE aqbudgets DROP COLUMN budget_description");
4282     }
4283     print "Upgrade to $DBversion done (Remove obsolete columns from aqbooksellers and aqbudgets if needed)\n";
4284     SetVersion ($DBversion);
4285 }
4286
4287 $DBversion = "3.03.00.046";
4288 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4289     $dbh->do("ALTER TABLE overduerules ALTER delay1 SET DEFAULT NULL, ALTER delay2 SET DEFAULT NULL, ALTER delay3 SET DEFAULT NULL");
4290     print "Upgrade to $DBversion done (Setting NULL default value for delayn columns in table overduerules)\n";
4291     SetVersion($DBversion);
4292 }
4293
4294 $DBversion = '3.03.00.047';
4295 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4296     $dbh->do("ALTER TABLE borrowers ADD `state` mediumtext AFTER city;");
4297     $dbh->do("ALTER TABLE borrowers ADD `B_state` mediumtext AFTER B_city;");
4298     $dbh->do("ALTER TABLE borrowers ADD `altcontactstate` mediumtext AFTER altcontactaddress3;");
4299     $dbh->do("ALTER TABLE deletedborrowers ADD `state` mediumtext AFTER city;");
4300     $dbh->do("ALTER TABLE deletedborrowers ADD `B_state` mediumtext AFTER B_city;");
4301     $dbh->do("ALTER TABLE deletedborrowers ADD `altcontactstate` mediumtext AFTER altcontactaddress3;");
4302     print "Upgrade to $DBversion done (Add state field to patron's addresses)\n";
4303 }
4304
4305 $DBversion = '3.03.00.048';
4306 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4307     $dbh->do("ALTER TABLE branches ADD `branchstate` mediumtext AFTER `branchcity`;");
4308     print "Upgrade to $DBversion done (Add state to branch address)\n";
4309     SetVersion ($DBversion);
4310 }
4311
4312 $DBversion = '3.03.00.049';
4313 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4314     $dbh->do("ALTER TABLE `accountlines` ADD `note` text NULL default NULL");
4315     $dbh->do("ALTER TABLE `accountlines` ADD `manager_id` int( 11 ) NULL ");
4316     print "Upgrade to $DBversion done (adding note and manager_id fields in accountlines table)\n";
4317     SetVersion($DBversion);
4318 }
4319
4320 $DBversion = "3.03.00.050";
4321 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4322     $dbh->do("
4323         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');
4324         ");
4325     print "Upgrade to $DBversion done (Adding OpacHiddenItems syspref)\n";
4326     SetVersion($DBversion);
4327 }
4328
4329 $DBversion = "3.03.00.051";
4330 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4331     print "Upgrade to $DBversion done (Remove spaces and dashes from message_attribute names)\n";
4332     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Due' WHERE message_name='Item Due'");
4333     $dbh->do("UPDATE message_attributes SET message_name = 'Advance_Notice' WHERE message_name='Advance Notice'");
4334     $dbh->do("UPDATE message_attributes SET message_name = 'Hold_Filled' WHERE message_name='Hold Filled'");
4335     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Check_in' WHERE message_name='Item Check-in'");
4336     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Checkout' WHERE message_name='Item Checkout'");
4337     SetVersion ($DBversion);
4338 }
4339
4340 $DBversion = "3.03.00.052";
4341 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4342     $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');");
4343     print "Upgrade to $DBversion done (Add syspref WaitingNotifyAtCheckin)\n";
4344     SetVersion ($DBversion);
4345 }
4346
4347 $DBversion = "3.04.00.000";
4348 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4349     print "Upgrade to $DBversion done Koha 3.4.0 release \n";
4350     SetVersion ($DBversion);
4351 }
4352
4353 $DBversion = "3.05.00.001";
4354 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4355     $dbh->do(qq{
4356     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');
4357     });
4358     print "Upgrade to $DBversion done (Adds New System preference numSearchRSSResults)\n";
4359     SetVersion($DBversion);
4360 }
4361
4362 $DBversion = '3.05.00.002';
4363 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4364     #follow up fix 5860: some installs already past 3.3.0.42
4365     stocknumber_checker();
4366     print "Upgrade to $DBversion done (Fix for stocknumber index)\n";
4367     SetVersion ($DBversion);
4368 }
4369
4370 $DBversion = "3.05.00.003";
4371 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4372     $dbh->do(qq{
4373     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');
4374     });
4375     print "Upgrade to $DBversion done (Adds New System preference OpacRenewalBranch)\n";
4376     SetVersion($DBversion);
4377 }
4378
4379 $DBversion = "3.05.00.004";
4380 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4381     $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');");
4382     print "Upgrade to $DBversion done (Add syspref ShowReviewerPhoto)\n";
4383     SetVersion($DBversion);
4384 }
4385
4386 $DBversion = "3.05.00.005";
4387 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4388     $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');");
4389     print "Upgrade to $DBversion done (Adds pref BasketConfirmations)\n";
4390     SetVersion($DBversion);
4391 }
4392
4393 $DBversion = "3.05.00.006";
4394 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4395     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('MARCAuthorityControlField008', '|| aca||aabn           | a|a     d', NULL, NULL, 'Textarea')");
4396     print "Upgrade to $DBversion done (Add syspref MARCAuthorityControlField008)\n";
4397     SetVersion ($DBversion);
4398 }
4399
4400 $DBversion = "3.05.00.007";
4401 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4402     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpenLibraryCovers',0,'If ON Openlibrary book covers will be show',NULL,'YesNo');");
4403     print "Upgrade to $DBversion done (Add syspref OpenLibraryCovers)\n";
4404     SetVersion($DBversion);
4405 }
4406
4407 $DBversion = "3.05.00.008";
4408 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4409     $dbh->do("ALTER TABLE `cities` ADD `city_state` VARCHAR( 100 ) NULL DEFAULT NULL AFTER  `city_name`;");
4410     $dbh->do("ALTER TABLE `cities` ADD `city_country` VARCHAR( 100 ) NULL DEFAULT NULL AFTER  `city_zipcode`;");
4411     print "Add state and country to cities table corresponding to new columns in borrowers\n";
4412     SetVersion($DBversion);
4413 }
4414
4415 $DBversion = "3.05.00.009";
4416 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4417     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4418               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE borrowernumber IS NULL");
4419     $dbh->do("DELETE FROM issues WHERE borrowernumber IS NULL");
4420
4421     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4422               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE itemnumber IS NULL");
4423     $dbh->do("DELETE FROM issues WHERE itemnumber IS NULL");
4424
4425     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4426               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)");
4427     $dbh->do("DELETE FROM issues WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowernumber = issues.borrowernumber)");
4428
4429     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4430               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)");
4431     $dbh->do("DELETE FROM issues WHERE NOT EXISTS (SELECT * FROM items WHERE itemnumber = issues.itemnumber)");
4432
4433     $dbh->do("ALTER TABLE issues DROP FOREIGN KEY `issues_ibfk_1`");
4434     $dbh->do("ALTER TABLE issues DROP FOREIGN KEY `issues_ibfk_2`");
4435     $dbh->do("ALTER TABLE issues ALTER COLUMN borrowernumber DROP DEFAULT");
4436     $dbh->do("ALTER TABLE issues ALTER COLUMN itemnumber DROP DEFAULT");
4437     $dbh->do("ALTER TABLE issues MODIFY COLUMN borrowernumber int(11) NOT NULL");
4438     $dbh->do("ALTER TABLE issues MODIFY COLUMN itemnumber int(11) NOT NULL");
4439     $dbh->do("ALTER TABLE issues DROP KEY `issuesitemidx`");
4440     $dbh->do("ALTER TABLE issues ADD PRIMARY KEY (`itemnumber`)");
4441     $dbh->do("ALTER TABLE issues ADD CONSTRAINT `issues_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE RESTRICT ON UPDATE CASCADE");
4442     $dbh->do("ALTER TABLE issues ADD CONSTRAINT `issues_ibfk_2` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE RESTRICT ON UPDATE CASCADE");
4443
4444     print "Upgrade to $DBversion done (issues referential integrity)\n";
4445     SetVersion ($DBversion);
4446 }
4447
4448 $DBversion = "3.05.00.010";
4449 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4450     $dbh->do("CREATE INDEX priorityfoundidx ON reserves (priority,found)");
4451     print "Create an index on reserves to speed up holds awaiting pickup report bug 5866\n";
4452     SetVersion($DBversion);
4453 }
4454
4455
4456 $DBversion = "3.05.00.011";
4457 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4458     $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')");
4459     print "Upgrade to $DBversion done (add OPACResultsSidebar syspref (enh 6165))\n";
4460     SetVersion($DBversion);
4461 }
4462
4463 $DBversion = "3.05.00.012";
4464 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4465     $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')");
4466     print "Upgrade to $DBversion done (add RecordLocalUseOnReturn syspref (enh 6403))\n";
4467     SetVersion($DBversion);
4468 }
4469
4470 $DBversion = "3.05.00.013";
4471 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4472     $dbh->do(qq|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OpacKohaUrl','0',"Show 'Powered by Koha' text on OPAC footer.",NULL,NULL)|);
4473     print "Upgrade to $DBversion done (Add syspref 'OpacKohaUrl')\n";
4474     SetVersion($DBversion);
4475 }
4476
4477 $DBversion = "3.05.00.014";
4478 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4479     $dbh->do("ALTER TABLE `borrowers` MODIFY `userid` VARCHAR(75)");
4480     print "Modified userid column length into 75 in borrowers\n";
4481     SetVersion($DBversion);
4482 }
4483
4484 $DBversion = "3.05.00.015";
4485 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4486     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectEnabled',0,'Enable Novelist Select content.  Requires Novelist Profile and Password',NULL,'YesNo')");
4487     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectProfile',NULL,'Novelist Select user Password',NULL,'free')");
4488     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectPassword',NULL,'Enable Novelist user Profile',NULL,'free')");
4489     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectView','tab','Where to display Novelist Select content','tab|above|below|right','Choice')");
4490     print "Upgrade to $DBversion done (Add support for EBSCO's NoveList Select (enh 6902))\n";
4491     SetVersion($DBversion);
4492 }
4493
4494 $DBversion = '3.05.00.016';
4495 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4496     $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');");
4497     print "Upgrade to $DBversion done (Add EasyAnalyticalRecords syspref)\n";
4498     SetVersion ($DBversion);
4499 }
4500
4501 $DBversion = '3.05.00.017';
4502 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4503     if (C4::Context->preference("marcflavour") eq 'MARC21' ||
4504         C4::Context->preference("marcflavour") eq 'NORMARC'){
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', '0', 'Host Biblionumber', 'Host Biblionumber', 0, 0, NULL, 7, NULL, NULL, '', NULL, -6, '', '', '', NULL)");
4506         $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)");
4507         print "Upgrade to $DBversion done (Add 773 subfield 9 and 0 to default framework)\n";
4508         SetVersion ($DBversion);
4509     } elsif (C4::Context->preference("marcflavour") eq 'UNIMARC'){
4510         $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)");
4511         print "Upgrade to $DBversion done (Add 461 subfield 9 to default framework)\n";
4512         SetVersion ($DBversion);
4513     }
4514 }
4515
4516 $DBversion = "3.05.00.018";
4517 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4518     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacNavBottom','','Links after OpacNav links','70|10','Textarea')");
4519     print "Upgrade to $DBversion done (add OpacNavBottom syspref (enh 6825): if appropriate, you can split OpacNav into OpacNav and OpacNavBottom)\n";
4520     SetVersion($DBversion);
4521 }
4522
4523 $DBversion = "3.05.00.019";
4524 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4525     $dbh->do("UPDATE itemtypes SET imageurl = 'vokal/Book.png' WHERE imageurl = 'vokal/BOOK.png'");
4526     $dbh->do("UPDATE itemtypes SET imageurl = 'vokal/Book-32px.png' WHERE imageurl = 'vokal/BOOK-32px.png'");
4527     $dbh->do("UPDATE authorised_values SET imageurl = 'vokal/Book.png' WHERE imageurl = 'vokal/BOOK.png'");
4528     $dbh->do("UPDATE authorised_values SET imageurl = 'vokal/Book-32px.png' WHERE imageurl = 'vokal/BOOK-32px.png'");
4529     print "Upgrade to $DBversion done (remove duplicate VOKAL Book icons, bug 6862)\n";
4530     SetVersion($DBversion);
4531 }
4532
4533 $DBversion = "3.05.00.020";
4534 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4535     $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')");
4536     print "Upgrade to $DBversion done (Add syspref AcqViewBaskets)\n";
4537     SetVersion($DBversion);
4538 }
4539
4540 $DBversion = "3.05.00.021";
4541 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4542     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN display_checkout TINYINT(1) NOT NULL DEFAULT '0';");
4543     print "Upgrade to $DBversion done (Added a display_checkout field in borrower_attribute_types table)\n";
4544     SetVersion($DBversion);
4545 }
4546
4547 $DBversion = "3.05.00.022";
4548 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4549     $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");
4550     print "Upgrade to $DBversion done (6094: Fixing ModAuthority problems, add a need_merge_authorities table)\n";
4551     SetVersion($DBversion);
4552 }
4553
4554 $DBversion = "3.05.00.023";
4555 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4556     $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');");
4557     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";
4558     SetVersion($DBversion);
4559 }
4560
4561 $DBversion = "3.06.00.000";
4562 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4563     print "Upgrade to $DBversion done Koha 3.6.0 release \n";
4564     SetVersion ($DBversion);
4565 }
4566
4567 $DBversion = "3.07.00.001";
4568 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4569     my $borrowers = $dbh->selectcol_arrayref( "SELECT borrowernumber from borrowers where debarred =1;", { Columns => [1] } );
4570     $dbh->do("ALTER TABLE borrowers MODIFY debarred DATE DEFAULT NULL;");
4571     $dbh->do( "UPDATE borrowers set debarred='9999-12-31' where borrowernumber IN (" . join( ",", @$borrowers ) . ");" ) if ($borrowers and scalar(@$borrowers)>0);
4572     $dbh->do("ALTER TABLE borrowers ADD COLUMN debarredcomment VARCHAR(255) DEFAULT NULL AFTER debarred;");
4573     $dbh->do("ALTER TABLE deletedborrowers MODIFY debarred DATE DEFAULT NULL;");
4574     $dbh->do("ALTER TABLE deletedborrowers ADD COLUMN debarredcomment VARCHAR(255) DEFAULT NULL AFTER debarred;");
4575     print "Upgrade done (Change borrowers.debarred into Date )\n";
4576     SetVersion($DBversion);
4577 }
4578
4579 $DBversion = "3.07.00.002";
4580 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4581     $dbh->do("UPDATE borrowers SET debarred=NULL WHERE debarred='0000-00-00';");
4582     print "Setting NULL to debarred where 0000-00-00 is stored (bug 7272)\n";
4583     SetVersion($DBversion);
4584 }
4585
4586 $DBversion = "3.07.00.003";
4587 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4588     $dbh->do(" UPDATE `message_attributes` SET message_name='Item_Due' WHERE message_name='Item_DUE'");
4589     print "Updating message_name in message_attributes\n";
4590     SetVersion($DBversion);
4591 }
4592
4593 $DBversion = "3.07.00.004";
4594 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4595     $dbh->do("ALTER TABLE  `suggestions` ADD  `patronreason` TEXT NULL AFTER  `reason`");
4596     print "Upgrade to $DBversion done (Add column to suggestions table to store patrons' reasons for submitting a suggestion. )\n";
4597     SetVersion($DBversion);
4598 }
4599
4600 $DBversion = "3.07.00.005";
4601 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4602     $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')");
4603     print "Upgrade to $DBversion done (BorrowerUnwantedField syspref)\n";
4604     SetVersion ($DBversion);
4605 }
4606
4607 $DBversion = "3.07.00.006";
4608 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4609     $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');");
4610     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";
4611     SetVersion($DBversion);
4612 }
4613
4614 $DBversion = "3.07.00.007";
4615 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4616     $dbh->do("ALTER TABLE items MODIFY materials text;");
4617     print "Upgrade to $DBversion done alter items.material from varchar(10) to text \n";
4618     SetVersion($DBversion);
4619 }
4620
4621 $DBversion = '3.07.00.008';
4622 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4623     if (C4::Context->preference("marcflavour") eq 'MARC21') {
4624         if (C4::Context->preference("opaclanguages") eq "de") {
4625             $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, '');");
4626         } else {
4627             $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, '');");
4628         }
4629     }
4630     print "Upgrade to $DBversion done (add MARC21 field 545 to framework)\n";
4631     SetVersion ($DBversion);
4632 }
4633
4634 $DBversion = "3.07.00.009";
4635 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4636     $dbh->do("ALTER TABLE `aqorders` ADD COLUMN `claims_count` INT(11)  DEFAULT 0, ADD COLUMN `claimed_date` DATE  DEFAULT NULL AFTER `claims_count`");
4637     print "Upgrade to $DBversion done (Add claims_count and claimed_date fields in aqorders table)\n";
4638     SetVersion($DBversion);
4639 }
4640
4641 $DBversion = "3.07.00.010";
4642 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4643     $dbh->do(
4644         q|CREATE TABLE `biblioimages` (
4645           `imagenumber` int(11) NOT NULL AUTO_INCREMENT,
4646           `biblionumber` int(11) NOT NULL,
4647           `mimetype` varchar(15) NOT NULL,
4648           `imagefile` mediumblob NOT NULL,
4649           `thumbnail` mediumblob NOT NULL,
4650           PRIMARY KEY (`imagenumber`),
4651           CONSTRAINT `bibliocoverimage_fk1` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
4652           ) ENGINE=InnoDB DEFAULT CHARSET=utf8|
4653     );
4654     $dbh->do(
4655         q|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OPACLocalCoverImages','0','Display local cover images on OPAC search and details pages.','1','YesNo')|
4656         );
4657     $dbh->do(
4658         q|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('LocalCoverImages','0','Display local cover images on intranet search and details pages.','1','YesNo')|
4659         );
4660     $dbh->do(
4661         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')|
4662     );
4663     $dbh->do(
4664         q|INSERT INTO permissions (module_bit, code, description) VALUES (13, 'upload_local_cover_images', 'Upload local cover images')|
4665     );
4666     print "Upgrade to $DBversion done (Added support for local cover images)\n";
4667     SetVersion($DBversion);
4668 }
4669
4670 $DBversion = "3.07.00.011";
4671 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4672     $dbh->do(<<ENDOFRENEWAL);
4673     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');
4674 ENDOFRENEWAL
4675     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";
4676     SetVersion($DBversion);
4677 }
4678
4679 $DBversion = "3.07.00.012";
4680 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4681     $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')");
4682     print "Upgrade to $DBversion add 'AllowItemsOnHoldCheckout' syspref \n";
4683     SetVersion ($DBversion);
4684 }
4685
4686 $DBversion = "3.07.00.013";
4687 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4688     $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');");
4689     print "Upgrade to $DBversion done (Bug 7345: Add system preference OpacExportOptions.)\n";
4690     SetVersion ($DBversion);
4691 }
4692
4693 $DBversion = "3.07.00.014";
4694 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4695     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";
4696     SetVersion($DBversion);
4697 }
4698
4699 $DBversion = "3.07.00.015";
4700 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4701     my $sth = $dbh->prepare(q|
4702         SELECT COUNT(*) FROM marc_subfield_structure where kohafield="biblioitems.editionstatement"
4703         |);
4704     $sth->execute;
4705     my $already_exists = $sth->fetchrow;
4706     if ( not $already_exists ) {
4707         my $field = C4::Context->preference("marcflavour") eq "UNIMARC" ? "205" : "250";
4708         my $subfield = "a";
4709         my $sth = $dbh->prepare( q|
4710             UPDATE marc_subfield_structure SET kohafield = "biblioitems.editionstatement"
4711             WHERE tagfield = ? AND tagsubfield = ?
4712         |);
4713         $sth->execute( $field, $subfield );
4714         print "Upgrade to $DBversion done (Added a mapping for biblioitems.editionstatement.)\n";
4715     } else {
4716         print "Upgrade to $DBversion done (Added a mapping for biblioitems.editionstatement (already exists, nothing to do).)\n";
4717     }
4718     SetVersion($DBversion);
4719 }
4720
4721 $DBversion = "3.07.00.016";
4722 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4723     $dbh->do("ALTER TABLE items ADD KEY `itemcallnumber` (itemcallnumber)");
4724     print "Upgrade to $DBversion done (Added index on items.itemcallnumber)\n";
4725     SetVersion($DBversion);
4726 }
4727
4728 $DBversion = "3.07.00.017";
4729 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4730     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('TransferWhenCancelAllWaitingHolds','0','Transfer items when cancelling all waiting holds',NULL,'YesNo')");
4731     print "Upgrade to $DBversion done (Add sysprefs to control transfer when cancel all waiting holds)\n";
4732     SetVersion ($DBversion);
4733 }
4734
4735 $DBversion = "3.07.00.018";
4736 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4737     $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;");
4738     print "Upgrade to $DBversion done ( adding offline operations table )\n";
4739     SetVersion($DBversion);
4740 }
4741
4742 $DBversion = "3.07.00.019";
4743 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4744     $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");
4745     $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");
4746     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";
4747     SetVersion($DBversion);
4748 }
4749
4750 $DBversion = "3.07.00.020";
4751 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4752     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OPACpatronimages',0,'Enable patron images in the OPAC',NULL,'YesNo');");
4753     print "Upgrade to $DBversion done (Bug 3516: Add the option to show patron images in the OPAC.)\n";
4754     SetVersion($DBversion);
4755 }
4756
4757 $DBversion = "3.07.00.021";
4758 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4759     $dbh->do(
4760     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('LinkerModule','Default','Chooses which linker module to use (see documentation).','Default|FirstMatchLastMatch','Choice');"
4761     );
4762     $dbh->do(
4763     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('LinkerOptions','','A pipe-separated list of options for the linker.','','free');"
4764     );
4765     $dbh->do(
4766     "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');"
4767     );
4768     $dbh->do(
4769     "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');"
4770     );
4771     $dbh->do(
4772     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AutoCreateAuthorities',0,'Automatically create authorities that do not exist when cataloging records.',NULL,'YesNo');"
4773     );
4774     $dbh->do(
4775     "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');"
4776     );
4777     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";
4778     SetVersion($DBversion);
4779 }
4780
4781 $DBversion = "3.07.00.022";
4782 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4783     $dbh->do("DELETE FROM reviews WHERE biblionumber NOT IN (SELECT biblionumber from biblio)");
4784     $dbh->do("UPDATE reviews SET borrowernumber = NULL WHERE borrowernumber NOT IN (SELECT borrowernumber FROM borrowers)");
4785     $dbh->do("ALTER TABLE reviews ADD CONSTRAINT reviews_ibfk_2 FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE");
4786     $dbh->do("ALTER TABLE reviews ADD CONSTRAINT reviews_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber ) ON UPDATE CASCADE ON DELETE SET NULL");
4787     print "Upgrade to $DBversion done (Bug 7493 - Add constraint linking OPAC comment biblionumber to biblio, OPAC comment borrowernumber to borrowers.)\n";
4788     SetVersion($DBversion);
4789 }
4790
4791 $DBversion = "3.07.00.023";
4792 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4793     $dbh->do("ALTER TABLE `message_transports` DROP FOREIGN KEY `message_transports_ibfk_3`");
4794     $dbh->do("ALTER TABLE `letter` DROP PRIMARY KEY");
4795     $dbh->do("ALTER TABLE `letter` ADD `branchcode` varchar(10) default NULL AFTER `code`");
4796     $dbh->do("ALTER TABLE `letter` ADD PRIMARY KEY  (`module`,`code`, `branchcode`)");
4797     $dbh->do("ALTER TABLE `message_transports` ADD `branchcode` varchar(10) NOT NULL default ''");
4798     $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");
4799     $dbh->do("ALTER TABLE `letter` ADD `is_html` tinyint(1) default 0 AFTER `name`");
4800
4801     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4802               VALUES ('circulation','ISSUESLIP','Issue Slip','Issue Slip', '<h3><<branches.branchname>></h3>
4803 Checked out to <<borrowers.title>> <<borrowers.firstname>> <<borrowers.initials>> <<borrowers.surname>> <br />
4804 (<<borrowers.cardnumber>>) <br />
4805
4806 <<today>><br />
4807
4808 <h4>Checked Out</h4>
4809 <checkedout>
4810 <p>
4811 <<biblio.title>> <br />
4812 Barcode: <<items.barcode>><br />
4813 Date due: <<issues.date_due>><br />
4814 </p>
4815 </checkedout>
4816
4817 <h4>Overdues</h4>
4818 <overdue>
4819 <p>
4820 <<biblio.title>> <br />
4821 Barcode: <<items.barcode>><br />
4822 Date due: <<issues.date_due>><br />
4823 </p>
4824 </overdue>
4825
4826 <hr>
4827
4828 <h4 style=\"text-align: center; font-style:italic;\">News</h4>
4829 <news>
4830 <div class=\"newsitem\">
4831 <h5 style=\"margin-bottom: 1px; margin-top: 1px\"><b><<opac_news.title>></b></h5>
4832 <p style=\"margin-bottom: 1px; margin-top: 1px\"><<opac_news.new>></p>
4833 <p class=\"newsfooter\" style=\"font-size: 8pt; font-style:italic; margin-bottom: 1px; margin-top: 1px\">Posted on <<opac_news.timestamp>></p>
4834 <hr />
4835 </div>
4836 </news>', 1)");
4837     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4838               VALUES ('circulation','ISSUEQSLIP','Issue Quick Slip','Issue Quick Slip', '<h3><<branches.branchname>></h3>
4839 Checked out to <<borrowers.title>> <<borrowers.firstname>> <<borrowers.initials>> <<borrowers.surname>> <br />
4840 (<<borrowers.cardnumber>>) <br />
4841
4842 <<today>><br />
4843
4844 <h4>Checked Out Today</h4>
4845 <checkedout>
4846 <p>
4847 <<biblio.title>> <br />
4848 Barcode: <<items.barcode>><br />
4849 Date due: <<issues.date_due>><br />
4850 </p>
4851 </checkedout>', 1)");
4852     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4853               VALUES ('circulation','RESERVESLIP','Reserve Slip','Reserve Slip', '<h5>Date: <<today>></h5>
4854
4855 <h3> Transfer to/Hold in <<branches.branchname>></h3>
4856
4857 <h3><<borrowers.surname>>, <<borrowers.firstname>></h3>
4858
4859 <ul>
4860     <li><<borrowers.cardnumber>></li>
4861     <li><<borrowers.phone>></li>
4862     <li> <<borrowers.address>><br />
4863          <<borrowers.address2>><br />
4864          <<borrowers.city >>  <<borrowers.zipcode>>
4865     </li>
4866     <li><<borrowers.email>></li>
4867 </ul>
4868 <br />
4869 <h3>ITEM ON HOLD</h3>
4870 <h4><<biblio.title>></h4>
4871 <h5><<biblio.author>></h5>
4872 <ul>
4873    <li><<items.barcode>></li>
4874    <li><<items.itemcallnumber>></li>
4875    <li><<reserves.waitingdate>></li>
4876 </ul>
4877 <p>Notes:
4878 <pre><<reserves.reservenotes>></pre>
4879 </p>', 1)");
4880     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4881               VALUES ('circulation','TRANSFERSLIP','Transfer Slip','Transfer Slip', '<h5>Date: <<today>></h5>
4882 <h3>Transfer to <<branches.branchname>></h3>
4883
4884 <h3>ITEM</h3>
4885 <h4><<biblio.title>></h4>
4886 <h5><<biblio.author>></h5>
4887 <ul>
4888    <li><<items.barcode>></li>
4889    <li><<items.itemcallnumber>></li>
4890 </ul>', 1)");
4891
4892     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('NoticeCSS','','Notices CSS url.',NULL,'free')");
4893     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('SlipCSS','','Slips CSS url.',NULL,'free')");
4894
4895     $dbh->do("UPDATE `letter` SET content = replace(content, '<<title>>', '<<biblio.title>>') WHERE code = 'HOLDPLACED'");
4896
4897     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";
4898     SetVersion($DBversion);
4899 }
4900
4901 $DBversion = "3.07.00.024";
4902 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4903     $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')");
4904     $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')");
4905     print "Upgrade to $DBversion done (Added system preference ExpireReservesMaxPickUpDelay, system preference ExpireReservesMaxPickUpDelayCharge, add reseves.charge_if_expired)\n";
4906 }
4907
4908 $DBversion = "3.07.00.025";
4909 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4910     if (TableExists('bibliocoverimage')) {
4911         $dbh->do( q|DROP TABLE bibliocoverimage;| );
4912         $dbh->do(
4913             q|CREATE TABLE biblioimages (
4914               imagenumber int(11) NOT NULL AUTO_INCREMENT,
4915               biblionumber int(11) NOT NULL,
4916               mimetype varchar(15) NOT NULL,
4917               imagefile mediumblob NOT NULL,
4918               thumbnail mediumblob NOT NULL,
4919               PRIMARY KEY (imagenumber),
4920               CONSTRAINT bibliocoverimage_fk1 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
4921               ) ENGINE=InnoDB DEFAULT CHARSET=utf8;|
4922         );
4923     }
4924     print "Upgrade to $DBversion done (Correct table name for local cover images if needed. )\n";
4925     SetVersion($DBversion);
4926 }
4927
4928 $DBversion = "3.07.00.026";
4929 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4930     $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');");
4931     print "Upgrade to $DBversion done (Add syspref CalendarFirstDayOfWeek used to select the first day of week to use in the calendar. )\n";
4932     SetVersion($DBversion);
4933 }
4934
4935 $DBversion = "3.07.00.027";
4936 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4937     $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');});
4938     print "Upgrade to $DBversion done (Added system preference RoutingListNote for adding a general note to all routing lists.)\n";
4939     SetVersion($DBversion);
4940 }
4941
4942 $DBversion = "3.07.00.028";
4943 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4944     $dbh->do(qq{
4945     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');
4946     });
4947     print "Upgrade to $DBversion done (Bug 6296 New System preference AllowPKIAuth)\n";
4948 }
4949
4950 $DBversion = "3.07.00.029";
4951 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4952     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_descriptions`;});
4953     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_mappings`;});
4954     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_biblios`;});
4955     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets`;});
4956
4957     $dbh->do(q{
4958         CREATE TABLE `oai_sets` (
4959           `id` int(11) NOT NULL auto_increment,
4960           `spec` varchar(80) NOT NULL UNIQUE,
4961           `name` varchar(80) NOT NULL,
4962           PRIMARY KEY (`id`)
4963         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4964     });
4965
4966     $dbh->do(q{
4967         CREATE TABLE `oai_sets_descriptions` (
4968           `set_id` int(11) NOT NULL,
4969           `description` varchar(255) NOT NULL,
4970           CONSTRAINT `oai_sets_descriptions_ibfk_1` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4971         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4972     });
4973
4974     $dbh->do(q{
4975         CREATE TABLE `oai_sets_mappings` (
4976           `set_id` int(11) NOT NULL,
4977           `marcfield` char(3) NOT NULL,
4978           `marcsubfield` char(1) NOT NULL,
4979           `marcvalue` varchar(80) NOT NULL,
4980           CONSTRAINT `oai_sets_mappings_ibfk_1` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4981         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4982     });
4983
4984     $dbh->do(q{
4985         CREATE TABLE `oai_sets_biblios` (
4986           `biblionumber` int(11) NOT NULL,
4987           `set_id` int(11) NOT NULL,
4988           PRIMARY KEY (`biblionumber`, `set_id`),
4989           CONSTRAINT `oai_sets_biblios_ibfk_1` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
4990           CONSTRAINT `oai_sets_biblios_ibfk_2` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4991         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4992     });
4993
4994     $dbh->do(q{
4995         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');
4996     });
4997
4998     print "Upgrade to $DBversion done (Atomic update for OAI-PMH sets management)\n";
4999     SetVersion($DBversion);
5000 }
5001
5002 $DBversion = "3.07.00.030";
5003 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5004     $dbh->do("ALTER TABLE default_circ_rules ADD
5005             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5006     $dbh->do("ALTER TABLE branch_item_rules ADD
5007             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5008     $dbh->do("ALTER TABLE default_branch_circ_rules ADD
5009             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5010     $dbh->do("ALTER TABLE default_branch_item_rules ADD
5011             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5012     # set the default rule to the current value of HomeOrHoldingBranchReturn (default to 'homebranch' if need be)
5013     my $homeorholdingbranchreturn = C4::Context->preference('HomeOrHoldingBranchReturn') || 'homebranch';
5014     $dbh->do("UPDATE default_circ_rules SET returnbranch = '$homeorholdingbranchreturn'");
5015     print "Upgrade to $DBversion done (Atomic update for OAI-PMH sets management)\n";
5016     SetVersion($DBversion);
5017 }
5018
5019 $DBversion = "3.07.00.031";
5020 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5021     $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')");
5022     print "Upgrade to $DBversion done (Add syspref to tell Koha if ICU indexing is in use for Zebra or not.)\n";
5023     SetVersion ($DBversion);
5024 }
5025
5026 $DBversion = "3.07.00.032";
5027 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5028     $dbh->do("ALTER TABLE virtualshelves MODIFY COLUMN owner int"); #should have been int already (fk to borrowers)
5029     $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
5030     $dbh->do("DELETE FROM virtualshelves WHERE owner IS NULL and category=1"); #delete private lists without owner (cascades to shelfcontents)
5031     $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");
5032     $dbh->do("UPDATE virtualshelves SET allow_add=0, allow_delete_own=1, allow_delete_other=0 WHERE category=1");
5033     $dbh->do("UPDATE virtualshelves SET allow_add=0, allow_delete_own=1, allow_delete_other=0 WHERE category=2");
5034     $dbh->do("UPDATE virtualshelves SET allow_add=1, allow_delete_own=1, allow_delete_other=1 WHERE category=3");
5035     $dbh->do("UPDATE virtualshelves SET category=2 WHERE category=3");
5036
5037     $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");
5038     $dbh->do("UPDATE virtualshelfcontents co LEFT JOIN virtualshelves sh USING (shelfnumber) SET co.borrowernumber=sh.owner");
5039
5040     $dbh->do("CREATE TABLE virtualshelfshares
5041     (id int AUTO_INCREMENT PRIMARY KEY, shelfnumber int NOT NULL,
5042     borrowernumber int, invitekey varchar(10), sharedate datetime,
5043     CONSTRAINT `virtualshelfshares_ibfk_1` FOREIGN KEY (`shelfnumber`) REFERENCES `virtualshelves` (`shelfnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
5044         CONSTRAINT `virtualshelfshares_ibfk_2` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE SET NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8");
5045
5046     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacAllowPublicListCreation',1,'If set, allows opac users to create public lists',NULL,'YesNo');");
5047     $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');");
5048
5049     print "Upgrade to $DBversion done (BZ7310: Improving list permissions)\n";
5050     SetVersion($DBversion);
5051 }
5052
5053 $DBversion = "3.07.00.033";
5054 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5055     $dbh->do("ALTER TABLE branches ADD opac_info text;");
5056     print "Upgrade to $DBversion done add opac_info to branches \n";
5057     SetVersion($DBversion);
5058 }
5059
5060 $DBversion = "3.07.00.034";
5061 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5062     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN category_code VARCHAR(10) NULL DEFAULT NULL AFTER `display_checkout`");
5063     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN class VARCHAR(255)  NOT NULL DEFAULT '' AFTER `category_code`");
5064     $dbh->do("ALTER TABLE borrower_attribute_types ADD CONSTRAINT category_code_fk FOREIGN KEY (category_code) REFERENCES categories(categorycode)");
5065     print "Upgrade to $DBversion done (New fields category_code and class in borrower_attribute_types table)\n";
5066     SetVersion($DBversion);
5067 }
5068
5069 $DBversion = "3.07.00.035";
5070 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5071     $dbh->do("ALTER TABLE issues CHANGE date_due date_due datetime");
5072     $dbh->do("UPDATE issues SET date_due = CONCAT(SUBSTR(date_due,1,11),'23:59:00')");
5073     $dbh->do("ALTER TABLE issues CHANGE returndate returndate datetime");
5074     $dbh->do("ALTER TABLE issues CHANGE lastreneweddate lastreneweddate datetime");
5075     $dbh->do("ALTER TABLE issues CHANGE issuedate issuedate datetime");
5076     $dbh->do("ALTER TABLE old_issues CHANGE date_due date_due datetime");
5077     $dbh->do("ALTER TABLE old_issues CHANGE returndate returndate datetime");
5078     $dbh->do("ALTER TABLE old_issues CHANGE lastreneweddate lastreneweddate datetime");
5079     $dbh->do("ALTER TABLE old_issues CHANGE issuedate issuedate datetime");
5080     $dbh->do("UPDATE accountlines SET description = CONCAT(description,' 23:59') WHERE accounttype='F' OR accounttype='FU'"); #BUG-8253
5081     print "Upgrade to $DBversion done (Setting up issues and accountlines tables for hourly loans)\n";
5082     SetVersion($DBversion);
5083 }
5084
5085 $DBversion = "3.07.00.036";
5086 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5087     $dbh->do(qq{
5088        ALTER TABLE z3950servers ADD timeout INT( 11 ) NOT NULL DEFAULT '0' AFTER syntax;
5089     });
5090     print "Upgrade to $DBversion done (New timeout field in z3950servers)\n";
5091 }
5092
5093 $DBversion = "3.07.00.037";
5094 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5095     $dbh->do("
5096        ALTER TABLE  `marc_subfield_structure` ADD  `maxlength` INT( 4 ) NOT NULL DEFAULT  '9999';
5097        ");
5098        $dbh->do("
5099        UPDATE `marc_subfield_structure` SET maxlength=24 WHERE tagfield='000';
5100        ");
5101        $dbh->do("
5102        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='MARC21','40','9999') WHERE tagfield='008';
5103        ");
5104        $dbh->do("
5105        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='NORMARC','40','9999') WHERE tagfield='008';
5106        ");
5107        $dbh->do("
5108        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='UNIMARC','36','9999') WHERE tagfield='100';
5109        ");
5110     print "Upgrade to $DBversion done (Add new field maxlength to marc_subfield_structure)\n";
5111     SetVersion($DBversion);
5112 }
5113
5114 $DBversion = "3.07.00.038";
5115 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5116     $dbh->do(qq{
5117         INSERT INTO systempreferences(variable,value,explanation,options,type)
5118         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')
5119     });
5120     print "Upgrade to $DBversion done (Added system preference 'UniqueItemFields')\n";
5121     SetVersion($DBversion);
5122 }
5123
5124 $DBversion = "3.07.00.039";
5125 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5126     $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')} );
5127     $dbh->do( qq{CREATE TABLE IF NOT EXISTS social_data
5128       ( isbn VARCHAR(30),
5129         num_critics INT,
5130         num_critics_pro INT,
5131         num_quotations INT,
5132         num_videos INT,
5133         score_avg DECIMAL(5,2),
5134         num_scores INT,
5135         PRIMARY KEY  (isbn)
5136       ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5137     } );
5138     $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')} );
5139     print "Upgrade to $DBversion done (added syspref and table for babeltheque (Babeltheque_url_js, babeltheque))\n";
5140     SetVersion($DBversion);
5141 }
5142
5143 $DBversion = "3.07.00.040";
5144 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5145     $dbh->do( qq{INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('SocialNetworks','0','Enable/Disable social networks links in opac detail','','YesNo')} );
5146     print "Upgrade to $DBversion done (added syspref SocialNetworks, to display facebook/ggl+ and other buttons)\n";
5147     SetVersion($DBversion);
5148 }
5149
5150
5151
5152 $DBversion = "3.07.00.041";
5153 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5154     $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')");
5155     print "Upgrade to $DBversion done (Add system preference SubscriptionDuplicateDroppedInput)\n";
5156     SetVersion($DBversion);
5157 }
5158
5159 $DBversion = "3.07.00.042";
5160 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5161     $dbh->do("ALTER TABLE reserves ADD suspend BOOLEAN NOT NULL DEFAULT 0");
5162     $dbh->do("ALTER TABLE old_reserves ADD suspend BOOLEAN NOT NULL DEFAULT 0");
5163
5164     $dbh->do("ALTER TABLE reserves ADD suspend_until DATETIME NULL DEFAULT NULL");
5165     $dbh->do("ALTER TABLE old_reserves ADD suspend_until DATETIME NULL DEFAULT NULL");
5166
5167     $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')");
5168
5169     print "Upgrade to $DBversion done (Add suspend fields to reserves table, add syspref AutoResumeSuspendedHolds)\n";
5170     SetVersion ($DBversion);
5171 }
5172
5173 $DBversion = "3.07.00.043";
5174 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5175     my $countXSLTDetailsDisplay = 0;
5176     my $valueXSLTDetailsDisplay = "";
5177     my $valueXSLTResultsDisplay = "";
5178     my $valueOPACXSLTDetailsDisplay = "";
5179     my $valueOPACXSLTResultsDisplay = "";
5180     #the line below test if database comes from a BibLibre's branch
5181     $countXSLTDetailsDisplay = $dbh->do('SELECT 1 FROM systempreferences WHERE variable="IntranetXSLTDetailsDisplay"');
5182     if ($countXSLTDetailsDisplay > 0)
5183     {
5184         #the two lines below will only be used to update the databases from the BibLibre's branch. They will not affect the others
5185         $dbh->do(q|UPDATE systempreferences SET variable="XSLTDetailsDisplay" WHERE variable="IntranetXSLTDetailsDisplay"|);
5186         $dbh->do(q|UPDATE systempreferences SET variable="XSLTResultsDisplay" WHERE variable="IntranetXSLTResultsDisplay"|);
5187     }
5188     else
5189     {
5190         $valueXSLTDetailsDisplay = "default" if (C4::Context->preference("XSLTDetailsDisplay"));
5191         $valueXSLTResultsDisplay = "default" if (C4::Context->preference("XSLTResultsDisplay"));
5192         $valueOPACXSLTDetailsDisplay = "default" if (C4::Context->preference("OPACXSLTDetailsDisplay"));
5193         $valueOPACXSLTResultsDisplay = "default" if (C4::Context->preference("OPACXSLTResultsDisplay"));
5194         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueXSLTDetailsDisplay\" WHERE variable='XSLTDetailsDisplay'");
5195         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueXSLTResultsDisplay\" WHERE variable='XSLTResultsDisplay'");
5196         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueOPACXSLTDetailsDisplay\" WHERE variable='OPACXSLTDetailsDisplay'");
5197         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueOPACXSLTResultsDisplay\" WHERE variable='OPACXSLTResultsDisplay'");
5198     }
5199     print "Upgrade to $DBversion done (XSLT systempreference takes a path to file rather than YesNo)\n";
5200     SetVersion($DBversion);
5201 }
5202
5203 $DBversion = "3.07.00.044";
5204 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5205     $dbh->do("ALTER TABLE aqbooksellers ADD deliverytime INT DEFAULT NULL");
5206     print "Upgrade to $DBversion done (Add deliverytime field in aqbooksellers table)";
5207     SetVersion($DBversion);
5208 }
5209
5210 $DBversion = "3.07.00.045";
5211 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5212     $dbh->do("ALTER TABLE import_batches MODIFY COLUMN batch_type ENUM('batch','z3950','webservice') NOT NULL default 'batch'");
5213     print "Upgrade to $DBversion done (Add 'webservice' to batch_type enum)\n";
5214     SetVersion ($DBversion);
5215 }
5216
5217 $DBversion = "3.07.00.046";
5218 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5219     $dbh->do("ALTER TABLE issuingrules ADD COLUMN lengthunit varchar(10) DEFAULT 'days' AFTER issuelength");
5220     print "Upgrade to $DBversion done (Setting up issues tables for hourly loans (lengthunit fix))\n";
5221     SetVersion($DBversion);
5222 }
5223
5224 $DBversion = "3.07.00.047";
5225 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5226     $dbh->do("CREATE INDEX items_location ON items(location)");
5227     $dbh->do("CREATE INDEX items_ccode ON items(ccode)");
5228     print "Upgrade to $DBversion done (items_location and items_ccode indexes added for ShelfBrowser)\n";
5229     SetVersion($DBversion);
5230 }
5231
5232 $DBversion = "3.07.00.048";
5233 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5234     $dbh->do(
5235         q | CREATE TABLE ratings (
5236   borrowernumber int(11) NOT NULL,
5237   biblionumber int(11) NOT NULL,
5238   rating_value tinyint(1) NOT NULL,
5239   timestamp timestamp NOT NULL default CURRENT_TIMESTAMP,
5240   PRIMARY KEY  (borrowernumber,biblionumber),
5241   CONSTRAINT ratings_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE,
5242   CONSTRAINT ratings_ibfk_2 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
5243 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
5244     );
5245
5246     $dbh->do(
5247 q /INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OpacStarRatings','disable',NULL,'disable|all|details','Choice') /
5248     );
5249
5250     print
5251 "Upgrade to $DBversion done (Add 'ratings' table and 'OpacStarRatings' syspref)\n";
5252     SetVersion($DBversion);
5253 }
5254
5255 $DBversion = "3.07.00.049";
5256 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5257     $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')");
5258     print "Upgrade to $DBversion done (Add system preference OpacBrowseResults ))\n";
5259     SetVersion($DBversion);
5260 }
5261
5262 $DBversion = "3.08.00.000";
5263 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5264     print "Upgrade to $DBversion done\n";
5265     SetVersion($DBversion);
5266 }
5267
5268 $DBversion = "3.09.00.001";
5269 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5270     $dbh->do("ALTER TABLE borrower_attribute_types MODIFY category_code VARCHAR( 1 ) NULL DEFAULT NULL");
5271     print "Upgrade to $DBversion done. (Bug 8002: Update patron attribute types table to allow NULL category_code)\n";
5272     SetVersion($DBversion);
5273 }
5274
5275 $DBversion = "3.09.00.002";
5276 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5277     $dbh->do("ALTER TABLE saved_sql
5278         ADD (
5279             cache_expiry INT NOT NULL DEFAULT 300,
5280             public BOOLEAN NOT NULL DEFAULT FALSE
5281         );
5282     ");
5283     print "Upgrade to $DBversion done (Added cache_expiry and public fields in
5284 saved_reports table.)\n";
5285     SetVersion($DBversion);
5286 }
5287
5288 $DBversion = "3.09.00.003";
5289 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5290     $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');");
5291     print "Upgrade to $DBversion done (Added SvcMaxReportRows syspref)\n";
5292     SetVersion($DBversion);
5293 }
5294
5295 $DBversion = "3.09.00.004";
5296 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5297     $dbh->do("INSERT IGNORE INTO permissions (module_bit, code, description) VALUES('13', 'edit_patrons', 'Perform batch modifivation of patrons')");
5298     print "Upgrade to $DBversion done (Adds permissions flag for access to the patron modifications tool)\n";
5299     SetVersion($DBversion);
5300 }
5301
5302 $DBversion = "3.09.00.005";
5303 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5304     unless (TableExists('quotes')) {
5305         $dbh->do( qq{
5306             CREATE TABLE `quotes` (
5307               `id` int(11) NOT NULL AUTO_INCREMENT,
5308               `source` text DEFAULT NULL,
5309               `text` mediumtext NOT NULL,
5310               `timestamp` datetime NOT NULL,
5311               PRIMARY KEY (`id`)
5312             ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5313         });
5314     }
5315     $dbh->do( qq{
5316         INSERT IGNORE INTO permissions VALUES (13, "edit_quotes","Edit quotes for quote-of-the-day feature");
5317     });
5318     $dbh->do( qq{
5319         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');
5320     });
5321     print "Upgrade to $DBversion done (Adding Quote of the Day Option.)\n";
5322     SetVersion($DBversion);
5323 }
5324
5325 $DBversion = "3.09.00.006";
5326 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5327     $dbh->do("UPDATE systempreferences SET
5328                 variable = 'OPACShowHoldQueueDetails',
5329                 value = CASE value WHEN '1' THEN 'priority' ELSE 'none' END,
5330                 options = 'none|priority|holds|holds_priority',
5331                 explanation = 'Show holds details in OPAC',
5332                 type = 'Choice'
5333               WHERE variable = 'OPACDisplayRequestPriority'");
5334     print "Upgrade to $DBversion done (Changed system preference OPACDisplayRequestPriority -> OPACShowHoldQueueDetails)\n";
5335     SetVersion($DBversion);
5336 }
5337
5338 $DBversion = "3.09.00.007";
5339 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5340     unless(C4::Context->preference('ReservesControlBranch')){
5341         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('ReservesControlBranch','PatronLibrary','ItemHomeLibrary|PatronLibrary','Branch checked for members reservations rights.','Choice')");
5342     }
5343     print "Upgrade to $DBversion done (Insert ReservesControlBranch systempreference into systempreferences table )\n";
5344     SetVersion($DBversion);
5345 }
5346
5347 $DBversion = "3.09.00.008";
5348 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5349     $dbh->do("ALTER TABLE sessions ADD PRIMARY KEY (id);");
5350     $dbh->do("ALTER TABLE sessions DROP INDEX `id`;");
5351     print "Upgrade to $DBversion done (redefine the field id as PRIMARY KEY of sessions)\n";
5352     SetVersion($DBversion);
5353 }
5354
5355 $DBversion = "3.09.00.009";
5356 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5357     $dbh->do("ALTER TABLE branches ADD PRIMARY KEY (branchcode);");
5358     $dbh->do("ALTER TABLE branches DROP INDEX branchcode;");
5359     print "Upgrade to $DBversion done (redefine the field branchcode as PRIMARY KEY of branches)\n";
5360     SetVersion ($DBversion);
5361 }
5362
5363 $DBversion = "3.09.00.010";
5364 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5365     $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')");
5366     print "Upgrade to $DBversion done (Add system preference issuelostitem ))\n";
5367     SetVersion($DBversion);
5368 }
5369
5370 $DBversion = "3.09.00.011";
5371 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5372     $dbh->do("ALTER TABLE `biblioitems` ADD `ean` VARCHAR( 13 ) NULL AFTER issn");
5373     $dbh->do("CREATE INDEX `ean` ON biblioitems (`ean`) ");
5374     $dbh->do("ALTER TABLE `deletedbiblioitems` ADD `ean` VARCHAR( 13 ) NULL AFTER issn");
5375     if (C4::Context->preference("marcflavour") eq 'UNIMARC') {
5376          $dbh->do("UPDATE marc_subfield_structure SET kohafield='biblioitems.ean' WHERE tagfield='073' and tagsubfield='a'");
5377     }
5378     print "Upgrade to $DBversion done (Adding ean in biblioitems and deletedbiblioitems)\n";
5379     print "If you have records with ean, please run misc/batchRebuildBiblioTables.pl to populate bibliotems.ean\n" if (C4::Context->preference("marcflavour") eq 'UNIMARC');
5380     SetVersion($DBversion);
5381 }
5382
5383 $DBversion = "3.09.00.012";
5384 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5385     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('SuspendHoldsIntranet', '1', NULL , 'Allow holds to be suspended from the intranet.', 'YesNo')");
5386     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('SuspendHoldsOpac', '1', NULL , 'Allow holds to be suspended from the OPAC.', 'YesNo')");
5387     print "Upgrade to $DBversion done (Add system preference OpacBrowseResults ))\n";
5388     SetVersion($DBversion);
5389 }
5390
5391 $DBversion ="3.09.00.013";
5392 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5393     $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');");
5394     print "Upgrade to $DBversion done (Add system preference DefaultLanguageField008))\n";
5395     SetVersion($DBversion);
5396 }
5397
5398 $DBversion ="3.09.00.014";
5399 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5400     # add phone message transport type
5401     $dbh->do("INSERT INTO message_transport_types (message_transport_type) VALUES ('phone')");
5402
5403     # adds HOLD_PHONE and PREDUE_PHONE letters (as placeholders)
5404     $dbh->do("INSERT INTO letter (module, code, name, title, content) VALUES
5405               ('reserves', 'HOLD_PHONE', 'Item Available for Pick-up (phone notice)', 'Item Available for Pick-up (phone notice)', 'Your item is available for pickup'),
5406               ('circulation', 'PREDUE_PHONE', 'Advance Notice of Item Due (phone notice)', 'Advance Notice of Item Due (phone notice)', 'Your item is due soon'),
5407               ('circulation', 'OVERDUE_PHONE', 'Overdue Notice (phone notice)', 'Overdue Notice (phone notice)', 'Your item is overdue')
5408               ");
5409
5410     # add phone notifications to patron message preferences options
5411     $dbh->do("INSERT INTO message_transports
5412              (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) VALUES
5413              (4, 'phone', 0, 'reserves', 'HOLD_PHONE'),
5414              (2, 'phone', 0, 'circulation', 'PREDUE_PHONE')
5415              ");
5416
5417     # add TalkingTechItivaPhoneNotification syspref
5418     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('TalkingTechItivaPhoneNotification',0,'If ON, enables Talking Tech I-tiva phone notifications',NULL,'YesNo');");
5419
5420     print "Upgrade done (Support for Talking Tech i-tiva phone notification system)\n";
5421     SetVersion($DBversion);
5422 }
5423
5424 $DBversion = "3.09.00.015";
5425 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5426     $dbh->do(qq{
5427         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')
5428     });
5429     print "Upgrade to $DBversion done (Add System preference StatisticsFields)\n";
5430     SetVersion($DBversion);
5431 }
5432
5433 $DBversion = "3.09.00.016";
5434 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5435     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACShowBarcode','0','Show items barcode in holding tab','','YesNo')");
5436     print "Upgrade to $DBversion done (Add syspref OPACShowBarcode)\n";
5437     SetVersion ($DBversion);
5438 }
5439
5440 $DBversion = "3.09.00.017";
5441 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5442     $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');");
5443     print "Upgrade to $DBversion done (Add customizable OpacNavRight region to the OPAC main page)\n";
5444     SetVersion ($DBversion);
5445 }
5446
5447 $DBversion = "3.09.00.018";
5448 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5449     $dbh->do("DROP TABLE IF EXISTS aqbudgetborrowers");
5450     $dbh->do("
5451         CREATE TABLE aqbudgetborrowers (
5452           budget_id int(11) NOT NULL,
5453           borrowernumber int(11) NOT NULL,
5454           PRIMARY KEY (budget_id, borrowernumber),
5455           CONSTRAINT aqbudgetborrowers_ibfk_1 FOREIGN KEY (budget_id)
5456             REFERENCES aqbudgets (budget_id)
5457             ON DELETE CASCADE ON UPDATE CASCADE,
5458           CONSTRAINT aqbudgetborrowers_ibfk_2 FOREIGN KEY (borrowernumber)
5459             REFERENCES borrowers (borrowernumber)
5460             ON DELETE CASCADE ON UPDATE CASCADE
5461         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
5462     ");
5463     $dbh->do("
5464         INSERT INTO permissions (module_bit, code, description)
5465         VALUES (11, 'budget_manage_all', 'Manage all budgets')
5466     ");
5467     print "Upgrade to $DBversion done (Add aqbudgetborrowers table)\n";
5468     SetVersion($DBversion);
5469 }
5470
5471 $DBversion = "3.09.00.019";
5472 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5473     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('OPACShowUnusedAuthorities','1','','Show authorities that are not being used in the OPAC.','YesNo')");
5474     print "Upgrade to $DBversion done (Add OPACShowUnusedAuthorities system preference)\n";
5475     SetVersion ($DBversion);
5476 }
5477
5478 $DBversion = "3.09.00.020";
5479 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5480     $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')");
5481     $dbh->do("
5482 CREATE TABLE IF NOT EXISTS borrower_files (
5483   file_id int(11) NOT NULL AUTO_INCREMENT,
5484   borrowernumber int(11) NOT NULL,
5485   file_name varchar(255) NOT NULL,
5486   file_type varchar(255) NOT NULL,
5487   file_description varchar(255) DEFAULT NULL,
5488   file_content longblob NOT NULL,
5489   date_uploaded timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
5490   PRIMARY KEY (file_id),
5491   KEY borrowernumber (borrowernumber)
5492 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
5493     ");
5494     $dbh->do("ALTER TABLE borrower_files ADD CONSTRAINT borrower_files_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE");
5495
5496     print "Upgrade to $DBversion done (Added borrow_files table, EnableBorrowerFiles syspref)\n";
5497     SetVersion($DBversion);
5498 }
5499
5500 $DBversion = "3.09.00.021";
5501 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5502     $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');");
5503     print "Upgrade to $DBversion done (Add syspref UpdateTotalIssuesOnCirc)\n";
5504     SetVersion($DBversion);
5505 }
5506
5507 $DBversion = "3.09.00.022";
5508 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5509     $dbh->do("ALTER TABLE search_history MODIFY COLUMN query_cgi text NOT NULL");
5510     print "Upgrade to $DBversion done (Change search_history.query_cgi type to text. bug 5981)\n";
5511     SetVersion($DBversion);
5512 }
5513
5514 $DBversion = "3.09.00.023";
5515 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5516     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('SearchEngine','Zebra','Solr|Zebra','Search Engine','Choice')");
5517     print "Upgrade to $DBversion done (Add system preference SearchEngine )\n";
5518     SetVersion($DBversion);
5519 }
5520
5521 $DBversion ="3.09.00.024";
5522 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5523     $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')");
5524     print "Upgrade to $DBversion done (Add system preference IntranetSlipPrinterJS))\n";
5525     SetVersion($DBversion);
5526 }
5527
5528 $DBversion = "3.09.00.025";
5529 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5530     $dbh->do('START TRANSACTION');
5531     $dbh->do('CREATE TABLE tmp_reserves AS SELECT * FROM old_reserves LIMIT 0');
5532     $dbh->do('ALTER TABLE tmp_reserves ADD reserve_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
5533     $dbh->do("
5534         INSERT INTO tmp_reserves (
5535           borrowernumber, reservedate, biblionumber,
5536           constrainttype, branchcode, notificationdate,
5537           reminderdate, cancellationdate, reservenotes,
5538           priority, found, timestamp, itemnumber,
5539           waitingdate, expirationdate, lowestPriority,
5540           suspend, suspend_until
5541         ) SELECT
5542           borrowernumber, reservedate, biblionumber,
5543           constrainttype, branchcode, notificationdate,
5544           reminderdate, cancellationdate, reservenotes,
5545           priority, found, timestamp, itemnumber,
5546           waitingdate, expirationdate, lowestPriority,
5547           suspend, suspend_until
5548         FROM old_reserves ORDER BY reservedate
5549     ");
5550     $dbh->do('SET @ai = ( SELECT MAX( reserve_id ) FROM tmp_reserves )');
5551     $dbh->do('TRUNCATE old_reserves');
5552     $dbh->do('ALTER TABLE old_reserves ADD reserve_id INT( 11 ) NOT NULL PRIMARY KEY FIRST');
5553     $dbh->do('INSERT INTO old_reserves SELECT * FROM tmp_reserves WHERE reserve_id <= @ai');
5554     $dbh->do("
5555         INSERT INTO tmp_reserves (
5556           borrowernumber, reservedate, biblionumber,
5557           constrainttype, branchcode, notificationdate,
5558           reminderdate, cancellationdate, reservenotes,
5559           priority, found, timestamp, itemnumber,
5560           waitingdate, expirationdate, lowestPriority,
5561           suspend, suspend_until
5562         ) SELECT
5563           borrowernumber, reservedate, biblionumber,
5564           constrainttype, branchcode, notificationdate,
5565           reminderdate, cancellationdate, reservenotes,
5566           priority, found, timestamp, itemnumber,
5567           waitingdate, expirationdate, lowestPriority,
5568           suspend, suspend_until
5569         FROM reserves ORDER BY reservedate
5570     ");
5571     $dbh->do('TRUNCATE reserves');
5572     $dbh->do('ALTER TABLE reserves ADD reserve_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
5573     $dbh->do('INSERT INTO reserves SELECT * FROM tmp_reserves WHERE reserve_id > COALESCE(@ai, 0)');
5574     $dbh->do('DROP TABLE tmp_reserves');
5575     $dbh->do('COMMIT');
5576
5577     my $sth = $dbh->prepare("
5578         SELECT COUNT( * ) AS count
5579         FROM information_schema.COLUMNS
5580         WHERE COLUMN_NAME =  'reserve_id'
5581         AND (
5582           TABLE_NAME LIKE  'reserves'
5583           OR
5584           TABLE_NAME LIKE  'old_reserves'
5585         )
5586     ");
5587     $sth->execute();
5588     my $row = $sth->fetchrow_hashref();
5589     die("Failed to add reserve_id to reserves tables, please refresh the page to try again.") unless ( $row->{'count'} );
5590
5591     print "Upgrade to $DBversion done (add reserve_id to reserves & old_reserves tables)\n";
5592     SetVersion($DBversion);
5593 }
5594
5595 $DBversion = "3.09.00.026";
5596 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5597     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
5598         ( 3, 'parameters_remaining_permissions', 'Remaining system parameters permissions'),
5599         ( 3, 'manage_circ_rules', 'manage circulation rules')");
5600     $dbh->do("INSERT INTO user_permissions (borrowernumber, module_bit, code)
5601         SELECT borrowernumber, 3, 'parameters_remaining_permissions'
5602         FROM borrowers WHERE flags & (1 << 3)");
5603     # Give new subpermissions to all users that have 'parameters' permission flag (bit 3) set
5604     # see userflags table
5605     $dbh->do("INSERT INTO user_permissions (borrowernumber, module_bit, code)
5606         SELECT borrowernumber, 3, 'manage_circ_rules'
5607         FROM borrowers WHERE flags & (1 << 3)");
5608     print "Upgrade to $DBversion done (Added parameters subpermissions)\n";
5609     SetVersion($DBversion);
5610 }
5611
5612 $DBversion = '3.09.00.027';
5613 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5614     $dbh->do("ALTER TABLE issuingrules ADD overduefinescap decimal(28,6) DEFAULT NULL");
5615     my $maxfine = C4::Context->preference('MaxFine');
5616     if ($maxfine && $maxfine < 900) { # an arbitrary value that tells us it's not "some huge value"
5617       $dbh->do("UPDATE issuingrules SET overduefinescap=?",undef,$maxfine);
5618       $dbh->do("UPDATE systempreferences SET value = NULL WHERE variable = 'MaxFine'");
5619     }
5620     $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'");
5621     print "Upgrade to $DBversion done (Bug 7420 add overduefinescap to circulation matrix)\n";
5622     SetVersion ($DBversion);
5623 }
5624
5625 $DBversion = "3.09.00.028";
5626 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5627     unless ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) {
5628         my %referencetypes = (  '00' => 'PERSO_NAME',
5629                                 '10' => 'CORPO_NAME',
5630                                 '11' => 'MEETI_NAME',
5631                                 '30' => 'UNIF_TITLE',
5632                                 '48' => 'CHRON_TERM',
5633                                 '50' => 'TOPIC_TERM',
5634                                 '51' => 'GEOGR_NAME',
5635                                 '55' => 'GENRE/FORM'
5636                 );
5637         my $query = q{SELECT DISTINCT authtypecode, tagfield
5638                     FROM auth_subfield_structure
5639                     WHERE (tagfield BETWEEN '400' AND '455' OR
5640                     tagfield BETWEEN '500' and '555') AND tagsubfield='a' AND
5641                     frameworkcode = '' AND ROW(authtypecode, tagfield) NOT IN
5642                     (SELECT authtypecode, tagfield FROM auth_subfield_structure
5643                     WHERE tagsubfield ='9' )};
5644         $sth = $dbh->prepare($query);
5645         $sth->execute;
5646         my $sth2 = $dbh->prepare(q{INSERT INTO auth_subfield_structure
5647                 (authtypecode, tagfield, tagsubfield, liblibrarian, libopac,
5648                  repeatable, mandatory, tab, authorised_value, value_builder,
5649                  seealso, isurl, hidden, linkid, kohafield, frameworkcode)
5650                 VALUES (?, ?, '9', '9 (RLIN)', '9 (RLIN)', 0, 0, ?, NULL, NULL,
5651                     NULL, 0, 1, '', '', '')});
5652         my $sth3 = $dbh->prepare(q{UPDATE auth_subfield_structure SET
5653                                     frameworkcode = ? WHERE authtypecode = ? AND
5654                                     tagfield = ? AND tagsubfield = 'a'});
5655         while (my $row = $sth->fetchrow_arrayref()) {
5656             my ($authtypecode, $field) = @$row;
5657             $sth2->execute($authtypecode, $field, substr($field, 0, 1));
5658             my $authtypemarker = substr $field, 1, 2;
5659             if ($authtypemarker && $referencetypes{$authtypemarker}) {
5660                 $sth3->execute($referencetypes{$authtypemarker}, $authtypecode, $field);
5661             }
5662         }
5663     }
5664
5665     print "Upgrade to $DBversion done (Add thesaurus links for MARC21/NORMARC)\n";
5666     SetVersion($DBversion);
5667 }
5668
5669 $DBversion = "3.09.00.029"; # FIXME
5670 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5671     $dbh->do("UPDATE systempreferences SET options=concat(options,'|EAN13') WHERE variable='itemBarcodeInputFilter' AND options NOT LIKE '%EAN13%'");
5672     print "Upgrade to $DBversion done (Add itemBarcodeInputFilter choice EAN13)\n";
5673
5674     $dbh->do("UPDATE systempreferences SET options = concat(options,'|EAN13'), explanation = concat(explanation,'; EAN13 - incremental') WHERE variable = 'autoBarcode' AND options NOT LIKE '%EAN13%'");
5675     print "Upgrade to $DBversion done ( Added EAN13 barcode autogeneration sequence )\n";
5676     SetVersion($DBversion);
5677 }
5678
5679 $DBversion ="3.09.00.030";
5680 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5681     my $query = "SELECT value FROM systempreferences WHERE variable='opacstylesheet'";
5682     my $remote= $dbh->selectrow_arrayref($query);
5683     $dbh->do("DELETE from systempreferences WHERE variable='opacstylesheet'");
5684     if($remote && $remote->[0]) {
5685         $query="UPDATE systempreferences SET value=? WHERE variable='opaclayoutstylesheet'";
5686         $dbh->do($query,undef,$remote->[0]);
5687         print "NOTE: The URL of your remote opac css file has been moved to preference opaclayoutstylesheet.\n";
5688     }
5689     print "Upgrade to $DBversion done (BZ 8263: Make OPAC stylesheet preferences more consistent)\n";
5690     SetVersion($DBversion);
5691 }
5692
5693 $DBversion = "3.09.00.031";
5694 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5695     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonReviews'");
5696     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonSimilarItems'");
5697     $dbh->do("DELETE FROM systempreferences WHERE variable='AWSAccessKeyID'");
5698     $dbh->do("DELETE FROM systempreferences WHERE variable='AWSPrivateKey'");
5699     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonReviews'");
5700     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonSimilarItems'");
5701     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonEnabled'");
5702     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonEnabled'");
5703     print "Upgrade to $DBversion done ('Remove preferences controlling broken Amazon features (Bug 8679')\n";
5704     SetVersion ($DBversion);
5705 }
5706
5707 $DBversion = "3.09.00.032";
5708 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5709     $dbh->do("UPDATE systempreferences SET value = 'call_number' WHERE variable = 'defaultSortField' AND value = 'callnumber'");
5710     $dbh->do("UPDATE systempreferences SET value = 'call_number' WHERE variable = 'OPACdefaultSortField' AND value = 'callnumber'");
5711     print "Upgrade to $DBversion done (Bug 8657 - Default sort by call number does not work. Correcting system preference value.)\n";
5712     SetVersion ($DBversion);
5713 }
5714
5715
5716 $DBversion = '3.09.00.033';
5717 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5718    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacSuppressionByIPRange','','Restrict the suppression to IP adresses outside of the IP range','','free');");
5719    print "Upgrade to $DBversion done (Add OpacSuppressionByIPRange syspref)\n";
5720    SetVersion ($DBversion);
5721 }
5722
5723 $DBversion ="3.09.00.034";
5724 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5725     $dbh->do("UPDATE auth_subfield_structure SET frameworkcode = 'PERSO_NAME' WHERE frameworkcode = 'PERSO_CODE'");
5726     $dbh->do("UPDATE auth_subfield_structure SET frameworkcode = 'CORPO_NAME' WHERE frameworkcode = 'ORGO_CODE'");
5727     print "Upgrade to $DBversion done (Bug 8207: correct typo in authority types)\n";
5728     SetVersion ($DBversion);
5729 }
5730
5731 $DBversion = "3.09.00.035";
5732 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5733     $dbh->do("
5734     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');
5735     ");
5736     $dbh->do(
5737     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SubfieldsToUseWhenPrefill','','Define a list of subfields to use when prefilling items (separated by space)','','Free');
5738     ");
5739     print "Upgrade to $DBversion done (Adding PrefillItem and SubfieldsToUseWhenPrefill sysprefs)\n";
5740     SetVersion ($DBversion);
5741 }
5742
5743 $DBversion = "3.09.00.036";
5744 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5745     # biblioitems changes
5746     $dbh->do("ALTER TABLE biblioitems ADD COLUMN agerestriction VARCHAR(255) DEFAULT NULL AFTER cn_sort");
5747     $dbh->do("ALTER TABLE deletedbiblioitems ADD COLUMN agerestriction VARCHAR(255) DEFAULT NULL AFTER cn_sort");
5748     # preferences changes
5749     $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')");
5750     $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')");
5751
5752     print "Upgrade to $DBversion done (Add colum agerestriction to biblioitems and deletedbiblioitems, add system preferences AgeRestrictionMarker and AgeRestrictionOverride)\n";
5753    SetVersion ($DBversion);
5754 }
5755
5756 $DBversion = "3.09.00.037";
5757 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5758     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('UseTransportCostMatrix',0,'Use Transport Cost Matrix when filling holds','','YesNo')");
5759
5760  $dbh->do("CREATE TABLE `transport_cost` (
5761               `frombranch` varchar(10) NOT NULL,
5762               `tobranch` varchar(10) NOT NULL,
5763               `cost` decimal(6,2) NOT NULL,
5764               `disable_transfer` tinyint(1) NOT NULL DEFAULT 0,
5765               CHECK ( `frombranch` <> `tobranch` ), -- a dud check, mysql does not support that
5766               PRIMARY KEY (`frombranch`, `tobranch`),
5767               CONSTRAINT `transport_cost_ibfk_1` FOREIGN KEY (`frombranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
5768               CONSTRAINT `transport_cost_ibfk_2` FOREIGN KEY (`tobranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
5769           ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
5770
5771     print "Upgrade to $DBversion done (creating `transport_cost` table; adding UseTransportCostMatrix systempref, in circulation)\n";
5772     SetVersion($DBversion);
5773 }
5774
5775 $DBversion ="3.09.00.038";
5776 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5777     $dbh->do("ALTER TABLE borrower_attributes CHANGE  attribute  attribute VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
5778     print "Upgrade to $DBversion done (Increase the maximum size of a borrower attribute value)\n";
5779     SetVersion($DBversion);
5780 }
5781
5782 $DBversion ="3.09.00.039";
5783 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5784     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,type) VALUES('DidYouMeanFromAuthorities','0','Suggest searches based on authority file.','YesNo');");
5785     print "Upgrade to $DBversion done (Add system preference DidYouMeanFromAuthorities)\n";
5786     SetVersion($DBversion);
5787 }
5788
5789 $DBversion = "3.09.00.040";
5790 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5791     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('IncludeSeeFromInSearches','0','','Include see-from references in searches.','YesNo');");
5792     print "Upgrade to $DBversion done (Add IncludeSeeFromInSearches system preference)\n";
5793     SetVersion ($DBversion);
5794 }
5795
5796 $DBversion = "3.09.00.041";
5797 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5798     $dbh->do(qq{
5799         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ExportRemoveFields','','List of fields for non export in circulation.pl (separated by a space)','','');
5800     });
5801     print "Upgrade to $DBversion done (Add system preference ExportRemoveFields)\n";
5802     SetVersion($DBversion);
5803 }
5804
5805 $DBversion = "3.09.00.042";
5806 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5807     $dbh->do(qq{
5808         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ExportWithCsvProfile','','Set a profile name for CSV export','','');
5809     });
5810     print "Upgrade to $DBversion done (Adds New System preference ExportWithCsvProfile)\n";
5811     SetVersion($DBversion)
5812 }
5813
5814 $DBversion = "3.09.00.043";
5815 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5816     $dbh->do("
5817         ALTER TABLE aqorders
5818         ADD parent_ordernumber int(11) DEFAULT NULL
5819     ");
5820     $dbh->do("
5821         UPDATE aqorders
5822         SET parent_ordernumber = ordernumber;
5823     ");
5824     print "Upgrade to $DBversion done (Adding parent_ordernumber in aqorders)\n";
5825     SetVersion($DBversion);
5826 }
5827
5828 $DBversion = '3.09.00.044';
5829 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5830     $dbh->do("ALTER TABLE statistics ADD COLUMN ccode VARCHAR ( 10 ) NULL AFTER associatedborrower");
5831     $dbh->do("UPDATE statistics SET statistics.ccode = ( SELECT items.ccode FROM items WHERE statistics.itemnumber = items.itemnumber )");
5832     $dbh->do("UPDATE statistics SET statistics.ccode = (
5833               SELECT deleteditems.ccode FROM deleteditems
5834                   WHERE statistics.itemnumber = deleteditems.itemnumber
5835               ) WHERE statistics.ccode IS NULL");
5836     print "Upgrade done ( Added Collection Code to Statistics table. )\n";
5837     SetVersion ($DBversion);
5838 }
5839
5840 $DBversion = "3.09.00.045";
5841 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5842     $dbh->do("ALTER TABLE borrower_attribute_types MODIFY category_code VARCHAR( 10 ) NULL DEFAULT NULL");
5843     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.";
5844     SetVersion($DBversion);
5845 }
5846
5847 $DBversion = "3.09.00.046";
5848 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5849     $dbh->do("ALTER TABLE `accountlines` ADD `accountlines_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;");
5850     print "Upgrade to $DBversion done (adding accountlines_id field in accountlines table)\n";
5851     SetVersion($DBversion);
5852 }
5853
5854 $DBversion = "3.09.00.047";
5855 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5856     # to preserve default behaviour as best as possible, set this new preference differently depending on whether IndependantBranches is set or not
5857     my $prefvalue = 'anywhere';
5858     if (C4::Context->preference("IndependantBranches")) { $prefvalue = 'homeorholdingbranch';}
5859     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowReturnToBranch', '$prefvalue', 'Where an item may be returned', 'anywhere|homebranch|holdingbranch|homeorholdingbranch', 'Choice');");
5860
5861     print "Upgrade to $DBversion done: adding AllowReturnToBranch syspref (bug 6151)";
5862     SetVersion($DBversion);
5863 }
5864
5865 $DBversion = "3.09.00.048";
5866 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5867     $dbh->do("ALTER TABLE authorised_values MODIFY lib varchar(200)");
5868     $dbh->do("ALTER TABLE authorised_values MODIFY lib_opac varchar(200)");
5869
5870     print "Upgrade to $DBversion done (Raise the length of Authorised Values descriptions)\n";
5871     SetVersion($DBversion);
5872 }
5873
5874 $DBversion ="3.09.00.049";
5875 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5876     $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');");
5877     $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');");
5878     $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');");
5879     $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');");
5880     print "Upgrade to $DBversion done (Add OPACMobileUserCSS, OpacMainUserBlockMobile, OpacShowLibrariesPulldownMobile and OpacShowFiltersPulldownMobile sysprefs)\n";
5881     SetVersion($DBversion);
5882 }
5883
5884 $DBversion = "3.09.00.050";
5885 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5886     $dbh->do("ALTER TABLE authorised_values MODIFY category varchar(16) NOT NULL DEFAULT '';");
5887     $dbh->do("INSERT INTO authorised_values (category, authorised_value, lib) VALUES
5888               ('REPORT_GROUP', 'CIRC', 'Circulation'),
5889               ('REPORT_GROUP', 'CAT', 'Catalog'),
5890               ('REPORT_GROUP', 'PAT', 'Patrons'),
5891               ('REPORT_GROUP', 'ACQ', 'Acquisitions'),
5892               ('REPORT_GROUP', 'ACC', 'Accounts');");
5893
5894     $dbh->do("ALTER TABLE reports_dictionary ADD report_area varchar(6) DEFAULT NULL;");
5895     $dbh->do("UPDATE reports_dictionary SET report_area = CASE area
5896                   WHEN 1 THEN 'CIRC'
5897                   WHEN 2 THEN 'CAT'
5898                   WHEN 3 THEN 'PAT'
5899                   WHEN 4 THEN 'ACQ'
5900                   WHEN 5 THEN 'ACC'
5901                   END;");
5902     $dbh->do("ALTER TABLE reports_dictionary DROP area;");
5903     $dbh->do("ALTER TABLE reports_dictionary ADD KEY dictionary_area_idx (report_area);");
5904
5905     $dbh->do("ALTER TABLE saved_sql ADD report_area varchar(6) DEFAULT NULL;");
5906     $dbh->do("ALTER TABLE saved_sql ADD report_group varchar(80) DEFAULT NULL;");
5907     $dbh->do("ALTER TABLE saved_sql ADD report_subgroup varchar(80) DEFAULT NULL;");
5908     $dbh->do("ALTER TABLE saved_sql ADD KEY sql_area_group_idx (report_group, report_subgroup);");
5909
5910     print "Upgrade to $DBversion done saved_sql new fields report_group and report_area; authorised_values.category 16 char \n";
5911     SetVersion($DBversion);
5912 }
5913
5914 $DBversion = "3.09.00.051";
5915 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5916     $dbh->do("
5917         CREATE TABLE aqinvoices (
5918           invoiceid int(11) NOT NULL AUTO_INCREMENT,
5919           invoicenumber mediumtext NOT NULL,
5920           booksellerid int(11) NOT NULL,
5921           shipmentdate date default NULL,
5922           billingdate date default NULL,
5923           closedate date default NULL,
5924           shipmentcost decimal(28,6) default NULL,
5925           shipmentcost_budgetid int(11) default NULL,
5926           PRIMARY KEY (invoiceid),
5927           CONSTRAINT aqinvoices_fk_aqbooksellerid FOREIGN KEY (booksellerid) REFERENCES aqbooksellers (id) ON DELETE CASCADE ON UPDATE CASCADE,
5928           CONSTRAINT aqinvoices_fk_shipmentcost_budgetid FOREIGN KEY (shipmentcost_budgetid) REFERENCES aqbudgets (budget_id) ON DELETE SET NULL ON UPDATE CASCADE
5929         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5930     ");
5931
5932     # Fill this new table with existing invoices
5933     my $sth = $dbh->prepare("
5934         SELECT aqorders.booksellerinvoicenumber AS invoicenumber, aqbasket.booksellerid, aqorders.datereceived
5935         FROM aqorders
5936           LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
5937         WHERE aqorders.booksellerinvoicenumber IS NOT NULL
5938           AND aqorders.booksellerinvoicenumber != ''
5939         GROUP BY aqorders.booksellerinvoicenumber
5940     ");
5941     $sth->execute;
5942     my $results = $sth->fetchall_arrayref({});
5943     $sth = $dbh->prepare("
5944         INSERT INTO aqinvoices (invoicenumber, booksellerid, shipmentdate) VALUES (?,?,?)
5945     ");
5946     foreach(@$results) {
5947         $sth->execute($_->{invoicenumber}, $_->{booksellerid}, $_->{datereceived});
5948     }
5949
5950     # Add the column in aqorders, fill it with correct value
5951     # and then drop booksellerinvoicenumber column
5952     $dbh->do("
5953         ALTER TABLE aqorders
5954         ADD COLUMN invoiceid int(11) default NULL AFTER booksellerinvoicenumber,
5955         ADD CONSTRAINT aqorders_ibfk_3 FOREIGN KEY (invoiceid) REFERENCES aqinvoices (invoiceid) ON DELETE SET NULL ON UPDATE CASCADE
5956     ");
5957
5958     $dbh->do("
5959         UPDATE aqorders, aqinvoices
5960         SET aqorders.invoiceid = aqinvoices.invoiceid
5961         WHERE aqorders.booksellerinvoicenumber = aqinvoices.invoicenumber
5962     ");
5963
5964     $dbh->do("
5965         ALTER TABLE aqorders
5966         DROP COLUMN booksellerinvoicenumber
5967     ");
5968
5969     print "Upgrade to $DBversion done (Add aqinvoices table) \n";
5970     SetVersion ($DBversion);
5971 }
5972
5973 $DBversion = "3.09.00.052";
5974 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5975     $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');");
5976     $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');");
5977     $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');");
5978     print "Upgrade to $DBversion done (Add systempreferences to decrease loan length on high demand items decreaseLoanHighHolds, decreaseLoanHighHoldsValue and decreaseLoanHighHoldsDuration) \n";
5979     SetVersion ($DBversion);
5980 }
5981
5982 $DBversion = "3.09.00.053";
5983 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5984     $dbh->do(
5985     q|CREATE TABLE `import_auths` (
5986         import_record_id int(11) NOT NULL,
5987         matched_authid int(11) default NULL,
5988         control_number varchar(25) default NULL,
5989         authorized_heading varchar(128) default NULL,
5990         original_source varchar(25) default NULL,
5991         CONSTRAINT import_auths_ibfk_1 FOREIGN KEY (import_record_id)
5992         REFERENCES import_records (import_record_id) ON DELETE CASCADE ON UPDATE CASCADE,
5993         KEY matched_authid (matched_authid)
5994         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;|
5995     );
5996     $dbh->do("ALTER TABLE import_batches
5997                 CHANGE COLUMN num_biblios num_records int(11) NOT NULL default 0,
5998                 ADD COLUMN record_type enum('biblio', 'auth', 'holdings') NOT NULL default 'biblio'");
5999     $dbh->do("UPDATE import_batches SET record_type='auth' WHERE import_batch_id IN
6000                 (SELECT import_batch_id FROM import_records WHERE record_type='auth')");
6001
6002     print "Upgrade to $DBversion done (Added support for staging authorities)\n";
6003     SetVersion ($DBversion);
6004 }
6005
6006 $DBversion = "3.09.00.054";
6007 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6008     $dbh->do("ALTER TABLE aqorders CHANGE COLUMN gst gstrate DECIMAL(6,4)  DEFAULT NULL");
6009     print "Upgrade to $DBversion done (Change column name in aqorders gst --> gstrate)\n";
6010     SetVersion($DBversion);
6011 }
6012
6013 $DBversion = "3.09.00.055";
6014 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6015     $dbh->do("ALTER TABLE aqorders ADD discount float(6,4) DEFAULT NULL AFTER gstrate");
6016     print "Upgrade to $DBversion done (Add discount field in aqorders table)\n";
6017     SetVersion($DBversion);
6018 }
6019
6020 $DBversion ="3.09.00.056";
6021 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6022     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('AuthDisplayHierarchy','0','Display authority hierarchies','','YesNo')");
6023     print "Upgrade to $DBversion done (Add system preference AuthDisplayHierarchy)\n";
6024     SetVersion($DBversion);
6025 }
6026
6027 $DBversion = "3.09.00.057";
6028 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6029     $dbh->do("ALTER TABLE aqbasket ADD deliveryplace VARCHAR(10) default NULL AFTER basketgroupid;");
6030     $dbh->do("ALTER TABLE aqbasket ADD billingplace VARCHAR(10) default NULL AFTER deliveryplace;");
6031     print "Upgrade to $DBversion done (Bug 5356: Added billingplace, deliveryplace to the aqbasket table)\n";
6032     SetVersion($DBversion);
6033 }
6034
6035 $DBversion ="3.09.00.058";
6036 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6037     $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');");
6038     $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');");
6039     print "Upgrade to $DBversion done (Add Did You Mean? configuration)\n";
6040     SetVersion($DBversion);
6041 }
6042
6043 $DBversion ="3.09.00.059";
6044 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6045     $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');");
6046     print "Upgrade to $DBversion done (Add system preference BlockReturnOfWithdrawnItems)\n";
6047     SetVersion($DBversion);
6048 }
6049
6050 $DBversion = "3.09.00.060";
6051 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6052     $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')");
6053     print "Upgrade to $DBversion done (Added HoldsToPullStartDate syspref)\n";
6054     SetVersion($DBversion);
6055 }
6056
6057 $DBversion = "3.09.00.061";
6058 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6059     $dbh->do("UPDATE systempreferences set value=0 WHERE variable='OPACItemsResultsDisplay' AND value='statuses'");
6060     $dbh->do("UPDATE systempreferences set value=1 WHERE variable='OPACItemsResultsDisplay' AND value='itemdetails'");
6061     $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'");
6062     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";
6063     SetVersion ($DBversion);
6064 }
6065
6066 $DBversion = "3.09.00.062";
6067 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6068    $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='NoZebra'");
6069    $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='QueryRemoveStopwords'");
6070    print "Upgrade to $DBversion done (Disable obsolete NoZebra and QueryRemoveStopwords sysprefs)\n";
6071    SetVersion ($DBversion);
6072 }
6073
6074 $DBversion = "3.09.00.063";
6075 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6076     my $gst_booksellers = $dbh->selectcol_arrayref("SELECT DISTINCT(gstrate) FROM aqbooksellers");
6077     my $gist_syspref = C4::Context->preference("gist");
6078     # remove the undef values and construct and array with the syspref and the supplier values
6079     my @gstrates = map { defined $_ ? $_ : () } @$gst_booksellers;
6080     push @gstrates, split ('\|', $gist_syspref);
6081     # we want to compare integer (or float)
6082     $_ = $_ + 0 for @gstrates;
6083     use List::MoreUtils qw/uniq/;
6084     # remove duplicate values
6085     @gstrates = uniq sort @gstrates;
6086     my $new_syspref_value = join '|', @gstrates;
6087     # update the syspref with the new values
6088     my $sth = $dbh->prepare("UPDATE systempreferences set value=? WHERE variable='gist'");
6089     $sth->execute( $new_syspref_value );
6090
6091     print "Upgrade to $DBversion done (Bug 8832, Set the syspref gist with the existing values)\n";
6092     SetVersion ($DBversion);
6093 }
6094
6095 $DBversion = "3.09.00.064";
6096 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6097    $dbh->do('ALTER TABLE items ADD coded_location_qualifier varchar(10) default NULL AFTER itemcallnumber');
6098    print "Upgrade to $DBversion done (Bug 6428: Added coded_location_qualifier to the items table)\n";
6099    SetVersion ($DBversion);
6100 }
6101
6102 $DBversion = "3.09.00.065";
6103 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6104    $dbh->do('ALTER TABLE deleteditems ADD coded_location_qualifier varchar(10) default NULL AFTER itemcallnumber');
6105    print "Upgrade to $DBversion done (Bug 6428: Added coded_location_qualifier to the deleteditems table)\n";
6106    SetVersion ($DBversion);
6107 }
6108
6109 $DBversion = "3.09.00.066";
6110 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6111    $dbh->do("DELETE FROM systempreferences WHERE variable='DidYouMeanFromAuthorities'");
6112    print "Upgrade to $DBversion done (Bug 9107: remove DidYouMeanFromAuthorities syspref)\n";
6113    SetVersion ($DBversion);
6114 }
6115
6116 $DBversion = "3.09.00.067";
6117 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6118    $dbh->do("ALTER TABLE statistics CHANGE COLUMN ccode ccode varchar(10) NULL");
6119    print "Upgrade to $DBversion done (Bug 9064: statistics.ccode potentially wrongly defined)\n";
6120    SetVersion ($DBversion);
6121 }
6122
6123 $DBversion = "3.10.00.00";
6124 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6125    print "Upgrade to $DBversion done (release tag)\n";
6126    SetVersion ($DBversion);
6127 }
6128
6129 $DBversion = "3.11.00.001";
6130 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6131     $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')");
6132     print "Upgrade to $DBversion done (Bug 2832 - Add alphabet syspref)\n";
6133 }
6134
6135 $DBversion = "3.11.00.002";
6136 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6137     $dbh->do(q{
6138         DELETE from aqorders_items where ordernumber NOT IN (SELECT ordernumber FROM aqorders);
6139     });
6140     $dbh->do(q{
6141         ALTER TABLE aqorders_items
6142         ADD CONSTRAINT aqorders_items_ibfk_1 FOREIGN KEY (ordernumber) REFERENCES aqorders (ordernumber)
6143         ON DELETE CASCADE ON UPDATE CASCADE;
6144     });
6145     print "Upgrade to $DBversion done (Bug 9030: Add constraint on aqorders_items.ordernumber)\n";
6146     SetVersion ($DBversion);
6147 }
6148
6149 $DBversion = "3.11.00.003";
6150 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6151     $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')");
6152     print "Upgrade to $DBversion done (Bug 7189: Add system preference RefundLostItemFeeOnReturn)\n";
6153     SetVersion($DBversion);
6154 }
6155
6156 $DBversion = "3.11.00.004";
6157 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6158     $dbh->do(qq{
6159         ALTER TABLE subscription ADD COLUMN closed INT(1) NOT NULL DEFAULT 0 AFTER enddate;
6160     });
6161
6162     print "Upgrade to $DBversion done (Bug 8782: Add field subscription.closed)\n";
6163     SetVersion($DBversion);
6164 }
6165
6166 $DBversion = "3.11.00.005";
6167 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6168     $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;});
6169
6170     $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;});
6171
6172     $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;});
6173
6174     print "Upgrade to $DBversion done (Bug 7919: Display of values depending on the connexion library)\n";
6175     SetVersion($DBversion);
6176 }
6177
6178 $DBversion = "3.11.00.006";
6179 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6180     $dbh->do(q{
6181         UPDATE virtualshelves SET sortfield="copyrightdate" where sortfield="year";
6182     });
6183     print "Upgrade to $DBversion done (Bug 9167: Update the virtualshelves.sortfield column with 'copyrightdate' if needed)\n";
6184     SetVersion($DBversion);
6185 }
6186
6187 $DBversion = "3.11.00.007";
6188 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6189     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ar', 'language', 'de', 'Arabisch')");
6190     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hy', 'language', 'de', 'Armenisch')");
6191     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'bg', 'language', 'de', 'Bulgarisch')");
6192     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'zh', 'language', 'de', 'Chinesisch')");
6193     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'cs', 'language', 'de', 'Tschechisch')");
6194     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'da', 'language', 'de', 'Dänisch')");
6195     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nl', 'language', 'de', 'Niederländisch')");
6196     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'en', 'language', 'de', 'Englisch')");
6197     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fi', 'language', 'de', 'Finnisch')");
6198     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fr', 'language', 'de', 'Französisch')");
6199     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'lo', 'language', 'fr', 'Laotien')");
6200     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'lo', 'language', 'de', 'Laotisch')");
6201     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'el', 'language', 'de', 'Griechisch (Nach 1453)')");
6202     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'he', 'language', 'de', 'Hebräisch')");
6203     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hi', 'language', 'de', 'Hindi')");
6204     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hu', 'language', 'de', 'Ungarisch')");
6205     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'id', 'language', 'de', 'Indonesisch')");
6206     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'it', 'language', 'de', 'Italienisch')");
6207     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ja', 'language', 'de', 'Japanisch')");
6208     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ko', 'language', 'de', 'Koreanisch')");
6209     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'la', 'language', 'de', 'Latein')");
6210     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'gl', 'language', 'fr', 'Galicien')");
6211     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'gl', 'language', 'de', 'Galizisch')");
6212     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nb', 'language', 'de', 'Norwegisch bokm&#229;l')");
6213     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nn', 'language', 'de', 'Norwegisch nynorsk')");
6214     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fa', 'language', 'de', 'Persisch')");
6215     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'pl', 'language', 'de', 'Polnisch')");
6216     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'pt', 'language', 'de', 'Portugiesisch')");
6217     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ro', 'language', 'de', 'Rumänisch')");
6218     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ru', 'language', 'de', 'Russisch')");
6219     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sr', 'language', 'fr', 'Serbe')");
6220     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sr', 'language', 'de', 'Serbisch')");
6221     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'es', 'language', 'de', 'Spanisch')");
6222     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sv', 'language', 'de', 'Schwedisch')");
6223     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tet', 'language', 'fr', 'Tétoum')");
6224     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tet', 'language', 'de', 'Tetum')");
6225     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'th', 'language', 'de', 'Thailändisch')");
6226     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tr', 'language', 'de', 'Türkisch')");
6227     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'uk', 'language', 'de', 'Ukrainisch')");
6228     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ur', 'language', 'fr', 'Ourdou')");
6229     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ur', 'language', 'de', 'Urdu')");
6230     print "Upgrade to $DBversion done (Bug 9056: add German and a couple of French translations to language_descriptions)\n";
6231     SetVersion ($DBversion);
6232 }
6233
6234 $DBversion = "3.11.00.008";
6235 if (CheckVersion($DBversion)) {
6236     $dbh->do("
6237         CREATE TABLE IF NOT EXISTS `borrower_modifications` (
6238           `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6239           `verification_token` varchar(255) NOT NULL DEFAULT '',
6240           `borrowernumber` int(11) NOT NULL DEFAULT '0',
6241           `cardnumber` varchar(16) DEFAULT NULL,
6242           `surname` mediumtext,
6243           `firstname` text,
6244           `title` mediumtext,
6245           `othernames` mediumtext,
6246           `initials` text,
6247           `streetnumber` varchar(10) DEFAULT NULL,
6248           `streettype` varchar(50) DEFAULT NULL,
6249           `address` mediumtext,
6250           `address2` text,
6251           `city` mediumtext,
6252           `state` text,
6253           `zipcode` varchar(25) DEFAULT NULL,
6254           `country` text,
6255           `email` mediumtext,
6256           `phone` text,
6257           `mobile` varchar(50) DEFAULT NULL,
6258           `fax` mediumtext,
6259           `emailpro` text,
6260           `phonepro` text,
6261           `B_streetnumber` varchar(10) DEFAULT NULL,
6262           `B_streettype` varchar(50) DEFAULT NULL,
6263           `B_address` varchar(100) DEFAULT NULL,
6264           `B_address2` text,
6265           `B_city` mediumtext,
6266           `B_state` text,
6267           `B_zipcode` varchar(25) DEFAULT NULL,
6268           `B_country` text,
6269           `B_email` text,
6270           `B_phone` mediumtext,
6271           `dateofbirth` date DEFAULT NULL,
6272           `branchcode` varchar(10) DEFAULT NULL,
6273           `categorycode` varchar(10) DEFAULT NULL,
6274           `dateenrolled` date DEFAULT NULL,
6275           `dateexpiry` date DEFAULT NULL,
6276           `gonenoaddress` tinyint(1) DEFAULT NULL,
6277           `lost` tinyint(1) DEFAULT NULL,
6278           `debarred` date DEFAULT NULL,
6279           `debarredcomment` varchar(255) DEFAULT NULL,
6280           `contactname` mediumtext,
6281           `contactfirstname` text,
6282           `contacttitle` text,
6283           `guarantorid` int(11) DEFAULT NULL,
6284           `borrowernotes` mediumtext,
6285           `relationship` varchar(100) DEFAULT NULL,
6286           `ethnicity` varchar(50) DEFAULT NULL,
6287           `ethnotes` varchar(255) DEFAULT NULL,
6288           `sex` varchar(1) DEFAULT NULL,
6289           `password` varchar(30) DEFAULT NULL,
6290           `flags` int(11) DEFAULT NULL,
6291           `userid` varchar(75) DEFAULT NULL,
6292           `opacnote` mediumtext,
6293           `contactnote` varchar(255) DEFAULT NULL,
6294           `sort1` varchar(80) DEFAULT NULL,
6295           `sort2` varchar(80) DEFAULT NULL,
6296           `altcontactfirstname` varchar(255) DEFAULT NULL,
6297           `altcontactsurname` varchar(255) DEFAULT NULL,
6298           `altcontactaddress1` varchar(255) DEFAULT NULL,
6299           `altcontactaddress2` varchar(255) DEFAULT NULL,
6300           `altcontactaddress3` varchar(255) DEFAULT NULL,
6301           `altcontactstate` text,
6302           `altcontactzipcode` varchar(50) DEFAULT NULL,
6303           `altcontactcountry` text,
6304           `altcontactphone` varchar(50) DEFAULT NULL,
6305           `smsalertnumber` varchar(50) DEFAULT NULL,
6306           `privacy` int(11) DEFAULT NULL,
6307           PRIMARY KEY (`verification_token`,`borrowernumber`),
6308           KEY `verification_token` (`verification_token`),
6309           KEY `borrowernumber` (`borrowernumber`)
6310         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6311 ");
6312
6313     $dbh->do("
6314         INSERT INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES
6315         ('PatronSelfRegistration', '0', NULL, 'If enabled, patrons will be able to register themselves via the OPAC.', 'YesNo'),
6316         ('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'),
6317         ('PatronSelfRegistrationDefaultCategory', '', '', 'A patron registered via the OPAC will receive a borrower category code set in this system preference.', 'free'),
6318         ('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'),
6319         ('PatronSelfRegistrationBorrowerMandatoryField',  'surname|firstname', NULL ,  'Choose the mandatory fields for a patron''s account, when registering via the OPAC.',  'free'),
6320         ('PatronSelfRegistrationBorrowerUnwantedField',  '', NULL ,  'Name the fields you don''t want to display when registering a new patron via the OPAC.',  'free');
6321     ");
6322
6323     $dbh->do("
6324     INSERT INTO  letter ( `module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content` )
6325     VALUES ( 'members', 'OPAC_REG_VERIFY', '', 'Opac Self-Registration Verification Email', '1', 'Verify Your Account', 'Hello!
6326
6327     Your library account has been created. Please verify your email address by clicking this link to complete the signup process:
6328
6329     http://<<OPACBaseURL>>/cgi-bin/koha/opac-registration-verify.pl?token=<<borrower_modifications.verification_token>>
6330
6331     If you did not initiate this request, you may safely ignore this one-time message. The request will expire shortly.'
6332     )");
6333
6334     print "Upgrade to $DBversion done (Bug 7067: Add Patron Self Registration)\n";
6335     SetVersion ($DBversion);
6336 }
6337
6338 $DBversion = "3.11.00.009";
6339 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6340     $dbh->do("
6341         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
6342         ('SeparateHoldings', '0', 'Separate current branch holdings from other holdings', NULL, 'YesNo'),
6343         ('SeparateHoldingsBranch', 'homebranch', 'Branch used to separate holdings', 'homebranch|holdingbranch', 'Choice'),
6344         ('OpacSeparateHoldings', '0', 'Separate current branch holdings from other holdings (OPAC)', NULL, 'YesNo'),
6345         ('OpacSeparateHoldingsBranch', 'homebranch', 'Branch used to separate holdings (OPAC)', 'homebranch|holdingbranch', 'Choice')
6346     ");
6347
6348     print "Upgrade to $DBversion done (Bug 7674: Add systempreferences SeparateHoldings, SeparateHoldingsBranch, OpacSeparateHoldings and OpacSeparateHoldingsBranch) \n";
6349     SetVersion ($DBversion);
6350 }
6351
6352 $DBversion = "3.11.00.010";
6353 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6354     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('RenewalSendNotice', '0', '', NULL, 'YesNo')");
6355     $dbh->do(q{
6356         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
6357         ('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>>.');
6358     });
6359     print "Upgrade to $DBversion done (Bug 9151 - Renewal notice according to patron alert preferences)\n";
6360     SetVersion($DBversion);
6361 }
6362
6363 $DBversion = "3.11.00.011";
6364 if ( CheckVersion($DBversion) ) {
6365    $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');");
6366    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('HTML5MediaExtensions','webm|ogg|ogv|oga|vtt','Media file extensions','','free');");
6367    print "Upgrade to $DBversion done (Bug 8377: Add HTML5MediaEnabled and HTML5MediaExtensions sysprefs)\n";
6368    SetVersion ($DBversion);
6369 }
6370
6371 $DBversion = "3.11.00.012";
6372 if ( CheckVersion($DBversion) ) {
6373     $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')");
6374     print "Upgrade to $DBversion done (Bug 9206: Only allow place holds in records that the patron don't have in his possession)\n";
6375     SetVersion($DBversion);
6376 }
6377
6378 $DBversion = "3.11.00.013";
6379 if ( CheckVersion($DBversion) ) {
6380     $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')");
6381     print "Upgrade to $DBversion done (Bug 9162 - Add a system preference to set which notes fields appears on title notes/description separator)\n";
6382     SetVersion($DBversion);
6383 }
6384
6385 $DBversion = "3.11.00.014";
6386 if ( CheckVersion($DBversion) ) {
6387    $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' )");
6388    $dbh->do("INSERT INTO systempreferences ( variable, value, explanation, type ) VALUES ( 'SCOUserJS', '', 'Define custom javascript for inclusion in the SCO module', 'free' )");
6389    print "Upgrade to $DBversion done (Bug 9009: Add SCOUserCSS and SCOUserJS sysprefs)\n";
6390 }
6391
6392 $DBversion = "3.11.00.015";
6393 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6394     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('RentalsInNoissuesCharge', '1', 'Rental charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
6395     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('ManInvInNoissuesCharge', '1', 'MANUAL_INV charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
6396     print "Upgrade to $DBversion done (Add sysprefs RentalsInNoissuesCharge and ManInvInNoissuesCharge.)\n";
6397     SetVersion($DBversion);
6398 }
6399
6400 $DBversion = "3.11.00.016";
6401 if ( CheckVersion($DBversion) ) {
6402    $dbh->do(q{
6403         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";
6404         });
6405    $dbh->do(q{
6406         UPDATE userflags SET flagdesc="Edit Authorities" where flagdesc="Allow to edit authorities";
6407         });
6408    $dbh->do(q{
6409         UPDATE userflags SET flagdesc="Allow access to the reports module" where flagdesc="Allow to access to the reports module";
6410         });
6411    $dbh->do(q{
6412         UPDATE userflags SET flagdesc="Set library management parameters (deprecated)" where flagdesc="Set library management parameters";
6413         });
6414    $dbh->do(q{
6415         UPDATE userflags SET flagdesc="Manage serial subscriptions" where flagdesc="Allow to manage serials subscriptions";
6416         });
6417    $dbh->do(q{
6418         UPDATE userflags SET flagdesc="Manage patrons fines and fees" where flagdesc="Update borrower charges";
6419         });
6420    $dbh->do(q{
6421         UPDATE userflags SET flagdesc="Check out and check in items" where flagdesc="Circulate books";
6422         });
6423    $dbh->do(q{
6424         UPDATE userflags SET flagdesc="Manage Koha system settings (Administration panel)" where flagdesc="Set Koha system parameters";
6425         });
6426    $dbh->do(q{
6427         UPDATE userflags SET flagdesc="Add or modify patrons" where flagdesc="Add or modify borrowers";
6428         });
6429    $dbh->do(q{
6430         UPDATE userflags SET flagdesc="Use all tools (expand for granular tools permissions)" where flagdesc="Use tools (export, import, barcodes)";
6431         });
6432    $dbh->do(q{
6433         UPDATE userflags SET flagdesc="Allow staff members to modify permissions for other staff members" where flagdesc="Set user permissions";
6434         });
6435    $dbh->do(q{
6436         UPDATE permissions SET description="Perform batch modification of patrons" where description="Perform batch modifivation of patrons";
6437         });
6438
6439    print "Upgrade to $DBversion done (Bug 9382 (updated with bug 9745) - refresh permission descriptions to make more sense)\n";
6440    SetVersion ($DBversion);
6441 }
6442
6443 $DBversion ="3.11.00.017";
6444 if ( CheckVersion($DBversion) ) {
6445     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksReviews','0','Display book review snippets from IDreamBooks.com','','YesNo');");
6446     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksReadometer','0','Display Readometer from IDreamBooks.com','','YesNo');");
6447     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksResults','0','Display IDreamBooks.com rating in search results','','YesNo');");
6448     print "Upgrade to $DBversion done (Add IDreamBooks enhanced content)\n";
6449     SetVersion($DBversion);
6450 }
6451
6452 $DBversion = "3.11.00.018";
6453 if ( CheckVersion($DBversion) ) {
6454    $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')");
6455    $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')");
6456    print "Upgrade to $DBversion done (Bug 9395: Problem with callnumber and standard number search in OPAC and Staff Client)\n";
6457    SetVersion ($DBversion);
6458 }
6459
6460 $DBversion = "3.11.00.019";
6461 if ( CheckVersion($DBversion) ) {
6462     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('UNIMARCAuthorityField100', 'afrey50      ba0', NULL, NULL, 'Textarea')");
6463     print "Upgrade to $DBversion done (Bug 9145 - Add syspref UNIMARCAuthorityField100)\n";
6464     SetVersion ($DBversion);
6465 }
6466
6467 $DBversion = "3.11.00.020";
6468 if ( CheckVersion($DBversion) ) {
6469     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UNIMARCField100Language', 'fre','UNIMARC field 100 default language',NULL,'short')");
6470     print "Upgrade to $DBversion done (Bug 8347 - Koha forces UNIMARC 100 field code language to 'fre')\n";
6471     SetVersion($DBversion);
6472 }
6473
6474 $DBversion ="3.11.00.021";
6475 if ( CheckVersion($DBversion) ) {
6476     $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');");
6477     print "Upgrade to $DBversion done (Bug 5888 - Subject search pop-up for the OPAC)\n";
6478     SetVersion($DBversion);
6479 }
6480
6481 $DBversion = "3.11.00.022";
6482 if ( CheckVersion($DBversion) ) {
6483     $dbh->do(
6484 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('Persona',0,'Use Mozilla Persona for login','','YesNo')"
6485     );
6486     print "Upgrade to $DBversion done (Bug 9587 - Allow login via Persona)\n";
6487     SetVersion($DBversion);
6488 }
6489
6490 $DBversion = "3.11.00.023";
6491 if ( CheckVersion($DBversion) ) {
6492     $dbh->do("UPDATE z3950servers SET host = 'lx2.loc.gov', port = 210, db = 'LCDB', syntax = 'USMARC', encoding = 'utf8' WHERE name = 'LIBRARY OF CONGRESS'");
6493     print "Upgrade to $DBversion done (Bug 9520 - Update default LOC Z39.50 target)\n";
6494     SetVersion($DBversion);
6495 }
6496
6497 $DBversion = "3.11.00.024";
6498 if ( CheckVersion($DBversion) ) {
6499     $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');");
6500     print "Upgrade to $DBversion done (Bug 5079: Add OpacItemLocation syspref)\n";
6501     SetVersion ($DBversion);
6502 }
6503
6504 $DBversion = "3.11.00.025";
6505 if ( CheckVersion($DBversion) ) {
6506     $dbh->do(
6507         "CREATE TABLE linktracker (
6508   id int(11) NOT NULL AUTO_INCREMENT,
6509   biblionumber int(11) DEFAULT NULL,
6510   itemnumber int(11) DEFAULT NULL,
6511   borrowernumber int(11) DEFAULT NULL,
6512   url text,
6513   timeclicked datetime DEFAULT NULL,
6514   PRIMARY KEY (id),
6515   KEY bibidx (biblionumber),
6516   KEY itemidx (itemnumber),
6517   KEY borridx (borrowernumber),
6518   KEY dateidx (timeclicked)
6519     ) ENGINE=InnoDB DEFAULT CHARSET=utf8;"
6520     );
6521     $dbh->do( "
6522   INSERT INTO systempreferences (variable,value,explanation,options,type)
6523   VALUES('TrackClicks','0','Track links clicked',NULL,'Integer')" );
6524     print
6525 "Upgrade to $DBversion done (Adds feature Bug 8917, the ability to track links clicked)\n";
6526     SetVersion($DBversion);
6527 }
6528
6529 $DBversion = "3.11.00.026";
6530 if ( CheckVersion($DBversion) ) {
6531     $dbh->do(qq{
6532         ALTER TABLE import_records ADD INDEX batch_id_record_type ( import_batch_id, record_type );
6533     });
6534     print "Upgrade to $DBversion done (Bug 9207: Add new index batch_id_record_type to import_records)\n";
6535     SetVersion($DBversion);
6536 }
6537
6538 $DBversion = "3.11.00.027";
6539 if ( CheckVersion($DBversion) ) {
6540     $dbh->do(q{
6541         INSERT INTO permissions ( module_bit, code, description )
6542         VALUES  ( '1', 'overdues_report', 'Execute overdue items report' )
6543     });
6544     # add new permission for users with all report permissions and circulation remaining permission
6545     $dbh->do(q{
6546         INSERT INTO user_permissions (borrowernumber, module_bit, code)
6547         SELECT user_permissions.borrowernumber, 1, 'overdues_report'
6548         FROM user_permissions
6549         LEFT JOIN borrowers USING(borrowernumber)
6550         WHERE borrowers.flags & (1 << 16)
6551         AND user_permissions.code = 'circulate_remaining_permissions'
6552     });
6553     print "Upgrade to $DBversion done ( Add circ permission overdues_report )\n";
6554     SetVersion($DBversion);
6555 }
6556
6557 $DBversion = "3.11.00.028";
6558 if ( CheckVersion($DBversion) ) {
6559     $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'    );");
6560     print "Upgrade to $DBversion done (Bug 9756 - Patron self registration missing the system preference PatronSelfRegistrationAdditionalInstructions)\n";
6561     SetVersion($DBversion);
6562 }
6563
6564 $DBversion = "3.11.00.029";
6565 if (CheckVersion($DBversion)) {
6566     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UseQueryParser', '0', 'If enabled, try to use QueryParser for queries.', NULL, 'YesNo')");
6567     print "Upgrade to $DBversion done (Bug 9239: Make it possible for Koha to use QueryParser)\n";
6568     SetVersion ($DBversion);
6569 }
6570
6571 $DBversion = "3.11.00.030";
6572 if ( CheckVersion($DBversion) ) {
6573     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('FinesIncludeGracePeriod','1','If enabled, fines calculations will include the grace period.',NULL,'YesNo');");
6574     print "Upgrade to $DBversion done (Add system preference FinesIncludeGracePeriod)\n";
6575     SetVersion($DBversion);
6576 }
6577
6578 $DBversion = "3.11.00.100";
6579 if ( CheckVersion($DBversion) ) {
6580     print "Upgrade to $DBversion done (3.12-alpha release)\n";
6581     SetVersion ($DBversion);
6582 }
6583
6584 $DBversion = "3.11.00.101";
6585 if ( CheckVersion($DBversion) ) {
6586    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('UNIMARCAuthorsFacetsSeparator',', ', 'UNIMARC authors facets separator', NULL, 'short')");
6587    print "Upgrade to $DBversion done (Bug 9341: Problem with UNIMARC authors facets)\n";
6588    SetVersion ($DBversion);
6589 }
6590
6591 $DBversion = "3.11.00.102";
6592 if ( CheckVersion($DBversion) ) {
6593     $dbh->do(q{
6594         DELETE FROM systempreferences WHERE variable='NoZebra'
6595     });
6596     $dbh->do(q{
6597         DELETE FROM systempreferences WHERE variable='QueryRemoveStopwords'
6598     });
6599     print "Upgrade to $DBversion done (Remove deprecated NoZebra and QueryRemoveStopwords sysprefs)\n";
6600     SetVersion($DBversion);
6601 }
6602
6603 $DBversion = "3.11.00.103";
6604 if ( CheckVersion($DBversion) ) {
6605     $dbh->do("DELETE FROM systempreferences WHERE variable = 'insecure';");
6606     print "Upgrade to $DBversion done (Bug 9827 - Remove 'insecure' system preference)\n";
6607     SetVersion($DBversion);
6608 }
6609
6610 $DBversion = "3.11.00.104";
6611 if ( CheckVersion($DBversion) ) {
6612     print "Upgrade to $DBversion done (3.12-alpha2 release)\n";
6613     SetVersion ($DBversion);
6614 }
6615
6616 $DBversion = "3.11.00.105";
6617 if ( CheckVersion($DBversion) ) {
6618     if ( C4::Context->preference("marcflavour") eq 'MARC21' ) {
6619         $sth = $dbh->prepare(
6620 "SELECT frameworkcode FROM marc_tag_structure WHERE tagfield = '029'"
6621         );
6622         $sth->execute;
6623         my $frameworkcodes = $sth->fetchall_hashref('frameworkcode');
6624
6625         for my $frameworkcode ( keys %$frameworkcodes ) {
6626             $dbh->do( "
6627     INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian,
6628     libopac, repeatable, mandatory, kohafield, tab, authorised_value, authtypecode,
6629     value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
6630     ('029', 'a', 'OCLC library identifier', 'OCLC library identifier', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6631     ('029', 'b', 'System control number', 'System control number', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6632     ('029', 'c', 'OAI set name', 'OAI set name', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6633     ('029', 't', 'Content type identifier', 'Content type identifier', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL)
6634    " );
6635         }
6636
6637         for my $tag ( '863', '864', '865' ) {
6638             $sth = $dbh->prepare(
6639 "SELECT frameworkcode FROM marc_tag_structure WHERE tagfield = '$tag'"
6640             );
6641             $sth->execute;
6642             my $frameworkcodes = $sth->fetchall_hashref('frameworkcode');
6643
6644             for my $frameworkcode ( keys %$frameworkcodes ) {
6645                 $dbh->do( "
6646      INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian,
6647      libopac, repeatable, mandatory, kohafield, tab, authorised_value, authtypecode,
6648      value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
6649      ('$tag', '6', 'Linkage', 'Linkage', 0, 0, '', 8, '', '', '', NULL, 5, '$frameworkcode', '', '', NULL),
6650      ('$tag', '8', 'Field link and sequence number', 'Field link and sequence number', 0, 0, '', 8, '', '', '', NULL, 5, '$frameworkcode', '', '', NULL),
6651      ('$tag', 'a', 'First level of enumeration', 'First level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6652      ('$tag', 'b', 'Second level of enumeration', 'Second level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6653      ('$tag', 'c', 'Third level of enumeration', 'Third level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6654      ('$tag', 'd', 'Fourth level of enumeration', 'Fourth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6655      ('$tag', 'e', 'Fifth level of enumeration', 'Fifth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6656      ('$tag', 'f', 'Sixth level of enumeration', 'Sixth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6657      ('$tag', 'g', 'Alternative numbering scheme, first level of enumeration', 'Alternative numbering scheme, first level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6658      ('$tag', 'h', 'Alternative numbering scheme, second level of enumeration', 'Alternative numbering scheme, second level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6659      ('$tag', 'i', 'First level of chronology', 'First level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6660      ('$tag', 'j', 'Second level of chronology', 'Second level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6661      ('$tag', 'k', 'Third level of chronology', 'Third level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6662      ('$tag', 'l', 'Fourth level of chronology', 'Fourth level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6663      ('$tag', 'm', 'Alternative numbering scheme, chronology', 'Alternative numbering scheme, chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6664      ('$tag', 'n', 'Converted Gregorian year', 'Converted Gregorian year', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6665      ('$tag', 'o', 'Type of unit', 'Type of unit', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6666      ('$tag', 'p', 'Piece designation', 'Piece designation', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6667      ('$tag', 'q', 'Piece physical condition', 'Piece physical condition', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6668      ('$tag', 's', 'Copyright article-fee code', 'Copyright article-fee code', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6669      ('$tag', 't', 'Copy number', 'Copy number', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6670      ('$tag', 'v', 'Issuing date', 'Issuing date', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6671      ('$tag', 'w', 'Break indicator', 'Break indicator', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6672      ('$tag', 'x', 'Nonpublic note', 'Nonpublic note', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6673      ('$tag', 'z', 'Public note', 'Public note', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL)
6674     " );
6675             }
6676         }
6677     }
6678     print "Upgrade to $DBversion done (Bug 9353: Missing subfields on MARC21 frameworks)\n";
6679     SetVersion($DBversion);
6680 }
6681
6682
6683 $DBversion = "3.11.00.106";
6684 if ( CheckVersion($DBversion) ) {
6685     $dbh->do("INSERT INTO userflags (bit, flag, flagdesc, defaulton) VALUES ('19', 'plugins', 'Koha plugins', '0')");
6686     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
6687               ('19', 'manage', 'Manage plugins ( install / uninstall )'),
6688               ('19', 'tool', 'Use tool plugins'),
6689               ('19', 'report', 'Use report plugins'),
6690               ('19', 'configure', 'Configure plugins')
6691             ");
6692     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UseKohaPlugins','0','Enable or disable the ability to use Koha Plugins.','','YesNo')");
6693
6694     $dbh->do("
6695         CREATE TABLE IF NOT EXISTS plugin_data (
6696             plugin_class varchar(255) NOT NULL,
6697             plugin_key varchar(255) NOT NULL,
6698             plugin_value text,
6699             PRIMARY KEY (plugin_class,plugin_key)
6700         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6701     ");
6702
6703     print "Upgrade to $DBversion done (Bug 7804: Added plugin system.)\n";
6704     SetVersion($DBversion);
6705 }
6706
6707 $DBversion = "3.11.00.107";
6708 if ( CheckVersion($DBversion) ) {
6709    $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('TimeFormat','24hr','12hr|24hr','Defines the global time format for visual output.','Choice')");
6710    print "Upgrade to $DBversion done (Bug 9014: Add syspref TimeFormat)\n";
6711    SetVersion ($DBversion);
6712 }
6713
6714 $DBversion = "3.11.00.108";
6715 if ( CheckVersion($DBversion) ) {
6716     $dbh->do("ALTER TABLE action_logs CHANGE timestamp timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;");
6717     $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');");
6718     $dbh->do("ALTER TABLE action_logs CHANGE timestamp timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;");
6719     print "Upgrade to $DBversion done (Bug 7241: Fix on circulation logs)\n";
6720     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";
6721     SetVersion($DBversion);
6722 }
6723
6724 $DBversion = "3.11.00.109";
6725 if ( CheckVersion($DBversion) ) {
6726    $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');");
6727    print "Upgrade to $DBversion done (Bug 9403: Add DisplayIconsXSLT)\n";
6728    SetVersion ($DBversion);
6729 }
6730
6731 $DBversion = "3.11.00.110";
6732 if ( CheckVersion($DBversion) ) {
6733     $dbh->do("ALTER TABLE pending_offline_operations CHANGE barcode barcode VARCHAR( 20 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
6734     $dbh->do("ALTER TABLE pending_offline_operations ADD amount DECIMAL( 28, 6 ) NULL DEFAULT NULL");
6735     print "Upgrade to $DBversion done (Bug 8220 - Allow koc uploads to go to process queue)\n";
6736     SetVersion ($DBversion);
6737 }
6738
6739 $DBversion = "3.11.00.111";
6740 if ( CheckVersion($DBversion) ) {
6741     my $sth = $dbh->prepare("
6742         SELECT module, code, branchcode, content
6743         FROM letter
6744         WHERE content LIKE '%<fine>%'
6745     ");
6746     $sth->execute;
6747     my $sth_update = $dbh->prepare("UPDATE letter SET content = ? WHERE module = ? AND code = ? AND branchcode = ?");
6748     while(my $row = $sth->fetchrow_hashref){
6749         $row->{content} =~ s/<fine>\w+<\/fine>/<<items.fine>>/;
6750         $sth_update->execute($row->{content}, $row->{module}, $row->{code}, $row->{branchcode});
6751     }
6752     print "Upgrade to $DBversion done (use new <<items.fine>> syntax in notices)\n";
6753     SetVersion($DBversion);
6754 }
6755
6756 $DBversion = "3.11.00.112";
6757 if ( CheckVersion($DBversion) ) {
6758     $dbh->do(qq{
6759         ALTER TABLE issuingrules ADD COLUMN renewalperiod int(4) DEFAULT NULL AFTER renewalsallowed
6760     });
6761     $dbh->do(qq{
6762         UPDATE issuingrules SET renewalperiod = issuelength
6763     });
6764     print "Upgrade to $DBversion done (Bug 8365: Add colum issuingrules.renewalperiod)\n";
6765     SetVersion ($DBversion);
6766 }
6767
6768 $DBversion = "3.11.00.113";
6769 if ( CheckVersion($DBversion) ) {
6770     $dbh->do(q{
6771         ALTER TABLE branchcategories ADD show_in_pulldown BOOLEAN NOT NULL DEFAULT '0',
6772         ADD INDEX ( show_in_pulldown )
6773     });
6774     print "Upgrade to $DBversion done (Bug 9257 - Add groups to normal search pulldown)\n";
6775     SetVersion ($DBversion);
6776 }
6777
6778 $DBversion = "3.11.00.115";
6779 if ( CheckVersion($DBversion) ) {
6780     $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')");
6781     $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')");
6782     print "Upgrade to $DBversion done (Bug 7740: Add syspref HighlightOwnItemsOnOPAC)\n";
6783     SetVersion ($DBversion);
6784 }
6785
6786 $DBversion = "3.11.00.116";
6787 if ( CheckVersion($DBversion) ) {
6788     $dbh->do(q{ALTER TABLE aqorders DROP COLUMN serialid;});
6789     $dbh->do(q{ALTER TABLE aqorders DROP COLUMN subscription;});
6790     $dbh->do(q{ALTER TABLE aqorders ADD COLUMN subscriptionid INT(11) DEFAULT NULL;});
6791     $dbh->do(q{ALTER TABLE aqorders ADD CONSTRAINT aqorders_subscriptionid FOREIGN KEY (subscriptionid) REFERENCES subscription (subscriptionid) ON DELETE CASCADE ON UPDATE CASCADE;});
6792     $dbh->do(q{ALTER TABLE subscription ADD COLUMN reneweddate DATE DEFAULT NULL;});
6793     print "Upgrade to $DBversion done (Bug 5343: table aqorders: DROP serialid and subscription fields and ADD subscriptionid, table subscription: ADD reneweddate)\n";
6794     SetVersion ($DBversion);
6795 }
6796
6797 $DBversion = "3.11.00.200";
6798 if ( CheckVersion($DBversion) ) {
6799     print "Upgrade to $DBversion done (3.12-beta1 release)\n";
6800     SetVersion ($DBversion);
6801 }
6802
6803 $DBversion = "3.11.00.201";
6804 if ( CheckVersion($DBversion) ) {
6805     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'BIBSYS' AND host LIKE 'z3950.bibsys.no'");
6806     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'NORBOK' AND host LIKE 'z3950.nb.no'");
6807     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'SAMBOK' AND host LIKE 'z3950.nb.no'");
6808     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'DEICHMAN' AND host like 'z3950.deich.folkebibl.no'");
6809     print "Upgrade to $DBversion done (Bug 9498 - Update encoding for Norwegian sample Z39.50 servers)\n";
6810     SetVersion($DBversion);
6811 }
6812
6813 $DBversion = "3.11.00.202";
6814 if ( CheckVersion($DBversion) ) {
6815    $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ca', 'language', 'Catalan','2013-01-12' )");
6816    $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'ca','cat')");
6817    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'es', 'Catalán')");
6818    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'en', 'Catalan')");
6819    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'fr', 'Catalan')");
6820    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'ca', 'Català')");
6821    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'de', 'Katalanisch')");
6822    print "Upgrade to $DBversion done (Bug 9381: Add Catalan laguage)\n";
6823    SetVersion ($DBversion);
6824 }
6825
6826 $DBversion = "3.11.00.203";
6827 if ( CheckVersion($DBversion) ) {
6828     $dbh->do(q{ALTER TABLE suggestions CHANGE COLUMN title title VARCHAR(255) DEFAULT NULL;});
6829     print "Upgrade to $DBversion done (Bug 2046 - increasing title column length for suggestions)\n";
6830     SetVersion ($DBversion);
6831 }
6832
6833 $DBversion = "3.11.00.300";
6834 if ( CheckVersion($DBversion) ) {
6835     print "Upgrade to $DBversion done (3.12-beta3 release)\n";
6836     SetVersion ($DBversion);
6837 }
6838
6839 $DBversion = "3.11.00.301";
6840 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6841     #issues
6842     $dbh->do(q{
6843         ALTER TABLE `issues`
6844             ADD KEY `itemnumber_idx` (`itemnumber`),
6845             ADD KEY `branchcode_idx` (`branchcode`),
6846             ADD KEY `issuingbranch_idx` (`issuingbranch`)
6847     });
6848     $dbh->do(q{
6849         ALTER TABLE `old_issues`
6850             ADD KEY `branchcode_idx` (`branchcode`),
6851             ADD KEY `issuingbranch_idx` (`issuingbranch`)
6852     });
6853     #items
6854     $dbh->do(q{
6855         ALTER TABLE `items` ADD KEY `itype_idx` (`itype`)
6856     });
6857     $dbh->do(q{
6858         ALTER TABLE `deleteditems` ADD KEY `itype_idx` (`itype`)
6859     });
6860     # biblioitems
6861     $dbh->do(q{
6862         ALTER TABLE `biblioitems` ADD KEY `itemtype_idx` (`itemtype`)
6863     });
6864     $dbh->do(q{
6865         ALTER TABLE `deletedbiblioitems` ADD KEY `itemtype_idx` (`itemtype`)
6866     });
6867     # statistics
6868     $dbh->do(q{
6869         ALTER TABLE `statistics`
6870             ADD KEY `branch_idx` (`branch`),
6871             ADD KEY `proccode_idx` (`proccode`),
6872             ADD KEY `type_idx` (`type`),
6873             ADD KEY `usercode_idx` (`usercode`),
6874             ADD KEY `itemnumber_idx` (`itemnumber`),
6875             ADD KEY `itemtype_idx` (`itemtype`),
6876             ADD KEY `borrowernumber_idx` (`borrowernumber`),
6877             ADD KEY `associatedborrower_idx` (`associatedborrower`),
6878             ADD KEY `ccode_idx` (`ccode`)
6879     });
6880
6881     print "Upgrade to $DBversion done (Bug 9681: Add some database indexes)\n";
6882     SetVersion($DBversion);
6883 }
6884
6885 $DBversion = "3.12.00.000";
6886 if ( CheckVersion($DBversion) ) {
6887     print "Upgrade to $DBversion done (3.12.0 release)\n";
6888     SetVersion ($DBversion);
6889 }
6890
6891 $DBversion = '3.13.00.000';
6892 if ( CheckVersion($DBversion) ) {
6893     print "Upgrade to $DBversion done (start the journey to Koha Pi)\n";
6894     SetVersion ($DBversion);
6895 }
6896
6897 $DBversion = "3.13.00.001";
6898 if ( CheckVersion($DBversion) ) {
6899     $dbh->do("INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('UseCourseReserves', '0', NULL, 'Enable the course reserves feature.', 'YesNo')");
6900     $dbh->do("INSERT INTO userflags (bit,flag,flagdesc,defaulton) VALUES ('18','coursereserves','Course Reserves','0')");
6901     $dbh->do("
6902 CREATE TABLE `courses` (
6903   `course_id` int(11) NOT NULL AUTO_INCREMENT,
6904   `department` varchar(20) DEFAULT NULL,
6905   `course_number` varchar(255) DEFAULT NULL,
6906   `section` varchar(255) DEFAULT NULL,
6907   `course_name` varchar(255) DEFAULT NULL,
6908   `term` varchar(20) DEFAULT NULL,
6909   `staff_note` mediumtext,
6910   `public_note` mediumtext,
6911   `students_count` varchar(20) DEFAULT NULL,
6912   `enabled` enum('yes','no') NOT NULL DEFAULT 'yes',
6913   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6914    PRIMARY KEY (`course_id`)
6915 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6916     ");
6917
6918     $dbh->do("
6919 CREATE TABLE `course_instructors` (
6920   `course_id` int(11) NOT NULL,
6921   `borrowernumber` int(11) NOT NULL,
6922   PRIMARY KEY (`course_id`,`borrowernumber`),
6923   KEY `borrowernumber` (`borrowernumber`)
6924 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6925     ");
6926
6927     $dbh->do("
6928 ALTER TABLE `course_instructors`
6929   ADD CONSTRAINT `course_instructors_ibfk_2` FOREIGN KEY (`course_id`) REFERENCES `courses` (`course_id`),
6930   ADD CONSTRAINT `course_instructors_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE;
6931     ");
6932
6933     $dbh->do("
6934 CREATE TABLE `course_items` (
6935   `ci_id` int(11) NOT NULL AUTO_INCREMENT,
6936   `itemnumber` int(11) NOT NULL,
6937   `itype` varchar(10) DEFAULT NULL,
6938   `ccode` varchar(10) DEFAULT NULL,
6939   `holdingbranch` varchar(10) DEFAULT NULL,
6940   `location` varchar(80) DEFAULT NULL,
6941   `enabled` enum('yes','no') NOT NULL DEFAULT 'no',
6942   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6943    PRIMARY KEY (`ci_id`),
6944    UNIQUE KEY `itemnumber` (`itemnumber`),
6945    KEY `holdingbranch` (`holdingbranch`)
6946 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6947     ");
6948
6949     $dbh->do("
6950 ALTER TABLE `course_items`
6951   ADD CONSTRAINT `course_items_ibfk_2` FOREIGN KEY (`holdingbranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
6952   ADD CONSTRAINT `course_items_ibfk_1` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE;
6953 ");
6954
6955     $dbh->do("
6956 CREATE TABLE `course_reserves` (
6957   `cr_id` int(11) NOT NULL AUTO_INCREMENT,
6958   `course_id` int(11) NOT NULL,
6959   `ci_id` int(11) NOT NULL,
6960   `staff_note` mediumtext,
6961   `public_note` mediumtext,
6962   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6963    PRIMARY KEY (`cr_id`),
6964    UNIQUE KEY `pseudo_key` (`course_id`,`ci_id`),
6965    KEY `course_id` (`course_id`)
6966 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6967 ");
6968
6969     $dbh->do("
6970 ALTER TABLE `course_reserves`
6971   ADD CONSTRAINT `course_reserves_ibfk_1` FOREIGN KEY (`course_id`) REFERENCES `courses` (`course_id`);
6972     ");
6973
6974     $dbh->do("
6975 INSERT INTO permissions (module_bit, code, description) VALUES
6976   (18, 'manage_courses', 'Add, edit and delete courses'),
6977   (18, 'add_reserves', 'Add course reserves'),
6978   (18, 'delete_reserves', 'Remove course reserves')
6979 ;
6980     ");
6981
6982
6983     print "Upgrade to $DBversion done (Add Course Reserves ( system preference UseCourseReserves ))\n";
6984     SetVersion($DBversion);
6985 }
6986
6987 $DBversion = "3.13.00.002";
6988 if ( CheckVersion($DBversion) ) {
6989    $dbh->do("UPDATE systempreferences SET variable = 'IndependentBranches' WHERE variable = 'IndependantBranches'");
6990    print "Upgrade to $DBversion done (Bug 10080 - Change system pref IndependantBranches to IndependentBranches)\n";
6991    SetVersion ($DBversion);
6992 }
6993
6994 $DBversion = '3.13.00.003';
6995 if ( CheckVersion($DBversion) ) {
6996     $dbh->do("ALTER TABLE serial DROP itemnumber");
6997     print "Upgrade to $DBversion done (Bug 7718 - Remove itemnumber column from serials table)\n";
6998     SetVersion($DBversion);
6999 }
7000
7001 $DBversion = "3.13.00.004";
7002 if(CheckVersion($DBversion)) {
7003     $dbh->do(
7004 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacShowHoldNotes',0,'Show hold notes on OPAC','','YesNo')"
7005     );
7006     print "Upgrade to $DBversion done (Bug 9722: Allow users to add notes when placing a hold in OPAC)\n";
7007     SetVersion($DBversion);
7008 }
7009
7010 $DBversion = "3.13.00.005";
7011 if(CheckVersion($DBversion)) {
7012     my $intra= C4::Context->preference("intranetstylesheet");
7013     #if this pref is not blank or starting with http, https or / [root], then
7014     #add an additional / to the front
7015     if($intra && $intra !~ /^(\/|https?)/) {
7016         $dbh->do("UPDATE systempreferences SET value=? WHERE variable=?",
7017             undef,('/'.$intra,"intranetstylesheet"));
7018         print "WARNING: Your system preference intranetstylesheet has been prefixed with a slash to make it an absolute path.\n";
7019     }
7020     print "Upgrade to $DBversion done (Bug 10052: Make intranetstylesheet and intranetcolorstylesheet behave exactly like their opac counterparts)\n";
7021     SetVersion ($DBversion);
7022 }
7023
7024 $DBversion = "3.13.00.006";
7025 if ( CheckVersion($DBversion) ) {
7026     $dbh->do(q{
7027         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
7028         VALUES ('CalculateFinesOnReturn','1','Switch to control if overdue fines are calculated on return or not', '', 'YesNo')
7029     });
7030     print "Upgrade to $DBversion done (Bug 10120: Fines on item return controlled by a systempreference)\n";
7031     SetVersion($DBversion);
7032 }
7033
7034 $DBversion = "3.13.00.007";
7035 if ( CheckVersion($DBversion) ) {
7036     $dbh->do("UPDATE systempreferences SET variable='OpacHoldNotes' WHERE variable='OpacShowHoldNotes'");
7037     print "Upgrade to $DBversion done (Bug 10343: Rename OpacShowHoldNotes to OpacHoldNotes)\n";
7038     SetVersion($DBversion);
7039 }
7040
7041 $DBversion = "3.13.00.008";
7042 if ( CheckVersion($DBversion) ) {
7043     $dbh->do("
7044 CREATE TABLE IF NOT EXISTS borrower_files (
7045   file_id int(11) NOT NULL AUTO_INCREMENT,
7046   borrowernumber int(11) NOT NULL,
7047   file_name varchar(255) NOT NULL,
7048   file_type varchar(255) NOT NULL,
7049   file_description varchar(255) DEFAULT NULL,
7050   file_content longblob NOT NULL,
7051   date_uploaded timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
7052   PRIMARY KEY (file_id),
7053   KEY borrowernumber (borrowernumber),
7054   CONSTRAINT borrower_files_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
7055 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7056     ");
7057     print "Upgrade to $DBversion done (Bug 10443: make sure borrower_files table exists)\n";
7058     SetVersion($DBversion);
7059 }
7060
7061 $DBversion = "3.13.00.009";
7062 if ( CheckVersion($DBversion) ) {
7063     $dbh->do("ALTER TABLE aqorders DROP COLUMN biblioitemnumber");
7064     print "Upgrade to $DBversion done (Bug 9987 - Drop column aqorders.biblioitemnumber)\n";
7065     SetVersion($DBversion);
7066 }
7067
7068 $DBversion = "3.13.00.010";
7069 if ( CheckVersion($DBversion) ) {
7070     $dbh->do(
7071         q{
7072 INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AcqWarnOnDuplicateInvoice','0','Warn librarians when they try to create a duplicate invoice', '', 'YesNo');
7073 }
7074     );
7075     print
7076 "Upgrade to $DBversion done (Bug 10366 - Add system preference to enabling warning librarian when invoice is duplicated)\n";
7077     SetVersion($DBversion);
7078 }
7079
7080 $DBversion = "3.13.00.011";
7081 if ( CheckVersion($DBversion) ) {
7082     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='ita' WHERE rfc4646_subtag='it'");
7083     print "Upgrade to $DBversion done (Bug 9519: Wrong language code for Italian in the advanced search language limitations)\n";
7084     SetVersion($DBversion);
7085 }
7086
7087 $DBversion = "3.13.00.012";
7088 if ( CheckVersion($DBversion) ) {
7089     $dbh->do("ALTER TABLE issuingrules MODIFY COLUMN overduefinescap decimal(28,6) DEFAULT NULL;");
7090     print "Upgrade to $DBversion done (Bug 10490: Correct datatype for overduefinescap in issuingrules)\n";
7091     SetVersion($DBversion);
7092 }
7093
7094 $DBversion ="3.13.00.013";
7095 if ( CheckVersion($DBversion) ) {
7096     $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');");
7097     print "Upgrade to $DBversion done (Bug 9576: add AllowTooManyOverride syspref to enable or disable issue limit confirmation)\n";
7098     SetVersion($DBversion);
7099 }
7100
7101 $DBversion = "3.13.00.014";
7102 if ( CheckVersion($DBversion) ) {
7103     $dbh->do("ALTER TABLE courses MODIFY COLUMN department varchar(80) DEFAULT NULL;");
7104     $dbh->do("ALTER TABLE courses MODIFY COLUMN term       varchar(80) DEFAULT NULL;");
7105     print "Upgrade to $DBversion done (Bug 10604: correct width of courses.department and courses.term)\n";
7106     SetVersion($DBversion);
7107 }
7108
7109 $DBversion = "3.13.00.015";
7110 if ( CheckVersion($DBversion) ) {
7111     $dbh->do(
7112 "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')"
7113     );
7114     print "Upgrade to $DBversion done (Bug 7494: Add itemBarcodeFallbackSearch syspref)\n";
7115     SetVersion($DBversion);
7116 }
7117
7118 $DBversion = "3.13.00.016";
7119 if ( CheckVersion($DBversion) ) {
7120     $dbh->do(q{
7121         ALTER TABLE items CHANGE wthdrawn withdrawn TINYINT( 1 ) NOT NULL DEFAULT  '0'
7122     });
7123
7124     $dbh->do(q{
7125         ALTER TABLE deleteditems CHANGE wthdrawn withdrawn TINYINT( 1 ) NOT NULL DEFAULT  '0'
7126     });
7127
7128     $dbh->do(q{
7129         UPDATE saved_sql SET savedsql = REPLACE(savedsql, 'wthdrawn', 'withdrawn')
7130     });
7131
7132     $dbh->do(q{
7133         UPDATE marc_subfield_structure SET kohafield = 'items.withdrawn' WHERE kohafield = 'items.wthdrawn'
7134     });
7135
7136     print "Upgrade to $DBversion done (Bug 10550 - Fix database typo wthdrawn)\n";
7137     SetVersion($DBversion);
7138 }
7139
7140 $DBversion = "3.13.00.017";
7141 if ( CheckVersion($DBversion) ) {
7142     $dbh->do(
7143 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveClientKey','','Client key for OverDrive integration','30','Free')"
7144     );
7145     $dbh->do(
7146 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveClientSecret','','Client key for OverDrive integration','30','YesNo')"
7147     );
7148     $dbh->do(
7149 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveLibraryID','','Library ID for OverDrive integration','','Integer')"
7150     );
7151     print "Upgrade to $DBversion done (Bug 10320 - Show results from library's OverDrive collection in OPAC search)\n";
7152     SetVersion($DBversion);
7153 }
7154
7155 $DBversion = "3.13.00.018";
7156 if ( CheckVersion($DBversion) ) {
7157     $dbh->do(qq{DROP TABLE IF EXISTS aqorders_transfers;});
7158     $dbh->do(qq{
7159         CREATE TABLE aqorders_transfers (
7160           ordernumber_from int(11) NULL,
7161           ordernumber_to int(11) NULL,
7162           timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
7163           UNIQUE KEY ordernumber_from (ordernumber_from),
7164           UNIQUE KEY ordernumber_to (ordernumber_to),
7165           CONSTRAINT aqorders_transfers_ordernumber_from FOREIGN KEY (ordernumber_from) REFERENCES aqorders (ordernumber) ON DELETE SET NULL ON UPDATE CASCADE,
7166           CONSTRAINT aqorders_transfers_ordernumber_to FOREIGN KEY (ordernumber_to) REFERENCES aqorders (ordernumber) ON DELETE SET NULL ON UPDATE CASCADE
7167         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7168     });
7169     print "Upgrade to $DBversion done (Bug 5349: Add aqorders_transfers table)\n";
7170     SetVersion($DBversion);
7171 }
7172
7173 $DBversion = "3.13.00.019";
7174 if ( CheckVersion($DBversion) ) {
7175     $dbh->do("ALTER TABLE itemtypes ADD COLUMN checkinmsg VARCHAR(255) AFTER summary;");
7176     $dbh->do("ALTER TABLE itemtypes ADD COLUMN checkinmsgtype CHAR(16) DEFAULT 'message' NOT NULL AFTER checkinmsg;");
7177     print "Upgrade to $DBversion done (Bug 10513 - Light up a warning/message when returning a chosen item type)\n";
7178     SetVersion($DBversion);
7179 }
7180
7181 $DBversion = "3.13.00.020";
7182 if ( CheckVersion($DBversion) ) {
7183     $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')");
7184     $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')");
7185     print "Upgrade to $DBversion done (Bug 7639: system preferences to forgive fines on lost items)\n";
7186     SetVersion($DBversion);
7187 }
7188
7189 $DBversion ="3.13.00.021";
7190 if ( CheckVersion($DBversion) ) {
7191     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ConfirmFutureHolds','0','Number of days for confirming future holds','','Integer');");
7192     print "Upgrade to $DBversion done (Bug 9761: Add ConfirmFutureHolds pref)\n";
7193     SetVersion($DBversion);
7194 }
7195
7196 $DBversion = "3.13.00.022";
7197 if ( CheckVersion($DBversion) ) {
7198     $dbh->do("DELETE from auth_tag_structure WHERE tagfield IN ('68a','68b')");
7199     $dbh->do("DELETE from auth_subfield_structure WHERE tagfield IN ('68a','68b')");
7200     print "Upgrade to $DBversion done (Bug 10687 - Delete erroneous tags 68a and 68b on default MARC21 auth framework)\n";
7201     SetVersion($DBversion);
7202 }
7203
7204 $DBversion = "3.13.00.023";
7205 if ( CheckVersion($DBversion) ) {
7206     $dbh->do("ALTER TABLE borrowers CHANGE password password VARCHAR(60);");
7207     print "Upgrade to $DBversion done (Bug 9611 upgrading password storage system)\n";
7208     SetVersion($DBversion);
7209 }
7210
7211 $DBversion = "3.13.00.024";
7212 if ( CheckVersion($DBversion) ) {
7213     $dbh->do(q{ALTER TABLE z3950servers ADD COLUMN recordtype VARCHAR(45) NOT NULL DEFAULT 'biblio' AFTER description;});
7214     print "Upgrade to $DBversion done (Bug 10096 - Add a Z39.50 interface for authority searching)\n";
7215 }
7216
7217 $DBversion = "3.13.00.025";
7218 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
7219    $dbh->do("ALTER TABLE oai_sets_mappings ADD COLUMN operator varchar(8) NOT NULL default 'equal' AFTER marcsubfield;");
7220    print "Upgrade to $DBversion done (Bug 9295: OAI notequal: add operator column to OAI mappings table)\n";
7221    SetVersion ($DBversion);
7222 }
7223
7224 $DBversion = "3.13.00.026";
7225 if ( CheckVersion($DBversion) ) {
7226     $dbh->do(q|
7227         ALTER TABLE auth_subfield_structure ADD COLUMN defaultvalue TEXT DEFAULT NULL AFTER frameworkcode
7228     |);
7229     print "Upgrade to $DBversion done (Bug 10602: Add the column auth_subfield_structure.defaultvalue)\n";
7230     SetVersion($DBversion);
7231 }
7232
7233 $DBversion = "3.13.00.027";
7234 if ( CheckVersion($DBversion) ) {
7235     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('AllowOfflineCirculation','0','','If on, enables HTML5 offline circulation functionality.','YesNo')");
7236     print "Upgrade to $DBversion done (Bug 10240: Add syspref AllowOfflineCirculation)\n";
7237     SetVersion ($DBversion);
7238 }
7239
7240 $DBversion = "3.13.00.028";
7241 if ( CheckVersion($DBversion) ) {
7242     $dbh->do(q{
7243         ALTER TABLE export_format ADD type VARCHAR(255) DEFAULT 'marc' AFTER encoding
7244     });
7245     $dbh->do(q{
7246         ALTER TABLE export_format CHANGE marcfields content mediumtext NOT NULL
7247     });
7248     print "Upgrade to $DBversion done (Bug 10853: Add new field export_format.type and rename export_format.marcfields with export_format.content)\n";
7249     SetVersion($DBversion);
7250 }
7251
7252 $DBversion = "3.13.00.029";
7253 if ( CheckVersion($DBversion) ) {
7254     $dbh->do(q{
7255         INSERT IGNORE INTO export_format( profile, description, content, csv_separator, type )
7256         VALUES ( "issues to claim", "Default CSV export for serial issue claims",
7257                 "SUPPLIER=aqbooksellers.name|TITLE=subscription.title|ISSUE NUMBER=serial.serialseq|LATE SINCE=serial.planneddate",
7258                 ",", "sql" )
7259     });
7260     print "Upgrade to $DBversion done (Bug 10854: Add the default CSV profile for claiming issues)\n";
7261     SetVersion($DBversion);
7262 }
7263
7264 $DBversion = "3.13.00.030";
7265 if ( CheckVersion($DBversion) ) {
7266     $dbh->do(qq{
7267         DELETE FROM patronimage WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowers.cardnumber = patronimage.cardnumber)
7268     });
7269
7270     $dbh->do(qq{
7271         ALTER TABLE patronimage ADD borrowernumber INT( 11 ) NULL FIRST
7272     });
7273
7274     $dbh->{AutoCommit} = 0;
7275     $dbh->{RaiseError} = 1;
7276
7277     eval {
7278         $dbh->do(qq{
7279             UPDATE patronimage LEFT JOIN borrowers USING ( cardnumber ) SET patronimage.borrowernumber = borrowers.borrowernumber
7280         });
7281         $dbh->commit();
7282     };
7283
7284     if ($@) {
7285         print "Upgrade to $DBversion done (Bug 10636 - patronimage should have borrowernumber as PK, not cardnumber) failed! Transaction aborted because $@\n";
7286         eval { $dbh->rollback };
7287     }
7288     else {
7289         $dbh->do(qq{
7290             ALTER TABLE patronimage DROP FOREIGN KEY patronimage_fk1
7291         });
7292         $dbh->do(qq{
7293             ALTER TABLE patronimage DROP PRIMARY KEY, ADD PRIMARY KEY( borrowernumber )
7294         });
7295         $dbh->do(qq{
7296             ALTER TABLE patronimage DROP cardnumber
7297         });
7298         $dbh->do(qq{
7299             ALTER TABLE patronimage ADD FOREIGN KEY ( borrowernumber ) REFERENCES borrowers ( borrowernumber ) ON DELETE CASCADE ON UPDATE CASCADE
7300         });
7301
7302         print "Upgrade to $DBversion done (Bug 10636 - patronimage should have borrowernumber as PK, not cardnumber)\n";
7303         SetVersion($DBversion);
7304     }
7305
7306     $dbh->{AutoCommit} = 1;
7307     $dbh->{RaiseError} = 0;
7308 }
7309
7310 $DBversion = "3.13.00.031";
7311 if ( CheckVersion($DBversion) ) {
7312
7313     $dbh->do(q{
7314         CREATE TABLE IF NOT EXISTS `patron_lists` (
7315           patron_list_id int(11) NOT NULL AUTO_INCREMENT,
7316           name varchar(255) CHARACTER SET utf8 NOT NULL,
7317           owner int(11) NOT NULL,
7318           PRIMARY KEY (patron_list_id),
7319           KEY owner (owner)
7320         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7321     });
7322
7323     $dbh->do(q{
7324         ALTER TABLE `patron_lists`
7325           ADD CONSTRAINT patron_lists_ibfk_1 FOREIGN KEY (`owner`) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE;
7326     });
7327
7328     $dbh->do(q{
7329         CREATE TABLE patron_list_patrons (
7330           patron_list_patron_id int(11) NOT NULL AUTO_INCREMENT,
7331           patron_list_id int(11) NOT NULL,
7332           borrowernumber int(11) NOT NULL,
7333           PRIMARY KEY (patron_list_patron_id),
7334           KEY patron_list_id (patron_list_id),
7335           KEY borrowernumber (borrowernumber)
7336         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7337     });
7338
7339     $dbh->do(q{
7340         ALTER TABLE `patron_list_patrons`
7341           ADD CONSTRAINT patron_list_patrons_ibfk_1 FOREIGN KEY (patron_list_id) REFERENCES patron_lists (patron_list_id) ON DELETE CASCADE ON UPDATE CASCADE,
7342           ADD CONSTRAINT patron_list_patrons_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE;
7343     });
7344
7345     $dbh->do(q{
7346         INSERT INTO permissions (module_bit, code, description) VALUES
7347         (13, 'manage_patron_lists', 'Add, edit and delete patron lists and their contents')
7348     });
7349
7350     print "Upgrade to $DBversion done (Bug 10565 - Add a 'Patron List' feature for storing and manipulating collections of patrons)\n";
7351     SetVersion($DBversion);
7352 }
7353
7354 $DBversion = "3.13.00.032";
7355 if ( CheckVersion($DBversion) ) {
7356     $dbh->do("ALTER TABLE aqorders ADD COLUMN orderstatus varchar(16) DEFAULT 'new' AFTER parent_ordernumber");
7357     $dbh->do("UPDATE aqorders SET orderstatus='ordered' WHERE basketno IN (SELECT basketno FROM aqbasket WHERE closedate IS NOT NULL)");
7358     $dbh->do(q{
7359         UPDATE aqorders SET orderstatus='partial'
7360         WHERE quantity > quantityreceived
7361         AND quantityreceived > 0
7362         AND ordernumber IN (
7363             SELECT parent_ordernumber
7364             FROM (
7365                 SELECT DISTINCT(parent_ordernumber)
7366                 FROM aqorders
7367                 WHERE ordernumber != parent_ordernumber
7368             ) AS aq
7369         )
7370         AND basketno IN (SELECT basketno FROM aqbasket WHERE closedate IS NOT NULL)
7371     });
7372     $dbh->do("UPDATE aqorders SET orderstatus='complete' WHERE quantity=quantityreceived");
7373     $dbh->do("UPDATE aqorders SET orderstatus='cancelled' WHERE datecancellationprinted IS NOT NULL");
7374     print "Upgrade to $DBversion done (Bug 5336: Add the new column aqorders.orderstatus)\n";
7375     SetVersion($DBversion);
7376 }
7377
7378 $DBversion = "3.13.00.033";
7379 if ( CheckVersion($DBversion) ) {
7380     $dbh->do(qq|
7381         DROP TABLE IF EXISTS subscription_frequencies
7382     |);
7383     $dbh->do(qq|
7384         CREATE TABLE subscription_frequencies (
7385             id INTEGER NOT NULL AUTO_INCREMENT,
7386             description TEXT NOT NULL,
7387             displayorder INT DEFAULT NULL,
7388             unit ENUM('day','week','month','year') DEFAULT NULL,
7389             unitsperissue INTEGER NOT NULL DEFAULT '1',
7390             issuesperunit INTEGER NOT NULL DEFAULT '1',
7391             PRIMARY KEY (id)
7392         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
7393     |);
7394
7395     $dbh->do(qq|
7396         DROP TABLE IF EXISTS subscription_numberpatterns
7397     |);
7398     $dbh->do(qq|
7399         CREATE TABLE subscription_numberpatterns (
7400             id INTEGER NOT NULL AUTO_INCREMENT,
7401             label VARCHAR(255) NOT NULL,
7402             displayorder INTEGER DEFAULT NULL,
7403             description TEXT NOT NULL,
7404             numberingmethod VARCHAR(255) NOT NULL,
7405             label1 VARCHAR(255) DEFAULT NULL,
7406             add1 INTEGER DEFAULT NULL,
7407             every1 INTEGER DEFAULT NULL,
7408             whenmorethan1 INTEGER DEFAULT NULL,
7409             setto1 INTEGER DEFAULT NULL,
7410             numbering1 VARCHAR(255) DEFAULT NULL,
7411             label2 VARCHAR(255) DEFAULT NULL,
7412             add2 INTEGER DEFAULT NULL,
7413             every2 INTEGER DEFAULT NULL,
7414             whenmorethan2 INTEGER DEFAULT NULL,
7415             setto2 INTEGER DEFAULT NULL,
7416             numbering2 VARCHAR(255) DEFAULT NULL,
7417             label3 VARCHAR(255) DEFAULT NULL,
7418             add3 INTEGER DEFAULT NULL,
7419             every3 INTEGER DEFAULT NULL,
7420             whenmorethan3 INTEGER DEFAULT NULL,
7421             setto3 INTEGER DEFAULT NULL,
7422             numbering3 VARCHAR(255) DEFAULT NULL,
7423             PRIMARY KEY (id)
7424         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
7425     |);
7426
7427     $dbh->do(qq|
7428         INSERT INTO subscription_frequencies (description, unit, unitsperissue, issuesperunit, displayorder)
7429         VALUES
7430             ('2/day', 'day', 1, 2, 1),
7431             ('1/day', 'day', 1, 1, 2),
7432             ('3/week', 'week', 1, 3, 3),
7433             ('1/week', 'week', 1, 1, 4),
7434             ('1/2 weeks', 'week', 2, 1, 5),
7435             ('1/3 weeks', 'week', 3, 1, 6),
7436             ('1/month', 'month', 1, 1, 7),
7437             ('1/2 months', 'month', 2, 1, 8),
7438             ('1/3 months', 'month', 3, 1, 9),
7439             ('2/year', 'month', 6, 1, 10),
7440             ('1/year', 'year', 1, 1, 11),
7441             ('1/2 year', 'year', 2, 1, 12),
7442             ('Irregular', NULL, 1, 1, 13)
7443     |);
7444
7445     # Used to link existing subscription to newly created frequencies
7446     my $frequencies_mapping = {     # keys are old frequency numbers, values are the new ones
7447         1 => 2,     # daily (n/week)
7448         2 => 4,     # 1/week
7449         3 => 5,     # 1/2 weeks
7450         4 => 6,     # 1/3 weeks
7451         5 => 7,     # 1/month
7452         6 => 8,     # 1/2 months (6/year)
7453         7 => 9,     # 1/3 months (1/quarter)
7454         8 => 9,    # 1/quarter (seasonal)
7455         9 => 10,    # 2/year
7456         10 => 11,   # 1/year
7457         11 => 12,   # 1/2 years
7458         12 => 1,    # 2/day
7459         16 => 13,   # Without periodicity
7460         32 => 13,   # Irregular
7461         48 => 13    # Unknown
7462     };
7463
7464     $dbh->do(qq|
7465         INSERT INTO subscription_numberpatterns
7466             (label, displayorder, description, numberingmethod,
7467             label1, add1, every1, whenmorethan1, setto1, numbering1,
7468             label2, add2, every2, whenmorethan2, setto2, numbering2,
7469             label3, add3, every3, whenmorethan3, setto3, numbering3)
7470         VALUES
7471             ('Number', 1, 'Simple Numbering method', 'No.{X}',
7472             'Number', 1, 1, 99999, 1, NULL,
7473             NULL, NULL, NULL, NULL, NULL, NULL,
7474             NULL, NULL, NULL, NULL, NULL, NULL),
7475
7476             ('Volume, Number, Issue', 2, 'Volume Number Issue 1', 'Vol.{X}, Number {Y}, Issue {Z}',
7477             'Volume', 1, 48, 99999, 1, NULL,
7478             'Number', 1, 4, 12, 1, NULL,
7479             'Issue', 1, 1, 4, 1, NULL),
7480
7481             ('Volume, Number', 3, 'Volume Number 1', 'Vol {X}, No {Y}',
7482             'Volume', 1, 12, 99999, 1, NULL,
7483             'Number', 1, 1, 12, 1, NULL,
7484             NULL, NULL, NULL, NULL, NULL, NULL),
7485
7486             ('Seasonal', 4, 'Season Year', '{X} {Y}',
7487             'Season', 1, 1, 3, 0, 'season',
7488             'Year', 1, 4, 99999, 1, NULL,
7489             NULL, NULL, NULL, NULL, NULL, NULL)
7490     |);
7491
7492     $dbh->do(qq|
7493         ALTER TABLE subscription
7494         MODIFY COLUMN numberpattern INTEGER DEFAULT NULL,
7495         MODIFY COLUMN periodicity INTEGER DEFAULT NULL
7496     |);
7497
7498     # Update existing subscriptions
7499
7500     my $query = qq|
7501         SELECT subscriptionid, periodicity, numberingmethod,
7502             add1, every1, whenmorethan1, setto1,
7503             add2, every2, whenmorethan2, setto2,
7504             add3, every3, whenmorethan3, setto3
7505         FROM subscription
7506         ORDER BY subscriptionid
7507     |;
7508     my $sth = $dbh->prepare($query);
7509     $sth->execute;
7510     my $insert_numberpatterns_sth = $dbh->prepare(qq|
7511         INSERT INTO subscription_numberpatterns
7512              (label, displayorder, description, numberingmethod,
7513             label1, add1, every1, whenmorethan1, setto1, numbering1,
7514             label2, add2, every2, whenmorethan2, setto2, numbering2,
7515             label3, add3, every3, whenmorethan3, setto3, numbering3)
7516         VALUES
7517             (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
7518     |);
7519     my $check_numberpatterns_sth = $dbh->prepare(qq|
7520         SELECT * FROM subscription_numberpatterns
7521         WHERE (add1 = ? OR (add1 IS NULL AND ? IS NULL)) AND (add2 = ? OR (add2 IS NULL AND ? IS NULL))
7522         AND (add3 = ? OR (add3 IS NULL AND ? IS NULL)) AND (every1 = ? OR (every1 IS NULL AND ? IS NULL))
7523         AND (every2 = ? OR (every2 IS NULL AND ? IS NULL)) AND (every3 = ? OR (every3 IS NULL AND ? IS NULL))
7524         AND (whenmorethan1 = ? OR (whenmorethan1 IS NULL AND ? IS NULL)) AND (whenmorethan2 = ? OR (whenmorethan2 IS NULL AND ? IS NULL))
7525         AND (whenmorethan3 = ? OR (whenmorethan3 IS NULL AND ? IS NULL)) AND (setto1 = ? OR (setto1 IS NULL AND ? IS NULL))
7526         AND (setto2 = ? OR (setto2 IS NULL AND ? IS NULL)) AND (setto3 = ? OR (setto3 IS NULL AND ? IS NULL))
7527         AND (numberingmethod = ? OR (numberingmethod IS NULL AND ? IS NULL))
7528         LIMIT 1
7529     |);
7530     my $update_subscription_sth = $dbh->prepare(qq|
7531         UPDATE subscription
7532         SET numberpattern = ?,
7533             periodicity = ?
7534         WHERE subscriptionid = ?
7535     |);
7536
7537     my $i = 1;
7538     while(my $sub = $sth->fetchrow_hashref) {
7539         $check_numberpatterns_sth->execute(
7540             $sub->{add1}, $sub->{add1}, $sub->{add2}, $sub->{add2}, $sub->{add3}, $sub->{add3},
7541             $sub->{every1}, $sub->{every1}, $sub->{every2}, $sub->{every2}, $sub->{every3}, $sub->{every3},
7542             $sub->{whenmorethan1}, $sub->{whenmorethan1}, $sub->{whenmorethan2}, $sub->{whenmorethan2},
7543             $sub->{whenmorethan3}, $sub->{whenmorethan3}, $sub->{setto1}, $sub->{setto1}, $sub->{setto2},
7544             $sub->{setto2}, $sub->{setto3}, $sub->{setto3}, $sub->{numberingmethod}, $sub->{numberingmethod}
7545         );
7546         my $p = $check_numberpatterns_sth->fetchrow_hashref;
7547         if (defined $p) {
7548             # Pattern already exists, link to it
7549             $update_subscription_sth->execute($p->{id},
7550                 $frequencies_mapping->{$sub->{periodicity}},
7551                 $sub->{subscriptionid});
7552         } else {
7553             # Create a new numbering pattern for this subscription
7554             my $ok = $insert_numberpatterns_sth->execute(
7555                 "Backup pattern $i", 4+$i, "Automatically created pattern by updatedatabase", $sub->{numberingmethod},
7556                 "X", $sub->{add1}, $sub->{every1}, $sub->{whenmorethan1}, $sub->{setto1}, undef,
7557                 "Y", $sub->{add2}, $sub->{every2}, $sub->{whenmorethan2}, $sub->{setto2}, undef,
7558                 "Z", $sub->{add3}, $sub->{every3}, $sub->{whenmorethan3}, $sub->{setto3}, undef
7559             );
7560             if($ok) {
7561                 my $id = $dbh->last_insert_id(undef, undef, 'subscription_numberpatterns', undef);
7562                 # Link to subscription_numberpatterns and subscription_frequencies
7563                 $update_subscription_sth->execute($id,
7564                     $frequencies_mapping->{$sub->{periodicity}},
7565                     $sub->{subscriptionid});
7566             }
7567             $i++;
7568         }
7569     }
7570
7571     # Remove now useless columns
7572     $dbh->do(qq|
7573         ALTER TABLE subscription
7574         DROP COLUMN numberingmethod,
7575         DROP COLUMN add1,
7576         DROP COLUMN every1,
7577         DROP COLUMN whenmorethan1,
7578         DROP COLUMN setto1,
7579         DROP COLUMN add2,
7580         DROP COLUMN every2,
7581         DROP COLUMN whenmorethan2,
7582         DROP COLUMN setto2,
7583         DROP COLUMN add3,
7584         DROP COLUMN every3,
7585         DROP COLUMN whenmorethan3,
7586         DROP COLUMN setto3,
7587         DROP COLUMN dow,
7588         DROP COLUMN issuesatonce,
7589         DROP COLUMN hemisphere,
7590         ADD COLUMN countissuesperunit INTEGER NOT NULL DEFAULT 1 AFTER periodicity,
7591         ADD COLUMN skip_serialseq BOOLEAN NOT NULL DEFAULT 0 AFTER irregularity,
7592         ADD COLUMN locale VARCHAR(80) DEFAULT NULL AFTER numberpattern,
7593         ADD CONSTRAINT subscription_ibfk_1 FOREIGN KEY (periodicity) REFERENCES subscription_frequencies (id) ON DELETE SET NULL ON UPDATE CASCADE,
7594         ADD CONSTRAINT subscription_ibfk_2 FOREIGN KEY (numberpattern) REFERENCES subscription_numberpatterns (id) ON DELETE SET NULL ON UPDATE CASCADE
7595     |);
7596
7597     # Set firstacquidate if not already set (firstacquidate is now mandatory)
7598     my $get_first_planneddate_sth = $dbh->prepare(qq|
7599         SELECT planneddate
7600         FROM serial
7601         WHERE subscriptionid = ?
7602         ORDER BY serialid
7603         LIMIT 1
7604     |);
7605     my $update_firstacquidate_sth = $dbh->prepare(qq|
7606         UPDATE subscription
7607         SET firstacquidate = ?
7608         WHERE subscriptionid = ?
7609     |);
7610     my $get_subscriptions_sth = $dbh->prepare(qq|
7611         SELECT subscriptionid, startdate
7612         FROM subscription
7613         WHERE firstacquidate IS NULL
7614           OR firstacquidate = '0000-00-00'
7615     |);
7616     $get_subscriptions_sth->execute;
7617     while ( my ($subscriptionid, $startdate) = $get_subscriptions_sth->fetchrow ) {
7618         # Try to get the planned date of the first serial
7619         $get_first_planneddate_sth->execute($subscriptionid);
7620         my ($first_planneddate) = $get_first_planneddate_sth->fetchrow;
7621         if ($first_planneddate and $first_planneddate =~ /^\d{4}-\d{2}-\d{2}$/) {
7622             $update_firstacquidate_sth->execute($first_planneddate, $subscriptionid);
7623         } else {
7624             # Defaults to subscription start date
7625             $update_firstacquidate_sth->execute($startdate, $subscriptionid);
7626         }
7627     }
7628
7629     print "Upgrade to $DBversion done (Bug 7688: add subscription_frequencies and subscription_numberpatterns tables)\n";
7630     SetVersion($DBversion);
7631 }
7632
7633 $DBversion = "3.13.00.034";
7634 if ( CheckVersion($DBversion) ) {
7635     $dbh->do("
7636         ALTER TABLE `import_batches`
7637         CHANGE `item_action` `item_action`
7638           ENUM( 'always_add', 'add_only_for_matches', 'add_only_for_new', 'ignore', 'replace' )
7639           NOT NULL DEFAULT 'always_add'
7640     ");
7641     print "Upgrade to $DBversion done (Bug 7131 - way to overlay items in in marc import)\n";
7642     SetVersion($DBversion);
7643 }
7644
7645 $DBversion ="3.13.00.035";
7646 if ( CheckVersion($DBversion) ) {
7647     $dbh->do(q{
7648 CREATE TABLE borrower_debarments (
7649   borrower_debarment_id int(11) NOT NULL AUTO_INCREMENT,
7650   borrowernumber int(11) NOT NULL,
7651   expiration date DEFAULT NULL,
7652   `type` enum('SUSPENSION','OVERDUES','MANUAL') NOT NULL DEFAULT 'MANUAL',
7653   `comment` text,
7654   manager_id int(11) DEFAULT NULL,
7655   created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
7656   updated timestamp NULL DEFAULT NULL,
7657   PRIMARY KEY (borrower_debarment_id),
7658   KEY borrowernumber (borrowernumber) ,
7659   CONSTRAINT `borrower_debarments_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
7660     ON DELETE CASCADE ON UPDATE CASCADE
7661 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7662     });
7663
7664     # debarments with end date
7665     $dbh->do(q{
7666 INSERT INTO borrower_debarments ( borrowernumber, expiration, comment ) SELECT borrowernumber, debarred, debarredcomment FROM borrowers WHERE debarred IS NOT NULL AND debarred <> '9999-12-31'
7667     });
7668     # debarments with no end date
7669     $dbh->do(q{
7670 INSERT INTO borrower_debarments ( borrowernumber, comment ) SELECT borrowernumber, debarredcomment FROM borrowers WHERE debarred = '9999-12-31'
7671     });
7672
7673     $dbh->do(q{
7674 INSERT IGNORE INTO systempreferences (variable,value,explanation,type) VALUES
7675 ('AutoRemoveOverduesRestrictions','0','Defines whether an OVERDUES debarment should be lifted automatically if all overdue items are returned by the patron.','YesNo')
7676     });
7677
7678     print "Upgrade to $DBversion done (Bug 2720 - Overdues which debar automatically should undebar automatically when returned)\n";
7679     SetVersion($DBversion);
7680 }
7681
7682 $DBversion = "3.13.00.036";
7683 if ( CheckVersion($DBversion) ) {
7684     $dbh->do(qq{
7685         INSERT INTO systempreferences (variable, value, explanation, options, type)
7686         VALUES ('StaffDetailItemSelection', '1', 'Enable item selection in record detail page', NULL, 'YesNo')
7687     });
7688     print "Upgrade to $DBversion done (Add system preference StaffDetailItemSelection)\n";
7689     SetVersion($DBversion);
7690 }
7691
7692 $DBversion = "3.13.00.037";
7693 if ( CheckVersion($DBversion) ) {
7694     #add phone if it is not there already (explains the ignore option)
7695     $dbh->do("
7696 INSERT IGNORE INTO message_transport_types (message_transport_type) values ('phone');
7697     ");
7698     print "Upgrade to $DBversion done (Bug 10572: Add phone to message_transport_types table for new installs)\n";
7699     SetVersion($DBversion);
7700 }
7701
7702 $DBversion = "3.13.00.038";
7703 if ( CheckVersion($DBversion) ) {
7704     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES(15, 'superserials', 'Manage subscriptions from any branch (only applies when IndependentBranches is used)')");
7705     print "Upgrade to $DBversion done (Bug 8435: Add superserials permission)\n";
7706     SetVersion($DBversion);
7707 }
7708
7709 $DBversion = "3.13.00.039";
7710 if ( CheckVersion($DBversion) ) {
7711     $dbh->do("
7712         ALTER TABLE aqbasket ADD branch varchar(10) default NULL
7713     ");
7714     $dbh->do("
7715         ALTER TABLE aqbasket
7716         ADD CONSTRAINT aqbasket_ibfk_4 FOREIGN KEY (branch)
7717             REFERENCES branches (branchcode)
7718             ON UPDATE CASCADE ON DELETE SET NULL
7719     ");
7720     $dbh->do("
7721         DROP TABLE IF EXISTS aqbasketusers
7722     ");
7723     $dbh->do("
7724         CREATE TABLE aqbasketusers (
7725             basketno int(11) NOT NULL,
7726             borrowernumber int(11) NOT NULL,
7727             PRIMARY KEY (basketno,borrowernumber),
7728             CONSTRAINT aqbasketusers_ibfk_1 FOREIGN KEY (basketno) REFERENCES aqbasket (basketno) ON DELETE CASCADE ON UPDATE CASCADE,
7729             CONSTRAINT aqbasketusers_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
7730         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7731     ");
7732     $dbh->do("
7733         INSERT INTO permissions (module_bit, code, description)
7734         VALUES (11, 'order_manage_all', 'Manage all orders and baskets, regardless of restrictions on them')
7735     ");
7736
7737     print "Upgrade to $DBversion done (Add branch and users list to baskets. "
7738         . "New permission order_manage_all)\n";
7739     SetVersion($DBversion);
7740 }
7741
7742 $DBversion = "3.13.00.040";
7743 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
7744     $dbh->do("CREATE TABLE IF NOT EXISTS marc_modification_templates (
7745               template_id int(11) NOT NULL auto_increment,
7746               name text NOT NULL,
7747               PRIMARY KEY  (template_id)
7748               ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;"
7749     );
7750
7751     $dbh->do("
7752       CREATE TABLE IF NOT EXISTS marc_modification_template_actions (
7753       mmta_id int(11) NOT NULL auto_increment,
7754       template_id int(11) NOT NULL,
7755       ordering int(3) NOT NULL,
7756       action enum('delete_field','update_field','move_field','copy_field') NOT NULL,
7757       field_number smallint(6) NOT NULL default '0',
7758       from_field varchar(3) NOT NULL,
7759       from_subfield varchar(1) NULL,
7760       field_value varchar(100) default NULL,
7761       to_field varchar(3) default NULL,
7762       to_subfield varchar(1) default NULL,
7763       to_regex_search text,
7764       to_regex_replace text,
7765       to_regex_modifiers varchar(8) default '',
7766       conditional enum('if','unless') default NULL,
7767       conditional_field varchar(3) default NULL,
7768       conditional_subfield varchar(1) default NULL,
7769       conditional_comparison enum('exists','not_exists','equals','not_equals') default NULL,
7770       conditional_value text,
7771       conditional_regex tinyint(1) NOT NULL default '0',
7772       description text,
7773       PRIMARY KEY  (mmta_id),
7774       CONSTRAINT `mmta_ibfk_1` FOREIGN KEY (`template_id`) REFERENCES `marc_modification_templates` (`template_id`) ON DELETE CASCADE ON UPDATE CASCADE
7775       ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7776     ");
7777
7778     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('13', 'marc_modification_templates', 'Manage marc modification templates')");
7779
7780     print "Upgrade to $DBversion done ( Bug 8015: Added tables for MARC Modification Framework )\n";
7781     SetVersion($DBversion);
7782 }
7783
7784 $DBversion = "3.13.00.041";
7785 if(CheckVersion($DBversion)) {
7786     $dbh->do(q{
7787         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');
7788     });
7789     print "Upgrade to $DBversion done (Bug 10986: Added AcqItemSetSubfieldsWhenReceived syspref)\n";
7790     SetVersion($DBversion);
7791 }
7792
7793 $DBversion = "3.13.00.042";
7794 if(CheckVersion($DBversion)) {
7795     print "Upgrade to $DBversion done (Koha 3.14 beta)\n";
7796     SetVersion($DBversion);
7797 }
7798
7799 $DBversion = "3.13.00.043";
7800 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
7801     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('SearchEngine','Zebra','Solr|Zebra','Search Engine','Choice')");
7802     print "Upgrade to $DBversion done (Bug 11196: Add system preference SearchEngine if missing )\n";
7803     SetVersion($DBversion);
7804 }
7805
7806 $DBversion = "3.14.00.000";
7807 if ( CheckVersion($DBversion) ) {
7808     print "Upgrade to $DBversion done (3.14.0 release)\n";
7809     SetVersion ($DBversion);
7810 }
7811
7812 $DBversion = '3.15.00.000';
7813 if ( CheckVersion($DBversion) ) {
7814     print "Upgrade to $DBversion done (the road goes ever on)\n";
7815     SetVersion ($DBversion);
7816 }
7817
7818 $DBversion = "3.15.00.001";
7819 if ( CheckVersion($DBversion) ) {
7820     $dbh->do("UPDATE systempreferences SET value='clear' where variable = 'CircAutoPrintQuickSlip' and value = '0'");
7821     $dbh->do("UPDATE systempreferences SET value='qslip' where variable = 'CircAutoPrintQuickSlip' and value = '1'");
7822     $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'");
7823     print "Upgrade to $DBversion done (Bug 11040: Add option to print full slip when checking out a null barcode)\n";
7824     SetVersion($DBversion);
7825 }
7826
7827 $DBversion = "3.15.00.002";
7828 if(CheckVersion($DBversion)) {
7829     $dbh->do("ALTER TABLE deleteditems MODIFY materials text;");
7830     print "Upgrade to $DBversion done (Bug 11275: alter deleteditems.materials from varchar(10) to text)\n";
7831     SetVersion($DBversion);
7832 }
7833
7834 $DBversion = "3.15.00.003";
7835 if ( CheckVersion($DBversion) ) {
7836     $dbh->do(q{
7837         UPDATE accountlines
7838         SET description = ''
7839         WHERE description IN (
7840             ' New Card',
7841             ' Fine',
7842             ' Sundry',
7843             'Writeoff',
7844             ' Account Management fee',
7845             'Payment,thanks', 'Payment,thanks - ',
7846             ' Lost Item'
7847         )
7848     });
7849     print "Upgrade to $DBversion done (Bug 2546: Update fine descriptions)\n";
7850     SetVersion($DBversion);
7851 }
7852
7853 $DBversion = "3.15.00.004";
7854 if ( CheckVersion($DBversion) ) {
7855     if ( C4::Context->preference("marcflavour") eq 'MARC21' ) {
7856         $dbh->do(qq{
7857             INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian, libopac, repeatable, mandatory,
7858             kohafield, tab, authorised_value, authtypecode, value_builder, isurl, hidden, frameworkcode, seealso, link,
7859             defaultvalue) VALUES
7860             ('015', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7861             ('020', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7862             ('024', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7863             ('027', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7864             ('800', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7865             ('810', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7866             ('811', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7867             ('830', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL);
7868         });
7869         $dbh->do(qq{
7870             INSERT IGNORE INTO auth_subfield_structure (authtypecode, tagfield, tagsubfield, liblibrarian, libopac, repeatable,
7871             mandatory, tab, authorised_value, value_builder, seealso, isurl, hidden, linkid, kohafield, frameworkcode) VALUES
7872             ('', '020', 'q', 'Qualifying information', 'Qualifying information', 1, 0, 0, NULL, NULL, NULL, 0, 0, '', '', ''),
7873             ('', '024', 'q', 'Qualifying information', 'Qualifying information', 1, 0, 0, NULL, NULL, NULL, 0, 0, '', '', '');
7874         });
7875     }
7876     print "Upgrade to $DBversion done (Bug 10970 - Update MARC21 frameworks to Update Nr. 17 - DB update)\n";
7877     SetVersion($DBversion);
7878 }
7879
7880 $DBversion = "3.15.00.005";
7881 if ( CheckVersion($DBversion) ) {
7882    $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('AcquisitionDetails', '1', '', 'Hide/Show acquisition details on the biblio detail page.', 'YesNo');");
7883    print "Upgrade to $DBversion done (Bug 8230: Add AcquisitionDetails system preference)\n";
7884    SetVersion ($DBversion);
7885 }
7886
7887 $DBversion = "3.15.00.006";
7888 if(CheckVersion($DBversion)) {
7889     $dbh->do(q{
7890         ALTER TABLE `borrowers`
7891         ADD KEY `surname_idx` (`surname`(255)),
7892         ADD KEY `firstname_idx` (`firstname`(255)),
7893         ADD KEY `othernames_idx` (`othernames`(255))
7894     });
7895     print "Upgrade to $DBversion done (Bug 11249 - Add DB indexes on borrower names)\n";
7896     SetVersion($DBversion);
7897 }
7898
7899 $DBversion = "3.15.00.007";
7900 if ( CheckVersion($DBversion) ) {
7901    $dbh->do("ALTER TABLE items ADD itemlost_on DATETIME NULL AFTER itemlost");
7902    $dbh->do("ALTER TABLE items ADD withdrawn_on DATETIME NULL AFTER withdrawn");
7903    $dbh->do("ALTER TABLE deleteditems ADD itemlost_on DATETIME NULL AFTER itemlost");
7904    $dbh->do("ALTER TABLE deleteditems ADD withdrawn_on DATETIME NULL AFTER withdrawn");
7905    print "Upgrade to $DBversion done (Bug 9673 - Track when items are marked as lost or withdrawn)\n";
7906    SetVersion ($DBversion);
7907 }
7908
7909 $DBversion = "3.15.00.008";
7910 if ( CheckVersion($DBversion) ) {
7911     $dbh->do(q{
7912         ALTER TABLE collections_tracking CHANGE ctId collections_tracking_id integer(11) NOT NULL auto_increment;
7913     });
7914     print "Upgrade to $DBversion done (Bug 11384) - change name of collections_tracker.ctId column)\n";
7915    SetVersion ($DBversion);
7916 }
7917
7918 $DBversion = "3.15.00.009";
7919 if ( CheckVersion($DBversion) ) {
7920     $dbh->do(q{
7921         ALTER TABLE suggestions MODIFY suggesteddate DATE NOT NULL
7922     });
7923     print "Upgrade to $DBversion done (Bug 11391) - drop default value on suggestions.suggesteddate column)\n";
7924    SetVersion ($DBversion);
7925 }
7926
7927 $DBversion = "3.15.00.010";
7928 if(CheckVersion($DBversion)) {
7929     $dbh->do("ALTER TABLE deleteditems DROP COLUMN marc");
7930     print "Upgrade to $DBversion done (Bug 6331: remove obsolete column in deleteditems.marc)\n";
7931     SetVersion ($DBversion);
7932 }
7933
7934 $DBversion = "3.15.00.011";
7935 if(CheckVersion($DBversion)) {
7936     $dbh->do("UPDATE marc_subfield_structure SET maxlength=9999 WHERE maxlength IS NULL OR maxlength=0;");
7937     print "Upgrade to $DBversion done (Bug 8018: set 9999 as default max length for subfields)\n";
7938     SetVersion ($DBversion);
7939 }
7940
7941 $DBversion = "3.15.00.012";
7942 if ( CheckVersion($DBversion) ) {
7943     $dbh->do(q{
7944         INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'force_checkout', 'Force checkout if a limitation exists')
7945     });
7946     $dbh->do(q{
7947         INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'manage_restrictions', 'Manage restrictions for accounts')
7948     });
7949     $dbh->do(q{
7950         INSERT INTO user_permissions (borrowernumber, module_bit, code)
7951             SELECT user_permissions.borrowernumber, 1, 'force_checkout'
7952             FROM user_permissions
7953             LEFT JOIN borrowers USING(borrowernumber)
7954             WHERE borrowers.flags & (1 << 1)
7955     });
7956     $dbh->do(q{
7957         INSERT INTO user_permissions (borrowernumber, module_bit, code)
7958             SELECT user_permissions.borrowernumber, 1, 'manage_restrictions'
7959             FROM user_permissions
7960             LEFT JOIN borrowers USING(borrowernumber)
7961             WHERE borrowers.flags & (1 << 1)
7962     });
7963
7964     print "Upgrade to $DBversion done (Bug 10863 - Add permissions force_checkout and manage_restrictions)\n";
7965     SetVersion($DBversion);
7966 }
7967
7968 $DBversion = "3.15.00.013";
7969 if(CheckVersion($DBversion)) {
7970     $dbh->do(q{
7971         UPDATE systempreferences
7972         SET explanation = 'Upon receiving items, update their subfields if they were created when placing an order (e.g. o=5|a="foo bar")'
7973         WHERE variable = "AcqItemSetSubfieldsWhenReceived"
7974     });
7975
7976     $dbh->do(q{
7977         UPDATE systempreferences
7978         SET value = ''
7979         WHERE variable = "AcqItemSetSubfieldsWhenReceived"
7980             AND value = "0"
7981     });
7982     print "Upgrade to $DBversion done (Bug 11237: Update explanation and default value for AcqItemSetSubfieldsWhenReceived syspref)\n";
7983     SetVersion($DBversion);
7984 }
7985
7986 $DBversion = "3.15.00.014";
7987 if (CheckVersion($DBversion)) {
7988     $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');");
7989     print "Upgrade to $DBversion done (Bug 11415: add system preference for automatic self checkout receipt printing)\n";
7990     SetVersion($DBversion);
7991 }
7992
7993 $DBversion = "3.15.00.015";
7994 if (CheckVersion($DBversion)) {
7995     $dbh->do("INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
7996         ('OpacSuggestionManagedBy',1,'','Show the name of the staff member who managed a suggestion in OPAC','YesNo');");
7997     print "Upgrade to $DBversion done (Bug 10907: Add OpacSuggestionManagedBy system preference)\n";
7998     SetVersion($DBversion);
7999 }
8000
8001 $DBversion = "3.15.00.016";
8002 if (CheckVersion($DBversion)) {
8003     $dbh->do("ALTER TABLE biblioitems CHANGE url url TEXT NULL DEFAULT NULL");
8004     $dbh->do("ALTER TABLE deletedbiblioitems CHANGE url url TEXT NULL DEFAULT NULL");
8005     print "Upgrade to $DBversion done (Bug 11268 - Biblioitems URL field is too small for some URLs)\n";
8006     SetVersion($DBversion);
8007 }
8008
8009 $DBversion = "3.15.00.017";
8010 if(CheckVersion($DBversion)) {
8011     $dbh->do(q{
8012         UPDATE systempreferences
8013         SET explanation = 'Define the contents of UNIMARC authority control field 100 position 08-35'
8014         WHERE variable = "UNIMARCAuthorityField100"
8015     });
8016     $dbh->do(q{
8017         UPDATE systempreferences
8018         SET explanation = 'Define the contents of MARC21 authority control field 008 position 06-39'
8019         WHERE variable = "MARCAuthorityControlField008"
8020     });
8021     $dbh->do(q{
8022         UPDATE systempreferences
8023         SET explanation = 'Define MARC Organization Code for MARC21 records - http://www.loc.gov/marc/organizations/orgshome.html'
8024         WHERE variable = "MARCOrgCode"
8025     });
8026     print "Upgrade to $DBversion done (Bug 11611 - fix possible confusion between UNIMARC and MARC21 in some sysprefs)\n";
8027     SetVersion($DBversion);
8028 }
8029
8030 $DBversion = "3.15.00.018";
8031 if ( CheckVersion($DBversion) ) {
8032     $dbh->{AutoCommit} = 0;
8033     $dbh->{RaiseError} = 1;
8034
8035     eval {
8036         $dbh->selectcol_arrayref(q|SELECT COUNT(*) FROM roadtype|);
8037     };
8038     unless ( $@ ) {
8039         my $av_added = $dbh->do(q|
8040             INSERT INTO authorised_values(category, authorised_value, lib, lib_opac)
8041                 SELECT 'ROADTYPE', roadtypeid, road_type, road_type
8042                 FROM roadtype;
8043         |);
8044
8045         my $rt_deleted = $dbh->do(q|
8046             DELETE FROM roadtype
8047         |);
8048
8049         if ( $av_added == $rt_deleted or $rt_deleted eq "0E0" ) {
8050             $dbh->do(q|
8051                 DROP TABLE roadtype;
8052             |);
8053             $dbh->commit;
8054             print "Upgrade to $DBversion done (Bug 7372: Move road types from the roadtype table to the ROADTYPE authorised values)\n";
8055             SetVersion($DBversion);
8056         } else {
8057             print "Upgrade to $DBversion failed (Bug 7372: Move road types from the roadtype table to the ROADTYPE authorised values.\nTransaction aborted because $@\n)";
8058             $dbh->rollback;
8059         }
8060     }
8061     $dbh->{AutoCommit} = 1;
8062     $dbh->{RaiseError} = 0;
8063 }
8064
8065 $DBversion = "3.15.00.019";
8066 if ( CheckVersion($DBversion) ) {
8067     $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')");
8068     print "Upgrade to $DBversion done (Bug 11256: Add system preference OpacMaxItemsToDisplay)\n";
8069     SetVersion($DBversion);
8070 }
8071
8072 $DBversion = "3.15.00.020";
8073 if ( CheckVersion($DBversion) ) {
8074     $dbh->do(q|
8075         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')
8076     |);
8077     print "Upgrade to $DBversion done (Bug 11343: Add system preference MaxItemsForBatch )\n";
8078     SetVersion($DBversion);
8079 }
8080
8081 $DBversion = "3.15.00.021";
8082 if(CheckVersion($DBversion)) {
8083     $dbh->do(q{
8084         ALTER TABLE `action_logs`
8085             DROP KEY timestamp,
8086             ADD KEY `timestamp_idx` (`timestamp`),
8087             ADD KEY `user_idx` (`user`),
8088             ADD KEY `module_idx` (`module`(255)),
8089             ADD KEY `action_idx` (`action`(255)),
8090             ADD KEY `object_idx` (`object`),
8091             ADD KEY `info_idx` (`info`(255))
8092     });
8093     print "Upgrade to $DBversion done (Bug 3445: Add indexes to action_logs table)\n";
8094     SetVersion($DBversion);
8095 }
8096
8097 $DBversion = "3.15.00.022";
8098 if (CheckVersion($DBversion)) {
8099     $dbh->do(q|
8100         DELETE FROM systempreferences WHERE variable= "memberofinstitution"
8101     |);
8102     print "Upgrade to $DBversion done (Bug 11751: Remove memberofinstitytion system preference)\n";
8103     SetVersion($DBversion);
8104 }
8105
8106 $DBversion = "3.15.00.023";
8107 if ( CheckVersion($DBversion) ) {
8108    $dbh->do("
8109        INSERT INTO systempreferences (variable,value,options,explanation,type)
8110        VALUES('CardnumberLength', '', '', 'Set a length for card numbers.', 'Free');
8111     ");
8112    print "Upgrade to $DBversion done (Bug 10861: Add CardnumberLength syspref)\n";
8113    SetVersion ($DBversion);
8114 }
8115
8116 $DBversion = "3.15.00.024";
8117 if ( CheckVersion($DBversion) ) {
8118     $dbh->do(q{
8119         DELETE FROM systempreferences WHERE variable = 'NoZebraIndexes'
8120     });
8121     print "Upgrade to $DBversion done (Bug 10012 - remove last vestiges of NoZebra)\n";
8122     SetVersion($DBversion);
8123 }
8124
8125 $DBversion = "3.15.00.025";
8126 if ( CheckVersion($DBversion) ) {
8127     $dbh->do(q{
8128         DROP TABLE aqorderdelivery;
8129     });
8130     print "Upgrade to $DBversion done (Bug 11928 - remove unused table)\n";
8131     SetVersion($DBversion);
8132 }
8133
8134 $DBversion = "3.15.00.026";
8135 if ( CheckVersion($DBversion) ) {
8136     $dbh->do(q{
8137         UPDATE language_descriptions SET description = 'Հայերեն' WHERE subtag = 'hy' AND lang = 'hy';
8138     });
8139     print "Upgrade to $DBversion done (Bug 11973 - Fix Armenian language description)\n";
8140     SetVersion($DBversion);
8141 }
8142
8143 $DBversion = "3.15.00.027";
8144 if (CheckVersion($DBversion)) {
8145     $dbh->do(q{
8146         ALTER TABLE opac_news ADD branchcode varchar(10) DEFAULT NULL
8147                                   AFTER idnew,
8148                               ADD CONSTRAINT opac_news_branchcode_ibfk
8149                                   FOREIGN KEY (branchcode)
8150                                   REFERENCES branches (branchcode)
8151                                   ON DELETE CASCADE ON UPDATE CASCADE;
8152     });
8153     print "Upgrade to $DBversion done (Bug 7567: Add branchcode to opac_news)\n";
8154     SetVersion($DBversion);
8155 }
8156
8157 $DBversion = "3.15.00.028";
8158 if(CheckVersion($DBversion)) {
8159     $dbh->do(q{
8160         ALTER TABLE issuingrules ADD norenewalbefore int(4) default NULL AFTER renewalperiod
8161     });
8162     print "Upgrade to $DBversion done (Bug 7413: Allow OPAC renewal x days before due date)\n";
8163     SetVersion($DBversion);
8164 }
8165
8166 $DBversion = "3.15.00.029";
8167 if ( CheckVersion($DBversion) ) {
8168     $dbh->do(q{
8169         UPDATE borrower_debarments SET expiration = NULL WHERE expiration = '9999-12-31'
8170     });
8171     print "Upgrade to $DBversion done (Bug 11846 - correct borrower_debarments with expiration 9999-12-31)\n";
8172     SetVersion($DBversion);
8173 }
8174
8175 $DBversion = "3.15.00.030";
8176 if(CheckVersion($DBversion)) {
8177     $dbh->do(q|
8178         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')
8179     |);
8180     print "Upgrade to $DBversion done (Bug 12052: Add OPACMySummaryNote syspref)\n";
8181     SetVersion($DBversion);
8182 }
8183
8184 $DBversion = "3.15.00.031";
8185 if ( CheckVersion($DBversion) ) {
8186    $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('10', 'writeoff', 'Write off fines and fees')");
8187    $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('10', 'remaining_permissions', 'Remaining permissions for managing fines and fees')");
8188    print "Upgrade to $DBversion done (Bug 9448 - Add separate permission for writing off fees)\n";
8189    SetVersion ($DBversion);
8190 }
8191
8192 $DBversion = "3.15.00.032";
8193 if ( CheckVersion($DBversion) ) {
8194     $dbh->do("ALTER TABLE aqorders CHANGE notes order_internalnote MEDIUMTEXT;");
8195     $dbh->do("ALTER TABLE aqorders ADD COLUMN order_vendornote MEDIUMTEXT AFTER order_internalnote;");
8196     print "Upgrade to $DBversion done (Bug 9416 - In each order, add a new note made for the vendor)\n";
8197    SetVersion ($DBversion);
8198 }
8199
8200 $DBversion = "3.15.00.033";
8201 if ( CheckVersion($DBversion) ) {
8202     $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')");
8203     print "Upgrade to $DBversion done (Bug 10951: Add NoLoginInstructions pref)\n";
8204     SetVersion($DBversion);
8205 }
8206
8207 $DBversion = "3.15.00.034";
8208 if ( CheckVersion($DBversion) ) {
8209     $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')");
8210     print "Upgrade to $DBversion done (Bug 10986: system preferences to limit languages in advanced search )\n";
8211     SetVersion ($DBversion);
8212 }
8213
8214 $DBversion = "3.15.00.035";
8215 if ( CheckVersion($DBversion) ) {
8216     #insert a notice for sharing a list and accepting a share
8217     $dbh->do("
8218 INSERT INTO letter (module, code, branchcode, name, is_html, title, content)
8219 VALUES ( 'members', 'SHARE_INVITE', '', 'Invitation for sharing a list', '0', 'Share list <<listname>>', 'Dear patron,
8220
8221 One of our patrons, <<borrowers.firstname>> <<borrowers.surname>>, invites you to share a list <<listname>> in our library catalog.
8222
8223 To access this shared list, please click on the following URL or copy-and-paste it into your browser address bar.
8224
8225 <<shareurl>>
8226
8227 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.
8228
8229 Thank you.
8230
8231 Your library.'
8232     )");
8233     $dbh->do("
8234 INSERT INTO letter (module, code, branchcode, name, is_html, title, content)
8235 VALUES ( 'members', 'SHARE_ACCEPT', '', 'Notification about an accepted share', '0', 'Share on list <<listname>> accepted', 'Dear patron,
8236
8237 We want to inform you that <<borrowers.firstname>> <<borrowers.surname>> accepted your invitation to share your list <<listname>> in our library catalog.
8238
8239 Thank you.
8240
8241 Your library.'
8242     )");
8243     print "Upgrade to $DBversion done (Bug 9032: Share a list)\n";
8244     SetVersion($DBversion);
8245 }
8246
8247 $DBversion = "3.15.00.036";
8248 if ( CheckVersion($DBversion) ) {
8249     $dbh->do(q{
8250         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
8251         VALUES('AllowMultipleIssuesOnABiblio',1,'Allow/Don\'t allow patrons to check out multiple items from one biblio','','YesNo')
8252     });
8253
8254     print "Upgrade to $DBversion done (Bug 10859 - Add system preference AllowMultipleIssuesOnABiblio)\n";
8255     SetVersion($DBversion);
8256 }
8257
8258 $DBversion = "3.15.00.037";
8259 if(CheckVersion($DBversion)) {
8260     $dbh->do(q{
8261         ALTER TABLE itemtypes ADD sip_media_type VARCHAR( 3 ) DEFAULT NULL AFTER checkinmsgtype
8262     });
8263     $dbh->do(q{
8264         INSERT INTO authorised_values (category, authorised_value, lib) VALUES
8265          ('SIP_MEDIA_TYPE', '000', 'Other'),
8266          ('SIP_MEDIA_TYPE', '001', 'Book'),
8267          ('SIP_MEDIA_TYPE', '002', 'Magazine'),
8268          ('SIP_MEDIA_TYPE', '003', 'Bound journal'),
8269          ('SIP_MEDIA_TYPE', '004', 'Audio tape'),
8270          ('SIP_MEDIA_TYPE', '005', 'Video tape'),
8271          ('SIP_MEDIA_TYPE', '006', 'CD/CDROM'),
8272          ('SIP_MEDIA_TYPE', '007', 'Diskette'),
8273          ('SIP_MEDIA_TYPE', '008', 'Book with diskette'),
8274          ('SIP_MEDIA_TYPE', '009', 'Book with CD'),
8275          ('SIP_MEDIA_TYPE', '010', 'Book with audio tape')
8276     });
8277     print "Upgrade to $DBversion done (Bug 11351 - Add support for SIP2 media type)\n";
8278     SetVersion($DBversion);
8279 }
8280
8281 $DBversion = '3.15.00.038';
8282 if ( CheckVersion($DBversion) ) {
8283     $dbh->do(q{
8284         INSERT INTO  systempreferences (
8285             variable,
8286             value,
8287             options,
8288             explanation,
8289             type
8290             )
8291         VALUES (
8292             'DisplayLibraryFacets',  'holding',  'home|holding|both',  'Defines which library facets to display.',  'Choice'
8293         );
8294     });
8295     print "Upgrade to $DBversion done (Bug 11334 - Add facet for home library)\n";
8296     SetVersion ($DBversion);
8297 }
8298
8299 $DBversion = "3.15.00.039";
8300 if ( CheckVersion($DBversion) ) {
8301
8302     $dbh->do( q{
8303         ALTER TABLE letter ADD COLUMN message_transport_type VARCHAR(20) NOT NULL DEFAULT 'email' AFTER content
8304     } );
8305
8306     $dbh->do( q{
8307         ALTER TABLE letter ADD CONSTRAINT message_transport_type_fk FOREIGN KEY (message_transport_type) REFERENCES message_transport_types(message_transport_type);
8308     } );
8309
8310     $dbh->do( q{
8311         ALTER TABLE letter DROP PRIMARY KEY, ADD PRIMARY KEY (`module`,`code`,`branchcode`, message_transport_type);
8312     } );
8313
8314     $dbh->do( q{
8315         CREATE TABLE overduerules_transport_types(
8316             id INT(11) NOT NULL AUTO_INCREMENT,
8317             branchcode varchar(10) NOT NULL DEFAULT '',
8318             categorycode VARCHAR(10) NOT NULL DEFAULT '',
8319             letternumber INT(1) NOT NULL DEFAULT 1,
8320             message_transport_type VARCHAR(20) NOT NULL DEFAULT 'email',
8321             PRIMARY KEY (id),
8322             CONSTRAINT overduerules_fk FOREIGN KEY (branchcode, categorycode) REFERENCES overduerules (branchcode, categorycode) ON DELETE CASCADE ON UPDATE CASCADE,
8323             CONSTRAINT mtt_fk FOREIGN KEY (message_transport_type) REFERENCES message_transport_types (message_transport_type) ON DELETE CASCADE ON UPDATE CASCADE
8324         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
8325     } );
8326
8327     my $sth = $dbh->prepare( q{
8328         SELECT * FROM overduerules;
8329     } );
8330
8331     $sth->execute;
8332     my $sth_insert_mtt = $dbh->prepare( q{
8333         INSERT INTO overduerules_transport_types (branchcode, categorycode, letternumber, message_transport_type) VALUES ( ?, ?, ?, ? )
8334     } );
8335     while ( my $row = $sth->fetchrow_hashref ) {
8336         my $branchcode = $row->{branchcode};
8337         my $categorycode = $row->{categorycode};
8338         for my $letternumber ( 1 .. 3 ) {
8339             next unless $row->{"letter$letternumber"};
8340             $sth_insert_mtt->execute(
8341                 $branchcode, $categorycode, $letternumber, 'email'
8342             );
8343         }
8344     }
8345
8346     print "Upgrade done (Bug 9016: Adds multi transport types management for notices)\n";
8347     SetVersion($DBversion);
8348 }
8349
8350 $DBversion = "3.15.00.040";
8351 if ( CheckVersion($DBversion) ) {
8352     $dbh->do(q|
8353         UPDATE message_transports SET letter_code='HOLD' WHERE letter_code='HOLD_PHONE' OR letter_code='HOLD_PRINT'
8354     |);
8355     $dbh->do(q|
8356         UPDATE letter SET code='HOLD', message_transport_type='print' WHERE code='HOLD_PRINT'
8357     |);
8358     $dbh->do(q|
8359         UPDATE letter SET code='HOLD', message_transport_type='phone' WHERE code='HOLD_PHONE'
8360     |);
8361     print "Upgrade to $DBversion done (Bug 10845: Multi transport types for holds)\n";
8362     SetVersion($DBversion);
8363 }
8364
8365 $DBversion = "3.15.00.041";
8366 if ( CheckVersion($DBversion) ) {
8367     my ( $name ) = $dbh->selectrow_array(q|
8368         SELECT name FROM letter WHERE code="HOLD"
8369     |);
8370     $dbh->do(q|
8371         UPDATE letter
8372         SET code="HOLD",
8373             message_transport_type="phone",
8374             name= ?
8375         WHERE code="HOLD_PHONE"
8376     |, {}, $name);
8377
8378     ( $name ) = $dbh->selectrow_array(q|
8379         SELECT name FROM letter WHERE code="PREDUE"
8380     |);
8381     $dbh->do(q|
8382         UPDATE letter
8383         SET code="PREDUE",
8384             message_transport_type="phone",
8385             name= ?
8386         WHERE code="PREDUE_PHONE"
8387     |, {}, $name);
8388
8389     ( $name ) = $dbh->selectrow_array(q|
8390         SELECT name FROM letter WHERE code="OVERDUE"
8391     |);
8392     $dbh->do(q|
8393         UPDATE letter
8394         SET code="OVERDUE",
8395             message_transport_type="phone",
8396             name= ?
8397         WHERE code="OVERDUE_PHONE"
8398     |, {}, $name);
8399
8400     print "Upgrade to $DBversion done (Bug 11867: Update letters *_PHONE)\n";
8401     SetVersion($DBversion);
8402 }
8403
8404 $DBversion = "3.15.00.042";
8405 if ( CheckVersion($DBversion) ) {
8406     $dbh->do(q{
8407         INSERT INTO systempreferences
8408             (variable,value,explanation,options,type)
8409         VALUES
8410             ('SpecifyReturnDate',0,'Define whether to display \"Specify Return Date\" form in Circulation','','YesNo')
8411     });
8412     print "Upgrade to $DBversion done (Bug 10694 - Allow arbitrary backdating of returns)\n";
8413     SetVersion($DBversion);
8414 }
8415
8416 $DBversion = "3.15.00.043";
8417 if ( CheckVersion($DBversion) ) {
8418     $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')");
8419    print "Upgrade to $DBversion done (Bug 7180: Added MarcFieldsToOrder syspref)\n";
8420    SetVersion ($DBversion);
8421 }
8422
8423 $DBversion = "3.15.00.044";
8424 if ( CheckVersion($DBversion) ) {
8425     $dbh->do("ALTER TABLE currency ADD isocode VARCHAR(5) default NULL AFTER symbol;");
8426     print "Upgrade to $DBversion done (Added isocode to the currency table)\n";
8427     SetVersion($DBversion);
8428 }
8429
8430 $DBversion = "3.15.00.045";
8431 if ( CheckVersion($DBversion) ) {
8432     $dbh->do("
8433         INSERT INTO systempreferences (variable,value,explanation,options,type)
8434         VALUES (
8435             'BlockExpiredPatronOpacActions',
8436             '0',
8437             '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',
8438             NULL,
8439             'YesNo'
8440         )
8441     ");
8442     $dbh->do("ALTER TABLE `categories` ADD COLUMN `BlockExpiredPatronOpacActions` TINYINT(1) DEFAULT -1 NOT NULL AFTER category_type");
8443     print "Upgraded to $DBversion done (Bug 6739 - expired patrons not blocked from opac actions)\n";
8444     SetVersion ($DBversion);
8445 }
8446
8447 $DBversion = "3.15.00.046";
8448 if ( CheckVersion($DBversion) ) {
8449     $dbh->do(q|
8450         ALTER TABLE search_history ADD COLUMN type VARCHAR(16) NOT NULL DEFAULT 'biblio' AFTER query_cgi
8451     |);
8452     print "Upgrade to $DBversion done (Bug 10807 - Add db field search_history.type)\n";
8453     SetVersion($DBversion);
8454 }
8455
8456 $DBversion = "3.15.00.047";
8457 if ( CheckVersion($DBversion) ) {
8458     $dbh->do(q|
8459         INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('EnableSearchHistory','0','','Enable or disable search history','YesNo')
8460     |);
8461     print "Upgrade to $DBversion done (Bug 10862: Add EnableSearchHistory syspref)\n";
8462     SetVersion($DBversion);
8463 }
8464
8465 $DBversion = "3.15.00.048";
8466 if ( CheckVersion($DBversion) ) {
8467     $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')");
8468     $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')");
8469     print "Upgrade to $DBversion done (Bug 10195: Records hidden with OpacSuppression can still be accessed)\n";
8470     SetVersion($DBversion);
8471 }
8472
8473 $DBversion = "3.15.00.049";
8474 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
8475     $dbh->do("ALTER TABLE biblioitems DROP INDEX isbn");
8476     $dbh->do("ALTER TABLE biblioitems DROP INDEX issn");
8477     $dbh->do("ALTER TABLE biblioitems DROP INDEX issn_idx");
8478     $dbh->do("ALTER TABLE biblioitems
8479               CHANGE isbn isbn MEDIUMTEXT NULL DEFAULT NULL,
8480               CHANGE issn issn MEDIUMTEXT NULL DEFAULT NULL
8481     ");
8482     $dbh->do("ALTER TABLE biblioitems
8483               ADD INDEX isbn ( isbn ( 255 ) ),
8484               ADD INDEX issn ( issn ( 255 ) )
8485     ");
8486
8487     $dbh->do("ALTER TABLE deletedbiblioitems DROP INDEX isbn");
8488     $dbh->do("ALTER TABLE deletedbiblioitems
8489               CHANGE isbn isbn MEDIUMTEXT NULL DEFAULT NULL,
8490               CHANGE issn issn MEDIUMTEXT NULL DEFAULT NULL
8491     ");
8492     $dbh->do("ALTER TABLE deletedbiblioitems
8493               ADD INDEX isbn ( isbn ( 255 ) )
8494     ");
8495
8496     print "Upgrade to $DBversion done (Bug 5377 - Biblioitems isbn and issn fields too small for multiple ISBN and ISSN)\n";
8497     SetVersion($DBversion);
8498 }
8499
8500 $DBversion = "3.15.00.050";
8501 if ( CheckVersion($DBversion) ) {
8502     $dbh->do("
8503         INSERT INTO systempreferences (
8504             variable,
8505             value,
8506             explanation,
8507             type
8508         ) VALUES (
8509             'AggressiveMatchOnISBN',
8510             '0',
8511             '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',
8512             'YesNo'
8513         )
8514     ");
8515
8516     print "Upgrade to $DBversion done (Bug 10500 - Improve isbn matching when importing records)\n";
8517     SetVersion($DBversion);
8518 }
8519
8520 $DBversion = "3.15.00.051";
8521 if ( CheckVersion($DBversion) ) {
8522     print "Upgrade to $DBversion done (Koha 3.16 beta)\n";
8523     SetVersion($DBversion);
8524 }
8525
8526 $DBversion = "3.15.00.052";
8527 if ( CheckVersion($DBversion) ) {
8528     print "Upgrade to $DBversion done (Koha 3.16 RC)\n";
8529     SetVersion($DBversion);
8530 }
8531
8532 $DBversion = "3.16.00.000";
8533 if ( CheckVersion($DBversion) ) {
8534     print "Upgrade to $DBversion done (3.16.0 release)\n";
8535     SetVersion ($DBversion);
8536 }
8537
8538 $DBversion = '3.17.00.000';
8539 if ( CheckVersion($DBversion) ) {
8540     print "Upgrade to $DBversion done (there is no time to rest on our laurels)\n";
8541     SetVersion ($DBversion);
8542 }
8543
8544 $DBversion = '3.17.00.001';
8545 if ( CheckVersion($DBversion) ) {
8546    $dbh->do("UPDATE systempreferences SET variable = 'AuthoritySeparator' WHERE variable = 'authoritysep'");
8547    print "Upgrade to $DBversion done (Bug 10330 - Rename system preference authoritysep to AuthoritySeparator)\n";
8548    SetVersion ($DBversion);
8549 }
8550
8551 $DBversion = "3.17.00.002";
8552 if (CheckVersion($DBversion)) {
8553     $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')");
8554     $dbh->do("
8555 CREATE TABLE IF NOT EXISTS `misc_files` (
8556   `file_id` int(11) NOT NULL AUTO_INCREMENT,
8557   `table_tag` varchar(255) NOT NULL,
8558   `record_id` int(11) NOT NULL,
8559   `file_name` varchar(255) NOT NULL,
8560   `file_type` varchar(255) NOT NULL,
8561   `file_description` varchar(255) DEFAULT NULL,
8562   `file_content` longblob NOT NULL, -- file content
8563   `date_uploaded` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
8564   PRIMARY KEY (`file_id`),
8565   KEY `table_tag` (`table_tag`),
8566   KEY `record_id` (`record_id`)
8567 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
8568     ");
8569     print "Upgrade to $DBversion done (Bug 3050 - Add an option to upload scanned invoices)\n";
8570     SetVersion($DBversion);
8571 }
8572
8573 $DBversion = "3.17.00.003";
8574 if (CheckVersion($DBversion)) {
8575     $dbh->do("UPDATE systempreferences SET type = 'Choice', options = '0|1|force' WHERE variable = 'OPACItemHolds'");
8576     print "Upgrade to $DBversion done (Bug 7825 - Changed OPACItemHolds syspref to Choice)\n";
8577     SetVersion($DBversion);
8578 }
8579
8580 $DBversion = "3.17.00.004";
8581 if (CheckVersion($DBversion)) {
8582     $dbh->do("ALTER TABLE categories ADD default_privacy ENUM( 'default', 'never', 'forever' ) NOT NULL DEFAULT 'default' AFTER category_type");
8583     print "Upgrade to $DBversion done (Bug 6254 - can't set patron privacy by default)\n";
8584     SetVersion($DBversion);
8585 }
8586
8587 $DBversion = "3.17.00.005";
8588 if (CheckVersion($DBversion)) {
8589     $dbh->do(q|
8590         ALTER TABLE issuingrules
8591         ADD maxsuspensiondays INT(11) DEFAULT NULL AFTER finedays;
8592     |);
8593     print "Upgrade to $DBversion done (Bug 12230: Add new issuing rule maxsuspensiondays)\n";
8594     SetVersion($DBversion);
8595 }
8596
8597 $DBversion = "3.17.00.006";
8598 if ( CheckVersion($DBversion) ) {
8599     $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')");
8600     $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')");
8601     print "Upgrade to $DBversion done (Bug 7720 - Ambiguity in OPAC Details location.)\n";
8602     SetVersion($DBversion);
8603 }
8604
8605 $DBversion = "3.17.00.007";
8606 if (CheckVersion($DBversion)) {
8607     $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');");
8608     print "Upgrade to $DBversion done (Bug 11629 - Add ability to update not for loan status on checkin)\n";
8609     SetVersion($DBversion);
8610 }
8611
8612 $DBversion = "3.17.00.008";
8613 if ( CheckVersion($DBversion) ) {
8614     $dbh->do(q|
8615         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('OPACAcquisitionDetails','0', '','Show the acquisition details at the OPAC','YesNo')
8616     |);
8617     print "Upgrade to $DBversion done (Bug 11169 - Add OPACAcquisitionDetails syspref)\n";
8618     SetVersion($DBversion);
8619 }
8620
8621 $DBversion = "3.17.00.009";
8622 if ( CheckVersion($DBversion) ) {
8623     $dbh->do(q{
8624         DELETE FROM systempreferences WHERE variable = 'UseTablesortForCirc'
8625     });
8626
8627     print "Upgrade to $DBversion done (Bug 11703 - Remove UseTablesortForCirc syspref)\n";
8628     SetVersion($DBversion);
8629 }
8630
8631 $DBversion = "3.17.00.010";
8632 if ( CheckVersion($DBversion) ) {
8633     $dbh->do("DELETE FROM systempreferences WHERE variable='opacsmallimage'");
8634     print "Upgrade to $DBversion done (Bug 11347 - PROG/CCSR deprecation: Remove opacsmallimage system preference)\n";
8635     SetVersion($DBversion);
8636 }
8637
8638 $DBversion = "3.17.00.011";
8639 if ( CheckVersion($DBversion) ) {
8640     $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'hr', 'language', 'Croatian','2014-07-24' )");
8641     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'hr','hrv')");
8642     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'hr', 'Hrvatski')");
8643     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'en', 'Croatian')");
8644     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'fr', 'Croate')");
8645     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'de', 'Kroatisch')");
8646     print "Upgrade to $DBversion done (Bug 12649: Add Croatian language)\n";
8647     SetVersion ($DBversion);
8648 }
8649
8650 $DBversion = "3.17.00.012";
8651 if ( CheckVersion($DBversion) ) {
8652     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacShowFiltersPulldownMobile'");
8653     print "Upgrade to $DBversion done ( Bug 12512 - PROG/CCSR deprecation: Remove OpacShowFiltersPulldownMobile system preference )\n";
8654     SetVersion ($DBversion);
8655 }
8656
8657 $DBversion = "3.17.00.013";
8658 if ( CheckVersion($DBversion) ) {
8659     $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')");
8660     print "Upgrade to $DBversion done (Re-add system preference maxreserves)\n";
8661     SetVersion ($DBversion);
8662 }
8663
8664 $DBversion = '3.17.00.014';
8665 if ( CheckVersion($DBversion) ) {
8666     $dbh->do("
8667         INSERT INTO systempreferences (variable,value,explanation,type) VALUES
8668         ('OverdueNoticeCalendar',0,'Take calendar into consideration when working out sending overdue notices','YesNo')
8669     ");
8670     print "Upgrade to $DBversion done (Bug 12529 - Adding a syspref to allow the overdue notices to consider the calendar when generating notices)\n";
8671     SetVersion($DBversion);
8672 }
8673
8674 $DBversion = "3.17.00.015";
8675 if ( CheckVersion($DBversion) ) {
8676     $dbh->do(q{
8677         CREATE TABLE IF NOT EXISTS columns_settings (
8678             module varchar(255) NOT NULL,
8679             page varchar(255) NOT NULL,
8680             tablename varchar(255) NOT NULL,
8681             columnname varchar(255) NOT NULL,
8682             cannot_be_toggled int(1) NOT NULL DEFAULT 0,
8683             is_hidden int(1) NOT NULL DEFAULT 0,
8684             PRIMARY KEY(module, page, tablename, columnname)
8685         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
8686     });
8687     print "Upgrade to $DBversion done (Bug 10212 - Create new table columns_settings)\n";
8688     SetVersion ($DBversion);
8689 }
8690
8691 $DBversion = "3.17.00.016";
8692 if ( CheckVersion($DBversion) ) {
8693     $dbh->do("CREATE TABLE aqcontacts (
8694         id int(11) NOT NULL auto_increment,
8695         name varchar(100) default NULL,
8696         position varchar(100) default NULL,
8697         phone varchar(100) default NULL,
8698         altphone varchar(100) default NULL,
8699         fax varchar(100) default NULL,
8700         email varchar(100) default NULL,
8701         notes mediumtext,
8702         claimacquisition BOOLEAN NOT NULL DEFAULT 0,
8703         claimissues BOOLEAN NOT NULL DEFAULT 0,
8704         acqprimary BOOLEAN NOT NULL DEFAULT 0,
8705         serialsprimary BOOLEAN NOT NULL DEFAULT 0,
8706         booksellerid int(11) not NULL,
8707         PRIMARY KEY  (id),
8708         CONSTRAINT booksellerid_aqcontacts_fk FOREIGN KEY (booksellerid)
8709             REFERENCES aqbooksellers (id) ON DELETE CASCADE ON UPDATE CASCADE
8710         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;");
8711     $dbh->do("INSERT INTO aqcontacts (name, position, phone, altphone, fax,
8712             email, notes, booksellerid, claimacquisition, claimissues, acqprimary, serialsprimary)
8713         SELECT contact, contpos, contphone, contaltphone, contfax, contemail,
8714             contnotes, id, 1, 1, 1, 1 FROM aqbooksellers;");
8715     $dbh->do("ALTER TABLE aqbooksellers DROP COLUMN contact,
8716         DROP COLUMN contpos, DROP COLUMN contphone,
8717         DROP COLUMN contaltphone, DROP COLUMN contfax,
8718         DROP COLUMN contemail, DROP COLUMN contnotes;");
8719     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contact>>', '<<aqcontacts.name>>')");
8720     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contpos>>', '<<aqcontacts.position>>')");
8721     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contphone>>', '<<aqcontacts.phone>>')");
8722     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contaltphone>>', '<<aqcontacts.altphone>>')");
8723     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contfax>>', '<<aqcontacts.contfax>>')");
8724     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contemail>>', '<<aqcontacts.contemail>>')");
8725     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contnotes>>', '<<aqcontacts.contnotes>>')");
8726     print "Upgrade to $DBversion done (Bug 10402: Move bookseller contacts to separate table)\n";
8727     SetVersion($DBversion);
8728 }
8729
8730 $DBversion = "3.17.00.017";
8731 if ( CheckVersion($DBversion) ) {
8732     # Correct invalid recordtypes (should be very exceptional)
8733     $dbh->do(q{
8734         UPDATE z3950servers set recordtype='biblio' WHERE recordtype NOT IN ('authority','biblio')
8735     });
8736     # Correct invalid server types (should also be very exceptional)
8737     $dbh->do(q{
8738         UPDATE z3950servers set type='zed' WHERE type <> 'zed'
8739     });
8740     # Adjust table
8741     $dbh->do(q{
8742         ALTER TABLE z3950servers
8743         DROP COLUMN icon,
8744         DROP COLUMN description,
8745         DROP COLUMN position,
8746         MODIFY COLUMN id int NOT NULL AUTO_INCREMENT FIRST,
8747         MODIFY COLUMN recordtype enum('authority','biblio') NOT NULL DEFAULT 'biblio',
8748         CHANGE COLUMN name servername mediumtext NOT NULL,
8749         CHANGE COLUMN type servertype enum('zed','sru') NOT NULL DEFAULT 'zed',
8750         ADD COLUMN sru_options varchar(255) default NULL,
8751         ADD COLUMN sru_fields mediumtext default NULL,
8752         ADD COLUMN add_xslt mediumtext default NULL
8753     });
8754     print "Upgrade to $DBversion done (Bug 6536: Z3950 improvements)\n";
8755     SetVersion ($DBversion);
8756 }
8757
8758 $DBversion = "3.17.00.018";
8759 if ( CheckVersion($DBversion) ) {
8760     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('HoldsInNoissuesCharge', '0', 'Hold charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
8761     print "Upgrade to $DBversion done (Bug 12205: Add HoldsInNoissuesCharge systempreference)\n";
8762     SetVersion($DBversion);
8763 }
8764
8765 $DBversion = "3.17.00.019";
8766 if ( CheckVersion($DBversion) ) {
8767     $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')"
8768     );
8769     print "Upgrade to $DBversion done (Bug 6149: Operator highlighted in search results)\n";
8770     SetVersion($DBversion);
8771 }
8772
8773 $DBversion = "3.17.00.020";
8774 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
8775     $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')");
8776     print "Upgrade to $DBversion done (Bug 8735 - Expire holds waiting only on days the library is open)\n";
8777     SetVersion ($DBversion);
8778 }
8779
8780 $DBversion = "3.17.00.021";
8781 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
8782     my $pref = C4::Context->preference('HomeOrHoldingBranch');
8783     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
8784        VALUES ('StaffSearchResultsDisplayBranch', ?,'homebranch|holdingbranch','Controls the display of the home or holding branch for staff search results','choice')", undef, $pref);
8785     print "Upgrade to $DBversion done (Bug 12582 - Control of branch displayed in search results linked to HomeOrHoldingBranch)\n";
8786     SetVersion ($DBversion);
8787 }
8788
8789 $DBversion = '3.17.00.022';
8790 if ( CheckVersion($DBversion) ) {
8791     my @temp= $dbh->selectrow_array(qq|
8792         SELECT count(*)
8793         FROM marc_subfield_structure
8794         WHERE kohafield='permanent_location' OR kohafield='items.permanent_location'
8795     |);
8796     print "Upgrade to $DBversion done (Bug 7817: Check for permanent_location)\n";
8797     if( $temp[0] ) {
8798         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";
8799     }
8800     SetVersion($DBversion);
8801 }
8802
8803 $DBversion = "3.17.00.023";
8804 if ( CheckVersion($DBversion) ) {
8805     $dbh->do(q{
8806         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')
8807     });
8808     print "Upgrade to $DBversion done (Bug 11169 - Add AcqItemSetSubfieldsWhenReceiptIsCancelled syspref)\n";
8809     SetVersion($DBversion);
8810 }
8811
8812 $DBversion = "3.17.00.024";
8813 if(CheckVersion($DBversion)) {
8814     $dbh->do(q{
8815         ALTER TABLE issues ADD auto_renew BOOLEAN default FALSE AFTER renewals
8816     });
8817     $dbh->do(q{
8818         ALTER TABLE old_issues ADD auto_renew BOOLEAN default FALSE AFTER renewals
8819     });
8820     $dbh->do(q{
8821         ALTER TABLE issuingrules ADD auto_renew BOOLEAN default FALSE AFTER norenewalbefore
8822     });
8823     print "Upgrade to $DBversion done (Bug 11577: [ENH] Automatic renewal feature)\n";
8824     SetVersion($DBversion);
8825 }
8826
8827 $DBversion = '3.17.00.025';
8828 if ( CheckVersion($DBversion) ) {
8829     $dbh->do(qq{
8830         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')
8831     });
8832     print "Upgrade to $DBversion done (Bug 12728: Checked syspref StatisticsFields)\n";
8833 }
8834
8835 $DBversion = "3.17.00.026";
8836 if ( CheckVersion($DBversion) ) {
8837     if ( C4::Context->preference('marcflavour') eq 'MARC21' ) {
8838         $dbh->do("UPDATE marc_subfield_structure SET liblibrarian = 'Encoded bitrate', libopac = 'Encoded bitrate' WHERE tagfield = '347' AND tagsubfield = 'f'");
8839         $dbh->do("UPDATE marc_subfield_structure SET repeatable = 1 WHERE tagfield IN ('110','111','610','611','710','711','810','811') AND tagsubfield = 'c'");
8840         $dbh->do("UPDATE auth_subfield_structure SET repeatable = 1 WHERE tagfield IN ('110','111','410','411','510','511','710','711') AND tagsubfield = 'c'");
8841         print "Upgrade to $DBversion done (Bug 12435 - Update MARC21 frameworks to Update No. 18 (April 2014))\n";
8842     }
8843     SetVersion($DBversion);
8844 }
8845
8846 $DBversion = "3.17.00.027";
8847 if ( CheckVersion($DBversion) ) {
8848     $dbh->do(q{
8849         DELETE FROM systempreferences WHERE variable = 'SearchEngine'
8850     });
8851     print "Upgrade to $DBversion done (Bug 12538 - Remove SearchEngine syspref)\n";
8852     SetVersion($DBversion);
8853 }
8854
8855 $DBversion = "3.17.00.028";
8856 if ( CheckVersion($DBversion) ) {
8857     $dbh->do(q{
8858         INSERT INTO systempreferences (variable,value) VALUES('OpacCustomSearch','');
8859     });
8860     print "Upgrade to $DBversion done (Bug 12296 - search box replaceable with a system preference)\n";
8861     SetVersion($DBversion);
8862 }
8863
8864 $DBversion = "3.17.00.029";
8865 if ( CheckVersion($DBversion) ) {
8866     $dbh->do("ALTER TABLE  `items` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8867     $dbh->do("ALTER TABLE  `deleteditems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8868     $dbh->do("ALTER TABLE  `biblioitems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8869     $dbh->do("ALTER TABLE  `deletedbiblioitems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8870     print "Upgrade to $DBversion done (Bug 12424 - ddc sorting of call numbers truncates long Cutter parts)\n";
8871     SetVersion ($DBversion);
8872 }
8873
8874 $DBversion = "3.17.00.030";
8875 if ( CheckVersion($DBversion) ) {
8876     $dbh->do(
8877         q{
8878        INSERT INTO systempreferences (variable, value, options, explanation, type )
8879        VALUES
8880         ('UsageStatsCountry', '', NULL, 'The country where your library is located, to be shown on the Hea Koha community website', 'YesNo'),
8881         ('UsageStatsID', '', NULL, 'This preference is part of Koha but it should not be deleted or updated manually.',  'Free'),
8882         ('UsageStatsLastUpdateTime', '', NULL, 'This preference is part of Koha but it should not be deleted or updated manually.', 'Free'),
8883         ('UsageStatsLibraryName', '', NULL, 'The library name to be shown on Hea Koha community website', 'Free'),
8884         ('UsageStatsLibraryType', 'public', 'public|university', 'The library type to be shown on the Hea Koha community website', 'Choice'),
8885         ('UsageStatsLibraryUrl', '', NULL, 'The library URL to be shown on Hea Koha community website', 'Free'),
8886         ('UsageStats', 0, NULL, 'Share anonymous usage data on the Hea Koha community website.', 'YesNo')
8887     });
8888     print "Upgrade to $DBversion done (Bug 11926: Add UsageStats systempreferences (HEA))\n";
8889     SetVersion ($DBversion);
8890 }
8891
8892 $DBversion = "3.17.00.031";
8893 if ( CheckVersion($DBversion) ) {
8894    $dbh->do("ALTER TABLE saved_sql CHANGE report_name report_name VARCHAR( 255 ) NOT NULL DEFAULT '' ");
8895    print "Upgrade to $DBversion done (Bug 2969: Report Name should be mandatory for saved reports)\n";
8896    SetVersion ($DBversion);
8897 }
8898
8899 $DBversion = "3.17.00.032";
8900 if ( CheckVersion($DBversion) ) {
8901     $dbh->do(
8902 "INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('ReplytoDefault',  '',  NULL,  'The default email address to be set as replyto.',  'Free')"
8903     );
8904     $dbh->do(
8905 "INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('ReturnpathDefault',  '',  NULL,  'The default email address to be set as return-path',  'Free')"
8906     );
8907     $dbh->do("ALTER TABLE branches ADD branchreplyto mediumtext AFTER branchemail");
8908     $dbh->do("ALTER TABLE branches ADD branchreturnpath mediumtext AFTER branchreplyto");
8909     print "Upgrade to $DBversion done (Bug 9530: Adding replyto and returnpath addresses.)\n";
8910     SetVersion($DBversion);
8911 }
8912
8913 $DBversion = "3.17.00.033";
8914 if ( CheckVersion($DBversion) ) {
8915     $dbh->do(q{
8916         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
8917         VALUES('FacetMaxCount', '20','Specify the max facet count for each category',NULL,'Integer')
8918     });
8919     print "Upgrade to $DBversion done (Bug 13088 - Allow the user to specify a max amount of facets to show)\n";
8920     SetVersion($DBversion);
8921 }
8922
8923 $DBversion = "3.17.00.034";
8924 if ( CheckVersion($DBversion) ) {
8925     $dbh->do(q|
8926         ALTER TABLE aqorders DROP COLUMN cancelledby;
8927     |);
8928
8929     print "Upgrade to $DBversion done (Bug 11007 - DROP column aqorders.cancelledby)\n";
8930     SetVersion($DBversion);
8931 }
8932
8933 $DBversion = "3.17.00.035";
8934 if ( CheckVersion($DBversion) ) {
8935     $dbh->do(q|
8936         ALTER TABLE serial ADD COLUMN claims_count INT(11) DEFAULT 0 after claimdate
8937     |);
8938     $dbh->do(q|
8939         UPDATE serial
8940         SET claims_count = 1
8941         WHERE claimdate IS NOT NULL
8942     |);
8943     print "Upgrade to $DBversion done (Bug 5342: Add claims_count field in serial table)\n";
8944     SetVersion($DBversion);
8945 }
8946
8947 $DBversion = "3.17.00.036";
8948 if ( CheckVersion($DBversion) ) {
8949     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacShowLibrariesPulldownMobile'");
8950     print "Upgrade to $DBversion done ( Bug 12513 - PROG/CCSR deprecation: Remove OpacShowLibrariesPulldownMobile system preference )\n";
8951     SetVersion ($DBversion);
8952 }
8953
8954 $DBversion = "3.17.00.037";
8955 if ( CheckVersion($DBversion) ) {
8956     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacMainUserBlockMobile'");
8957     print "Upgrade to $DBversion done ( Bug 12246 - PROG/CCSR deprecation: Remove OpacMainUserBlockMobile system preference )\n";
8958     SetVersion ($DBversion);
8959 }
8960
8961 $DBversion = "3.17.00.038";
8962 if ( CheckVersion($DBversion) ) {
8963     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACMobileUserCSS'");
8964     print "Upgrade to $DBversion done ( Bug 12245 - PROG/CCSR deprecation: Remove OPACMobileUserCSS system preference )\n";
8965     SetVersion ($DBversion);
8966 }
8967
8968 $DBversion = "3.17.00.039";
8969 if ( CheckVersion($DBversion) ) {
8970     $dbh->do("INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES
8971     ('OPACFallback', 'prog', 'bootstrap|prog', 'Define the fallback theme for the OPAC interface.', 'Themes')");
8972     print "Upgrade to $DBversion done (Bug 12539 - PROG/CCSR deprecation: Remove hardcoded theme from C4/Templates.pm)\n";
8973     SetVersion ($DBversion);
8974 }
8975
8976 $DBversion = "3.17.00.040";
8977 if ( CheckVersion($DBversion) ) {
8978     my $opac_theme = C4::Context->preference( 'opacthemes' );
8979     if ( !defined $opac_theme || $opac_theme eq 'prog' || $opac_theme eq 'ccsr' ) {
8980         $dbh->do("UPDATE systempreferences SET value='bootstrap' WHERE variable='opacthemes'");
8981     }
8982     print "Upgrade to $DBversion done (Bug 12223: 'prog' and 'ccsr' themes removed)\n";
8983     SetVersion($DBversion);
8984 }
8985
8986 $DBversion = "3.17.00.041";
8987 if ( CheckVersion($DBversion) ) {
8988     print "Upgrade to $DBversion done (Bug 11346: Deprecate the 'prog' and 'CCSR' themes)\n";
8989     SetVersion($DBversion);
8990 }
8991
8992 $DBversion = "3.17.00.042";
8993 if ( CheckVersion($DBversion) ) {
8994     $dbh->do("DELETE FROM systempreferences WHERE variable='yuipath'");
8995     print "Upgrade to $DBversion done (Bug 12494: Remove yuipath system preference)\n";
8996     SetVersion ($DBversion);
8997 }
8998
8999 $DBversion = "3.17.00.043";
9000 if ( CheckVersion($DBversion) ) {
9001     $dbh->do("
9002         ALTER TABLE aqorders
9003         ADD COLUMN cancellationreason TEXT DEFAULT NULL AFTER datecancellationprinted
9004     ");
9005     print "Upgrade to $DBversion done (Bug 7162: Add aqorders.cancellationreason)\n";
9006     SetVersion ($DBversion);
9007 }
9008
9009 $DBversion = "3.17.00.044";
9010 if ( CheckVersion($DBversion) ) {
9011     $dbh->do(q{
9012         INSERT IGNORE INTO systempreferences
9013             (variable,value,explanation,options,type)
9014             VALUES('OnSiteCheckouts','0','Enable/Disable the on-site checkouts feature','','YesNo');
9015     });
9016     $dbh->do(q{
9017         INSERT IGNORE INTO systempreferences
9018             (variable,value,explanation,options,type)
9019             VALUES('OnSiteCheckoutsForce','0','Enable/Disable the on-site for all cases (Even if a user is debarred, etc.)','','YesNo');
9020     });
9021     $dbh->do(q{
9022         ALTER TABLE issues ADD COLUMN onsite_checkout INT(1) NOT NULL DEFAULT 0 AFTER issuedate;
9023     });
9024     $dbh->do(q{
9025         ALTER TABLE old_issues ADD COLUMN onsite_checkout INT(1) NOT NULL DEFAULT 0 AFTER issuedate;
9026     });
9027     print "Upgrade to $DBversion done (Bug 10860: Add new system preference OnSiteCheckouts + fields [old_]issues.onsite_checkout)\n";
9028     SetVersion($DBversion);
9029 }
9030
9031 $DBversion = "3.17.00.045";
9032 if ( CheckVersion($DBversion) ) {
9033     $dbh->do(q{
9034         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
9035         ('LocalHoldsPriority',  '0', NULL,  'Enables the LocalHoldsPriority feature',  'YesNo'),
9036         ('LocalHoldsPriorityItemControl',  'holdingbranch',  'holdingbranch|homebranch',  'decides if the feature operates using the item''s home or holding library.',  'Choice'),
9037         ('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')
9038     });
9039     print "Upgrade to $DBversion done (Bug 11126 - Make the holds system optionally give precedence to local holds)\n";
9040     SetVersion($DBversion);
9041 }
9042
9043 $DBversion = "3.17.00.046";
9044 if ( CheckVersion($DBversion) ) {
9045     $dbh->do(q{
9046         CREATE TABLE IF NOT EXISTS items_search_fields (
9047           name VARCHAR(255) NOT NULL,
9048           label VARCHAR(255) NOT NULL,
9049           tagfield CHAR(3) NOT NULL,
9050           tagsubfield CHAR(1) NULL DEFAULT NULL,
9051           authorised_values_category VARCHAR(16) NULL DEFAULT NULL,
9052           PRIMARY KEY(name),
9053           CONSTRAINT items_search_fields_authorised_values_category
9054             FOREIGN KEY (authorised_values_category) REFERENCES authorised_values (category)
9055             ON DELETE SET NULL ON UPDATE CASCADE
9056         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
9057     });
9058     print "Upgrade to $DBversion done (Bug 11425: Add items_search_fields table)\n";
9059     SetVersion($DBversion);
9060 }
9061
9062 $DBversion = "3.17.00.047";
9063 if ( CheckVersion($DBversion) ) {
9064     $dbh->do(q{
9065         ALTER TABLE collections
9066             CHANGE colBranchcode colBranchcode VARCHAR( 10 ) NULL DEFAULT NULL,
9067             ADD INDEX ( colBranchcode ),
9068             ADD CONSTRAINT collections_ibfk_1 FOREIGN KEY (colBranchcode) REFERENCES branches (branchcode) ON DELETE CASCADE ON UPDATE CASCADE
9069     });
9070     print "Upgrade to $DBversion done (Bug 8836 - Resurrect Rotating Collections)\n";
9071     SetVersion($DBversion);
9072 }
9073
9074 $DBversion = "3.17.00.048";
9075 if ( CheckVersion($DBversion) ) {
9076     $dbh->do(q|
9077         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')
9078     |);
9079     print "Upgrade to $DBversion done (Bug 12448 - Add RentalFeesCheckoutConfirmation syspref)\n";
9080     SetVersion($DBversion);
9081 }
9082
9083 $DBversion = "3.17.00.049";
9084 if ( CheckVersion($DBversion) ) {
9085     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'am', 'language', 'Amharic','2014-10-29')");
9086     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'am','amh')");
9087     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'am', 'language', 'am', 'አማርኛ')");
9088     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'am', 'language', 'en', 'Amharic')");
9089
9090     $dbh->do("UPDATE language_descriptions SET description = 'لعربية' WHERE subtag = 'ar' AND type = 'language' AND lang = 'ar'");
9091
9092     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'az', 'language', 'Azerbaijani','2014-10-30')");
9093     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'az','aze')");
9094     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'az', 'language', 'az', 'Azərbaycan dili')");
9095     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'az', 'language', 'en', 'Azerbaijani')");
9096
9097     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'be', 'language', 'Byelorussian','2014-10-30')");
9098     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'be','bel')");
9099     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'be', 'language', 'be', 'Беларуская мова')");
9100     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'be', 'language', 'en', 'Byelorussian')");
9101
9102     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'bn', 'language', 'Bengali','2014-10-30')");
9103     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'bn','ben')");
9104     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'bn', 'language', 'bn', 'বাংলা')");
9105     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'bn', 'language', 'en', 'Bengali')");
9106
9107     $dbh->do("UPDATE language_descriptions SET description = 'Български' WHERE subtag = 'bg' AND type = 'language' AND lang = 'bg'");
9108     $dbh->do("UPDATE language_descriptions SET description = 'Ceština' WHERE subtag = 'cs' AND type = 'language' AND lang = 'cs'");
9109     $dbh->do("UPDATE language_descriptions SET description = 'Ελληνικά' WHERE subtag = 'el' AND type = 'language' AND lang = 'el'");
9110     $dbh->do("UPDATE language_descriptions SET description = 'Español' WHERE subtag = 'es' AND type = 'language' AND lang = 'es'");
9111
9112     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'eu', 'language', 'Basque','2014-10-30')");
9113     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'eu','eus')");
9114     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'eu', 'language', 'eu', 'Euskera')");
9115     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'eu', 'language', 'en', 'Basque')");
9116
9117     $dbh->do("UPDATE language_descriptions SET description = 'فارسى' WHERE subtag = 'fa' AND type = 'language' AND lang = 'fa'");
9118     $dbh->do("UPDATE language_descriptions SET description = 'Suomi' WHERE subtag = 'fi' AND type = 'language' AND lang = 'fi'");
9119
9120     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'fo', 'language', 'Faroese','2014-10-30')");
9121     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'fo','fao')");
9122     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'fo', 'language', 'fo', 'Føroyskt')");
9123     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'fo', 'language', 'en', 'Faroese')");
9124
9125     $dbh->do("UPDATE language_descriptions SET description = 'Français' WHERE subtag = 'fr' AND type = 'language' AND lang = 'fr'");
9126     $dbh->do("UPDATE language_descriptions SET description = 'עִבְרִית' WHERE subtag = 'he' AND type = 'language' AND lang = 'he'");
9127     $dbh->do("UPDATE language_descriptions SET description = 'हिन्दी' WHERE subtag = 'hi' AND type = 'language' AND lang = 'hi'");
9128
9129     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'is', 'language', 'Icelandic','2014-10-30')");
9130     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'is','ice')");
9131     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'is', 'language', 'is', 'Íslenska')");
9132     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'is', 'language', 'en', 'Icelandic')");
9133
9134     $dbh->do("UPDATE language_descriptions SET description = '日本語' WHERE subtag = 'ja' AND type = 'language' AND lang = 'ja'");
9135
9136     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ka', 'language', 'Kannada','2014-10-30')");
9137     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ka','kan')");
9138     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'ka', 'ಕನ್ನಡ')");
9139     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'en', 'Kannada')");
9140
9141     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'km', 'language', 'Khmer','2014-10-30')");
9142     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'km','khm')");
9143     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'km', 'language', 'km', 'ភាសាខ្មែរ')");
9144     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'km', 'language', 'en', 'Khmer')");
9145
9146     $dbh->do("UPDATE language_descriptions SET description = '한국어' WHERE subtag = 'ko' AND type = 'language' AND lang = 'ko'");
9147
9148     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ku', 'language', 'Kurdish','2014-05-13')");
9149     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ku','kur')");
9150     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'ku', 'کوردی')");
9151     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'en', 'Kurdish')");
9152     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'fr', 'Kurde')");
9153     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'de', 'Kurdisch')");
9154     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'es', 'Kurdo')");
9155
9156     $dbh->do("UPDATE language_descriptions SET description = 'ພາສາລາວ' WHERE subtag = 'lo' AND type = 'language' AND lang = 'lo'");
9157
9158     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mi', 'language', 'Maori','2014-10-30')");
9159     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mi','mri')");
9160     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mi', 'language', 'mi', 'Te Reo Māori')");
9161     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mi', 'language', 'en', 'Maori')");
9162
9163     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mn', 'language', 'Mongolian','2014-10-30')");
9164     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mn','mon')");
9165     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mn', 'language', 'mn', 'Mонгол')");
9166     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mn', 'language', 'en', 'Mongolian')");
9167
9168     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mr', 'language', 'Marathi','2014-10-30')");
9169     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mr','mar')");
9170     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mr', 'language', 'mr', 'मराठी')");
9171     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mr', 'language', 'en', 'Marathi')");
9172
9173     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ms', 'language', 'Malay','2014-10-30')");
9174     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ms','may')");
9175     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ms', 'language', 'ms', 'Bahasa melayu')");
9176     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ms', 'language', 'en', 'Malay')");
9177
9178     $dbh->do("UPDATE language_descriptions SET description = 'Norsk bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'nb'");
9179     $dbh->do("UPDATE language_descriptions SET description = 'Norwegian bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'en'");
9180     $dbh->do("UPDATE language_descriptions SET description = 'Norvégien bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'fr'");
9181     $dbh->do("UPDATE language_descriptions SET description = 'Norwegisch bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'de'");
9182
9183     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ne', 'language', 'Nepali','2014-10-30')");
9184     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ne','nep')");
9185     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)VALUES ( 'ne', 'language', 'ne', 'नेपाली')");
9186     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ne', 'language', 'en', 'Nepali')");
9187
9188     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'pbr', 'language', 'Pangwa','2014-10-30')");
9189     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'pbr','pbr')");
9190     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'pbr', 'language', 'pbr', 'Ekipangwa')");
9191     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'pbr', 'language', 'en', 'Pangwa')");
9192
9193     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'prs', 'language', 'Dari','2014-10-30')");
9194     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'prs','prs')");
9195     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'prs', 'language', 'prs', 'درى')");
9196     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'prs', 'language', 'en', 'Dari')");
9197
9198     $dbh->do("UPDATE language_descriptions SET description = 'Português' WHERE subtag = 'pt' AND type = 'language' AND lang = 'pt'");
9199     $dbh->do("UPDATE language_descriptions SET description = 'Român' WHERE subtag = 'ro' AND type = 'language' AND lang = 'ro'");
9200     $dbh->do("UPDATE language_descriptions SET description = 'Русский' WHERE subtag = 'ru' AND type = 'language' AND lang = 'ru'");
9201
9202     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'rw', 'language', 'Kinyarwanda','2014-10-30')");
9203     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'rw','kin')");
9204     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'rw', 'language', 'rw', 'Ikinyarwanda')");
9205     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'rw', 'language', 'en', 'Kinyarwanda')");
9206
9207     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sd', 'language', 'Sindhi','2014-10-30')");
9208     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sd','snd')");
9209     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sd', 'language', 'sd', 'سنڌي')");
9210     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sd', 'language', 'en', 'Sindhi')");
9211
9212     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sk', 'language', 'Slovak','2014-10-30')");
9213     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sk','slk')");
9214     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sk', 'language', 'sk', 'Slovenčina')");
9215     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sk', 'language', 'en', 'Slovak')");
9216
9217     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sl', 'language', 'Slovene','2014-10-30')");
9218     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sl','slv')");
9219     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sl', 'language', 'sl', 'Slovenščina')");
9220     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sl', 'language', 'en', 'Slovene')");
9221
9222     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sq', 'language', 'Albanian','2014-10-30')");
9223     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sq','sqi')");
9224     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sq', 'language', 'sq', 'Shqip')");
9225     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sq', 'language', 'en', 'Albanian')");
9226
9227     $dbh->do("UPDATE language_descriptions SET description = 'Cрпски' WHERE subtag = 'sr' AND type = 'language' AND lang = 'sr'");
9228
9229     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sw', 'language', 'Swahili','2014-10-30')");
9230     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sw','swa')");
9231     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sw', 'language', 'sw', 'Kiswahili')");
9232     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sw', 'language', 'en', 'Swahili')");
9233
9234     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ta', 'language', 'Tamil','2014-10-30')");
9235     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ta','tam')");
9236     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ta', 'language', 'ta', 'தமிழ்')");
9237     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ta', 'language', 'en', 'Tamil')");
9238
9239     $dbh->do("UPDATE language_descriptions SET description = 'Tetun' WHERE subtag = 'tet' AND type = 'language' AND lang = 'tet'");
9240     $dbh->do("UPDATE language_descriptions SET description = 'ภาษาไทย' WHERE subtag = 'th' AND type = 'language' AND lang = 'th'");
9241
9242     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'tl', 'language', 'Tagalog','2014-10-30')");
9243     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'tl','tgl')");
9244     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'tl', 'language', 'tl', 'Tagalog')");
9245     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'tl', 'language', 'en', 'Tagalog')");
9246
9247     $dbh->do("UPDATE language_descriptions SET description = 'Türkçe' WHERE subtag = 'tr' AND type = 'language' AND lang = 'tr'");
9248     $dbh->do("UPDATE language_descriptions SET description = 'Українська' WHERE subtag = 'uk' AND type = 'language' AND lang = 'uk'");
9249     $dbh->do("UPDATE language_descriptions SET description = 'اردو' WHERE subtag = 'ur' AND type = 'language' AND lang = 'ur'");
9250
9251     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'vi', 'language', 'Vietnamese','2014-10-30')");
9252     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'vi','vie')");
9253     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'vi', 'language', 'vi', '㗂越')");
9254     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'vi', 'language', 'en', 'Vietnamese')");
9255
9256     $dbh->do("UPDATE language_descriptions SET description = '中文' WHERE subtag = 'zh' AND type = 'language' AND lang = 'zh'");
9257     $dbh->do("UPDATE language_descriptions SET description = '' WHERE subtag = 'Arab,script' AND type = 'Arab' AND lang = 'العربية'");
9258
9259     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Armn', 'script', 'Armenian','2014-10-30')");
9260     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Armn', 'script', 'Armn', 'Հայոց այբուբեն')");
9261     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Armn', 'script', 'en', 'Armenian')");
9262
9263     $dbh->do("UPDATE language_descriptions SET description = 'Кирилица' WHERE subtag = 'Cyrl' AND type = 'script' AND lang = 'Cyrl'");
9264
9265     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Ethi', 'script', 'Ethiopic','2014-10-30')");
9266     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Ethi', 'script', 'Ethi', 'ግዕዝ')");
9267     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Ethi', 'script', 'en', 'Ethiopic')");
9268
9269     $dbh->do("UPDATE language_descriptions SET description = 'Ελληνικό αλφάβητο' WHERE subtag = 'Grek' AND type = 'script' AND lang = 'Grek'");
9270     $dbh->do("UPDATE language_descriptions SET description = '简体字' WHERE subtag = 'Hans' AND type = 'script' AND lang = 'Hans'");
9271     $dbh->do("UPDATE language_descriptions SET description = '繁體字' WHERE subtag = 'Hant' AND type = 'script' AND lang = 'Hant'");
9272     $dbh->do("UPDATE language_descriptions SET description = 'אָלֶף־בֵּית עִבְרִי' WHERE subtag = 'Hebr' AND type = 'script' AND lang = 'Hebr'");
9273
9274     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Jpan', 'script', 'Japanese','2014-10-30')");
9275     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Jpan', 'script', 'Jpan', '漢字')");
9276     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Jpan', 'script', 'en', 'Japanese')");
9277
9278     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Knda', 'script', 'Kannada','2014-10-30')");
9279     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Knda', 'script', 'Knda', 'ಕನ್ನಡ ಲಿಪಿ')");
9280     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Knda', 'script', 'en', 'Kannada')");
9281
9282     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Kore', 'script', 'Korean','2014-10-30')");
9283     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Kore', 'script', 'Kore', '한글')");
9284     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Kore', 'script', 'en', 'Korean')");
9285
9286     $dbh->do("UPDATE language_descriptions SET description = 'ອັກສອນລາວ' WHERE subtag = 'Laoo' AND type = 'script' AND lang = 'Laoo'");
9287
9288     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'AL', 'region', 'Albania','2014-10-30')");
9289     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AL', 'region', 'en', 'Albania')");
9290     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AL', 'region', 'sq', 'Shqipërisë')");
9291
9292     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'AZ', 'region', 'Azerbaijan','2014-10-30')");
9293     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AZ', 'region', 'en', 'Azerbaijan')");
9294     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AZ', 'region', 'az', 'Azərbaycan')");
9295
9296     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BE', 'region', 'Belgium','2014-10-30')");
9297     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BE', 'region', 'en', 'Belgium')");
9298     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BE', 'region', 'nl', 'België')");
9299
9300     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BR', 'region', 'Brazil','2014-10-30')");
9301     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BR', 'region', 'en', 'Brazil')");
9302     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BR', 'region', 'pt', 'Brasil')");
9303
9304     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BY', 'region', 'Belarus','2014-10-30')");
9305     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BY', 'region', 'en', 'Belarus')");
9306     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BY', 'region', 'be', 'Беларусь')");
9307
9308     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CA', 'region', 'fr', 'Canada')");
9309
9310     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CH', 'region', 'Switzerland','2014-10-30')");
9311     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CH', 'region', 'en', 'Switzerland')");
9312     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CH', 'region', 'de', 'Schweiz')");
9313
9314     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CN', 'region', 'China','2014-10-30')");
9315     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CN', 'region', 'en', 'China')");
9316     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CN', 'region', 'zh', '中国')");
9317
9318     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CZ', 'region', 'Czech Republic','2014-10-30')");
9319     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CZ', 'region', 'en', 'Czech Republic')");
9320     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CZ', 'region', 'cs', 'Česká republika')");
9321
9322     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'DE', 'region', 'Germany','2014-10-30')");
9323     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DE', 'region', 'en', 'Germany')");
9324     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DE', 'region', 'de', 'Deutschland')");
9325
9326     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DK', 'region', 'en', 'Denmark')");
9327
9328     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ES', 'region', 'Spain','2014-10-30')");
9329     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ES', 'region', 'en', 'Spain')");
9330     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ES', 'region', 'es', 'España')");
9331
9332     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'FI', 'region', 'Finland','2014-10-30')");
9333     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FI', 'region', 'en', 'Finland')");
9334     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FI', 'region', 'fi', 'Suomi')");
9335
9336     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'FO', 'region', 'Faroe Islands','2014-10-30')");
9337     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FO', 'region', 'en', 'Faroe Islands')");
9338     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FO', 'region', 'fo', 'Føroyar')");
9339
9340     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'GR', 'region', 'Greece','2014-10-30')");
9341     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'GR', 'region', 'en', 'Greece')");
9342     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'GR', 'region', 'el', 'Ελλάδα')");
9343
9344     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'HR', 'region', 'Croatia','2014-10-30')");
9345     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HR', 'region', 'en', 'Croatia')");
9346     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HR', 'region', 'hr', 'Hrvatska')");
9347
9348     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'HU', 'region', 'Hungary','2014-10-30')");
9349     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HU', 'region', 'en', 'Hungary')");
9350     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HU', 'region', 'hu', 'Magyarország')");
9351
9352     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ID', 'region', 'Indonesia','2014-10-30')");
9353     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ID', 'region', 'en', 'Indonesia')");
9354     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ID', 'region', 'id', 'Indonesia')");
9355
9356     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'IS', 'region', 'Iceland','2014-10-30')");
9357     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IS', 'region', 'en', 'Iceland')");
9358     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IS', 'region', 'is', 'Ísland')");
9359
9360     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'IT', 'region', 'Italy','2014-10-30')");
9361     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IT', 'region', 'en', 'Italy')");
9362     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IT', 'region', 'it', 'Italia')");
9363
9364     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'JP', 'region', 'Japan','2014-10-30')");
9365     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'JP', 'region', 'en', 'Japan')");
9366     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'JP', 'region', 'ja', '日本')");
9367
9368     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KE', 'region', 'Kenya','2014-10-30')");
9369     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KE', 'region', 'en', 'Kenya')");
9370     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KE', 'region', 'rw', 'Kenya')");
9371
9372     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KH', 'region', 'Cambodia','2014-10-30')");
9373     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KH', 'region', 'en', 'Cambodia')");
9374     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KH', 'region', 'km', 'កម្ពុជា')");
9375
9376     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KP', 'region', 'North Korea','2014-10-30')");
9377     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KP', 'region', 'en', 'North Korea')");
9378     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KP', 'region', 'ko', '조선민주주의인민공화국')");
9379
9380     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'LK', 'region', 'Sri Lanka','2014-10-30')");
9381     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'LK', 'region', 'en', 'Sri Lanka')");
9382     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'LK', 'region', 'ta', 'இலங்கை')");
9383
9384     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'MY', 'region', 'Malaysia','2014-10-30')");
9385     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'MY', 'region', 'en', 'Malaysia')");
9386     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'MY', 'region', 'ms', 'Malaysia')");
9387
9388     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NE', 'region', 'Niger','2014-10-30')");
9389     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NE', 'region', 'en', 'Niger')");
9390     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NE', 'region', 'ne', 'Niger')");
9391
9392     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NL', 'region', 'Netherlands','2014-10-30')");
9393     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NL', 'region', 'en', 'Netherlands')");
9394     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NL', 'region', 'nl', 'Nederland')");
9395
9396     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NO', 'region', 'Norway','2014-10-30')");
9397     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'en', 'Norway')");
9398     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'ne', 'Noreg')");
9399     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'nn', 'Noreg')");
9400
9401     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PH', 'region', 'Philippines','2014-10-30')");
9402     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PH', 'region', 'en', 'Philippines')");
9403     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PH', 'region', 'tl', 'Pilipinas')");
9404
9405     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PK', 'region', 'Pakistan','2014-10-30')");
9406     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PK', 'region', 'en', 'Pakistan')");
9407     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PK', 'region', 'sd', 'پاكستان')");
9408
9409     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PL', 'region', 'Poland','2014-10-30')");
9410     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PL', 'region', 'en', 'Poland')");
9411     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PL', 'region', 'pl', 'Polska')");
9412
9413     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PT', 'region', 'Portugal','2014-10-30')");
9414     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PT', 'region', 'en', 'Portugal')");
9415     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PT', 'region', 'pt', 'Portugal')");
9416
9417     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RO', 'region', 'Romania','2014-10-30')");
9418     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RO', 'region', 'en', 'Romania')");
9419     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RO', 'region', 'ro', 'România')");
9420
9421     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RU', 'region', 'Russia','2014-10-30')");
9422     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RU', 'region', 'en', 'Russia')");
9423     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RU', 'region', 'ru', 'Россия')");
9424
9425     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RW', 'region', 'Rwanda','2014-10-30')");
9426     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RW', 'region', 'en', 'Rwanda')");
9427     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RW', 'region', 'rw', 'Rwanda')");
9428
9429     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SE', 'region', 'Sweden','2014-10-30')");
9430     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SE', 'region', 'en', 'Sweden')");
9431     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SE', 'region', 'sv', 'Sverige')");
9432
9433     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SI', 'region', 'Slovenia','2014-10-30')");
9434     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SI', 'region', 'en', 'Slovenia')");
9435     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SI', 'region', 'sl', 'Slovenija')");
9436
9437     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SK', 'region', 'Slovakia','2014-10-30')");
9438     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SK', 'region', 'en', 'Slovakia')");
9439     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SK', 'region', 'sk', 'Slovensko')");
9440
9441     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TH', 'region', 'Thailand','2014-10-30')");
9442     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TH', 'region', 'en', 'Thailand')");
9443     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TH', 'region', 'th', 'ประเทศไทย')");
9444
9445     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TR', 'region', 'Turkey','2014-10-30')");
9446     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TR', 'region', 'en', 'Turkey')");
9447     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TR', 'region', 'tr', 'Türkiye')");
9448
9449     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TW', 'region', 'Taiwan','2014-10-30')");
9450     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TW', 'region', 'en', 'Taiwan')");
9451     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TW', 'region', 'zh', '台灣')");
9452
9453     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'UA', 'region', 'Ukraine','2014-10-30')");
9454     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'UA', 'region', 'en', 'Ukraine')");
9455     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'UA', 'region', 'uk', 'Україна')");
9456
9457     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'VN', 'region', 'Vietnam','2014-10-30')");
9458     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'VN', 'region', 'en', 'Vietnam')");
9459     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'VN', 'region', 'vi', 'Việt Nam')");
9460
9461     print "Upgrade to $DBversion done (Bug 12250: Update descriptions for languages, scripts and regions)\n";
9462     SetVersion($DBversion);
9463 }
9464
9465 $DBversion = "3.17.00.050";
9466 if ( CheckVersion($DBversion) ) {
9467     $dbh->do(q|
9468         INSERT INTO permissions (module_bit, code, description) VALUES
9469           (13, 'records_batchdel', 'Perform batch deletion of records (bibliographic or authority)')
9470     |);
9471     print "Upgrade to $DBversion done (Bug 12403: Add permission tools_records_batchdelitem)\n";
9472     SetVersion($DBversion);
9473 }
9474
9475 $DBversion = "3.17.00.051";
9476 if ( CheckVersion($DBversion) ) {
9477     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('GoogleIndicTransliteration','0','','GoogleIndicTransliteration on the OPAC.','YesNo')");
9478     print "Upgrade to $DBversion done (Bug 13211: Added system preferences GoogleIndicTransliteration on the OPAC)\n";
9479     SetVersion($DBversion);
9480 }
9481
9482 $DBversion = "3.17.00.052";
9483 if ( CheckVersion($DBversion) ) {
9484     $dbh->do(q{
9485         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');
9486     });
9487
9488     $dbh->do(q{
9489         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');
9490    });
9491    print "Upgrade to $DBversion done (Bug 9043: Add system preference OpacAdvSearchOptions and OpacAdvSearchMoreOptions)\n";
9492    SetVersion ($DBversion);
9493 }
9494
9495 $DBversion = "3.17.00.053";
9496 if ( CheckVersion($DBversion) ) {
9497     $dbh->do(q{
9498         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)');
9499     });
9500
9501     $dbh->do(q{
9502         INSERT INTO permissions (module_bit, code, description) VALUES ('9', 'delete_all_items', 'Delete all items at once');
9503     });
9504
9505     $dbh->do(q{
9506         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)');
9507     });
9508
9509     # The delete_all_items permission should be added to users having the edit_items permission.
9510     $dbh->do(q{
9511         INSERT INTO user_permissions (borrowernumber, module_bit, code) SELECT borrowernumber, module_bit, "delete_all_items" FROM user_permissions WHERE code="edit_items";
9512     });
9513
9514     # Add 2 new prefs
9515     $dbh->do(q{
9516         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');
9517     });
9518
9519     $dbh->do(q{
9520         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');
9521     });
9522
9523     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";
9524     SetVersion($DBversion);
9525 }
9526
9527 $DBversion = "3.17.00.054";
9528 if (CheckVersion($DBversion)) {
9529     $dbh->do(q{
9530         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
9531         ('AllowRenewalIfOtherItemsAvailable','0',NULL,'If enabled, allow a patron to renew an item with unfilled holds if other available items can fill that hold.','YesNo')
9532     });
9533     print "Upgrade to $DBversion done (Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds)\n";
9534     SetVersion($DBversion);
9535 }
9536
9537 $DBversion = "3.17.00.055";
9538 if ( CheckVersion($DBversion) ) {
9539     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBEnable', '0', NULL, 'Enable communication with the Norwegian national patron database.', 'YesNo')");
9540     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBEndpoint', '', NULL, 'Which NL endpoint to use.', 'Free')");
9541     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBUsername', '', NULL, 'Username for communication with the Norwegian national patron database.', 'Free')");
9542     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBPassword', '', NULL, 'Password for communication with the Norwegian national patron database.', 'Free')");
9543     $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')");
9544     $dbh->do("
9545 CREATE TABLE borrower_sync (
9546     borrowersyncid int(11) NOT NULL AUTO_INCREMENT,
9547     borrowernumber int(11) NOT NULL,
9548     synctype varchar(32) NOT NULL,
9549     sync tinyint(1) NOT NULL DEFAULT '0',
9550     syncstatus varchar(10) DEFAULT NULL,
9551     lastsync varchar(50) DEFAULT NULL,
9552     hashed_pin varchar(64) DEFAULT NULL,
9553     PRIMARY KEY (borrowersyncid),
9554     KEY borrowernumber (borrowernumber),
9555     CONSTRAINT borrower_sync_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
9556 ) ENGINE=InnoDB DEFAULT CHARSET=utf8"
9557 );
9558     print "Upgrade to $DBversion done (Bug 11401 - Add support for Norwegian national library card)\n";
9559     SetVersion($DBversion);
9560 }
9561
9562 $DBversion = "3.17.00.056";
9563 if ( CheckVersion($DBversion) ) {
9564     $dbh->do(q{
9565         UPDATE systempreferences SET value = 'pubdate,itemtype,language,sorting,location' WHERE variable='OpacAdvSearchOptions'
9566     });
9567
9568     $dbh->do(q{
9569         UPDATE systempreferences SET value = 'pubdate,itemtype,language,subtype,sorting,location' WHERE variable='OpacAdvSearchMoreOptions'
9570     });
9571
9572     print "Upgrade to $DBversion done (Bug 9043 - Update the values for OpacAdvSearchOptions and OpacAdvSearchOptions)\n";
9573     SetVersion($DBversion);
9574 }
9575
9576 $DBversion = "3.17.00.057";
9577 if ( CheckVersion($DBversion) ) {
9578     print "Upgrade to $DBversion done (Koha 3.18 beta)\n";
9579     SetVersion ($DBversion);
9580 }
9581
9582 $DBversion = "3.17.00.058";
9583 if( CheckVersion($DBversion) ){
9584     $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')");
9585     $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')");
9586     $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')");
9587     print "Upgrade to $DBversion done (Bug 8337: System preferences for longoverdue cron)\n";
9588     SetVersion($DBversion);
9589 }
9590
9591 $DBversion = "3.17.00.059";
9592 if ( CheckVersion($DBversion) ) {
9593     $dbh->do(q{
9594         UPDATE permissions SET description = "Add and delete budgets (but can't modifiy budgets)" WHERE description = "Add and delete budgets (but cant modify budgets)";
9595     });
9596     print "Upgrade to $DBversion done (Bug 10749: Fix typo in budget_add_del permission description)\n";
9597     SetVersion ($DBversion);
9598 }
9599
9600 $DBversion = "3.17.00.060";
9601 if ( CheckVersion($DBversion) ) {
9602     my $count_l = $dbh->selectcol_arrayref(q|
9603         SELECT COUNT(*) FROM letter WHERE message_transport_type='feed'
9604     |);
9605     my $count_mq = $dbh->selectcol_arrayref(q|
9606         SELECT COUNT(*) FROM message_queue WHERE message_transport_type='feed'
9607     |);
9608     my $count_ott = $dbh->selectcol_arrayref(q|
9609         SELECT COUNT(*) FROM overduerules_transport_types WHERE message_transport_type='feed'
9610     |);
9611     my $count_mt = $dbh->selectcol_arrayref(q|
9612         SELECT COUNT(*) FROM message_transports WHERE message_transport_type='feed'
9613     |);
9614     my $count_bmtp = $dbh->selectcol_arrayref(q|
9615         SELECT COUNT(*) FROM borrower_message_transport_preferences WHERE message_transport_type='feed'
9616     |);
9617
9618     my $deleted = 0;
9619     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 ) {
9620         $deleted = $dbh->do(q|
9621             DELETE FROM message_transport_types where message_transport_type='feed'
9622         |);
9623         $deleted = $deleted ne '0E0' ? 1 : 0;
9624     }
9625
9626     print "Upgrade to $DBversion done (Bug 12298: Delete the 'feed' message transport type " . ($deleted ? '(deleted!)' : '(not deleted)') . ")\n";
9627     SetVersion($DBversion);
9628 }
9629
9630 $DBversion = "3.18.00.000";
9631 if ( CheckVersion($DBversion) ) {
9632     print "Upgrade to $DBversion done (3.18.0 release)\n";
9633     SetVersion($DBversion);
9634 }
9635
9636 $DBversion = "3.19.00.000";
9637 if ( CheckVersion($DBversion) ) {
9638     print "Upgrade to $DBversion done (there's life after 3.18)\n";
9639     SetVersion ($DBversion);
9640 }
9641
9642 $DBversion = "3.19.00.001";
9643 if ( CheckVersion($DBversion) ) {
9644     $dbh->do("
9645         UPDATE systempreferences
9646         SET options = 'public|school|academic|research|private|societyAssociation|corporate|government|religiousOrg|subscription'
9647         WHERE variable = 'UsageStatsLibraryType'
9648     ");
9649     if ( C4::Context->preference("UsageStatsLibraryType") eq "university" ) {
9650         C4::Context->set_preference("UsageStatsLibraryType", "academic")
9651     }
9652     print "Upgrade to $DBversion done (Bug 13436: Add more options to UsageStatsLibraryType)\n";
9653     SetVersion ($DBversion);
9654 }
9655
9656 $DBversion = "3.19.00.002";
9657 if ( CheckVersion($DBversion) ) {
9658     $dbh->do(q|
9659         UPDATE suggestions SET branchcode="" WHERE branchcode="__ANY__"
9660     |);
9661     print "upgrade to $DBversion done (Bug 10753: replace __ANY__ with empty string in suggestions.branchcode)\n";
9662     SetVersion ($DBversion);
9663 }
9664
9665 $DBversion = "3.19.00.003";
9666 if ( CheckVersion($DBversion) ) {
9667     my ($count) = $dbh->selectrow_array("SELECT COUNT(*) FROM borrowers GROUP BY userid HAVING COUNT(userid) > 1");
9668
9669     if ( $count ) {
9670         print "Upgrade to $DBversion done (Bug 1861 - Unique patrons logins not (totally) enforced) FAILED!\n";
9671         print "Your database has users with duplicate user logins. Please have your administrator deduplicate your user logins.\n";
9672         print "Afterward, your Koha administrator should execute the following database query: ALTER TABLE borrowers DROP INDEX userid, ADD UNIQUE userid (userid)";
9673     } else {
9674         $dbh->do(q{
9675             ALTER TABLE borrowers
9676                 DROP INDEX userid ,
9677                 ADD UNIQUE userid (userid)
9678         });
9679         print "Upgrade to $DBversion done (Bug 1861: Unique patrons logins not (totally) enforced)\n";
9680     }
9681     SetVersion ($DBversion);
9682 }
9683
9684 $DBversion = "3.19.00.004";
9685 if ( CheckVersion($DBversion) ) {
9686     my $pref_value = C4::Context->preference('OpacExportOptions');
9687     $pref_value =~ s/\|/,/g; # multiple is separated by ,
9688     $dbh->do(q{
9689         UPDATE systempreferences
9690             SET value = ?,
9691                 type = 'multiple'
9692         WHERE variable = 'OpacExportOptions'
9693     }, {}, $pref_value );
9694     print "Upgrade to $DBversion done (Bug 13346: OpacExportOptions is now multiple)\n";
9695     SetVersion ($DBversion);
9696 }
9697
9698 $DBversion = "3.19.00.005";
9699 if(CheckVersion($DBversion)) {
9700     $dbh->do(q{
9701         ALTER TABLE authorised_values MODIFY COLUMN category VARCHAR(32) NOT NULL DEFAULT ''
9702     });
9703
9704     $dbh->do(q{
9705         ALTER TABLE borrower_attribute_types MODIFY COLUMN authorised_value_category VARCHAR(32) DEFAULT NULL
9706     });
9707
9708     print "Upgrade to $DBversion done (Bug 13379: Modify authorised_values.category to varchar(32))\n";
9709     SetVersion($DBversion);
9710 }
9711
9712 $DBversion = "3.19.00.006";
9713 if ( CheckVersion($DBversion) ) {
9714     $dbh->do(q|SET foreign_key_checks = 0|);
9715     my $sth = $dbh->table_info( '','','','TABLE' );
9716     my ( $cat, $schema, $name, $type, $remarks );
9717     while ( ( $cat, $schema, $name, $type, $remarks ) = $sth->fetchrow_array ) {
9718         my $table_sth = $dbh->prepare(qq|SHOW CREATE TABLE $name|);
9719         $table_sth->execute;
9720         my @table = $table_sth->fetchrow_array;
9721         unless ( $table[1] =~ /COLLATE=utf8mb4_unicode_ci/ ) { #catches utf8mb4 collated tables
9722             if ( $name eq 'marc_subfield_structure' ) {
9723                 $dbh->do(q|
9724                     ALTER TABLE marc_subfield_structure
9725                     MODIFY COLUMN tagfield varchar(3) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9726                     MODIFY COLUMN tagsubfield varchar(1) COLLATE utf8_bin NOT NULL DEFAULT '',
9727                     MODIFY COLUMN liblibrarian varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9728                     MODIFY COLUMN libopac varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9729                     MODIFY COLUMN kohafield varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
9730                     MODIFY COLUMN authorised_value varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
9731                     MODIFY COLUMN authtypecode varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
9732                     MODIFY COLUMN value_builder varchar(80) COLLATE utf8_unicode_ci DEFAULT NULL,
9733                     MODIFY COLUMN frameworkcode varchar(4) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9734                     MODIFY COLUMN seealso varchar(1100) COLLATE utf8_unicode_ci DEFAULT NULL,
9735                     MODIFY COLUMN link varchar(80) COLLATE utf8_unicode_ci DEFAULT NULL
9736                 |);
9737                 $dbh->do(qq|ALTER TABLE $name CHARACTER SET utf8 COLLATE utf8_unicode_ci|);
9738             }
9739             else {
9740                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci|);
9741             }
9742         }
9743     }
9744     $dbh->do(q|SET foreign_key_checks = 1|);;
9745
9746     print "Upgrade to $DBversion done (Bug 11944: Convert DB tables to utf8_unicode_ci)\n";
9747     SetVersion($DBversion);
9748 }
9749
9750 $DBversion = "3.19.00.007";
9751 if ( CheckVersion($DBversion) ) {
9752     my $orphan_budgets = $dbh->selectall_arrayref(q|
9753         SELECT budget_id, budget_name, budget_code
9754         FROM aqbudgets
9755         WHERE   budget_parent_id IS NOT NULL
9756             AND budget_parent_id NOT IN (
9757                 SELECT DISTINCT budget_id FROM aqbudgets
9758             )
9759     |, { Slice => {} } );
9760
9761     if ( @$orphan_budgets ) {
9762         for my $b ( @$orphan_budgets ) {
9763             print "Fund $b->{budget_name} (code:$b->{budget_code}, id:$b->{budget_id}) does not have a parent, it may cause problem\n";
9764         }
9765         print "Upgrade to $DBversion done (Bug 12905: Check budget integrity: FAIL)\n";
9766     } else {
9767         print "Upgrade to $DBversion done (Bug 12905: Check budget integrity: OK)\n";
9768     }
9769     SetVersion ($DBversion);
9770 }
9771
9772 $DBversion = "3.19.00.008";
9773 if ( CheckVersion($DBversion) ) {
9774     my $number_of_orders_not_linked = $dbh->selectcol_arrayref(q|
9775         SELECT COUNT(*)
9776         FROM aqorders o
9777         WHERE NOT EXISTS (
9778             SELECT NULL
9779             FROM aqbudgets b
9780             WHERE b.budget_id = o.budget_id
9781         );
9782     |);
9783
9784     if ( $number_of_orders_not_linked->[0] > 0 ) {
9785         $dbh->do(q|
9786             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)
9787         |);
9788         my $budget_period_id = $dbh->last_insert_id( undef, undef, 'aqbudgetperiods', undef );
9789         $dbh->do(qq|
9790             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 );
9791         |);
9792         my $budget_id = $dbh->last_insert_id( undef, undef, 'aqbudgets', undef );
9793         $dbh->do(qq|
9794             UPDATE aqorders o
9795             SET budget_id = $budget_id
9796             WHERE NOT EXISTS (
9797                 SELECT NULL
9798                 FROM aqbudgets b
9799                 WHERE b.budget_id = o.budget_id
9800             )
9801         |);
9802     }
9803
9804     $dbh->do(q|
9805         ALTER TABLE aqorders
9806         ADD CONSTRAINT aqorders_budget_id_fk FOREIGN KEY (budget_id) REFERENCES aqbudgets(budget_id) ON DELETE CASCADE ON UPDATE CASCADE
9807     |);
9808
9809     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";
9810     SetVersion($DBversion);
9811 }
9812
9813 $DBversion = "3.19.00.009";
9814 if ( CheckVersion($DBversion) ) {
9815     $dbh->do(q|
9816         UPDATE suggestions s SET s.budgetid = NULL
9817         WHERE NOT EXISTS (
9818             SELECT NULL
9819             FROM aqbudgets b
9820             WHERE b.budget_id = s.budgetid
9821         );
9822     |);
9823
9824     $dbh->do(q|
9825         ALTER TABLE suggestions
9826         ADD CONSTRAINT suggestions_budget_id_fk FOREIGN KEY (budgetid) REFERENCES aqbudgets(budget_id) ON DELETE SET NULL ON UPDATE CASCADE
9827     |);
9828
9829     print "Upgrade to $DBversion done (Bug 13007: Add new foreign key suggestions.budgetid)\n";
9830     SetVersion($DBversion);
9831 }
9832
9833 $DBversion = "3.19.00.010";
9834 if ( CheckVersion($DBversion) ) {
9835     $dbh->do(q|
9836         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
9837         VALUES('SessionRestrictionByIP','1','Check for Change in  Remote IP address for Session Security. Disable when remote ip address changes frequently.','','YesNo')
9838     |);
9839     print "Upgrade to $DBversion done (Bug 5511: SessionRestrictionByIP)\n";
9840     SetVersion ($DBversion);
9841 }
9842
9843 $DBversion = "3.19.00.011";
9844 if ( CheckVersion($DBversion) ) {
9845     $dbh->do(q|
9846         INSERT INTO userflags (bit, flag, flagdesc, defaulton) VALUES
9847         (20, 'lists', 'Lists', 0)
9848     |);
9849     $dbh->do(q|
9850         INSERT INTO permissions (module_bit, code, description) VALUES
9851         (20, 'delete_public_lists', 'Delete public lists')
9852     |);
9853     print "Upgrade to $DBversion done (Bug 13417: Add permission to delete public lists)\n";
9854     SetVersion ($DBversion);
9855 }
9856
9857 $DBversion = "3.19.00.012";
9858 if(CheckVersion($DBversion)) {
9859     $dbh->do(q{
9860         ALTER TABLE biblioitems MODIFY COLUMN marcxml longtext
9861     });
9862
9863     $dbh->do(q{
9864         ALTER TABLE deletedbiblioitems MODIFY COLUMN marcxml longtext
9865     });
9866
9867     print "Upgrade to $DBversion done (Bug 13523 Remove NOT NULL restriction on field marcxml due to mysql STRICT_TRANS_TABLES)\n";
9868     SetVersion ($DBversion);
9869 }
9870
9871 $DBversion = "3.19.00.013";
9872 if ( CheckVersion($DBversion) ) {
9873     $dbh->do(q|
9874         INSERT INTO permissions (module_bit, code, description) VALUES
9875           (13, 'records_batchmod', 'Perform batch modification of records (biblios or authorities)')
9876     |);
9877     print "Upgrade to $DBversion done (Bug 11395: Add permission tools_records_batchmod)\n";
9878     SetVersion($DBversion);
9879 }
9880
9881 $DBversion = "3.19.00.014";
9882 if ( CheckVersion($DBversion) ) {
9883     $dbh->do(q|
9884         CREATE TABLE aqorder_users (
9885             ordernumber int(11) NOT NULL,
9886             borrowernumber int(11) NOT NULL,
9887             PRIMARY KEY (ordernumber, borrowernumber),
9888             CONSTRAINT aqorder_users_ibfk_1 FOREIGN KEY (ordernumber) REFERENCES aqorders (ordernumber) ON DELETE CASCADE ON UPDATE CASCADE,
9889             CONSTRAINT aqorder_users_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
9890         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
9891     |);
9892
9893     $dbh->do(q|
9894         INSERT INTO letter(module, code, branchcode, name, title, content, message_transport_type)
9895         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')
9896     |);
9897     print "Upgrade to $DBversion done (Bug 12648: Add letter ACQ_NOTIF_ON_RECEIV )\n";
9898     SetVersion ($DBversion);
9899 }
9900
9901 $DBversion = "3.19.00.015";
9902 if ( CheckVersion($DBversion) ) {
9903     $dbh->do(q|
9904         ALTER TABLE search_history ADD COLUMN id INT(11) NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY(id);
9905     |);
9906     print "Upgrade to $DBversion done (Bug 11430: Add primary key for search_history)\n";
9907     SetVersion ($DBversion);
9908 }
9909
9910 $DBversion = "3.19.00.016";
9911 if(CheckVersion($DBversion)) {
9912     my @order_cancellation_reason = $dbh->selectrow_array("SELECT count(*) FROM authorised_values WHERE category='ORDER_CANCELLATION_REASON'");
9913     if ($order_cancellation_reason[0] == 0) {
9914         $dbh->do(q{
9915             INSERT INTO authorised_values (category, authorised_value, lib) VALUES
9916              ('ORDER_CANCELLATION_REASON', 0, 'No reason provided'),
9917              ('ORDER_CANCELLATION_REASON', 1, 'Out of stock'),
9918              ('ORDER_CANCELLATION_REASON', 2, 'Restocking')
9919         });
9920
9921         my $already_existing_reasons = $dbh->selectcol_arrayref(q{
9922             SELECT DISTINCT( cancellationreason )
9923             FROM aqorders;
9924         }, { Slice => {} });
9925
9926         my $update_orders_sth = $dbh->prepare(q{
9927             UPDATE aqorders
9928             SET cancellationreason = ?
9929             WHERE cancellationreason = ?
9930         });
9931
9932         my $insert_av_sth = $dbh->prepare(q{
9933             INSERT INTO authorised_values (category, authorised_value, lib) VALUES
9934              ('ORDER_CANCELLATION_REASON', ?, ?)
9935         });
9936         my $i = 3;
9937         for my $reason ( @$already_existing_reasons ) {
9938             next unless $reason;
9939             $insert_av_sth->execute( $i, $reason );
9940             $update_orders_sth->execute( $i, $reason );
9941             $i++;
9942         }
9943         print "Upgrade to $DBversion done (Bug 13380: Add the ORDER_CANCELLATION_REASON authorised value)\n";
9944     }
9945     else {
9946         print "Upgrade to $DBversion done (Bug 13380: ORDER_CANCELLATION_REASON authorised value already existed from earlier update!)\n";
9947     }
9948
9949     SetVersion($DBversion);
9950 }
9951
9952 $DBversion = '3.19.00.017';
9953 if ( CheckVersion($DBversion) ) {
9954     # First create the column
9955     $dbh->do("ALTER TABLE issuingrules ADD onshelfholds tinyint(1) default 0 NOT NULL");
9956     # Now update the column
9957     if (C4::Context->preference("AllowOnShelfHolds")){
9958         # Pref is on, set allow for all rules
9959         $dbh->do("UPDATE issuingrules SET onshelfholds=1");
9960     } else {
9961         # If the preference is not set, leave off
9962         $dbh->do("UPDATE issuingrules SET onshelfholds=0");
9963     }
9964     # Remove from the systempreferences table
9965     $dbh->do("DELETE FROM systempreferences WHERE variable = 'AllowOnShelfHolds'");
9966
9967     # First create the column
9968     $dbh->do("ALTER TABLE issuingrules ADD opacitemholds char(1) DEFAULT 'N' NOT NULL");
9969     # Now update the column
9970     my $opacitemholds = C4::Context->preference("OPACItemHolds") || '';
9971     if (lc ($opacitemholds) eq 'force') {
9972         $opacitemholds = 'F';
9973     }
9974     else {
9975         $opacitemholds = $opacitemholds ? 'Y' : 'N';
9976     }
9977     # Set allow for all rules
9978     $dbh->do("UPDATE issuingrules SET opacitemholds='$opacitemholds'");
9979
9980     # Remove from the systempreferences table
9981     $dbh->do("DELETE FROM systempreferences WHERE variable = 'OPACItemHolds'");
9982
9983     print "Upgrade to $DBversion done (Bug 5786: Move AllowOnShelfHolds to circulation matrix; Move OPACItemHolds system preference to circulation matrix)\n";
9984     SetVersion ($DBversion);
9985 }
9986
9987
9988 $DBversion = "3.19.00.018";
9989 if ( CheckVersion($DBversion) ) {
9990     $dbh->do(q|
9991         UPDATE systempreferences set variable="OpacAdditionalStylesheet" WHERE variable="opaccolorstylesheet"
9992     |);
9993     print "Upgrade to $DBversion done (Bug 10328: Rename opaccolorstylesheet to OpacAdditionalStylesheet\n";
9994     SetVersion ($DBversion);
9995 }
9996
9997 $DBversion = "3.19.00.019";
9998 if ( CheckVersion($DBversion) ) {
9999     $dbh->do(q{
10000         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
10001         VALUES('Coce','0', 'If on, enables cover retrieval from the configured Coce server', NULL, 'YesNo')
10002     });
10003     $dbh->do(q{
10004         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
10005         VALUES('CoceHost', NULL, 'Coce server URL', NULL,'Free')
10006     });
10007     $dbh->do(q{
10008         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
10009         VALUES('CoceProviders', NULL, 'Coce providers', 'aws,gb,ol', 'multiple')
10010     });
10011     print "Upgrade to $DBversion done (Bug 9580: Cover image from Coce, a remote image URL cache)\n";
10012     SetVersion($DBversion);
10013 }
10014
10015 $DBversion = "3.19.00.020";
10016 if ( CheckVersion($DBversion) ) {
10017     $dbh->do(q|
10018         ALTER TABLE aqorders DROP COLUMN supplierreference;
10019     |);
10020
10021     print "Upgrade to $DBversion done (Bug 11008: DROP column aqorders.supplierreference)\n";
10022     SetVersion($DBversion);
10023 }
10024
10025 $DBversion = "3.19.00.021";
10026 if ( CheckVersion($DBversion) ) {
10027     $dbh->do(q|
10028         ALTER TABLE issues DROP COLUMN issuingbranch
10029     |);
10030     $dbh->do(q|
10031         ALTER TABLE old_issues DROP COLUMN issuingbranch
10032     |);
10033     print "Upgrade to $DBversion done (Bug 2806: Remove issuingbranch columns)\n";
10034     SetVersion ($DBversion);
10035 }
10036
10037 $DBversion = '3.19.00.022';
10038 if ( CheckVersion($DBversion) ) {
10039     $dbh->do(q{
10040         ALTER TABLE suggestions DROP COLUMN mailoverseeing;
10041     });
10042     print "Upgrade to $DBversion done (Bug 13006: Drop column suggestion.mailoverseeing)\n";
10043     SetVersion($DBversion);
10044 }
10045
10046 $DBversion = "3.19.00.023";
10047 if ( CheckVersion($DBversion) ) {
10048     $dbh->do(q|
10049         DELETE FROM systempreferences where variable = 'AddPatronLists'
10050     |);
10051     print "Upgrade to $DBversion done (Bug 13497: Remove the AddPatronLists system preferences)\n";
10052     SetVersion ($DBversion);
10053 }
10054
10055 $DBversion = "3.19.00.024";
10056 if ( CheckVersion($DBversion) ) {
10057     $dbh->do(qq|DROP table patroncards;|);
10058     print "Upgrade to $DBversion done (Bug 13539: Remove table patroncards from database as it's no longer in use)\n";
10059     SetVersion ($DBversion);
10060 }
10061
10062 $DBversion = "3.19.00.025";
10063 if ( CheckVersion($DBversion) ) {
10064     $dbh->do(q|
10065         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
10066         ('SearchWithISBNVariations','0',NULL,'If enabled, search on all variations of the ISBN','YesNo')
10067     |);
10068     print "Upgrade to $DBversion done (Bug 13528: Add the SearchWithISBNVariations syspref)\n";
10069     SetVersion ($DBversion);
10070 }
10071
10072 $DBversion = "3.19.00.026";
10073 if( CheckVersion($DBversion) ) {
10074     if ( C4::Context->preference('marcflavour') eq 'MARC21' ) {
10075     $dbh->do(q{
10076         INSERT IGNORE INTO auth_tag_structure (authtypecode, tagfield, liblibrarian, libopac, repeatable, mandatory, authorised_value) VALUES
10077         ('', '388', 'TIME PERIOD OF CREATION', 'TIME PERIOD OF CREATION', 1, 0, NULL);
10078     });
10079
10080     $dbh->do(q{
10081         INSERT IGNORE INTO auth_subfield_structure (authtypecode, tagfield, tagsubfield, liblibrarian, libopac, repeatable,
10082         mandatory, tab, authorised_value, value_builder, seealso, isurl, hidden, linkid, kohafield, frameworkcode) VALUES
10083         ('', '388', '0', 'Authority record control number or standard number', 'Authority record control number or standard number', 1, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10084         ('', '388', '2', 'Source of term', 'Source of term', 0, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10085         ('', '388', '3', 'Materials specified', 'Materials specified', 0, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10086         ('', '388', '6', 'Linkage', 'Linkage', 0, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10087         ('', '388', '8', 'Field link and sequence number', 'Field link and sequence number', 1, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10088         ('', '388', 'a', 'Time period of creation term', 'Time period of creation term', 1, 0, 3, NULL, NULL, NULL, 0, 0, '', '', '');
10089     });
10090
10091     $dbh->do(q{
10092         UPDATE IGNORE auth_subfield_structure SET repeatable = 1 WHERE tagsubfield = 'g' AND tagfield IN
10093         ('100','110','111','130','400','410','411','430','500','510','511','530','700','710','730');
10094     });
10095
10096     $dbh->do(q{
10097         INSERT IGNORE INTO auth_subfield_structure (authtypecode, tagfield, tagsubfield, liblibrarian, libopac, repeatable,
10098         mandatory, tab, authorised_value, value_builder, seealso, isurl, hidden, linkid, kohafield, frameworkcode) VALUES
10099         ('', '150', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 1, NULL, NULL, NULL, 0, 0, '', '', ''),
10100         ('', '151', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 1, NULL, NULL, NULL, 0, 0, '', '', ''),
10101         ('', '450', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 4, NULL, NULL, NULL, 0, 0, '', '', ''),
10102         ('', '451', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 4, NULL, NULL, NULL, 0, 0, '', '', ''),
10103         ('', '550', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 5, NULL, NULL, NULL, 0, 0, '', '', ''),
10104         ('', '551', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 5, NULL, NULL, NULL, 0, 0, '', '', ''),
10105         ('', '750', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10106         ('', '751', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10107         ('', '748', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10108         ('', '755', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10109         ('', '780', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10110         ('', '781', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10111         ('', '782', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10112         ('', '785', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10113         ('', '710', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10114         ('', '730', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10115         ('', '748', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10116         ('', '750', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10117         ('', '751', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10118         ('', '755', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10119         ('', '762', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10120         ('', '780', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10121         ('', '781', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10122         ('', '782', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10123         ('', '785', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10124         ('', '788', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', '');
10125     });
10126
10127     $dbh->do(q{
10128         UPDATE IGNORE auth_subfield_structure SET liblibrarian = 'Relationship information', libopac = 'Relationship information'
10129         WHERE tagsubfield = 'i' AND tagfield IN ('700','710','730','750','751','762');
10130     });
10131
10132     $dbh->do(q{
10133         UPDATE IGNORE auth_subfield_structure SET liblibrarian = 'Relationship code', libopac = 'Relationship code'
10134         WHERE tagsubfield = '4' AND tagfield IN ('700','710');
10135     });
10136
10137     $dbh->do(q{
10138         INSERT IGNORE INTO marc_tag_structure (tagfield, liblibrarian, libopac, repeatable, mandatory, authorised_value, frameworkcode) VALUES
10139         ('370', 'ASSOCIATED PLACE', 'ASSOCIATED PLACE', 1, 0, NULL, ''),
10140         ('388', 'TIME PERIOD OF CREATION', 'TIME PERIOD OF CREATION', 1, 0, NULL, '');
10141     });
10142
10143     $dbh->do(q{
10144         INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian, libopac, repeatable, mandatory,
10145         kohafield, tab, authorised_value, authtypecode, value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
10146         ('370', '0', 'Authority record control number or standard number', 'Authority record control number or standard number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10147         ('370', '2', 'Source of term', 'Source of term', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10148         ('370', '6', 'Linkage', 'Linkage', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10149         ('370', '8', 'Field link and sequence number', 'Field link and sequence number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10150         ('370', 'c', 'Associated country', 'Associated country', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10151         ('370', 'f', 'Other associated place', 'Other associated place', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10152         ('370', 'g', 'Place of origin of work', 'Place of origin of work', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10153         ('370', 's', 'Start period', 'Start period', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10154         ('370', 't', 'End period', 'End period', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10155         ('370', 'u', 'Uniform Resource Identifier', 'Uniform Resource Identifier', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10156         ('370', 'v', 'Source of information', 'Source of information', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10157         ('377', 'l', 'Language term', 'Language term', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10158         ('382', 's', 'Total number of performers', 'Total number of performers', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10159         ('388', '0', 'Authority record control number or standard number', 'Authority record control number or standard number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10160         ('388', '2', 'Source of term', 'Source of term', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10161         ('388', '3', ' Materials specified', ' Materials specified', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10162         ('388', '6', ' Linkage', ' Linkage', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10163         ('388', '8', 'Field link and sequence number', 'Field link and sequence number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10164         ('388', 'a', 'Time period of creation term', 'Time period of creation term', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10165         ('650', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, '', 6, '', '', '', 0, -1, '', '', '', NULL),
10166         ('651', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, '', 6, '', '', '', 0, -1, '', '', '', NULL);
10167     });
10168
10169     $dbh->do(q{
10170         UPDATE IGNORE marc_subfield_structure SET repeatable = 1 WHERE tagsubfield = 'g' AND
10171         tagfield IN ('100','110','111','130','240','243','246','247','600','610','611','630','700','710','711','730','800','810','811','830');
10172     });
10173     }
10174
10175     print "Upgrade to $DBversion done (Bug 13322: Update MARC21 frameworks to Update No. 19 - October 2014)\n";
10176     SetVersion($DBversion);
10177 }
10178
10179 $DBversion = '3.19.00.027';
10180 if ( CheckVersion($DBversion) ) {
10181     $dbh->do("ALTER TABLE items ADD COLUMN itemnotes_nonpublic MEDIUMTEXT AFTER itemnotes");
10182     $dbh->do("ALTER TABLE deleteditems ADD COLUMN itemnotes_nonpublic MEDIUMTEXT AFTER itemnotes");
10183     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";
10184     SetVersion($DBversion);
10185 }
10186
10187 $DBversion = "3.19.00.028";
10188 if( CheckVersion($DBversion) ) {
10189     eval {
10190         local $dbh->{PrintError} = 0;
10191         $dbh->do(q{
10192             ALTER TABLE issues DROP PRIMARY KEY
10193         });
10194     };
10195
10196     $dbh->do(q{
10197         ALTER TABLE old_issues ADD issue_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10198     });
10199
10200     $dbh->do(q{
10201         ALTER TABLE old_issues CHANGE issue_id issue_id INT( 11 ) NOT NULL
10202     });
10203
10204     $dbh->do(q{
10205         ALTER TABLE issues ADD issue_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10206     });
10207
10208     $dbh->do(q{
10209         UPDATE issues SET issue_id = issue_id + ( SELECT COUNT(*) FROM old_issues ) ORDER BY issue_id DESC
10210     });
10211
10212     my $max_issue_id = $schema->resultset('Issue')->get_column('issue_id')->max();
10213     if ($max_issue_id) {
10214         $max_issue_id++;
10215         $dbh->do(qq{
10216             ALTER TABLE issues AUTO_INCREMENT = $max_issue_id
10217         });
10218     }
10219
10220     print "Upgrade to $DBversion done (Bug 13790: Add unique id issue_id to issues and oldissues tables)\n";
10221     SetVersion($DBversion);
10222 }
10223
10224 $DBversion = "3.19.00.029";
10225 if ( CheckVersion($DBversion) ) {
10226     $dbh->do(q|
10227          ALTER TABLE sessions CHANGE COLUMN a_session a_session MEDIUMTEXT
10228     |);
10229     print "Upgrade to $DBversion done (Bug 13606: Upgrade sessions.a_session to MEDIUMTEXT)\n";
10230     SetVersion($DBversion);
10231 }
10232
10233 $DBversion = "3.19.00.030";
10234 if ( CheckVersion($DBversion) ) {
10235     $dbh->do(q|
10236 UPDATE language_subtag_registry SET subtag = 'kn' WHERE subtag = 'ka' AND description = 'Kannada';
10237     |);
10238     $dbh->do(q|
10239 UPDATE language_rfc4646_to_iso639 SET rfc4646_subtag = 'kn' WHERE rfc4646_subtag = 'ka' AND iso639_2_code = 'kan';
10240     |);
10241     $dbh->do(q|
10242 UPDATE language_descriptions SET subtag = 'kn', lang = 'kn' WHERE subtag = 'ka' AND lang = 'ka' AND description = 'ಕನ್ನಡ';
10243     |);
10244     $dbh->do(q|
10245 UPDATE language_descriptions SET subtag = 'kn' WHERE subtag = 'ka' AND description = 'Kannada';
10246     |);
10247     $dbh->do(q|
10248 INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ka', 'language', 'Georgian','2015-04-20');
10249     |);
10250     $dbh->do(q|
10251 DELETE FROM language_subtag_registry
10252        WHERE NOT id IN
10253          (SELECT id FROM
10254            (SELECT MIN(id) as id,subtag,type,description,added
10255             FROM language_subtag_registry
10256             GROUP BY subtag,type,description,added)
10257            AS subtable);
10258     |);
10259     $dbh->do(q|
10260 INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ka', 'geo');
10261     |);
10262     $dbh->do(q|
10263 DELETE FROM language_rfc4646_to_iso639
10264        WHERE NOT id IN
10265          (SELECT id FROM
10266            (SELECT MIN(id) as id,rfc4646_subtag,iso639_2_code
10267             FROM language_rfc4646_to_iso639
10268             GROUP BY rfc4646_subtag,iso639_2_code)
10269            AS subtable);
10270     |);
10271     $dbh->do(q|
10272 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'ka', 'ქართული');
10273     |);
10274     $dbh->do(q|
10275 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'en', 'Georgian');
10276     |);
10277     $dbh->do(q|
10278 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'fr', 'Géorgien');
10279     |);
10280     $dbh->do(q|
10281 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'de', 'Georgisch');
10282     |);
10283     $dbh->do(q|
10284 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'es', 'Georgiano');
10285     |);
10286     $dbh->do(q|
10287 DELETE FROM language_descriptions
10288        WHERE NOT id IN
10289          (SELECT id FROM
10290            (SELECT MIN(id) as id,subtag,type,lang,description
10291             FROM language_descriptions GROUP BY subtag,type,lang,description)
10292            AS subtable);
10293     |);
10294     print "Upgrade to $DBversion done (Bug 14030: Add Georgian language and fix Kannada language code)\n";
10295     SetVersion($DBversion);
10296 }
10297
10298 $DBversion = "3.19.00.031";
10299 if ( CheckVersion($DBversion) ) {
10300     $dbh->do(q{
10301         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10302         VALUES('IdRef','0','Disable/enable the IdRef webservice from the OPAC detail page.',NULL,'YesNo')
10303     });
10304     print "Upgrade to $DBversion done (Bug 8992: Add system preference IdRef))\n";
10305     SetVersion($DBversion);
10306 }
10307
10308 $DBversion = "3.19.00.032";
10309 if ( CheckVersion($DBversion) ) {
10310     $dbh->do(q|
10311         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10312         VALUES('AddressFormat','us','Choose format to display postal addresses','','Choice')
10313     |);
10314     print "Upgrade to $DBversion done (Bug 4041: Address Format as a I18N/L10N system preference\n";
10315     SetVersion ($DBversion);
10316 }
10317
10318 $DBversion = "3.19.00.033";
10319 if ( CheckVersion($DBversion) ) {
10320     $dbh->do(q|
10321         ALTER TABLE auth_header
10322         CHANGE COLUMN datemodified modification_time TIMESTAMP NOT NULL default CURRENT_TIMESTAMP
10323     |);
10324     $dbh->do(q|
10325         ALTER TABLE auth_header
10326         CHANGE COLUMN modification_time modification_time TIMESTAMP NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP
10327     |);
10328     print "Upgrade to $DBversion done (Bug 11165: Update auth_header.datemodified when updated)\n";
10329     SetVersion ($DBversion);
10330 }
10331
10332 $DBversion = "3.19.00.034";
10333 if ( CheckVersion($DBversion) ) {
10334     $dbh->do(q|
10335         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10336         VALUES('CardnumberLength', '', '', 'Set a length for card numbers.', 'Free')
10337     |);
10338     print "Upgrade to $DBversion done (Bug 13984: CardnumberLength syspref missing on some setups\n";
10339     SetVersion ($DBversion);
10340 }
10341
10342 $DBversion = "3.19.00.035";
10343 if ( CheckVersion($DBversion) ) {
10344     $dbh->do(q|
10345         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('useDischarge','','Allows librarians to discharge borrowers and borrowers to request a discharge','','YesNo')
10346     |);
10347     $dbh->do(q|
10348         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.')
10349     |);
10350
10351     $dbh->do(q|
10352         ALTER TABLE borrower_debarments CHANGE type type ENUM('SUSPENSION','OVERDUES','MANUAL','DISCHARGE') NOT NULL DEFAULT 'MANUAL'
10353     |);
10354
10355     $dbh->do(q|
10356         CREATE TABLE discharges (
10357           borrower int(11) DEFAULT NULL,
10358           needed timestamp NULL DEFAULT NULL,
10359           validated timestamp NULL DEFAULT NULL,
10360           KEY borrower_discharges_ibfk1 (borrower),
10361           CONSTRAINT borrower_discharges_ibfk1 FOREIGN KEY (borrower) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
10362         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
10363     |);
10364
10365     print "Upgrade to $DBversion done (Bug 8007: Add System Preferences useDischarge, the discharge notice and the new table discharges)\n";
10366     SetVersion($DBversion);
10367 }
10368
10369 $DBversion = "3.19.00.036";
10370 if ( CheckVersion($DBversion) ) {
10371     $dbh->do(q|
10372         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10373         VALUES ('CronjobLog','0',NULL,'If ON, log information from cron jobs.','YesNo')
10374     |);
10375     print "Upgrade to $DBversion done (Bug 13889: Add cron jobs information to system log)\n";
10376     SetVersion ($DBversion);
10377 }
10378
10379 $DBversion = "3.19.00.037";
10380 if ( CheckVersion($DBversion) ) {
10381     $dbh->do(q|
10382         ALTER TABLE marc_subfield_structure
10383         MODIFY COLUMN tagsubfield varchar(1) COLLATE utf8_bin NOT NULL DEFAULT ''
10384     |);
10385     print "Upgrade to $DBversion done (Bug 13810: Change collate for tagsubfield (utf8_bin))\n";
10386     SetVersion ($DBversion);
10387 }
10388
10389 $DBversion = "3.19.00.038";
10390 if ( CheckVersion($DBversion) ) {
10391     $dbh->do(q|
10392         ALTER TABLE virtualshelves
10393         ADD COLUMN created_on DATETIME NOT NULL AFTER lastmodified
10394     |);
10395     # Set created_on = lastmodified
10396     # I would say it's better than 0000-00-00
10397     # Set modified to the existing value (do not get the current ts!)
10398     $dbh->do(q|
10399         UPDATE virtualshelves
10400         SET created_on = lastmodified, lastmodified = lastmodified
10401     |);
10402     print "Upgrade to $DBversion done (Bug 13421: Add DB field virtualshelves.created_on)\n";
10403     SetVersion ($DBversion);
10404 }
10405
10406 $DBversion = "3.19.00.039";
10407 if ( CheckVersion($DBversion) ) {
10408     print "Upgrade to $DBversion done (Koha 3.20 beta)\n";
10409     SetVersion ($DBversion);
10410 }
10411
10412 $DBversion = "3.19.00.040";
10413 if ( CheckVersion($DBversion) ) {
10414     $dbh->do(q|
10415         ALTER TABLE aqorders DROP COLUMN totalamount
10416     |);
10417     print "Upgrade to $DBversion done (Bug 11006: Drop column aqorders.totalamount)\n";
10418     SetVersion ($DBversion);
10419 }
10420
10421 $DBversion = "3.19.00.041";
10422 if ( CheckVersion($DBversion) ) {
10423     unless ( index_exists( 'suggestions', 'status' ) ) {
10424         $dbh->do(q|
10425             ALTER TABLE suggestions ADD KEY status (STATUS)
10426         |);
10427     }
10428     unless ( index_exists( 'suggestions', 'biblionumber' ) ) {
10429         $dbh->do(q|
10430             ALTER TABLE suggestions ADD KEY biblionumber (biblionumber)
10431         |);
10432     }
10433     unless ( index_exists( 'suggestions', 'branchcode' ) ) {
10434         $dbh->do(q|
10435             ALTER TABLE suggestions ADD KEY branchcode (branchcode)
10436         |);
10437     }
10438     print "Upgrade to $DBversion done (Bug 14132: suggestions table is missing indexes)\n";
10439     SetVersion ($DBversion);
10440 }
10441
10442 $DBversion = "3.19.00.042";
10443 if ( CheckVersion($DBversion) ) {
10444     $dbh->do(q{
10445         DELETE ass.*
10446         FROM auth_subfield_structure AS ass
10447         LEFT JOIN auth_types USING(authtypecode)
10448         WHERE auth_types.authtypecode IS NULL
10449     });
10450
10451     unless ( foreign_key_exists( 'auth_subfield_structure', 'auth_subfield_structure_ibfk_1' ) ) {
10452         $dbh->do(q{
10453             ALTER TABLE auth_subfield_structure
10454             ADD CONSTRAINT auth_subfield_structure_ibfk_1
10455             FOREIGN KEY (authtypecode) REFERENCES auth_types(authtypecode)
10456             ON DELETE CASCADE ON UPDATE CASCADE
10457         });
10458     }
10459
10460     print "Upgrade to $DBversion done (Bug 8480: Add foreign key on auth_subfield_structure.authtypecode)\n";
10461     SetVersion($DBversion);
10462 }
10463
10464 $DBversion = "3.19.00.043";
10465 if ( CheckVersion($DBversion) ) {
10466     $dbh->do(q|
10467         INSERT IGNORE INTO authorised_values (category, authorised_value, lib) VALUES
10468         ('REPORT_GROUP', 'SER', 'Serials')
10469     |);
10470
10471     print "Upgrade to $DBversion done (Bug 5338: Add Serial to the report groups if does not exist)\n";
10472     SetVersion ($DBversion);
10473 }
10474
10475 $DBversion = "3.20.00.000";
10476 if ( CheckVersion($DBversion) ) {
10477     print "Upgrade to $DBversion done (Koha 3.20)\n";
10478     SetVersion ($DBversion);
10479 }
10480
10481 $DBversion = "3.21.00.000";
10482 if ( CheckVersion($DBversion) ) {
10483     print "Upgrade to $DBversion done (El tiempo vuela, un nuevo ciclo comienza.)\n";
10484     SetVersion ($DBversion);
10485 }
10486
10487 $DBversion = "3.21.00.001";
10488 if ( CheckVersion($DBversion) ) {
10489     $dbh->do(q|
10490         UPDATE systempreferences SET variable='IntranetUserJS' where variable='intranetuserjs'
10491     |);
10492     print "Upgrade to $DBversion done (Bug 12160: Rename intranetuserjs to IntranetUserJS)\n";
10493     SetVersion ($DBversion);
10494 }
10495
10496 $DBversion = "3.21.00.002";
10497 if ( CheckVersion($DBversion) ) {
10498     $dbh->do(q|
10499         UPDATE systempreferences SET variable='OPACUserJS' where variable='opacuserjs'
10500     |);
10501     print "Upgrade to $DBversion done (Bug 12160: Rename opacuserjs to OPACUserJS)\n";
10502     SetVersion ($DBversion);
10503 }
10504
10505 $DBversion = "3.21.00.003";
10506 if ( CheckVersion($DBversion) ) {
10507     $dbh->do(q|
10508         INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added)
10509         VALUES ( 'IN', 'region', 'India','2015-05-28');
10510     |);
10511     $dbh->do(q|
10512         INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)
10513         VALUES ( 'IN', 'region', 'en', 'India');
10514     |);
10515     $dbh->do(q|
10516         INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)
10517         VALUES ( 'IN', 'region', 'bn', 'ভারত');
10518     |);
10519     print "Upgrade to $DBversion done (Bug 14285: Add new region India)\n";
10520     SetVersion ($DBversion);
10521 }
10522
10523 $DBversion = '3.21.00.004';
10524 if ( CheckVersion($DBversion) ) {
10525     my $OPACBaseURL = C4::Context->preference('OPACBaseURL');
10526     if (defined($OPACBaseURL) && substr($OPACBaseURL,0,4) ne "http") {
10527         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.};
10528         $OPACBaseURL = 'http://' . $OPACBaseURL;
10529         my $sth_OPACBaseURL = $dbh->prepare( q{
10530             UPDATE systempreferences SET value=?,explanation=?
10531             WHERE variable='OPACBaseURL'; } );
10532         $sth_OPACBaseURL->execute($OPACBaseURL,$explanation);
10533     }
10534     if (defined($OPACBaseURL)) {
10535         $dbh->do( q{ UPDATE letter
10536                      SET content=replace(content,
10537                                          'http://<<OPACBaseURL>>',
10538                                          '<<OPACBaseURL>>')
10539                      WHERE content LIKE "%http://<<OPACBaseURL>>%"; } );
10540     }
10541
10542     print "Upgrade to $DBversion done (Bug 5010: Fix OPACBaseURL to include protocol)\n";
10543     SetVersion($DBversion);
10544 }
10545
10546 $DBversion = "3.21.00.005";
10547 if ( CheckVersion($DBversion) ) {
10548     $dbh->do(q|
10549         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10550         VALUES ('ReportsLog','0',NULL,'If ON, log information about reports.','YesNo')
10551     |);
10552     print "Upgrade to $DBversion done (Bug 14024: Add reports to action logs)\n";
10553     SetVersion ($DBversion);
10554 }
10555
10556 $DBversion = "3.21.00.006";
10557 if ( CheckVersion($DBversion) ) {
10558     # Remove the borrow permission flag (bit 7)
10559     $dbh->do(q|
10560         UPDATE borrowers
10561         SET flags = flags - ( flags & (1<<7) )
10562         WHERE flags IS NOT NULL
10563             AND flags > 0
10564     |);
10565     $dbh->do(q|
10566         DELETE FROM userflags WHERE bit=7;
10567     |);
10568     print "Upgrade to $DBversion done (Bug 7976: Remove the 'borrow' permission)\n";
10569     SetVersion($DBversion);
10570 }
10571
10572 $DBversion = "3.21.00.007";
10573 if ( CheckVersion($DBversion) ) {
10574     unless ( index_exists( 'aqbasket', 'authorisedby' ) ) {
10575         $dbh->do(q|
10576             ALTER TABLE aqbasket
10577                 ADD KEY authorisedby (authorisedby)
10578         |);
10579     }
10580     unless ( index_exists( 'aqbooksellers', 'name' ) ) {
10581         $dbh->do(q|
10582             ALTER TABLE aqbooksellers
10583                 ADD KEY name (name(255))
10584         |);
10585     }
10586     unless ( index_exists( 'aqbudgets', 'budget_parent_id' ) ) {
10587         $dbh->do(q|
10588             ALTER TABLE aqbudgets
10589                 ADD KEY budget_parent_id (budget_parent_id)|);
10590         }
10591     unless ( index_exists( 'aqbudgets', 'budget_code' ) ) {
10592         $dbh->do(q|
10593             ALTER TABLE aqbudgets
10594                 ADD KEY budget_code (budget_code)|);
10595     }
10596     unless ( index_exists( 'aqbudgets', 'budget_branchcode' ) ) {
10597         $dbh->do(q|
10598             ALTER TABLE aqbudgets
10599                 ADD KEY budget_branchcode (budget_branchcode)|);
10600     }
10601     unless ( index_exists( 'aqbudgets', 'budget_period_id' ) ) {
10602         $dbh->do(q|
10603             ALTER TABLE aqbudgets
10604                 ADD KEY budget_period_id (budget_period_id)|);
10605     }
10606     unless ( index_exists( 'aqbudgets', 'budget_owner_id' ) ) {
10607         $dbh->do(q|
10608             ALTER TABLE aqbudgets
10609                 ADD KEY budget_owner_id (budget_owner_id)|);
10610     }
10611     unless ( index_exists( 'aqbudgets_planning', 'budget_period_id' ) ) {
10612         $dbh->do(q|
10613             ALTER TABLE aqbudgets_planning
10614                 ADD KEY budget_period_id (budget_period_id)|);
10615     }
10616     unless ( index_exists( 'aqorders', 'parent_ordernumber' ) ) {
10617         $dbh->do(q|
10618             ALTER TABLE aqorders
10619                 ADD KEY parent_ordernumber (parent_ordernumber)|);
10620     }
10621     unless ( index_exists( 'aqorders', 'orderstatus' ) ) {
10622         $dbh->do(q|
10623             ALTER TABLE aqorders
10624                 ADD KEY orderstatus (orderstatus)|);
10625     }
10626     print "Upgrade to $DBversion done (Bug 14053: Acquisition db tables are missing indexes)\n";
10627     SetVersion ($DBversion);
10628 }
10629
10630 $DBversion = "3.21.00.008";
10631 if ( CheckVersion($DBversion) ) {
10632     $dbh->do(q{
10633         DELETE IGNORE FROM systempreferences
10634         WHERE variable = 'HomeOrHoldingBranchReturn';
10635     });
10636     print "Upgrade to $DBversion done (Bug 7981: Transfer message on return. HomeOrHoldingBranchReturn syspref removed in favour of circulation rules.)\n";
10637     SetVersion($DBversion);
10638 }
10639
10640 $DBversion = "3.21.00.009";
10641 if ( CheckVersion($DBversion) ) {
10642     eval {
10643         local $dbh->{PrintError} = 0;
10644         $dbh->do(q|
10645             UPDATE aqorders SET orderstatus='cancelled'
10646             WHERE (datecancellationprinted IS NOT NULL OR
10647                    datecancellationprinted<>'0000-00-00');
10648         |);
10649     };
10650     print "Upgrade to $DBversion done (Bug 13993: Correct orderstatus for transferred orders)\n";
10651     SetVersion($DBversion);
10652 }
10653
10654 $DBversion = "3.21.00.010";
10655 if ( CheckVersion($DBversion) ) {
10656     $dbh->do(q|
10657         ALTER TABLE message_queue
10658             DROP message_id
10659     |);
10660     $dbh->do(q|
10661         ALTER TABLE message_queue
10662             ADD message_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10663     |);
10664     print "Upgrade to $DBversion done (Bug 7793: redefine the field message_id as PRIMARY KEY of message_queue)\n";
10665     SetVersion ($DBversion);
10666 }
10667
10668 $DBversion = "3.21.00.011";
10669 if ( CheckVersion($DBversion) ) {
10670     $dbh->do(q{
10671         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10672         VALUES ('OpacLangSelectorMode','footer','top|both|footer','Select the location to display the language selector','Choice')
10673     });
10674     print "Upgrade to $DBversion done (Bug 14252: Make the OPAC language switcher available in the masthead navbar, footer, or both)\n";
10675     SetVersion ($DBversion);
10676 }
10677
10678 $DBversion = "3.21.00.012";
10679 if ( CheckVersion($DBversion) ) {
10680     $dbh->do(q|
10681         INSERT INTO letter (module, code, name, title, content, message_transport_type)
10682         VALUES
10683         ('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')
10684     |);
10685     print "Upgrade to $DBversion done (Bug 13014: Add the TO_PROCESS letter code)\n";
10686     SetVersion($DBversion);
10687 }
10688
10689 $DBversion = "3.21.00.013";
10690 if ( CheckVersion($DBversion) ) {
10691     my $msg;
10692     if ( C4::Context->preference('OPACPrivacy') ) {
10693         if ( my $anonymous_patron = C4::Context->preference('AnonymousPatron') ) {
10694             my $anonymous_patron_exists = $dbh->selectcol_arrayref(q|
10695                 SELECT COUNT(*)
10696                 FROM borrowers
10697                 WHERE borrowernumber=?
10698             |, {}, $anonymous_patron);
10699             unless ( $anonymous_patron_exists->[0] ) {
10700                 $msg = "Configuration WARNING: OPACPrivacy is set but AnonymousPatron is not linked to an existing patron";
10701             }
10702         }
10703         else {
10704             $msg = "Configuration WARNING: OPACPrivacy is set but AnonymousPatron is not";
10705         }
10706     }
10707     else {
10708         my $patrons_have_required_anonymity = $dbh->selectcol_arrayref(q|
10709             SELECT COUNT(*)
10710             FROM borrowers
10711             WHERE privacy = 2
10712         |, {} );
10713         if ( $patrons_have_required_anonymity->[0] ) {
10714             $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.";
10715         }
10716     }
10717
10718     $msg //= "Privacy is correctly set";
10719     print "Upgrade to $DBversion done (Bug 9942: $msg)\n";
10720     SetVersion ($DBversion);
10721 }
10722
10723 $DBversion = "3.21.00.014";
10724 if ( CheckVersion($DBversion) ) {
10725     $dbh->do(q{
10726         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10727         VALUES ('OAI-PMH:DeletedRecord','persistent','Koha\'s deletedbiblio table will never be deleted (persistent) or might be deleted (transient)','transient|persistent','Choice')
10728     });
10729
10730     if ( foreign_key_exists( 'oai_sets_biblios', 'oai_sets_biblios_ibfk_1' ) ) {
10731         $dbh->do(q|
10732             ALTER TABLE oai_sets_biblios DROP FOREIGN KEY oai_sets_biblios_ibfk_1
10733         |);
10734     }
10735     print "Upgrade to $DBversion done (Bug 3206: OAI repository deleted record support)\n";
10736     SetVersion ($DBversion);
10737 }
10738
10739 $DBversion = "3.21.00.015";
10740 if ( CheckVersion($DBversion) ) {
10741     $dbh->do(q{
10742         UPDATE systempreferences SET value='0' WHERE variable='CalendarFirstDayOfWeek' AND value='Sunday';
10743     });
10744     $dbh->do(q{
10745         UPDATE systempreferences SET value='1' WHERE variable='CalendarFirstDayOfWeek' AND value='Monday';
10746     });
10747     $dbh->do(q{
10748         UPDATE systempreferences SET options='0|1|2|3|4|5|6' WHERE variable='CalendarFirstDayOfWeek';
10749     });
10750
10751     print "Upgrade to $DBversion done (Bug 12137: Extend functionality of CalendarFirstDayOfWeek to be any day)\n";
10752     SetVersion($DBversion);
10753 }
10754
10755 $DBversion = "3.21.00.016";
10756 if ( CheckVersion($DBversion) ) {
10757     my $rs = $schema->resultset('Systempreference');
10758     $rs->find_or_create(
10759         {
10760             variable => 'DumpTemplateVarsIntranet',
10761             value    => 0,
10762             explanation => 'If enabled, dump all Template Toolkit variable to a comment in the html source for the staff intranet.',
10763             type => 'YesNo',
10764         }
10765     );
10766     $rs->find_or_create(
10767         {
10768             variable => 'DumpTemplateVarsOpac',
10769             value    => 0,
10770             explanation => 'If enabled, dump all Template Toolkit variable to a comment in the html source for the opac.',
10771             type => 'YesNo',
10772         }
10773     );
10774     print "Upgrade to $DBversion done (Bug 13948: Add ability to dump template toolkit variables to html comment)\n";
10775     SetVersion($DBversion);
10776 }
10777
10778 $DBversion = "3.21.00.017";
10779 if ( CheckVersion($DBversion) ) {
10780     $dbh->do("
10781         CREATE TABLE uploaded_files (
10782             id int(11) NOT NULL AUTO_INCREMENT,
10783             hashvalue CHAR(40) NOT NULL,
10784             filename TEXT NOT NULL,
10785             dir TEXT NOT NULL,
10786             filesize int(11),
10787             dtcreated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
10788             categorycode tinytext,
10789             owner int(11),
10790             PRIMARY KEY (id)
10791         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
10792     ");
10793
10794     print "Upgrade to $DBversion done (Bug 6874: New cataloging plugin upload.pl)\n";
10795     print "This plugin comes with a new config variable (upload_path) and a new table (uploaded_files)\n";
10796     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";
10797     SetVersion($DBversion);
10798 }
10799
10800 $DBversion = "3.21.00.018";
10801 if ( CheckVersion($DBversion) ) {
10802     $dbh->do(q{
10803         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10804         VALUES
10805             ('RestrictedPageLocalIPs','',NULL,'Beginning of IP addresses considered as local (comma separated ex: \"127.0.0,127.0.2\")','Free'),
10806             ('RestrictedPageContent','',NULL,'HTML content of the restricted page','TextArea'),
10807             ('RestrictedPageTitle','',NULL,'Title of the restricted page (breadcrumb and header)','Free')
10808     });
10809     print "Upgrade to $DBversion done (Bug 13485: Add a page to display links to restricted sites)\n";
10810     SetVersion ($DBversion);
10811 }
10812
10813 $DBversion = "3.21.00.019";
10814 if ( CheckVersion($DBversion) ) {
10815     if ( column_exists( 'reserves', 'constrainttype' ) ) {
10816         $dbh->do(q{
10817             ALTER TABLE reserves DROP constrainttype
10818         });
10819         $dbh->do(q{
10820             ALTER TABLE old_reserves DROP constrainttype
10821         });
10822     }
10823     $dbh->do(q{
10824         DROP TABLE IF EXISTS reserveconstraints
10825     });
10826     print "Upgrade to $DBversion done (Bug 9809: Get rid of reserveconstraints)\n";
10827     SetVersion ($DBversion);
10828 }
10829
10830 $DBversion = "3.21.00.020";
10831 if ( CheckVersion($DBversion) ) {
10832     $dbh->do(q{
10833         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`)
10834         VALUES ('FeeOnChangePatronCategory','1','','If set, when a patron changes to a category with enrolment fee, a fee is charged','YesNo')
10835     });
10836     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";
10837     SetVersion($DBversion);
10838 }
10839
10840 $DBversion = "3.21.00.021";
10841 if ( CheckVersion($DBversion) ) {
10842     $dbh->do(q{
10843         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10844         VALUES ('UseWYSIWYGinSystemPreferences','0','','Show WYSIWYG editor when editing certain HTML system preferences.','YesNo')
10845     });
10846     print "Upgrade to $DBversion done (Bug 11584: Add wysiwyg editor to system preferences dealing with HTML)\n";
10847     SetVersion($DBversion);
10848 }
10849
10850 $DBversion = "3.21.00.022";
10851 if ( CheckVersion($DBversion) ) {
10852     $dbh->do(q{
10853         DELETE cr.*
10854         FROM course_reserves AS cr
10855         LEFT JOIN course_items USING(ci_id)
10856         WHERE course_items.ci_id IS NULL
10857     });
10858
10859     my ($print_error) = $dbh->{PrintError};
10860     $dbh->{RaiseError} = 0;
10861     $dbh->{PrintError} = 0;
10862     if ( foreign_key_exists('course_reserves', 'course_reserves_ibfk_2') ) {
10863         $dbh->do(q{ALTER TABLE course_reserves DROP FOREIGN KEY course_reserves_ibfk_2});
10864         $dbh->do(q{ALTER TABLE course_reserves DROP INDEX course_reserves_ibfk_2});
10865     }
10866     $dbh->{PrintError} = $print_error;
10867
10868     $dbh->do(q{
10869         ALTER TABLE course_reserves
10870             ADD CONSTRAINT course_reserves_ibfk_2
10871                 FOREIGN KEY (ci_id) REFERENCES course_items (ci_id)
10872                 ON DELETE CASCADE ON UPDATE CASCADE
10873     });
10874     print "Upgrade to $DBversion done (Bug 14205: Deleting an Item/Record does not remove link to course reserve)\n";
10875     SetVersion($DBversion);
10876 }
10877
10878 $DBversion = "3.21.00.023";
10879 if ( CheckVersion($DBversion) ) {
10880     eval {
10881         local $dbh->{PrintError} = 0;
10882         $dbh->do(q{
10883             UPDATE borrowers SET debarred=NULL WHERE debarred='0000-00-00'
10884         });
10885         $dbh->do(q{
10886             UPDATE borrowers SET dateexpiry=NULL where dateexpiry='0000-00-00'
10887         });
10888         $dbh->do(q{
10889             UPDATE borrowers SET dateofbirth=NULL where dateofbirth='0000-00-00'
10890         });
10891         $dbh->do(q{
10892             UPDATE borrowers SET dateenrolled=NULL where dateenrolled='0000-00-00'
10893         });
10894     };
10895
10896     print "Upgrade to $DBversion done (Bug 14717: Prevent 0000-00-00 dates in patron data)\n";
10897     SetVersion($DBversion);
10898 }
10899
10900 $DBversion = "3.21.00.024";
10901 if ( CheckVersion($DBversion) ) {
10902     $dbh->do(q{
10903         ALTER TABLE marc_modification_template_actions
10904         MODIFY COLUMN action
10905             ENUM('delete_field','update_field','move_field','copy_field','copy_and_replace_field')
10906             NOT NULL
10907     });
10908     print "Upgrade to $DBversion done (Bug 14098: Regression in Marc Modification Templates)\n";
10909     SetVersion($DBversion);
10910 }
10911
10912 $DBversion = "3.21.00.025";
10913 if ( CheckVersion($DBversion) ) {
10914     $dbh->do(q{
10915         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10916         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')
10917     });
10918     $dbh->do(q{
10919         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10920         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')
10921     });
10922     print "Upgrade to $DBversion done (Bug 12357: Enhancements to RIS and BibTeX exporting)\n";
10923     SetVersion($DBversion);
10924 }
10925
10926 $DBversion = "3.21.00.026";
10927 if ( CheckVersion($DBversion) ) {
10928     $dbh->do(q{
10929         UPDATE matchpoints
10930         SET search_index='issn'
10931         WHERE matcher_id IN (SELECT matcher_id FROM marc_matchers WHERE code = 'ISSN')
10932     });
10933     print "Upgrade to $DBversion done (Bug 14472: Wrong ISSN search index in record matching rules)\n";
10934     SetVersion($DBversion);
10935 }
10936
10937 $DBversion = "3.21.00.027";
10938 if ( CheckVersion($DBversion) ) {
10939     $dbh->do(q|
10940         INSERT IGNORE INTO permissions (module_bit, code, description)
10941         VALUES (1, 'self_checkout', 'Perform self checkout at the OPAC. It should be used for the patron matching the AutoSelfCheckID')
10942     |);
10943
10944     my $AutoSelfCheckID = C4::Context->preference('AutoSelfCheckID');
10945
10946     $dbh->do(q|
10947         UPDATE borrowers
10948         SET flags=0
10949         WHERE userid=?
10950     |, undef, $AutoSelfCheckID);
10951
10952     $dbh->do(q|
10953         DELETE FROM user_permissions
10954         WHERE borrowernumber=(SELECT borrowernumber FROM borrowers WHERE userid=?)
10955     |, undef, $AutoSelfCheckID);
10956
10957     $dbh->do(q|
10958         INSERT INTO user_permissions(borrowernumber, module_bit, code)
10959         SELECT borrowernumber, 1, 'self_checkout' FROM borrowers WHERE userid=?
10960     |, undef, $AutoSelfCheckID);
10961     print "Upgrade to $DBversion done (Bug 14298: AutoSelfCheckID user should only be able to access SCO)\n";
10962     SetVersion($DBversion);
10963 }
10964
10965 $DBversion = "3.21.00.028";
10966 if ( CheckVersion($DBversion) ) {
10967     unless ( column_exists('uploaded_files', 'public') ) {
10968         $dbh->do(q{
10969             ALTER TABLE uploaded_files
10970                 ADD COLUMN public tinyint,
10971                 ADD COLUMN permanent tinyint
10972         });
10973         $dbh->do(q{
10974             UPDATE uploaded_files SET public=1, permanent=1
10975         });
10976         $dbh->do(q{
10977             ALTER TABLE uploaded_files
10978                 CHANGE COLUMN categorycode uploadcategorycode tinytext
10979         });
10980     }
10981     print "Upgrade to $DBversion done (Bug 14321: Merge UploadedFile and UploadedFiles into Koha::Upload)\n";
10982     SetVersion($DBversion);
10983 }
10984
10985 $DBversion = "3.21.00.029";
10986 if ( CheckVersion($DBversion) ) {
10987     unless ( column_exists('discharges', 'discharge_id') ) {
10988         $dbh->do(q{
10989             ALTER TABLE discharges
10990                 ADD COLUMN discharge_id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10991         });
10992     }
10993     print "Upgrade to $DBversion done (Bug 14368: Add discharges history)\n";
10994     SetVersion($DBversion);
10995 }
10996
10997 $DBversion = "3.21.00.030";
10998 if ( CheckVersion($DBversion) ) {
10999     $dbh->do(q{
11000         UPDATE marc_subfield_structure
11001         SET value_builder='marc21_leader.pl'
11002         WHERE value_builder='marc21_leader_book.pl'
11003     });
11004     $dbh->do(q{
11005         UPDATE marc_subfield_structure
11006         SET value_builder='marc21_leader.pl'
11007         WHERE value_builder='marc21_leader_computerfile.pl'
11008     });
11009     $dbh->do(q{
11010         UPDATE marc_subfield_structure
11011         SET value_builder='marc21_leader.pl'
11012         WHERE value_builder='marc21_leader_video.pl'
11013     });
11014     print "Upgrade to $DBversion done (Bug 14201: Remove unused code or template from some MARC21 leader plugins )\n";
11015     SetVersion($DBversion);
11016 }
11017
11018 $DBversion = "3.21.00.031";
11019 if ( CheckVersion($DBversion) ) {
11020     $dbh->do(q{
11021         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
11022         VALUES
11023             ('SMSSendPassword', '', '', 'Password used to send SMS messages', 'free'),
11024             ('SMSSendUsername', '', '', 'Username/Login used to send SMS messages', 'free')
11025     });
11026     print "Upgrade to $DBversion done (Bug 14820: SMSSendUsername and SMSSendPassword are not listed in the system preferences)\n";
11027     SetVersion($DBversion);
11028 }
11029
11030 $DBversion = "3.21.00.032";
11031 if ( CheckVersion($DBversion) ) {
11032     $dbh->do(q{
11033         CREATE TABLE additional_fields (
11034             id int(11) NOT NULL AUTO_INCREMENT,
11035             tablename varchar(255) NOT NULL DEFAULT '',
11036             name varchar(255) NOT NULL DEFAULT '',
11037             authorised_value_category varchar(16) NOT NULL DEFAULT '',
11038             marcfield varchar(16) NOT NULL DEFAULT '',
11039             searchable tinyint(1) NOT NULL DEFAULT '0',
11040             PRIMARY KEY (id),
11041             UNIQUE KEY fields_uniq (tablename,name)
11042         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
11043     });
11044     $dbh->do(q{
11045         CREATE TABLE additional_field_values (
11046             id int(11) NOT NULL AUTO_INCREMENT,
11047             field_id int(11) NOT NULL,
11048             record_id int(11) NOT NULL,
11049             value varchar(255) NOT NULL DEFAULT '',
11050             PRIMARY KEY (id),
11051             UNIQUE KEY field_record (field_id,record_id),
11052             CONSTRAINT afv_fk FOREIGN KEY (field_id) REFERENCES additional_fields (id) ON DELETE CASCADE ON UPDATE CASCADE
11053         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
11054     });
11055     print "Upgrade to $DBversion done (Bug 10855: Additional fields for subscriptions)\n";
11056     SetVersion($DBversion);
11057 }
11058
11059 $DBversion = "3.21.00.033";
11060 if ( CheckVersion($DBversion) ) {
11061
11062     my $done = 0;
11063     my $count_ethnicity = $dbh->selectrow_arrayref(q|
11064         SELECT COUNT(*) FROM ethnicity
11065     |);
11066     my $count_borrower_modifications = $dbh->selectrow_arrayref(q|
11067         SELECT COUNT(*)
11068         FROM borrower_modifications
11069         WHERE ethnicity IS NOT NULL
11070             OR ethnotes IS NOT NULL
11071     |);
11072     my $count_borrowers = $dbh->selectrow_arrayref(q|
11073         SELECT COUNT(*)
11074         FROM borrowers
11075         WHERE ethnicity IS NOT NULL
11076             OR ethnotes IS NOT NULL
11077     |);
11078     # We don't care about the ethnicity of the deleted borrowers, right?
11079     if ( $count_ethnicity->[0] == 0
11080             and $count_borrower_modifications->[0] == 0
11081             and $count_borrowers->[0] == 0
11082     ) {
11083         $dbh->do(q|
11084             DROP TABLE ethnicity
11085         |);
11086         $dbh->do(q|
11087             ALTER TABLE borrower_modifications
11088             DROP COLUMN ethnicity,
11089             DROP COLUMN ethnotes
11090         |);
11091         $dbh->do(q|
11092             ALTER TABLE borrowers
11093             DROP COLUMN ethnicity,
11094             DROP COLUMN ethnotes
11095         |);
11096         $dbh->do(q|
11097             ALTER TABLE deletedborrowers
11098             DROP COLUMN ethnicity,
11099             DROP COLUMN ethnotes
11100         |);
11101         $done = 1;
11102     }
11103     if ( $done ) {
11104         print "Upgrade to $DBversion done (Bug 10020: Drop table ethnicity and columns ethnicity and ethnotes)\n";
11105     }
11106     else {
11107         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";
11108     }
11109
11110     SetVersion ($DBversion);
11111 }
11112
11113 $DBversion = "3.21.00.034";
11114 if ( CheckVersion($DBversion) ) {
11115     $dbh->do(q{
11116         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11117         VALUES('MembershipExpiryDaysNotice',NULL,'Send an account expiration notice that a patron''s card is about to expire after',NULL,'Integer')
11118     });
11119     $dbh->do(q{
11120         INSERT IGNORE INTO letter (module, code, branchcode, name, title, content, message_transport_type)
11121         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')
11122     });
11123     print "Upgrade to $DBversion done (Bug 6810: Send membership expiry reminder notices)\n";
11124     SetVersion($DBversion);
11125 }
11126
11127 $DBversion = "3.21.00.035";
11128 if ( CheckVersion($DBversion) ) {
11129     $dbh->do(q|
11130         ALTER TABLE branch_borrower_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11131     |);
11132     $dbh->do(q|
11133         UPDATE branch_borrower_circ_rules SET maxonsiteissueqty = maxissueqty;
11134     |);
11135     $dbh->do(q|
11136         ALTER TABLE default_borrower_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11137     |);
11138     $dbh->do(q|
11139         UPDATE default_borrower_circ_rules SET maxonsiteissueqty = maxissueqty;
11140     |);
11141     $dbh->do(q|
11142         ALTER TABLE default_branch_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11143     |);
11144     $dbh->do(q|
11145         UPDATE default_branch_circ_rules SET maxonsiteissueqty = maxissueqty;
11146     |);
11147     $dbh->do(q|
11148         ALTER TABLE default_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11149     |);
11150     $dbh->do(q|
11151         UPDATE default_circ_rules SET maxonsiteissueqty = maxissueqty;
11152     |);
11153     $dbh->do(q|
11154         ALTER TABLE issuingrules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11155     |);
11156     $dbh->do(q|
11157         UPDATE issuingrules SET maxonsiteissueqty = maxissueqty;
11158     |);
11159     $dbh->do(q|
11160         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11161         VALUES ('ConsiderOnSiteCheckoutsAsNormalCheckouts','1',NULL,'Consider on-site checkouts as normal checkouts','YesNo');
11162     |);
11163
11164     print "Upgrade to $DBversion done (Bug 14045: Add DB fields maxonsiteissueqty and pref ConsiderOnSiteCheckoutsAsNormalCheckouts)\n";
11165     SetVersion ($DBversion);
11166 }
11167
11168 $DBversion = "3.21.00.036";
11169 if ( CheckVersion($DBversion) ) {
11170    $dbh->do(q{
11171         ALTER TABLE authorised_values_branches
11172         DROP FOREIGN KEY authorised_values_branches_ibfk_1,
11173         DROP FOREIGN KEY authorised_values_branches_ibfk_2
11174     });
11175     $dbh->do(q{
11176         ALTER TABLE authorised_values_branches
11177         MODIFY av_id INT( 11 ) NOT NULL,
11178         MODIFY branchcode VARCHAR( 10 ) NOT NULL,
11179         ADD FOREIGN KEY (`av_id`) REFERENCES `authorised_values` (`id`) ON DELETE CASCADE,
11180         ADD FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE
11181    });
11182    print "Upgrade to $DBversion done (Bug 10363: There is no package for authorised values)\n";
11183    SetVersion($DBversion);
11184 }
11185
11186 $DBversion = "3.21.00.037";
11187 if ( CheckVersion($DBversion) ) {
11188    $dbh->do(q{
11189        INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11190        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')
11191    });
11192    $dbh->do(q{
11193        INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11194        VALUES ('RestrictionBlockRenewing','0','If patron is restricted, should renewal be allowed or blocked',NULL,'YesNo')
11195     });
11196    print "Upgrade to $DBversion done (Bug 8236: Prevent renewing if overdue or restriction)\n";
11197    SetVersion($DBversion);
11198 }
11199
11200 $DBversion = "3.21.00.038";
11201 if ( CheckVersion($DBversion) ) {
11202     $dbh->do(q|
11203         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11204         VALUES ('BatchCheckouts','0','','Enable or disable batch checkouts','YesNo')
11205     |);
11206     $dbh->do(q|
11207         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11208         VALUES ('BatchCheckoutsValidCategories','',NULL,'Patron categories allowed to checkout in a batch','Free')
11209     |);
11210     print "Upgrade to $DBversion done (Bug 11759: Add the batch checkout feature)\n";
11211     SetVersion($DBversion);
11212 }
11213
11214 $DBversion = "3.21.00.039";
11215 if ( CheckVersion($DBversion) ) {
11216     $dbh->do(q|
11217         ALTER TABLE creator_layouts ADD COLUMN oblique_title INT(1) NULL DEFAULT 1 AFTER guidebox
11218     |);
11219     print "Upgrade to $DBversion done (Bug 12194: Add column oblique_title to layouts)\n";
11220     SetVersion($DBversion);
11221 }
11222
11223 $DBversion = "3.21.00.040";
11224 if ( CheckVersion($DBversion) ) {
11225     $dbh->do(q{
11226         ALTER TABLE itemtypes
11227             ADD hideinopac TINYINT(1) NOT NULL DEFAULT 0
11228               AFTER sip_media_type,
11229             ADD searchcategory VARCHAR(80) DEFAULT NULL
11230               AFTER hideinopac;
11231     });
11232     print "Upgrade to $DBversion done (Bug 10937: Option to hide and group itemtypes from advanced search)\n";
11233     SetVersion($DBversion);
11234 }
11235
11236 $DBversion = "3.21.00.041";
11237 if ( CheckVersion($DBversion) ) {
11238     $dbh->do(q|
11239         ALTER TABLE issuingrules
11240             ADD chargeperiod_charge_at BOOLEAN NOT NULL DEFAULT  '0' AFTER chargeperiod
11241     |);
11242     print "Upgrade to $DBversion done (Bug 13590: Add ability to charge fines at start of charge period)\n";
11243     SetVersion($DBversion);
11244 }
11245
11246 $DBversion = "3.21.00.042";
11247 if ( CheckVersion($DBversion) ) {
11248     $dbh->do(q|
11249         ALTER TABLE items_search_fields
11250             MODIFY COLUMN authorised_values_category VARCHAR(32) DEFAULT NULL
11251     |);
11252     print "Upgrade to $DBversion done (Bug 15069: items_search_fields.authorised_values_category is still a varchar(32))\n";
11253     SetVersion($DBversion);
11254 }
11255
11256 $DBversion = "3.21.00.043";
11257 if ( CheckVersion($DBversion) ) {
11258     $dbh->do(q|
11259         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11260         VALUES ('EnableAdvancedCatalogingEditor','0','','Enable the Rancor advanced cataloging editor','YesNo')
11261     |);
11262     print "Upgrade to $DBversion done (Bug 11559: Professional cataloger's interface)\n";
11263     SetVersion($DBversion);
11264 }
11265
11266 $DBversion = "3.21.00.044";
11267 if ( CheckVersion($DBversion) ) {
11268     $dbh->do(q|
11269         CREATE TABLE localization (
11270             localization_id int(11) NOT NULL AUTO_INCREMENT,
11271             entity varchar(16) COLLATE utf8_unicode_ci NOT NULL,
11272             code varchar(64) COLLATE utf8_unicode_ci NOT NULL,
11273             lang varchar(25) COLLATE utf8_unicode_ci NOT NULL,
11274             translation text COLLATE utf8_unicode_ci,
11275             PRIMARY KEY (localization_id),
11276             UNIQUE KEY entity_code_lang (entity,code,lang)
11277         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
11278     |);
11279     print "Upgrade to $DBversion done (Bug 14100: Generic solution for language overlay)\n";
11280     SetVersion($DBversion);
11281 }
11282
11283 $DBversion = "3.21.00.045";
11284 if ( CheckVersion($DBversion) ) {
11285     $dbh->do(q|
11286         ALTER TABLE opac_news
11287             ADD borrowernumber int(11) default NULL
11288                 AFTER number
11289     |);
11290     $dbh->do(q|
11291         ALTER TABLE opac_news
11292             ADD CONSTRAINT borrowernumber_fk
11293                 FOREIGN KEY (borrowernumber)
11294                 REFERENCES borrowers (borrowernumber)
11295                 ON DELETE SET NULL ON UPDATE CASCADE
11296     |);
11297     print "Upgrade to $DBversion done (Bug 14246: (newsauthor) Add borrowernumber to koha_news)\n";
11298     SetVersion($DBversion);
11299 }
11300
11301 $DBversion = "3.21.00.046";
11302 if ( CheckVersion($DBversion) ) {
11303     $dbh->do(q{
11304         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11305         VALUES ('NewsAuthorDisplay','none','none|opac|staff|both','Display the author name for news items.','Choice')
11306     });
11307     print "Upgrade to $DBversion done (Bug 14247: (newsauthor) System preference for news author display)\n";
11308     SetVersion($DBversion);
11309 }
11310
11311 $DBversion = "3.21.00.047";
11312 if(CheckVersion($DBversion)) {
11313     $dbh->do(q{
11314         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11315         VALUES ('IndependentBranchesPatronModifications','0','Show only modification request for the logged in branch','','YesNo')
11316     });
11317     print "Upgrade to $DBversion done (Bug 10904: Limit patron update request management by branch)\n";
11318     SetVersion($DBversion);
11319 }
11320
11321 $DBversion = '3.21.00.048';
11322 if ( CheckVersion($DBversion) ) {
11323     my $create_table_issues = @{ $dbh->selectall_arrayref(q|SHOW CREATE TABLE issues|) }[0]->[1];
11324     if ($create_table_issues !~ m|UNIQUE KEY.*itemnumber| ) {
11325         $dbh->do(q|ALTER TABLE issues ADD CONSTRAINT UNIQUE KEY (itemnumber)|);
11326     }
11327     print "Upgrade to $DBversion done (Bug 14978: Make sure issues.itemnumber is a unique key)\n";
11328     SetVersion($DBversion);
11329 }
11330
11331 $DBversion = "3.21.00.049";
11332 if ( CheckVersion($DBversion) ) {
11333     $dbh->do(q{UPDATE systempreferences SET variable = 'AudioAlerts' WHERE variable = 'soundon'});
11334
11335     $dbh->do(q{
11336         CREATE TABLE audio_alerts (
11337             id int(11) NOT NULL AUTO_INCREMENT,
11338             precedence smallint(5) unsigned NOT NULL,
11339             selector varchar(255) NOT NULL,
11340             sound varchar(255) NOT NULL,
11341             PRIMARY KEY (id),
11342             KEY precedence (precedence)
11343         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
11344     });
11345
11346     $dbh->do(q{
11347         INSERT IGNORE INTO audio_alerts VALUES
11348         (1, 1, '.audio-alert-action', 'opening.ogg'),
11349         (2, 2, '.audio-alert-warning', 'critical.ogg'),
11350         (3, 3, '.audio-alert-success', 'beep.ogg');
11351     });
11352
11353     print "Upgrade to $DBversion done (Bug 11431: Add additional sound options for warnings)\n";
11354     SetVersion($DBversion);
11355 }
11356
11357 $DBversion = "3.21.00.050";
11358 if(CheckVersion($DBversion)) {
11359     $dbh->do(q{
11360         INSERT INTO letter ( module, code, branchcode, name, is_html, title, content, message_transport_type )
11361         VALUES ( 'circulation', 'OVERDUES_SLIP', '', 'Overdues Slip', '0', 'OVERDUES_SLIP', 'The following item(s) is/are currently overdue:
11362
11363 <item>"<<biblio.title>>" by <<biblio.author>>, <<items.itemcallnumber>>, Barcode: <<items.barcode>> Fine: <<items.fine>></item>
11364 ', 'print' )
11365     });
11366     print "Upgrade to $DBversion done (Bug 12933: Add ability to print overdue slip from staff intranet)\n";
11367     SetVersion($DBversion);
11368 }
11369
11370 $DBversion = "3.21.00.051";
11371 if ( CheckVersion($DBversion) ) {
11372     $dbh->do(q{
11373         ALTER TABLE virtualshelves
11374             CHANGE COLUMN sortfield sortfield VARCHAR(16) DEFAULT 'title'
11375     });
11376     $dbh->do(q{
11377         UPDATE virtualshelves
11378         SET sortfield='title'
11379             WHERE sortfield IS NULL;
11380     });
11381     print "Upgrade to $DBversion done (Bug 14544: Move the list related code to Koha::Virtualshelves)\n";
11382     SetVersion($DBversion);
11383 }
11384
11385 $DBversion = "3.21.00.052";
11386 if ( CheckVersion($DBversion) ) {
11387     $dbh->do(q{
11388         ALTER TABLE serial
11389             ADD COLUMN publisheddatetext VARCHAR(100) DEFAULT NULL AFTER publisheddate
11390     });
11391     print "Upgrade to $DBversion done (Bug 8296: Add descriptive (text) published date field for serials)\n";
11392     SetVersion($DBversion);
11393 }
11394
11395 $DBversion = "3.21.00.053";
11396 if ( CheckVersion($DBversion) ) {
11397     my $query = q{ SELECT * FROM itemtypes ORDER BY description };
11398     my $sth   = C4::Context->dbh->prepare($query);
11399     $sth->execute;
11400     my $suggestion_formats = $sth->fetchall_arrayref( {} );
11401
11402     foreach my $format (@$suggestion_formats) {
11403         $dbh->do(
11404             q|
11405             INSERT IGNORE INTO authorised_values (category, authorised_value, lib, lib_opac, imageurl)
11406             VALUES (?, ?, ?, ?, ?)
11407         |, {},
11408             'SUGGEST_FORMAT', $format->{itemtype}, $format->{description}, $format->{description},
11409             $format->{imageurl}
11410         );
11411     }
11412     print "Upgrade to $DBversion done (Bug 9468: create new SUGGEST_FORMAT authorised_value list)\n";
11413     SetVersion($DBversion);
11414 }
11415
11416 $DBversion = "3.21.00.054";
11417 if(CheckVersion($DBversion)) {
11418     $dbh->do(q{
11419         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11420         VALUES('MergeReportFields','','Displayed fields for deleted MARC records after merge',NULL,'Free')
11421     });
11422     print "Upgrade to $DBversion done (Bug 8064: Merge several biblio records)\n";
11423     SetVersion($DBversion);
11424 }
11425
11426 $DBversion = "3.21.00.055";
11427 if ( CheckVersion($DBversion) ) {
11428     print "Upgrade to $DBversion done (Koha 3.22 beta)\n";
11429     SetVersion($DBversion);
11430 }
11431
11432 $DBversion = "3.21.00.056";
11433 if(CheckVersion($DBversion)) {
11434     $dbh->do(q{
11435         UPDATE systempreferences
11436         SET
11437             options='metric|us|iso|dmydot',
11438             explanation='Define global date format (us mm/dd/yyyy, metric dd/mm/yyy, ISO yyyy-mm-dd, DMY separated by dots dd.mm.yyyy)'
11439         WHERE variable='dateformat'
11440     });
11441     print "Upgrade to $DBversion done (Bug 12072: New dateformat dd.mm.yyyy)\n";
11442     SetVersion($DBversion);
11443 }
11444
11445 $DBversion = "3.22.00.000";
11446 if ( CheckVersion($DBversion) ) {
11447     print "Upgrade to $DBversion done (Koha 3.22)\n";
11448     SetVersion($DBversion);
11449 }
11450
11451 $DBversion = "3.23.00.000";
11452 if ( CheckVersion($DBversion) ) {
11453     print "Upgrade to $DBversion done (The year of the monkey will be here soon.)\n";
11454     SetVersion ($DBversion);
11455 }
11456
11457 $DBversion = "3.23.00.001";
11458 if(CheckVersion($DBversion)) {
11459     $dbh->do(q{
11460         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11461         VALUES (
11462             'DefaultToLoggedInLibraryCircRules',  '0', NULL ,  'If enabled, circ rules editor will default to the logged in library''s rules, rather than the ''all libraries'' rules.',  'YesNo'
11463         ), (
11464             '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'
11465         )
11466     });
11467
11468     print "Upgrade to $DBversion done (Bug 11625 - Add pref DefaultToLoggedInLibraryCircRules and DefaultToLoggedInLibraryNoticesSlips)\n";
11469     SetVersion($DBversion);
11470 }
11471
11472 $DBversion = "3.23.00.002";
11473 if(CheckVersion($DBversion)) {
11474     $dbh->do(q{
11475         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11476         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')
11477     });
11478
11479     print "Upgrade to $DBversion done (Bug 11747 - add pref DefaultToLoggedInLibraryOverdueTriggers)\n";
11480     SetVersion($DBversion);
11481 }
11482
11483 $DBversion = "3.23.00.003";
11484 if(CheckVersion($DBversion)) {
11485     $dbh->do(q{
11486         UPDATE letter SET name = "Hold Slip" WHERE name = "Reserve Slip"
11487     });
11488     $dbh->do(q{
11489         UPDATE letter SET title = "Hold Slip" WHERE title = "Reserve Slip";
11490     });
11491
11492     print "Upgrade to $DBversion done (Bug 8085 - Rename 'Reserve slip' to 'Hold slip')\n";
11493     SetVersion($DBversion);
11494 }
11495
11496 $DBversion = "3.23.00.004";
11497 if ( CheckVersion($DBversion) ) {
11498     $dbh->do(q{
11499         DROP TABLE IF EXISTS `stopwords`;
11500     });
11501     print "Upgrade to $DBversion done (Bug 9819 - stopwords related code should be removed)\n";
11502     SetVersion($DBversion);
11503 }
11504
11505 $DBversion = "3.23.00.005";
11506 if ( CheckVersion($DBversion) ) {
11507     $dbh->do(q{
11508         UPDATE permissions SET description = 'Manage circulation rules' WHERE description = 'manage circulation rules'
11509     });
11510     $dbh->do(q{
11511         UPDATE permissions SET description = 'Manage staged MARC records, including completing and reversing imports' WHERE description = 'Managed staged MARC records, including completing and reversing imports'
11512     });
11513     print "Upgrade to $DBversion done (Bug 11569 - Typo in userpermissions.sql)\n";
11514     SetVersion($DBversion);
11515 }
11516 $DBversion = "3.23.00.006";
11517 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
11518    $dbh->do("
11519        ALTER TABLE serial
11520         ADD serialseq_x VARCHAR( 100 ) NULL DEFAULT NULL AFTER serialseq,
11521         ADD serialseq_y VARCHAR( 100 ) NULL DEFAULT NULL AFTER serialseq_x,
11522         ADD serialseq_z VARCHAR( 100 ) NULL DEFAULT NULL AFTER serialseq_y
11523    ");
11524
11525     my $sth = $dbh->prepare("SELECT * FROM subscription");
11526     $sth->execute();
11527
11528     my $sth2 = $dbh->prepare("SELECT * FROM subscription_numberpatterns WHERE id = ?");
11529
11530     my $sth3 = $dbh->prepare("UPDATE serial SET serialseq_x = ?, serialseq_y = ?, serialseq_z = ? WHERE serialid = ?");
11531
11532     foreach my $subscription ( $sth->fetchrow_hashref() ) {
11533         next if !defined($subscription);
11534         $sth2->execute( $subscription->{numberpattern} );
11535         my $number_pattern = $sth2->fetchrow_hashref();
11536
11537         my $numbering_method = $number_pattern->{numberingmethod};
11538         # Get all the data between the enumeration values, we need
11539         # to split each enumeration string based on these values.
11540         my @splits = split( /\{[XYZ]\}/, $numbering_method );
11541         # Get the order in which the X Y and Z values are used
11542         my %indexes;
11543         foreach my $i (qw(X Y Z)) {
11544             $indexes{$i} = index( $numbering_method, "{$i}" );
11545             delete $indexes{$i} if $indexes{$i} == -1;
11546         }
11547         my @indexes = sort { $indexes{$a} <=> $indexes{$b} } keys(%indexes);
11548
11549         my @serials = @{
11550             $dbh->selectall_arrayref(
11551                 "SELECT * FROM serial WHERE subscriptionid = $subscription->{subscriptionid}",
11552                 { Slice => {} }
11553             )
11554         };
11555
11556         foreach my $serial (@serials) {
11557             my $serialseq = $serial->{serialseq};
11558             my %enumeration_data;
11559
11560             ## We cannot split on multiple values at once,
11561             ## so let's replace each of those values with __SPLIT__
11562             if (@splits) {
11563                 for my $split_item (@splits) {
11564                     my $quoted_split = quotemeta($split_item);
11565                     $serialseq =~ s/$quoted_split/__SPLIT__/;
11566                 }
11567                 (
11568                     undef,
11569                     $enumeration_data{ $indexes[0] // q{} },
11570                     $enumeration_data{ $indexes[1] // q{} },
11571                     $enumeration_data{ $indexes[2] // q{} }
11572                 ) = split( /__SPLIT__/, $serialseq );
11573             }
11574             else
11575             {    ## Nothing to split on means the only thing in serialseq is a single placeholder e.g. {X}
11576                 $enumeration_data{ $indexes[0] } = $serialseq;
11577             }
11578
11579             $sth3->execute(
11580                     $enumeration_data{'X'},
11581                     $enumeration_data{'Y'},
11582                     $enumeration_data{'Z'},
11583                     $serial->{serialid},
11584             );
11585         }
11586     }
11587
11588     print "Upgrade to $DBversion done ( Bug 8956 - Split serials enumeration data into separate fields )\n";
11589     SetVersion($DBversion);
11590 }
11591
11592 $DBversion = "3.23.00.007";
11593 if ( CheckVersion($DBversion) ) {
11594     $dbh->do("SET FOREIGN_KEY_CHECKS=0");
11595     $dbh->do("ALTER TABLE overduerules RENAME old_overduerules");
11596     $dbh->do("CREATE TABLE overduerules (
11597         `overduerules_id` int(11) NOT NULL AUTO_INCREMENT,
11598         `branchcode` varchar(10) NOT NULL DEFAULT '',
11599         `categorycode` varchar(10) NOT NULL DEFAULT '',
11600         `delay1` int(4) DEFAULT NULL,
11601         `letter1` varchar(20) DEFAULT NULL,
11602         `debarred1` varchar(1) DEFAULT '0',
11603         `delay2` int(4) DEFAULT NULL,
11604         `debarred2` varchar(1) DEFAULT '0',
11605         `letter2` varchar(20) DEFAULT NULL,
11606         `delay3` int(4) DEFAULT NULL,
11607         `letter3` varchar(20) DEFAULT NULL,
11608         `debarred3` int(1) DEFAULT '0',
11609         PRIMARY KEY (`overduerules_id`),
11610         UNIQUE KEY `overduerules_branch_cat` (`branchcode`,`categorycode`)
11611         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
11612     $dbh->do("INSERT INTO overduerules(branchcode, categorycode, delay1, letter1, debarred1, delay2, debarred2, letter2, delay3, letter3, debarred3) SELECT * FROM old_overduerules");
11613     $dbh->do("DROP TABLE old_overduerules");
11614     $dbh->do("ALTER TABLE overduerules_transport_types
11615               ADD COLUMN overduerules_id int(11) NOT NULL");
11616     my $mtts = $dbh->selectall_arrayref("SELECT * FROM overduerules_transport_types", { Slice => {} });
11617     $dbh->do("DELETE FROM overduerules_transport_types");
11618     $dbh->do("ALTER TABLE overduerules_transport_types
11619               DROP FOREIGN KEY overduerules_fk,
11620               ADD FOREIGN KEY overduerules_transport_types_fk (overduerules_id) REFERENCES overduerules (overduerules_id) ON DELETE CASCADE ON UPDATE CASCADE,
11621               DROP COLUMN branchcode,
11622               DROP COLUMN categorycode");
11623     my $s = $dbh->prepare("INSERT INTO overduerules_transport_types (overduerules_id, id, letternumber, message_transport_type) "
11624                          ." VALUES((SELECT overduerules_id FROM overduerules WHERE branchcode = ? AND categorycode = ?),?,?,?)");
11625     foreach my $mtt(@$mtts){
11626         $s->execute($mtt->{branchcode}, $mtt->{categorycode}, $mtt->{id}, $mtt->{letternumber}, $mtt->{message_transport_type} );
11627     }
11628     $dbh->do("SET FOREIGN_KEY_CHECKS=1");
11629
11630     print "Upgrade to $DBversion done (Bug 13624 - Remove columns branchcode, categorytype from table overduerules_transport_types)\n";
11631     SetVersion($DBversion);
11632 }
11633
11634 $DBversion = "3.23.00.008";
11635 if ( CheckVersion($DBversion) ) {
11636
11637     $dbh->do(q{ALTER TABLE borrowers ADD privacy_guarantor_checkouts BOOLEAN NOT NULL DEFAULT '0' AFTER privacy});
11638
11639     $dbh->do(q{ALTER TABLE deletedborrowers ADD privacy_guarantor_checkouts BOOLEAN NOT NULL DEFAULT '0' AFTER privacy});
11640
11641     $dbh->do(q{
11642         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type )
11643         VALUES (
11644             'AllowStaffToSetCheckoutsVisibilityForGuarantor',  '0', NULL,
11645             'If enabled, library staff can set a patron''s checkouts to be visible to linked patrons from the opac.',  'YesNo'
11646         ), (
11647             'AllowPatronToSetCheckoutsVisibilityForGuarantor',  '0', NULL,
11648             'If enabled, the patron can set checkouts to be visible to  his or her guarantor',  'YesNo'
11649         )
11650     });
11651
11652     print "Upgrade to $DBversion done (Bug 9303 - relative's checkouts in the opac)\n";
11653     SetVersion($DBversion);
11654 }
11655
11656 $DBversion = "3.23.00.009";
11657 if ( CheckVersion($DBversion) ) {
11658     $dbh->do(q{
11659         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type ) VALUES
11660         ( 'EnablePayPalOpacPayments',  '0', NULL ,  'Enables the ability to pay fees and fines from  the OPAC via PayPal',  'YesNo' ),
11661         ( 'PayPalChargeDescription',  'Koha fee payment', NULL ,  'This preference defines what the user will see the charge listed as in PayPal',  'Free' ),
11662         ( 'PayPalPwd',  '', NULL ,  'Your PayPal API password',  'Free' ),
11663         ( 'PayPalSandboxMode',  '1', NULL ,  'If enabled, the system will use PayPal''s sandbox server for testing, rather than the production server.',  'YesNo' ),
11664         ( 'PayPalSignature',  '', NULL ,  'Your PayPal API signature',  'Free' ),
11665         ( 'PayPalUser',  '', NULL ,  'Your PayPal API username ( email address )',  'Free' )
11666     });
11667
11668     print "Upgrade to $DBversion done (Bug 11622 - Add ability to pay fees and fines from OPAC via PayPal)\n";
11669     SetVersion($DBversion);
11670 }
11671
11672 $DBversion = "3.23.00.010";
11673 if ( CheckVersion($DBversion) ) {
11674     $dbh->do(q{
11675         ALTER TABLE issuingrules ADD cap_fine_to_replacement_price BOOLEAN NOT NULL DEFAULT '0' AFTER overduefinescap
11676     });
11677
11678     print "Upgrade to $DBversion done (Bug 9129 - Add the ability to set the maximum fine for an item to its replacement price)\n";
11679     SetVersion($DBversion);
11680 }
11681
11682 $DBversion = "3.23.00.011";
11683 if ( CheckVersion($DBversion) ) {
11684     $dbh->do(q{
11685         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES ('HoldFeeMode','not_always','always|not_always','Set the hold fee mode','Choice')
11686     });
11687
11688     print "Upgrade to $DBversion done (Bug 13592 - Hold fee not being applied on placing a hold)\n";
11689     SetVersion($DBversion);
11690 }
11691
11692 $DBversion = "3.23.00.012";
11693 if ( CheckVersion($DBversion) ) {
11694     $dbh->do(q{
11695         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')
11696     });
11697
11698     print "Upgrade to $DBversion done (Bug 15380 - Move the authority types related code to Koha::Authority::Type[s] - part 1)\n";
11699     SetVersion($DBversion);
11700 }
11701
11702 $DBversion = "3.23.00.013";
11703 if ( CheckVersion($DBversion) ) {
11704     $dbh->do(q{
11705         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')
11706     });
11707     $dbh->do(q{
11708         CREATE TABLE IF NOT EXISTS `items_last_borrower` (
11709   `id` int(11) NOT NULL AUTO_INCREMENT,
11710   `itemnumber` int(11) NOT NULL,
11711   `borrowernumber` int(11) NOT NULL,
11712   `created_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
11713   PRIMARY KEY (`id`),
11714   UNIQUE KEY `itemnumber` (`itemnumber`),
11715   KEY `borrowernumber` (`borrowernumber`),
11716   CONSTRAINT `items_last_borrower_ibfk_2` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
11717   CONSTRAINT `items_last_borrower_ibfk_1` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE
11718 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
11719     });
11720
11721     print "Upgrade to $DBversion done (Bug 14945 - Add the ability to store the last patron to return an item)\n";
11722     SetVersion($DBversion);
11723
11724 }
11725
11726 $DBversion = "3.23.00.014";
11727 if ( CheckVersion($DBversion) ) {
11728     $dbh->do(q{
11729         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
11730 VALUES ('ClaimsBccCopy','0','','Bcc the ClaimAcquisition and ClaimIssues alerts','YesNo')
11731     });
11732
11733     print "Upgrade to $DBversion done (Bug 10076 - Add Bcc syspref for claimacquisition and clamissues)\n";
11734     SetVersion($DBversion);
11735 }
11736
11737 $DBversion = "3.23.00.015";
11738 if ( CheckVersion($DBversion) ) {
11739     $dbh->do(q{
11740         UPDATE letter SET code = "HOLD_SLIP" WHERE code = "RESERVESLIP";
11741     });
11742
11743     print "Upgrade to $DBversion done (Bug 15443 - Re-code RESERVESLIP as HOLD_SLIP)\n";
11744     SetVersion($DBversion);
11745 }
11746
11747 $DBversion = "3.23.00.016";
11748 if ( CheckVersion($DBversion) ) {
11749     $dbh->do(q{
11750     INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
11751     VALUES ('OpacResetPassword',  '0','','Shows the ''Forgot your password?'' link in the OPAC','YesNo');
11752 });
11753     $dbh->do(q{
11754     CREATE TABLE IF NOT EXISTS borrower_password_recovery (
11755       borrowernumber int(11) NOT NULL,
11756       uuid varchar(128) NOT NULL,
11757       valid_until timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
11758       PRIMARY KEY (borrowernumber),
11759       KEY borrowernumber (borrowernumber)
11760     ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
11761 });
11762     $dbh->do(q{
11763     INSERT IGNORE INTO `letter` (module, code, branchcode, name, is_html, title, content, message_transport_type)
11764     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');
11765
11766     });
11767
11768     print "Upgrade to $DBversion done (Bug 8753 - Add forgot password link to OPAC)\n";
11769     SetVersion($DBversion);
11770 }
11771
11772 $DBversion = "3.23.00.017";
11773 if ( CheckVersion($DBversion) ) {
11774
11775 $dbh->do(q{
11776     DELETE FROM uploaded_files
11777     WHERE COALESCE(permanent,0)=0 AND dir='koha_upload'
11778 });
11779
11780 my $tmp = C4::Context->temporary_directory . '/koha_upload';
11781 remove_tree( $tmp ) if -d $tmp;
11782
11783     print "Upgrade to $DBversion done (Bug 14893 - Separate temporary storage per instance in Upload.pm)\n";
11784     SetVersion($DBversion);
11785
11786 }
11787
11788 $DBversion = "3.23.00.018";
11789 if ( CheckVersion($DBversion) ) {
11790     $dbh->do(q{
11791         UPDATE systempreferences SET value="0" where type="YesNo" and value="";
11792     });
11793
11794     print "Upgrade to $DBversion done (Bug 15446 - Fix systempreferences rows where type=YesNo and value='')\n";
11795     SetVersion($DBversion);
11796 }
11797
11798 $DBversion = "3.23.00.019";
11799 if ( CheckVersion($DBversion) ) {
11800     $dbh->do(q{
11801         UPDATE `authorised_values` SET `lib`='Non-fiction' WHERE `lib`='Non Fiction';
11802     });
11803
11804     print "Upgrade to $DBversion done (Bug 15411 - Change Non Fiction to Non-fiction in authorised_values)\n";
11805     SetVersion($DBversion);
11806 }
11807
11808 $DBversion = "3.23.00.020";
11809 if ( CheckVersion($DBversion) ) {
11810     $dbh->do(q{
11811         CREATE TABLE  sms_providers (
11812            id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
11813            name VARCHAR( 255 ) NOT NULL ,
11814            domain VARCHAR( 255 ) NOT NULL ,
11815            UNIQUE (
11816                name
11817            )
11818         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
11819     });
11820
11821     $dbh->do(q{
11822         ALTER TABLE borrowers ADD sms_provider_id INT( 11 ) NULL DEFAULT NULL AFTER smsalertnumber;
11823     });
11824     $dbh->do(q{
11825         ALTER TABLE borrowers ADD FOREIGN KEY ( sms_provider_id ) REFERENCES sms_providers ( id ) ON UPDATE CASCADE ON DELETE SET NULL;
11826     });
11827     $dbh->do(q{
11828         ALTER TABLE deletedborrowers ADD sms_provider_id INT( 11 ) NULL DEFAULT NULL AFTER smsalertnumber;
11829     });
11830
11831     print "Upgrade to $DBversion done (Bug 9021 - Add SMS via email as an alternative to SMS services via SMS::Send drivers)\n";
11832     SetVersion($DBversion);
11833 }
11834
11835 $DBversion = "3.23.00.021";
11836 if ( CheckVersion($DBversion) ) {
11837     $dbh->do(q{
11838         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES ('ShowAllCheckins', '0', '', 'Show all checkins', 'YesNo');
11839     });
11840
11841     print "Upgrade to $DBversion done (Bug 15736 - Add a preference to control whether all items should be shown in checked-in items list)\n";
11842     SetVersion($DBversion);
11843 }
11844
11845 $DBversion = "3.23.00.022";
11846 if ( CheckVersion($DBversion) ) {
11847     $dbh->do(q{ ALTER TABLE tags_all MODIFY COLUMN borrowernumber INT(11) });
11848     $dbh->do(q{ ALTER TABLE tags_all drop FOREIGN KEY tags_borrowers_fk_1 });
11849     $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 });
11850     $dbh->do(q{ ALTER TABLE tags_approval DROP FOREIGN KEY tags_approval_borrowers_fk_1 });
11851     $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 });
11852
11853     print "Upgrade to $DBversion done (Bug 13534 - Deleting staff patron will delete tags approved by this patron)\n";
11854     SetVersion($DBversion);
11855 }
11856
11857 $DBversion = "3.23.00.023";
11858 if ( CheckVersion($DBversion) ) {
11859     $dbh->do(q{
11860         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11861         VALUES('OpenLibrarySearch','0','If Yes Open Library search results will show in OPAC',NULL,'YesNo');
11862     });
11863
11864     print "Upgrade to $DBversion done (Bug 6624 - Allow Koha to use the new read API from OpenLibrary)\n";
11865     SetVersion($DBversion);
11866 }
11867
11868 $DBversion = "3.23.00.024";
11869 if ( CheckVersion($DBversion) ) {
11870     $dbh->do(q{
11871         ALTER TABLE deletedborrowers MODIFY COLUMN userid VARCHAR(75) DEFAULT NULL;
11872     });
11873
11874     $dbh->do(q{
11875         ALTER TABLE deletedborrowers MODIFY COLUMN password VARCHAR(60) DEFAULT NULL;
11876     });
11877
11878     print "Upgrade to $DBversion done (Bug 15517 - Tables borrowers and deletedborrowers differ again)\n";
11879     SetVersion($DBversion);
11880 }
11881
11882 $DBversion = "3.23.00.025";
11883 if ( CheckVersion($DBversion) ) {
11884     $dbh->do(q{
11885         DROP TABLE IF EXISTS nozebra;
11886     });
11887
11888     print "Upgrade to $DBversion done (Bug 15526 - Drop nozebra database table)\n";
11889     SetVersion($DBversion);
11890 }
11891
11892 $DBversion = "3.23.00.026";
11893 if ( CheckVersion($DBversion) ) {
11894     $dbh->do(q{
11895         UPDATE systempreferences SET value = CONCAT_WS('|', IF(value='', NULL, value), "password") WHERE variable="PatronSelfRegistrationBorrowerUnwantedField" AND value NOT LIKE "%password%";
11896     });
11897
11898     print "Upgrade to $DBversion done (Bug 15343 - Allow patrons to choose their own password on self registration)\n";
11899     SetVersion($DBversion);
11900 }
11901
11902 $DBversion = "3.23.00.027";
11903 if ( CheckVersion($DBversion) ) {
11904     my ( $db_value ) = $dbh->selectrow_array(q|SELECT count(*) FROM branches|);
11905     my $pref_value = C4::Context->preference("singleBranchMode") || 0;
11906     if ( $db_value > 1 and $pref_value == 1 ) {
11907         warn "WARNING: You have more than 1 libraries in your branches tables but the singleBranchMode system preference is on.\n";
11908         warn "This configuration does not make sense. The system preference is going to be deleted,\n";
11909         warn "and this parameter will be based on the number of libraries defined.\n";
11910     }
11911     $dbh->do(q|DELETE FROM systempreferences WHERE variable="singleBranchMode"|);
11912
11913     print "Upgrade to $DBversion done (Bug 4941 - Can't set branch in staff client when singleBranchMode is enabled)\n";
11914     SetVersion($DBversion);
11915 }
11916
11917 $DBversion = "3.23.00.028";
11918 if ( CheckVersion($DBversion) ) {
11919     $dbh->do(q{
11920         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';
11921     });
11922
11923     print "Upgrade to $DBversion done (Bug 14658 - Split PatronSelfRegistrationBorrowerUnwantedField into two preferences for creating and editing)\n";
11924     SetVersion($DBversion);
11925 }
11926
11927 $DBversion = "3.23.00.029";
11928 if ( CheckVersion($DBversion) ) {
11929
11930     # move marc21_field_003.pl 040c and 040d to marc21_orgcode.pl
11931     $dbh->do(q{
11932         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' );
11933     });
11934     $dbh->do(q{
11935         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' );
11936     });
11937
11938     print "Upgrade to $DBversion done (Bug 14199 - Unify all organization code plugins)\n";
11939     SetVersion($DBversion);
11940 }
11941
11942 $DBversion = "3.23.00.030";
11943 if(CheckVersion($DBversion)) {
11944     $dbh->do(q{
11945         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
11946         VALUES ('OpacMaintenanceNotice','','','A user-defined block of HTML to appear on screen when OpacMaintenace is enabled','Textarea')
11947     });
11948
11949     print "Upgrade to $DBversion done (Bug 15311: Let libraries set text to display when OpacMaintenance = on)\n";
11950     SetVersion($DBversion);
11951 }
11952
11953 $DBversion = "3.23.00.031";
11954 if(CheckVersion($DBversion)) {
11955     $dbh->do(q{
11956         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11957         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')
11958     });
11959
11960     print "Upgrade to $DBversion done (Bug 14395 - Two different ways to calculate 'No renewal before')\n";
11961     SetVersion($DBversion);
11962 }
11963
11964 $DBversion = "3.23.00.032";
11965 if ( CheckVersion($DBversion) ) {
11966     $dbh->do(q{
11967    -- Add issue_id to accountlines table
11968     ALTER TABLE accountlines ADD issue_id INT(11) NULL DEFAULT NULL AFTER accountlines_id;
11969     });
11970
11971 ## Close out any accruing fines with no current issue
11972     $dbh->do(q{
11973     UPDATE accountlines LEFT JOIN issues USING ( itemnumber, borrowernumber ) SET accounttype = 'F' WHERE accounttype = 'FU' and issues.issue_id IS NULL;
11974     });
11975
11976 ## Close out any extra not really accruing fines, keep only the latest accring fine
11977     $dbh->do(q{
11978     UPDATE accountlines a1
11979     LEFT JOIN (SELECT MAX(accountlines_id) AS keeper,
11980                       borrowernumber,
11981                       itemnumber
11982                FROM   accountlines
11983                WHERE  accounttype = 'FU'
11984                GROUP BY borrowernumber, itemnumber
11985               ) a2 USING ( borrowernumber, itemnumber )
11986     SET    a1.accounttype = 'F'
11987     WHERE  a1.accounttype = 'FU'
11988     AND  a1.accountlines_id != a2.keeper;
11989     });
11990
11991 ## Update the unclosed fines to add the current issue_id to them
11992     $dbh->do(q{
11993     UPDATE accountlines LEFT JOIN issues USING ( itemnumber ) SET accountlines.issue_id = issues.issue_id WHERE accounttype = 'FU'; 
11994     });
11995
11996     print "Upgrade to $DBversion done (Bug 15675 - Add issue_id column to accountlines and use it for updating fines)\n";
11997     SetVersion($DBversion);
11998 }
11999
12000 $DBversion = "3.23.00.033";
12001 if ( CheckVersion($DBversion) ) {
12002     $dbh->do(q{
12003     UPDATE systempreferences SET value = CONCAT_WS('|', IF(value = '', NULL, value), 'cardnumber') WHERE variable = 'PatronSelfRegistrationBorrowerUnwantedField' AND value NOT LIKE '%cardnumber%';
12004     });
12005
12006     $dbh->do(q{
12007     UPDATE systempreferences SET value = CONCAT_WS('|', IF(value = '', NULL, value), 'categorycode') WHERE variable = 'PatronSelfRegistrationBorrowerUnwantedField' AND value NOT LIKE '%categorycode%';
12008     });
12009
12010     print "Upgrade to $DBversion done (Bug 14659 - Allow patrons to enter card number and patron category on OPAC registration page)\n";
12011     SetVersion($DBversion);
12012 }
12013
12014 $DBversion = "3.23.00.034";
12015 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12016     $dbh->do(q{
12017         ALTER TABLE `items` ADD `new` VARCHAR(32) NULL AFTER `stocknumber`;
12018     });
12019     $dbh->do(q{
12020         ALTER TABLE `deleteditems` ADD `new` VARCHAR(32) NULL AFTER `stocknumber`;
12021     });
12022     print "Upgrade to $DBversion done (Bug 11023: Adds field 'new' in items and deleteditems tables)\n";
12023     SetVersion($DBversion);
12024 }
12025
12026 $DBversion = "3.23.00.035";
12027 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12028     $dbh->do(q{
12029         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('HTML5MediaYouTube',0,'Embed|Don\'t embed','YouTube links as videos','YesNo');
12030     });
12031     print "Upgrade to $DBversion done (Bug 14168 - enhance streaming cataloging to include youtube)\n";
12032
12033     SetVersion($DBversion);
12034     }
12035
12036 $DBversion = "3.23.00.036";
12037 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12038     $dbh->do(q{
12039     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');
12040     });
12041     print "Upgrade to $DBversion done (Bug 12803 - Add ability to skip closed libraries when generating the holds queue)\n";
12042     SetVersion($DBversion);
12043     }
12044
12045 $DBversion = "3.23.00.037";
12046 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12047 ## Add the new currency.archived column
12048     $dbh->do(q{
12049     ALTER TABLE currency ADD column archived tinyint(1) DEFAULT 0;
12050     });
12051 ## Set currency=NULL if empty (just in case)
12052     $dbh->do(q{
12053     UPDATE aqorders SET currency=NULL WHERE currency="";
12054     });
12055 ## Insert the missing currency and mark them as archived before adding the FK
12056     $dbh->do(q{
12057     INSERT INTO currency(currency, archived) SELECT distinct currency, 1 FROM aqorders WHERE currency NOT IN (SELECT currency FROM currency);
12058     });
12059 ## Correct the field length in aqorders before adding FK too
12060     $dbh->do(q{ ALTER TABLE aqorders MODIFY COLUMN currency varchar(10) default NULL; });
12061 ## And finally add the FK
12062     $dbh->do(q{
12063     ALTER TABLE aqorders ADD FOREIGN KEY (currency) REFERENCES currency(currency) ON DELETE SET NULL ON UPDATE SET null;
12064     });
12065
12066     print "Upgrade to $DBversion done (Bug 15084 - Move the currency related code to Koha::Acquisition::Currenc[y|ies])\n";
12067     SetVersion($DBversion);
12068 }
12069
12070 $DBversion = "3.23.00.038";
12071 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12072     $dbh->do(q{
12073     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');
12074     });
12075     print "Upgrade to $DBversion done (Bug 14694 - Make decreaseloanHighHolds more flexible)\n";
12076     SetVersion($DBversion);
12077 }
12078
12079 $DBversion = "3.23.00.039";
12080 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12081
12082     $dbh->do(q{
12083     ALTER TABLE suggestions
12084     MODIFY COLUMN currency varchar(10) default NULL;
12085     });
12086     $dbh->do(q{
12087     ALTER TABLE aqbooksellers
12088     MODIFY COLUMN currency varchar(10) default NULL;
12089     });
12090     print "Upgrade to $DBversion done (Bug 15084 - Move the currency related code to Koha::Acquisition::Currenc[y|ies])\n";
12091     SetVersion($DBversion);
12092 }
12093
12094
12095 $DBversion = "3.23.00.040";
12096 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12097
12098     my $c = $dbh->selectrow_array('SELECT COUNT(*) FROM systempreferences WHERE variable="intranetcolorstylesheet" AND value="blue.css"');
12099
12100     if ( $c ) {
12101         print "WARNING: You are using a stylesheeet which has been removed from the Koha codebase.\n";
12102         print "Update your intranetcolorstylesheet.\n";
12103     }
12104     print "Upgrade to $DBversion done (Bug 16019 - Check intranetcolorstylesheet for blue.css)\n";
12105     SetVersion($DBversion);
12106 }
12107
12108 $DBversion = "3.23.00.041";
12109 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12110
12111     my $dbh = C4::Context->dbh;
12112     my ($print_error) = $dbh->{PrintError};
12113     $dbh->{RaiseError} = 0;
12114     $dbh->{PrintError} = 0;
12115     $dbh->do("ALTER TABLE overduerules_transport_types ADD COLUMN letternumber INT(1) NOT NULL DEFAULT 1 AFTER id");
12116     $dbh->{PrintError} = $print_error;
12117
12118     print "Upgrade to $DBversion done (Bug 16007: Make sure overduerules_transport_types.letternumber exists)\n";
12119     SetVersion($DBversion);
12120 }
12121
12122 $DBversion = "3.23.00.042";
12123 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12124
12125     $dbh->do(q{
12126             ALTER TABLE items CHANGE new new_status VARCHAR(32) NULL;
12127             });
12128     $dbh->do(q{
12129             ALTER TABLE deleteditems CHANGE new new_status VARCHAR(32) NULL;
12130             });
12131     $dbh->do(q{
12132             UPDATE systempreferences SET value=REPLACE(value, '"items.new"', '"items.new_status"') WHERE variable="automatic_item_modification_by_age_configuration";
12133             });
12134
12135     print "Upgrade to $DBversion done (Bug 16004 - Replace items.new with items.new_status)\n";
12136     SetVersion($DBversion);
12137 }
12138
12139 $DBversion = "3.23.00.043";
12140 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12141     $dbh->do(q{
12142             UPDATE systempreferences SET value="" WHERE value IS NULL;
12143             });
12144
12145     print "Upgrade to $DBversion done (Bug 16070 - Empty (undef) system preferences may cause some issues in combination with memcache)\n";
12146     SetVersion($DBversion);
12147 }
12148
12149 $DBversion = "3.23.00.044";
12150 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12151     $dbh->do(q{
12152             INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
12153             ('GoogleOpenIDConnect', '0', NULL, 'if ON, allows the use of Google OpenID Connect for login', 'YesNo'),
12154             ('GoogleOAuth2ClientID', '', NULL, 'Client ID for the web app registered with Google', 'Free'),
12155             ('GoogleOAuth2ClientSecret', '', NULL, 'Client Secret for the web app registered with Google', 'Free'),
12156             ('GoogleOpenIDConnectDomain', '', NULL, 'Restrict OpenID Connect to this domain (or subdomains of this domain). Leave blank for all Google domains', 'Free');
12157             });
12158
12159     print "Upgrade to $DBversion done (Bug 10988 - Allow login via Google OAuth2 (OpenID Connect))\n";
12160     SetVersion($DBversion);
12161 }
12162
12163 $DBversion = "3.23.00.045";
12164 if ( CheckVersion($DBversion) ) {
12165 ## Holds details for vendors supplying goods by EDI
12166    $dbh->do(q{
12167            CREATE TABLE IF NOT EXISTS vendor_edi_accounts (
12168                    id INT(11) NOT NULL auto_increment,
12169                    description TEXT NOT NULL,
12170                    host VARCHAR(40),
12171                    username VARCHAR(40),
12172                    password VARCHAR(40),
12173                    last_activity DATE,
12174                    vendor_id INT(11) REFERENCES aqbooksellers( id ),
12175                    download_directory TEXT,
12176                    upload_directory TEXT,
12177                    san VARCHAR(20),
12178                    id_code_qualifier VARCHAR(3) default '14',
12179                    transport VARCHAR(6) default 'FTP',
12180                    quotes_enabled TINYINT(1) not null default 0,
12181                    invoices_enabled TINYINT(1) not null default 0,
12182                    orders_enabled TINYINT(1) not null default 0,
12183                    responses_enabled TINYINT(1) not null default 0,
12184                    auto_orders TINYINT(1) not null default 0,
12185                    shipment_budget INTEGER(11) REFERENCES aqbudgets( budget_id ),
12186                    PRIMARY KEY  (id),
12187                    KEY vendorid (vendor_id),
12188                    KEY shipmentbudget (shipment_budget),
12189                    CONSTRAINT vfk_vendor_id FOREIGN KEY ( vendor_id ) REFERENCES aqbooksellers ( id ),
12190                    CONSTRAINT vfk_shipment_budget FOREIGN KEY ( shipment_budget ) REFERENCES aqbudgets ( budget_id )
12191                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
12192    });
12193
12194 ## Hold the actual edifact messages with links to associated baskets
12195    $dbh->do(q{
12196            CREATE TABLE IF NOT EXISTS edifact_messages (
12197                    id INT(11) NOT NULL auto_increment,
12198                    message_type VARCHAR(10) NOT NULL,
12199                    transfer_date DATE,
12200                    vendor_id INT(11) REFERENCES aqbooksellers( id ),
12201                    edi_acct  INTEGER REFERENCES vendor_edi_accounts( id ),
12202                    status TEXT,
12203                    basketno INT(11) REFERENCES aqbasket( basketno),
12204                    raw_msg MEDIUMTEXT,
12205                    filename TEXT,
12206                    deleted BOOLEAN NOT NULL DEFAULT 0,
12207                    PRIMARY KEY  (id),
12208                    KEY vendorid ( vendor_id),
12209                    KEY ediacct (edi_acct),
12210                    KEY basketno ( basketno),
12211                    CONSTRAINT emfk_vendor FOREIGN KEY ( vendor_id ) REFERENCES aqbooksellers ( id ),
12212                    CONSTRAINT emfk_edi_acct FOREIGN KEY ( edi_acct ) REFERENCES vendor_edi_accounts ( id ),
12213                    CONSTRAINT emfk_basketno FOREIGN KEY ( basketno ) REFERENCES aqbasket ( basketno )
12214                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
12215             });
12216
12217 ## invoices link back to the edifact message it was generated from
12218    $dbh->do(q{
12219            ALTER TABLE aqinvoices ADD COLUMN message_id INT(11) REFERENCES edifact_messages( id );
12220            });
12221
12222 ## clean up link on deletes
12223    $dbh->do(q{
12224            ALTER TABLE aqinvoices ADD CONSTRAINT edifact_msg_fk FOREIGN KEY ( message_id ) REFERENCES edifact_messages ( id ) ON DELETE SET NULL;
12225            });
12226
12227 ## Hold the supplier ids from quotes for ordering
12228 ## although this is an EAN-13 article number the standard says 35 characters ???
12229    $dbh->do(q{
12230            ALTER TABLE aqorders ADD COLUMN line_item_id VARCHAR(35);
12231            });
12232
12233 ## The suppliers unique reference usually a quotation line number ('QLI')
12234 ## Otherwise Suppliers unique orderline reference ('SLI')
12235    $dbh->do(q{
12236            ALTER TABLE aqorders ADD COLUMN suppliers_reference_number VARCHAR(35);
12237            });
12238    $dbh->do(q{
12239            ALTER TABLE aqorders ADD COLUMN suppliers_reference_qualifier VARCHAR(3);
12240            });
12241    $dbh->do(q{
12242            ALTER TABLE aqorders ADD COLUMN suppliers_report text;
12243            });
12244
12245 ## hold the EAN/SAN used in ordering
12246    $dbh->do(q{
12247            CREATE TABLE IF NOT EXISTS edifact_ean (
12248                    ee_id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
12249                    description VARCHAR(128) NULL DEFAULT NULL,
12250                    branchcode VARCHAR(10) NOT NULL REFERENCES branches (branchcode),
12251                    ean VARCHAR(15) NOT NULL,
12252                    id_code_qualifier VARCHAR(3) NOT NULL DEFAULT '14',
12253                    CONSTRAINT efk_branchcode FOREIGN KEY ( branchcode ) REFERENCES branches ( branchcode )
12254                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
12255            });
12256
12257 ## Add a permission for managing EDI
12258    $dbh->do(q{
12259            INSERT INTO permissions (module_bit, code, description) values (11, 'edi_manage', 'Manage EDIFACT transmissions');
12260            });
12261
12262    print "Upgrade to $DBversion done (Bug 7736 - Edifact QUOTE and ORDER functionality))\n";
12263    SetVersion($DBversion);
12264 }
12265
12266 $DBversion = "3.23.00.046";
12267 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12268
12269     $dbh->do(q{
12270     ALTER TABLE vendor_edi_accounts ADD COLUMN plugin VARCHAR(256) NOT NULL DEFAULT "";
12271     });
12272
12273     print "Upgrade to $DBversion done (Bug 15630 - Make Edifact module pluggable))\n";
12274     SetVersion($DBversion);
12275 }
12276
12277 $DBversion = "3.23.00.047";
12278 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12279
12280     $dbh->do(q{
12281          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');
12282          });
12283     $dbh->do(q{
12284          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');
12285          });
12286
12287     print "Upgrade to $DBversion done (Bug 15008 - Add custom HTML areas to circulation and reports home pages)\n";
12288     SetVersion($DBversion);
12289 }
12290
12291 $DBversion = "3.23.00.048";
12292 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12293     $dbh->do(q{
12294     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';
12295     });
12296
12297     print "Upgrade to $DBversion done (Bug 5979 - Add separate OPACISBD system preference)\n";
12298     SetVersion($DBversion);
12299 }
12300
12301
12302
12303 $DBversion = "3.23.00.049";
12304 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12305 my $dbh = C4::Context->dbh;
12306 my ( $column_has_been_used ) = $dbh->selectrow_array(q|
12307             SELECT COUNT(*)
12308                 FROM borrower_attributes
12309                     WHERE password IS NOT NULL
12310                     |);
12311
12312 if ( $column_has_been_used ) {
12313         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.|;
12314 } else {
12315         $dbh->do(q|
12316         ALTER TABLE borrower_attribute_types DROP column password_allowed
12317         |);
12318         $dbh->do(q|
12319         ALTER TABLE borrower_attributes DROP column password;
12320         |);
12321     }
12322     print "Upgrade to $DBversion done (Bug 12267 - Allow password option in Patron Attribute non functional)\n";
12323         SetVersion($DBversion);
12324 }
12325
12326
12327 $DBversion = "3.23.00.050";
12328 if ( CheckVersion($DBversion) ) {
12329
12330     $dbh->do(q|INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
12331                     VALUES('SearchEngine','Zebra','Choose Search Engine','','Choice')|);
12332
12333
12334     $dbh->do(q|DROP TABLE IF EXISTS search_marc_to_field|);
12335     $dbh->do(q|DROP TABLE IF EXISTS search_marc_map|);
12336     $dbh->do(q|DROP TABLE IF EXISTS search_field|);
12337
12338 # This specifies the fields that will be stored in the search engine.
12339  $dbh->do(q|
12340          CREATE TABLE `search_field` (
12341              `id` int(11) NOT NULL AUTO_INCREMENT, 
12342              `name` varchar(255) NOT NULL COMMENT 'the name of the field as it will be stored in the search engine',
12343              `label` varchar(255) NOT NULL COMMENT 'the human readable name of the field, for display', 
12344              `type` ENUM('', 'string', 'date', 'number', 'boolean', 'sum') NOT NULL COMMENT 'what type of data this holds, relevant when storing it in the search engine',
12345              PRIMARY KEY (`id`),
12346              UNIQUE KEY (`name`)
12347              ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
12348          |);
12349 # This contains a MARC field specifier for a given index, marc type, and marc
12350 # field.
12351 $dbh->do(q|
12352         CREATE TABLE `search_marc_map` (
12353             id int(11) NOT NULL AUTO_INCREMENT,
12354             index_name ENUM('biblios','authorities') NOT NULL COMMENT 'what storage index this map is for',
12355             marc_type ENUM('marc21', 'unimarc', 'normarc') NOT NULL COMMENT 'what MARC type this map is for',
12356             marc_field VARCHAR(255) NOT NULL COMMENT 'the MARC specifier for this field',
12357             PRIMARY KEY(`id`),
12358             unique key( index_name, marc_field, marc_type),
12359             INDEX (`index_name`)
12360             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
12361         |);
12362
12363 # This joins the two search tables together. We can have any combination:
12364 # one marc field could have many search fields (maybe you want one value
12365 # to go to 'author' and 'corporate-author) and many marc fields could go
12366 # to one search field (e.g. all the various author fields going into
12367 # 'author'.)
12368 #
12369 # a note about the sort field:
12370 # * if all the entries for a mapping are 'null', nothing special is done with that mapping.
12371 # * if any of the entries are not null, then a __sort field is created in ES for this mapping. In this case:
12372 #   * any mapping with sort == false WILL NOT get copied into a __sort field
12373 #   * any mapping with sort == true or is null WILL get copied into a __sort field
12374 #   * any sorts on the field name will be applied to $fieldname.'__sort' instead.
12375 # this means that we can have search for author that includes 1xx, 245$c, and 7xx, but the sort only applies to 1xx.
12376
12377 $dbh->do(q|
12378         CREATE TABLE `search_marc_to_field` (
12379             search_marc_map_id int(11) NOT NULL,
12380             search_field_id int(11) NOT NULL,
12381             facet boolean DEFAULT FALSE COMMENT 'true if a facet field should be generated for this',
12382             suggestible boolean DEFAULT FALSE COMMENT 'true if this field can be used to generate suggestions for browse',
12383             sort boolean DEFAULT NULL COMMENT 'true/false creates special sort handling, null doesn''t',
12384             PRIMARY KEY(search_marc_map_id, search_field_id),
12385             FOREIGN KEY(search_marc_map_id) REFERENCES search_marc_map(id) ON DELETE CASCADE ON UPDATE CASCADE,
12386             FOREIGN KEY(search_field_id) REFERENCES search_field(id) ON DELETE CASCADE ON UPDATE CASCADE
12387             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
12388         |);
12389
12390     print "WARNING: If you plan to use Elasticsearch you should go to 'Home › Administration › Search engine configuration' and reset the mappings\n";
12391     print "Upgrade to $DBversion done (Bug 12478 - Elasticsearch support for Koha)\n";
12392     SetVersion($DBversion);
12393 }
12394
12395
12396 $DBversion = "3.23.00.051";
12397 if ( CheckVersion($DBversion) ) {
12398 $dbh->do(q{
12399         ALTER TABLE edifact_messages
12400         DROP FOREIGN KEY emfk_vendor,
12401         DROP FOREIGN KEY emfk_edi_acct,
12402         DROP FOREIGN KEY emfk_basketno;
12403         });
12404
12405 $dbh->do(q{
12406         ALTER TABLE edifact_messages
12407         ADD CONSTRAINT emfk_vendor FOREIGN KEY ( vendor_id ) REFERENCES aqbooksellers ( id ) ON DELETE CASCADE ON UPDATE CASCADE,
12408         ADD CONSTRAINT emfk_edi_acct FOREIGN KEY ( edi_acct ) REFERENCES vendor_edi_accounts ( id ) ON DELETE CASCADE ON UPDATE CASCADE,
12409         ADD CONSTRAINT emfk_basketno FOREIGN KEY ( basketno ) REFERENCES aqbasket ( basketno ) ON DELETE CASCADE ON UPDATE CASCADE;
12410         });
12411
12412     print "Upgrade to $DBversion done (Bug 16354 - Fix FK constraints for edifact_messages table)\n";
12413     SetVersion($DBversion);
12414 }
12415
12416
12417 $DBversion = "3.23.00.052";
12418 if ( CheckVersion($DBversion) ) {
12419 ## Insert permission
12420
12421     $dbh->do(q{
12422         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
12423         (13, 'upload_general_files', 'Upload any file'),
12424         (13, 'upload_manage', 'Manage uploaded files');
12425         });
12426 ## Update user_permissions for current users (check count in uploaded_files)
12427 ## Note 9 == edit_catalogue and 13 == tools
12428 ## We do not insert if someone is superlibrarian, does not have edit_catalogue,
12429 ## or already has all tools
12430
12431         $dbh->do(q{
12432                 INSERT IGNORE INTO user_permissions (borrowernumber, module_bit, code)
12433                 SELECT borrowernumber, 13, 'upload_general_files'
12434                 FROM borrowers bo
12435                 WHERE flags<>1 AND flags & POW(2,13) = 0 AND
12436                 ( flags & POW(2,9) > 0 OR 
12437                   (SELECT COUNT(*) FROM user_permissions
12438                    WHERE borrowernumber=bo.borrowernumber AND module_bit=9 ) > 0 )
12439                 AND ( SELECT COUNT(*) FROM uploaded_files ) > 0
12440                 });
12441
12442     print "Upgrade to $DBversion done (Bug 14686 - New menu option and permission for file uploading)\n";
12443     SetVersion($DBversion);
12444 }
12445
12446 $DBversion = "3.23.00.053";
12447 if ( CheckVersion($DBversion) ) {
12448     my $letters = $dbh->selectall_arrayref(
12449         q|
12450         SELECT code, name
12451         FROM letter
12452         WHERE message_transport_type="email"
12453         |, { Slice => {} }
12454     );
12455     for my $letter (@$letters) {
12456         $dbh->do(
12457             q|
12458                 UPDATE letter
12459                 SET name = ?
12460                 WHERE code = ?
12461                 AND message_transport_type <> "email"
12462                 |, undef, $letter->{name}, $letter->{code}
12463         );
12464     }
12465
12466     print "Upgrade to $DBversion done (Bug 16217 - Notice' names may have diverged)\n";
12467     SetVersion($DBversion);
12468 }
12469
12470 $DBversion = "3.23.00.054";
12471 if ( CheckVersion($DBversion) ) {
12472     $dbh->do(q{
12473         ALTER TABLE branch_item_rules ADD COLUMN hold_fulfillment_policy ENUM('any', 'homebranch', 'holdingbranch') NOT NULL DEFAULT 'any' AFTER holdallowed;
12474     });
12475     $dbh->do(q{
12476         ALTER TABLE default_branch_circ_rules ADD COLUMN hold_fulfillment_policy ENUM('any', 'homebranch', 'holdingbranch') NOT NULL DEFAULT 'any' AFTER holdallowed;
12477     });
12478     $dbh->do(q{
12479         ALTER TABLE default_branch_item_rules ADD COLUMN hold_fulfillment_policy ENUM('any', 'homebranch', 'holdingbranch') NOT NULL DEFAULT 'any' AFTER holdallowed;
12480     });
12481     $dbh->do(q{
12482         ALTER TABLE default_circ_rules ADD COLUMN hold_fulfillment_policy ENUM('any', 'homebranch', 'holdingbranch') NOT NULL DEFAULT 'any' AFTER holdallowed;
12483     });
12484
12485     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";
12486     SetVersion($DBversion);
12487 }
12488
12489 $DBversion = "3.23.00.055";
12490 if ( CheckVersion($DBversion) ) {
12491     $dbh->do(q{
12492         ALTER TABLE reserves ADD COLUMN itemtype VARCHAR(10) NULL DEFAULT NULL AFTER suspend_until;
12493     });
12494     $dbh->do(q{
12495         ALTER TABLE reserves ADD KEY `itemtype` (`itemtype`);
12496     });
12497     $dbh->do(q{
12498         ALTER TABLE reserves ADD CONSTRAINT `reserves_ibfk_5` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE;
12499     });
12500     $dbh->do(q{
12501         ALTER TABLE old_reserves ADD COLUMN itemtype VARCHAR(10) NULL DEFAULT NULL AFTER suspend_until;
12502     });
12503     $dbh->do(q{
12504         ALTER TABLE old_reserves ADD KEY `itemtype` (`itemtype`);
12505     });
12506     $dbh->do(q{
12507         ALTER TABLE old_reserves ADD CONSTRAINT `old_reserves_ibfk_4` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE;
12508     });
12509
12510     $dbh->do(q{
12511         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
12512         ('AllowHoldItemTypeSelection','0','','If enabled, patrons and staff will be able to select the itemtype when placing a hold','YesNo');
12513     });
12514
12515     print "Upgrade to $DBversion done (Bug 15533 - Allow patrons and librarians to select itemtype when placing hold)\n";
12516     SetVersion($DBversion);
12517 }
12518
12519 $DBversion = "3.23.00.056";
12520 if ( CheckVersion($DBversion) ) {
12521     $dbh->do(q{
12522         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
12523         ('NoIssuesChargeGuarantees','','','Define maximum amount withstanding before check outs are blocked','Integer');
12524     });
12525
12526     print "Upgrade to $DBversion done (Bug 14577 - Allow restriction of checkouts based on fines of guarantor/guarantee)\n";
12527     SetVersion($DBversion);
12528 }
12529
12530 $DBversion = "3.23.00.057";
12531 if ( CheckVersion($DBversion) ) {
12532     $dbh->do(q{
12533         ALTER TABLE aqbasket ADD COLUMN is_standing TINYINT(1) NOT NULL DEFAULT 0 AFTER branch;
12534     });
12535
12536     print "Upgrade to $DBversion done (Bug 15531 - Add support for standing orders)\n";
12537     SetVersion($DBversion);
12538 }
12539
12540 $DBversion = "3.23.00.058";
12541 if ( CheckVersion($DBversion) ) {
12542
12543     my ($count_imageurl) = $dbh->selectrow_array(q|
12544         SELECT COUNT(*)
12545         FROM authorised_values
12546         WHERE imageurl IS NOT NULL
12547             AND imageurl <> ""
12548     |);
12549
12550     unless ($count_imageurl) {
12551         if (   C4::Context->preference('AuthorisedValueImages')
12552             or C4::Context->preference('StaffAuthorisedValueImages') )
12553         {
12554             $dbh->do(q|
12555                 UPDATE systempreferences
12556                 SET value = 0
12557                 WHERE variable = "AuthorisedValueImages"
12558                    or variable = "StaffAuthorisedValueImages"
12559             |);
12560             warn "The system preferences AuthorisedValueImages and StaffAuthorisedValueImages have been turned off\n";
12561             warn "authorised_values.imageurl is not populated, that means you are not using this feature\n";
12562         }
12563     }
12564     else {
12565         warn "At least one authorised value has an icon defined (imageurl)\n";
12566         warn "The system preference AuthorisedValueImages or StaffAuthorisedValueImages could be turned off if you are not aware of this feature\n";
12567     }
12568
12569     print "Upgrade to $DBversion done (Bug 16041 - StaffAuthorisedValueImages & AuthorisedValueImages preferences - impact on search performance)\n";
12570     SetVersion($DBversion);
12571 }
12572
12573 $DBversion = "3.23.00.059";
12574 if ( CheckVersion($DBversion) ) {
12575     $dbh->do(q{
12576         DELETE FROM systempreferences WHERE variable="AuthorisedValueImages" OR variable="StaffAuthorisedValueImages";
12577     });
12578
12579     print "Upgrade to $DBversion done (Bug 16167 - Remove prefs to drive authorised value images)\n";
12580     SetVersion($DBversion);
12581 }
12582
12583 $DBversion = "3.23.00.060";
12584 if ( CheckVersion($DBversion) ) {
12585     $dbh->do(q{
12586         INSERT IGNORE INTO systempreferences ( value, variable, options, explanation,type )
12587         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';
12588     });
12589
12590     print "Upgrade to $DBversion done (Bug 12528 - Enable staff to deny message setting access to patrons on the OPAC)\n";
12591     SetVersion($DBversion);
12592 }
12593
12594 $DBversion = "3.23.00.061";
12595 if ( CheckVersion($DBversion) ) {
12596     my ( $cnt ) = $dbh->selectrow_array( q|
12597         SELECT COUNT(*) FROM items it
12598         LEFT JOIN biblio bi ON bi.biblionumber=it.biblionumber
12599         LEFT JOIN biblioitems bii USING (biblioitemnumber)
12600         WHERE bi.biblionumber IS NULL
12601     |);
12602     if( $cnt ) {
12603         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";
12604     } else {
12605         # now add FK
12606         $dbh->do( q|
12607             ALTER TABLE items
12608             ADD FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
12609         |);
12610         print "Upgrade to $DBversion done (Bug 16170 - Add FK for biblionumber in items)\n";
12611     }
12612     SetVersion($DBversion);
12613 }
12614
12615 $DBversion = "3.23.00.062";
12616 if ( CheckVersion($DBversion) ) {
12617     $dbh->do( q|
12618             ALTER TABLE aqorders DROP COLUMN budgetgroup_id;
12619             |);
12620     print "Upgrade to $DBversion done (Bug 16414 - aqorders.budgetgroup_id has never been used and can be removed)\n";
12621 SetVersion($DBversion);
12622 }
12623
12624 $DBversion = "3.23.00.063";
12625 if ( CheckVersion($DBversion) ) {
12626     $dbh->do(q{
12627         UPDATE letter SET branchcode='' WHERE branchcode IS NULL;
12628     });
12629     $dbh->do(q{
12630         ALTER TABLE letter MODIFY COLUMN branchcode varchar(10) NOT NULL DEFAULT ''
12631     });
12632     $dbh->do(q{
12633         ALTER TABLE permissions MODIFY COLUMN code varchar(64) NOT NULL DEFAULT '';
12634     });
12635     print "Upgrade to $DBversion done (Bug 16402: Fix DB structure to work on MySQL 5.7)\n";
12636     SetVersion($DBversion);
12637 }
12638
12639 $DBversion = "3.23.00.064";
12640 if ( CheckVersion($DBversion) ) {
12641     $dbh->do(q{
12642         ALTER TABLE creator_layouts MODIFY layout_name char(25) NOT NULL DEFAULT 'DEFAULT';
12643     });
12644     print "Upgrade to $DBversion done (Bug 15086 - Creators layout and template sql has warnings)\n";
12645     SetVersion($DBversion);
12646 }
12647
12648 $DBversion = "16.05.00.000";
12649 if ( CheckVersion($DBversion) ) {
12650     print "Upgrade to $DBversion done (Koha 16.05)\n";
12651     SetVersion($DBversion);
12652 }
12653
12654 $DBversion = "16.06.00.000";
12655 if ( CheckVersion($DBversion) ) {
12656     print "Upgrade to $DBversion done (Koha 16.06 - starting a new dev line at KohaCon16 in Thessaloniki, Greece! Koha is great!)\n";
12657     SetVersion($DBversion);
12658 }
12659
12660 $DBversion = "16.06.00.001";
12661 if ( CheckVersion($DBversion) ) {
12662     $dbh->do(q{
12663         UPDATE accountlines SET accounttype='HE', description=itemnumber WHERE (description REGEXP '^Hold waiting too long [0-9]+') AND accounttype='F';
12664     });
12665
12666     print "Upgrade to $DBversion done (Bug 16200 - 'Hold waiting too long' fee has a translation problem)\n";
12667     SetVersion($DBversion);
12668 }
12669
12670 $DBversion = "16.06.00.002";
12671 if ( CheckVersion($DBversion) ) {
12672     unless ( column_exists('borrowers', 'updated_on') ) {
12673         $dbh->do(q{
12674             ALTER TABLE borrowers
12675                 ADD COLUMN updated_on timestamp NULL DEFAULT CURRENT_TIMESTAMP
12676                 ON UPDATE CURRENT_TIMESTAMP
12677                 AFTER privacy_guarantor_checkouts;
12678         });
12679         $dbh->do(q{
12680             ALTER TABLE deletedborrowers
12681                 ADD COLUMN updated_on timestamp NULL DEFAULT CURRENT_TIMESTAMP
12682                 ON UPDATE CURRENT_TIMESTAMP
12683                 AFTER privacy_guarantor_checkouts;
12684         });
12685     }
12686
12687     print "Upgrade to $DBversion done (Bug 10459 - borrowers should have a timestamp)\n";
12688     SetVersion($DBversion);
12689 }
12690
12691 $DBversion = "16.06.00.003";
12692 if ( CheckVersion($DBversion) ) {
12693     $dbh->do(q{
12694         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
12695         SELECT 'MaxItemsToProcessForBatchMod', value, NULL, 'Process up to a given number of items in a single item modification batch.', 'Integer' FROM systempreferences WHERE variable='MaxItemsForBatch';
12696     });
12697     $dbh->do(q{
12698         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
12699         SELECT 'MaxItemsToDisplayForBatchDel', value, NULL, 'Display up to a given number of items in a single item deletionbatch.', 'Integer' FROM systempreferences WHERE variable='MaxItemsForBatch';
12700     });
12701     $dbh->do(q{
12702         DELETE FROM systempreferences WHERE variable="MaxItemsForBatch";
12703     });
12704
12705     print "Upgrade to $DBversion done (Bug 11490 - MaxItemsForBatch should be split into two new prefs)\n";
12706     SetVersion($DBversion);
12707 }
12708
12709 $DBversion = '16.06.00.004';
12710 if ( CheckVersion($DBversion) ) {
12711     $dbh->do(q{
12712         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
12713          SELECT 'OPACXSLTListsDisplay', COALESCE(value,''), '', 'Enable XSLT stylesheet control over lists pages display on OPAC', 'Free'
12714          FROM systempreferences WHERE variable='OPACXSLTResultsDisplay';
12715     });
12716
12717     $dbh->do(q{
12718         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
12719          SELECT 'XSLTListsDisplay', COALESCE(value,''), '', 'Enable XSLT stylesheet control over lists pages display on intranet', 'Free'
12720          FROM systempreferences WHERE variable='XSLTResultsDisplay';
12721     });
12722
12723     print "Upgrade to $DBversion done (Bug 15485: Allow choosing different XSLTs for lists)\n";
12724     SetVersion($DBversion);
12725 }
12726
12727 $DBversion = '16.06.00.005';
12728 if ( CheckVersion($DBversion) ) {
12729     $dbh->do(q{
12730         UPDATE `systempreferences` set options = 'US|FR|CH' where variable = 'CurrencyFormat';
12731     });
12732
12733     print "Upgrade to $DBversion done (Bug 16768 - Add official number format for Switzerland: 1'234'567.89)\n";
12734     SetVersion($DBversion);
12735 }
12736
12737 $DBversion = "16.06.00.006";
12738 if ( CheckVersion($DBversion) ) {
12739     $dbh->do(q{
12740         CREATE TABLE `refund_lost_item_fee_rules` (
12741           `branchcode` varchar(10) NOT NULL default '',
12742           `refund` tinyint(1) NOT NULL default 0,
12743           PRIMARY KEY  (`branchcode`)
12744         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
12745     });
12746     $dbh->do(q{
12747         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
12748         VALUES( 'RefundLostOnReturnControl',
12749                 'CheckinLibrary',
12750                 'If a lost item is returned, choose which branch to pick rules for refunding.',
12751                 'CheckinLibrary|PatronLibrary|ItemHomeBranch|ItemHoldingbranch',
12752                 'Choice')
12753     });
12754     # Pick the old syspref as the default rule
12755     $dbh->do(q{
12756         INSERT INTO refund_lost_item_fee_rules (branchcode,refund)
12757             SELECT '*', COALESCE(value,'1') FROM systempreferences WHERE variable='RefundLostItemFeeOnReturn'
12758     });
12759     # Delete the old syspref
12760     $dbh->do(q{
12761         DELETE IGNORE FROM systempreferences
12762         WHERE variable='RefundLostItemFeeOnReturn'
12763     });
12764
12765     print "Upgrade to $DBversion done (Bug 14048: Change RefundLostItemFeeOnReturn to be branch specific)\n";
12766     SetVersion($DBversion);
12767 }
12768
12769 $DBversion = '16.06.00.007';
12770 if ( CheckVersion($DBversion) ) {
12771     $dbh->do(q{
12772         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) 
12773         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');
12774     });
12775
12776     print "Upgrade to $DBversion done (Bug 3534 - Patron quick add form)\n";
12777     SetVersion($DBversion);
12778 }
12779
12780 $DBversion = '16.06.00.008';
12781 if ( CheckVersion($DBversion) ) {
12782     $dbh->do(q{
12783         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
12784         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');
12785     });
12786     $dbh->do(q{
12787         ALTER TABLE categories
12788         ADD COLUMN `checkprevcheckout` varchar(7) NOT NULL default 'inherit'
12789         AFTER `default_privacy`;
12790     });
12791     $dbh->do(q{
12792         ALTER TABLE borrowers
12793         ADD COLUMN `checkprevcheckout` varchar(7) NOT NULL default 'inherit'
12794         AFTER `privacy_guarantor_checkouts`;
12795     });
12796     $dbh->do(q{
12797         ALTER TABLE deletedborrowers
12798         ADD COLUMN `checkprevcheckout` varchar(7) NOT NULL default 'inherit'
12799         AFTER `privacy_guarantor_checkouts`;
12800     });
12801
12802     print "Upgrade to $DBversion done (Bug 6906 - show 'Borrower has previously issued \$ITEM' alert on checkout)\n";
12803     SetVersion($DBversion);
12804 }
12805
12806 $DBversion = '16.06.00.009';
12807 if ( CheckVersion($DBversion) ) {
12808     $dbh->do(q{
12809         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) 
12810         VALUES ('IntranetCatalogSearchPulldown','0',NULL,'Show a search field pulldown for \"Search the catalog\" boxes. ','YesNo');
12811     });
12812
12813     print "Upgrade to $DBversion done (Bug 14902 - Add qualifier menu to staff side 'Search the Catalog')\n";
12814     SetVersion($DBversion);
12815 }
12816
12817 $DBversion = '16.06.00.010';
12818 if ( CheckVersion($DBversion) ) {
12819     $dbh->do(q{
12820         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
12821         VALUES ('MaxOpenSuggestions','',NULL,'Limit the number of open suggestions a patron can have at once, unlimited if blank','Integer')
12822     });
12823
12824     print "Upgrade to $DBversion done (Bug 15128 - Add ability to limit the number of open purchase suggestions a patron can make)\n";
12825     SetVersion($DBversion);
12826 }
12827
12828 $DBversion = '16.06.00.011';
12829 if ( CheckVersion($DBversion) ) {
12830     $dbh->do(q{
12831         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
12832         ('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'),
12833         ('NovelistSelectStaffView','tab','tab|above|below','Where to display Novelist Select content','Choice');
12834     });
12835
12836     print "Upgrade to $DBversion done (Bug 11606 - Novelist Select in Staff Client)\n";
12837     SetVersion($DBversion);
12838 }
12839
12840 $DBversion = '16.06.00.012';
12841 if ( CheckVersion($DBversion) ) {
12842     $dbh->do(q{
12843         ALTER TABLE virtualshelves MODIFY COLUMN created_on DATETIME not NULL;
12844     });
12845
12846     print "Upgrade to $DBversion done (Bug 16573 - Web installer fails to load structure and sample data on MySQL 5.7)\n";
12847     SetVersion($DBversion);
12848 }
12849
12850 $DBversion = '16.06.00.013';
12851 if ( CheckVersion($DBversion) ) {
12852     $dbh->do(q{
12853         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES
12854         ('OPACResultsLibrary', 'homebranch', 'homebranch|holdingbranch', 'Defines whether the OPAC displays the holding or home branch in search results when using XSLT', 'Choice');
12855     });
12856
12857     print "Upgrade to $DBversion done (Bug 7441 - Search results showing wrong branch)\n";
12858     SetVersion($DBversion);
12859 }
12860
12861 $DBversion = "16.06.00.014";
12862 if ( CheckVersion($DBversion) ) {
12863     $dbh->do(q{
12864         ALTER TABLE `action_logs` ADD COLUMN `interface` VARCHAR(30) DEFAULT NULL AFTER `info`;
12865     });
12866
12867     $dbh->do(q{
12868         ALTER TABLE `action_logs` ADD KEY `interface` (`interface`);
12869     });
12870
12871     print "Upgrade to $DBversion done (Bug 16829: action_logs should have an 'interface' column)\n";
12872     SetVersion($DBversion);
12873 }
12874
12875 $DBversion = "16.06.00.015";
12876 if ( CheckVersion($DBversion) ) {
12877     $dbh->do(q{
12878         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type ) VALUES
12879         ('HoldsLog','0',NULL,'If ON, log create/cancel/suspend/resume actions on holds.','YesNo');
12880     });
12881
12882     print "Upgrade to $DBversion done (Bug 14642: Add logging of hold modifications)\n";
12883     SetVersion($DBversion);
12884 }
12885
12886 $DBversion = "16.06.00.016";
12887 if ( CheckVersion($DBversion) ) {
12888     $dbh->do(q{
12889         update marc_subfield_structure set defaultvalue=REPLACE(defaultvalue, 'YYYY', '<<YYYY>>') where defaultvalue like "%YYYY%" and defaultvalue not like "%<<YYYY>>%";
12890     });
12891     $dbh->do(q{
12892         update marc_subfield_structure set defaultvalue=REPLACE(defaultvalue, 'MM', '<<MM>>') where defaultvalue like "%MM%" and defaultvalue not like "%<<MM>>%";
12893     });
12894     $dbh->do(q{
12895         update marc_subfield_structure set defaultvalue=REPLACE(defaultvalue, 'DD', '<<DD>>') where defaultvalue like "%DD%" and defaultvalue not like "%<<DD>>%";
12896     });
12897     $dbh->do(q{
12898         update marc_subfield_structure set defaultvalue=REPLACE(defaultvalue, 'user', '<<USER>>') where defaultvalue like "%user%" and defaultvalue not like "%<<USER>>%";
12899     });
12900
12901     print "Upgrade to $DBversion done (Bug 7045 - Default-value substitution inconsistent)\n";
12902     SetVersion($DBversion);
12903 }
12904
12905 $DBversion = "16.06.00.017";
12906 if ( CheckVersion($DBversion) ) {
12907     $dbh->do(q{
12908         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');
12909     });
12910
12911     print "Upgrade to $DBversion done (Bug 10848 - Allow configuration of mandatory/required fields on the suggestion form in OPAC)\n";
12912     SetVersion($DBversion);
12913 }
12914
12915 $DBversion = "16.06.00.018";
12916 if ( CheckVersion($DBversion) ) {
12917     $dbh->do(q{
12918         ALTER TABLE issuingrules ADD COLUMN holds_per_record SMALLINT(6) NOT NULL DEFAULT 1 AFTER reservesallowed;
12919     });
12920
12921     print "Upgrade to $DBversion done (Bug 14695 - Add ability to place multiple item holds on a given record per patron)\n";
12922     SetVersion($DBversion);
12923 }
12924
12925 $DBversion = "16.06.00.019";
12926 if ( CheckVersion($DBversion) ) {
12927     $dbh->do(q{
12928         ALTER TABLE reviews CHANGE COLUMN approved approved tinyint(4) DEFAULT 0;
12929     });
12930     $dbh->do(q{
12931         UPDATE reviews SET approved=0 WHERE approved IS NULL;
12932     });
12933
12934     print "Upgrade to $DBversion done (Bug 15839 - Move the reviews related code to Koha::Reviews)\n";
12935     SetVersion($DBversion);
12936 }
12937
12938 $DBversion = "16.06.00.020";
12939 if ( CheckVersion($DBversion) ) {
12940     $dbh->do(q{
12941         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('SwitchOnSiteCheckouts', '0', 'Automatically switch an on-site checkout to a normal checkout', NULL, 'YesNo');
12942     });
12943
12944     print "Upgrade to $DBversion done (Bug 16272 - Transform checkout from on-site checkout to regular checkout)\n";
12945     SetVersion($DBversion);
12946 }
12947
12948 $DBversion = "16.06.00.021";
12949 if ( CheckVersion($DBversion) ) {
12950     $dbh->do(q{
12951         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');
12952     });
12953
12954     print "Upgrade to $DBversion done (Bug 16275 - Prevent patron self registration if the email already filled in borrowers.email)\n";
12955     SetVersion($DBversion);
12956 }
12957
12958 $DBversion = "16.06.00.022";
12959 if ( CheckVersion($DBversion) ) {
12960     $dbh->do(q{
12961         INSERT IGNORE INTO `permissions`
12962         (module_bit, code,             description) VALUES
12963         (16,         'delete_reports', 'Delete SQL reports');
12964     });
12965     $dbh->do(q{
12966         INSERT IGNORE INTO user_permissions
12967         (borrowernumber,      module_bit,code)
12968         SELECT borrowernumber,module_bit,'delete_reports'
12969             FROM user_permissions
12970             WHERE module_bit=16 AND code='create_reports';
12971     });
12972
12973     print "Upgrade to $DBversion done (Bug 16978 - Add delete reports user permission)\n";
12974     SetVersion($DBversion);
12975 }
12976
12977 $DBversion = "16.06.00.023";
12978 if ( CheckVersion($DBversion) ) {
12979     my $pref = C4::Context->preference('timeout');
12980     if( !$pref || $pref eq '12000000' ) {
12981         # update if pref is null or equals old default value
12982         $dbh->do(q|
12983             UPDATE systempreferences SET value = '1d', type = 'Free'
12984             WHERE variable = 'timeout'
12985         |);
12986         print "Upgrade to $DBversion done (Bug 17187)\nNote: Pref value for timeout has been adjusted.\n";
12987     } else {
12988         # only update pref type
12989         $dbh->do(q|
12990             UPDATE systempreferences SET type = 'Free'
12991             WHERE variable = 'timeout'
12992         |);
12993         print "Upgrade to $DBversion done (Bug 17187)\nNote: Pref value for timeout has not been adjusted.\n";
12994     }
12995     SetVersion($DBversion);
12996 }
12997
12998 $DBversion = "16.06.00.024";
12999 if ( CheckVersion($DBversion) ) {
13000     $dbh->do(q{
13001         UPDATE language_descriptions SET description = 'Română' WHERE subtag = 'ro' AND type = 'language' AND lang = 'ro';
13002     });
13003
13004     print "Upgrade to $DBversion done (Bug 16311 - Advanced search language limit typo for Romanian)\n";
13005     SetVersion($DBversion);
13006 }
13007
13008 $DBversion = "16.06.00.025";
13009 if ( CheckVersion($DBversion) ) {
13010     $dbh->do(q{
13011         ALTER TABLE `subscription` ADD `itemtype` VARCHAR( 10 ) NULL AFTER reneweddate, ADD `previousitemtype` VARCHAR( 10 ) NULL AFTER itemtype;
13012     });
13013     $dbh->do(q{
13014         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
13015         ('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');
13016     });
13017
13018     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";
13019     SetVersion($DBversion);
13020 }
13021
13022 $DBversion = "16.06.00.026";
13023 if ( CheckVersion($DBversion) ) {
13024     $dbh->do(q{
13025         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('PatronSelfRegistrationLibraryList', '', 'Only display libraries listed. If empty, all libraries are displayed.', NULL, 'Free');
13026     });
13027
13028     print "Upgrade to $DBversion done (Bug 16274 - Make the selfregistration branchcode selection configurable)\n";
13029     SetVersion($DBversion);
13030 }
13031
13032 $DBversion = "16.06.00.027";
13033 if ( CheckVersion($DBversion) ) {
13034     unless ( column_exists('borrowers', 'lastseen') ) {
13035         $dbh->do(q{
13036             ALTER TABLE borrowers ADD COLUMN lastseen datetime default NULL AFTER updated_on;
13037         });
13038         $dbh->do(q{
13039             ALTER TABLE deletedborrowers ADD COLUMN lastseen datetime default NULL AFTER updated_on;
13040         });
13041     }
13042     $dbh->do(q{
13043         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');
13044     });
13045
13046     print "Upgrade to $DBversion done (Bug 16276: Add a new pref TrackLastPatronActivity and new column borrowers.lastseen)\n";
13047     SetVersion($DBversion);
13048 }
13049
13050 $DBversion = '16.06.00.028';
13051 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
13052     {
13053         print "Attempting upgrade to $DBversion (Bug 17135) ...\n";
13054         my $maintenance_script = C4::Context->config("intranetdir") . "/installer/data/mysql/fix_unclosed_nonaccruing_fines_bug17135.pl";
13055         system("perl $maintenance_script --confirm");
13056
13057         print "Upgrade to $DBversion done (Bug 17135 - Fine for the previous overdue may get overwritten by the next one)\n";
13058
13059         unless ($original_version < TransformToNum("3.23.00.032")) { ## Bug 15675
13060             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";
13061             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";
13062         }
13063         SetVersion ($DBversion);
13064     }
13065 }
13066
13067 $DBversion = "16.06.00.029";
13068 if ( CheckVersion($DBversion) ) {
13069     $dbh->do(q{
13070         UPDATE systempreferences SET type="Choice" WHERE variable="UsageStatsLibraryType";
13071     });
13072     $dbh->do(q{
13073         UPDATE systempreferences SET value="Canada" WHERE variable="UsageStatsCountry" AND value="CANADA";
13074     });
13075     $dbh->do(q{
13076         UPDATE systempreferences SET value="Czech Republic" WHERE variable="UsageStatsCountry" AND value="CZ";
13077     });
13078     $dbh->do(q{
13079         UPDATE systempreferences SET value="United Kingdom" WHERE variable="UsageStatsCountry" AND (value="England" OR value="UK");
13080     });
13081     $dbh->do(q{
13082         UPDATE systempreferences SET value="Spain" WHERE variable="UsageStatsCountry" AND value="España";
13083     });
13084     $dbh->do(q{
13085         UPDATE systempreferences SET value="Greece" WHERE variable="UsageStatsCountry" AND value="GR";
13086     });
13087     $dbh->do(q{
13088         UPDATE systempreferences SET value="Ireland" WHERE variable="UsageStatsCountry" AND value="Irelanbd";
13089     });
13090     $dbh->do(q{
13091         UPDATE systempreferences SET value="Mexico" WHERE variable="UsageStatsCountry" AND value="México";
13092     });
13093     $dbh->do(q{
13094         UPDATE systempreferences SET value="Peru" WHERE variable="UsageStatsCountry" AND value="Perú";
13095     });
13096     $dbh->do(q{
13097         UPDATE systempreferences SET value="Dominican Rep." WHERE variable="UsageStatsCountry" AND value="República Dominicana";
13098     });
13099     $dbh->do(q{
13100         UPDATE systempreferences SET value="Trinidad & Tob." WHERE variable="UsageStatsCountry" AND value="Trinidad";
13101     });
13102     $dbh->do(q{
13103         UPDATE systempreferences SET value="Turkey" WHERE variable="UsageStatsCountry" AND value="Türkiye";
13104     });
13105     $dbh->do(q{
13106         UPDATE systempreferences SET value="USA" WHERE variable="UsageStatsCountry" AND (value="United States" OR value="United States of America" OR value="US");
13107     });
13108     $dbh->do(q{
13109         UPDATE systempreferences SET value="Zimbabwe" WHERE variable="UsageStatsCountry" AND value="Zimbabbwe";
13110     });
13111
13112     print "Upgrade to $DBversion done (Bug 14707 - Change UsageStatsCountry from free text to a dropdown list)\n";
13113     SetVersion($DBversion);
13114 }
13115
13116 $DBversion = "16.06.00.030";
13117 if ( CheckVersion($DBversion) ) {
13118     $dbh->do(q{
13119         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
13120         ('OPACHoldingsDefaultSortField','first_column','first_column|homebranch|holdingbranch','Default sort field for the holdings table at the OPAC','choice');
13121     });
13122
13123     print "Upgrade to $DBversion done (Bug 16552 - Add the ability to change the default holdings sort)\n";
13124     SetVersion($DBversion);
13125 }
13126
13127 $DBversion = "16.06.00.031";
13128 if ( CheckVersion($DBversion) ) {
13129     $dbh->do(q{
13130         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');
13131     });
13132
13133     print "Upgrade to $DBversion done (Bug 16273 - Prevent selfregistration from printing the borrower password and filling the logging form)\n";
13134     SetVersion($DBversion);
13135 }
13136
13137 $DBversion = "16.06.00.032";
13138 if ( CheckVersion($DBversion) ) {
13139     $dbh->do(q{
13140         UPDATE marc_subfield_structure SET authorised_value="WITHDRAWN" WHERE authorised_value="WTHDRAWN";
13141     });
13142
13143     print "Upgrade to $DBversion done (Bug 17357 - WTHDRAWN is still used in installer files)\n";
13144     SetVersion($DBversion);
13145 }
13146
13147
13148 $DBversion = "16.06.00.033";
13149 if ( CheckVersion($DBversion) ) {
13150     $dbh->do(q{
13151         CREATE TABLE authorised_value_categories (
13152         category_name VARCHAR(32) NOT NULL,
13153         primary key (category_name)
13154         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13155         });
13156 ## Add authorised value categories
13157     $dbh->do(q{
13158     INSERT INTO authorised_value_categories (category_name )
13159     SELECT DISTINCT category FROM authorised_values;
13160     });
13161     
13162 ## Add special categories
13163     $dbh->do(q{
13164     INSERT IGNORE INTO authorised_value_categories( category_name )
13165     VALUES
13166     ('Asort1'),
13167     ('Asort2'),
13168     ('Bsort1'),
13169     ('Bsort2'),
13170     ('SUGGEST'),
13171     ('DAMAGED'),
13172     ('LOST'),
13173     ('REPORT_GROUP'),
13174     ('REPORT_SUBGROUP'),
13175     ('DEPARTMENT'),
13176     ('TERM'),
13177     ('SUGGEST_STATUS'),
13178     ('ITEMTYPECAT');
13179     });
13180
13181 ## Add very special categories
13182     $dbh->do(q{
13183     INSERT IGNORE INTO authorised_value_categories( category_name )
13184     VALUES
13185     ('branches'),
13186     ('itemtypes'),
13187     ('cn_source');
13188     });
13189
13190     $dbh->do(q{
13191     INSERT IGNORE INTO authorised_value_categories( category_name )
13192     VALUES
13193     ('WITHDRAWN'),
13194     ('RESTRICTED'),
13195     ('NOT_LOAN'),
13196     ('CCODE'),
13197     ('LOC'),
13198     ('STACK');
13199     });
13200
13201 ## Update the FK
13202     $dbh->do(q{
13203     ALTER TABLE items_search_fields
13204     DROP FOREIGN KEY items_search_fields_authorised_values_category;
13205     });
13206
13207     $dbh->do(q{
13208     ALTER TABLE items_search_fields
13209     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;
13210     });
13211
13212     $dbh->do(q{
13213     ALTER TABLE authorised_values
13214     ADD CONSTRAINT `authorised_values_authorised_values_category` FOREIGN KEY (`category`) REFERENCES `authorised_value_categories` (`category_name`) ON DELETE CASCADE ON UPDATE CASCADE;
13215     });
13216
13217     $dbh->do(q{
13218             INSERT IGNORE INTO authorised_value_categories( category_name ) SELECT DISTINCT(authorised_value) FROM marc_subfield_structure;
13219             });
13220
13221     $dbh->do(q{
13222             UPDATE marc_subfield_structure SET authorised_value = NULL WHERE authorised_value = '';
13223             });
13224
13225     # 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)
13226     my $table_sth = $dbh->prepare(qq|SHOW CREATE TABLE marc_subfield_structure|);
13227     $table_sth->execute;
13228     my @table = $table_sth->fetchrow_array;
13229     if ( $table[1] !~ /COLLATE=utf8_unicode_ci/ and $table[1] !~ /COLLATE=utf8mb4_unicode_ci/ ) { #catches utf8mb4 collated tables
13230         $dbh->do(qq|ALTER TABLE marc_subfield_structure CHARACTER SET utf8 COLLATE utf8_unicode_ci|);
13231     }
13232     $dbh->do(q{
13233             ALTER TABLE marc_subfield_structure
13234             MODIFY COLUMN authorised_value VARCHAR(32) DEFAULT NULL,
13235             ADD CONSTRAINT marc_subfield_structure_ibfk_1 FOREIGN KEY (authorised_value) REFERENCES authorised_value_categories (category_name) ON UPDATE CASCADE ON DELETE SET NULL;
13236             });
13237
13238       print "Upgrade to $DBversion done (Bug 17216 - Add a new table to store authorized value categories)\n";
13239       SetVersion($DBversion);
13240 }
13241
13242 $DBversion = "16.06.00.034";
13243 if ( CheckVersion($DBversion) ) {
13244     $dbh->do(q{
13245         ALTER TABLE biblioitems DROP COLUMN marc;
13246     });
13247     $dbh->do(q{
13248         ALTER TABLE deletedbiblioitems DROP COLUMN marc;
13249     });
13250
13251     print "Upgrade to $DBversion done (Bug 10455 - remove redundant 'biblioitems.marc' field)\n";
13252     SetVersion($DBversion);
13253 }
13254
13255 $DBversion = '16.06.00.035';
13256 if ( CheckVersion($DBversion) ) {
13257     $dbh->do(q{
13258         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
13259          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'
13260          FROM systempreferences WHERE variable='AllowItemsOnHoldCheckout';
13261     });
13262
13263     print "Upgrade to $DBversion done (Bug 15131: Give SCO separate control for AllowItemsOnHoldCheckout)\n";
13264     SetVersion($DBversion);
13265 }
13266
13267 $DBversion = '16.06.00.036';
13268 if ( CheckVersion($DBversion) ) {
13269     $dbh->do(q{
13270         CREATE TABLE IF NOT EXISTS `housebound_profile` (
13271           `borrowernumber` int(11) NOT NULL, -- Number of the borrower associated with this profile.
13272           `day` text NOT NULL,  -- The preferred day of the week for delivery.
13273           `frequency` text NOT NULL, -- The Authorised_Value definining the pattern for delivery.
13274           `fav_itemtypes` text default NULL, -- Free text describing preferred itemtypes.
13275           `fav_subjects` text default NULL, -- Free text describing preferred subjects.
13276           `fav_authors` text default NULL, -- Free text describing preferred authors.
13277           `referral` text default NULL, -- Free text indicating how the borrower was added to the service.
13278           `notes` text default NULL, -- Free text for additional notes.
13279           PRIMARY KEY  (`borrowernumber`),
13280           CONSTRAINT `housebound_profile_bnfk`
13281             FOREIGN KEY (`borrowernumber`)
13282             REFERENCES `borrowers` (`borrowernumber`)
13283             ON UPDATE CASCADE ON DELETE CASCADE
13284         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13285     });
13286     $dbh->do(q{
13287         CREATE TABLE IF NOT EXISTS `housebound_visit` (
13288           `id` int(11) NOT NULL auto_increment, -- ID of the visit.
13289           `borrowernumber` int(11) NOT NULL, -- Number of the borrower, & the profile, linked to this visit.
13290           `appointment_date` date default NULL, -- Date of visit.
13291           `day_segment` varchar(10),  -- Rough time frame: 'morning', 'afternoon' 'evening'
13292           `chooser_brwnumber` int(11) default NULL, -- Number of the borrower to choose items  for delivery.
13293           `deliverer_brwnumber` int(11) default NULL, -- Number of the borrower to deliver items.
13294           PRIMARY KEY  (`id`),
13295           CONSTRAINT `houseboundvisit_bnfk`
13296             FOREIGN KEY (`borrowernumber`)
13297             REFERENCES `housebound_profile` (`borrowernumber`)
13298             ON UPDATE CASCADE ON DELETE CASCADE,
13299           CONSTRAINT `houseboundvisit_bnfk_1`
13300             FOREIGN KEY (`chooser_brwnumber`)
13301             REFERENCES `borrowers` (`borrowernumber`)
13302             ON UPDATE CASCADE ON DELETE CASCADE,
13303           CONSTRAINT `houseboundvisit_bnfk_2`
13304             FOREIGN KEY (`deliverer_brwnumber`)
13305             REFERENCES `borrowers` (`borrowernumber`)
13306             ON UPDATE CASCADE ON DELETE CASCADE
13307         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13308     });
13309     $dbh->do(q{
13310         CREATE TABLE IF NOT EXISTS `housebound_role` (
13311           `borrowernumber_id` int(11) NOT NULL, -- borrowernumber link
13312           `housebound_chooser` tinyint(1) NOT NULL DEFAULT 0, -- set to 1 to indicate this patron is a housebound chooser volunteer
13313           `housebound_deliverer` tinyint(1) NOT NULL DEFAULT 0, -- set to 1 to indicate this patron is a housebound deliverer volunteer
13314           PRIMARY KEY (`borrowernumber_id`),
13315           CONSTRAINT `houseboundrole_bnfk`
13316             FOREIGN KEY (`borrowernumber_id`)
13317             REFERENCES `borrowers` (`borrowernumber`)
13318             ON UPDATE CASCADE ON DELETE CASCADE
13319         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13320     });
13321     $dbh->do(q{
13322         INSERT IGNORE INTO systempreferences
13323                (variable,value,options,explanation,type) VALUES
13324                ('HouseboundModule',0,'',
13325                'If ON, enable housebound module functionality.','YesNo');
13326     });
13327     $dbh->do(q{
13328         INSERT IGNORE INTO authorised_value_categories( category_name ) VALUES
13329             ('HSBND_FREQ');
13330     });
13331     $dbh->do(q{
13332         INSERT IGNORE INTO authorised_values (category, authorised_value, lib) VALUES
13333                ('HSBND_FREQ','EW','Every week');
13334     });
13335
13336     print "Upgrade to $DBversion done (Bug 5670 - Housebound Readers Module)\n";
13337     SetVersion($DBversion);
13338 }
13339
13340 $DBversion = "16.06.00.037";
13341 if ( CheckVersion($DBversion) ) {
13342     $dbh->do(q{
13343         ALTER TABLE `issuingrules` ADD `article_requests` ENUM( 'no', 'yes', 'bib_only', 'item_only' ) NOT NULL DEFAULT 'no' AFTER `opacitemholds`;
13344     });
13345     $dbh->do(q{
13346         INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES
13347             ('ArticleRequests', '0', NULL, 'Enables the article request feature', 'YesNo'),
13348             ('ArticleRequestsMandatoryFields', '', NULL, 'Comma delimited list of required fields for bibs where article requests rule = ''yes''', 'multiple'),
13349             ('ArticleRequestsMandatoryFieldsItemsOnly', '', NULL, 'Comma delimited list of required fields for bibs where article requests rule = ''item_only''', 'multiple'),
13350             ('ArticleRequestsMandatoryFieldsRecordOnly', '', NULL, 'Comma delimited list of required fields for bibs where article requests rule = ''bib_only''', 'multiple');
13351     });
13352     $dbh->do(q{
13353         CREATE TABLE IF NOT EXISTS `article_requests` (
13354           `id` int(11) NOT NULL AUTO_INCREMENT,
13355           `borrowernumber` int(11) NOT NULL,
13356           `biblionumber` int(11) NOT NULL,
13357           `itemnumber` int(11) DEFAULT NULL,
13358           `branchcode` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
13359           `title` text,
13360           `author` text,
13361           `volume` text,
13362           `issue` text,
13363           `date` text,
13364           `pages` text,
13365           `chapters` text,
13366           `patron_notes` text,
13367           `status` enum('PENDING','PROCESSING','COMPLETED','CANCELED') NOT NULL DEFAULT 'PENDING',
13368           `notes` text,
13369           `created_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
13370           `updated_on` timestamp NULL DEFAULT NULL,
13371           PRIMARY KEY (`id`),
13372           KEY `borrowernumber` (`borrowernumber`),
13373           KEY `biblionumber` (`biblionumber`),
13374           KEY `itemnumber` (`itemnumber`),
13375           KEY `branchcode` (`branchcode`),
13376           CONSTRAINT `article_requests_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
13377           CONSTRAINT `article_requests_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
13378           CONSTRAINT `article_requests_ibfk_3` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE SET NULL ON UPDATE CASCADE,
13379           CONSTRAINT `article_requests_ibfk_4` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE SET NULL ON UPDATE CASCADE
13380         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13381     });
13382     $dbh->do(q{
13383         INSERT INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`) VALUES
13384         ('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'),
13385         ('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'),
13386         ('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'),
13387         ('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'),
13388         ('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');
13389     });
13390
13391     print "Upgrade to $DBversion done (Bug 14610 - Add ability to place article requests in Koha)\n";
13392     SetVersion($DBversion);
13393 }
13394
13395 $DBversion = '16.06.00.038';
13396 if ( CheckVersion($DBversion) ) {
13397     $dbh->do(q{
13398         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');
13399     });
13400
13401     print "Upgrade to $DBversion done (Bug 14874 - Add ability to search for patrons by date of birth from checkout and patron quick searches)\n";
13402     SetVersion($DBversion);
13403 }
13404
13405 $DBversion = "16.06.00.039";
13406 if ( CheckVersion($DBversion) ) {
13407
13408     my $sth = $dbh->prepare(q{
13409         SELECT s.itemnumber, i.itype, b.itemtype
13410         FROM
13411          ( SELECT DISTINCT itemnumber
13412            FROM statistics
13413            WHERE ( type = "return" OR type = "localuse" ) AND
13414                  itemtype IS NULL
13415          ) s
13416         LEFT JOIN
13417          ( SELECT itemnumber,biblionumber, itype
13418              FROM items
13419            UNION
13420            SELECT itemnumber,biblionumber, itype
13421              FROM deleteditems
13422          ) i
13423         ON (s.itemnumber=i.itemnumber)
13424         LEFT JOIN
13425          ( SELECT biblionumber, itemtype
13426              FROM biblioitems
13427            UNION
13428            SELECT biblionumber, itemtype
13429              FROM deletedbiblioitems
13430          ) b
13431         ON (i.biblionumber=b.biblionumber);
13432     });
13433     $sth->execute();
13434
13435     my $update_sth = $dbh->prepare(q{
13436         UPDATE statistics
13437         SET itemtype=?
13438         WHERE itemnumber=? AND itemtype IS NULL
13439     });
13440     my $ilevel_itypes = C4::Context->preference('item-level_itypes');
13441
13442     while ( my ($itemnumber,$item_itype,$biblio_itype) = $sth->fetchrow_array ) {
13443
13444         my $effective_itemtype = $ilevel_itypes
13445                                     ? $item_itype // $biblio_itype
13446                                     : $biblio_itype;
13447         warn "item-level_itypes set but no itype defined for item ($itemnumber)"
13448             if $ilevel_itypes and !defined $item_itype;
13449         $update_sth->execute( $effective_itemtype, $itemnumber );
13450     }
13451
13452     print "Upgrade to $DBversion done (Bug 14598: itemtype is not set on statistics by C4::Circulation::AddReturn)\n";
13453     SetVersion($DBversion);
13454 }
13455
13456 $DBversion = '16.06.00.040';
13457 if ( CheckVersion($DBversion) ) {
13458     $dbh->do(q{
13459         ALTER TABLE `aqcontacts` ADD `orderacquisition` BOOLEAN NOT NULL DEFAULT 0 AFTER `notes`;
13460     });
13461     $dbh->do(q{
13462         INSERT IGNORE INTO `letter` (module, code, name, title, content, message_transport_type) VALUES
13463         ('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');
13464     });
13465
13466     print "Upgrade to $DBversion done (Bug 5260 - Add option to send an order by e-mail to the acquisition module)\n";
13467     SetVersion($DBversion);
13468 }
13469
13470 $DBversion = '16.06.00.041';
13471 if ( CheckVersion($DBversion) ) {
13472     $dbh->do(q{
13473         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')
13474     });
13475
13476     print "Upgrade to $DBversion done (Bug 14629 - Add aggressive ISSN matching feature equivalent to the aggressive ISBN matcher)\n";
13477     SetVersion($DBversion);
13478 }
13479
13480 $DBversion = '16.06.00.042';
13481 if ( CheckVersion($DBversion) ) {
13482     $dbh->do(q|
13483         ALTER TABLE aqorders
13484             ADD COLUMN unitprice_tax_excluded decimal(28,6) default NULL AFTER unitprice,
13485             ADD COLUMN unitprice_tax_included decimal(28,6) default NULL AFTER unitprice_tax_excluded,
13486             ADD COLUMN rrp_tax_excluded decimal(28,6) default NULL AFTER rrp,
13487             ADD COLUMN rrp_tax_included decimal(28,6) default NULL AFTER rrp_tax_excluded,
13488             ADD COLUMN ecost_tax_excluded decimal(28,6) default NULL AFTER ecost,
13489             ADD COLUMN ecost_tax_included decimal(28,6) default NULL AFTER ecost_tax_excluded,
13490             ADD COLUMN tax_value decimal(6,4) default NULL AFTER gstrate
13491     |);
13492
13493     # rename gstrate with tax_rate
13494     $dbh->do(q|ALTER TABLE aqorders CHANGE COLUMN gstrate tax_rate decimal(6,4) DEFAULT NULL|);
13495     $dbh->do(q|ALTER TABLE aqbooksellers CHANGE COLUMN gstrate tax_rate decimal(6,4) DEFAULT NULL|);
13496
13497     # Fill the new columns
13498     my $orders = $dbh->selectall_arrayref(q|
13499         SELECT * FROM aqorders
13500     |, { Slice => {} } );
13501
13502     my $sth_update_order = $dbh->prepare(q|
13503         UPDATE aqorders
13504         SET unitprice_tax_excluded = ?,
13505             unitprice_tax_included = ?,
13506             rrp_tax_excluded = ?,
13507             rrp_tax_included = ?,
13508             ecost_tax_excluded = ?,
13509             ecost_tax_included = ?,
13510             tax_value = ?
13511         WHERE ordernumber = ?
13512     |);
13513
13514     my $sth_get_bookseller = $dbh->prepare(q|
13515         SELECT aqbooksellers.*
13516         FROM aqbooksellers
13517         LEFT JOIN aqbasket ON aqbasket.booksellerid = aqbooksellers.id
13518         LEFT JOIN aqorders ON aqorders.basketno = aqbasket.basketno
13519         WHERE ordernumber = ?
13520     |);
13521
13522     require Number::Format;
13523     my $format = Number::Format->new;
13524     my $precision = 2;
13525     for my $order ( @$orders ) {
13526         $sth_get_bookseller->execute( $order->{ordernumber} );
13527         my ( $bookseller ) = $sth_get_bookseller->fetchrow_hashref;
13528         $order->{rrp}   = $format->round( $order->{rrp}, $precision );
13529         $order->{ecost} = $format->round( $order->{ecost}, $precision );
13530         $order->{tax_rate} ||= 0 ; # tax_rate can be NULL in DB
13531         # Ordering
13532         if ( $bookseller->{listincgst} ) {
13533             $order->{rrp_tax_included} = $order->{rrp};
13534             $order->{rrp_tax_excluded} = $format->round(
13535                 $order->{rrp_tax_included} / ( 1 + $order->{tax_rate} ), $precision );
13536             $order->{ecost_tax_included} = $order->{ecost};
13537             $order->{ecost_tax_excluded} = $format->round(
13538                 $order->{ecost} / ( 1 + $order->{tax_rate} ), $precision );
13539         }
13540         else {
13541             $order->{rrp_tax_excluded} = $order->{rrp};
13542             $order->{rrp_tax_included} = $format->round(
13543                 $order->{rrp} * ( 1 + $order->{tax_rate} ), $precision );
13544             $order->{ecost_tax_excluded} = $order->{ecost};
13545             $order->{ecost_tax_included} = $format->round(
13546                 $order->{ecost} * ( 1 + $order->{tax_rate} ), $precision );
13547         }
13548
13549         #receiving
13550         if ( $bookseller->{listincgst} ) {
13551             $order->{unitprice_tax_included} = $format->round( $order->{unitprice}, $precision );
13552             $order->{unitprice_tax_excluded} = $format->round(
13553               $order->{unitprice_tax_included} / ( 1 + $order->{tax_rate} ), $precision );
13554         }
13555         else {
13556             $order->{unitprice_tax_excluded} = $format->round( $order->{unitprice}, $precision );
13557             $order->{unitprice_tax_included} = $format->round(
13558               $order->{unitprice_tax_excluded} * ( 1 + $order->{tax_rate} ), $precision );
13559         }
13560
13561         # If the order is received, the tax is calculated from the unit price
13562         if ( $order->{orderstatus} eq 'complete' ) {
13563             $order->{tax_value} = $format->round(
13564               ( $order->{unitprice_tax_included} - $order->{unitprice_tax_excluded} )
13565               * $order->{quantity}, $precision );
13566         } else {
13567             # otherwise the ecost is used
13568             $order->{tax_value} = $format->round(
13569                 ( $order->{ecost_tax_included} - $order->{ecost_tax_excluded} ) *
13570                   $order->{quantity}, $precision );
13571         }
13572
13573         $sth_update_order->execute(
13574             $order->{unitprice_tax_excluded},
13575             $order->{unitprice_tax_included},
13576             $order->{rrp_tax_excluded},
13577             $order->{rrp_tax_included},
13578             $order->{ecost_tax_excluded},
13579             $order->{ecost_tax_included},
13580             $order->{tax_value},
13581             $order->{ordernumber},
13582         );
13583     }
13584
13585     print "Upgrade to $DBversion done (Bug 13321 - Tax and prices calculation need to be fixed)\n";
13586     SetVersion($DBversion);
13587 }
13588
13589 $DBversion = '16.06.00.043';
13590 if ( CheckVersion($DBversion) ) {
13591     # Add the new columns
13592     $dbh->do(q|
13593         ALTER TABLE aqorders
13594             ADD COLUMN tax_rate_on_ordering   decimal(6,4) default NULL AFTER tax_rate,
13595             ADD COLUMN tax_rate_on_receiving  decimal(6,4) default NULL AFTER tax_rate_on_ordering,
13596             ADD COLUMN tax_value_on_ordering  decimal(28,6) default NULL AFTER tax_value,
13597             ADD COLUMN tax_value_on_receiving decimal(28,6) default NULL AFTER tax_value_on_ordering
13598     |);
13599
13600     my $orders = $dbh->selectall_arrayref(q|
13601         SELECT * FROM aqorders
13602     |, { Slice => {} } );
13603
13604     my $sth_update_order = $dbh->prepare(q|
13605         UPDATE aqorders
13606         SET tax_rate_on_ordering = tax_rate,
13607             tax_rate_on_receiving = tax_rate,
13608             tax_value_on_ordering = ?,
13609             tax_value_on_receiving = ?
13610         WHERE ordernumber = ?
13611     |);
13612
13613     for my $order (@$orders) {
13614         my $tax_value_on_ordering =
13615           $order->{quantity} *
13616           $order->{ecost_tax_excluded} *
13617           $order->{tax_rate};
13618
13619         my $tax_value_on_receiving =
13620           ( defined $order->{unitprice_tax_excluded} )
13621           ? $order->{quantity} * $order->{unitprice_tax_excluded} * $order->{tax_rate}
13622           : undef;
13623
13624         $sth_update_order->execute( $tax_value_on_ordering,
13625             $tax_value_on_receiving, $order->{ordernumber} );
13626     }
13627
13628     # Remove the old columns
13629     $dbh->do(q|
13630         ALTER TABLE aqorders
13631             CHANGE COLUMN tax_value tax_value_bak  decimal(28,6) default NULL,
13632             CHANGE COLUMN tax_rate tax_rate_bak decimal(6,4) default NULL
13633     |);
13634
13635     print "Upgrade to $DBversion done (Bug 13323 - Change the tax rate on receiving)\n";
13636     SetVersion($DBversion);
13637 }
13638
13639 $DBversion = '16.06.00.044';
13640 if ( CheckVersion($DBversion) ) {
13641     $dbh->do(q{
13642         ALTER TABLE `messages`
13643         ADD `manager_id` int(11) NULL,
13644         ADD FOREIGN KEY (`manager_id`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL;
13645     });
13646
13647     print "Upgrade to $DBversion done (Bug 17397 - Show name of librarian who created circulation message)\n";
13648     SetVersion($DBversion);
13649 }
13650
13651 $DBversion = '16.06.00.045';
13652 if ( CheckVersion($DBversion) ) {
13653     $dbh->do(q{
13654         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";
13655     });
13656
13657     print "Upgrade to $DBversion done (Bug 17443 - Make possible to renew patron by later of expiry and current date)\n";
13658     SetVersion($DBversion);
13659 }
13660
13661 $DBversion = '16.06.00.046';
13662 if ( CheckVersion($DBversion) ) {
13663     $dbh->do(q{
13664         ALTER TABLE issuingrules ADD COLUMN no_auto_renewal_after INT(4) DEFAULT NULL AFTER auto_renew;
13665     });
13666
13667     print "Upgrade to $DBversion done (Bug 15581 - Add a circ rule to not allow auto-renewals after defined loan period)\n";
13668     SetVersion($DBversion);
13669 }
13670
13671 $DBversion = '16.06.00.047';
13672 if ( CheckVersion($DBversion) ) {
13673     $dbh->do(q{
13674         UPDATE language_descriptions SET description = 'Čeština' WHERE subtag = 'cs' AND type = 'language' AND lang = 'cs'
13675     });
13676
13677     print "Upgrade to $DBversion done (Bug 17518: Displayed language name for Czech is wrong)\n";
13678     SetVersion($DBversion);
13679 }
13680
13681 $DBversion = '16.06.00.048';
13682 if( CheckVersion( $DBversion ) ) {
13683     $dbh->do(q|
13684         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
13685         (13, 'upload_general_files', 'Upload any file'),
13686         (13, 'upload_manage', 'Manage uploaded files');
13687     |);
13688
13689     # Update user_permissions for current users (check count in uploaded_files)
13690     # Note 9 == edit_catalogue and 13 == tools
13691     # We do not insert if someone is superlibrarian, does not have edit_catalogue,
13692     # or already has all tools
13693     $dbh->do(q|
13694         INSERT IGNORE INTO user_permissions (borrowernumber, module_bit, code)
13695         SELECT borrowernumber, 13, 'upload_general_files'
13696         FROM borrowers bo
13697         WHERE flags<>1 AND flags & POW(2,13) = 0 AND
13698             ( flags & POW(2,9) > 0 OR (
13699                 SELECT COUNT(*) FROM user_permissions
13700                 WHERE borrowernumber=bo.borrowernumber AND module_bit=9 ) > 0 )
13701             AND ( SELECT COUNT(*) FROM uploaded_files ) > 0;
13702     |);
13703
13704     SetVersion( $DBversion );
13705     print "Upgrade to $DBversion done (Bug 17663 - Forgotten userpermissions)\n";
13706 }
13707
13708 $DBversion = '16.06.00.049';
13709 if( CheckVersion( $DBversion ) ) {
13710     $dbh->do(q|
13711         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) 
13712         VALUES ('ReplytoDefault',  '',  NULL,  'The default email address to be set as replyto.',  'Free');
13713     |);
13714
13715     $dbh->do(q|
13716         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
13717         VALUES ('ReturnpathDefault',  '',  NULL,  'The default email address to be set as return-path',  'Free');
13718     |);
13719
13720     SetVersion( $DBversion );
13721     print "Upgrade to $DBversion done (Bug 17391 - ReturnpathDefault and ReplyToDefault missing from syspref.sql)\n";
13722 }
13723
13724 $DBversion = "16.06.00.050";
13725 if ( CheckVersion($DBversion) ) {
13726
13727     # If index issn_idx still exists, we assume that dbrev 3.15.00.049 failed,
13728     # and we repeat it (partially).
13729     # Note: the db rev only pertains to biblioitems and is not needed for
13730     # deletedbiblioitems.
13731
13732     my $temp = $dbh->selectall_arrayref( "SHOW INDEXES FROM biblioitems WHERE key_name = 'issn_idx'" );
13733
13734     if( @$temp > 0 ) {
13735         $dbh->do( "ALTER TABLE biblioitems DROP INDEX isbn" );
13736         $dbh->do( "ALTER TABLE biblioitems DROP INDEX issn" );
13737         $dbh->do( "ALTER TABLE biblioitems DROP INDEX issn_idx" );
13738         $dbh->do( "ALTER TABLE biblioitems CHANGE isbn isbn MEDIUMTEXT NULL DEFAULT NULL, CHANGE issn issn MEDIUMTEXT NULL DEFAULT NULL" );
13739         $dbh->do( "ALTER TABLE biblioitems ADD INDEX isbn ( isbn ( 255 ) ), ADD INDEX issn ( issn ( 255 ) )" );
13740         print "Upgrade to $DBversion done (Bug 8835). Removed issn_idx.\n";
13741     } else {
13742         print "Upgrade to $DBversion done (Bug 8835). Everything is fine.\n";
13743     }
13744
13745     SetVersion($DBversion);
13746 }
13747
13748 $DBversion = "16.11.00.000";
13749 if ( CheckVersion($DBversion) ) {
13750     print "Upgrade to $DBversion done (Koha 16.11)\n";
13751     SetVersion($DBversion);
13752 }
13753
13754 $DBversion = "16.12.00.000";
13755 if ( CheckVersion($DBversion) ) {
13756     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";
13757     SetVersion($DBversion);
13758 }
13759
13760 $DBversion = "16.12.00.001";
13761 if ( CheckVersion($DBversion) ) {
13762     $dbh->do(q{
13763         ALTER TABLE borrower_modifications
13764         ADD COLUMN extended_attributes text DEFAULT NULL
13765         AFTER privacy
13766     });
13767
13768     print "Upgrade to $DBversion done (Bug 17767 - Let Koha::Patron::Modification handle extended attributes)\n";
13769     SetVersion($DBversion);
13770 }
13771
13772 $DBversion = '16.12.00.002';
13773 if ( CheckVersion($DBversion) ) {
13774     unless (column_exists( 'branchtransfers', 'branchtransfer_id' )
13775         and index_exists( 'branchtransfers', 'PRIMARY' ) )
13776     {
13777         $dbh->do(
13778             "ALTER TABLE branchtransfers
13779                  ADD COLUMN branchtransfer_id int(12) NOT NULL auto_increment FIRST, ADD CONSTRAINT PRIMARY KEY (branchtransfer_id);"
13780         );
13781     }
13782
13783     SetVersion($DBversion);
13784     print "Upgrade to $DBversion done (Bug 14187 - branchtransfer needs a primary key (id) for DBIx and common sense.)\n";
13785 }
13786
13787 $DBversion = '16.12.00.003';
13788 if ( CheckVersion($DBversion) ) {
13789     $dbh->do(q{DELETE FROM systempreferences WHERE variable="Persona"});
13790     SetVersion($DBversion);
13791     print "Upgrade to $DBversion done (Bug 17486 - Remove 'Mozilla Persona' as an authentication method)\n";
13792 }
13793
13794 $DBversion = '16.12.00.004';
13795 if ( CheckVersion($DBversion) ) {
13796     $dbh->do(q{
13797         CREATE TABLE biblio_metadata (
13798             `id` INT(11) NOT NULL AUTO_INCREMENT,
13799             `biblionumber` INT(11) NOT NULL,
13800             `format` VARCHAR(16) NOT NULL,
13801             `marcflavour` VARCHAR(16) NOT NULL,
13802             `metadata` LONGTEXT NOT NULL,
13803             PRIMARY KEY(id),
13804             UNIQUE KEY `biblio_metadata_uniq_key` (`biblionumber`,`format`,`marcflavour`),
13805             CONSTRAINT `biblio_metadata_fk_1` FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
13806         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13807     });
13808     $dbh->do(q{
13809         CREATE TABLE deletedbiblio_metadata (
13810             `id` INT(11) NOT NULL AUTO_INCREMENT,
13811             `biblionumber` INT(11) NOT NULL,
13812             `format` VARCHAR(16) NOT NULL,
13813             `marcflavour` VARCHAR(16) NOT NULL,
13814             `metadata` LONGTEXT NOT NULL,
13815             PRIMARY KEY(id),
13816             UNIQUE KEY `deletedbiblio_metadata_uniq_key` (`biblionumber`,`format`,`marcflavour`),
13817             CONSTRAINT `deletedbiblio_metadata_fk_1` FOREIGN KEY (biblionumber) REFERENCES deletedbiblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
13818         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13819     });
13820     $dbh->do(q{
13821         INSERT INTO biblio_metadata ( biblionumber, format, marcflavour, metadata ) SELECT biblionumber, 'marcxml', 'CHANGEME', marcxml FROM biblioitems;
13822     });
13823     $dbh->do(q{
13824         INSERT INTO deletedbiblio_metadata ( biblionumber, format, marcflavour, metadata ) SELECT biblionumber, 'marcxml', 'CHANGEME', marcxml FROM deletedbiblioitems;
13825     });
13826     $dbh->do(q{
13827         UPDATE biblio_metadata SET marcflavour = (SELECT value FROM systempreferences WHERE variable="marcflavour");
13828     });
13829     $dbh->do(q{
13830         UPDATE deletedbiblio_metadata SET marcflavour = (SELECT value FROM systempreferences WHERE variable="marcflavour");
13831     });
13832     $dbh->do(q{
13833         ALTER TABLE biblioitems DROP COLUMN marcxml;
13834     });
13835     $dbh->do(q{
13836         ALTER TABLE deletedbiblioitems DROP COLUMN marcxml;
13837     });
13838     SetVersion($DBversion);
13839     print "Upgrade to $DBversion done (Bug 17196 - Move marcxml out of the biblioitems table)\n";
13840 }
13841
13842 $DBversion = '16.12.00.005';
13843 if( CheckVersion( $DBversion ) ) {
13844     $dbh->do( "INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('AuthorityMergeMode','loose','loose|strict','Authority merge mode','Choice')");
13845
13846     SetVersion( $DBversion );
13847     print "Upgrade to $DBversion done (Bug 17913 - AuthorityMergeMode)\n";
13848 }
13849
13850 $DBversion = "16.12.00.006";
13851 if ( CheckVersion($DBversion) ) {
13852     unless (     column_exists( 'borrower_attributes', 'id' )
13853              and index_exists( 'borrower_attributes', 'PRIMARY' ) )
13854     {
13855         $dbh->do(q{
13856             ALTER TABLE `borrower_attributes`
13857                 ADD `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
13858         });
13859     }
13860
13861     print "Upgrade to $DBversion done (Bug 17813: Table borrower_attributes needs a primary key\n";
13862     SetVersion($DBversion);
13863 }
13864
13865 $DBversion = "16.12.00.007";
13866 if( CheckVersion( $DBversion ) ) {
13867
13868     if ( column_exists('opac_news', 'new' ) ) {
13869         $dbh->do(q|ALTER TABLE opac_news CHANGE COLUMN new content text NOT NULL|);
13870     }
13871
13872     $dbh->do(q|
13873         UPDATE letter SET content = REPLACE(content, "<<opac_news.new>>", "<<opac_news.content>>") WHERE content LIKE "%<<opac_news.new>>%"
13874     |);
13875
13876     SetVersion( $DBversion );
13877     print "Upgrade to $DBversion done (Bug 17960 - Rename opac_news with opac_news.content (template notices have been updated!))\n";
13878 }
13879
13880 $DBversion = "16.12.00.008";
13881 if( CheckVersion( $DBversion ) ) {
13882     $dbh->do(q{
13883         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
13884         ('MarcItemFieldsToOrder','','Set the mapping values for new item records created from a MARC record in a staged file. In a YAML format.', NULL, 'textarea');
13885     });
13886
13887     SetVersion( $DBversion );
13888     print "Upgrade to $DBversion done (Bug 15503 - Grab Item Information from Order Files)\n";
13889 }
13890
13891 $DBversion = "16.12.00.009";
13892 if( CheckVersion( $DBversion ) ) {
13893     $dbh->do(q{
13894         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
13895         ('OPACHoldsIfAvailableAtPickup','1','','Allow to pickup up holds at libraries where the item is available','YesNo');
13896     });
13897
13898     $dbh->do(q{
13899         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
13900         ('OPACHoldsIfAvailableAtPickupExceptions','','','List the patron categories not affected by OPACHoldsIfAvailableAtPickup if off','Free');
13901     });
13902
13903     SetVersion( $DBversion );
13904     print "Upgrade to $DBversion done (Bug 17453 - Inter-site holds improvement)\n";
13905 }
13906
13907 $DBversion = "16.12.00.010";
13908 if( CheckVersion( $DBversion ) ) {
13909     $dbh->do(q{
13910         ALTER TABLE borrowers ADD overdrive_auth_token text default NULL AFTER lastseen;
13911     });
13912
13913     $dbh->do(q{
13914         ALTER TABLE deletedborrowers ADD overdrive_auth_token text default NULL AFTER lastseen;
13915     });
13916
13917     $dbh->do(q{
13918         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
13919         VALUES ('OverDriveCirculation','0','Enable client to see their OverDrive account','','YesNo');
13920     });
13921
13922     SetVersion( $DBversion );
13923     print "Upgrade to $DBversion done (Bug 16034 - Integration with OverDrive Patron API)\n";
13924 }
13925
13926 $DBversion = "16.12.00.011";
13927 if( CheckVersion( $DBversion ) ) {
13928     $dbh->do(q{
13929         ALTER TABLE search_field CHANGE COLUMN type type ENUM('', 'string', 'date', 'number', 'boolean', 'sum') NOT NULL
13930         COMMENT 'what type of data this holds, relevant when storing it in the search engine';
13931     });
13932
13933     SetVersion( $DBversion );
13934     print "Upgrade to $DBversion done (Bug 17260 - updatedatabase.pl fails on invalid entries in ENUM and BOOLEAN columns)\n";
13935 }
13936
13937 $DBversion = "16.12.00.012";
13938 if( CheckVersion( $DBversion ) ) {
13939     $dbh->do(q{
13940         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`)
13941         VALUES ('OpacNewsLibrarySelect', '0', '', 'Show selector for branches on OPAC news page', 'YesNo');
13942     });
13943
13944     SetVersion( $DBversion );
13945     print "Upgrade to $DBversion done (Bug 14764 - Add OPAC News branch selector)\n";
13946 }
13947
13948 $DBversion = "16.12.00.013";
13949 if( CheckVersion( $DBversion ) ) {
13950     $dbh->do(q{
13951         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
13952         VALUES ('CircSidebar','0','','Activate or deactivate the navigation sidebar on all Circulation pages','YesNo');
13953     });
13954
13955     SetVersion( $DBversion );
13956     print "Upgrade to $DBversion done (Bug 16530 - Add a circ sidebar navigation menu)\n";
13957 }
13958
13959 $DBversion = "16.12.00.014";
13960 if( CheckVersion( $DBversion ) ) {
13961     $dbh->do(q{
13962             INSERT INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
13963             ('LoadSearchHistoryToTheFirstLoggedUser', '1', NULL, 'If ON, the next user will automatically get the last searches in his history', 'YesNo');
13964             });
13965             SetVersion( $DBversion );
13966             print "Upgrade to $DBversion done (Bug 8010 - Search history can be added to the wrong patron)\n";
13967             }
13968
13969 $DBversion = "16.12.00.015";
13970 if( CheckVersion( $DBversion ) ) {
13971     unless( column_exists( 'branches', 'geolocation' ) ) {
13972         $dbh->do(q|
13973                 ALTER TABLE branches ADD COLUMN geolocation VARCHAR(255) DEFAULT NULL after opac_info
13974                 |);
13975     }
13976
13977     $dbh->do(q|
13978             INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type ) VALUES ('UsageStatsGeolocation', '', NULL, 'Geolocation of the main library', 'Free');
13979             |);
13980     $dbh->do(q|
13981             INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type ) VALUES ('UsageStatsLibrariesInfo', '', NULL, 'Share libraries information', 'YesNo');
13982             |);
13983     $dbh->do(q|
13984             INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type ) VALUES ('UsageStatsPublicID', '', NULL, 'Public ID for Hea website', 'Free');
13985             |);
13986         
13987         SetVersion( $DBversion );
13988     print "Upgrade to $DBversion done (Bug 18066 - Hea version 2)\n";
13989 }
13990
13991 $DBversion = "16.12.00.016";
13992 if ( CheckVersion($DBversion) ) {
13993     unless ( column_exists( 'borrower_attribute_types', 'opac_editable' ) )
13994     {
13995         $dbh->do(q{
13996             ALTER TABLE borrower_attribute_types
13997                 ADD COLUMN `opac_editable` tinyint(1) NOT NULL default 0 AFTER `opac_display`
13998         });
13999     }
14000
14001     print "Upgrade to $DBversion done (Bug 13757: Make patron attributes editable in the opac if set to 'editable in OPAC)'\n";
14002     SetVersion($DBversion);
14003 }
14004
14005 $DBversion = "16.12.00.017";
14006 if ( CheckVersion($DBversion) ) {
14007     $dbh->do(q{
14008         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
14009         VALUES ('CumulativeRestrictionPeriods',  0,  NULL,  'Cumulate the restriction periods instead of keeping the highest',  'YesNo')
14010     });
14011
14012     print "Upgrade to $DBversion done (Bug 14146 - Additional days are not added to restriction period when checking-in several overdues for same patron)'\n";
14013     SetVersion($DBversion);
14014 }
14015
14016 $DBversion = "16.12.00.018";
14017 if ( CheckVersion($DBversion) ) {
14018     $dbh->do(q{
14019         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
14020             SELECT 'ExportCircHistory', COUNT(*), NULL, "Display the export circulation options",  'YesNo'
14021             FROM systempreferences
14022             WHERE ( variable = 'ExportRemoveFields' AND value != "" AND value IS NOT NULL )
14023                 OR ( variable = 'ExportWithCsvProfile' AND value != "" AND value IS NOT NULL );
14024     });
14025
14026     $dbh->do(q{
14027         DELETE FROM systempreferences WHERE variable="ExportWithCsvProfile";
14028     });
14029
14030     print "Upgrade to $DBversion done (Bug 15498 - Replace ExportWithCsvProfile with ExportCircHistory)'\n";
14031     SetVersion($DBversion);
14032 }
14033
14034 $DBversion = "16.12.00.019";
14035 if( CheckVersion( $DBversion ) ) {
14036     if ( column_exists( 'issues', 'return' ) ) {
14037         $dbh->do(q|ALTER TABLE issues DROP column `return`|);
14038     }
14039
14040     if ( column_exists( 'old_issues', 'return' ) ) {
14041         $dbh->do(q|ALTER TABLE old_issues DROP column `return`|);
14042     }
14043
14044     SetVersion( $DBversion );
14045     print "Upgrade to $DBversion done (Bug 18173 - Remove issues.return DB field)\n";
14046 }
14047
14048 $DBversion = "16.12.00.020";
14049 if( CheckVersion( $DBversion ) ) {
14050     $dbh->do(q{
14051         UPDATE systempreferences SET options="any_time_is_placed|not_always|any_time_is_collected" WHERE variable="HoldFeeMode";
14052     });
14053
14054     $dbh->do(q{
14055         UPDATE systempreferences SET value="any_time_is_placed" WHERE variable="HoldFeeMode" AND value="always";
14056     });
14057
14058     SetVersion( $DBversion );
14059     print "Upgrade to $DBversion done (Bug 17560 - Hold fee placement at point of checkout)\n";
14060 }
14061
14062 $DBversion = "16.12.00.021";
14063 if( CheckVersion( $DBversion ) ) {
14064     $dbh->do(q{
14065         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14066         ('RenewalLog','0','','If ON, log information about renewals','YesNo');
14067     });
14068
14069     SetVersion( $DBversion );
14070     print "Upgrade to $DBversion done (Bug 17708 - Renewal log seems empty)\n";
14071 }
14072
14073 $DBversion = "16.12.00.022";
14074 if( CheckVersion( $DBversion ) ) {
14075     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";
14076     SetVersion( $DBversion );
14077     print "Upgrade to $DBversion done (Bug 17866 - Change sender for serial claim notifications)\n";
14078 }
14079
14080 $DBversion = '16.12.00.023';
14081 if( CheckVersion( $DBversion ) ) {
14082     my $oldval = C4::Context->preference('dontmerge');
14083     my $newval = $oldval ? 0 : 50;
14084
14085     # Remove dontmerge, add AuthorityMergeLimit
14086     $dbh->do(q{
14087         DELETE FROM systempreferences WHERE variable = 'dontmerge';
14088     });
14089     $dbh->do(qq{
14090         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');
14091     });
14092
14093     $dbh->do(q{
14094         ALTER TABLE need_merge_authorities
14095             ADD COLUMN authid_new BIGINT AFTER authid,
14096             ADD COLUMN reportxml text AFTER authid_new,
14097             ADD COLUMN timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
14098     });
14099
14100     $dbh->do(q{
14101         UPDATE need_merge_authorities SET authid_new=authid WHERE done <> 1
14102     });
14103
14104     SetVersion( $DBversion );
14105     if( $newval == 0 ) {
14106         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";
14107     }
14108     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";
14109     print "Upgrade to $DBversion done (Bug 9988 - Add AuthorityMergeLimit)\n";
14110 }
14111
14112 $DBversion = '16.12.00.024';
14113 if( CheckVersion( $DBversion ) ) {
14114     $dbh->do(q{
14115         UPDATE systempreferences SET variable="NoticeBcc" WHERE variable="OverdueNoticeBcc";
14116     });
14117
14118     SetVersion( $DBversion );
14119     print "Upgrade to $DBversion done (Bug 14537 - The system preference 'OverdueNoticeBcc' is mis-named.)\n";
14120 }
14121
14122 $DBversion = '16.12.00.025';
14123 if( CheckVersion( $DBversion ) ) {
14124     $dbh->do(q|
14125         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
14126         VALUES ('UploadPurgeTemporaryFilesDays','',NULL,'If not empty, number of days used when automatically deleting temporary uploads','integer');
14127     |);
14128
14129     my ( $cnt ) = $dbh->selectrow_array( "SELECT COUNT(*) FROM uploaded_files WHERE permanent IS NULL or permanent=0" );
14130     if( $cnt ) {
14131         print "NOTE: You have $cnt temporary uploads. You could benefit from setting pref UploadPurgeTemporaryFilesDays now to automatically delete them.\n";
14132     }
14133
14134     SetVersion( $DBversion );
14135     print "Upgrade to $DBversion done (Bug 17669 - Introduce preference for deleting temporary uploads)\n";
14136 }
14137
14138 $DBversion = '16.12.00.026';
14139 if( CheckVersion( $DBversion ) ) {
14140
14141     # In order to be overcomplete, we check if the situation is what we expect
14142     if( !index_exists( 'serialitems', 'PRIMARY' ) ) {
14143         if( index_exists( 'serialitems', 'serialitemsidx' ) ) {
14144             $dbh->do(q|
14145                 ALTER TABLE serialitems ADD PRIMARY KEY (itemnumber), DROP INDEX serialitemsidx;
14146             |);
14147         } else {
14148             $dbh->do(q|ALTER TABLE serialitems ADD PRIMARY KEY (itemnumber)|);
14149         }
14150     }
14151
14152     SetVersion( $DBversion );
14153     print "Upgrade to $DBversion done (Bug 18427 - Add a primary key to serialitems)\n";
14154 }
14155
14156 $DBversion = '16.12.00.027';
14157 if( CheckVersion( $DBversion ) ) {
14158
14159     $dbh->do(q{
14160         CREATE TABLE IF NOT EXISTS club_templates (
14161           id int(11) NOT NULL AUTO_INCREMENT,
14162           `name` tinytext NOT NULL,
14163           description text,
14164           is_enrollable_from_opac tinyint(1) NOT NULL DEFAULT '0',
14165           is_email_required tinyint(1) NOT NULL DEFAULT '0',
14166           branchcode varchar(10) NULL DEFAULT NULL,
14167           date_created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
14168           date_updated timestamp NULL DEFAULT NULL,
14169           is_deletable tinyint(1) NOT NULL DEFAULT '1',
14170           PRIMARY KEY (id),
14171           KEY ct_branchcode (branchcode),
14172           CONSTRAINT `club_templates_ibfk_1` FOREIGN KEY (branchcode) REFERENCES `branches` (branchcode) ON DELETE CASCADE ON UPDATE CASCADE
14173         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14174     });
14175
14176     $dbh->do(q{
14177         CREATE TABLE IF NOT EXISTS clubs (
14178           id int(11) NOT NULL AUTO_INCREMENT,
14179           club_template_id int(11) NOT NULL,
14180           `name` tinytext NOT NULL,
14181           description text,
14182           date_start date DEFAULT NULL,
14183           date_end date DEFAULT NULL,
14184           branchcode varchar(10) NULL DEFAULT NULL,
14185           date_created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
14186           date_updated timestamp NULL DEFAULT NULL,
14187           PRIMARY KEY (id),
14188           KEY club_template_id (club_template_id),
14189           KEY branchcode (branchcode),
14190           CONSTRAINT clubs_ibfk_1 FOREIGN KEY (club_template_id) REFERENCES club_templates (id) ON DELETE CASCADE ON UPDATE CASCADE,
14191           CONSTRAINT clubs_ibfk_2 FOREIGN KEY (branchcode) REFERENCES branches (branchcode)
14192         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14193     });
14194
14195     $dbh->do(q{
14196         CREATE TABLE IF NOT EXISTS club_enrollments (
14197           id int(11) NOT NULL AUTO_INCREMENT,
14198           club_id int(11) NOT NULL,
14199           borrowernumber int(11) NOT NULL,
14200           date_enrolled timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
14201           date_canceled timestamp NULL DEFAULT NULL,
14202           date_created timestamp NULL DEFAULT NULL,
14203           date_updated timestamp NULL DEFAULT NULL,
14204           branchcode varchar(10) NULL DEFAULT NULL,
14205           PRIMARY KEY (id),
14206           KEY club_id (club_id),
14207           KEY borrowernumber (borrowernumber),
14208           KEY branchcode (branchcode),
14209           CONSTRAINT club_enrollments_ibfk_1 FOREIGN KEY (club_id) REFERENCES clubs (id) ON DELETE CASCADE ON UPDATE CASCADE,
14210           CONSTRAINT club_enrollments_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE,
14211           CONSTRAINT club_enrollments_ibfk_3 FOREIGN KEY (branchcode) REFERENCES branches (branchcode) ON DELETE SET NULL ON UPDATE CASCADE
14212         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14213     });
14214
14215     $dbh->do(q{
14216         CREATE TABLE IF NOT EXISTS club_template_enrollment_fields (
14217           id int(11) NOT NULL AUTO_INCREMENT,
14218           club_template_id int(11) NOT NULL,
14219           `name` tinytext NOT NULL,
14220           description text,
14221           authorised_value_category varchar(16) DEFAULT NULL,
14222           PRIMARY KEY (id),
14223           KEY club_template_id (club_template_id),
14224           CONSTRAINT club_template_enrollment_fields_ibfk_1 FOREIGN KEY (club_template_id) REFERENCES club_templates (id) ON DELETE CASCADE ON UPDATE CASCADE
14225         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14226     });
14227
14228     $dbh->do(q{
14229         CREATE TABLE IF NOT EXISTS club_enrollment_fields (
14230           id int(11) NOT NULL AUTO_INCREMENT,
14231           club_enrollment_id int(11) NOT NULL,
14232           club_template_enrollment_field_id int(11) NOT NULL,
14233           `value` text NOT NULL,
14234           PRIMARY KEY (id),
14235           KEY club_enrollment_id (club_enrollment_id),
14236           KEY club_template_enrollment_field_id (club_template_enrollment_field_id),
14237           CONSTRAINT club_enrollment_fields_ibfk_1 FOREIGN KEY (club_enrollment_id) REFERENCES club_enrollments (id) ON DELETE CASCADE ON UPDATE CASCADE,
14238           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
14239         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14240     });
14241
14242     $dbh->do(q{
14243         CREATE TABLE IF NOT EXISTS club_template_fields (
14244           id int(11) NOT NULL AUTO_INCREMENT,
14245           club_template_id int(11) NOT NULL,
14246           `name` tinytext NOT NULL,
14247           description text,
14248           authorised_value_category varchar(16) DEFAULT NULL,
14249           PRIMARY KEY (id),
14250           KEY club_template_id (club_template_id),
14251           CONSTRAINT club_template_fields_ibfk_1 FOREIGN KEY (club_template_id) REFERENCES club_templates (id) ON DELETE CASCADE ON UPDATE CASCADE
14252         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14253     });
14254
14255     $dbh->do(q{
14256         CREATE TABLE IF NOT EXISTS club_fields (
14257           id int(11) NOT NULL AUTO_INCREMENT,
14258           club_template_field_id int(11) NOT NULL,
14259           club_id int(11) NOT NULL,
14260           `value` text,
14261           PRIMARY KEY (id),
14262           KEY club_template_field_id (club_template_field_id),
14263           KEY club_id (club_id),
14264           CONSTRAINT club_fields_ibfk_3 FOREIGN KEY (club_template_field_id) REFERENCES club_template_fields (id) ON DELETE CASCADE ON UPDATE CASCADE,
14265           CONSTRAINT club_fields_ibfk_4 FOREIGN KEY (club_id) REFERENCES clubs (id) ON DELETE CASCADE ON UPDATE CASCADE
14266         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14267     });
14268
14269     $dbh->do(q{
14270         INSERT IGNORE INTO userflags (bit, flag, flagdesc, defaulton) VALUES (21, 'clubs', 'Patron clubs', '0');
14271     });
14272
14273     $dbh->do(q{
14274         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
14275            (21, 'edit_templates', 'Create and update club templates'),
14276            (21, 'edit_clubs', 'Create and update clubs'),
14277            (21, 'enroll', 'Enroll patrons in clubs')
14278         ;
14279     });
14280
14281     SetVersion( $DBversion );
14282     print "Upgrade to $DBversion done (Bug 12461 - Add patron clubs feature)\n";
14283 }
14284
14285 $DBversion = '16.12.00.028';
14286 if( CheckVersion( $DBversion ) ) {
14287     $dbh->do(q{
14288         UPDATE systempreferences  SET options = 'us|de|fr' WHERE variable = 'AddressFormat';
14289     });
14290
14291     SetVersion( $DBversion );
14292     print "Upgrade to $DBversion done (Bug 18110 - Adds FR to the syspref AddressFormat)\n";
14293 }
14294
14295 $DBversion = '16.12.00.029';
14296 if( CheckVersion( $DBversion ) ) {
14297     unless( column_exists( 'issues', 'note' ) ) {
14298         $dbh->do(q|ALTER TABLE issues ADD note mediumtext default NULL AFTER onsite_checkout|);
14299     }
14300     unless( column_exists( 'issues', 'notedate' ) ) {
14301         $dbh->do(q|ALTER TABLE issues ADD notedate datetime default NULL AFTER note|);
14302     }
14303     unless( column_exists( 'old_issues', 'note' ) ) {
14304         $dbh->do(q|ALTER TABLE old_issues ADD note mediumtext default NULL AFTER onsite_checkout|);
14305     }
14306     unless( column_exists( 'old_issues', 'notedate' ) ) {
14307         $dbh->do(q|ALTER TABLE old_issues ADD notedate datetime default NULL AFTER note|);
14308     }
14309
14310     $dbh->do(q|
14311         INSERT IGNORE INTO letter (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`)
14312         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');
14313     |);
14314
14315     $dbh->do(q|
14316         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`,`type`)
14317         VALUES ('AllowCheckoutNotes', '0', NULL, 'Allow patrons to submit notes about checked out items.','YesNo');
14318     |);
14319
14320     SetVersion( $DBversion );
14321     print "Upgrade to $DBversion done (Bug 14224: Add column issues.note and issues.notedate)\n";
14322 }
14323
14324 $DBversion = '16.12.00.030';
14325 if( CheckVersion( $DBversion ) ) {
14326     unless( column_exists( 'issuingrules', 'no_auto_renewal_after_hard_limit' ) ) {
14327         $dbh->do(q{
14328             ALTER TABLE issuingrules ADD COLUMN no_auto_renewal_after_hard_limit DATE DEFAULT NULL AFTER no_auto_renewal_after;
14329         });
14330     }
14331
14332     SetVersion( $DBversion );
14333     print "Upgrade to $DBversion done (Bug 16344 - Add a circ rule to limit the auto renewals given a specific date)\n";
14334 }
14335
14336 $DBversion = '16.12.00.031';
14337 if( CheckVersion( $DBversion ) ) {
14338     if ( !index_exists( 'biblioitems', 'timestamp' ) ) {
14339         $dbh->do("ALTER TABLE biblioitems ADD KEY `timestamp` (`timestamp`);");
14340     }
14341     if ( !index_exists( 'deletedbiblioitems', 'timestamp' ) ) {
14342         $dbh->do("ALTER TABLE deletedbiblioitems ADD KEY `timestamp` (`timestamp`);");
14343     }
14344     if ( !index_exists( 'items', 'timestamp' ) ) {
14345         $dbh->do("ALTER TABLE items ADD KEY `timestamp` (`timestamp`);");
14346     }
14347     if ( !index_exists( 'deleteditems', 'timestamp' ) ) {
14348         $dbh->do("ALTER TABLE deleteditems ADD KEY `timestamp` (`timestamp`);");
14349     }
14350
14351     SetVersion( $DBversion );
14352     print "Upgrade to $DBversion done (Bug 15108: OAI-PMH provider improvements)\n";
14353 }
14354
14355 $DBversion = '16.12.00.032';
14356 if( CheckVersion( $DBversion ) ) {
14357     require Koha::Calendar;
14358
14359     $dbh->do(q{
14360         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) 
14361         VALUES ('ExcludeHolidaysFromMaxPickUpDelay', '0', 'If ON, reserves max pickup delay takes into account the closed days.', NULL, 'Integer');
14362     });
14363
14364     my $waiting_holds = $dbh->selectall_arrayref(q|
14365         SELECT expirationdate, waitingdate, branchcode
14366         FROM reserves
14367         WHERE found = 'W' AND priority = 0
14368     |, { Slice => {} });
14369     my $update_sth = $dbh->prepare(q|
14370         UPDATE reserves
14371         SET expirationdate = ?
14372         WHERE reserve_id = ?
14373     |);
14374     my $max_pickup_delay = C4::Context->preference("ReservesMaxPickUpDelay");
14375     for my $hold ( @$waiting_holds ) {
14376
14377         my $requested_expiration;
14378         if ($hold->{expirationdate}) {
14379             $requested_expiration = dt_from_string($hold->{expirationdate});
14380         }
14381
14382         my $expirationdate = dt_from_string($hold->{waitingdate});
14383         if ( C4::Context->preference("ExcludeHolidaysFromMaxPickUpDelay") ) {
14384             my $calendar = Koha::Calendar->new( branchcode => $hold->{branchcode} );
14385             $expirationdate = $calendar->days_forward( $expirationdate, $max_pickup_delay );
14386         } else {
14387             $expirationdate->add( days => $max_pickup_delay );
14388         }
14389
14390         my $cmp = $requested_expiration ? DateTime->compare($requested_expiration, $expirationdate) : 0;
14391         $update_sth->execute($cmp == -1 ? $requested_expiration->ymd : $expirationdate->ymd, $hold->{reserve_id});
14392     }
14393
14394     SetVersion( $DBversion );
14395     print "Upgrade to $DBversion done (Bug 12063 - Update reserves.expirationdate)\n";
14396 }
14397
14398 $DBversion = '16.12.00.033';
14399 if( CheckVersion( $DBversion ) ) {
14400
14401     if( !column_exists( 'letter', 'lang' ) ) {
14402         $dbh->do( "ALTER TABLE letter ADD COLUMN lang VARCHAR(25) NOT NULL DEFAULT 'default' AFTER message_transport_type" );
14403     }
14404
14405     if( !column_exists( 'borrowers', 'lang' ) ) {
14406         $dbh->do( "ALTER TABLE borrowers ADD COLUMN lang VARCHAR(25) NOT NULL DEFAULT 'default' AFTER lastseen" );
14407         $dbh->do( "ALTER TABLE deletedborrowers ADD COLUMN lang VARCHAR(25) NOT NULL DEFAULT 'default' AFTER lastseen" );
14408     }
14409
14410     # Add test on existene of this key
14411     $dbh->do( "ALTER TABLE message_transports DROP FOREIGN KEY message_transports_ibfk_3 ");
14412     $dbh->do( "ALTER TABLE letter DROP PRIMARY KEY ");
14413     $dbh->do( "ALTER TABLE letter ADD PRIMARY KEY (`module`, `code`, `branchcode`, `message_transport_type`, `lang`) ");
14414
14415     $dbh->do( "INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
14416         VALUES ('TranslateNotices',  '0',  NULL,  'Allow notices to be translated',  'YesNo') ");
14417
14418     SetVersion( $DBversion );
14419     print "Upgrade to $DBversion done (Bug 17762 - Add columns letter.lang and borrowers.lang to allow translation of notices)\n";
14420 }
14421
14422 $DBversion = '16.12.00.034';
14423 if( CheckVersion( $DBversion ) ) {
14424     $dbh->do(q{
14425         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
14426         VALUES ('OPACFineNoRenewalsBlockAutoRenew','0','','Block/Allow auto renewals if the patron owe more than OPACFineNoRenewals','YesNo')
14427     });
14428
14429     SetVersion( $DBversion );
14430     print "Upgrade to $DBversion done (Bug 15582 - Ability to block auto renewals if the OPACFineNoRenewals amount is reached)\n";
14431 }
14432
14433 $DBversion = '16.12.00.035';
14434 if( CheckVersion( $DBversion ) ) {
14435     if( !column_exists( 'issues', 'auto_renew_error' ) ) {
14436         $dbh->do(q{
14437            ALTER TABLE issues ADD COLUMN auto_renew_error VARCHAR(32) DEFAULT NULL AFTER auto_renew;
14438         });
14439     }
14440
14441     if( !column_exists( 'old_issues', 'auto_renew_error' ) ) {
14442         $dbh->do(q{
14443             ALTER TABLE old_issues ADD COLUMN auto_renew_error VARCHAR(32) DEFAULT NULL AFTER auto_renew;
14444         });
14445     }
14446
14447     $dbh->do(q{
14448         INSERT INTO letter (module, code, name, title, content, message_transport_type) VALUES ('circulation', 'AUTO_RENEWALS', 'notification on auto renewing', 'Auto renewals',
14449 "Dear [% borrower.firstname %] [% borrower.surname %],
14450 [% IF checkout.auto_renew_error %]
14451 The following item [% biblio.title %] has not been correctly renewed
14452 [% IF checkout.auto_renew_error == 'too_many' %]
14453 You have reach the maximum of checkouts possible.
14454 [% ELSIF checkout.auto_renew_error == 'on_reserve' %]
14455 This item is on hold for another patron.
14456 [% ELSIF checkout.auto_renew_error == 'restriction' %]
14457 You are currently restricted.
14458 [% ELSIF checkout.auto_renew_error == 'overdue' %]
14459 You have overdues.
14460 [% ELSIF checkout.auto_renew_error == 'auto_too_late' %]
14461 It\'s too late to renew this checkout.
14462 [% ELSIF checkout.auto_renew_error == 'auto_too_much_oweing' %]
14463 You have too much unpaid fines.
14464 [% END %]
14465 [% ELSE %]
14466 The following item [% biblio.title %] has correctly been renewed and is now due [% checkout.date_due %]
14467 [% END %]", 'email');
14468     });
14469
14470     SetVersion( $DBversion );
14471     print "Upgrade to $DBversion done (Bug 15705 - Notify the user on auto renewing)\n";
14472 }
14473
14474 $DBversion = '16.12.00.036';
14475 if( CheckVersion( $DBversion ) ) {
14476     $dbh->do(q{
14477         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
14478         VALUES ('NumSavedReports', '20', NULL, 'By default, show this number of saved reports.', 'Integer');
14479     });
14480
14481     SetVersion( $DBversion );
14482     print "Upgrade to $DBversion done (Bug 17465 - Add a System Preference to control number of Saved Reports displayed)\n";
14483 }
14484
14485 $DBversion = '16.12.00.037';
14486 if( CheckVersion( $DBversion ) ) {
14487     $dbh->do( q|
14488         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
14489         VALUES ('FailedLoginAttempts','','','Number of login attempts before lockout the patron account','Integer');
14490     |);
14491
14492     unless( column_exists( 'borrowers', 'login_attempts' ) ) {
14493         $dbh->do(q|
14494             ALTER TABLE borrowers ADD COLUMN login_attempts INT(4) DEFAULT 0 AFTER lastseen
14495         |);
14496         $dbh->do(q|
14497             ALTER TABLE deletedborrowers ADD COLUMN login_attempts INT(4) DEFAULT 0 AFTER lastseen
14498         |);
14499     }
14500
14501     SetVersion( $DBversion );
14502     print "Upgrade to $DBversion done (Bug 18314 - Add FailedLoginAttempts and borrowers.login_attempts)\n";
14503 }
14504
14505 $DBversion = '16.12.00.038';
14506 if( CheckVersion( $DBversion ) ) {
14507     $dbh->do(q{
14508         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14509         ('ExportRemoveFields','',NULL,'List of fields for non export in circulation.pl (separated by a space)','Free');
14510     });
14511
14512     SetVersion( $DBversion );
14513     print "Upgrade to $DBversion done (Bug 18663 - Missing db update for ExportRemoveFields)\n";
14514 }
14515
14516 $DBversion = '16.12.00.039';
14517 if( CheckVersion( $DBversion ) ) {
14518     $dbh->do(q{
14519         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14520         ('TalkingTechItivaPhoneNotification','0',NULL,'If ON, enables Talking Tech I-tiva phone notifications','YesNo');
14521     });
14522
14523     SetVersion( $DBversion );
14524     print "Upgrade to $DBversion done (Bug 18600 - Missing db update for TalkingTechItivaPhoneNotification)\n";
14525 }
14526
14527 $DBversion = '17.05.00.000';
14528 if( CheckVersion( $DBversion ) ) {
14529
14530     SetVersion( $DBversion );
14531     print "Upgrade to $DBversion done (Koha 17.05)\n";
14532 }
14533
14534 $DBversion = '17.06.00.000';
14535 if( CheckVersion( $DBversion ) ) {
14536     SetVersion( $DBversion );
14537     print "Upgrade to $DBversion done (He pai ake te iti i te kore)\n";
14538 }
14539
14540 $DBversion = '17.06.00.001';
14541 if( CheckVersion( $DBversion ) ) {
14542
14543     unless ( column_exists( 'export_format', 'used_for' ) ) {
14544         $dbh->do(q|ALTER TABLE export_format ADD used_for varchar(255) DEFAULT 'export_records' AFTER type|);
14545
14546         $dbh->do(q|UPDATE export_format SET used_for = 'late_issues' WHERE type = 'sql'|);
14547         $dbh->do(q|UPDATE export_format SET used_for = 'export_records' WHERE type = 'marc'|);
14548     }
14549     SetVersion( $DBversion );
14550     print "Upgrade to $DBversion done (Bug 8612 - Add new column export_format.used_for)\n";
14551 }
14552
14553 $DBversion = '17.06.00.002';
14554 if ( CheckVersion($DBversion) ) {
14555
14556     unless ( column_exists('virtualshelves', 'allow_change_from_owner' ) ) {
14557         $dbh->do(q|
14558             ALTER TABLE virtualshelves
14559             ADD COLUMN allow_change_from_owner tinyint(1) default 1,
14560             ADD COLUMN allow_change_from_others tinyint(1) default 0
14561         |);
14562
14563         # Conversion:
14564         # Since we had no readonly lists, change_from_owner is set to true.
14565         # When adding or delete_other was granted, change_from_others is true.
14566         # Note: In my opinion the best choice; there is no exact match.
14567         $dbh->do(q|
14568             UPDATE virtualshelves
14569             SET allow_change_from_owner = 1,
14570                 allow_change_from_others = CASE WHEN allow_add=1 OR allow_delete_other=1 THEN 1 ELSE 0 END
14571         |);
14572
14573         # Remove the old columns
14574         $dbh->do(q|
14575             ALTER TABLE virtualshelves
14576             DROP COLUMN allow_add,
14577             DROP COLUMN allow_delete_own,
14578             DROP COLUMN allow_delete_other
14579         |);
14580     }
14581
14582     SetVersion($DBversion);
14583     print "Upgrade to $DBversion done (Bug 18228 - Alter table virtualshelves to simplify permissions)\n";
14584 }
14585
14586 $DBversion = '17.06.00.003';
14587 if ( CheckVersion($DBversion) ) {
14588
14589     # Fetch all auth types
14590     my $authtypes = $dbh->selectcol_arrayref(q|SELECT authtypecode FROM auth_types|);
14591
14592     if ( grep { $_ eq 'Default' } @$authtypes ) {
14593
14594         # If this exists as an authtypecode, we don't do anything
14595     }
14596     else {
14597         # Replace the incorrect Default by empty string
14598         $dbh->do(q|
14599             UPDATE auth_header SET authtypecode='' WHERE authtypecode='Default'
14600         |);
14601     }
14602
14603     SetVersion($DBversion);
14604     print "Upgrade to $DBversion done (Bug 18801 - Update incorrect Default auth type codes)\n";
14605 }
14606
14607 $DBversion = '17.06.00.004';
14608 if( CheckVersion( $DBversion ) ) {
14609     $dbh->do(q{
14610         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14611         ('GoogleOpenIDConnectAutoRegister',   '0',NULL,' Google OpenID Connect logins to auto-register patrons.','YesNo'),
14612         ('GoogleOpenIDConnectDefaultCategory','','','This category code will be used to create Google OpenID Connect patrons.','Textarea'),
14613         ('GoogleOpenIDConnectDefaultBranch',  '','','This branch code will be used to create Google OpenID Connect patrons.','Textarea');
14614     });
14615
14616     SetVersion( $DBversion );
14617     print "Upgrade to $DBversion done (Bug 16892: Add automatic patron registration via OAuth2 login)\n";
14618 }
14619
14620 $DBversion = '17.06.00.005';
14621 if( CheckVersion( $DBversion ) ) {
14622     $dbh->do(q{
14623         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')
14624         });
14625
14626     SetVersion( $DBversion );
14627     print "Upgrade to $DBversion done (Bug 18718 - Language selector in staff header menu similar to OPAC )\n";
14628 }
14629
14630 $DBversion = '17.06.00.006';
14631 if( CheckVersion( $DBversion ) ) {
14632     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.};
14633     print "\n";
14634
14635     SetVersion( $DBversion );
14636     print "Upgrade to $DBversion done (Bug 18811 - Visibility settings inconsistent between framework and authority editor)\n";
14637 }
14638
14639 $DBversion = '17.06.00.007';
14640 if( CheckVersion( $DBversion ) ) {
14641     if( !column_exists( 'branches', 'marcorgcode' ) ) {
14642         $dbh->do( "ALTER TABLE branches ADD COLUMN marcorgcode VARCHAR(16) default NULL AFTER geolocation" );
14643     }
14644
14645     SetVersion( $DBversion );
14646     print "Upgrade to $DBversion done (Bug 10132 - MARCOrgCode on branch level (branches.marcorgcode))\n";
14647 }
14648
14649 $DBversion = '17.06.00.008';
14650 if( CheckVersion( $DBversion ) ) {
14651     unless ( column_exists( 'borrowers', 'date_renewed' ) ) {
14652         $dbh->do(q{
14653             ALTER TABLE borrowers ADD COLUMN date_renewed DATE NULL DEFAULT NULL AFTER dateexpiry;
14654         });
14655     }
14656
14657     unless ( column_exists( 'deletedborrowers', 'date_renewed' ) ) {
14658         $dbh->do(q{
14659             ALTER TABLE deletedborrowers ADD COLUMN date_renewed DATE NULL DEFAULT NULL AFTER dateexpiry;
14660         });
14661     }
14662
14663     unless ( column_exists( 'borrower_modifications', 'date_renewed' ) ) {
14664         $dbh->do(q{
14665             ALTER TABLE borrower_modifications ADD COLUMN date_renewed DATE NULL DEFAULT NULL AFTER dateexpiry;
14666         });
14667     }
14668
14669     SetVersion( $DBversion );
14670     print "Upgrade to $DBversion done (Bug 6758 - Capture membership renewal date for reporting purposes (borrowers.date_renewed))\n";
14671 }
14672
14673 $DBversion = '17.06.00.009';
14674 if( CheckVersion( $DBversion ) ) {
14675     $dbh->do(q{
14676         ALTER TABLE borrowers MODIFY COLUMN login_attempts int(4) DEFAULT 0 AFTER lang;
14677     });
14678     $dbh->do(q{
14679         ALTER TABLE deletedborrowers MODIFY COLUMN login_attempts int(4) DEFAULT 0 AFTER lang;
14680     });
14681
14682     SetVersion( $DBversion );
14683     print "Upgrade to $DBversion done (Bug 19344 -  Reorder lang and login_attempts in the [deleted]borrowers tables)\n";
14684 }
14685
14686 $DBversion = '17.06.00.010';
14687 if ( CheckVersion($DBversion) ) {
14688     $dbh->do(q{
14689         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
14690         VALUES (
14691             'DefaultCountryField008','','',
14692             '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')
14693     });
14694     SetVersion($DBversion);
14695     print "Upgrade to $DBversion done (Bug 13912 - System preference for default place of publication (country code) for field 008, range 15-17)\n";
14696 }
14697
14698 $DBversion = '17.06.00.011';
14699 if ( CheckVersion($DBversion) ) {
14700     # Drop index that might exist because of bug 5337
14701     if( index_exists('biblioitems', 'ean')) {
14702         $dbh->do(q{ ALTER TABLE biblioitems DROP INDEX ean });
14703     }
14704     if( index_exists('deletedbiblioitems', 'ean')) {
14705         $dbh->do(q{ ALTER TABLE deletedbiblioitems DROP INDEX ean });
14706     }
14707
14708     # Change data type of column
14709     $dbh->do(q{ ALTER TABLE biblioitems MODIFY COLUMN ean MEDIUMTEXT default NULL });
14710     $dbh->do(q{ ALTER TABLE deletedbiblioitems MODIFY COLUMN ean MEDIUMTEXT default NULL });
14711
14712     # Add indexes
14713     $dbh->do(q{ ALTER TABLE biblioitems ADD INDEX ean ( ean(255) )});
14714     $dbh->do(q{ ALTER TABLE deletedbiblioitems ADD INDEX ean ( ean(255 ) )});
14715
14716     SetVersion($DBversion);
14717     print "Upgrade to $DBversion done (Bug 13766 - Make ean mediumtext and add ean indexes)\n";
14718 }
14719
14720 $DBversion = '17.06.00.012';
14721 if( CheckVersion( $DBversion ) ) {
14722     my $where = q|host='clio-db.cc.columbia.edu' AND port=7090|;
14723     my $sql = "SELECT COUNT(*) FROM z3950servers WHERE $where";
14724     my ( $cnt ) = $dbh->selectrow_array( $sql );
14725     if( $cnt ) {
14726         $dbh->do( "DELETE FROM z3950servers WHERE $where" );
14727         print "Removed $cnt Z39.50 target(s) for Columbia University\n";
14728     }
14729
14730     SetVersion( $DBversion );
14731     print "Upgrade to $DBversion done (Bug 19043 - Z39.50 target for Columbia University is no longer publicly available.)\n";
14732 }
14733
14734 $DBversion = '17.06.00.013';
14735 if( CheckVersion( $DBversion ) ) {
14736     $dbh->do( "UPDATE systempreferences SET value = CONCAT('http://', value) WHERE variable = 'staffClientBaseURL' AND value <> '' AND value NOT LIKE 'http%'" );
14737
14738     my ( $staffClientBaseURL_used_in_notices ) = $dbh->selectrow_array(q|
14739         SELECT COUNT(*) FROM letter where content like "%staffClientBaseURL%"
14740     |);
14741     if ( $staffClientBaseURL_used_in_notices ) {
14742         warn "\tYou may need to update one or more notice templates if they contain 'staffClientBaseURL'\n";
14743     }
14744
14745     SetVersion( $DBversion );
14746     print "Upgrade to $DBversion done (Bug 16401 - fix potentialy bad set staffClientBaseURL preference)\n";
14747 }
14748
14749 $DBversion = '17.06.00.014';
14750 if( CheckVersion( $DBversion ) ) {
14751     unless( column_exists('aqbasket','create_items') ){
14752         $dbh->do(q{
14753             ALTER TABLE aqbasket
14754                 ADD COLUMN create_items ENUM('ordering', 'receiving', 'cataloguing') default NULL AFTER is_standing
14755         });
14756     }
14757
14758     SetVersion( $DBversion );
14759     print "Upgrade to $DBversion done (Bug 15685 - Allow creation of items (AcqCreateItem) to be customizable per-basket)\n";
14760 }
14761
14762 $DBversion = '17.06.00.015';
14763 if( CheckVersion( $DBversion ) ) {
14764     $dbh->do(q{
14765         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES
14766         ('SelfCheckoutByLogin','0',NULL,'Have patrons login into the web-based self checkout system with their username/password or their cardnumber','YesNo')
14767     });
14768
14769     SetVersion( $DBversion );
14770     print "Upgrade to $DBversion done (Bug 19186 - Insert system preference SelfCheckoutByLogin if missing)\n";
14771 }
14772
14773 $DBversion = '17.06.00.016';
14774 if( CheckVersion( $DBversion ) ) {
14775     $dbh->do(q{
14776         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
14777         VALUES ('RequireStrongPassword','0','','Require a strong login password for staff and patrons','YesNo');
14778     });
14779
14780     SetVersion( $DBversion );
14781     print "Upgrade to $DBversion done (Bug 18298 - Allow enforcing password complexity (system preference RequireStrongPassword))\n";
14782 }
14783
14784 $DBversion = '17.06.00.017';
14785 if( CheckVersion( $DBversion ) ) {
14786     unless (TableExists('account_offsets')) {
14787         $dbh->do(q{
14788             DROP TABLE IF EXISTS `accountoffsets`;
14789         });
14790
14791         $dbh->do(q{
14792             CREATE TABLE IF NOT EXISTS `account_offset_types` (
14793               `type` varchar(16) NOT NULL, -- The type of offset this is
14794               PRIMARY KEY (`type`)
14795             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14796         });
14797
14798         $dbh->do(q{
14799             CREATE TABLE IF NOT EXISTS `account_offsets` (
14800               `id` int(11) NOT NULL auto_increment, -- unique identifier for each offset
14801               `credit_id` int(11) NULL DEFAULT NULL, -- The id of the accountline the increased the patron's balance
14802               `debit_id` int(11) NULL DEFAULT NULL, -- The id of the accountline that decreased the patron's balance
14803               `type` varchar(16) NOT NULL, -- The type of offset this is
14804               `amount` decimal(26,6) NOT NULL, -- The amount of the change
14805               `created_on` timestamp NOT NULL default CURRENT_TIMESTAMP,
14806               PRIMARY KEY (`id`),
14807               CONSTRAINT `account_offsets_ibfk_p` FOREIGN KEY (`credit_id`) REFERENCES `accountlines` (`accountlines_id`) ON DELETE CASCADE ON UPDATE CASCADE,
14808               CONSTRAINT `account_offsets_ibfk_f` FOREIGN KEY (`debit_id`) REFERENCES `accountlines` (`accountlines_id`) ON DELETE CASCADE ON UPDATE CASCADE,
14809               CONSTRAINT `account_offsets_ibfk_t` FOREIGN KEY (`type`) REFERENCES `account_offset_types` (`type`) ON DELETE CASCADE ON UPDATE CASCADE
14810             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14811         });
14812
14813         $dbh->do(q{
14814             INSERT IGNORE INTO account_offset_types ( type ) VALUES
14815             ('Writeoff'),
14816             ('Payment'),
14817             ('Lost Item'),
14818             ('Processing Fee'),
14819             ('Manual Debit'),
14820             ('Reverse Payment'),
14821             ('Forgiven'),
14822             ('Dropbox'),
14823             ('Rental Fee'),
14824             ('Fine Update'),
14825             ('Fine');
14826         });
14827     }
14828
14829     SetVersion( $DBversion );
14830     print "Upgrade to $DBversion done (Bug 14826 - Resurrect account offsets table (Add new tables account_offsets and account_offset_types))\n";
14831 }
14832
14833 $DBversion = '17.06.00.018';
14834 if( CheckVersion( $DBversion ) ) {
14835     $dbh->do(q{
14836         INSERT IGNORE INTO systempreferences (variable,value,explanation,type) VALUES ('useDefaultReplacementCost',0,'default replacement cost defined in item type','YesNo');
14837     });
14838     $dbh->do(q{
14839         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');
14840     });
14841     $dbh->do(q{
14842         ALTER TABLE `itemtypes` MODIFY COLUMN `rentalcharge` DECIMAL(28,6) NULL DEFAULT NULL;
14843     });
14844     unless ( column_exists( 'itemtypes', 'defaultreplacecost' ) ) {
14845         $dbh->do(q{
14846             ALTER TABLE `itemtypes` ADD `defaultreplacecost` DECIMAL(28,6) NULL DEFAULT NULL AFTER `rentalcharge`;
14847         });
14848     }
14849     unless ( column_exists( 'itemtypes', 'processfee' ) ) {
14850         $dbh->do(q{
14851             ALTER TABLE `itemtypes` ADD `processfee` DECIMAL(28,6) NULL DEFAULT NULL AFTER `defaultreplacecost`;
14852         });
14853
14854     }
14855     SetVersion( $DBversion );
14856     print "Upgrade to $DBversion done (Bug 12768 - Insert system preferences useDefaultReplacementCost and ProcessingFeeNote + Add new columns defaultreplacecost and processfee to the itemtypes table)\n";
14857 }
14858
14859 $DBversion = '17.06.00.019';
14860 if( CheckVersion( $DBversion ) ) {
14861     $dbh->do(q{
14862         INSERT IGNORE INTO account_offset_types ( type ) VALUES ( 'Processing Fee' );
14863     });
14864
14865     SetVersion( $DBversion );
14866     print "Upgrade to $DBversion done (Bug 12768 - Add 'Processing Fee' to the account_offset_types table if missing)\n";
14867 }
14868
14869 $DBversion = '17.06.00.020';
14870 if( CheckVersion( $DBversion ) ) {
14871     $dbh->do(q{
14872         UPDATE systempreferences
14873         SET
14874             variable='OpacLocationOnDetail',
14875             options='holding|home|both|column',
14876             explanation='In the OPAC detail, display the shelving location on its own column or under a library columns.'
14877         WHERE
14878             variable='OpacLocationBranchToDisplayShelving'
14879     });
14880
14881     SetVersion( $DBversion );
14882     print "Upgrade to $DBversion done (Bug 19028: Add 'shelving location' to holdings table in detail page (Rename syspref OpacLocationBranchToDisplayShelving with OpacLocationOnDetail))\n";
14883 }
14884
14885 $DBversion = '17.06.00.021';
14886 if( CheckVersion( $DBversion ) ) {
14887     $dbh->do(q{
14888         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')
14889     });
14890
14891     SetVersion( $DBversion );
14892     print "Upgrade to $DBversion done (Bug 17381 - Add system preference SCOMainUserBlock)\n";
14893 }
14894
14895 $DBversion = '17.06.00.022';
14896 if( CheckVersion( $DBversion ) ) {
14897     my $hide_barcode = C4::Context->preference('OPACShowBarcode') ? 0 : 1;
14898     $dbh->do(q{
14899         DELETE FROM systempreferences
14900         WHERE
14901             variable='OPACShowBarcode'
14902     });
14903
14904     # Configure column visibility if it isn't
14905     $dbh->do(q{
14906         INSERT IGNORE INTO columns_settings
14907             (module,page,tablename,columnname,cannot_be_toggled,is_hidden)
14908         VALUES
14909             ('opac','biblio-detail','holdingst','item_barcode',0,?)
14910     }, undef, $hide_barcode);
14911
14912     SetVersion( $DBversion );
14913     print "Upgrade to $DBversion done (Bug 19038: Remove OPACShowBarcode syspref)\n";
14914 }
14915
14916 $DBversion = '17.06.00.023';
14917 if( CheckVersion( $DBversion ) ) {
14918     $dbh->do(q{
14919         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14920         ('MarkLostItemsAsReturned','1','','Mark items as returned when flagged as lost','YesNo');
14921     });
14922
14923     SetVersion( $DBversion );
14924     print "Upgrade to $DBversion done (Bug 12363 - Add system preference MarkLostItemsAsReturned)\n";
14925 }
14926
14927 $DBversion = '17.06.00.024';
14928 if( CheckVersion( $DBversion ) ) {
14929     $dbh->do(q{
14930         INSERT IGNORE INTO systempreferences (`variable`,`value`,`options`,`explanation`,`type`) VALUES
14931         ('OPACUserSummary', 1, NULL, "Show the summary of a logged in user's checkouts, overdues, holds and fines on the mainpage", 'YesNo');
14932     });
14933
14934     SetVersion( $DBversion );
14935     print "Upgrade to $DBversion done (Bug 2093 - Add system preference OPACUserSummary)\n";
14936 }
14937
14938 $DBversion = '17.06.00.025';
14939 if( CheckVersion( $DBversion ) ) {
14940     $dbh->do(q{
14941         ALTER TABLE borrowers MODIFY cardnumber varchar(32);
14942     });
14943     $dbh->do(q{
14944         ALTER TABLE borrower_modifications MODIFY cardnumber varchar(32);
14945     });
14946     $dbh->do(q{
14947         ALTER TABLE deletedborrowers MODIFY cardnumber varchar(32);
14948     });
14949     $dbh->do(q{
14950         ALTER TABLE pending_offline_operations MODIFY cardnumber varchar(32);
14951     });
14952     $dbh->do(q{
14953         ALTER TABLE tmp_holdsqueue MODIFY cardnumber varchar(32);
14954     });
14955
14956     SetVersion( $DBversion );
14957     print "Upgrade to $DBversion done (Bug 13178 - Increase cardnumber fields to VARCHAR(32))\n";
14958 }
14959
14960 $DBversion = '17.06.00.026';
14961 if( CheckVersion( $DBversion ) ) {
14962     $dbh->do(q{
14963         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14964         ('BlockReturnOfLostItems','0','0','If enabled, items that are marked as lost cannot be returned.','YesNo');
14965     });
14966
14967     SetVersion( $DBversion );
14968     print "Upgrade to $DBversion done (Bug 10748 - Add system preference BlockReturnOfLostItems)\n";
14969 }
14970
14971 $DBversion = '17.06.00.027';
14972 if( CheckVersion( $DBversion ) ) {
14973     if ( !column_exists( 'statistics', 'location' ) ) {
14974         $dbh->do('ALTER TABLE statistics ADD COLUMN location VARCHAR(80) default NULL AFTER itemtype');
14975     }
14976
14977     SetVersion($DBversion);
14978     print "Upgrade to $DBversion done (Bug 18882 - Add location code to statistics table for checkouts and renewals)\n";
14979 }
14980
14981 $DBversion = '17.06.00.028';
14982 if( CheckVersion( $DBversion ) ) {
14983     if ( !TableExists( 'illrequests' ) ) {
14984         $dbh->do(q{
14985             CREATE TABLE illrequests (
14986                illrequest_id serial PRIMARY KEY,           -- ILL request number
14987                borrowernumber integer DEFAULT NULL,        -- Patron associated with request
14988                biblio_id integer DEFAULT NULL,             -- Potential bib linked to request
14989                branchcode varchar(50) NOT NULL,            -- The branch associated with the request
14990                status varchar(50) DEFAULT NULL,            -- Current Koha status of request
14991                placed date DEFAULT NULL,                   -- Date the request was placed
14992                replied date DEFAULT NULL,                  -- Last API response
14993                updated timestamp DEFAULT CURRENT_TIMESTAMP -- Last modification to request
14994                  ON UPDATE CURRENT_TIMESTAMP,
14995                completed date DEFAULT NULL,                -- Date the request was completed
14996                medium varchar(30) DEFAULT NULL,            -- The Koha request type
14997                accessurl varchar(500) DEFAULT NULL,        -- Potential URL for accessing item
14998                cost varchar(20) DEFAULT NULL,              -- Cost of request
14999                notesopac text DEFAULT NULL,                -- Patron notes attached to request
15000                notesstaff text DEFAULT NULL,               -- Staff notes attached to request
15001                orderid varchar(50) DEFAULT NULL,           -- Backend id attached to request
15002                backend varchar(20) DEFAULT NULL,           -- The backend used to create request
15003                CONSTRAINT `illrequests_bnfk`
15004                  FOREIGN KEY (`borrowernumber`)
15005                  REFERENCES `borrowers` (`borrowernumber`)
15006                  ON UPDATE CASCADE ON DELETE CASCADE,
15007                CONSTRAINT `illrequests_bcfk_2`
15008                  FOREIGN KEY (`branchcode`)
15009                  REFERENCES `branches` (`branchcode`)
15010                  ON UPDATE CASCADE ON DELETE CASCADE
15011            ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
15012         });
15013     }
15014
15015     if ( !TableExists( 'illrequestattributes' ) ) {
15016         $dbh->do(q{
15017             CREATE TABLE illrequestattributes (
15018                 illrequest_id bigint(20) unsigned NOT NULL, -- ILL request number
15019                 type varchar(200) NOT NULL,                 -- API ILL property name
15020                 value text NOT NULL,                        -- API ILL property value
15021                 PRIMARY KEY  (`illrequest_id`,`type`),
15022                 CONSTRAINT `illrequestattributes_ifk`
15023                   FOREIGN KEY (illrequest_id)
15024                   REFERENCES `illrequests` (`illrequest_id`)
15025                   ON UPDATE CASCADE ON DELETE CASCADE
15026             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
15027         });
15028     }
15029
15030     # System preferences
15031     $dbh->do(q{
15032         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
15033             ('ILLModule','0','If ON, enables the interlibrary loans module.','','YesNo');
15034     });
15035
15036     $dbh->do(q{
15037         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
15038             ('ILLModuleCopyrightClearance','','70|10','Enter text to enable the copyright clearance stage of request creation. Text will be displayed','Textarea');
15039     });
15040     # userflags
15041     $dbh->do(q{
15042         INSERT IGNORE INTO userflags (bit,flag,flagdesc,defaulton) VALUES
15043             (22,'ill','The Interlibrary Loans Module',0);
15044     });
15045
15046     SetVersion( $DBversion );
15047     print "Upgrade to $DBversion done (Bug 7317 - Add an Interlibrary Loan Module to Circulation and OPAC)\n";
15048 }
15049
15050 $DBversion = '17.11.00.000';
15051 if( CheckVersion( $DBversion ) ) {
15052     SetVersion( $DBversion );
15053     print "Upgrade to $DBversion done (Koha 17.11)\n";
15054 }
15055
15056 $DBversion = '17.12.00.000';
15057 if( CheckVersion( $DBversion ) ) {
15058     SetVersion( $DBversion );
15059     print "Upgrade to $DBversion done (Tē tōia, tē haumatia)\n";
15060 }
15061
15062 $DBversion = '17.12.00.001';
15063 if( CheckVersion( $DBversion ) ) {
15064     foreach my $table (qw(biblio_metadata deletedbiblio_metadata)) {
15065         if (!column_exists($table, 'timestamp')) {
15066             $dbh->do(qq{
15067                 ALTER TABLE `$table`
15068                 ADD COLUMN `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER `metadata`,
15069                 ADD KEY `timestamp` (`timestamp`)
15070             });
15071             $dbh->do(qq{
15072                 UPDATE $table metadata
15073                     LEFT JOIN biblioitems ON (biblioitems.biblionumber = metadata.biblionumber)
15074                     LEFT JOIN biblio ON (biblio.biblionumber = metadata.biblionumber)
15075                 SET metadata.timestamp = GREATEST(biblioitems.timestamp, biblio.timestamp);
15076             });
15077         }
15078     }
15079
15080     SetVersion( $DBversion );
15081     print "Upgrade to $DBversion done (Bug 19724 - Add [deleted]biblio_metadata.timestamp)\n";
15082 }
15083
15084 $DBversion = '17.12.00.002';
15085 if( CheckVersion( $DBversion ) ) {
15086
15087     my $msss = $dbh->selectall_arrayref(q|
15088         SELECT kohafield, tagfield, tagsubfield, frameworkcode
15089         FROM marc_subfield_structure
15090         WHERE   frameworkcode != ''
15091     |, { Slice => {} });
15092
15093
15094     my $sth = $dbh->prepare(q|
15095         SELECT kohafield
15096         FROM marc_subfield_structure
15097         WHERE frameworkcode = ''
15098         AND tagfield = ?
15099         AND tagsubfield = ?
15100     |);
15101
15102     my @exceptions;
15103     for my $mss ( @$msss ) {
15104         $sth->execute($mss->{tagfield}, $mss->{tagsubfield} );
15105         my ( $default_kohafield ) = $sth->fetchrow_array();
15106         if( $mss->{kohafield} ) {
15107             push @exceptions, { frameworkcode => $mss->{frameworkcode}, tagfield => $mss->{tagfield}, tagsubfield => $mss->{tagsubfield}, kohafield => $mss->{kohafield} } if not $default_kohafield or $default_kohafield ne $mss->{kohafield};
15108         } else {
15109             push @exceptions, { frameworkcode => $mss->{frameworkcode}, tagfield => $mss->{tagfield}, tagsubfield => $mss->{tagsubfield}, kohafield => q{} } if $default_kohafield;
15110         }
15111     }
15112
15113     if (@exceptions) {
15114         print "WARNING: The Default framework is now considered as authoritative for Koha to MARC mappings. We have found that your additional frameworks contained "
15115           . scalar(@exceptions)
15116           . " 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";
15117         for my $exception (@exceptions) {
15118             print "Field "
15119               . $exception->{tagfield} . '$'
15120               . $exception->{tagsubfield}
15121               . " in framework "
15122               . $exception->{frameworkcode} . ': ';
15123             if ( $exception->{kohafield} ) {
15124                 print "Mapping to "
15125                   . $exception->{kohafield}
15126                   . " has been adjusted.\n";
15127             }
15128             else {
15129                 print "Mapping has been reset.\n";
15130             }
15131         }
15132
15133         # Sync kohafield
15134
15135         # Clear the destination frameworks first
15136         $dbh->do(q|
15137             UPDATE marc_subfield_structure
15138             SET kohafield = NULL
15139             WHERE   frameworkcode > ''
15140                 AND     Kohafield > ''
15141         |);
15142
15143         # Now copy from Default
15144         my $msss = $dbh->selectall_arrayref(q|
15145             SELECT kohafield, tagfield, tagsubfield
15146             FROM marc_subfield_structure
15147             WHERE   frameworkcode = ''
15148                 AND     kohafield > ''
15149         |, { Slice => {} });
15150         my $sth = $dbh->prepare(q|
15151             UPDATE marc_subfield_structure
15152             SET kohafield = ?
15153             WHERE frameworkcode > ''
15154             AND tagfield = ?
15155             AND tagsubfield = ?
15156         |);
15157         for my $mss (@$msss) {
15158             $sth->execute( $mss->{kohafield}, $mss->{tagfield},
15159                 $mss->{tagsubfield} );
15160         }
15161
15162         # Clear the cache
15163         my @frameworkcodes = $dbh->selectall_arrayref(q|
15164             SELECT frameworkcode FROM biblio_framework WHERE frameworkcode > ''
15165         |);
15166         for my $frameworkcode (@frameworkcodes) {
15167             Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
15168         }
15169         Koha::Caches->get_instance->clear_from_cache("default_value_for_mod_marc-");
15170     }
15171
15172     SetVersion( $DBversion );
15173     print "Upgrade to $DBversion done (Bug 19096 - Make Default authoritative for Koha to MARC mappings)\n";
15174 }
15175
15176 $DBversion = '17.12.00.003';
15177 if( CheckVersion( $DBversion ) ) {
15178     $dbh->do(q|DROP TABLE IF EXISTS notifys|);
15179
15180     if( column_exists( 'accountlines', 'notify_id' ) ) {
15181         $dbh->do(q|ALTER TABLE accountlines DROP COLUMN notify_id|);
15182         $dbh->do(q|ALTER TABLE accountlines DROP COLUMN notify_level|);
15183     }
15184
15185     SetVersion( $DBversion );
15186     print "Upgrade to $DBversion done (Bug 10021 - Drop notifys-related table and columns)\n";
15187 }
15188
15189 $DBversion = '17.12.00.004';
15190 if( CheckVersion( $DBversion ) ) {
15191     $dbh->do(q{
15192         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
15193         VALUES
15194             ('RESTdefaultPageSize','20','','Set the default number of results returned by the REST API endpoints','Integer')
15195     });
15196
15197     SetVersion( $DBversion );
15198     print "Upgrade to $DBversion done (Bug 19278 - Add a configurable default page size for REST endpoints)\n";
15199 }
15200
15201 $DBversion = '17.12.00.005';
15202 if( CheckVersion( $DBversion ) ) {
15203     # For installations having the note already
15204     $dbh->do(q{
15205         UPDATE letter
15206         SET code    = 'CHECKOUT_NOTE',
15207             name    = 'Checkout note on item set by patron',
15208             title   = 'Checkout note',
15209             content = REPLACE(content, "<<biblio.item>>", "<<biblio.title>>")
15210         WHERE code = 'PATRON_NOTE'
15211     });
15212     # For installations coming from 17.11
15213     $dbh->do(q{
15214         INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`)
15215         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')
15216     });
15217
15218     SetVersion( $DBversion );
15219     print "Upgrade to $DBversion done (Bug 18915 - Correct CHECKOUT_NOTE notice template)\n";
15220 }
15221
15222 $DBversion = '17.12.00.006';
15223 if( CheckVersion( $DBversion ) ) {
15224     $dbh->do(q{
15225         UPDATE systempreferences SET value=replace(value, "http://www.scholar", "https://scholar") WHERE variable='OPACSearchForTitleIn';
15226     });
15227
15228     SetVersion( $DBversion );
15229     print "Upgrade to $DBversion done (Bug 17682 - Update URL for Google Scholar in OPACSearchForTitleIn)\n";
15230 }
15231
15232 $DBversion = '17.12.00.007';
15233 if( CheckVersion( $DBversion ) ) {
15234
15235     unless ( TableExists( 'library_groups' ) ) {
15236         $dbh->do(q{
15237             CREATE TABLE library_groups (
15238                 id INT(11) NOT NULL auto_increment,    -- unique id for each group
15239                 parent_id INT(11) NULL DEFAULT NULL,   -- if this is a child group, the id of the parent group
15240                 branchcode VARCHAR(10) NULL DEFAULT NULL, -- The branchcode of a branch belonging to the parent group
15241                 title VARCHAR(100) NULL DEFAULT NULL,     -- Short description of the goup
15242                 description TEXT NULL DEFAULT NULL,    -- Longer explanation of the group, if necessary
15243                 created_on TIMESTAMP NULL,             -- Date and time of creation
15244                 updated_on TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- Date and time of last
15245                 PRIMARY KEY id ( id ),
15246                 FOREIGN KEY (parent_id) REFERENCES library_groups(id) ON UPDATE CASCADE ON DELETE CASCADE,
15247                 FOREIGN KEY (branchcode) REFERENCES branches(branchcode) ON UPDATE CASCADE ON DELETE CASCADE,
15248                 UNIQUE KEY title ( title )
15249             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
15250         });
15251     }
15252
15253     SetVersion( $DBversion );
15254     print "Upgrade to $DBversion done (Bug 15707 - Add new table library_groups)\n";
15255 }
15256
15257 $DBversion = '17.12.00.008';
15258 if ( CheckVersion($DBversion) ) {
15259
15260     if ( TableExists( 'branchcategories' ) and TableExists('branchrelations' )) {
15261         $dbh->do(q{
15262             INSERT INTO library_groups ( title, description, created_on ) VALUES ( '__SEARCH_GROUPS__', 'Library search groups', NOW() )
15263         });
15264         my $search_groups_root_id = $dbh->last_insert_id(undef, undef, 'library_groups', undef);
15265
15266         my $sth = $dbh->prepare("SELECT * FROM branchcategories");
15267
15268         my $sth2 = $dbh->prepare("INSERT INTO library_groups ( parent_id, title, description, created_on ) VALUES ( ?, ?, ?, NOW() )");
15269
15270         my $sth3 = $dbh->prepare("SELECT * FROM branchrelations WHERE categorycode = ?");
15271
15272         my $sth4 = $dbh->prepare("INSERT INTO library_groups ( parent_id, branchcode, created_on ) VALUES ( ?, ?, NOW() )");
15273
15274         $sth->execute();
15275         while ( my $lc = $sth->fetchrow_hashref ) {
15276             my $description = $lc->{categorycode};
15277             $description .= " - " . $lc->{codedescription} if $lc->{codedescription};
15278
15279             $sth2->execute($search_groups_root_id, $lc->{categoryname}, $description);
15280
15281             my $subgroup_id = $dbh->last_insert_id(undef, undef, 'library_groups', undef);
15282
15283             $sth3->execute( $lc->{categorycode} );
15284
15285             while ( my $l = $sth3->fetchrow_hashref ) {
15286                 $sth4->execute( $subgroup_id, $l->{branchcode} );
15287             }
15288         }
15289
15290         $dbh->do("DROP TABLE branchrelations");
15291         $dbh->do("DROP TABLE branchcategories");
15292     }
15293
15294     print "Upgrade to $DBversion done (Bug 16735 - Migrate library search groups into the new hierarchical groups)\n";
15295     SetVersion($DBversion);
15296 }
15297
15298 $DBversion = '17.12.00.009';
15299 if ( CheckVersion($DBversion) ) {
15300     $dbh->do(q|
15301         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
15302         (4, 'edit_borrowers', 'Add, modify and view patron information'),
15303         (4, 'view_borrower_infos_from_any_libraries', 'View patron infos from any libraries');
15304     |);
15305
15306     # We are lucky here, there is nothing else to do: flags 4-borrowers did not contain sub permissions
15307
15308     SetVersion( $DBversion );
15309     print "Upgrade to $DBversion done (Bug 18403 - Add the view_borrower_infos_from_any_libraries permission )\n";
15310 }
15311
15312 $DBversion = '17.12.00.010';
15313 if( CheckVersion( $DBversion ) ) {
15314
15315     if( !column_exists( 'library_groups', 'ft_hide_patron_info' ) ) {
15316         $dbh->do( "ALTER TABLE library_groups ADD COLUMN ft_hide_patron_info tinyint(1) NOT NULL DEFAULT 0 AFTER description" );
15317     }
15318
15319     SetVersion( $DBversion );
15320     print "Upgrade to $DBversion done (Bug 20133 - Add library_groups.ft_hide_patron_info)\n";
15321 }
15322
15323 $DBversion = '17.12.00.011';
15324 if( CheckVersion( $DBversion ) ) {
15325
15326     if( !column_exists( 'library_groups', 'ft_search_groups_opac' ) ) {
15327         $dbh->do( "ALTER TABLE library_groups ADD COLUMN ft_search_groups_opac tinyint(1) NOT NULL DEFAULT 0 AFTER ft_hide_patron_info" );
15328         $dbh->do( "ALTER TABLE library_groups ADD COLUMN ft_search_groups_staff tinyint(1) NOT NULL DEFAULT 0 AFTER ft_search_groups_opac" );
15329         $dbh->do( "UPDATE library_groups SET ft_search_groups_staff = 1 AND ft_search_groups_opac = 1 WHERE title = '__SEARCH_GROUPS__'" );
15330     }
15331
15332     SetVersion( $DBversion );
15333     print "Upgrade to $DBversion done (Bug 20157 - Use group 'features' to decide which groups to use for group searching functionality)\n";
15334 }
15335
15336 $DBversion = '17.12.00.012';
15337 if( CheckVersion( $DBversion ) ) {
15338
15339     $dbh->do( q|
15340         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15341         VALUES ('AutoSwitchPatron', '0', '', 'Auto switch to patron', 'YesNo');
15342     |);
15343
15344     SetVersion( $DBversion );
15345     print "Upgrade to $DBversion done (Bug 15752 - Add system preference AutoSwitchPatron)\n";
15346 }
15347
15348 $DBversion = '17.12.00.013';
15349 if( CheckVersion( $DBversion ) ) {
15350
15351     $dbh->do(q|
15352         ALTER TABLE club_enrollments MODIFY date_created timestamp NULL DEFAULT NULL;
15353     |);
15354
15355     SetVersion( $DBversion );
15356     print "Upgrade to $DBversion done (Bug 20175 - Set DEFAULT NULL value for club_enrollments.date_created)\n";
15357 }
15358
15359 $DBversion = '17.12.00.014';
15360 if( CheckVersion( $DBversion ) ) {
15361     $dbh->do( "UPDATE marc_subfield_structure SET kohafield=NULL where kohafield='additionalauthors.author'" );
15362     SetVersion( $DBversion );
15363     print "Upgrade to $DBversion done (Bug 19790 - Remove additionalauthors.author from installer files)\n";
15364 }
15365
15366 $DBversion = '17.12.00.015';
15367 if( CheckVersion( $DBversion ) ) {
15368     $dbh->do(q|
15369         ALTER TABLE borrowers
15370         MODIFY surname MEDIUMTEXT,
15371         MODIFY address MEDIUMTEXT,
15372         MODIFY city MEDIUMTEXT
15373     |);
15374     $dbh->do(q|
15375         ALTER TABLE deletedborrowers
15376         MODIFY surname MEDIUMTEXT,
15377         MODIFY address MEDIUMTEXT,
15378         MODIFY city MEDIUMTEXT
15379     |);
15380
15381     $dbh->do(q|
15382         ALTER TABLE export_format
15383         MODIFY csv_separator VARCHAR(2) NOT NULL DEFAULT ',',
15384         MODIFY field_separator VARCHAR(2),
15385         MODIFY subfield_separator VARCHAR(2)
15386     |);
15387     $dbh->do(q|
15388         ALTER TABLE export_format MODIFY encoding VARCHAR(255) NOT NULL DEFAULT 'utf8'
15389     |);
15390
15391     $dbh->do(q|
15392         ALTER TABLE reserves MODIFY lowestPriority tinyint(1) NOT NULL DEFAULT 0
15393     |);
15394     $dbh->do(q|
15395         ALTER TABLE old_reserves MODIFY lowestPriority tinyint(1) NOT NULL DEFAULT 0
15396     |);
15397
15398     SetVersion( $DBversion );
15399     print "Upgrade to $DBversion done (Bug 20144 - Adapt DB structure to work with new SQL modes)\n";
15400 }
15401
15402 $DBversion = '17.12.00.016';
15403 if( CheckVersion( $DBversion ) ) {
15404     $dbh->do(q|SET foreign_key_checks = 0|);
15405     my $sth = $dbh->table_info( '','','','TABLE' );
15406
15407     while ( my ( $cat, $schema, $name, $type, $remarks ) = $sth->fetchrow_array ) {
15408         my $table_sth = $dbh->prepare(qq|SHOW CREATE TABLE $name|);
15409         $table_sth->execute;
15410         my @table = $table_sth->fetchrow_array;
15411         unless ( $table[1] =~ /COLLATE=utf8mb4_unicode_ci/ ) {
15412             # Some users might have done the upgrade to utf8mb4 on their own
15413             # to support supplemental chars (japanese, chinese, etc)
15414             if ( $name eq 'additional_fields' ) {
15415                 $dbh->do(qq|
15416                     ALTER TABLE $name
15417                         DROP KEY `fields_uniq`,
15418                         ADD UNIQUE KEY `fields_uniq` (`tablename` (191), `name` (191))
15419                 |);
15420                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15421             }
15422             elsif ( $name eq 'authorised_values' ) {
15423                 $dbh->do(qq|
15424                     ALTER TABLE $name
15425                         DROP KEY `lib`,
15426                         ADD KEY `lib` (`lib` (191))
15427                 |);
15428                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15429             }
15430             elsif ( $name eq 'borrower_modifications' ) {
15431                 $dbh->do(qq|
15432                     ALTER TABLE $name
15433                         DROP PRIMARY KEY,
15434                         DROP KEY `verification_token`,
15435                         ADD PRIMARY KEY (`verification_token` (191),`borrowernumber`),
15436                         ADD KEY `verification_token` (`verification_token` (191))
15437                 |);
15438                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15439             }
15440             elsif ( $name eq 'columns_settings' ) {
15441                 $dbh->do(qq|
15442                     ALTER TABLE $name
15443                         DROP PRIMARY KEY,
15444                         ADD PRIMARY KEY (`module` (191), `page` (191), `tablename` (191), `columnname` (191))
15445                 |);
15446                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15447             }
15448             elsif ( $name eq 'illrequestattributes' ) {
15449                 $dbh->do(qq|
15450                     ALTER TABLE $name
15451                         DROP PRIMARY KEY,
15452                         ADD PRIMARY KEY  (`illrequest_id`, `type` (191))
15453                 |);
15454                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15455             }
15456             elsif ( $name eq 'items_search_fields' ) {
15457                 $dbh->do(qq|
15458                     ALTER TABLE $name
15459                         DROP PRIMARY KEY,
15460                         ADD PRIMARY KEY (`name` (191))
15461                 |);
15462                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15463             }
15464             elsif ( $name eq 'marc_subfield_structure' ) {
15465                 # In this case we convert each column explicitly
15466                 # to preserve 'tagsubield' collation (utf8mb4_bin)
15467                 $dbh->do(qq|
15468                     ALTER TABLE $name
15469                         MODIFY COLUMN tagfield
15470                             VARCHAR(3) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
15471                         MODIFY COLUMN tagsubfield
15472                             VARCHAR(1) COLLATE utf8mb4_bin NOT NULL DEFAULT '',
15473                         MODIFY COLUMN liblibrarian
15474                             VARCHAR(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
15475                         MODIFY COLUMN libopac
15476                             VARCHAR(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
15477                         MODIFY COLUMN kohafield
15478                             VARCHAR(40) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15479                         MODIFY COLUMN authorised_value
15480                             VARCHAR(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15481                         MODIFY COLUMN authtypecode
15482                             VARCHAR(20) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15483                         MODIFY COLUMN value_builder
15484                             VARCHAR(80) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15485                         MODIFY COLUMN frameworkcode
15486                             VARCHAR(4) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
15487                         MODIFY COLUMN seealso
15488                             VARCHAR(1100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15489                         MODIFY COLUMN link
15490                             VARCHAR(80) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15491                         MODIFY COLUMN defaultvalue
15492                             MEDIUMTEXT COLLATE utf8mb4_unicode_ci default NULL
15493                 |);
15494                 $dbh->do(qq|ALTER TABLE $name CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15495             }
15496             elsif ( $name eq 'plugin_data' ) {
15497                 $dbh->do(qq|
15498                     ALTER TABLE $name
15499                         DROP PRIMARY KEY,
15500                         ADD PRIMARY KEY (`plugin_class` (191), `plugin_key` (191))
15501                 |);
15502                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15503             }
15504             elsif ( $name eq 'search_field' ) {
15505                 $dbh->do(qq|
15506                     ALTER TABLE $name
15507                         DROP KEY `name`,
15508                         ADD UNIQUE KEY `name` (`name` (191))
15509                 |);
15510                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15511             }
15512             elsif ( $name eq 'search_marc_map' ) {
15513                 $dbh->do(qq|
15514                     ALTER TABLE $name
15515                         DROP KEY `index_name`,
15516                         ADD UNIQUE KEY `index_name` (`index_name`, `marc_field` (191), `marc_type`)
15517                 |);
15518                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15519             }
15520             elsif ( $name eq 'sms_providers' ) {
15521                 $dbh->do(qq|
15522                     ALTER TABLE $name
15523                         DROP KEY `name`,
15524                         ADD UNIQUE KEY `name` (`name` (191))
15525                 |);
15526                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15527             }
15528             elsif ( $name eq 'tags' ) {
15529                 $dbh->do(qq|
15530                     ALTER TABLE $name
15531                         DROP PRIMARY KEY,
15532                         ADD PRIMARY KEY (`entry` (191))
15533                 |);
15534                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15535             }
15536             elsif ( $name eq 'tags_approval' ) {
15537                 $dbh->do(qq|
15538                     ALTER TABLE $name
15539                         MODIFY COLUMN `term` VARCHAR(191) NOT NULL
15540                 |);
15541                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15542             }
15543             elsif ( $name eq 'tags_index' ) {
15544                 $dbh->do(qq|
15545                     ALTER TABLE $name
15546                         MODIFY COLUMN `term` VARCHAR(191) NOT NULL
15547                 |);
15548                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15549             }
15550             else {
15551                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15552             }
15553         }
15554     }
15555     $dbh->do(q|SET foreign_key_checks = 1|);
15556
15557     print "Upgrade to $DBversion done (Bug 18336 - Convert DB tables to utf8mb4 🎁)\n";
15558     SetVersion($DBversion);
15559 }
15560
15561
15562 $DBversion = '17.12.00.017';
15563 if( CheckVersion( $DBversion ) ) {
15564
15565     if( !column_exists( 'items', 'damaged_on' ) ) {
15566         $dbh->do( "ALTER TABLE items ADD COLUMN damaged_on DATETIME NULL AFTER damaged");
15567     }
15568     if( !column_exists( 'deleteditems', 'damaged_on' ) ) {
15569         $dbh->do( "ALTER TABLE deleteditems ADD COLUMN damaged_on DATETIME NULL AFTER damaged");
15570     }
15571
15572     SetVersion( $DBversion );
15573     print "Upgrade to $DBversion done (Bug 17672 - Add damaged_on to items and deleteditems tables)\n";
15574 }
15575
15576 $DBversion = '17.12.00.018';
15577 if( CheckVersion( $DBversion ) ) {
15578
15579     $dbh->do( q|
15580         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')
15581     |);
15582
15583     SetVersion( $DBversion );
15584     print "Upgrade to $DBversion done (Bug 19290 - Add system preference BrowseResultSelection)\n";
15585 }
15586
15587 $DBversion = '17.12.00.019';
15588 if( CheckVersion( $DBversion ) ) {
15589
15590     $dbh->do(q|UPDATE auth_subfield_structure SET hidden=1 WHERE hidden<>0|);
15591
15592     SetVersion( $DBversion );
15593     print "Upgrade to $DBversion done (Bug 20074 - Auth_subfield_structure changes hidden attribute)\n";
15594 }
15595
15596 $DBversion = '17.12.00.020';
15597 if( CheckVersion( $DBversion ) ) {
15598
15599     $dbh->do(q|
15600         INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)
15601         VALUES ('vi', 'language', 'de', 'Vietnamesisch')
15602     |);
15603
15604     $dbh->do(q|
15605         UPDATE language_descriptions SET description = 'Tiếng Việt'
15606         WHERE subtag = 'vi' and type = 'language' and lang = 'vi'
15607     |);
15608
15609     SetVersion( $DBversion );
15610     print "Upgrade to $DBversion done (Bug 20082 - Update descriptions of Vietnamese language)\n";
15611 }
15612
15613 $DBversion = '17.12.00.021';
15614 if( CheckVersion( $DBversion ) ) {
15615
15616     $dbh->do(q|
15617         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
15618         ('PurgeSuggestionsOlderThan', '', NULL, 'Default value for cronjob purge_suggestions.pl', 'Integer');
15619     |);
15620
15621     SetVersion( $DBversion );
15622     print "Upgrade to $DBversion done (Bug 13287 - Add system preference PurgeSuggestionsOlderThan)\n";
15623 }
15624
15625 $DBversion = '17.12.00.022';
15626 if( CheckVersion( $DBversion ) ) {
15627
15628     if( !column_exists( 'currency', 'p_sep_by_space' ) ) {
15629         $dbh->do(q|
15630             ALTER TABLE currency ADD COLUMN p_sep_by_space tinyint(1) default 0 after archived
15631         |);
15632     }
15633
15634     SetVersion( $DBversion );
15635     print "Upgrade to $DBversion done (Bug 4078 - Add column currency.p_sep_by_space)\n";
15636 }
15637
15638 $DBversion = '17.12.00.023';
15639 if( CheckVersion( $DBversion ) ) {
15640     $dbh->do(q{
15641         DELETE FROM systempreferences
15642         WHERE variable='checkdigit'
15643     });
15644
15645     SetVersion( $DBversion );
15646     print "Upgrade to $DBversion done (Bug 20264 - Remove system preference 'checkdigit')\n";
15647 }
15648
15649 $DBversion = '17.12.00.024';
15650 if( CheckVersion( $DBversion ) ) {
15651
15652     $dbh->do(q{
15653         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15654         VALUES ('SelfCheckInMainUserBlock', '', '70|10', 'Add a block of HTML that will display on the self check-in screen.', 'Textarea');
15655     });
15656
15657     $dbh->do(q{
15658         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15659         VALUES ('SelfCheckInModule', 0, NULL, 'Enable the standalone self-checkin module.', 'YesNo');
15660     });
15661
15662     $dbh->do(q{
15663         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15664         VALUES ('SelfCheckInModuleUserID', NULL, NULL, 'Patron ID (borrowernumber) to be allowed on the self-checkin module.', 'Integer');
15665     });
15666
15667     $dbh->do(q{
15668         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15669         VALUES ('SelfCheckInTimeout', 120, NULL, 'Define the number of seconds before the self check-in module times out.', 'Integer');
15670     });
15671
15672     $dbh->do(q{
15673         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15674         VALUES ('SelfCheckInUserCSS', '', NULL, 'Add CSS to be included in the self check-in module in an embedded <style> tag.', 'free');
15675     });
15676
15677     $dbh->do(q{
15678         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15679         VALUES ('SelfCheckInUserJS', '', NULL, 'Define custom javascript for inclusion in the self check-in module.', 'free');
15680     });
15681
15682     # Add new userflag for self check
15683     $dbh->do(q{
15684         INSERT IGNORE INTO userflags (bit,flag,flagdesc,defaulton) VALUES
15685             (23,'self_check','Self check modules',0);
15686     });
15687
15688     # Add self check-in module subpermission
15689     $dbh->do(q{
15690         INSERT IGNORE INTO permissions (module_bit,code,description)
15691         VALUES (23, 'self_checkin_module', 'Log into the self check-in module');
15692     });
15693
15694     # Add self check-in module subpermission
15695     $dbh->do(q{
15696         INSERT IGNORE INTO permissions (module_bit,code,description)
15697         VALUES (23, 'self_checkout_module', 'Perform self checkout at the OPAC. It should be used for the patron matching the AutoSelfCheckID');
15698     });
15699
15700     # Update patrons with self_checkout permission
15701     # IMPORTANT: Needs to happen before removing the old subpermission
15702     $dbh->do(q{
15703         UPDATE user_permissions
15704         SET module_bit = 23,
15705                   code = 'self_checkout_module'
15706         WHERE module_bit = 1 AND code = 'self_checkout';
15707     });
15708
15709     # Remove old self_checkout permission
15710     $dbh->do(q{
15711         DELETE IGNORE FROM permissions
15712         WHERE  code='self_checkout';
15713     });
15714
15715     SetVersion( $DBversion );
15716     print "Upgrade to $DBversion done (Bug 15492 - Add a standalone self-checkin module)\n";
15717 }
15718
15719 $DBversion = '17.12.00.025';
15720 if( CheckVersion( $DBversion ) ) {
15721     $dbh->do(q|
15722         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
15723         VALUES ('StaffLoginInstructions','','HTML to go into the login box for the staff client',NULL,'Free')
15724     |);
15725     $dbh->do(q|
15726         UPDATE systempreferences
15727         SET variable = 'OpacLoginInstructions'
15728         WHERE variable = 'NoLoginInstructions'
15729     |);
15730
15731     SetVersion( $DBversion );
15732     print "Upgrade to $DBversion done (Bug 20291 - Add StaffLoginInstructions system preference and rename NoLoginInstructions with OpacLoginInstructions)\n";
15733 }
15734
15735 $DBversion = '17.12.00.026';
15736 if( CheckVersion( $DBversion ) ) {
15737     if( !column_exists( 'issuingrules', 'suspension_chargeperiod' ) ) {
15738         $dbh->do(q|
15739             ALTER TABLE issuingrules ADD COLUMN suspension_chargeperiod int(11) DEFAULT '1' AFTER maxsuspensiondays;
15740         |);
15741     }
15742
15743     SetVersion( $DBversion );
15744     print "Upgrade to $DBversion done (Bug 19804 - Add issuingrules.suspension_chargeperiod)\n";
15745 }
15746
15747 $DBversion = '17.12.00.027';
15748 if( CheckVersion( $DBversion ) ) {
15749     $dbh->do(q|
15750         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
15751         VALUES ('UseACQFrameworkForBiblioRecords','0','','Use the ACQ framework for the catalog details','YesNo')
15752     |);
15753
15754     SetVersion( $DBversion );
15755     print "Upgrade to $DBversion done (Bug 19289 - Add system preference UseACQFrameworkForBiblioRecords)\n";
15756 }
15757
15758 $DBversion = '17.12.00.028';
15759 if( CheckVersion( $DBversion ) ) {
15760     if( !column_exists( 'marc_tag_structure', 'ind1_defaultvalue' ) ) {
15761         $dbh->do(q|
15762             ALTER TABLE marc_tag_structure
15763             ADD COLUMN ind2_defaultvalue VARCHAR(1) NOT NULL DEFAULT '' AFTER authorised_value,
15764             ADD COLUMN ind1_defaultvalue VARCHAR(1) NOT NULL DEFAULT '' AFTER authorised_value;
15765         |);
15766     }
15767
15768     SetVersion( $DBversion );
15769     print "Upgrade to $DBversion done (Bug 9701 - Add default indicators (marc_tag_structure.indX_defaultvalue))\n";
15770 }
15771
15772 $DBversion = '17.12.00.029';
15773 if( CheckVersion( $DBversion ) ) {
15774     my $pref =
15775 q|# PERSO_NAME  100 600 696 700 796 800 896
15776 marc21, 100, ind1:auth1
15777 marc21, 600, ind1:auth1, ind2:thesaurus
15778 marc21, 696, ind1:auth1
15779 marc21, 700, ind1:auth1
15780 marc21, 796, ind1:auth1
15781 marc21, 800, ind1:auth1
15782 marc21, 896, ind1:auth1
15783 # CORPO_NAME  110 610 697 710 797 810 897
15784 marc21, 110, ind1:auth1
15785 marc21, 610, ind1:auth1, ind2:thesaurus
15786 marc21, 697, ind1:auth1
15787 marc21, 710, ind1:auth1
15788 marc21, 797, ind1:auth1
15789 marc21, 810, ind1:auth1
15790 marc21, 897, ind1:auth1
15791 # MEETI_NAME    111 611 698 711 798 811 898
15792 marc21, 111, ind1:auth1
15793 marc21, 611, ind1:auth1, ind2:thesaurus
15794 marc21, 698, ind1:auth1
15795 marc21, 711, ind1:auth1
15796 marc21, 798, ind1:auth1
15797 marc21, 811, ind1:auth1
15798 marc21, 898, ind1:auth1
15799 # UNIF_TITLE        130 440 630 699 730 799 830 899 / 240
15800 marc21, 130, ind1:auth2
15801 marc21, 240, , ind2:auth2
15802 marc21, 440, , ind2:auth2
15803 marc21, 630, ind1:auth2, ind2:thesaurus
15804 marc21, 699, ind1:auth2
15805 marc21, 730, ind1:auth2
15806 marc21, 799, ind1:auth2
15807 marc21, 830, , ind2:auth2
15808 marc21, 899, ind1:auth2
15809 # CHRON_TERM    648
15810 marc21, 648, , ind2:thesaurus
15811 # TOPIC_TERM      650 654 656 657 658 690
15812 marc21, 650, , ind2:thesaurus
15813 # GEOGR_NAME   651 662 691 / 751
15814 marc21, 651, , ind2:thesaurus
15815 # GENRE/FORM    655
15816 marc21, 655, , ind2:thesaurus
15817
15818 # UNIMARC: Always copy the indicators from the authority
15819 unimarc, *, ind1:auth1, ind2:auth2|;
15820
15821     $dbh->do( q|
15822         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
15823         VALUES ( 'AuthorityControlledIndicators', ?, 'Authority controlled indicators per biblio field', NULL, 'Free' );
15824     |, undef, $pref );
15825
15826     SetVersion( $DBversion );
15827     print "Upgrade to $DBversion done (Bug 14769 - Authorities merge: Set correct indicators in biblio field (new system preference AuthorityControlledIndicators))\n";
15828 }
15829
15830 $DBversion = '17.12.00.030';
15831 if( CheckVersion( $DBversion ) ) {
15832     $dbh->do(q|
15833         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
15834         VALUES ('NovelistSelectStaffProfile',NULL,'Novelist staff client user Profile',NULL,'free')
15835     |);
15836
15837     SetVersion( $DBversion );
15838     print "Upgrade to $DBversion done (Bug 19882 - Add system preference NovelistSelectStaffProfile)\n";
15839 }
15840
15841 $DBversion = '17.12.00.031';
15842 if( CheckVersion( $DBversion ) ) {
15843     $dbh->do(q|
15844         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
15845         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')
15846     |);
15847
15848     SetVersion( $DBversion );
15849     print "Upgrade to $DBversion done (Bug 11674 - Add system preference MarcFieldDocURL)\n";
15850 }
15851
15852 $DBversion = '17.12.00.032';
15853 if( CheckVersion( $DBversion ) ) {
15854     $dbh->do(q|
15855         UPDATE letter SET code = "SERIAL_ALERT" WHERE code = "RLIST";
15856     |);
15857     $dbh->do(q|
15858         UPDATE letter SET name = "New serial issue" WHERE name = "Routing List";
15859     |);
15860     $dbh->do(q|
15861         UPDATE subscription SET letter = "SERIAL_ALERT" WHERE letter = "RLIST";
15862     |);
15863
15864     SetVersion( $DBversion );
15865     print "Upgrade to $DBversion done (Bug 19794 - Rename RLIST notice to SERIAL_ALERT)\n";
15866 }
15867
15868 $DBversion = '17.12.00.033';
15869 if( CheckVersion( $DBversion ) ) {
15870     if ( !column_exists( 'accountlines', 'payment_type' ) ) {
15871         $dbh->do(q{
15872             ALTER TABLE accountlines ADD payment_type varchar(80) default NULL AFTER accounttype
15873         });
15874     }
15875
15876     $dbh->do(q{
15877         INSERT IGNORE INTO authorised_value_categories( category_name ) VALUES ('PAYMENT_TYPE')
15878     });
15879
15880     SetVersion( $DBversion );
15881     print "Upgrade to $DBversion done (Bug 18786 - Add ability to create custom payment types)\n";
15882 }
15883
15884 $DBversion = '17.12.00.034';
15885 if( CheckVersion( $DBversion ) ) {
15886
15887     $dbh->do( q{
15888         INSERT IGNORE INTO account_offset_types ( type ) VALUES ('Void Payment')
15889     } );
15890
15891     SetVersion( $DBversion );
15892     print "Upgrade to $DBversion done (Bug 18790 - Add ability to void payment)\n";
15893 }
15894
15895 $DBversion = '17.12.00.035';
15896 if( CheckVersion( $DBversion ) ) {
15897     my ( $original_value ) = $dbh->selectrow_array(q|
15898         SELECT value FROM systempreferences WHERE variable="MarkLostItemsAsReturned"
15899     |);
15900     if ( $original_value and $original_value eq '1' ) {
15901         $dbh->do(q{
15902             UPDATE systempreferences
15903             SET type="multiple",
15904                 options="batchmod|moredetail|cronjob|additem",
15905                 value="batchmod,moredetail,cronjob,additem"
15906             WHERE variable="MarkLostItemsAsReturned"
15907         });
15908     } else {
15909         $dbh->do(q{
15910             UPDATE systempreferences
15911             SET type="multiple",
15912                 options="batchmod|moredetail|cronjob|additem",
15913                 value=""
15914             WHERE variable="MarkLostItemsAsReturned"
15915         });
15916     }
15917
15918     SetVersion( $DBversion );
15919     print "Upgrade to $DBversion done (Bug 19974 - Make MarkLostItemsAsReturned multiple)\n";
15920 }
15921
15922 $DBversion = '17.12.00.036';
15923 if( CheckVersion( $DBversion ) ) {
15924
15925     $dbh->do( q{
15926         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');
15927     } );
15928     $dbh->do( q{
15929         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');
15930     } );
15931     $dbh->do( q{
15932         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');
15933     } );
15934     $dbh->do( q{
15935         UPDATE systempreferences SET options="batchmod|moredetail|cronjob|additem|pendingreserves" WHERE variable="MarkLostItemsAsReturned";
15936     } );
15937
15938     SetVersion( $DBversion );
15939     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";
15940 }
15941
15942 $DBversion = '17.12.00.037';
15943 if( CheckVersion( $DBversion ) ) {
15944
15945     SetVersion( $DBversion );
15946     print "Upgrade to $DBversion done (This change has been reverted, nothing done!)\n";
15947 }
15948
15949 $DBversion = '17.12.00.038';
15950 if( CheckVersion( $DBversion ) ) {
15951
15952     $dbh->do( q{
15953         UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'slo' WHERE iso639_2_code = 'slk' AND rfc4646_subtag = 'sk';
15954     } );
15955
15956     SetVersion( $DBversion );
15957     print "Upgrade to $DBversion done (Bug 20245 - Use Bibliographic code value for Slovak language)\n";
15958 }
15959
15960 $DBversion = '17.12.00.039';
15961 if( CheckVersion( $DBversion ) ) {
15962
15963     $dbh->do( q{
15964         UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'baq' WHERE iso639_2_code = 'eus' AND rfc4646_subtag = 'eu';
15965     } );
15966     $dbh->do( q{
15967         UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'mao' WHERE iso639_2_code = 'mri' AND rfc4646_subtag = 'mi';
15968     } );
15969     $dbh->do( q{
15970         UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'alb' WHERE iso639_2_code = 'sqi' AND rfc4646_subtag = 'sq';
15971     } );
15972
15973     SetVersion( $DBversion );
15974     print "Upgrade to $DBversion done (Bug 20482 - Use Bibliographic code value for Basque, Maori and Albanian languages)\n";
15975 }
15976
15977 $DBversion = '17.12.00.040';
15978 if( CheckVersion( $DBversion ) ) {
15979
15980     $dbh->do( q{
15981         INSERT IGNORE INTO systempreferences ( value, variable, options, explanation, type )
15982         VALUES ( '0', 'ProtectSuperlibrarianPrivileges', NULL, 'If enabled, non-superlibrarians cannot set superlibrarian privileges', 'YesNo' )
15983     } );
15984
15985     SetVersion( $DBversion );
15986     print "Upgrade to $DBversion done (Bug 20100 - Add new system preference ProtectSuperlibrarianPrivileges)\n";
15987 }
15988
15989 $DBversion = '17.12.00.041';
15990 if( CheckVersion( $DBversion ) ) {
15991
15992     $dbh->do( q{
15993         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES (13, 'access_files', 'Access to the files stored on the server');
15994     } );
15995
15996     SetVersion( $DBversion );
15997     print "Upgrade to $DBversion done (Bug 11317 - Add a new permission to access files stored on the server)\n";
15998 }
15999
16000 $DBversion = '17.12.00.042';
16001 if( CheckVersion( $DBversion ) ) {
16002
16003     if (!TableExists('oauth_access_tokens')) {
16004         $dbh->do(q{
16005             CREATE TABLE oauth_access_tokens (
16006                 `access_token` VARCHAR(191) NOT NULL,
16007                 `client_id`    VARCHAR(191) NOT NULL,
16008                 `expires`      INT NOT NULL,
16009                 PRIMARY KEY (`access_token`)
16010             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
16011         });
16012     }
16013
16014     SetVersion( $DBversion );
16015     print "Upgrade to $DBversion done (Bug 20402 - Implement OAuth2 authentication for REST API)\n";
16016 }
16017
16018 $DBversion = '17.12.00.043';
16019 if(CheckVersion($DBversion)) {
16020
16021     if (!TableExists('api_keys')) {
16022         $dbh->do(q{
16023             CREATE TABLE `api_keys` (
16024                 `client_id`   VARCHAR(191) NOT NULL,
16025                 `secret`      VARCHAR(191) NOT NULL,
16026                 `description` VARCHAR(255) NOT NULL,
16027                 `patron_id`   INT(11) NOT NULL,
16028                 `active`      TINYINT(1) DEFAULT 1 NOT NULL,
16029                 PRIMARY KEY `client_id` (`client_id`),
16030                 UNIQUE KEY `secret` (`secret`),
16031                 KEY `patron_id` (`patron_id`),
16032                 CONSTRAINT `api_keys_fk_patron_id`
16033                   FOREIGN KEY (`patron_id`)
16034                   REFERENCES `borrowers` (`borrowernumber`)
16035                   ON DELETE CASCADE ON UPDATE CASCADE
16036             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16037         });
16038     }
16039
16040     print "Upgrade to $DBversion done (Bug 20568 - Add API key management interface for patrons)\n";
16041     SetVersion($DBversion);
16042 }
16043
16044 $DBversion = '17.12.00.044';
16045 if(CheckVersion($DBversion)) {
16046
16047     $dbh->do(q{
16048         INSERT IGNORE INTO systempreferences (`variable`,`value`,`options`,`explanation`,`type`)
16049         VALUES
16050             ('RESTOAuth2ClientCredentials','0',NULL,'If enabled, the OAuth2 client credentials flow is enabled for the REST API.','YesNo');
16051     });
16052
16053     print "Upgrade to $DBversion done (Bug 20624 - Disable OAuth2 client credentials grant by default)\n";
16054     SetVersion($DBversion);
16055 }
16056
16057 $DBversion = '18.05.00.000';
16058 if( CheckVersion( $DBversion ) ) {
16059     SetVersion( $DBversion );
16060     print "Upgrade to $DBversion done (Koha 18.05)\n";
16061 }
16062
16063 $DBversion = '18.06.00.000';
16064 if( CheckVersion( $DBversion ) ) {
16065     SetVersion( $DBversion );
16066     print "Upgrade to $DBversion done (Koha 18.06 - It's Adventure time!)\n";
16067 }
16068
16069 $DBversion = '18.06.00.001';
16070 if( CheckVersion( $DBversion ) ) {
16071     $dbh->do(q{UPDATE permissions SET description = 'Manage budgets' WHERE code = 'period_manage';});
16072     $dbh->do(q{UPDATE permissions SET description = 'Manage funds' WHERE code = 'budget_manage';});
16073     $dbh->do(q{UPDATE permissions SET description = 'Modify funds (can''t create lines, but can modify existing ones)' WHERE code = 'budget_modify';});
16074     $dbh->do(q{UPDATE permissions SET description = 'Manage baskets and order lines' WHERE code = 'order_manage';});
16075     $dbh->do(q{UPDATE permissions SET description = 'Manage all baskets and order lines, regardless of restrictions on them' WHERE code = 'order_manage_all';});
16076     $dbh->do(q{UPDATE permissions SET description = 'Manage basket groups' WHERE code = 'group_manage';});
16077     $dbh->do(q{UPDATE permissions SET description = 'Receive orders and manage shipments' WHERE code = 'order_receive';});
16078     $dbh->do(q{UPDATE permissions SET description = 'Add and delete funds (but can''t modify funds)' WHERE code = 'budget_add_del';});
16079     $dbh->do(q{UPDATE permissions SET description = 'Manage all funds' WHERE code = 'budget_manage_all';});
16080     SetVersion( $DBversion );
16081     print "Upgrade to $DBversion done (Bug 3849- Improve descriptions of granular acquisition permissions)\n";
16082 }
16083
16084 $DBversion = '18.06.00.002';
16085 if( CheckVersion( $DBversion ) ) {
16086     $dbh->do(q{DELETE FROM userflags WHERE bit = 12 AND flag = 'management';});
16087     $dbh->do(q{UPDATE borrowers SET flags = flags - ( flags & (1<<12) ) WHERE flags & (1 << 12);});
16088     SetVersion( $DBversion );
16089     print "Upgrade to $DBversion done (Bug 2426 - Remove deprecated management permission)\n";
16090 }
16091
16092 $DBversion = '18.06.00.003';
16093 if( CheckVersion( $DBversion ) ) {
16094     $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'" );
16095     SetVersion( $DBversion );
16096     print "Upgrade to $DBversion done (Bug 20073 - Add new types for Elasticsearch fields)\n";
16097 }
16098
16099 $DBversion = '18.06.00.004';
16100 if( CheckVersion( $DBversion ) ) {
16101
16102     # Add 'Manual Credit' offset type
16103     $dbh->do(q{
16104         INSERT IGNORE INTO `account_offset_types` (`type`) VALUES ('Manual Credit');
16105     });
16106
16107     # Fix wrong account offsets / Manual credits
16108     $dbh->do(q{
16109         UPDATE account_offsets
16110         SET credit_id=debit_id,
16111             debit_id=NULL,
16112             type='Manual Credit'
16113         WHERE amount < 0 AND
16114               type='Manual Debit' AND
16115               debit_id IN
16116                 (SELECT accountlines_id AS debit_id
16117                  FROM accountlines
16118                  WHERE accounttype='C');
16119     });
16120
16121     # Fix wrong account offsets / Manually forgiven amounts
16122     $dbh->do(q{
16123         UPDATE account_offsets
16124         SET credit_id=debit_id,
16125             debit_id=NULL,
16126             type='Writeoff'
16127         WHERE amount < 0 AND
16128               type='Manual Debit' AND
16129               debit_id IN
16130                 (SELECT accountlines_id AS debit_id
16131                  FROM accountlines
16132                  WHERE accounttype='FOR');
16133     });
16134
16135     SetVersion( $DBversion );
16136     print "Upgrade to $DBversion done (Bug 20980 - Manual credit offsets are stored as debits)\n";
16137 }
16138
16139 $DBversion = '18.06.00.005';
16140 if( CheckVersion( $DBversion ) ) {
16141     unless ( column_exists('aqorders', 'created_by') ) {
16142         $dbh->do( "ALTER TABLE aqorders ADD COLUMN created_by int(11) NULL DEFAULT NULL AFTER quantityreceived;" );
16143         unless ( foreign_key_exists('aqorders', 'aqorders_created_by') ) {
16144             $dbh->do( "ALTER TABLE aqorders ADD CONSTRAINT aqorders_created_by FOREIGN KEY (created_by) REFERENCES borrowers (borrowernumber) ON DELETE SET NULL ON UPDATE CASCADE;" );
16145         }
16146         $dbh->do( "UPDATE aqbasket LEFT JOIN borrowers ON ( aqbasket.authorisedby = borrowers.borrowernumber ) SET aqbasket.authorisedby = NULL WHERE borrowers.borrowernumber IS NULL;" );
16147         $dbh->do( "UPDATE aqorders LEFT JOIN aqbasket ON ( aqorders.basketno = aqbasket.basketno ) SET aqorders.created_by = aqbasket.authorisedby WHERE aqorders.created_by IS NULL;" );
16148     }
16149     SetVersion( $DBversion );
16150     print "Upgrade to $DBversion done (Bug 12395 - Save order line's creator)\n";
16151 }
16152
16153 $DBversion = '18.06.00.006';
16154 if( CheckVersion( $DBversion ) ) {
16155     unless ( column_exists('patron_lists', 'shared') ) {
16156         $dbh->do( "ALTER TABLE patron_lists ADD COLUMN shared tinyint(1) default 0 AFTER owner;" );
16157     }
16158     SetVersion( $DBversion );
16159     print "Upgrade to $DBversion done (Bug 19524 - Share patron lists between staff)\n";
16160 }
16161
16162 $DBversion = '18.06.00.007';
16163 if( CheckVersion( $DBversion ) ) {
16164     $dbh->do( "INSERT IGNORE INTO permissions (module_bit, code, description) VALUES (11, 'currencies_manage', 'Manage currencies and exchange rates');" );
16165     $dbh->do(q{
16166         INSERT IGNORE INTO user_permissions (borrowernumber, module_bit, code)
16167             SELECT borrowernumber, 11, 'currencies_manage' FROM borrowers WHERE flags & (1 << 3) OR borrowernumber IN
16168             (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16169     });
16170     SetVersion( $DBversion );
16171     print "Upgrade to $DBversion done (Bug 7651 - Add separate permission for managing currencies and exchange rates)\n";
16172 }
16173
16174 $DBversion = '18.06.00.008';
16175 if( CheckVersion( $DBversion ) ) {
16176     $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')" );
16177     SetVersion( $DBversion );
16178     print "Upgrade to $DBversion done (Bug 13560 - need an add option in marc modification templates)\n";
16179 }
16180
16181 $DBversion = '18.06.00.009';
16182 if( CheckVersion( $DBversion ) ) {
16183     $dbh->do( "
16184         CREATE TABLE IF NOT EXISTS aqinvoice_adjustments (
16185             adjustment_id int(11) NOT NULL AUTO_INCREMENT,
16186             invoiceid int(11) NOT NULL,
16187             adjustment decimal(28,6),
16188             reason varchar(80) default NULL,
16189             note mediumtext default NULL,
16190             budget_id int(11) default NULL,
16191             encumber_open smallint(1) NOT NULL default 1,
16192             timestamp timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
16193             PRIMARY KEY (adjustment_id),
16194             CONSTRAINT aqinvoice_adjustments_fk_invoiceid FOREIGN KEY (invoiceid) REFERENCES aqinvoices (invoiceid) ON DELETE CASCADE ON UPDATE CASCADE,
16195             CONSTRAINT aqinvoice_adjustments_fk_budget_id FOREIGN KEY (budget_id) REFERENCES aqbudgets (budget_id) ON DELETE SET NULL ON UPDATE CASCADE
16196         ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
16197         " );
16198     $dbh->do("INSERT IGNORE INTO authorised_value_categories (category_name) VALUES ('ADJ_REASON')");
16199     SetVersion( $DBversion );
16200     print "Upgrade to $DBversion done (Bug 19166 - Add the ability to add adjustments to an invoice)\n";
16201 }
16202
16203 $DBversion = '18.06.00.010';
16204 if( CheckVersion( $DBversion ) ) {
16205     $dbh->do(q{
16206         INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`, `lang`)
16207         VALUES
16208             ('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'),
16209                 ('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');
16210     });
16211     $dbh->do(q{
16212         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
16213         VALUES ('UseEmailReceipts','0','','Send email receipts for payments and write-offs','YesNo')
16214     });
16215     SetVersion( $DBversion );
16216     print "Upgrade to $DBversion done (Bug 19191 - Add ability to email receipts for account payments and write-offs)\n";
16217 }
16218
16219 $DBversion = '18.06.00.011';
16220 if( CheckVersion( $DBversion ) ) {
16221     unless( column_exists( 'issues', 'noteseen' ) ) {
16222         $dbh->do(q|ALTER TABLE issues ADD COLUMN noteseen int(1) default NULL AFTER notedate|);
16223     }
16224
16225     unless( column_exists( 'old_issues', 'noteseen' ) ) {
16226         $dbh->do(q|ALTER TABLE old_issues ADD COLUMN noteseen int(1) default NULL AFTER notedate|);
16227     }
16228     $dbh->do(q|INSERT IGNORE INTO permissions (module_bit, code, description) VALUES ( 1, 'manage_checkout_notes', 'Mark checkout notes as seen/not seen');|);
16229     SetVersion( $DBversion );
16230     print "Upgrade to $DBversion done (Bug 17698: Add column issues.noteseen and old_issues.noteseen)\n";
16231 }
16232
16233 $DBversion = '18.06.00.012';
16234 if( CheckVersion( $DBversion ) ) {
16235     $dbh->do(q|INSERT IGNORE INTO permissions (module_bit, code, description) VALUES (11, 'suggestions_manage', 'Manage purchase suggestions');|);
16236     $dbh->do(q|INSERT IGNORE INTO user_permissions (borrowernumber, module_bit, code) SELECT borrowernumber, 11, 'suggestions_manage' FROM borrowers WHERE flags & (1 << 2);|);
16237     SetVersion( $DBversion );
16238     print "Upgrade to $DBversion done (Bug 11911 - Add separate permission for managing suggestions)\n";
16239 }
16240
16241 $DBversion = '18.06.00.013';
16242 if( CheckVersion( $DBversion ) ) {
16243     $dbh->do(q{
16244         INSERT IGNORE INTO `account_offset_types` (`type`) VALUES ('Credit Applied');
16245     });
16246     SetVersion( $DBversion );
16247     print "Upgrade to $DBversion done (Bug 20997 - Add Koha::Account::Line::apply)\n";
16248 }
16249
16250 $DBversion = '18.06.00.014';
16251 if( CheckVersion( $DBversion ) ) {
16252     $dbh->do(q{
16253             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');
16254     });
16255     SetVersion( $DBversion );
16256     print "Upgrade to $DBversion done (Bug 21121 - New syspref to allow hiding of private patron data in circulation page)\n";
16257 }
16258
16259 $DBversion = '18.06.00.015';
16260 if( CheckVersion( $DBversion ) ) {
16261     $dbh->do(q{DELETE FROM systempreferences where variable="OCLCAffiliateID";});
16262     $dbh->do(q{DELETE FROM systempreferences where variable="XISBN";});
16263     $dbh->do(q{DELETE FROM systempreferences where variable="XISBNDailyLimit";});
16264     SetVersion( $DBversion );
16265     print "Upgrade to $DBversion done (Bug 21226 - Remove prefs OCLCAffiliateID, XISBN and XISBNDailyLimit)\n";
16266 }
16267
16268 $DBversion = '18.06.00.016';
16269 if( CheckVersion( $DBversion ) ) {
16270     my $dtf  = Koha::Database->new->schema->storage->datetime_parser;
16271     my $days = C4::Context->preference('MaxPickupDelay') || 7;
16272     my $date = dt_from_string()->add( days => $days );
16273     my $sql  = q|UPDATE reserves SET expirationdate = ? WHERE expirationdate IS NULL AND waitingdate IS NOT NULL|;
16274     $dbh->do( $sql, undef, $dtf->format_datetime($date) );
16275     SetVersion( $DBversion );
16276     print "Upgrade to $DBversion done (Bug 20773 - expirationdate filled for waiting holds)\n";
16277 }
16278
16279 $DBversion = '18.06.00.017';
16280 if( CheckVersion( $DBversion ) ) {
16281     $dbh->do(q|INSERT IGNORE INTO authorised_value_categories (category_name) VALUES ('ROADTYPE');|);
16282     SetVersion( $DBversion );
16283     print "Upgrade to $DBversion done (Bug 21144: Add ROADTYPE to default authorised values categories)\n";
16284 }
16285
16286 $DBversion = '18.06.00.018';
16287 if( CheckVersion( $DBversion ) ) {
16288     $dbh->do( q|
16289 UPDATE items LEFT JOIN issues USING (itemnumber)
16290 SET items.onloan = NULL
16291 WHERE issues.itemnumber IS NULL
16292     |);
16293     SetVersion( $DBversion );
16294     print "Upgrade to $DBversion done (Bug 20487: Clear items.onloan for unissued items)\n";
16295 }
16296
16297 $DBversion = '18.06.00.019';
16298 if( CheckVersion( $DBversion ) ) {
16299     $dbh->do( q|
16300 INSERT IGNORE INTO columns_settings (module, page, tablename, columnname, cannot_be_toggled, is_hidden) VALUES
16301 ("circ", "circulation", "issues-table", "collection", 0, 1),
16302 ("members", "moremember", "issues-table", "collection", 0, 1);
16303     |);
16304     SetVersion( $DBversion );
16305     print "Upgrade to $DBversion done (Bug 19719: Default to hiding collection code column)\n";
16306 }
16307
16308 $DBversion = '18.06.00.020';
16309 if( CheckVersion( $DBversion ) ) {
16310     if( !column_exists( 'branch_borrower_circ_rules', 'max_holds' ) ) {
16311         $dbh->do(q{
16312             ALTER TABLE branch_borrower_circ_rules ADD COLUMN max_holds INT(4) NULL DEFAULT NULL AFTER maxonsiteissueqty
16313         });
16314     }
16315     if( !column_exists( 'default_borrower_circ_rules', 'max_holds' ) ) {
16316         $dbh->do(q{
16317             ALTER TABLE default_borrower_circ_rules ADD COLUMN max_holds INT(4) NULL DEFAULT NULL AFTER maxonsiteissueqty
16318         });
16319     }
16320     SetVersion( $DBversion );
16321     print "Upgrade to $DBversion done (Bug 15524 - Set limit on maximum possible holds per patron by category)\n";
16322 }
16323
16324 $DBversion = '18.06.00.021';
16325 if( CheckVersion( $DBversion ) ) {
16326     my $dbh = C4::Context->dbh;
16327     unless ( C4::Context->preference('NorwegianPatronDBEnable') ) {
16328         $dbh->do(q|
16329             DELETE FROM systempreferences
16330             WHERE variable IN ('NorwegianPatronDBEnable', 'NorwegianPatronDBEndpoint', 'NorwegianPatronDBUsername', 'NorwegianPatronDBPassword', 'NorwegianPatronDBSearchNLAfterLocalHit')
16331         |);
16332         if ( TableExists('borrower_sync') ) {
16333             $dbh->do(q|DROP TABLE borrower_sync|);
16334         }
16335     }
16336     SetVersion( $DBversion );
16337     print "Upgrade to $DBversion done (Bug 21068 - Remove system preferences NorwegianPatronDB*)\n";
16338 }
16339
16340 $DBversion = '18.06.00.022';
16341 if( CheckVersion( $DBversion ) ) {
16342     my $dbh = C4::Context->dbh;
16343     $dbh->do(q|
16344         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
16345         ('HoldsAutoFill','0',NULL,'If on, librarian will not be asked if hold should be filled, it will be filled automatically','YesNo'),
16346         ('HoldsAutoFillPrintSlip','0',NULL,'If on, hold slip print dialog will be displayed automatically','YesNo')
16347     |);
16348     SetVersion( $DBversion );
16349     print "Upgrade to $DBversion done (Bug 19383 - Add ability to print hold receipts automatically)\n";
16350 }
16351
16352 $DBversion = '18.06.00.023';
16353 if( CheckVersion( $DBversion ) ) {
16354     if( !column_exists( 'aqorders', 'replacementprice' ) ){
16355         $dbh->do( "ALTER TABLE aqorders ADD COLUMN replacementprice DECIMAL(28,6)" );
16356         $dbh->do( "UPDATE aqorders set replacementprice = rrp WHERE replacementprice IS NULL" );
16357     }
16358     SetVersion( $DBversion );
16359     print "Upgrade to $DBversion done (Bug 18639 - Add replacementprice field to aqorders table)\n";
16360 }
16361
16362 $DBversion = '18.06.00.024';
16363 if( CheckVersion( $DBversion ) ) {
16364     if( !column_exists( 'branches', 'pickup_location' ) ){
16365         $dbh->do( "ALTER TABLE branches ADD COLUMN pickup_location TINYINT(1) not null default 1" );
16366     }
16367     SetVersion( $DBversion );
16368     print "Upgrade to $DBversion done (Bug 7534 - Let libraries have configuration for pickup locations)\n";
16369 }
16370
16371 $DBversion = '18.06.00.025';
16372 if( CheckVersion( $DBversion ) ) {
16373     $dbh->do(q{
16374         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
16375         ('KohaManualBaseURL','https://koha-community.org/manual/','','Where is the Koha manual/documentation located?','Free'),
16376         ('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')
16377     });
16378     SetVersion( $DBversion );
16379     print "Upgrade to $DBversion done (Bug 19817: Add pref KohaManualLanguage and KohaManualBaseURL)\n";
16380 }
16381
16382 $DBversion = '18.06.00.026';
16383 if( CheckVersion( $DBversion ) ) {
16384     $dbh->do(q|
16385 INSERT IGNORE INTO  systempreferences (variable, value, options, explanation, type) VALUES ('ArticleRequestsLinkControl', 'always', 'always\|calc', 'Control display of article request link on search results', 'Choice')
16386     |);
16387     SetVersion( $DBversion );
16388     print "Upgrade to $DBversion done (Bug 17530 - Add pref ArticleRequestsLinkControl)\n";
16389 }
16390
16391 $DBversion = '18.06.00.027';
16392 if( CheckVersion( $DBversion ) ) {
16393     $dbh->do( "DROP TABLE IF EXISTS services_throttle" );
16394     SetVersion( $DBversion );
16395     print "Upgrade to $DBversion done (Bug 21235: Remove table services_throttle)\n";
16396 }
16397
16398 $DBversion = '18.06.00.028';
16399 if( CheckVersion( $DBversion ) ) {
16400     $dbh->do(q{
16401 INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
16402 ('HoldsSplitQueue','nothing','nothing|branch|itemtype|branch_itemtype','In the staff client, split the holds view by the given criteria','Choice'),
16403 ('HoldsSplitQueueNumbering', 'actual', 'actual|virtual', 'If the holds queue is split, decide if the acual priorities should be displayed', 'Choice');
16404 });
16405     SetVersion( $DBversion );
16406     print "Upgrade to $DBversion done (Bug 19469 - Add ability to split view of holds view on record by pickup library and/or itemtype)\n";
16407 }
16408
16409 $DBversion = '18.06.00.029';
16410 if( CheckVersion( $DBversion ) ) {
16411     unless ( index_exists( 'subscription', 'by_biblionumber' ) ) {
16412         $dbh->do(q{
16413             CREATE INDEX `by_biblionumber` ON `subscription` (`biblionumber`)
16414         });
16415     }
16416     SetVersion( $DBversion );
16417     print "Upgrade to $DBversion done (Bug 21288: Slowness in acquisition caused by GetInvoices\n";
16418 }
16419
16420 $DBversion = '18.06.00.030';
16421 if( CheckVersion( $DBversion ) ) {
16422     if ( column_exists( 'accountlines', 'dispute' ) ) {
16423         $dbh->do(q{
16424             ALTER TABLE `accountlines`
16425                 DROP COLUMN `dispute`
16426         });
16427     }
16428     SetVersion( $DBversion );
16429     print "Upgrade to $DBversion done (Bug 20777 - Remove unused field accountlines.dispute)\n";
16430 }
16431
16432 $DBversion = '18.06.00.031';
16433 if( CheckVersion( $DBversion ) ) {
16434     # Add table and add column
16435     unless (TableExists('patron_consent')) {
16436         $dbh->do(q|
16437     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 )
16438         |);
16439     }
16440     unless ( column_exists( 'borrower_modifications', 'gdpr_proc_consent' ) ) {
16441         $dbh->do(q|
16442     ALTER TABLE borrower_modifications ADD COLUMN gdpr_proc_consent datetime
16443         |);
16444     }
16445     # Add two sysprefs too
16446     $dbh->do(q|
16447 INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type ) VALUES ('PrivacyPolicyURL','',NULL,'This URL is used in messages about GDPR consents.', 'Free')
16448     |);
16449     $dbh->do(q|
16450 INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type ) VALUES ('GDPR_Policy','','Enforced\|Permissive\|Disabled','General Data Protection Regulation - policy', 'Choice')
16451     |);
16452     SetVersion( $DBversion );
16453     print "Upgrade to $DBversion done (Bug 20819: Add patron_consent)\n";
16454 }
16455
16456 $DBversion = '18.06.00.032';
16457 if( CheckVersion( $DBversion ) ) {
16458     $dbh->do(q|ALTER TABLE items                   CHANGE COLUMN ccode ccode varchar(80) default NULL|);
16459     $dbh->do(q|ALTER TABLE deleteditems            CHANGE COLUMN ccode ccode varchar(80) default NULL|);
16460     $dbh->do(q|ALTER TABLE branch_transfer_limits  CHANGE COLUMN ccode ccode varchar(80) default NULL|);
16461     $dbh->do(q|ALTER TABLE course_items            CHANGE COLUMN ccode ccode varchar(80) default NULL|);
16462     SetVersion( $DBversion );
16463     print "Upgrade to $DBversion done (Bug 5458: length of items.ccode disagrees with authorised_values.authorised_value)\n";
16464 }
16465
16466 $DBversion = '18.06.00.033';
16467 if( CheckVersion( $DBversion ) ) {
16468     $dbh->do(q|
16469         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')
16470     |);
16471     SetVersion( $DBversion );
16472     print "Upgrade to $DBversion done (Bug 12747 - Add AdditionalFieldsInZ3950ResultSearch system preference)\n";
16473 }
16474
16475 $DBversion = '18.06.00.034';
16476 if( CheckVersion( $DBversion ) ) {
16477     $dbh->do(q|
16478         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
16479         VALUES ('RecordedBooksClientSecret','','30','Client key for RecordedBooks integration','YesNo'),
16480                ('RecordedBooksLibraryID','','','Library ID for RecordedBooks integration','Integer'),
16481                ('RecordedBooksDomain','','','RecordedBooks domain','Free');
16482     |);
16483     SetVersion( $DBversion );
16484     print "Upgrade to $DBversion done (Bug 17602 - Integrate support for OneClickdigital/Recorded Books API)\n";
16485 }
16486
16487 $DBversion = '18.06.00.035';
16488 if( CheckVersion( $DBversion ) ) {
16489     $dbh->do(q{
16490         UPDATE `systempreferences` SET options = 'US|CA|DE|FR|IN|JP|UK' WHERE variable = 'AmazonLocale' AND options='US|CA|DE|FR|JP|UK';
16491     });
16492     SetVersion( $DBversion );
16493     print "Upgrade to $DBversion done (Bug 21403 - Add Indian Amazon Affiliate option to AmazonLocale setting)\n";
16494 }
16495
16496
16497 $DBversion = '18.06.00.036';
16498 if( CheckVersion( $DBversion ) ) {
16499     unless (TableExists('circulation_rules')){
16500         $dbh->do(q{
16501             CREATE TABLE `circulation_rules` (
16502               `id` int(11) NOT NULL auto_increment,
16503               `branchcode` varchar(10) NULL default NULL,
16504               `categorycode` varchar(10) NULL default NULL,
16505               `itemtype` varchar(10) NULL default NULL,
16506               `rule_name` varchar(32) NOT NULL,
16507               `rule_value` varchar(32) NOT NULL,
16508               PRIMARY KEY (`id`),
16509               CONSTRAINT `circ_rules_ibfk_1` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
16510               CONSTRAINT `circ_rules_ibfk_2` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`) ON DELETE CASCADE ON UPDATE CASCADE,
16511               CONSTRAINT `circ_rules_ibfk_3` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE,
16512               KEY `rule_name` (`rule_name`),
16513               UNIQUE (`branchcode`,`categorycode`,`itemtype`,`rule_name`)
16514             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16515         });
16516     }
16517     if (column_exists('branch_borrower_circ_rules', 'max_holds') ){
16518         $dbh->do(q{
16519             INSERT IGNORE INTO circulation_rules ( branchcode, categorycode, itemtype, rule_name, rule_value )
16520             SELECT branchcode, categorycode, NULL, 'max_holds', COALESCE( max_holds, '' ) FROM branch_borrower_circ_rules
16521         });
16522         $dbh->do(q{
16523             ALTER TABLE branch_borrower_circ_rules DROP COLUMN max_holds
16524         });
16525     }
16526     if (column_exists('default_borrower_circ_rules', 'max_holds') ){
16527         $dbh->do(q{
16528             INSERT IGNORE INTO circulation_rules ( branchcode, categorycode, itemtype, rule_name, rule_value )
16529             SELECT NULL, categorycode, NULL, 'max_holds', COALESCE( max_holds, '' ) FROM default_borrower_circ_rules
16530         });
16531         $dbh->do(q{
16532             ALTER TABLE default_borrower_circ_rules DROP COLUMN max_holds
16533         });
16534     }
16535     SetVersion( $DBversion );
16536     print "Upgrade to $DBversion done (Bug 18887 - Introduce new table 'circulation_rules', use for 'max_holds' rules)\n";
16537 }
16538
16539 $DBversion = '18.06.00.037';
16540 if( CheckVersion( $DBversion ) ) {
16541     unless (TableExists('branches_overdrive')){
16542         $dbh->do( q|
16543             CREATE TABLE branches_overdrive (
16544                 `branchcode` VARCHAR( 10 ) NOT NULL ,
16545                 `authname` VARCHAR( 255 ) NOT NULL ,
16546                 PRIMARY KEY (`branchcode`) ,
16547                 CONSTRAINT `branches_overdrive_ibfk_1` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
16548             ) ENGINE = INNODB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci |
16549         );
16550     }
16551     $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');");
16552     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('OverDriveWebsiteID','', 'WebsiteID provided by OverDrive', NULL, 'Free');");
16553     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('OverDrivePasswordRequired','', 'Does the library require passwords for OverDrive SIP authentication', NULL, 'YesNo');");
16554     SetVersion( $DBversion );
16555     print "Upgrade to $DBversion done (Bug 21082 - Add overdrive patron auth method)\n";
16556 }
16557
16558 $DBversion = '18.06.00.038';
16559 if( CheckVersion( $DBversion ) ) {
16560     $dbh->do( "ALTER TABLE edifact_ean MODIFY branchcode VARCHAR(10) NULL DEFAULT NULL" );
16561     SetVersion( $DBversion );
16562     print "Upgrade to $DBversion done (Bug 21417 - EDI ordering fails when basket and EAN libraries do not match)\n";
16563 }
16564
16565 $DBversion = '18.06.00.039';
16566 if( CheckVersion( $DBversion ) ) {
16567     $dbh->do(q{
16568         INSERT IGNORE INTO `permissions` (module_bit, code, description) VALUES(3, 'manage_circ_rules_from_any_libraries', 'Manage circ rules for any libraries');
16569     });
16570     SetVersion( $DBversion );
16571     print "Upgrade to $DBversion done (Bug 15520 - Add more granular permission for only editing own library's circ rules)\n";
16572 }
16573
16574 $DBversion = '18.06.00.040';
16575 if( CheckVersion( $DBversion ) ) {
16576     # Stock Rotation Rotas
16577     unless (TableExists('stockrotationrotas')){
16578         $dbh->do(q{
16579           CREATE TABLE `stockrotationrotas` (
16580             `rota_id` int(11) auto_increment,         -- Stockrotation rota ID
16581             `title` varchar(100) NOT NULL,            -- Title for this rota
16582             `description` text NOT NULL,              -- Description for this rota
16583             `cyclical` tinyint(1) NOT NULL default 0, -- Should items on this rota keep cycling?
16584             `active` tinyint(1) NOT NULL default 0,   -- Is this rota currently active?
16585             PRIMARY KEY (`rota_id`),
16586             CONSTRAINT `stockrotationrotas_title`
16587             UNIQUE (`title`)
16588           ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16589         });
16590     }
16591     # Stock Rotation Stages
16592     unless (TableExists('stockrotationstages')){
16593         $dbh->do(q{
16594           CREATE TABLE `stockrotationstages` (
16595               `stage_id` int(11) auto_increment,     -- Unique stage ID
16596               `position` int(11) NOT NULL,           -- The position of this stage within its rota
16597               `rota_id` int(11) NOT NULL,            -- The rota this stage belongs to
16598               `branchcode_id` varchar(10) NOT NULL,  -- Branch this stage relates to
16599               `duration` int(11) NOT NULL default 4, -- The number of days items shoud occupy this stage
16600               PRIMARY KEY (`stage_id`),
16601               CONSTRAINT `stockrotationstages_rifk`
16602                 FOREIGN KEY (`rota_id`)
16603                 REFERENCES `stockrotationrotas` (`rota_id`)
16604                 ON UPDATE CASCADE ON DELETE CASCADE,
16605               CONSTRAINT `stockrotationstages_bifk`
16606                 FOREIGN KEY (`branchcode_id`)
16607                 REFERENCES `branches` (`branchcode`)
16608                 ON UPDATE CASCADE ON DELETE CASCADE
16609           ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16610         });
16611     }
16612     # Stock Rotation Items
16613     unless (TableExists('stockrotationitems')){
16614         $dbh->do(q{
16615           CREATE TABLE `stockrotationitems` (
16616               `itemnumber_id` int(11) NOT NULL,         -- Itemnumber to link to a stage & rota
16617               `stage_id` int(11) NOT NULL,              -- stage ID to link the item to
16618               `indemand` tinyint(1) NOT NULL default 0, -- Should this item be skipped for rotation?
16619               `fresh` tinyint(1) NOT NULL default 0,    -- Flag showing item is only just added to rota
16620               PRIMARY KEY (itemnumber_id),
16621               CONSTRAINT `stockrotationitems_iifk`
16622                 FOREIGN KEY (`itemnumber_id`)
16623                 REFERENCES `items` (`itemnumber`)
16624                 ON UPDATE CASCADE ON DELETE CASCADE,
16625               CONSTRAINT `stockrotationitems_sifk`
16626                 FOREIGN KEY (`stage_id`)
16627                 REFERENCES `stockrotationstages` (`stage_id`)
16628                 ON UPDATE CASCADE ON DELETE CASCADE
16629           ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16630         });
16631     }
16632     # System preferences
16633     $dbh->do(q{
16634         INSERT IGNORE INTO `systempreferences` (`variable`,`value`,`explanation`,`options`,`type`)
16635         VALUES ('StockRotation','0','If ON, enables the stock rotation module','','YesNo'),
16636                ('RotationPreventTransfers','0','If ON, prevent any transfers for items on stock rotation rotas, except for stock rotation transfers','','YesNo');
16637     });
16638     # Permissions
16639     $dbh->do(q{
16640         INSERT IGNORE INTO `userflags` (`bit`, `flag`, `flagdesc`, `defaulton`)
16641         VALUES (24, 'stockrotation', 'Manage stockrotation operations', 0);
16642     });
16643     $dbh->do(q{
16644         INSERT IGNORE INTO `permissions` (`module_bit`, `code`, `description`)
16645         VALUES (24, 'manage_rotas', 'Create, edit and delete rotas'),
16646                (24, 'manage_rota_items', 'Add and remove items from rotas');
16647     });
16648     # Notices
16649     $dbh->do(q{
16650         INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`)
16651         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');
16652     });
16653     print "Upgrade to $DBversion done (Bug 11897 - Add Stock Rotation Feature)\n";
16654     SetVersion( $DBversion );
16655 }
16656
16657 $DBversion = '18.06.00.041';
16658 if( CheckVersion( $DBversion ) ) {
16659
16660      if( !column_exists( 'illrequests', 'price_paid' ) ) {
16661         $dbh->do(q{
16662             ALTER TABLE illrequests
16663                 ADD COLUMN price_paid varchar(20) DEFAULT NULL
16664                 AFTER cost
16665         });
16666      }
16667
16668      if( !column_exists( 'illrequestattributes', 'readonly' ) ) {
16669         $dbh->do(q{
16670             ALTER TABLE illrequestattributes
16671                 ADD COLUMN readonly tinyint(1) NOT NULL DEFAULT 1
16672                 AFTER value
16673         });
16674         $dbh->do(q{
16675             UPDATE illrequestattributes SET readonly = 1
16676         });
16677      }
16678
16679     SetVersion( $DBversion );
16680     print "Upgrade to $DBversion done (Bug 20772 - Add illrequestattributes.readonly and illrequest.price_paid columns)\n";
16681 }
16682
16683 $DBversion = '18.06.00.042';
16684 if( CheckVersion( $DBversion ) ) {
16685     $dbh->do( "alter table statistics change column ccode ccode varchar(80) default NULL" );
16686
16687     SetVersion( $DBversion );
16688     print "Upgrade to $DBversion done (Bug 21617: Make statistics.ccode longer)\n";
16689 }
16690
16691 $DBversion = "18.06.00.043";
16692 if ( CheckVersion($DBversion) ) {
16693     if ( !column_exists( 'issuingrules', 'holds_per_day' ) ) {
16694         $dbh->do(q{
16695             ALTER TABLE `issuingrules`
16696                 ADD COLUMN `holds_per_day` SMALLINT(6) DEFAULT NULL
16697                 AFTER `holds_per_record`
16698         });
16699     }
16700     print "Upgrade to $DBversion done (Bug 15486: Restrict number of holds placed by day)\n";
16701     SetVersion($DBversion);
16702 }
16703
16704 $DBversion = '18.06.00.044';
16705 if( CheckVersion( $DBversion ) ) {
16706     unless( column_exists( 'creator_batches', 'description' ) ) {
16707         $dbh->do(q|ALTER TABLE creator_batches ADD description mediumtext default NULL AFTER batch_id|);
16708     }
16709     SetVersion( $DBversion );
16710     print "Upgrade to $DBversion done (Bug 15766: Add column creator_batches.description)\n";
16711 }
16712
16713 $DBversion = '18.06.00.045';
16714 if( CheckVersion( $DBversion ) ) {
16715     $dbh->do(q(
16716         INSERT IGNORE INTO message_transports
16717         (message_attribute_id,message_transport_type,is_digest,letter_module,letter_code)
16718         VALUES
16719         (2, 'phone', 0, 'circulation', 'PREDUE'),
16720         (2, 'phone', 1, 'circulation', 'PREDUEDGST'),
16721         (4, 'phone', 0, 'reserves',    'HOLD')
16722         ));
16723     SetVersion( $DBversion );
16724     print "Upgrade to $DBversion done (Bug 21639 - Add phone transports by default)\n";
16725 }
16726
16727 $DBversion = '18.06.00.046';
16728 if( CheckVersion( $DBversion ) ) {
16729     unless (TableExists('illcomments')) {
16730         $dbh->do(q{
16731             CREATE TABLE illcomments (
16732                 illcomment_id int(11) NOT NULL AUTO_INCREMENT, -- Unique ID of the comment
16733                 illrequest_id bigint(20) unsigned NOT NULL,    -- ILL request number
16734                 borrowernumber integer DEFAULT NULL,           -- Link to the user who made the comment (could be librarian, patron or ILL partner library)
16735                 comment text DEFAULT NULL,                     -- The text of the comment
16736                 timestamp timestamp DEFAULT CURRENT_TIMESTAMP, -- Date and time when the comment was made
16737                 PRIMARY KEY  ( illcomment_id ),
16738                 CONSTRAINT illcomments_bnfk
16739                   FOREIGN KEY ( borrowernumber )
16740                   REFERENCES  borrowers  ( borrowernumber )
16741                   ON UPDATE CASCADE ON DELETE CASCADE,
16742                 CONSTRAINT illcomments_ifk
16743                   FOREIGN KEY (illrequest_id)
16744                   REFERENCES illrequests ( illrequest_id )
16745                   ON UPDATE CASCADE ON DELETE CASCADE
16746             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16747         });
16748     }
16749
16750     SetVersion( $DBversion );
16751     print "Upgrade to $DBversion done (Bug 18591 - Add comments to ILL requests)\n";
16752 }
16753
16754 $DBversion = '18.06.00.047';
16755 if( CheckVersion( $DBversion ) ) {
16756     # insert the authorized_value_category for CONTROL_NUM_SEQUENCE
16757     $dbh->do( "INSERT IGNORE INTO authorised_value_categories values ('CONTROL_NUM_SEQUENCE');" );
16758     SetVersion( $DBversion );
16759     print "Upgrade to $DBversion done (Bug 19263 - Advanced Editor - Rancor - Add auto control number (001) widget)\n";
16760 }
16761
16762 $DBversion = '18.06.00.048';
16763 if( CheckVersion( $DBversion ) ) {
16764     $dbh->do( "ALTER TABLE stockrotationrotas CHANGE COLUMN description description text" );
16765     SetVersion( $DBversion );
16766     print "Upgrade to $DBversion done (Bug 21682 - Remove default on stockrotationrotas.description)\n";
16767 }
16768
16769 $DBversion = '18.06.00.049';
16770 if( CheckVersion( $DBversion ) ) {
16771     $dbh->do(q{
16772         UPDATE letter SET content = REPLACE(content,"item.reason ne \'in-demand\'","item.reason != \'in-demand\'")
16773         WHERE code="SR_SLIP";
16774     });
16775     print "Upgrade to $DBversion done (Bug 21656 - Stock Rotation Notice, Template Toolkit Syntax Correction)\n";
16776     SetVersion( $DBversion );
16777 }
16778
16779 $DBversion = '18.06.00.050';
16780 if( CheckVersion( $DBversion ) ) {
16781     $dbh->do(q{
16782         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');
16783     });
16784     print "Upgrade to $DBversion done (Bug 14385 - Add OpacHiddenItemExceptions)\n";
16785     SetVersion( $DBversion );
16786 }
16787
16788 $DBversion = '18.06.00.051';
16789 if( CheckVersion( $DBversion ) ) {
16790     $dbh->do(q{
16791         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES
16792         ('AdlibrisCoversEnabled', '0', NULL, 'Display cover images in OPAC results and detail listing from Swedish retailer Adlibris.','YesNo'),
16793         ('AdlibrisCoversURL', 'http://www.adlibris.com/se/organisationer/showimagesafe.aspx', NULL, 'Base URL for Adlibris cover image web service.', 'Free');
16794     });
16795     print "Upgrade to $DBversion done (Bug 8630 - Add covers from AdLibris to the OPAC and Intranet)\n";
16796     SetVersion( $DBversion );
16797 }
16798
16799 $DBversion = '18.06.00.052';
16800 if( CheckVersion( $DBversion ) ) {
16801     $dbh->do(q{
16802         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
16803            ( 3, 'manage_sysprefs', 'Manage global system preferences'),
16804            ( 3, 'manage_libraries', 'Manage libraries and library groups'),
16805            ( 3, 'manage_itemtypes', 'Manage item types'),
16806            ( 3, 'manage_auth_values', 'Manage authorized values'),
16807            ( 3, 'manage_patron_categories', 'Manage patron categories'),
16808            ( 3, 'manage_patron_attributes', 'Manage extended patron attributes'),
16809            ( 3, 'manage_transfers', 'Manage library transfer limits and transport cost matrix'),
16810            ( 3, 'manage_item_circ_alerts', 'Manage item circulation alerts'),
16811            ( 3, 'manage_cities', 'Manage cities and towns'),
16812            ( 3, 'manage_marc_frameworks', 'Manage MARC bibliographic and authority frameworks'),
16813            ( 3, 'manage_keywords2koha_mappings', 'Manage keywords to Koha mappings'),
16814            ( 3, 'manage_classifications', 'Manage classification sources'),
16815            ( 3, 'manage_matching_rules', 'Manage record matching rules'),
16816            ( 3, 'manage_oai_sets', 'Manage OAI sets'),
16817            ( 3, 'manage_item_search_fields', 'Manage item search fields'),
16818            ( 3, 'manage_search_engine_config', 'Manage search engine configuration'),
16819            ( 3, 'manage_search_targets', 'Manage Z39.50 and SRU server configuration'),
16820            ( 3, 'manage_didyoumean', 'Manage Did you mean? configuration'),
16821            ( 3, 'manage_column_config', 'Manage column configuration'),
16822            ( 3, 'manage_sms_providers', 'Manage SMS cellular providers'),
16823            ( 3, 'manage_audio_alerts', 'Manage audio alerts'),
16824            ( 3, 'manage_usage_stats', 'Manage usage statistics settings');
16825     });
16826     $dbh->do(q{
16827         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16828             SELECT borrowernumber, 3, 'manage_sysprefs' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16829     });
16830     $dbh->do(q{
16831         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16832             SELECT borrowernumber, 3, 'manage_libraries' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16833     });
16834     $dbh->do(q{
16835         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16836             SELECT borrowernumber, 3, 'manage_itemtypes' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16837     });
16838     $dbh->do(q{
16839         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16840             SELECT borrowernumber, 3, 'manage_auth_values' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16841     });
16842     $dbh->do(q{
16843         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16844             SELECT borrowernumber, 3, 'manage_patron_categories' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16845     });
16846     $dbh->do(q{
16847         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16848             SELECT borrowernumber, 3, 'manage_patron_attributes' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16849     });
16850     $dbh->do(q{
16851         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16852             SELECT borrowernumber, 3, 'manage_transfers' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16853     });
16854     $dbh->do(q{
16855         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16856             SELECT borrowernumber, 3, 'manage_item_circ_alerts' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16857     });
16858     $dbh->do(q{
16859         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16860             SELECT borrowernumber, 3, 'manage_cities' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16861     });
16862     $dbh->do(q{
16863         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16864             SELECT borrowernumber, 3, 'manage_marc_frameworks' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16865     });
16866     $dbh->do(q{
16867         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16868             SELECT borrowernumber, 3, 'manage_keywords2koha_mappings' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16869     });
16870     $dbh->do(q{
16871         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16872             SELECT borrowernumber, 3, 'manage_classifications' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16873     });
16874     $dbh->do(q{
16875         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16876             SELECT borrowernumber, 3, 'manage_matching_rules' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16877     });
16878     $dbh->do(q{
16879         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16880             SELECT borrowernumber, 3, 'manage_oai_sets' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16881     });
16882     $dbh->do(q{
16883         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16884             SELECT borrowernumber, 3, 'manage_item_search_fields' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16885     });
16886     $dbh->do(q{
16887         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16888             SELECT borrowernumber, 3, 'manage_search_engine_config' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16889     });
16890     $dbh->do(q{
16891         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16892             SELECT borrowernumber, 3, 'manage_search_targets' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16893     });
16894     $dbh->do(q{
16895         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16896             SELECT borrowernumber, 3, 'manage_didyoumean' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16897     });
16898     $dbh->do(q{
16899         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16900             SELECT borrowernumber, 3, 'manage_column_config' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16901     });
16902     $dbh->do(q{
16903         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16904             SELECT borrowernumber, 3, 'manage_sms_providers' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16905     });
16906     $dbh->do(q{
16907         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16908             SELECT borrowernumber, 3, 'manage_audio_alerts' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16909     });
16910     $dbh->do(q{
16911         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16912             SELECT borrowernumber, 3, 'manage_usage_stats' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16913     });
16914     $dbh->do(q{
16915         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16916             SELECT borrowernumber, 3, 'manage_item_search_fields' FROM borrowers WHERE flags & (1 << 2);
16917     });
16918     SetVersion( $DBversion );
16919     print "Upgrade to $DBversion done (Bug 14391: Add granular permissions to the administration module)\n";
16920 }
16921
16922 $DBversion = '18.06.00.053';
16923 if( CheckVersion( $DBversion ) ) {
16924     $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')" );
16925     SetVersion( $DBversion );
16926     print "Upgrade to $DBversion done (Bug 15494 - Block renewals by arbitrary item values)\n";
16927 }
16928
16929 $DBversion = '18.06.00.054';
16930 if( CheckVersion( $DBversion ) ) {
16931     if( !column_exists( 'search_field', 'weight' ) ) {
16932         $dbh->do( "ALTER TABLE `search_field` ADD COLUMN `weight` decimal(5,2) DEFAULT NULL AFTER `type`" );
16933     }
16934     SetVersion( $DBversion );
16935     print "Upgrade to $DBversion done (Bug 18316 - Add column search_field.weight)\n";
16936 }
16937
16938 $DBversion = '18.06.00.055';
16939 if( CheckVersion( $DBversion ) ) {
16940     unless( column_exists( 'issuingrules', 'note' ) ) {
16941         $dbh->do(q|ALTER TABLE `issuingrules` ADD `note` varchar(100) default NULL AFTER `article_requests`|);
16942     }
16943     SetVersion( $DBversion );
16944     print "Upgrade to $DBversion done (Bug 12365: Add column issuingrules.note)\n";
16945 }
16946
16947 $DBversion = '18.06.00.056';
16948 if( CheckVersion( $DBversion ) ) {
16949
16950     # All attributes we're potentially interested in
16951     my $ff_req = $dbh->selectall_arrayref(
16952         'SELECT a.illrequest_id, a.type, a.value '.
16953         'FROM illrequests r, illrequestattributes a '.
16954         'WHERE r.illrequest_id = a.illrequest_id '.
16955         'AND r.backend = "FreeForm"',
16956         { Slice => {} }
16957     );
16958
16959     # Before we go any further, identify whether we've done
16960     # this before, we test for the presence of "container_title"
16961     # We stop as soon as we find one
16962     foreach my $req(@{$ff_req}) {
16963         if ($req->{type} eq 'container_title') {
16964             warn "Upgrade already carried out";
16965         }
16966     }
16967
16968     # Transform into a hashref with the key of the request ID
16969     my $requests = {};
16970     foreach my $request(@{$ff_req}) {
16971         my $id = $request->{illrequest_id};
16972         if (!exists $requests->{$id}) {
16973             $requests->{$id} = {};
16974         }
16975         $requests->{$id}->{$request->{type}} = $request->{value};
16976     }
16977
16978     # Transform any article requests
16979     my $transformed = {};
16980     foreach my $id(keys %{$requests}) {
16981         if (lc($requests->{$id}->{type}) eq 'article') {
16982             $transformed->{$id} = $requests->{$id};
16983             $transformed->{$id}->{type} = 'article';
16984             $transformed->{$id}->{container_title} = $transformed->{$id}->{title}
16985                 if defined $transformed->{$id}->{title} &&
16986                     length $transformed->{$id}->{title} > 0;
16987             $transformed->{$id}->{title} = $transformed->{$id}->{article_title}
16988                 if defined $transformed->{$id}->{article_title} &&
16989                     length $transformed->{$id}->{article_title} > 0;
16990             $transformed->{$id}->{author} = $transformed->{$id}->{article_author}
16991                 if defined $transformed->{$id}->{article_author} &&
16992                     length $transformed->{$id}->{article_author} > 0;
16993             $transformed->{$id}->{pages} = $transformed->{$id}->{article_pages}
16994                 if defined $transformed->{$id}->{article_pages} &&
16995                     length $transformed->{$id}->{article_pages} > 0;
16996         }
16997     }
16998
16999     # Now write back the transformed data
17000     # Rather than selectively replace, we just remove all attributes we've
17001     # transformed and re-write them
17002     my @changed = keys %{$transformed};
17003     my $changed_str = join(',', @changed);
17004
17005     if (scalar @changed > 0) {
17006         my ($raise_error) = $dbh->{RaiseError};
17007         $dbh->{AutoCommit} = 0;
17008         $dbh->{RaiseError} = 1;
17009         eval {
17010             my $del = $dbh->do(
17011                 "DELETE FROM illrequestattributes ".
17012                 "WHERE illrequest_id IN ($changed_str)"
17013             );
17014             foreach my $reqid(keys %{$transformed}) {
17015                 my $attr = $transformed->{$reqid};
17016                 foreach my $key(keys %{$attr}) {
17017                     my $sth = $dbh->prepare(
17018                         'INSERT INTO illrequestattributes '.
17019                         '(illrequest_id, type, value) '.
17020                         'VALUES '.
17021                         '(?, ?, ?)'
17022                     );
17023                     $sth->execute(
17024                         $reqid,
17025                         $key,
17026                         $attr->{$key}
17027                     );
17028                 }
17029             }
17030             $dbh->commit;
17031         };
17032
17033         if ($@) {
17034             warn "Upgrade to $DBversion failed: $@\n";
17035             eval { $dbh->rollback };
17036         } else {
17037             SetVersion( $DBversion );
17038             print "Upgrade to $DBversion done (Bug 21079 - Unify metadata schema across backends)\n";
17039         }
17040
17041         $dbh->{AutoCommit} = 1;
17042         $dbh->{RaiseError} = $raise_error;
17043     }
17044
17045 }
17046
17047 $DBversion = '18.06.00.057';
17048 if( CheckVersion( $DBversion ) ) {
17049     # System preferences
17050     $dbh->do(q{
17051         INSERT IGNORE INTO `systempreferences` (`variable`,`value`,`explanation`,`options`,`type`)
17052         VALUES ('showLastPatron','0','','If ON, enables the last patron feature in the intranet','YesNo');
17053     });
17054     SetVersion( $DBversion );
17055     print "Upgrade to $DBversion done (Bug 20312 - Add showLastPatron systempreference)\n";
17056 }
17057
17058 $DBversion = '18.06.00.058';
17059 if( CheckVersion( $DBversion ) ) {
17060     $dbh->do(q{
17061         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES
17062         ('MarcFieldForCreatorId','',NULL,'Where to store the borrowernumber of the record''s creator','Free'),
17063         ('MarcFieldForCreatorName','',NULL,'Where to store the name of the record''s creator','Free'),
17064         ('MarcFieldForModifierId','',NULL,'Where to store the borrowernumber of the record''s last modifier','Free'),
17065         ('MarcFieldForModifierName','',NULL,'Where to store the name of the record''s last modifier','Free')
17066     });
17067
17068     SetVersion( $DBversion );
17069     print "Upgrade to $DBversion done (Bug 19349 - Add system preferences MarcFieldForCreatorId, MarcFieldForCreatorName, MarcFieldForModifierId, MarcFieldForModifierName)\n";
17070 }
17071
17072 $DBversion = '18.06.00.059';
17073 if( CheckVersion( $DBversion ) ) {
17074     $dbh->do(q{
17075         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type`) VALUES  ('EmailSMSSendDriverFromAddress', '', '', 'Email SMS send driver from address override', 'Free');
17076     });
17077     SetVersion( $DBversion );
17078     print "Upgrade to $DBversion done (Bug 20356 - Add EmailSMSSendDriverFromAddress system preference)\n";
17079 }
17080
17081 $DBversion = '18.06.00.060';
17082 if( CheckVersion( $DBversion ) ) {
17083     unless( TableExists( 'class_split_rules' ) ) {
17084         $dbh->do(q|
17085             CREATE TABLE class_split_rules (
17086               class_split_rule varchar(10) NOT NULL default '',
17087               description LONGTEXT,
17088               split_routine varchar(30) NOT NULL default '',
17089               split_regex varchar(255) NOT NULL default '',
17090               PRIMARY KEY (class_split_rule),
17091               UNIQUE KEY class_split_rule_idx (class_split_rule)
17092             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
17093         |);
17094
17095         $dbh->do(q|
17096             ALTER TABLE class_sources
17097             ADD COLUMN class_split_rule varchar(10) NOT NULL default ''
17098             AFTER class_sort_rule
17099         |);
17100
17101         $dbh->do(q|
17102             UPDATE class_sources
17103             SET class_split_rule = class_sort_rule
17104         |);
17105
17106         $dbh->do(q|
17107             UPDATE class_sources
17108             SET class_split_rule = 'generic'
17109             WHERE class_split_rule NOT IN('dewey', 'generic', 'lcc')
17110         |);
17111
17112         $dbh->do(q|
17113             INSERT INTO class_split_rules(class_split_rule, description, split_routine)
17114             VALUES
17115             ('dewey', 'Default sorting rules for DDC', 'Dewey'),
17116             ('lcc', 'Default sorting rules for LCC', 'LCC'),
17117             ('generic', 'Generic call number sorting rules', 'Generic')
17118         |);
17119
17120         $dbh->do(q|
17121             ALTER TABLE class_sources
17122             ADD CONSTRAINT class_source_ibfk_2 FOREIGN KEY (class_split_rule)
17123             REFERENCES class_split_rules (class_split_rule)
17124         |);
17125     }
17126
17127     SetVersion( $DBversion );
17128     print "Upgrade to $DBversion done (Bug 15836 - Add class_sort_rules.split_routine and split_regex)\n";
17129 }
17130
17131 $DBversion = '18.06.00.061';
17132 if ( CheckVersion($DBversion) ) {
17133     $dbh->do(q{
17134         INSERT IGNORE INTO `systempreferences` (`variable`,`value`,`explanation`,`options`,`type`) VALUES
17135         ('ElasticsearchIndexStatus_biblios', '0', 'Biblios index status', NULL, NULL),
17136         ('ElasticsearchIndexStatus_authorities', '0', 'Authorities index status', NULL, NULL)
17137     });
17138     SetVersion($DBversion);
17139     print "Upgrade to $DBversion done (Bug 19893 - Add elasticsearch index status preferences)\n";
17140 }
17141
17142 $DBversion = '18.06.00.062';
17143 if( CheckVersion( $DBversion ) ) {
17144     $dbh->do( "INSERT IGNORE INTO authorised_value_categories (category_name) VALUES ('PA_CLASS');");
17145     SetVersion( $DBversion );
17146     print "Upgrade to $DBversion done (Bug 21730: Add new authorised value category PA_CLASS)\n";
17147 }
17148
17149 $DBversion = '18.11.00.000';
17150 if( CheckVersion( $DBversion ) ) {
17151     SetVersion( $DBversion );
17152     print "Upgrade to $DBversion done (18.11.00 release)\n";
17153 }
17154
17155 $DBversion = '18.12.00.000';
17156 if( CheckVersion( $DBversion ) ) {
17157     SetVersion( $DBversion );
17158     print "Upgrade to $DBversion done (...and Steven!)\n";
17159 }
17160
17161 $DBversion = '18.12.00.001';
17162 if( CheckVersion( $DBversion ) ) {
17163     $dbh->do(q{
17164         UPDATE permissions SET code = 'manage_didyoumean' WHERE code = 'manage_didyouean';
17165     });
17166     $dbh->do(q{
17167         UPDATE user_permissions SET code = 'manage_didyoumean' WHERE code = 'manage_didyouean';
17168     });
17169     SetVersion( $DBversion );
17170     print "Upgrade to $DBversion (Bug 21961 - Fix typo in manage_didyoumean permission)\n";
17171 }
17172
17173 $DBversion = '18.12.00.002';
17174 if( CheckVersion( $DBversion ) ) {
17175     my $sth = $dbh->prepare(q|SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_NAME='accountlines_ibfk_1'|);
17176     $sth->execute;
17177     if ($sth->fetchrow_hashref) {
17178         $dbh->do(q|
17179             ALTER TABLE accountlines DROP FOREIGN KEY accountlines_ibfk_1;
17180         |);
17181         $dbh->do(q|
17182             ALTER TABLE accountlines CHANGE COLUMN borrowernumber borrowernumber INT(11) DEFAULT NULL;
17183         |);
17184         $dbh->do(q|
17185             ALTER TABLE accountlines ADD CONSTRAINT accountlines_ibfk_borrowers FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE SET NULL ON UPDATE CASCADE;
17186         |);
17187     }
17188     SetVersion( $DBversion );
17189     print "Upgrade to $DBversion done (Bug 21065 - Set ON DELETE SET NULL on accountlines.borrowernumber)\n";
17190 }
17191
17192 $DBversion = '18.12.00.003';
17193 if( CheckVersion( $DBversion ) ) {
17194     # On a new installation the class_sources.sql will have failed, so we need to add all missing data
17195     my( $sort_cnt ) = $dbh->selectrow_array( q|SELECT COUNT(*) FROM class_sort_rules|);
17196     if( !$sort_cnt ) {
17197         $dbh->do(q|INSERT INTO `class_sort_rules` (`class_sort_rule`, `description`, `sort_routine`) VALUES
17198                                ('dewey', 'Default filing rules for DDC', 'Dewey'),
17199                                ('lcc', 'Default filing rules for LCC', 'LCC'),
17200                                ('generic', 'Generic call number filing rules', 'Generic')
17201             |);
17202     }
17203
17204     my ( $split_cnt ) = $dbh->selectrow_array( q|SELECT COUNT(*) FROM class_split_rules|);
17205     if( !$split_cnt ) {
17206         $dbh->do(q|INSERT INTO `class_split_rules` (`class_split_rule`, `description`, `split_routine`) VALUES
17207                                ('dewey', 'Default splitting rules for DDC', 'Dewey'),
17208                                ('lcc', 'Default splitting rules for LCC', 'LCC'),
17209                                ('generic', 'Generic call number splitting rules', 'Generic')
17210             |);
17211     }
17212
17213     my( $source_cnt ) = $dbh->selectrow_array( q|SELECT COUNT(*) FROM class_sources|);
17214     if( !$source_cnt ) {
17215         $dbh->do(q|INSERT INTO `class_sources` (`cn_source`, `description`, `used`, `class_sort_rule`, `class_split_rule`) VALUES
17216                             ('ddc', 'Dewey Decimal Classification', 1, 'dewey', 'dewey'),
17217                             ('lcc', 'Library of Congress Classification', 1, 'lcc', 'lcc'),
17218                             ('udc', 'Universal Decimal Classification', 0, 'generic', 'generic'),
17219                             ('sudocs', 'SuDoc Classification (U.S. GPO)', 0, 'generic', 'generic'),
17220                             ('anscr', 'ANSCR (Sound Recordings)', 0, 'generic', 'generic'),
17221                             ('z', 'Other/Generic Classification Scheme', 0, 'generic', 'generic')
17222             |);
17223
17224     }
17225
17226     SetVersion( $DBversion );
17227     print "Upgrade to $DBversion done (Bug 22024 - Add missing splitting rule definitions)\n";
17228 }
17229
17230 $DBversion = '18.12.00.004';
17231 if( CheckVersion( $DBversion ) ) {
17232     if( !column_exists( 'accountlines', 'branchcode' ) ) {
17233         $dbh->do("ALTER TABLE accountlines ADD branchcode VARCHAR( 10 ) NULL DEFAULT NULL AFTER manager_id");
17234         $dbh->do("ALTER TABLE accountlines ADD CONSTRAINT accountlines_ibfk_branches FOREIGN KEY (branchcode) REFERENCES branches (branchcode) ON DELETE SET NULL ON UPDATE CASCADE");
17235     }
17236     SetVersion( $DBversion );
17237     print "Upgrade to $DBversion done (Bug 19066 - Add branchcode to accountlines)\n";
17238 }
17239
17240 $DBversion = '18.12.00.005';
17241 if( CheckVersion( $DBversion ) ) {
17242     $dbh->do(q{
17243         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
17244         ('OverDriveUsername','cardnumber','cardnumber|userid','Which patron information should be passed as OverDrive username','Choice')
17245     });
17246     SetVersion( $DBversion );
17247     print "Upgrade to $DBversion done (Bug 22030: Add OverDriveUsername syspref)\n";
17248 }
17249
17250 $DBversion = '18.12.00.006';
17251 if( CheckVersion( $DBversion ) ) {
17252     $dbh->do(q{
17253         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
17254         ('AccountAutoReconcile','0','If enabled, patron balances will get reconciled automatically on each transaction.',NULL,'YesNo');
17255     });
17256     SetVersion($DBversion);
17257     print "Upgrade to $DBversion done (Bug 21915 - Add a way to automatically reconcile balance for patrons)\n";
17258 }
17259
17260 $DBversion = '18.12.00.007';
17261 if( CheckVersion( $DBversion ) ) {
17262     if( column_exists( 'issuingrules', 'chargename' ) ) {
17263         $dbh->do( "ALTER TABLE issuingrules DROP chargename" );
17264     }
17265     SetVersion( $DBversion );
17266     print "Upgrade to $DBversion done (Bug 21753: Drop chargename from issuingrules )\n";
17267 }
17268
17269 $DBversion = '18.12.00.008';
17270 if( CheckVersion( $DBversion ) ) {
17271     if( !column_exists( 'subscription', 'mana_id' ) ) {
17272         $dbh->do( "ALTER TABLE subscription ADD mana_id int(11) NULL DEFAULT NULL" );
17273     }
17274
17275     if( !column_exists( 'saved_sql', 'mana_id' ) ) {
17276         $dbh->do( "ALTER TABLE saved_sql ADD mana_id int(11) NULL DEFAULT NULL" );
17277     }
17278     $dbh->do(q{
17279         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
17280         ('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.','YesNo');
17281     });
17282     $dbh->do(q{
17283         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
17284         ('AutoShareWithMana','','','defines datas automatically shared with mana','multiple');
17285     });
17286     $dbh->do(q{
17287         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
17288         ('ManaToken','',NULL,'Security token used for authentication on Mana KB service (anti spam)','Textarea');
17289     });
17290     SetVersion( $DBversion );
17291     print "Upgrade to $DBversion done (Bug 17047 - Mana knowledge base)\n";
17292 }
17293
17294 $DBversion = '18.12.00.009';
17295 if( CheckVersion( $DBversion ) ) {
17296     $dbh->do(q{
17297         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');
17298     });
17299     SetVersion( $DBversion );
17300     print "Upgrade to $DBversion done (Bug 21241 - Add FallbackToSMSIfNoEmail syspref )\n";
17301 }
17302
17303 $DBversion = '18.12.00.010';
17304 if( CheckVersion( $DBversion ) ) {
17305     $dbh->do(q{
17306         INSERT IGNORE INTO systempreferences
17307             ( variable, value, options, explanation, type )
17308         VALUES
17309             ('RESTPublicAPI','1',NULL,'If enabled, the REST API will expose the /public endpoints.','YesNo')
17310     });
17311
17312     # Always end with this (adjust the bug info)
17313     SetVersion( $DBversion );
17314     print "Upgrade to $DBversion done (Bug 22061 - Add a /public namespace that can be switched on/off)\n";
17315 }
17316
17317 $DBversion = '18.12.00.011';
17318 if( CheckVersion( $DBversion ) ) {
17319     if ( column_exists( 'biblio_metadata', 'marcflavour' ) ) {
17320         $dbh->do(q{
17321             ALTER TABLE biblio_metadata
17322                 CHANGE COLUMN marcflavour `schema` VARCHAR(16)
17323         });
17324     }
17325     if ( column_exists( 'deletedbiblio_metadata', 'marcflavour' ) ) {
17326         $dbh->do(q{
17327             ALTER TABLE deletedbiblio_metadata
17328                 CHANGE COLUMN marcflavour `schema` VARCHAR(16)
17329         });
17330     }
17331     SetVersion( $DBversion );
17332     print "Upgrade to $DBversion done (Bug 22155 - biblio_metadata.marcflavour should be renamed 'schema')\n";
17333 }
17334
17335 $DBversion = '18.12.00.012';
17336 if( CheckVersion( $DBversion ) ) {
17337     $dbh->do(q{
17338         INSERT IGNORE INTO systempreferences
17339             (variable, value, options, explanation, type )
17340         VALUES
17341             ('RESTBasicAuth','0',NULL,'If enabled, Basic authentication is enabled for the REST API.','YesNo')
17342     });
17343     SetVersion( $DBversion );
17344     print "Upgrade to $DBversion done (Bug 22132 - Add Basic authentication)\n";
17345 }
17346
17347 $DBversion = '18.12.00.013';
17348 if( CheckVersion( $DBversion ) ) {
17349     $dbh->do(q{
17350         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES ( 3, 'manage_mana', 'Manage Mana KB content sharing');
17351     });
17352     SetVersion( $DBversion );
17353     print "Upgrade to $DBversion done (Bug 22198 - Add ghranular permission setting for Mana KB)\n";
17354 }
17355
17356 $DBversion = '18.12.00.014';
17357 if( CheckVersion( $DBversion ) ) {
17358     unless( foreign_key_exists( 'messages', 'messages_borrowernumber' ) ) {
17359         $dbh->do(q|
17360             DELETE m FROM messages m
17361             LEFT JOIN borrowers b ON m.borrowernumber=b.borrowernumber
17362             WHERE b.borrowernumber IS NULL
17363         |);
17364         $dbh->do(q|
17365             ALTER TABLE messages
17366             ADD CONSTRAINT messages_borrowernumber
17367             FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
17368         |);
17369     }
17370     SetVersion( $DBversion );
17371     print "Upgrade to $DBversion done (Bug 13515 - Add a FOREIGN KEY constaint on messages.borrowernumber)\n";
17372 }
17373
17374 $DBversion = '18.12.00.015';
17375 if( CheckVersion( $DBversion ) ) {
17376     $dbh->do( "UPDATE action_logs SET info = REPLACE(info,'cardnumber_replaced','cardnumber'), timestamp = timestamp WHERE module='MEMBERS' AND action='MODIFY'" );
17377     $dbh->do( "UPDATE action_logs SET info = REPLACE(info,'previous_cardnumber','before'), timestamp = timestamp WHERE module='MEMBERS' AND action='MODIFY'" );
17378     $dbh->do( "UPDATE action_logs SET info = REPLACE(info,'new_cardnumber','after'), timestamp = timestamp WHERE module='MEMBERS' AND action='MODIFY'" );
17379
17380     SetVersion( $DBversion );
17381     print "Upgrade to $DBversion done (Bug 3820 - Update patron modification logs)\n";
17382 }
17383
17384 $DBversion = '18.12.00.016';
17385 if( CheckVersion( $DBversion ) ) {
17386
17387     if ( !column_exists( 'illrequests', 'status_alias' ) ) {
17388         # Fresh upgrade, just add the column and constraint
17389         $dbh->do( "ALTER TABLE illrequests ADD COLUMN status_alias varchar(80) DEFAULT NULL AFTER status" );
17390     } else {
17391         # Migrate all existing foreign keys from referencing authorised_values.id
17392         # to referencing authorised_values.authorised_value
17393         # First remove the foreign key constraint and index
17394         if ( foreign_key_exists( 'illrequests', 'illrequests_safk' ) ) {
17395             $dbh->do( "ALTER TABLE illrequests DROP FOREIGN KEY illrequests_safk");
17396         }
17397         if ( index_exists( 'illrequests', 'illrequests_safk' ) ) {
17398             $dbh->do( "DROP INDEX illrequests_safk ON illrequests" );
17399         }
17400         # Now change the illrequests.status_alias column definition from int to varchar
17401         $dbh->do( "ALTER TABLE illrequests MODIFY COLUMN status_alias varchar(80)" );
17402         # Now replace all references to authorised_values.id with their
17403         # corresponding authorised_values.authorised_value
17404         my $sth = $dbh->prepare( "SELECT illrequest_id, status_alias FROM illrequests WHERE status_alias IS NOT NULL" );
17405         $sth->execute();
17406         while (my @row = $sth->fetchrow_array()) {
17407             my $r_id = $row[0];
17408             my $av_id = $row[1];
17409             # Get the authorised value's authorised_value value
17410             my ($av_val) = $dbh->selectrow_array( "SELECT authorised_value FROM authorised_values WHERE id = ?", {}, $av_id );
17411             # Now update illrequests.status_alias
17412             if ($av_val) {
17413                 $dbh->do( "UPDATE illrequests SET status_alias = ? WHERE illrequest_id = ?", {}, ($av_val, $r_id) );
17414             }
17415         }
17416     }
17417     if ( !foreign_key_exists( 'illrequests', 'illrequests_safk' ) ) {
17418         $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" );
17419     }
17420     $dbh->do( "INSERT IGNORE INTO authorised_value_categories SET category_name = 'ILLSTATUS'");
17421
17422     SetVersion( $DBversion );
17423     print "Upgrade to $DBversion done (Bug 20581 - Allow manual selection of custom ILL request statuses)\n";
17424 }
17425
17426 $DBversion = '18.12.00.017';
17427 if( CheckVersion( $DBversion ) ) {
17428     $dbh->do(q{
17429         INSERT IGNORE INTO account_offset_types ( type ) VALUES ( 'fine_increase' ), ( 'fine_decrease' );
17430     });
17431     $dbh->do(q{
17432         UPDATE account_offsets SET type = 'fine_increase' WHERE type = 'Fine Update' AND amount > 0;
17433     });
17434     $dbh->do(q{
17435         UPDATE account_offsets SET type = 'fine_decrease' WHERE type = 'Fine Update' AND amount < 0;
17436     });
17437
17438     $dbh->do(q{
17439         DELETE FROM account_offset_types WHERE type = 'Fine Update';
17440     });
17441     SetVersion( $DBversion );
17442     print "Upgrade to $DBversion done (Bug 21747 - Update account_offset_types to include 'fine_increase' and 'fine_decrease')\n";
17443 }
17444
17445 $DBversion = '18.12.00.018';
17446 if( CheckVersion( $DBversion ) ) {
17447   $dbh->do( "UPDATE `search_field` SET `name` = 'date-of-publication', `label` = 'date-of-publication' WHERE `name` = 'pubdate'" );
17448   $dbh->do( "UPDATE `search_field` SET `name` = 'title-series', `label` = 'title-series' WHERE `name` = 'se'" );
17449   $dbh->do( "UPDATE `search_field` SET `name` = 'identifier-standard', `label` = 'identifier-standard' WHERE `name` = 'identifier-standard'" );
17450   $dbh->do( "UPDATE `search_field` SET `name` = 'author', `label` = 'author' WHERE `name` = 'author'" );
17451   $dbh->do( "UPDATE `search_field` SET `name` = 'control-number', `label` = 'control-number' WHERE `name` = 'control-number'" );
17452   $dbh->do( "UPDATE `search_field` SET `name` = 'place-of-publication', `label` = 'place-of-publication' WHERE `name` = 'place'" );
17453   $dbh->do( "UPDATE `search_field` SET `name` = 'date-of-acquisition', `label` = 'date-of-acquisition' WHERE `name` = 'acqdate'" );
17454   $dbh->do( "UPDATE `search_field` SET `name` = 'isbn', `label` = 'isbn' WHERE `name` = 'isbn'" );
17455   $dbh->do( "UPDATE `search_field` SET `name` = 'koha-auth-number', `label` = 'koha-auth-number' WHERE `name` = 'an'" );
17456   $dbh->do( "UPDATE `search_field` SET `name` = 'subject', `label` = 'subject' WHERE `name` = 'subject'" );
17457   $dbh->do( "UPDATE `search_field` SET `name` = 'publisher', `label` = 'publisher' WHERE `name` = 'publisher'" );
17458   $dbh->do( "UPDATE `search_field` SET `name` = 'record-source', `label` = 'record-source' WHERE `name` = 'record-source'" );
17459   $dbh->do( "UPDATE `search_field` SET `name` = 'title', `label` = 'title' WHERE `name` = 'title'" );
17460   $dbh->do( "UPDATE `search_field` SET `name` = 'local-classification', `label` = 'local-classification' WHERE `name` = 'local-classification'" );
17461   $dbh->do( "UPDATE `search_field` SET `name` = 'bib-level', `label` = 'bib-level' WHERE `name` = 'bib-level'" );
17462   $dbh->do( "UPDATE `search_field` SET `name` = 'microform-generation', `label` = 'microform-generation' WHERE `name` = 'microform-generation'" );
17463   $dbh->do( "UPDATE `search_field` SET `name` = 'material-type', `label` = 'material-type' WHERE `name` = 'material-type'" );
17464   $dbh->do( "UPDATE `search_field` SET `name` = 'bgf-number', `label` = 'bgf-number' WHERE `name` = 'bgf-number'" );
17465   $dbh->do( "UPDATE `search_field` SET `name` = 'number-db', `label` = 'number-db' WHERE `name` = 'number-db'" );
17466   $dbh->do( "UPDATE `search_field` SET `name` = 'number-natl-biblio', `label` = 'number-natl-biblio' WHERE `name` = 'number-natl-biblio'" );
17467   $dbh->do( "UPDATE `search_field` SET `name` = 'number-legal-deposit', `label` = 'number-legal-deposit' WHERE `name` = 'number-legal-deposit'" );
17468   $dbh->do( "UPDATE `search_field` SET `name` = 'issn', `label` = 'issn' WHERE `name` = 'issn'" );
17469   $dbh->do( "UPDATE `search_field` SET `name` = 'local-number', `label` = 'local-number' WHERE `name` = 'local-number'" );
17470   $dbh->do( "UPDATE `search_field` SET `name` = 'suppress', `label` = 'supress' WHERE `name` = 'suppress'" );
17471   $dbh->do( "UPDATE `search_field` SET `name` = 'bnb-card-number', `label` = 'bnb-card-number' WHERE `name` = 'bnb-card-number'" );
17472   $dbh->do( "UPDATE `search_field` SET `name` = 'date/time-last-modified', `label` = 'date/time-last-modified' WHERE `name` = 'date-time-last-modified'" );
17473   $dbh->do( "DELETE FROM `search_field` WHERE `name` = 'lc-cardnumber'" );
17474   $dbh->do( "DELETE FROM `search_marc_map` WHERE `id` NOT IN(SELECT `search_marc_map_id` FROM `search_marc_to_field`)" );
17475   SetVersion( $DBversion );
17476   print "Upgrade to $DBversion done (Bug 19575 - Use canonical field names and resolve aliased fields)\n";
17477 }
17478
17479 $DBversion = '18.12.00.019';
17480 if( CheckVersion( $DBversion ) ) {
17481     $dbh->do(q{
17482         INSERT IGNORE INTO account_offset_types ( type ) VALUES ( 'Reserve Fee' );
17483     });
17484
17485     SetVersion( $DBversion );
17486     print "Upgrade to $DBversion done (Bug 21728 - Add 'Reserve Fee' to the account_offset_types table if missing)\n";
17487 }
17488
17489 $DBversion = '18.12.00.020';
17490 if( CheckVersion( $DBversion ) ) {
17491     if ( TableExists( 'branch_borrower_circ_rules' ) ) {
17492         if ( column_exists( 'branch_borrower_circ_rules', 'maxissueqty' ) ) {
17493             $dbh->do("
17494                 INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17495                 SELECT categorycode, branchcode, NULL, 'patron_maxissueqty', COALESCE( maxissueqty, '' )
17496                 FROM branch_borrower_circ_rules
17497             ");
17498             $dbh->do("
17499                 INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17500                 SELECT categorycode, branchcode, NULL, 'patron_maxonsiteissueqty', COALESCE( maxonsiteissueqty, '' )
17501                 FROM branch_borrower_circ_rules
17502             ");
17503             $dbh->do("DROP TABLE branch_borrower_circ_rules");
17504         }
17505     }
17506
17507     if ( TableExists( 'default_borrower_circ_rules' ) ) {
17508         if ( column_exists( 'default_borrower_circ_rules', 'maxissueqty' ) ) {
17509             $dbh->do("
17510                 INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17511                 SELECT categorycode, NULL, NULL, 'patron_maxissueqty', COALESCE( maxissueqty, '' )
17512                 FROM default_borrower_circ_rules
17513             ");
17514             $dbh->do("
17515                 INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17516                 SELECT categorycode, NULL, NULL, 'patron_maxonsiteissueqty', COALESCE( maxonsiteissueqty, '' )
17517                 FROM default_borrower_circ_rules
17518             ");
17519             $dbh->do("DROP TABLE default_borrower_circ_rules");
17520         }
17521     }
17522
17523     if ( column_exists( 'default_circ_rules', 'maxissueqty' ) ) {
17524         $dbh->do("
17525             INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17526             SELECT NULL, NULL, NULL, 'patron_maxissueqty', COALESCE( maxissueqty, '' )
17527             FROM default_circ_rules
17528         ");
17529         $dbh->do("
17530             INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17531             SELECT NULL, NULL, NULL, 'patron_maxonsiteissueqty', COALESCE( maxonsiteissueqty, '' )
17532             FROM default_circ_rules
17533         ");
17534         $dbh->do("ALTER TABLE default_circ_rules DROP COLUMN maxissueqty, DROP COLUMN maxonsiteissueqty");
17535     }
17536
17537     if ( column_exists( 'default_branch_circ_rules', 'maxissueqty' ) ) {
17538         $dbh->do("
17539             INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17540             SELECT NULL, branchcode, NULL, 'patron_maxissueqty', COALESCE( maxissueqty, '' )
17541             FROM default_branch_circ_rules
17542         ");
17543         $dbh->do("
17544             INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17545             SELECT NULL, NULL, NULL, 'patron_maxonsiteissueqty', COALESCE( maxonsiteissueqty, '' )
17546             FROM default_branch_circ_rules
17547         ");
17548         $dbh->do("ALTER TABLE default_branch_circ_rules DROP COLUMN maxissueqty, DROP COLUMN maxonsiteissueqty");
17549     }
17550
17551     if ( column_exists( 'issuingrules', 'maxissueqty' ) ) {
17552         # Cleaning invalid rules before, to avoid FK contraints to fail
17553         $dbh->do(q|
17554             DELETE FROM issuingrules WHERE categorycode != '*' AND categorycode NOT IN (SELECT categorycode FROM categories);
17555         |);
17556         $dbh->do(q|
17557             DELETE FROM issuingrules WHERE branchcode != '*' AND branchcode NOT IN (SELECT branchcode FROM branches);
17558         |);
17559         $dbh->do(q|
17560             DELETE FROM issuingrules WHERE itemtype != '*' AND itemtype NOT IN (SELECT itemtype FROM itemtypes);
17561         |);
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                    'maxissueqty',
17569                    COALESCE( maxissueqty, '' )
17570             FROM issuingrules
17571         ");
17572         $dbh->do("
17573             INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17574             SELECT IF(categorycode='*', NULL, categorycode),
17575                    IF(branchcode='*', NULL, branchcode),
17576                    IF(itemtype='*', NULL, itemtype),
17577                    'maxonsiteissueqty',
17578                    COALESCE( maxonsiteissueqty, '' )
17579             FROM issuingrules
17580         ");
17581         $dbh->do("ALTER TABLE issuingrules DROP COLUMN maxissueqty, DROP COLUMN maxonsiteissueqty");
17582     }
17583
17584     SetVersion( $DBversion );
17585     print "Upgrade to $DBversion done (Bug 18925 - Move maxissueqty and maxonsiteissueqty to circulation_rules)\n";
17586 }
17587
17588 $DBversion = '18.12.00.021';
17589 if ( CheckVersion($DBversion) ) {
17590
17591     if ( !column_exists( 'itemtypes', 'rentalcharge_daily' ) ) {
17592         $dbh->do("ALTER TABLE `itemtypes` ADD COLUMN `rentalcharge_daily` decimal(28,6) default NULL AFTER `rentalcharge`");
17593     }
17594
17595     if ( !column_exists( 'itemtypes', 'rentalcharge_hourly' ) ) {
17596         $dbh->do("ALTER TABLE `itemtypes` ADD COLUMN `rentalcharge_hourly` decimal(28,6) default NULL AFTER `rentalcharge_daily`");
17597     }
17598
17599     if ( column_exists( 'itemtypes', 'rental_charge_daily' ) ) {
17600         $dbh->do("UPDATE `itemtypes` SET `rentalcharge_daily` = `rental_charge_daily`");
17601         $dbh->do("ALTER TABLE `itemtypes` DROP COLUMN `rental_charge_daily`");
17602     }
17603
17604     SetVersion($DBversion);
17605     print "Upgrade to $DBversion done (Bug 20912 - Support granular rental charges)\n";
17606 }
17607
17608 $DBversion = '18.12.00.022';
17609 if( CheckVersion( $DBversion ) ) {
17610     $dbh->do( q{
17611         INSERT IGNORE INTO permissions (module_bit,code,description)
17612         VALUES
17613         (3,'manage_additional_fields','Add, edit, or delete additional custom fields for baskets or subscriptions (also requires order_manage or edit_subscription permissions)')
17614     });
17615     $dbh->do( q{
17616         INSERT INTO user_permissions (borrowernumber, module_bit, code)
17617         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');
17618     });
17619     $dbh->do( q{
17620         INSERT INTO user_permissions (borrowernumber, module_bit, code)
17621         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);
17622     });
17623     SetVersion( $DBversion );
17624     print "Upgrade to $DBversion done (Bug 15774 - Add permission for managing additional fields)\n";
17625 }
17626
17627 $DBversion = '18.12.00.023';
17628 if( CheckVersion( $DBversion ) ) {
17629     $dbh->do(q|
17630       INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
17631       VALUES ('ILLOpacbackends',NULL,NULL,'ILL backends to enabled for OPAC initiated requests','multiple');
17632     |);
17633
17634     # Always end with this (adjust the bug info)
17635     SetVersion( $DBversion );
17636     print "Upgrade to $DBversion done (Bug 20639 - Add ILLOpacbackends syspref)\n";
17637 }
17638
17639 $DBversion = '18.12.00.024';
17640 if ( CheckVersion($DBversion) ) {
17641
17642     # Fixup any pre-existing bad suggestedby, manageddate, accepteddate dates
17643     eval {
17644         local $dbh->{PrintError} = 0;
17645         $dbh->do(
17646             "UPDATE suggestions SET suggesteddate = '1970-01-01' WHERE suggesteddate = '0000-00-00';"
17647         );
17648         $dbh->do(
17649             "UPDATE suggestions SET manageddate = '1970-01-01' WHERE manageddate = '0000-00-00';"
17650         );
17651         $dbh->do(
17652             "UPDATE suggestions SET accepteddate = '1970-01-01' WHERE accepteddate = '0000-00-00';"
17653         );
17654     };
17655
17656     # Add constraint for suggestedby
17657     unless ( foreign_key_exists( 'suggestions', 'suggestions_ibfk_suggestedby' ) )
17658     {
17659         $dbh->do(
17660 "ALTER TABLE suggestions CHANGE COLUMN suggestedby suggestedby INT(11) NULL DEFAULT NULL;"
17661         );
17662         $dbh->do(
17663 "UPDATE suggestions LEFT JOIN borrowers ON (suggestions.suggestedby = borrowers.borrowernumber) SET suggestedby = null WHERE borrowernumber IS null"
17664         );
17665         $dbh->do(
17666 "ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_suggestedby` FOREIGN KEY (`suggestedby`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE"
17667         );
17668     }
17669
17670     # Add constraint for managedby
17671     unless ( foreign_key_exists( 'suggestions', 'suggestions_ibfk_managedby' ) )
17672     {
17673         $dbh->do(
17674 "UPDATE suggestions LEFT JOIN borrowers ON (suggestions.managedby = borrowers.borrowernumber) SET managedby = null WHERE borrowernumber IS NULL"
17675         );
17676         $dbh->do(
17677 "ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_managedby` FOREIGN KEY (`managedby`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE"
17678         );
17679     }
17680
17681     # Add constraint for acceptedby
17682     unless (
17683         foreign_key_exists( 'suggestions', 'suggestions_ibfk_acceptedby' ) )
17684     {
17685         $dbh->do(
17686 "UPDATE suggestions LEFT JOIN borrowers ON (suggestions.acceptedby = borrowers.borrowernumber) SET acceptedby = null WHERE borrowernumber IS NULL"
17687         );
17688         $dbh->do(
17689 "ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_acceptedby` FOREIGN KEY (`acceptedby`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE"
17690         );
17691     }
17692
17693     # Add constraint for rejectedby
17694     unless (
17695         foreign_key_exists( 'suggestions', 'suggestions_ibfk_rejectedby' ) )
17696     {
17697         $dbh->do(
17698 "UPDATE suggestions LEFT JOIN borrowers ON (suggestions.rejectedby = borrowers.borrowernumber) SET rejectedby = null WHERE borrowernumber IS null"
17699         );
17700         $dbh->do(
17701 "ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_rejectedby` FOREIGN KEY (`rejectedby`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE"
17702         );
17703     }
17704
17705     # Add constraint for biblionumber
17706     unless (
17707         foreign_key_exists( 'suggestions', 'suggestions_ibfk_biblionumber' ) )
17708     {
17709         $dbh->do(
17710 "UPDATE suggestions s LEFT JOIN biblio b ON (s.biblionumber = b.biblionumber) SET s.biblionumber = null WHERE b.biblionumber IS null"
17711         );
17712         $dbh->do(
17713 "ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_biblionumber` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE SET NULL ON UPDATE CASCADE"
17714         );
17715     }
17716
17717     # Add constraint for branchcode
17718     unless (
17719         foreign_key_exists( 'suggestions', 'suggestions_ibfk_branchcode' ) )
17720     {
17721         $dbh->do(
17722 "UPDATE suggestions s LEFT JOIN branches b ON (s.branchcode = b.branchcode) SET s.branchcode = null WHERE b.branchcode IS null"
17723         );
17724         $dbh->do(
17725 "ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_branchcode` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE SET NULL ON UPDATE CASCADE"
17726         );
17727     }
17728
17729     SetVersion($DBversion);
17730     print
17731 "Upgrade to $DBversion done (Bug 22368 - Add missing constraints to suggestions)\n";
17732 }
17733
17734 $DBversion = '18.12.00.025';
17735 if( CheckVersion( $DBversion ) ) {
17736
17737     $dbh->do('SET FOREIGN_KEY_CHECKS=0');
17738
17739     # Change columns accordingly
17740     $dbh->do(q{
17741         ALTER TABLE tags_index
17742             MODIFY COLUMN term VARCHAR(191) COLLATE utf8mb4_bin NOT NULL;
17743     });
17744
17745     $dbh->do(q{
17746         ALTER TABLE tags_approval
17747             MODIFY COLUMN term VARCHAR(191) COLLATE utf8mb4_bin NOT NULL;
17748     });
17749
17750     $dbh->do(q{
17751         ALTER TABLE tags_all
17752             MODIFY COLUMN term VARCHAR(191) COLLATE utf8mb4_bin NOT NULL;
17753     });
17754
17755     $dbh->do('SET FOREIGN_KEY_CHECKS=1');
17756
17757     SetVersion( $DBversion );
17758     print "Upgrade to $DBversion done (Bug 21846 - Using emoji as tags has broken weights)\n";
17759     my $maintenance_script = C4::Context->config("intranetdir") . "/misc/maintenance/fix_tags_weight.pl";
17760     print "WARNING: (Bug 21846) You need to manually run $maintenance_script to fix possible issues with tags.\n";
17761 }
17762
17763 $DBversion = '18.12.00.026';
17764 if( CheckVersion( $DBversion ) ) {
17765     $dbh->do( "INSERT IGNORE INTO systempreferences (variable, value, explanation, type) VALUES ('IllLog', 0, 'If ON, log information about ILL requests', 'YesNo')" );
17766
17767     SetVersion( $DBversion );
17768     print "Upgrade to $DBversion done (Bug 20750 - Allow timestamped auditing of ILL request events)\n";
17769 }
17770
17771 $DBversion = '18.12.00.027';
17772 if( CheckVersion( $DBversion ) ) {
17773     $dbh->do(q{
17774 INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
17775        ('ILLModuleUnmediated','0','','If enabled, try to immediately progress newly placed ILL requests.','YesNo');
17776     });
17777     SetVersion( $DBversion );
17778     print "Upgrade to $DBversion done (Bug 18837: Add ILLModuleUnmediated Syspref)\n";
17779 }
17780
17781 $DBversion = '18.12.00.028';
17782 if( CheckVersion( $DBversion ) ) {
17783     $dbh->do(q{
17784         INSERT IGNORE INTO account_offset_types ( type ) VALUES ( 'Account Fee' );
17785     });
17786
17787     $dbh->do(q{
17788         INSERT IGNORE INTO account_offset_types ( type ) VALUES ( 'Hold Expired' );
17789     });
17790
17791     SetVersion( $DBversion );
17792     print "Upgrade to $DBversion done (Bug 21756 - Add 'Account Fee' and 'Hold Expired' to the account_offset_types table if missing)\n";
17793 }
17794
17795 $DBversion = '18.12.00.029';
17796 if( CheckVersion( $DBversion ) ) {
17797     $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')" );
17798
17799     SetVersion( $DBversion );
17800     print "Upgrade to $DBversion done (Bug 18736 - Add syspref to control order rounding)\n";
17801 }
17802
17803 $DBversion = '18.12.00.030';
17804 if( CheckVersion( $DBversion ) ) {
17805     if( column_exists( 'accountlines', 'accountno' ) ) {
17806         $dbh->do( "ALTER TABLE accountlines DROP COLUMN accountno" );
17807     }
17808     if( column_exists( 'statistics', 'proccode' ) ) {
17809         $dbh->do( "ALTER TABLE statistics DROP COLUMN proccode" );
17810     }
17811     SetVersion( $DBversion );
17812     print "Upgrade to $DBversion done (Bug 21683 - Remove accountlines.accountno and statistics.proccode fields)\n";
17813 }
17814
17815 $DBversion = '18.12.00.031';
17816 if( CheckVersion( $DBversion ) ) {
17817
17818     # Add constraint for manager_id
17819     unless( foreign_key_exists( 'accountlines', 'accountlines_ibfk_borrowers_2' ) ) {
17820         $dbh->do("ALTER TABLE accountlines CHANGE COLUMN manager_id manager_id INT(11) NULL DEFAULT NULL");
17821         $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");
17822         $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");
17823     }
17824
17825     # Rename accountlines_ibfk_2 to accountlines_ibfk_items
17826     if ( foreign_key_exists( 'accountlines', 'accountlines_ibfk_2' ) && !foreign_key_exists( 'accountlines', 'accountlines_ibfk_items' ) ) {
17827         $dbh->do("ALTER TABLE accountlines DROP FOREIGN KEY accountlines_ibfk_2");
17828         $dbh->do("ALTER TABLE accountlines ADD CONSTRAINT `accountlines_ibfk_items` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE SET NULL ON UPDATE CASCADE");
17829     }
17830
17831     SetVersion( $DBversion );
17832     print "Upgrade to $DBversion done (Bug 22008 - Add missing constraints for accountlines.manager_id)\n";
17833 }
17834
17835 $DBversion = '18.12.00.032';
17836 if( CheckVersion( $DBversion ) ) {
17837     if( !column_exists( 'search_field', 'facet_order' ) ) {
17838         $dbh->do("ALTER TABLE search_field ADD COLUMN facet_order TINYINT(4) DEFAULT NULL AFTER weight");
17839     }
17840     $dbh->do("UPDATE search_field SET facet_order=1 WHERE name='author'");
17841     $dbh->do("UPDATE search_field SET facet_order=2 WHERE name='itype'");
17842     $dbh->do("UPDATE search_field SET facet_order=3 WHERE name='location'");
17843     $dbh->do("UPDATE search_field SET facet_order=4 WHERE name='su-geo'");
17844     $dbh->do("UPDATE search_field SET facet_order=5 WHERE name='title-series'");
17845     $dbh->do("UPDATE search_field SET facet_order=6 WHERE name='subject'");
17846     $dbh->do("UPDATE search_field SET facet_order=7 WHERE name='ccode'");
17847     $dbh->do("UPDATE search_field SET facet_order=8 WHERE name='holdingbranch'");
17848     $dbh->do("UPDATE search_field SET facet_order=9 WHERE name='homebranch'");
17849     SetVersion( $DBversion );
17850     print "Upgrade to $DBversion done (Bug 18235 - Elastic search - make facets configurable)\n";
17851 }
17852
17853 $DBversion = '18.12.00.033';
17854 if( CheckVersion( $DBversion ) ) {
17855     $dbh->do( "UPDATE search_field SET facet_order=10 WHERE name='ln'" );
17856     SetVersion( $DBversion );
17857     print "Upgrade to $DBversion done (Bug 18213 - Add language facets to Elasticsearch)\n";
17858 }
17859
17860 $DBversion = '18.12.00.034';
17861 if( CheckVersion( $DBversion ) ) {
17862
17863     if ( column_exists( 'accountlines', 'lastincrement' ) ) {
17864         $dbh->do("ALTER TABLE `accountlines` DROP COLUMN `lastincrement`");
17865     }
17866
17867     SetVersion( $DBversion );
17868     print "Upgrade to $DBversion done (Bug 22516 - Drop deprecated accountlines.lastincrement field)\n";
17869 }
17870
17871 $DBversion = '18.12.00.035';
17872 if( CheckVersion( $DBversion ) ) {
17873     $dbh->do( "INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type)
17874                VALUES ('MaxItemsToDisplayForBatchMod','1000',NULL,'Display up to a given number of items in a single item modification batch.','Integer')"
17875             );
17876     SetVersion( $DBversion );
17877     print "Upgrade to $DBversion done (Bug 19722 - Add a MaxItemsToDisplayForBatchMod preference)\n";
17878 }
17879
17880 $DBversion = '18.12.00.036';
17881 if ( CheckVersion($DBversion) ) {
17882
17883     my $rows = $dbh->do(
17884         qq{
17885         UPDATE `accountlines`
17886         SET
17887           `accounttype` = 'FU'
17888         WHERE
17889           `accounttype` = 'O'
17890       }
17891     );
17892
17893     SetVersion($DBversion);
17894     printf "Upgrade to $DBversion done (Bug 22518 - Fix accounttype 'O' to 'FU' - %d updated)\n", $rows;
17895 }
17896
17897 $DBversion = '18.12.00.037';
17898 if( CheckVersion( $DBversion ) ) {
17899
17900     $dbh->do( "UPDATE issues SET renewals = 0 WHERE renewals IS NULL" );
17901     $dbh->do( "UPDATE old_issues SET renewals = 0 WHERE renewals IS NULL" );
17902
17903     $dbh->do( "ALTER TABLE issues MODIFY COLUMN renewals tinyint(4) NOT NULL default 0");
17904     $dbh->do( "ALTER TABLE old_issues MODIFY COLUMN renewals tinyint(4) NOT NULL default 0");
17905
17906     # Always end with this (adjust the bug info)
17907     SetVersion( $DBversion );
17908     print "Upgrade to $DBversion done (Bug 22607 - Set default value of issues.renewals to 0)\n";
17909 }
17910
17911 $DBversion = '18.12.00.038';
17912 if ( CheckVersion($DBversion) ) {
17913
17914     if ( !column_exists( 'accountlines', 'status' ) ) {
17915         $dbh->do(
17916             qq{
17917             ALTER TABLE `accountlines`
17918             ADD
17919               `status` varchar(16) DEFAULT NULL
17920             AFTER
17921               `accounttype`
17922           }
17923         );
17924     }
17925
17926     SetVersion($DBversion);
17927     print "Upgrade to $DBversion done (Bug 22512 - Add status to accountlines)\n";
17928 }
17929
17930 $DBversion = '18.12.00.039';
17931 if ( CheckVersion($DBversion) ) {
17932
17933     if ( !column_exists( 'accountlines', 'interface' ) ) {
17934         $dbh->do(
17935             qq{
17936             ALTER TABLE `accountlines`
17937             ADD
17938               `interface` varchar(16)
17939             AFTER
17940               `manager_id`;
17941           }
17942         );
17943     }
17944
17945     $dbh->do(qq{
17946         UPDATE
17947           `accountlines`
17948         SET
17949           interface = 'opac'
17950         WHERE
17951           borrowernumber = manager_id;
17952     });
17953
17954     $dbh->do(qq{
17955         UPDATE
17956           `accountlines`
17957         SET
17958           interface = 'cron'
17959         WHERE
17960           manager_id IS NULL
17961         AND
17962           branchcode IS NULL;
17963     });
17964
17965     $dbh->do(qq{
17966         UPDATE
17967           `accountlines`
17968         SET
17969           interface = 'intranet'
17970         WHERE
17971           interface IS NULL;
17972     });
17973
17974     $dbh->do(qq{
17975         ALTER TABLE `accountlines`
17976         MODIFY COLUMN `interface` varchar(16) NOT NULL;
17977     });
17978
17979     SetVersion($DBversion);
17980     print "Upgrade to $DBversion done (Bug 22600 - Add interface to accountlines)\n";
17981 }
17982
17983 $DBversion = '18.12.00.040';
17984 if( CheckVersion( $DBversion ) ) {
17985     $dbh->do("UPDATE accountlines SET description = REPLACE(description, 'Reserve Charge - ', '') WHERE description LIKE 'Reserve Charge - %'");
17986     SetVersion( $DBversion );
17987     print "Upgrade to $DBversion done (Bug 12166 - Remove 'Reserve Charge' text from accountlines description)\n";
17988 }
17989
17990 $DBversion = '18.12.00.041';
17991 if( CheckVersion( $DBversion ) ) {
17992     my $table_sth = $dbh->prepare('SHOW CREATE TABLE `search_marc_map`');
17993     $table_sth->execute();
17994     my @table = $table_sth->fetchrow_array();
17995     unless ( $table[1] =~ /`marc_field`.*COLLATE utf8mb4_bin/ ) { #catches utf8mb4 collated tables
17996         $dbh->do("ALTER TABLE `search_marc_map` MODIFY `marc_field` VARCHAR(255) NOT NULL COLLATE utf8mb4_bin COMMENT 'the MARC specifier for this field'");
17997     }
17998
17999     # Always end with this (adjust the bug info)
18000     SetVersion( $DBversion );
18001         print "Upgrade to $DBversion done (Bug 19670 - Change collation of marc_field to allow mixed case search field mappings)\n";
18002 }
18003
18004 $DBversion = '18.12.00.042';
18005 if( CheckVersion( $DBversion ) ) {
18006     $dbh->do( "UPDATE systempreferences SET value = 'default' WHERE variable = 'XSLTDetailsDisplay' AND value = ''" );
18007     SetVersion( $DBversion );
18008     print "Upgrade to $DBversion done (Bug 29891 - Remove non-XSLT detail view in the staff client)\n";
18009 }
18010
18011 $DBversion = '18.12.00.043';
18012 if ( CheckVersion($DBversion) ) {
18013     $dbh->do("UPDATE accountlines SET description = REPLACE(description, 'Lost Item ', '') WHERE description LIKE 'Lost Item %'");
18014     SetVersion($DBversion);
18015     print "Upgrade to $DBversion done (Bug 21953 - Remove 'Lost Item' text from accountlines description)\n";
18016 }
18017
18018 $DBversion = '18.12.00.044';
18019 if( CheckVersion( $DBversion ) ) {
18020
18021     if ( !column_exists( 'categories', 'reset_password' ) ) {
18022         $dbh->do(q{
18023             ALTER TABLE categories
18024                 ADD COLUMN reset_password TINYINT(1) NULL DEFAULT NULL
18025                 AFTER checkprevcheckout
18026         });
18027     }
18028
18029     SetVersion( $DBversion );
18030     print "Upgrade to $DBversion done (Bug 21890 - Patron password reset by category)\n";
18031 }
18032
18033 $DBversion = '18.12.00.045';
18034 if( CheckVersion( $DBversion ) ) {
18035
18036     if ( !column_exists( 'categories', 'change_password' ) ) {
18037         $dbh->do(q{
18038             ALTER TABLE categories
18039                 ADD COLUMN change_password TINYINT(1) NULL DEFAULT NULL
18040                 AFTER reset_password
18041         });
18042     }
18043
18044     SetVersion( $DBversion );
18045     print "Upgrade to $DBversion done (Bug 10796 - Patron password change by category)\n";
18046 }
18047
18048 $DBversion = '18.12.00.046';
18049 if( CheckVersion( $DBversion ) ) {
18050     $dbh->do( "UPDATE systempreferences SET value = 'default' WHERE variable = 'XSLTResultsDisplay' AND value = ''" );
18051     SetVersion( $DBversion );
18052     print "Upgrade to $DBversion done (Bug 22695 - Remove non-XSLT search results view from the staff client)\n";
18053 }
18054
18055 $DBversion = '18.12.00.047';
18056 if( CheckVersion( $DBversion ) ) {
18057     $dbh->do(q|
18058         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');
18059     |);
18060     $dbh->do(q|
18061         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');
18062     |);
18063     SetVersion( $DBversion );
18064     print "Upgrade to $DBversion done (Bug 14557: Add Libris spellchecking system preferences)\n";
18065 }
18066
18067 $DBversion = '18.12.00.048';
18068 if( CheckVersion( $DBversion ) ) {
18069     $dbh->do( q{
18070         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
18071         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');
18072     });
18073     $dbh->do("UPDATE systempreferences SET value='exact_time' WHERE variable='NoRenewalBeforePrecision' AND value IS NULL;" );
18074     SetVersion( $DBversion );
18075     print "Upgrade to $DBversion done (Bug 22044 - Set a default value for NoRenewalBeforePrecision)\n";
18076 }
18077
18078 $DBversion = '18.12.00.049';
18079 if( CheckVersion( $DBversion ) ) {
18080
18081     $dbh->do(q{
18082         ALTER TABLE borrowers
18083             ADD COLUMN flgAnonymized tinyint DEFAULT 0
18084             AFTER overdrive_auth_token
18085     }) if !column_exists('borrowers', 'flgAnonymized');
18086
18087     $dbh->do(q{
18088         ALTER TABLE deletedborrowers
18089             ADD COLUMN flgAnonymized tinyint DEFAULT 0
18090             AFTER overdrive_auth_token
18091     }) if !column_exists('deletedborrowers', 'flgAnonymized');
18092
18093     SetVersion( $DBversion );
18094     print "Upgrade to $DBversion done (Bug 21336 - Add field flgAnonymized)\n";
18095 }
18096
18097 $DBversion = '18.12.00.050';
18098 if( CheckVersion( $DBversion ) ) {
18099     $dbh->do( q|
18100 INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
18101 VALUES
18102 ('UnsubscribeReflectionDelay','',NULL,'Delay for locking unsubscribers', 'Integer'),
18103 ('PatronAnonymizeDelay','',NULL,'Delay for anonymizing patrons', 'Integer'),
18104 ('PatronRemovalDelay','',NULL,'Delay for removing anonymized patrons', 'Integer')
18105     |);
18106     SetVersion( $DBversion );
18107     print "Upgrade to $DBversion done (Bug 21336 - Add preferences)\n";
18108 }
18109
18110 $DBversion = '18.12.00.051';
18111 if( CheckVersion( $DBversion ) ) {
18112     my $failed_attempts = C4::Context->preference('FailedLoginAttempts');
18113     $dbh->do( "UPDATE borrowers SET login_attempts = ? WHERE login_attempts > ?", undef, $failed_attempts, $failed_attempts ) if $failed_attempts && $failed_attempts > 0;
18114     SetVersion( $DBversion );
18115     print "Upgrade to $DBversion done (Bug 21336 - Reset login_attempts)\n";
18116 }
18117
18118 $DBversion = '18.12.00.052';
18119 if( CheckVersion( $DBversion ) ) {
18120     $dbh->do(q{
18121         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
18122         ('OpacMoreSearches', '', NULL, 'Add additional elements to the OPAC more searches bar', 'Textarea')
18123     } );
18124
18125     SetVersion( $DBversion );
18126     print "Upgrade to $DBversion done (Bug 22311 - Add a SysPref to allow adding content to the #moresearches div in the opac)\n";
18127 }
18128
18129 $DBversion = '18.12.00.053';
18130 if( CheckVersion( $DBversion ) ) {
18131     $dbh->do(q{
18132         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES
18133         ('AutoReturnCheckedOutItems', '0', '', 'If disabled, librarian must confirm return of checked out item when checking out to another.', 'YesNo');
18134     });
18135
18136     SetVersion( $DBversion );
18137     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";
18138 }
18139
18140 $DBversion = '18.12.00.054';
18141 if( CheckVersion( $DBversion ) ) {
18142     $dbh->do(q{
18143         INSERT IGNORE permissions (module_bit, code, description)
18144         VALUES
18145         (9,'advanced_editor','Use the advanced cataloging editor')
18146     });
18147     if( C4::Context->preference('EnableAdvancedCatalogingEditor') ){
18148         $dbh->do(q{
18149             INSERT INTO user_permissions (borrowernumber, module_bit, code)
18150             SELECT borrowernumber, 9, 'advanced_editor' FROM borrowers WHERE borrowernumber IN (SELECT DISTINCT borrowernumber FROM user_permissions WHERE code = 'edit_catalogue');
18151         });
18152     }
18153     SetVersion( $DBversion );
18154     print "Upgrade to $DBversion done (Bug 20128: Add permission for Advanced Cataloging Editor)\n";
18155 }
18156
18157 $DBversion = '18.12.00.055';
18158 if ( CheckVersion($DBversion) ) {
18159
18160     $dbh->do(qq{
18161         UPDATE
18162           `account_offset_types`
18163         SET
18164           type = 'OVERDUE'
18165         WHERE
18166           type = 'Fine';
18167     });
18168
18169     $dbh->do(qq{
18170         UPDATE
18171           `account_offset_types`
18172         SET
18173           type = 'OVERDUE_INCREASE'
18174         WHERE
18175           type = 'fine_increase';
18176     });
18177
18178     $dbh->do(qq{
18179         UPDATE
18180           `account_offset_types`
18181         SET
18182           type = 'OVERDUE_DECREASE'
18183         WHERE
18184           type = 'fine_decrease';
18185     });
18186
18187     if ( column_exists( 'accountlines', 'accounttype' ) ) {
18188         $dbh->do(
18189             qq{
18190             ALTER TABLE `accountlines`
18191             CHANGE COLUMN `accounttype`
18192               `accounttype` varchar(16) DEFAULT NULL;
18193           }
18194         );
18195     }
18196
18197     $dbh->do(qq{
18198         UPDATE
18199           accountlines
18200         SET
18201           accounttype = 'OVERDUE',
18202           status = 'UNRETURNED'
18203         WHERE
18204           accounttype = 'FU';
18205     });
18206
18207     $dbh->do(qq{
18208         UPDATE
18209           accountlines
18210         SET
18211           accounttype = 'OVERDUE',
18212           status = 'FORGIVEN'
18213         WHERE
18214           accounttype = 'FFOR';
18215     });
18216
18217     $dbh->do(qq{
18218         UPDATE
18219           accountlines
18220         SET
18221           accounttype = 'OVERDUE',
18222           status = 'RETURNED'
18223         WHERE
18224           accounttype = 'F';
18225     });
18226     SetVersion($DBversion);
18227     print "Upgrade to $DBversion done (Bug 22521 - Update accountlines.accounttype to varchar(16), and map new statuses)\n";
18228 }
18229
18230 $DBversion = '18.12.00.056';
18231 if( CheckVersion( $DBversion ) ) {
18232     $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'");
18233     SetVersion( $DBversion );
18234     print "Upgrade to $DBversion done (Bug 8701 - Update OpacHiddenItems system preference description)\n";
18235 }
18236
18237 $DBversion = '18.12.00.057';
18238 if( CheckVersion( $DBversion ) ) {
18239     if( column_exists('statistics', 'associatedborrower') ) {
18240         $dbh->do(q{ ALTER TABLE statistics DROP COLUMN associatedborrower });
18241     }
18242     if( column_exists('statistics', 'usercode') ) {
18243         $dbh->do(q{ ALTER TABLE statistics DROP COLUMN usercode });
18244     }
18245
18246     SetVersion($DBversion);
18247     print "Upgrade to $DBversion done (Bug 13795 - Delete unused fields from statistics table)\n";
18248 }
18249
18250 $DBversion = '18.12.00.058';
18251 if( CheckVersion( $DBversion ) ) {
18252     my $opaclang = C4::Context->preference("opaclanguages");
18253     my @langs;
18254     push @langs, split ( '\,', $opaclang );
18255     # Get any existing value from the OpacNavRight system preference
18256     my ($OpacNavRight) = $dbh->selectrow_array( q|
18257         SELECT value FROM systempreferences WHERE variable='OpacNavRight';
18258     |);
18259     if( $OpacNavRight ){
18260         # If there is a value in the OpacNavRight preference, insert it into opac_news
18261         $dbh->do("INSERT INTO opac_news (branchcode, lang, title, content ) VALUES (NULL, ?, '', ?)", undef, "OpacNavRight_$langs[0]", $OpacNavRight);
18262     }
18263     # Remove the OpacNavRight system preference
18264     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacNavRight'");
18265     SetVersion ($DBversion);
18266     print "Upgrade to $DBversion done (Bug 22318: Move contents of OpacNavRight preference to Koha news system)\n";
18267 }
18268
18269 $DBversion = '18.12.00.059';
18270 if( CheckVersion( $DBversion ) ) {
18271     if( column_exists( 'import_records', 'z3950random' ) ) {
18272         $dbh->do( "ALTER TABLE import_records DROP COLUMN z3950random" );
18273     }
18274
18275     # Always end with this (adjust the bug info)
18276     SetVersion( $DBversion );
18277     print "Upgrade to $DBversion done (Bug 22532 - Remove import_records z3950random column)\n";
18278 }
18279
18280 $DBversion = '18.12.00.060';
18281 if ( CheckVersion($DBversion) ) {
18282
18283     my $rows = $dbh->do(
18284         qq{
18285         UPDATE `accountlines`
18286         SET
18287           `accounttype` = 'L',
18288           `status`      = 'REPLACED'
18289         WHERE
18290           `accounttype` = 'Rep'
18291       }
18292     );
18293
18294     SetVersion($DBversion);
18295     printf "Upgrade to $DBversion done (Bug 22564 - Fix accounttype 'Rep' - %d updated)\n", $rows;
18296 }
18297
18298 $DBversion = '18.12.00.061';
18299 if( CheckVersion( $DBversion ) ) {
18300
18301     if ( column_exists( 'borrowers', 'flgAnonymized' ) ) {
18302         $dbh->do(q{
18303             UPDATE borrowers SET flgAnonymized = 0 WHERE flgAnonymized IS NULL
18304         });
18305         $dbh->do(q{
18306             ALTER TABLE borrowers
18307                 CHANGE `flgAnonymized` `anonymized` TINYINT(1) NOT NULL DEFAULT 0
18308         });
18309     }
18310
18311     if ( column_exists( 'deletedborrowers', 'flgAnonymized' ) ) {
18312         $dbh->do(q{
18313             UPDATE deletedborrowers SET flgAnonymized = 0 WHERE flgAnonymized IS NULL
18314         });
18315         $dbh->do(q{
18316             ALTER TABLE deletedborrowers
18317                 CHANGE `flgAnonymized` `anonymized` TINYINT(1) NOT NULL DEFAULT 0
18318         });
18319     }
18320
18321     SetVersion( $DBversion );
18322     print "Upgrade to $DBversion done (Bug 21336 - (follow-up) Rename flgAnonymized column)\n";
18323 }
18324
18325 $DBversion = '18.12.00.062';
18326 if( CheckVersion( $DBversion ) ) {
18327     $dbh->do( q|
18328         UPDATE search_marc_map SET marc_field='007_/0'
18329           WHERE marc_type IN ('marc21', 'normarc') AND marc_field='007_/1' AND id IN
18330             (SELECT search_marc_map_id FROM search_marc_to_field WHERE search_field_id IN
18331               (SELECT id FROM search_field WHERE label='ff7-00')
18332             )
18333     |);
18334
18335     $dbh->do( q|
18336         UPDATE search_marc_map SET marc_field='007_/1'
18337           WHERE marc_type IN ('marc21', 'normarc') AND marc_field='007_/2' AND id IN
18338             (SELECT search_marc_map_id FROM search_marc_to_field WHERE search_field_id IN
18339               (SELECT id FROM search_field WHERE label='ff7-01')
18340             )
18341     |);
18342
18343     $dbh->do( q|
18344         UPDATE search_marc_map SET marc_field='007_/2'
18345           WHERE marc_type IN ('marc21', 'normarc') AND marc_field='007_/3' AND id IN
18346             (SELECT search_marc_map_id FROM search_marc_to_field WHERE search_field_id IN
18347               (SELECT id FROM search_field WHERE label='ff7-02')
18348             )
18349     |);
18350
18351     # N.B. ff7-01-02 really is 00-01!
18352     $dbh->do( q|
18353         UPDATE search_marc_map SET marc_field='007_/0-1'
18354           WHERE marc_type IN ('marc21', 'normarc') AND marc_field='007_/1-2' AND id IN
18355             (SELECT search_marc_map_id FROM search_marc_to_field WHERE search_field_id IN
18356               (SELECT id FROM search_field WHERE label='ff7-01-02')
18357             )
18358     |);
18359
18360     $dbh->do( q|
18361         UPDATE search_marc_map SET marc_field='008_/0-5'
18362           WHERE marc_type IN ('marc21', 'normarc') AND marc_field='008_/1-5' AND id IN
18363             (SELECT search_marc_map_id FROM search_marc_to_field WHERE search_field_id IN
18364               (SELECT id FROM search_field WHERE label='date-entered-on-file')
18365             )
18366     |);
18367
18368     $dbh->do( q|
18369         UPDATE search_marc_map SET marc_field='leader_/0-4'
18370           WHERE marc_type IN ('marc21', 'normarc') AND marc_field='leader_/1-5' AND id IN
18371             (SELECT search_marc_map_id FROM search_marc_to_field WHERE search_field_id IN
18372               (SELECT id FROM search_field WHERE label='llength')
18373             )
18374     |);
18375
18376     # Always end with this (adjust the bug info)
18377     SetVersion( $DBversion );
18378     print "Upgrade to $DBversion done (Bug 22339 - Fix search field mappings of MARC fixed fields)\n";
18379 }
18380
18381 $DBversion = '18.12.00.063';
18382 if ( CheckVersion($DBversion) ) {
18383
18384     my $types_map = {
18385         'Writeoff'      => 'W',
18386         'Payment'       => 'Pay',
18387         'Lost Item'     => 'CR',
18388         'Manual Credit' => 'C',
18389         'Forgiven'      => 'FOR'
18390     };
18391
18392     my $sth = $dbh->prepare( "SELECT accountlines_id FROM accountlines WHERE accounttype = 'VOID'" );
18393     my $sth2 = $dbh->prepare( "SELECT type FROM account_offsets WHERE credit_id = ? ORDER BY created_on LIMIT 1" );
18394     my $sth3 = $dbh->prepare( "UPDATE accountlines SET accounttype = ?, status = 'VOID' WHERE accountlines_id = ?" );
18395     $sth->execute();
18396     while (my $row = $sth->fetchrow_hashref) {
18397         $sth2->execute($row->{accountlines_id});
18398         my $result = $sth2->fetchrow_hashref;
18399         my $type = $types_map->{$result->{'type'}} // 'Pay';
18400         $sth3->execute($type,$row->{accountlines_id});
18401     }
18402
18403     SetVersion($DBversion);
18404     print "Upgrade to $DBversion done (Bug 22511 - Update existing VOID accountlines)\n";
18405 }
18406
18407 $DBversion = '18.12.00.064';
18408 if( CheckVersion( $DBversion ) ) {
18409     $dbh->do(q{
18410         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');
18411     });
18412     $dbh->do(q{
18413         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%';
18414     });
18415     $dbh->do(q{
18416         DELETE FROM systempreferences WHERE variable='InProcessingToShelvingCart';
18417     });
18418     $dbh->do(q{
18419         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%';
18420     });
18421     $dbh->do(q{
18422         DELETE FROM systempreferences WHERE variable='ReturnToShelvingCart';
18423     });
18424     SetVersion( $DBversion );
18425     print "Upgrade to $DBversion done (Bug 14576: Add UpdateItemLocationOnCheckin syspref)\n";
18426 }
18427
18428 $DBversion = '18.12.00.065';
18429 if( CheckVersion( $DBversion ) ) {
18430     $dbh->do( q{
18431         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
18432         SELECT 'IndependentBranchesTransfers', value, NULL, 'Allow non-superlibrarians to transfer items between libraries','YesNo'
18433         FROM systempreferences WHERE variable = 'IndependentBranches'
18434     });
18435     SetVersion( $DBversion );
18436     print "Upgrade to $DBversion done (Bug 10300 - Allow transferring of items to be have separate IndependentBranches syspref)\n";
18437 }
18438
18439 $DBversion = '18.12.00.066';
18440 if ( CheckVersion($DBversion) ) {
18441     $dbh->do(q{
18442         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `explanation`, `options`, `type`) VALUES
18443           ('OpenURLResolverURL', '', 'URL of OpenURL Resolver', NULL, 'Free'),
18444           ('OpenURLText', '', 'Text of OpenURL links (or image title if OpenURLImageLocation is defined)', NULL, 'Free'),
18445           ('OpenURLImageLocation', '', 'Location of image for OpenURL links', NULL, 'Free'),
18446           ('OPACShowOpenURL', '', 'Enable display of OpenURL links in OPAC search results and detail page', NULL, 'YesNo'),
18447           ('OPACOpenURLItemTypes', '', 'Show the OpenURL link only for these item types', NULL, 'Free');
18448     });
18449
18450     SetVersion($DBversion);
18451     print
18452 "Upgrade to $DBversion done (Bug 8995 - Add new preferences for OpenURLResolvers)\n";
18453 }
18454
18455 $DBversion = '18.12.00.067';
18456 if ( CheckVersion($DBversion) ) {
18457     $dbh->do(q{
18458         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
18459         VALUES ('SendAllEmailsTo','',NULL,'All emails will be redirected to this email if it is not empty','free');
18460     });
18461     SetVersion($DBversion);
18462     print
18463 "Upgrade to $DBversion done (Bug 8000 - Add new preferences for SendAllEmailsTo)\n";
18464 }
18465
18466 $DBversion = '18.12.00.068';
18467 if ( CheckVersion($DBversion) ) {
18468     $dbh->do(q{
18469         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
18470         ('AllowRenewalOnHoldOverride','0','','If on, allow items on hold to be renewed with a specified due date','YesNo');
18471     });
18472     SetVersion($DBversion);
18473     print "Upgrade to $DBversion done (Bug 7088: Cannot renew items on hold even with override)\n";
18474 }
18475
18476 $DBversion = '18.12.00.069';
18477 if( CheckVersion( $DBversion ) ) {
18478
18479     $dbh->do(q{
18480         INSERT INTO plugin_data
18481             (plugin_class, plugin_key, plugin_value)
18482         SELECT
18483             plugin_class,
18484             '__ENABLED__',
18485             1
18486         FROM plugin_data
18487         WHERE plugin_key='__INSTALLED_VERSION__'
18488     });
18489
18490     # Always end with this (adjust the bug info)
18491     SetVersion( $DBversion );
18492     print "Upgrade to $DBversion done (Bug 22053 - enable all plugins)\n";
18493 }
18494
18495 $DBversion = '18.12.00.070';
18496 if ( CheckVersion($DBversion) ) {
18497     $dbh->do(q{
18498         INSERT IGNORE INTO systempreferences
18499             ( `variable`, `value`, `options`, `explanation`, `type` )
18500         VALUES
18501         ('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');
18502     });
18503     SetVersion($DBversion);
18504     print "Upgrade to $DBversion done (Bug 14407 - Limit web-based self-checkout to specific IP addresses)\n";
18505 }
18506
18507 $DBversion = '18.12.00.071';
18508 if( CheckVersion( $DBversion ) ) {
18509     $dbh->do(q{
18510 INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`, `lang`) VALUES
18511 ('circulation', 'ACCOUNT_CREDIT', '', 'Account payment', 0, 'Account payment', '<table>
18512 [% IF ( LibraryName ) %]
18513  <tr>
18514     <th colspan="4" class="centerednames">
18515         <h3>[% LibraryName | html %]</h3>
18516     </th>
18517  </tr>
18518 [% END %]
18519  <tr>
18520     <th colspan="4" class="centerednames">
18521         <h2><u>Fee receipt</u></h2>
18522     </th>
18523  </tr>
18524  <tr>
18525     <th colspan="4" class="centerednames">
18526         <h2>[% Branches.GetName( patron.branchcode ) | html %]</h2>
18527     </th>
18528  </tr>
18529  <tr>
18530     <th colspan="4">
18531         Received with thanks from  [% patron.firstname | html %] [% patron.surname | html %] <br />
18532         Card number: [% patron.cardnumber | html %]<br />
18533     </th>
18534  </tr>
18535   <tr>
18536     <th>Date</th>
18537     <th>Description of charges</th>
18538     <th>Note</th>
18539     <th>Amount</th>
18540  </tr>
18541
18542   [% FOREACH account IN accounts %]
18543     <tr class="highlight">
18544       <td>[% account.date | $KohaDates %]</td>
18545       <td>
18546         [% PROCESS account_type_description account=account %]
18547         [%- IF account.description %], [% account.description | html %][% END %]
18548       </td>
18549       <td>[% account.note | html %]</td>
18550       [% IF ( account.amountcredit ) %]<td class="credit">[% ELSE %]<td class="debit">[% END %][% account.amount | $Price %]</td>
18551     </tr>
18552
18553   [% END %]
18554 <tfoot>
18555   <tr>
18556     <td colspan="3">Total outstanding dues as on date: </td>
18557     [% IF ( totalcredit ) %]<td class="credit">[% ELSE %]<td class="debit">[% END %][% total | $Price %]</td>
18558   </tr>
18559 </tfoot>
18560 </table>', 'print', 'default');
18561     });
18562     SetVersion( $DBversion );
18563     print "Upgrade to $DBversion done (Bug 22809 - Move 'ACCOUNT_CREDIT' from template to a slip)\n";
18564 }
18565
18566 $DBversion = '18.12.00.072';
18567 if( CheckVersion( $DBversion ) ) {
18568     $dbh->do(q{
18569 INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`, `lang`) VALUES
18570 ('circulation', 'ACCOUNT_DEBIT', '', 'Account fee', 0, 'Account fee', '<table>
18571   [% IF ( LibraryName ) %]
18572     <tr>
18573       <th colspan="5" class="centerednames">
18574         <h3>[% LibraryName | html %]</h3>
18575       </th>
18576     </tr>
18577   [% END %]
18578
18579   <tr>
18580     <th colspan="5" class="centerednames">
18581       <h2><u>INVOICE</u></h2>
18582     </th>
18583   </tr>
18584   <tr>
18585     <th colspan="5" class="centerednames">
18586       <h2>[% Branches.GetName( patron.branchcode ) | html %]</h2>
18587     </th>
18588   </tr>
18589   <tr>
18590     <th colspan="5" >
18591       Bill to: [% patron.firstname | html %] [% patron.surname | html %] <br />
18592       Card number: [% patron.cardnumber | html %]<br />
18593     </th>
18594   </tr>
18595   <tr>
18596     <th>Date</th>
18597     <th>Description of charges</th>
18598     <th>Note</th>
18599     <th style="text-align:right;">Amount</th>
18600     <th style="text-align:right;">Amount outstanding</th>
18601   </tr>
18602
18603   [% FOREACH account IN accounts %]
18604     <tr class="highlight">
18605       <td>[% account.date | $KohaDates%]</td>
18606       <td>
18607         [% PROCESS account_type_description account=account %]
18608         [%- IF account.description %], [% account.description | html %][% END %]
18609       </td>
18610       <td>[% account.note | html %]</td>
18611       [% IF ( account.amountcredit ) %]<td class="credit">[% ELSE %]<td class="debit">[% END %][% account.amount | $Price %]</td>
18612       [% IF ( account.amountoutstandingcredit ) %]<td class="credit">[% ELSE %]<td class="debit">[% END %][% account.amountoutstanding | $Price %]</td>
18613     </tr>
18614   [% END %]
18615
18616   <tfoot>
18617     <tr>
18618       <td colspan="4">Total outstanding dues as on date: </td>
18619       [% IF ( totalcredit ) %]<td class="credit">[% ELSE %]<td class="debit">[% END %][% total | $Price %]</td>
18620     </tr>
18621   </tfoot>
18622 </table>', 'print', 'default');
18623     });
18624     SetVersion( $DBversion );
18625     print "Upgrade to $DBversion done (Bug 22809 - Move 'INVOICE' from template to a slip)\n";
18626 }
18627
18628 $DBversion = '18.12.00.073';
18629 if( CheckVersion( $DBversion ) ) {
18630     $dbh->do( q{
18631             INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
18632             ('EmailPurchaseSuggestions','0','0|EmailAddressForSuggestions|BranchEmailAddress|KohaAdminEmailAddress','Choose email address that will be sent new purchase suggestions','Choice'),
18633             ('EmailAddressForSuggestions','','','If you choose EmailAddressForSuggestions you should enter a valid email address','free')
18634     });
18635
18636     $dbh->do( q{
18637             INSERT IGNORE INTO `letter` (module, code, name, title, content, is_html, message_transport_type) VALUES
18638             ('suggestions','NEW_SUGGESTION','New suggestion','New suggestion','<h3>Suggestion pending approval</h3>
18639                 <p><h4>Suggested by</h4>
18640                     <ul>
18641                         <li><<borrowers.firstname>> <<borrowers.surname>></li>
18642                         <li><<borrowers.cardnumber>></li>
18643                         <li><<borrowers.phone>></li>
18644                         <li><<borrowers.email>></li>
18645                     </ul>
18646                 </p>
18647                 <p><h4>Title suggested</h4>
18648                     <ul>
18649                         <li><b>Library:</b> <<branches.branchname>></li>
18650                         <li><b>Title:</b> <<suggestions.title>></li>
18651                         <li><b>Author:</b> <<suggestions.author>></li>
18652                         <li><b>Copyright date:</b> <<suggestions.copyrightdate>></li>
18653                         <li><b>Standard number (ISBN, ISSN or other):</b> <<suggestions.isbn>></li>
18654                         <li><b>Publisher:</b> <<suggestions.publishercode>></li>
18655                         <li><b>Collection title:</b> <<suggestions.collectiontitle>></li>
18656                         <li><b>Publication place:</b> <<suggestions.place>></li>
18657                         <li><b>Quantity:</b> <<suggestions.quantity>></li>
18658                         <li><b>Item type:</b> <<suggestions.itemtype>></li>
18659                         <li><b>Reason for suggestion:</b> <<suggestions.patronreason>></li>
18660                         <li><b>Notes:</b> <<suggestions.note>></li>
18661                     </ul>
18662                 </p>',1, 'email')
18663     });
18664
18665     SetVersion( $DBversion );
18666     print "Upgrade to $DBversion done (Bug 5770 - Email librarian when purchase suggestion made)\n";
18667 }
18668
18669 $DBversion = '18.12.00.074';
18670 if( CheckVersion( $DBversion ) ) {
18671     unless ( TableExists( 'keyboard_shortcuts' ) ) {
18672         $dbh->do(q|
18673             CREATE TABLE keyboard_shortcuts (
18674             shortcut_name varchar(80) NOT NULL,
18675             shortcut_keys varchar(80) NOT NULL,
18676             PRIMARY KEY (shortcut_name)
18677             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;|
18678         );
18679     }
18680     $dbh->do(q|
18681         INSERT IGNORE INTO keyboard_shortcuts (shortcut_name, shortcut_keys) VALUES
18682         ("insert_copyright","Alt-C"),
18683         ("insert_copyright_sound","Alt-P"),
18684         ("insert_delimiter","Ctrl-D"),
18685         ("subfield_help","Ctrl-H"),
18686         ("link_authorities","Shift-Ctrl-L"),
18687         ("delete_field","Ctrl-X"),
18688         ("delete_subfield","Shift-Ctrl-X"),
18689         ("new_line","Enter"),
18690         ("line_break","Shift-Enter"),
18691         ("next_position","Tab"),
18692         ("prev_position","Shift-Tab")
18693         ;|
18694     );
18695     $dbh->do(q|
18696         INSERT IGNORE permissions (module_bit, code, description)
18697         VALUES
18698         (3,'manage_keyboard_shortcuts','Manage keyboard shortcuts for advanced cataloging editor')
18699         ;|
18700     );
18701     SetVersion( $DBversion );
18702     print "Upgrade to $DBversion done (Bug 21411 - Add keyboard_shortcuts table)\n";
18703 }
18704
18705 $DBversion = '18.12.00.075';
18706 if( CheckVersion( $DBversion ) ) {
18707     # you can use $dbh here like:
18708     unless ( foreign_key_exists( 'tmp_holdsqueue', 'tmp_holdsqueue_ibfk_1' ) ) {
18709         $dbh->do(q{
18710             DELETE t FROM tmp_holdsqueue t
18711             LEFT JOIN items i ON t.itemnumber=i.itemnumber
18712             WHERE i.itemnumber IS NULL
18713         });
18714         $dbh->do(q{
18715             ALTER TABLE tmp_holdsqueue
18716             ADD CONSTRAINT `tmp_holdsqueue_ibfk_1` FOREIGN KEY (`itemnumber`)
18717             REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE
18718         });
18719     }
18720     SetVersion( $DBversion );
18721     print "Upgrade to $DBversion done (Bug 22899 - Add items constraint to tmp_holdsqueue)\n";
18722 }
18723
18724 $DBversion = '19.05.00.000';
18725 if( CheckVersion( $DBversion ) ) {
18726     SetVersion( $DBversion );
18727     print "Upgrade to $DBversion done (19.05.00 release)\n";
18728 }
18729
18730 $DBversion = '19.06.00.000';
18731 if( CheckVersion( $DBversion ) ) {
18732     SetVersion( $DBversion );
18733     print "Upgrade to $DBversion done (Wingardium Leviosa!)\n";
18734 }
18735
18736 $DBversion = '19.06.00.001'; 
18737 if( CheckVersion( $DBversion ) ) {
18738     $dbh->do( q{
18739         UPDATE systempreferences 
18740         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.' 
18741         WHERE variable = 'UpdateItemLocationOnCheckin'
18742     });
18743     SetVersion( $DBversion );
18744     print "Upgrade to $DBversion done (Bug 22960: Fix typo in syspref description)\n";
18745 }
18746
18747 $DBversion = '19.06.00.002';
18748 if ( CheckVersion($DBversion) ) {
18749
18750     $dbh->do(q{ALTER TABLE subscriptionhistory CHANGE opacnote opacnote LONGTEXT NULL});
18751     $dbh->do(q{ALTER TABLE subscriptionhistory CHANGE librariannote librariannote LONGTEXT NULL});
18752
18753     $dbh->do(q{UPDATE subscriptionhistory SET opacnote = NULL WHERE opacnote = ''});
18754     $dbh->do(q{UPDATE subscriptionhistory SET librariannote = NULL WHERE librariannote = ''});
18755
18756     SetVersion ($DBversion);
18757     print "Upgrade to $DBversion done (Bug 10215: Increase the size of opacnote and librariannote for table subscriptionhistory)\n";
18758 }
18759
18760 $DBversion = '19.06.00.003';
18761 if( CheckVersion( $DBversion ) ) {
18762     $dbh->do(q{UPDATE systempreferences SET value = REPLACE( value, ' ', '|' ) WHERE variable = 'UniqueItemFields'; });
18763
18764     SetVersion( $DBversion );
18765     print "Upgrade to $DBversion done (Bug 22867: UniqueItemFields preference value should be pipe-delimited)\n";
18766 }
18767
18768 $DBversion = '19.06.00.004';
18769 if( CheckVersion( $DBversion ) ) {
18770     $dbh->do( 'UPDATE language_descriptions SET description = "Griechisch (Modern 1453-)"
18771       WHERE subtag = "el" and type = "language" and lang ="de"' );
18772     SetVersion( $DBversion );
18773     print "Upgrade to $DBversion done (Bug 22770: Fix typo in language description for el in German)\n";
18774 }
18775
18776 $DBversion = '19.06.00.005';
18777 if( CheckVersion( $DBversion ) ) {
18778     unless ( column_exists( 'reserves', 'item_level_hold' ) ) {
18779         $dbh->do( "ALTER TABLE reserves ADD COLUMN item_level_hold BOOLEAN NOT NULL DEFAULT 0 AFTER itemtype" );
18780     }
18781     unless ( column_exists( 'old_reserves', 'item_level_hold' ) ) {
18782         $dbh->do( "ALTER TABLE old_reserves ADD COLUMN item_level_hold BOOLEAN NOT NULL DEFAULT 0 AFTER itemtype" );
18783     }
18784
18785     SetVersion( $DBversion );
18786     print "Upgrade to $DBversion done (Bug  9834: Add the reserves.item_level_hold column)\n";
18787 }
18788
18789 $DBversion = '19.06.00.006';
18790 if( CheckVersion( $DBversion ) ) {
18791
18792     unless ( TableExists('plugin_methods') ) {
18793         $dbh->do(q{
18794             CREATE TABLE plugin_methods (
18795               plugin_class varchar(255) NOT NULL,
18796               plugin_method varchar(255) NOT NULL,
18797               PRIMARY KEY ( `plugin_class` (191), `plugin_method` (191) )
18798             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
18799         });
18800     }
18801
18802     require Koha::Plugins;
18803     Koha::Plugins->new({ enable_plugins => 1 })->InstallPlugins;
18804
18805     SetVersion( $DBversion );
18806     print "Upgrade to $DBversion done (Bug 21073: Improve plugin performance)\n";
18807 }
18808
18809 $DBversion = '19.06.00.007';
18810 if( CheckVersion( $DBversion ) ) {
18811     $dbh->do( "DELETE FROM systempreferences WHERE variable = 'RotationPreventTransfers'" );
18812     SetVersion( $DBversion );
18813     print "Upgrade to $DBversion done (Bug 22653: Remove unimplemented RotationPreventTransfers system preference)\n";
18814 }
18815
18816 $DBversion = '19.06.00.008';
18817 if( CheckVersion( $DBversion ) ) {
18818     $dbh->do( "UPDATE userflags SET flagdesc = 'Allow staff members to modify permissions and passwords for other staff members' WHERE flag = 'staffaccess'" );
18819     SetVersion( $DBversion );
18820     print "Upgrade to $DBversion done (Bug 23109: Improve description of staffaccess permission)\n";
18821 }
18822
18823 $DBversion = '19.06.00.009';
18824 if( CheckVersion( $DBversion ) ) {
18825     $dbh->do(q{
18826         INSERT IGNORE INTO keyboard_shortcuts (shortcut_name, shortcut_keys)
18827             VALUES ("toggle_keyboard", "Shift-Ctrl-K")
18828     });
18829
18830     SetVersion( $DBversion );
18831     print "Upgrade to $DBversion done (Bug 17178: add shortcut to keyboard_shortcuts)\n";
18832 }
18833
18834 $DBversion = '19.06.00.010';
18835 if( CheckVersion( $DBversion ) ) {
18836
18837     if ( TableExists('default_circ_rules') ) {
18838         if ( column_exists( 'default_circ_rules', 'holdallowed' ) ) {
18839             $dbh->do("
18840                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18841                 SELECT NULL, NULL, NULL, 'holdallowed', holdallowed
18842                 FROM default_circ_rules
18843             ");
18844             $dbh->do("
18845                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18846                 SELECT NULL, NULL, NULL, 'hold_fulfillment_policy', hold_fulfillment_policy
18847                 FROM default_circ_rules
18848             ");
18849             $dbh->do("
18850                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18851                 SELECT NULL, NULL, NULL, 'returnbranch', returnbranch
18852                 FROM default_circ_rules
18853             ");
18854             $dbh->do("DROP TABLE default_circ_rules");
18855         }
18856     }
18857
18858     if ( TableExists('default_branch_circ_rules') ) {
18859         if ( column_exists( 'default_branch_circ_rules', 'holdallowed' ) ) {
18860             $dbh->do("
18861                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18862                 SELECT NULL, branchcode, NULL, 'holdallowed', holdallowed
18863                 FROM default_branch_circ_rules
18864             ");
18865             $dbh->do("
18866                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18867                 SELECT NULL, branchcode, NULL, 'hold_fulfillment_policy', hold_fulfillment_policy
18868                 FROM default_branch_circ_rules
18869             ");
18870             $dbh->do("
18871                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18872                 SELECT NULL, branchcode, NULL, 'returnbranch', returnbranch
18873                 FROM default_branch_circ_rules
18874             ");
18875             $dbh->do("DROP TABLE default_branch_circ_rules");
18876         }
18877     }
18878
18879     if ( TableExists('branch_item_rules') ) {
18880         if ( column_exists( 'branch_item_rules', 'holdallowed' ) ) {
18881             $dbh->do("
18882                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18883                 SELECT NULL, branchcode, itemtype, 'holdallowed', holdallowed
18884                 FROM branch_item_rules
18885             ");
18886             $dbh->do("
18887                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18888                 SELECT NULL, branchcode, itemtype, 'hold_fulfillment_policy', hold_fulfillment_policy
18889                 FROM branch_item_rules
18890             ");
18891             $dbh->do("
18892                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18893                 SELECT NULL, branchcode, itemtype, 'returnbranch', returnbranch
18894                 FROM branch_item_rules
18895             ");
18896             $dbh->do("DROP TABLE branch_item_rules");
18897         }
18898     }
18899
18900     if ( TableExists('default_branch_item_rules') ) {
18901         if ( column_exists( 'default_branch_item_rules', 'holdallowed' ) ) {
18902             $dbh->do("
18903                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18904                 SELECT NULL, NULL, itemtype, 'holdallowed', holdallowed
18905                 FROM default_branch_item_rules
18906             ");
18907             $dbh->do("
18908                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18909                 SELECT NULL, NULL, itemtype, 'hold_fulfillment_policy', hold_fulfillment_policy
18910                 FROM default_branch_item_rules
18911             ");
18912             $dbh->do("
18913                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18914                 SELECT NULL, NULL, itemtype, 'returnbranch', returnbranch
18915                 FROM default_branch_item_rules
18916             ");
18917             $dbh->do("DROP TABLE default_branch_item_rules");
18918         }
18919     }
18920
18921     SetVersion( $DBversion );
18922     print "Upgrade to $DBversion done (Bug 18928: Move holdallowed, hold_fulfillment_policy, returnbranch to circulation_rules)\n";
18923 }
18924
18925 $DBversion = '19.06.00.011';
18926 if( CheckVersion( $DBversion ) ) {
18927
18928     if ( TableExists('refund_lost_item_fee_rules') ) {
18929         if ( column_exists( 'refund_lost_item_fee_rules', 'refund' ) ) {
18930             $dbh->do("
18931                 INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18932                 SELECT NULL, IF(branchcode='*', NULL, branchcode), NULL, 'refund', refund
18933                 FROM refund_lost_item_fee_rules
18934             ");
18935             $dbh->do("DROP TABLE refund_lost_item_fee_rules");
18936         }
18937     }
18938
18939     SetVersion( $DBversion );
18940     print "Upgrade to $DBversion done (Bug 18930: Move lost item refund rules to circulation_rules table)\n";
18941 }
18942
18943 $DBversion = '19.06.00.012';
18944 if ( CheckVersion($DBversion) ) {
18945
18946     # Find and correct pathological cases of LR becoming a credit
18947     my $sth = $dbh->prepare( "SELECT accountlines_id, issue_id, borrowernumber, itemnumber, amount, manager_id FROM accountlines WHERE accounttype = 'LR' AND amount < 0" );
18948     $sth->execute();
18949     while ( my $row = $sth->fetchrow_hashref ) {
18950         $dbh->do(
18951             "INSERT INTO accountlines (accounttype, issue_id, borrowernumber, itemnumber, amount, manager_id, interface) VALUES ( ?, ?, ?, ?, ?, ?, ? );",
18952             {},
18953             (
18954                 'CR',                   $row->{issue_id},
18955                 $row->{borrowernumber}, $row->{itemnumber},
18956                 $row->{amount},         $row->{manager_id},
18957                 'upgrade'
18958             )
18959         );
18960         my $credit_id = $dbh->last_insert_id(undef, undef, 'accountlines', undef);
18961         my $amount = $row->{amount} * -1;
18962         $dbh->do("INSERT INTO account_offsets (credit_id, debit_id, type, amount) VALUES (?,?,?,?);",{},($credit_id, $row->{accountlines_id}, 'Lost Item', $amount));
18963         $dbh->do("UPDATE accountlines SET amount = '$amount' WHERE accountlines_id = '$row->{accountlines_id}';");
18964     }
18965
18966     $dbh->do(qq{
18967         UPDATE
18968           accountlines
18969         SET
18970           accounttype = 'LOST',
18971           status = 'RETURNED'
18972         WHERE
18973           accounttype = 'LR';
18974     });
18975
18976     # Find and correct pathalogical cases of L having been converted to W
18977     $sth = $dbh->prepare( "SELECT accountlines_id, issue_id, borrowernumber, itemnumber, amount, manager_id FROM accountlines WHERE accounttype = 'W' AND itemnumber IS NOT NULL" );
18978     $sth->execute();
18979     while ( my $row = $sth->fetchrow_hashref ) {
18980         my $amount = $row->{amount} * -1;
18981         $dbh->do(
18982             "INSERT INTO accountlines (accounttype, issue_id, borrowernumber, itemnumber, amount, manager_id, interface) VALUES ( ?, ?, ?, ?, ?, ?, ? );",
18983             {},
18984             (
18985                 'LOST', $row->{issue_id}, $row->{borrowernumber},
18986                 $row->{itemnumber}, $amount, $row->{manager_id},
18987                 'upgrade'
18988             )
18989         );
18990         my $debit_id = $dbh->last_insert_id(undef, undef, 'accountlines', undef);
18991         $dbh->do(
18992             "INSERT INTO account_offsets (credit_id, debit_id, type, amount) VALUES (?,?,?,?);",
18993             {},
18994             (
18995                 $row->{accountlines_id}, $debit_id,
18996                 'Lost Item',    $amount
18997             )
18998         );
18999     }
19000
19001     $dbh->do(qq{
19002         UPDATE
19003           accountlines
19004         SET
19005           accounttype = 'LOST'
19006         WHERE
19007           accounttype = 'L';
19008     });
19009
19010     $dbh->do(qq{
19011         UPDATE
19012           accountlines
19013         SET
19014           accounttype = 'LOST_RETURN'
19015         WHERE
19016           accounttype = 'CR';
19017     });
19018
19019     SetVersion($DBversion);
19020     print "Upgrade to $DBversion done (Bug 22563: Fix accounttypes for 'L', 'LR' and 'CR')\n";
19021 }
19022
19023 $DBversion = '19.06.00.013';
19024 if ( CheckVersion( $DBversion ) ) {
19025     unless ( column_exists( 'borrower_modifications', 'changed_fields' ) ) {
19026         $dbh->do("ALTER TABLE borrower_modifications ADD changed_fields MEDIUMTEXT AFTER verification_token;");
19027     }
19028     SetVersion( $DBversion );
19029     print "Upgrade to $DBversion done (Bug 23151: Add borrower_modifications.changed_fields column)\n";
19030 }
19031
19032 $DBversion = '19.06.00.014';
19033 if ( CheckVersion($DBversion) ) {
19034
19035     $dbh->do(qq{
19036         UPDATE
19037           accountlines
19038         SET
19039           accounttype = 'RENT_DAILY_RENEW'
19040         WHERE
19041           accounttype = 'Rent'
19042         AND
19043           description LIKE 'Renewal of Daily Rental Item%';
19044     });
19045
19046     $dbh->do(qq{
19047         UPDATE
19048           accountlines
19049         SET
19050           accounttype = 'RENT_DAILY'
19051         WHERE
19052           accounttype = 'Rent'
19053         AND
19054           description LIKE 'Daily rental';
19055     });
19056
19057
19058     $dbh->do(qq{
19059         UPDATE
19060           accountlines
19061         SET
19062           accounttype = 'RENT_RENEW'
19063         WHERE
19064           accounttype = 'Rent'
19065         AND
19066           description LIKE 'Renewal of Rental Item%';
19067     });
19068
19069     $dbh->do(qq{
19070         UPDATE
19071           accountlines
19072         SET
19073           accounttype = 'RENT'
19074         WHERE
19075           accounttype = 'Rent';
19076     });
19077
19078     SetVersion($DBversion);
19079     print "Upgrade to $DBversion done (Bug 11573: Fix accounttypes for 'Rent')\n";
19080 }
19081
19082 $DBversion = '19.06.00.015';
19083 if( CheckVersion( $DBversion ) ) {
19084     $dbh->do( "UPDATE `search_field` SET `name` = 'date-time-last-modified', `label` = 'date-time-last-modified' WHERE `name` = 'date/time-last-modified'" );
19085
19086     SetVersion( $DBversion );
19087     print "Upgrade to $DBversion done (Bug 22524: Fix date/time-last-modified search with Elasticsearch)\n";
19088 }
19089
19090 $DBversion = '19.06.00.016';
19091 if( CheckVersion( $DBversion ) ) {
19092
19093     $dbh->do(q|
19094         INSERT IGNORE INTO keyboard_shortcuts (shortcut_name, shortcut_keys) VALUES
19095             ("insert_copyright","Alt-C"),
19096             ("insert_copyright_sound","Alt-P"),
19097             ("insert_delimiter","Ctrl-D"),
19098             ("subfield_help","Ctrl-H"),
19099             ("link_authorities","Shift-Ctrl-L"),
19100             ("delete_field","Ctrl-X"),
19101             ("delete_subfield","Shift-Ctrl-X"),
19102             ("new_line","Enter"),
19103             ("line_break","Shift-Enter"),
19104             ("next_position","Tab"),
19105             ("prev_position","Shift-Tab"),
19106             ("toggle_keyboard", "Shift-Ctrl-K")
19107     ;|);
19108
19109     SetVersion( $DBversion );
19110     print "Upgrade to $DBversion done (Bug 23396: Fix missing keyboard_shortcuts table)\n";
19111 }
19112
19113 $DBversion = '19.06.00.017';
19114 if ( CheckVersion($DBversion) ) {
19115
19116     $dbh->do(qq{
19117         INSERT INTO
19118           authorised_values (category,authorised_value,lib)
19119         VALUES
19120           ('PAYMENT_TYPE','SIP00','Cash via SIP2'),
19121           ('PAYMENT_TYPE','SIP01','VISA via SIP2'),
19122           ('PAYMENT_TYPE','SIP02','Creditcard via SIP2')
19123     });
19124
19125     $dbh->do(qq{
19126         UPDATE
19127           accountlines
19128         SET
19129           accounttype  = 'Pay',
19130           payment_type = 'SIP00'
19131         WHERE
19132           accounttype = 'Pay00';
19133     });
19134
19135     $dbh->do(qq{
19136         UPDATE
19137           accountlines
19138         SET
19139           accounttype  = 'Pay',
19140           payment_type = 'SIP01'
19141         WHERE
19142           accounttype = 'Pay01';
19143     });
19144
19145     $dbh->do(qq{
19146         UPDATE
19147           accountlines
19148         SET
19149           accounttype  = 'Pay',
19150           payment_type = 'SIP02'
19151         WHERE
19152           accounttype = 'Pay02';
19153     });
19154
19155     my $sth = $dbh->prepare( q{SELECT * FROM accountlines WHERE accounttype REGEXP '^Pay[[:digit:]]{2}$' } );
19156     $sth->execute();
19157     my $seen = {};
19158     while (my $row = $sth->fetchrow_hashref) {
19159         my $type = $row->{accounttype};
19160         my $sipcode = $type;
19161         $sipcode =~ s/Pay/SIP/g;
19162         unless ($seen->{$sipcode}) {
19163             $dbh->do(qq{
19164                 INSERT INTO
19165                   authorised_values (category,authorised_value,lib)
19166                 VALUES
19167                   ('PAYMENT_TYPE',"$sipcode",'Unrecognised SIP2 payment type')
19168             });
19169
19170              $dbh->do(qq{
19171                 UPDATE
19172                   accountlines
19173                 SET
19174                   accounttype  = 'Pay',
19175                   payment_type = "$sipcode"
19176                 WHERE
19177                   accounttype = "$type";
19178             });
19179
19180             $seen->{$sipcode} = 1;
19181         }
19182     }
19183
19184     SetVersion($DBversion);
19185     print "Upgrade to $DBversion done (Bug 22610: Fix accounttypes for SIP2 payments)\n";
19186 }
19187
19188 $DBversion = '19.06.00.018';
19189 if( CheckVersion( $DBversion ) ) {
19190     if( !column_exists( 'biblio', 'subtitle' ) ) {
19191         $dbh->do( "ALTER TABLE biblio ADD COLUMN medium LONGTEXT AFTER title" );
19192         $dbh->do( "ALTER TABLE biblio ADD COLUMN subtitle LONGTEXT AFTER medium" );
19193         $dbh->do( "ALTER TABLE biblio ADD COLUMN part_number LONGTEXT AFTER subtitle" );
19194         $dbh->do( "ALTER TABLE biblio ADD COLUMN part_name LONGTEXT AFTER part_number" );
19195
19196         $dbh->do( "ALTER TABLE deletedbiblio ADD COLUMN medium LONGTEXT AFTER title" );
19197         $dbh->do( "ALTER TABLE deletedbiblio ADD COLUMN subtitle LONGTEXT AFTER medium" );
19198         $dbh->do( "ALTER TABLE deletedbiblio ADD COLUMN part_number LONGTEXT AFTER subtitle" );
19199         $dbh->do( "ALTER TABLE deletedbiblio ADD COLUMN part_name LONGTEXT AFTER part_number" );
19200     }
19201
19202     $dbh->do( "UPDATE marc_subfield_structure SET kohafield='biblio.subtitle' WHERE kohafield='bibliosubtitle.subtitle'" );
19203
19204     my $marcflavour = C4::Context->preference('marcflavour');
19205
19206     if ( $marcflavour eq 'UNIMARC' ) {
19207         $dbh->do(qq{
19208             UPDATE marc_subfield_structure SET kohafield='biblio.medium'
19209             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='200' AND tagsubfield='b'
19210         });
19211         $dbh->do(qq{
19212             UPDATE marc_subfield_structure SET kohafield='biblio.subtitle'
19213             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='200' AND tagsubfield='e'
19214         });
19215         $dbh->do(qq{
19216             UPDATE marc_subfield_structure SET kohafield='biblio.part_number'
19217             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='200' AND tagsubfield='h'
19218         });
19219         $dbh->do(qq{
19220             UPDATE marc_subfield_structure SET kohafield='biblio.part_name'
19221             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='200' AND tagsubfield='i'
19222         });
19223     } else {
19224         $dbh->do(qq{
19225             UPDATE marc_subfield_structure SET kohafield='biblio.medium'
19226             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='245' AND tagsubfield='h'
19227         });
19228         $dbh->do(qq{
19229             UPDATE marc_subfield_structure SET kohafield='biblio.subtitle'
19230             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='245' AND tagsubfield='b'
19231         });
19232         $dbh->do(qq{
19233             UPDATE marc_subfield_structure SET kohafield='biblio.part_number'
19234             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='245' AND tagsubfield='n'
19235         });
19236         $dbh->do(qq{
19237             UPDATE marc_subfield_structure SET kohafield='biblio.part_name'
19238             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='245' AND tagsubfield='p'
19239         });
19240     }
19241
19242     $sth = $dbh->prepare("SELECT * FROM fieldmapping");
19243     $sth->execute;
19244     my @fails_11529;
19245     if ( $sth->rows ) {
19246         while ( my $value = $sth->fetchrow_hashref() ) {
19247             my $framework =
19248               $value->{frameworkcode} eq ""
19249               ? "Default"
19250               : $value->{frameworkcode};
19251             push @fails_11529,
19252               {
19253                 field        => $value->{field},
19254                 fieldcode    => $value->{fieldcode},
19255                 subfieldcode => $value->{subfieldcode},
19256                 framework    => $framework
19257               };
19258         }
19259     }
19260
19261     $dbh->do( "DROP TABLE IF EXISTS fieldmapping" );
19262
19263     $dbh->do( "DELETE FROM user_permissions WHERE code='manage_keywords2koha_mappings'" );
19264
19265     $dbh->do( "DELETE FROM permissions WHERE code='manage_keywords2koha_mappings'" );
19266
19267     # Always end with this (adjust the bug info)
19268     SetVersion( $DBversion );
19269     print "Upgrade to $DBversion done (Bug 11529: Add medium, subtitle and part information to biblio table)\n";
19270     if ( @fails_11529 ) {
19271         print "WARNING: Keyword to MARC Mappings:\n";
19272         for my $fail_11529 ( @fails_11529 ) {
19273             print "    keyword: "
19274               . $fail_11529->{field}
19275               . " to field: "
19276               . $fail_11529->{fieldcode} . "\$"
19277               . $fail_11529->{subfieldcode} . " for "
19278               . $fail_11529->{framework}
19279               . " framework\n";
19280         }
19281         print "The keyword to marc mapping feature is no longer supported. Above find the\n";
19282         print "mappings that had been defined in your system. You will need to remap any\n";
19283         print "desired MARC fields to the Koha field you desire in the Koha to MARC mappings\n";
19284         print "page under Administration\n";
19285     }
19286     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"
19287 }
19288
19289 $DBversion = '19.06.00.019';
19290 if ( CheckVersion($DBversion) ) {
19291     $dbh->do(q{
19292         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type)
19293         VALUES
19294           (
19295             'FinePaymentAutoPopup',
19296             '0',
19297             NULL,
19298             'If enabled, automatically display a print dialog for a payment receipt when making a payment.',
19299             'YesNo'
19300           )
19301     });
19302
19303     SetVersion($DBversion);
19304     print
19305 "Upgrade to $DBversion done (Bug 23228: Add option to automatically display payment receipt for printing after making a payment)\n";
19306 }
19307
19308 $DBversion = '19.06.00.020';
19309 if( CheckVersion( $DBversion ) ) {
19310     $dbh->do(q|
19311         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
19312         ('PreserveSerialNotes','1','','When a new "Expected" issue is generated, should it be prefilled with last created issue notes?','YesNo');
19313     |);
19314
19315     SetVersion( $DBversion );
19316     print "Upgrade to $DBversion done (Bug 23416: Add PreserveSerialNotes syspref)\n";
19317 }
19318
19319 $DBversion = '19.06.00.021';
19320 if( CheckVersion( $DBversion ) ) {
19321
19322     $dbh->do(q|
19323         ALTER TABLE marc_subfield_structure CHANGE COLUMN hidden hidden TINYINT(1) DEFAULT 8 NOT NULL;
19324     |);
19325     # Always end with this (adjust the bug info)
19326     SetVersion( $DBversion );
19327     print "Upgrade to $DBversion done (Bug 23309: Can't add new subfields to bibliographic frameworks in strict mode)\n";
19328 }
19329
19330 $DBversion = '19.06.00.022';
19331 if ( CheckVersion($DBversion) ) {
19332
19333     unless ( TableExists('borrower_relationships') ) {
19334         $dbh->do(q{
19335             CREATE TABLE `borrower_relationships` (
19336                   id INT(11) NOT NULL AUTO_INCREMENT,
19337                   guarantor_id INT(11) NOT NULL,
19338                   guarantee_id INT(11) NOT NULL,
19339                   relationship VARCHAR(100) NOT NULL,
19340                   PRIMARY KEY (id),
19341                   UNIQUE KEY `guarantor_guarantee_idx` ( `guarantor_id`, `guarantee_id` ),
19342                   CONSTRAINT r_guarantor FOREIGN KEY ( guarantor_id ) REFERENCES borrowers ( borrowernumber ) ON UPDATE CASCADE ON DELETE CASCADE,
19343                   CONSTRAINT r_guarantee FOREIGN KEY ( guarantee_id ) REFERENCES borrowers ( borrowernumber ) ON UPDATE CASCADE ON DELETE CASCADE
19344             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
19345         });
19346
19347         $dbh->do(q{
19348             UPDATE borrowers
19349             LEFT JOIN borrowers guarantor ON ( borrowers.guarantorid = guarantor.borrowernumber )
19350             SET borrowers.guarantorid = NULL WHERE guarantor.borrowernumber IS NULL;
19351         });
19352
19353         # Bad data handling: guarantorid IS NOT NULL AND relationship IS NULL
19354         $dbh->do(q{
19355             UPDATE borrowers
19356             SET relationship = '_bad_data'
19357             WHERE guarantorid IS NOT NULL AND
19358                   relationship IS NULL
19359         });
19360
19361         $dbh->do(q{
19362             INSERT INTO borrower_relationships ( guarantor_id, guarantee_id, relationship )
19363             SELECT guarantorid, borrowernumber, relationship FROM borrowers WHERE guarantorid IS NOT NULL;
19364         });
19365
19366         # Clean migrated guarantor data
19367         $dbh->do(q{
19368             UPDATE borrowers
19369             SET contactname=NULL,
19370                 contactfirstname=NULL,
19371                 relationship=NULL
19372             WHERE guarantorid IS NOT NULL
19373         });
19374     }
19375
19376     if ( column_exists( 'borrowers', 'guarantorid' ) ) {
19377         $dbh->do(q{
19378             ALTER TABLE borrowers DROP guarantorid;
19379         });
19380     }
19381
19382     if ( column_exists( 'deletedborrowers', 'guarantorid' ) ) {
19383         $dbh->do(q{
19384             ALTER TABLE deletedborrowers DROP guarantorid;
19385         });
19386     }
19387
19388     if ( column_exists( 'borrower_modifications', 'guarantorid' ) ) {
19389         $dbh->do(q{
19390             ALTER TABLE borrower_modifications DROP guarantorid;
19391         });
19392     }
19393
19394     SetVersion($DBversion);
19395     print "Upgrade to $DBversion done (Bug 14570: Make it possible to add multiple guarantors to a record)\n";
19396 }
19397
19398 $DBversion = '19.06.00.023';
19399 if( CheckVersion( $DBversion ) ) {
19400     $dbh->do(q{
19401         INSERT IGNORE INTO `systempreferences` (`variable`,`value`,`explanation`,`options`,`type`) VALUES
19402         ('ElasticsearchMARCFormat', 'ISO2709', 'ISO2709|ARRAY', 'Elasticsearch MARC format. ISO2709 format is recommended as it is faster and takes less space, whereas array is searchable.', 'Choice')
19403     });
19404
19405     SetVersion( $DBversion );
19406     print "Upgrade to $DBversion done (Bug 22258: Add ElasticsearchMARCFormat preference)\n";
19407 }
19408
19409 $DBversion = '19.06.00.024';
19410 if( CheckVersion( $DBversion ) ) {
19411     $dbh->do(q{ALTER TABLE accountlines CHANGE COLUMN accounttype accounttype varchar(80) default NULL});
19412
19413     SetVersion( $DBversion );
19414     print "Upgrade to $DBversion done (Bug 23539: accountlines.accounttype should match authorised_values.authorised_value in size)\n";
19415 }
19416
19417 $DBversion = '19.06.00.025';
19418 if( CheckVersion( $DBversion ) ) {
19419     $dbh->do( q/INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES (?, ?, ?, ?, ?)/, undef, 'BarcodeSeparators','\s\r\n','','Splitting characters for barcodes','Free' );
19420     SetVersion( $DBversion );
19421     print "Upgrade to $DBversion done (Bug 22996: Add pref BarcodeSeparators)\n";
19422 }
19423
19424 $DBversion = '19.06.00.026';
19425 if( CheckVersion( $DBversion ) ) {
19426
19427     unless ( column_exists( 'borrowers', 'privacy_guarantor_fines' ) ) {
19428         $dbh->do(q{
19429             ALTER TABLE borrowers
19430                 ADD privacy_guarantor_fines TINYINT(1) NOT NULL DEFAULT '0' AFTER privacy;
19431         });
19432     }
19433
19434     unless ( column_exists( 'deletedborrowers', 'privacy_guarantor_fines' ) ) {
19435         $dbh->do(q{
19436             ALTER TABLE deletedborrowers
19437                 ADD privacy_guarantor_fines TINYINT(1) NOT NULL DEFAULT '0' AFTER privacy;
19438         });
19439     }
19440
19441     $dbh->do(q{
19442         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type )
19443         VALUES (
19444             'AllowStaffToSetFinesVisibilityForGuarantor',  '0', NULL,
19445             'If enabled, library staff can set a patron''s fines to be visible to linked patrons from the opac.',  'YesNo'
19446         ), (
19447             'AllowPatronToSetFinesVisibilityForGuarantor',  '0', NULL,
19448             'If enabled, the patron can set fines to be visible to  his or her guarantor',  'YesNo'
19449         )
19450     });
19451
19452     SetVersion( $DBversion );
19453     print "Upgrade to $DBversion done (Bug 20691: Add ability for guarantors to view guarantee's fines in OPAC)\n";
19454 }
19455
19456 $DBversion = '19.06.00.027';
19457 if( CheckVersion( $DBversion ) ) {
19458
19459     if( !TableExists( 'itemtypes_branches' ) ) {
19460        $dbh->do( "
19461             CREATE TABLE itemtypes_branches( -- association table between authorised_values and branches
19462                 itemtype VARCHAR(10) NOT NULL,
19463                 branchcode VARCHAR(10) NOT NULL,
19464                 FOREIGN KEY (itemtype) REFERENCES itemtypes(itemtype) ON DELETE CASCADE,
19465                 FOREIGN KEY (branchcode) REFERENCES branches(branchcode) ON DELETE CASCADE
19466             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
19467         ");
19468     }
19469
19470     SetVersion( $DBversion );
19471     print "Upgrade to $DBversion done (Bug 15497: Add itemtypes_branches table)\n";
19472 }
19473
19474 $DBversion = '19.06.00.028';
19475 if ( CheckVersion($DBversion) ) {
19476
19477     $dbh->do(qq{
19478         UPDATE
19479           accountlines
19480         SET
19481           accounttype = 'ACCOUNT'
19482         WHERE
19483           accounttype = 'A';
19484     });
19485
19486     SetVersion($DBversion);
19487     print "Upgrade to $DBversion done (Bug 11573: Fix accounttypes for 'A')\n";
19488 }
19489
19490 $DBversion = '19.06.00.029';
19491 if ( CheckVersion($DBversion) ) {
19492
19493     unless ( TableExists( 'cash_registers' ) ) {
19494         $dbh->do(qq{
19495     CREATE TABLE `cash_registers` (
19496     `id` int(11) NOT NULL auto_increment, -- unique identifier for each account register
19497     `name` varchar(24) NOT NULL, -- the user friendly identifier for each account register
19498     `description` longtext NOT NULL, -- the user friendly description for each account register
19499     `branch` varchar(10) NOT NULL, -- the foreign key the library this account register belongs
19500     `branch_default` tinyint(1) NOT NULL DEFAULT 0, -- boolean flag to denote that this till is the branch default
19501     `starting_float` decimal(28, 6), -- the starting float this account register should be assigned
19502     `archived` tinyint(1) NOT NULL DEFAULT 0, -- boolean flag to denote if this till is archived or not
19503     PRIMARY KEY (`id`),
19504     UNIQUE KEY `name` (`name`,`branch`),
19505     CONSTRAINT cash_registers_branch FOREIGN KEY (branch) REFERENCES branches (branchcode) ON UPDATE CASCADE ON DELETE CASCADE
19506     ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
19507         });
19508     }
19509
19510     unless ( column_exists( 'accountlines', 'register_id' ) ) {
19511         $dbh->do(qq{ALTER TABLE `accountlines` ADD `register_id` int(11) NULL DEFAULT NULL AFTER `manager_id`});
19512         $dbh->do(qq{
19513             ALTER TABLE `accountlines`
19514             ADD CONSTRAINT `accountlines_ibfk_registers` FOREIGN KEY (`register_id`)
19515             REFERENCES `cash_registers` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
19516         });
19517     }
19518
19519     $dbh->do(qq{
19520         INSERT IGNORE INTO `userflags` (`bit`, `flag`, `flagdesc`, `defaulton`)
19521         VALUES (25, 'cash_management', 'Cash management', 0)
19522     });
19523
19524     $dbh->do(qq{
19525         INSERT IGNORE permissions (module_bit, code, description)
19526         VALUES
19527         (25, 'manage_cash_registers', 'Add and remove cash registers')
19528     });
19529
19530     $dbh->do(qq{
19531         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
19532         ('UseCashRegisters','0','','Use cash registers with the accounting system and assign patron transactions to them.','YesNo')
19533     });
19534
19535     SetVersion($DBversion);
19536     print "Upgrade to $DBversion done (Bug 23321: Add cash_registers table, permissions and preferences)\n";
19537 }
19538
19539 $DBversion = '19.06.00.030';
19540 if( CheckVersion( $DBversion ) ) {
19541
19542     if ( !TableExists('club_holds') ) {
19543         $dbh->do(q|
19544             CREATE TABLE club_holds (
19545                 id        INT(11) NOT NULL AUTO_INCREMENT,
19546                 club_id   INT(11) NOT NULL, -- id for the club the hold was generated for
19547                 biblio_id INT(11) NOT NULL, -- id for the bibliographic record the hold has been placed against
19548                 item_id   INT(11) NULL DEFAULT NULL, -- If item-level, the id for the item the hold has been placed agains
19549                 date_created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, -- Timestamp for the placed hold
19550                 PRIMARY KEY (id),
19551                 -- KEY club_id (club_id),
19552                 CONSTRAINT clubs_holds_ibfk_1 FOREIGN KEY (club_id)   REFERENCES clubs  (id) ON DELETE CASCADE ON UPDATE CASCADE,
19553                 CONSTRAINT clubs_holds_ibfk_2 FOREIGN KEY (biblio_id) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE,
19554                 CONSTRAINT clubs_holds_ibfk_3 FOREIGN KEY (item_id)   REFERENCES items  (itemnumber) ON DELETE CASCADE ON UPDATE CASCADE
19555             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
19556         |);
19557     }
19558
19559     if ( !TableExists('club_holds_to_patron_holds') ) {
19560         $dbh->do(q|
19561             CREATE TABLE club_holds_to_patron_holds (
19562                 id              INT(11) NOT NULL AUTO_INCREMENT,
19563                 club_hold_id    INT(11) NOT NULL,
19564                 patron_id       INT(11) NOT NULL,
19565                 hold_id         INT(11),
19566                 error_code      ENUM ( 'damaged', 'ageRestricted', 'itemAlreadyOnHold',
19567                                     'tooManyHoldsForThisRecord', 'tooManyReservesToday',
19568                                     'tooManyReserves', 'notReservable', 'cannotReserveFromOtherBranches',
19569                                     'libraryNotFound', 'libraryNotPickupLocation', 'cannotBeTransferred'
19570                                 ) NULL DEFAULT NULL,
19571                 error_message   varchar(100) NULL DEFAULT NULL,
19572                 PRIMARY KEY (id),
19573                 -- KEY club_hold_id (club_hold_id),
19574                 CONSTRAINT clubs_holds_paton_holds_ibfk_1 FOREIGN KEY (club_hold_id) REFERENCES club_holds (id) ON DELETE CASCADE ON UPDATE CASCADE,
19575                 CONSTRAINT clubs_holds_paton_holds_ibfk_2 FOREIGN KEY (patron_id) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE,
19576                 CONSTRAINT clubs_holds_paton_holds_ibfk_3 FOREIGN KEY (hold_id) REFERENCES reserves (reserve_id) ON DELETE CASCADE ON UPDATE CASCADE
19577             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
19578         |);
19579     }
19580
19581     # Always end with this (adjust the bug info)
19582     SetVersion( $DBversion );
19583     print "Upgrade to $DBversion done (Bug 19618: add club_holds tables)\n";
19584 }
19585
19586 $DBversion = '19.06.00.031';
19587 if( CheckVersion( $DBversion ) ) {
19588     $dbh->do(q|
19589         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
19590         ('OPACDetailQRCode','0','','Enable the display of a QR Code on the OPAC detail page','YesNo');
19591     |);
19592
19593     SetVersion( $DBversion );
19594     print "Upgrade to $DBversion done (Bug 23566: Add OPACDetailQRCode system preference)\n";
19595 }
19596
19597 $DBversion = '19.06.00.032';
19598 if ( CheckVersion($DBversion) ) {
19599     if ( !column_exists( 'search_marc_to_field', 'search' ) ) {
19600         $dbh->do(q|
19601             ALTER TABLE `search_marc_to_field` ADD COLUMN `search` tinyint(1) NOT NULL DEFAULT 1
19602         |);
19603     }
19604     if ( !column_exists( 'search_field', 'staff_client' ) ) {
19605         $dbh->do(q|
19606             ALTER TABLE `search_field` ADD COLUMN `staff_client` tinyint(1) NOT NULL DEFAULT 1
19607         |);
19608     }
19609     if ( !column_exists( 'search_field', 'opac' ) ) {
19610         $dbh->do(q|
19611             ALTER TABLE `search_field` ADD COLUMN `opac` tinyint(1) NOT NULL DEFAULT 1
19612         |);
19613     }
19614
19615     SetVersion($DBversion);
19616     print
19617 "Upgrade to $DBversion done (Bug 20589: Add field boosting and use elastic query fields parameter instead of depricated _all)\n";
19618 }
19619
19620 $DBversion = '19.06.00.033';
19621 if( CheckVersion( $DBversion ) ) {
19622
19623     $dbh->do(qq{
19624         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
19625         ('OnSiteCheckoutAutoCheck','0','','Enable/Do not enable onsite checkout by default if last checkout was an onsite checkout','YesNo')
19626     });
19627     SetVersion( $DBversion );
19628     print "Upgrade to $DBversion done (Bug 23686: Add OnSiteCheckoutAutoCheck system preference)\n";
19629 }
19630
19631 $DBversion = '19.06.00.034';
19632 if( CheckVersion( $DBversion ) ) {
19633     $dbh->do(q{
19634         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
19635         ('TransfersBlockCirc','1',NULL,'Should the transfer modal block circulation staff from continuing scanning items','YesNo')
19636     });
19637     SetVersion( $DBversion );
19638     print "Upgrade to $DBversion done (Bug 23007: Make transfer modals optionally block circ)\n";
19639 }
19640
19641 $DBversion = '19.06.00.035';
19642 if( CheckVersion( $DBversion ) ) {
19643
19644     $dbh->do(q{
19645         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
19646         ( 'IntranetCoce','0', NULL, 'If on, enables cover retrieval from the configured Coce server in the staff client', 'YesNo')
19647     });
19648
19649     $dbh->do(qq{
19650         UPDATE systempreferences SET 
19651           variable = 'OpacCoce', 
19652           explanation = 'If on, enables cover retrieval from the configured Coce server in the OPAC'
19653         WHERE 
19654           variable = 'Coce'
19655     });
19656
19657     SetVersion( $DBversion );
19658     print "Upgrade to $DBversion done (Bug 18421: Add Coce image cache to the Intranet)\n";
19659 }
19660
19661 $DBversion = '19.06.00.036';
19662 if( CheckVersion( $DBversion ) ) {
19663
19664     $dbh->do(q{
19665         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type`) VALUES  
19666         ('QueryRegexEscapeOptions', 'escape', 'dont_escape|escape|unescape_escaped', 'Escape option for regexps delimiters in Elasicsearch queries.', 'Choice')
19667     });
19668
19669     SetVersion( $DBversion );
19670     print "Upgrade to $DBversion done (Bug 20334: Add elasticsearch escape options preference)\n";
19671 }
19672
19673 $DBversion = '19.06.00.037';
19674 if( CheckVersion( $DBversion ) ) {
19675     $dbh->do(q{
19676         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
19677         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')
19678     });
19679
19680     SetVersion( $DBversion );
19681     print "Upgrade to $DBversion done (Bug 21701: PayPal return URL option)\n";
19682 }
19683
19684 $DBversion = '19.06.00.038';
19685 if( CheckVersion( $DBversion ) ) {
19686     $dbh->do( "UPDATE systempreferences SET variable='PatronAutoComplete' WHERE variable='CircAutocompl' LIMIT 1" );
19687     SetVersion( $DBversion );
19688     print "Upgrade to $DBversion done (Bug 23697: Rename CircAutocompl system preference to PatronAutoComplete)\n";
19689 }
19690
19691 $DBversion = '19.06.00.039';
19692 if( CheckVersion( $DBversion ) ) {
19693     $dbh->do(q|
19694         INSERT IGNORE INTO keyboard_shortcuts (shortcut_name, shortcut_keys) VALUES
19695         ("copy_line","Ctrl-C"),
19696         ("copy_subfield","Shift-Ctrl-C"),
19697         ("paste_line","Ctrl-P"),
19698         ("insert_line","Ctrl-I")
19699         ;
19700     |);
19701     SetVersion( $DBversion );
19702     print "Upgrade to $DBversion done (Bug 17179: Add additional keyboard_shortcuts)\n";
19703 }
19704
19705 $DBversion = '19.06.00.040';
19706 if( CheckVersion( $DBversion ) ) {
19707     $dbh->do(q|
19708         INSERT IGNORE INTO systempreferences
19709         (variable,value,explanation,options,type)
19710         VALUES
19711         ('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')
19712     |);
19713
19714     SetVersion( $DBversion );
19715     print "Upgrade to $DBversion done (Bug 17140: Add pref to allow rounding fines at payment)\n";
19716 }
19717
19718 $DBversion = '19.06.00.041';
19719 if( CheckVersion( $DBversion ) ) {
19720     my ($socialnetworks) = $dbh->selectrow_array( q|
19721         SELECT value FROM systempreferences WHERE variable='socialnetworks';
19722     |);
19723     if( $socialnetworks ){
19724         # If the socialnetworks preference is enabled, enable all social networks
19725         $dbh->do("UPDATE systempreferences SET value = 'email,facebook,linkedin,twitter', explanation = 'email|facebook|linkedin|twitter', type = 'multiple'  WHERE variable = 'SocialNetworks'");
19726     } else {
19727         $dbh->do("UPDATE systempreferences SET value = '', explanation = 'email|facebook|linkedin|twitter', type = 'multiple'  WHERE variable = 'SocialNetworks'");
19728     }
19729     SetVersion ($DBversion);
19730     print "Upgrade to $DBversion done (Bug 22880: Allow granular control of socialnetworks preference)\n";
19731 }
19732
19733 $DBversion = '19.06.00.042';
19734 if( CheckVersion( $DBversion ) ) {
19735     $dbh->do(q{
19736         INSERT IGNORE INTO systempreferences
19737             ( variable, value, options, explanation, type )
19738         VALUES
19739             ('CustomCoverImages','0',NULL,'If enabled, the custom cover images will be displayed in the staff client. CustomCoverImagesURL must be defined.','YesNo'),
19740             ('OPACCustomCoverImages','0',NULL,'If enabled, the custom cover images will be displayed at the OPAC. CustomCoverImagesURL must be defined.','YesNo'),
19741             ('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')
19742     });
19743
19744     SetVersion( $DBversion );
19745     print "Upgrade to $DBversion done (Bug 22445: Add new pref *CustomCoverImages*)\n";
19746 }
19747
19748 $DBversion = '19.06.00.043';
19749 if ( CheckVersion($DBversion) ) {
19750
19751     # Adding account_debit_types
19752     if ( !TableExists('account_debit_types') ) {
19753         $dbh->do(
19754             qq{
19755                 CREATE TABLE account_debit_types (
19756                   code varchar(80) NOT NULL,
19757                   description varchar(200) NULL,
19758                   can_be_added_manually tinyint(4) NOT NULL DEFAULT 1,
19759                   default_amount decimal(28, 6) NULL,
19760                   is_system tinyint(1) NOT NULL DEFAULT 0,
19761                   archived tinyint(1) NOT NULL DEFAULT 0,
19762                   PRIMARY KEY (code)
19763                 ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci
19764               }
19765         );
19766     }
19767
19768     # Adding account_debit_types_branches
19769     if ( !TableExists('account_debit_types_branches') ) {
19770         $dbh->do(
19771             qq{
19772                 CREATE TABLE account_debit_types_branches (
19773                     debit_type_code VARCHAR(80),
19774                     branchcode VARCHAR(10),
19775                     FOREIGN KEY (debit_type_code) REFERENCES account_debit_types(code) ON DELETE CASCADE,
19776                     FOREIGN KEY (branchcode) REFERENCES branches(branchcode) ON DELETE CASCADE
19777                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
19778             }
19779         );
19780     }
19781
19782     # Populating account_debit_types
19783     $dbh->do(
19784         qq{
19785             INSERT IGNORE INTO account_debit_types (
19786               code,
19787               description,
19788               can_be_added_manually,
19789               default_amount,
19790               is_system
19791             )
19792             VALUES
19793               ('ACCOUNT', 'Account creation fee', 0, NULL, 1),
19794               ('ACCOUNT_RENEW', 'Account renewal fee', 0, NULL, 1),
19795               ('RESERVE_EXPIRED', 'Hold waiting too long', 0, NULL, 1),
19796               ('LOST', 'Lost item', 1, NULL, 1),
19797               ('MANUAL', 'Manual fee', 1, NULL, 0),
19798               ('NEW_CARD', 'New card fee', 1, NULL, 1),
19799               ('OVERDUE', 'Overdue fine', 0, NULL, 1),
19800               ('PROCESSING', 'Lost item processing fee', 0, NULL, 1),
19801               ('RENT', 'Rental fee', 0, NULL, 1),
19802               ('RENT_DAILY', 'Daily rental fee', 0, NULL, 1),
19803               ('RENT_RENEW', 'Renewal of rental item', 0, NULL, 1),
19804               ('RENT_DAILY_RENEW', 'Renewal of daily rental item', 0, NULL, 1),
19805               ('RESERVE', 'Hold fee', 0, NULL, 1)
19806         }
19807     );
19808
19809     # Update accountype 'Res' to 'RESERVE'
19810     $dbh->do(
19811         qq{
19812           UPDATE accountlines SET accounttype = 'RESERVE' WHERE accounttype = 'Res'
19813         }
19814     );
19815
19816     # Update accountype 'PF' to 'PROCESSING'
19817     $dbh->do(
19818         qq{
19819           UPDATE accountlines SET accounttype = 'PROCESSING' WHERE accounttype = 'PF'
19820         }
19821     );
19822
19823     # Update accountype 'HE' to 'RESERVE_EXPIRED'
19824     $dbh->do(
19825         qq{
19826           UPDATE accountlines SET accounttype = 'RESERVE_EXPIRED' WHERE accounttype = 'HE'
19827         }
19828     );
19829
19830     # Update accountype 'N' to 'NEW_CARD'
19831     $dbh->do(
19832         qq{
19833           UPDATE accountlines SET accounttype = 'NEW_CARD' WHERE accounttype = 'N'
19834         }
19835     );
19836
19837     # Update accountype 'M' to 'MANUAL'
19838     $dbh->do(
19839         qq{
19840           UPDATE accountlines SET accounttype = 'MANUAL' WHERE accounttype = 'M'
19841         }
19842     );
19843
19844     # Catch 'F' cases introduced since bug 22521
19845     $dbh->do(qq{
19846         UPDATE
19847           accountlines
19848         SET
19849           accounttype = 'OVERDUE',
19850           status = 'RETURNED'
19851         WHERE
19852           accounttype = 'F';
19853     });
19854
19855     # Moving MANUAL_INV to account_debit_types
19856     $dbh->do(
19857         qq{
19858             INSERT IGNORE INTO account_debit_types (
19859               code,
19860               default_amount,
19861               description,
19862               can_be_added_manually,
19863               is_system
19864             )
19865             SELECT
19866               authorised_value,
19867               lib,
19868               authorised_value,
19869               1,
19870               0
19871             FROM
19872               authorised_values
19873             WHERE
19874               category = 'MANUAL_INV'
19875           }
19876     );
19877
19878     # Update uncaught partial accounttypes left behind after bugs 23539 and 22521
19879     my $sth = $dbh->prepare( "SELECT code, SUBSTR(code, 1,5) AS subcode FROM account_debit_types" );
19880     $sth->execute();
19881     while ( my $row = $sth->fetchrow_hashref ) {
19882         $dbh->do(
19883             qq{
19884               UPDATE accountlines SET accounttype = ? WHERE accounttype = ?
19885             },
19886             {},
19887             (
19888                 $row->{code},
19889                 $row->{subcode}
19890             )
19891         );
19892     }
19893
19894     # Add any unexpected accounttype codes to debit_types as appropriate
19895     $dbh->do(
19896         qq{
19897           INSERT IGNORE INTO account_debit_types (
19898             code,
19899             description,
19900             can_be_added_manually,
19901             default_amount,
19902             is_system
19903           )
19904           SELECT
19905             DISTINCT(accounttype),
19906             "Unexpected type found during upgrade",
19907             1,
19908             NULL,
19909             0
19910           FROM
19911             accountlines
19912           WHERE
19913             amount >= 0
19914         }
19915     );
19916
19917     # Adding debit_type_code to accountlines
19918     unless ( column_exists('accountlines', 'debit_type_code') ) {
19919         $dbh->do(
19920             qq{
19921                 ALTER TABLE accountlines
19922                 ADD
19923                   debit_type_code varchar(80) DEFAULT NULL
19924                 AFTER
19925                   accounttype
19926               }
19927         );
19928     }
19929
19930     # Linking debit_type_code in accountlines to code in account_debit_types
19931     unless ( foreign_key_exists( 'accountlines', 'accountlines_ibfk_debit_type' ) ) {
19932         $dbh->do(
19933             qq{
19934             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
19935               }
19936         );
19937     }
19938
19939     # Populating debit_type_code
19940     $dbh->do(
19941         qq{
19942         UPDATE accountlines SET debit_type_code = accounttype, accounttype = NULL WHERE accounttype IN (SELECT code from account_debit_types) AND amount >= 0
19943         }
19944     );
19945
19946     # Remove MANUAL_INV
19947     $dbh->do(
19948         qq{
19949         DELETE FROM authorised_values WHERE category = 'MANUAL_INV'
19950         }
19951     );
19952     $dbh->do(
19953         qq{
19954         DELETE FROM authorised_value_categories WHERE category_name = 'MANUAL_INV'
19955         }
19956     );
19957
19958     # Add new permission
19959     $dbh->do(
19960         q{
19961             INSERT IGNORE INTO permissions (module_bit, code, description)
19962             VALUES
19963               (
19964                 3,
19965                 'manage_accounts',
19966                 'Manage Account Debit and Credit Types'
19967               )
19968         }
19969     );
19970
19971     SetVersion($DBversion);
19972     print "Upgrade to $DBversion done (Bug 23049: Add account debit_types)\n";
19973 }
19974
19975 $DBversion = '19.06.00.044';
19976 if ( CheckVersion($DBversion) ) {
19977
19978     # Adding account_credit_types
19979     if ( !TableExists('account_credit_types') ) {
19980         $dbh->do(
19981             qq{
19982                 CREATE TABLE account_credit_types (
19983                   code varchar(80) NOT NULL,
19984                   description varchar(200) NULL,
19985                   can_be_added_manually tinyint(4) NOT NULL DEFAULT 1,
19986                   is_system tinyint(1) NOT NULL DEFAULT 0,
19987                   PRIMARY KEY (code)
19988                 ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci
19989               }
19990         );
19991     }
19992
19993     # Adding account_credit_types_branches
19994     if ( !TableExists('account_credit_types_branches') ) {
19995         $dbh->do(
19996             qq{
19997                 CREATE TABLE account_credit_types_branches (
19998                     credit_type_code VARCHAR(80),
19999                     branchcode VARCHAR(10),
20000                     FOREIGN KEY (credit_type_code) REFERENCES account_credit_types(code) ON DELETE CASCADE,
20001                     FOREIGN KEY (branchcode) REFERENCES branches(branchcode) ON DELETE CASCADE
20002                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
20003             }
20004         );
20005     }
20006
20007     # Populating account_credit_types
20008     $dbh->do(
20009         qq{
20010             INSERT IGNORE INTO account_credit_types (
20011               code,
20012               description,
20013               can_be_added_manually,
20014               is_system
20015             )
20016             VALUES
20017               ('PAYMENT', 'Payment', 0, 1),
20018               ('WRITEOFF', 'Writeoff', 0, 1),
20019               ('FORGIVEN', 'Forgiven', 1, 1),
20020               ('CREDIT', 'Credit', 1, 1),
20021               ('LOST_RETURN', 'Lost item fee refund', 0, 1)
20022         }
20023     );
20024
20025     # Catch LOST_RETURNED cases from original bug 22563 update
20026     $dbh->do(
20027         qq{
20028             UPDATE accountlines
20029             SET accounttype = 'LOST_RETURN'
20030             WHERE accounttype = 'LOST_RETURNED'
20031     });
20032
20033     # Adding credit_type_code to accountlines
20034     unless ( column_exists('accountlines', 'credit_type_code') ) {
20035         $dbh->do(
20036             qq{
20037                 ALTER TABLE accountlines
20038                 ADD
20039                   credit_type_code varchar(80) DEFAULT NULL
20040                 AFTER
20041                   accounttype
20042               }
20043         );
20044     }
20045
20046     # Linking credit_type_code in accountlines to code in account_credit_types
20047     unless ( foreign_key_exists( 'accountlines', 'accountlines_ibfk_credit_type' ) ) {
20048         $dbh->do(
20049             qq{
20050                 ALTER TABLE accountlines
20051                 ADD CONSTRAINT
20052                   `accountlines_ibfk_credit_type`
20053                 FOREIGN KEY (`credit_type_code`) REFERENCES `account_credit_types` (`code`)
20054                 ON DELETE RESTRICT
20055                 ON UPDATE CASCADE
20056               }
20057         );
20058     }
20059
20060     # Update accountype 'C' to 'CREDIT'
20061     $dbh->do(
20062         qq{
20063           UPDATE accountlines SET accounttype = 'CREDIT' WHERE accounttype = 'C' OR accounttype = 'CR'
20064         }
20065     );
20066
20067     # Update accountype 'FOR' to 'FORGIVEN'
20068     $dbh->do(
20069         qq{
20070           UPDATE accountlines SET accounttype = 'FORGIVEN' WHERE accounttype = 'FOR' OR accounttype = 'FORW'
20071         }
20072     );
20073
20074     # Update accountype 'Pay' to 'PAYMENT'
20075     $dbh->do(
20076         qq{
20077           UPDATE accountlines SET accounttype = 'PAYMENT' WHERE accounttype = 'Pay' OR accounttype = 'PAY'
20078         }
20079     );
20080
20081     # Update accountype 'W' to 'WRITEOFF'
20082     $dbh->do(
20083         qq{
20084           UPDATE accountlines SET accounttype = 'WRITEOFF' WHERE accounttype = 'W' OR accounttype = 'WO'
20085         }
20086     );
20087
20088     # Add any unexpected accounttype codes to credit_types as appropriate
20089     $dbh->do(
20090         qq{
20091           INSERT IGNORE INTO account_credit_types (
20092             code,
20093             description,
20094             can_be_added_manually,
20095             is_system
20096           )
20097           SELECT
20098             DISTINCT(accounttype),
20099             "Unexpected type found during upgrade",
20100             1,
20101             0
20102           FROM
20103             accountlines
20104           WHERE
20105             amount < 0
20106         }
20107     );
20108
20109     # Populating credit_type_code
20110     $dbh->do(
20111         qq{
20112           UPDATE
20113             accountlines 
20114           SET
20115             credit_type_code = accounttype, accounttype = NULL
20116           WHERE accounttype IN (SELECT code from account_credit_types)
20117         }
20118     );
20119
20120     # Drop accounttype field
20121     $dbh->do(
20122         qq{
20123           ALTER TABLE accountlines
20124           DROP COLUMN `accounttype`
20125         }
20126     );
20127
20128     SetVersion($DBversion);
20129     print "Upgrade to $DBversion done (Bug 23805: Add account credit_types)\n";
20130 }
20131
20132 $DBversion = '19.06.00.045';
20133 if( CheckVersion( $DBversion ) ) {
20134     $dbh->do( "UPDATE systempreferences SET value = '2' WHERE value = '0' AND variable = 'UsageStats'" );
20135
20136     SetVersion( $DBversion );
20137     print "Upgrade to $DBversion done (Bug 23866: Set HEA syspref to prompt for review)\n";
20138 }
20139
20140 $DBversion = '19.06.00.046';
20141 if( CheckVersion( $DBversion ) ) {
20142     $dbh->do(qq{
20143         UPDATE systempreferences
20144         SET 
20145           options = "Calendar|Days|Datedue|Dayweek", 
20146           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"
20147         WHERE
20148           variable = "useDaysMode"
20149     });
20150
20151     # Always end with this (adjust the bug info)
20152     SetVersion( $DBversion );
20153     print "Upgrade to $DBversion done (Bug 15260: Option for extended loan with useDaysMode)\n";
20154 }
20155
20156 $DBversion = '19.06.00.047';
20157 if ( CheckVersion($DBversion) ) {
20158     if ( !TableExists('return_claims') ) {
20159         $dbh->do(
20160             q{
20161             CREATE TABLE return_claims (
20162                 id int(11) auto_increment,                             -- Unique ID of the return claim
20163                 itemnumber int(11) NOT NULL,                           -- ID of the item
20164                 issue_id int(11) NULL DEFAULT NULL,                    -- ID of the checkout that triggered the claim
20165                 borrowernumber int(11) NOT NULL,                       -- ID of the patron
20166                 notes MEDIUMTEXT DEFAULT NULL,                         -- Notes about the claim
20167                 created_on TIMESTAMP NULL,                             -- Time and date the claim was created
20168                 created_by int(11) NULL DEFAULT NULL,                  -- ID of the staff member that registered the claim
20169                 updated_on TIMESTAMP NULL ON UPDATE CURRENT_TIMESTAMP, -- Time and date of the latest change on the claim (notes)
20170                 updated_by int(11) NULL DEFAULT NULL,                  -- ID of the staff member that updated the claim
20171                 resolution  varchar(80) NULL DEFAULT NULL,             -- Resolution code (RETURN_CLAIM_RESOLUTION AVs)
20172                 resolved_on TIMESTAMP NULL DEFAULT NULL,               -- Time and date the claim was resolved
20173                 resolved_by int(11) NULL DEFAULT NULL,                 -- ID of the staff member that resolved the claim
20174                 PRIMARY KEY (`id`),
20175                 KEY `itemnumber` (`itemnumber`),
20176                 CONSTRAINT UNIQUE `issue_id` ( issue_id ),
20177                 CONSTRAINT `issue_id` FOREIGN KEY (`issue_id`) REFERENCES `issues` (`issue_id`) ON DELETE SET NULL ON UPDATE CASCADE,
20178                 CONSTRAINT `rc_items_ibfk` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
20179                 CONSTRAINT `rc_borrowers_ibfk` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
20180                 CONSTRAINT `rc_created_by_ibfk` FOREIGN KEY (`created_by`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE,
20181                 CONSTRAINT `rc_updated_by_ibfk` FOREIGN KEY (`updated_by`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE,
20182                 CONSTRAINT `rc_resolved_by_ibfk` FOREIGN KEY (`resolved_by`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE
20183             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
20184         }
20185         );
20186     }
20187
20188     $dbh->do(
20189         q{
20190         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
20191         ('ClaimReturnedChargeFee', 'ask', 'ask|charge|no_charge', 'Controls whether or not a lost item fee is charged for return claims', 'Choice'),
20192         ('ClaimReturnedLostValue', '', '', 'Sets the LOST AV value that represents "Claims returned" as a lost value', 'Free'),
20193         ('ClaimReturnedWarningThreshold', '', '', 'Sets the number of return claims past which the librarian will be warned the patron has many return claims', 'Integer');
20194     }
20195     );
20196
20197     $dbh->do(
20198         q{
20199         INSERT IGNORE INTO authorised_value_categories ( category_name ) VALUES
20200             ('RETURN_CLAIM_RESOLUTION');
20201     }
20202     );
20203
20204     $dbh->do(
20205         q{
20206         INSERT IGNORE INTO `authorised_values` ( category, authorised_value, lib )
20207         VALUES
20208           ('RETURN_CLAIM_RESOLUTION', 'RET_BY_PATRON', 'Returned by patron'),
20209           ('RETURN_CLAIM_RESOLUTION', 'FOUND_IN_LIB', 'Found in library');
20210     }
20211     );
20212
20213     SetVersion($DBversion);
20214     print
20215 "Upgrade to $DBversion done (Bug 14697: Extend and enhance 'Claims returned' lost status)\n";
20216 }
20217
20218 $DBversion = '19.06.00.048';
20219 if( CheckVersion( $DBversion ) ) {
20220     # you can use $dbh here like:
20221     $dbh->do( qq{
20222         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
20223         VALUES  ('OPACShowMusicalInscripts','0','','Display musical inscripts on the OPAC record details page when available.','YesNo'),
20224                 ('OPACPlayMusicalInscripts','0','','If displayed musical inscripts, play midi conversion on the OPAC record details page.','YesNo')
20225     } );
20226
20227     SetVersion( $DBversion );
20228     print "Upgrade to $DBversion done (Bug 22581: add new OPACShowMusicalInscripts and OPACPlayMusicalInscripts system preferences)\n";
20229 }
20230
20231 $DBversion = '19.06.00.049';
20232 if( CheckVersion( $DBversion ) ) {
20233
20234     $dbh->do(q{
20235         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
20236         SELECT
20237             'SuspensionsCalendar',
20238             IF( value='noFinesWhenClosed', 'noSuspensionsWhenClosed', 'ignoreCalendar'),
20239             'ignoreCalendar|noSuspensionsWhenClosed',
20240             'Specify whether to use the Calendar in calculating suspensions',
20241             'Choice'
20242         FROM systempreferences
20243         WHERE variable='finesCalendar';
20244     });
20245
20246     SetVersion( $DBversion );
20247     print "Upgrade to $DBversion done (Bug 13958: Add a SuspensionsCalendar syspref)\n";
20248 }
20249
20250 $DBversion = '19.06.00.050';
20251 if( CheckVersion( $DBversion ) ) {
20252     $dbh->do( q{
20253             INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
20254             VALUES ('OPACFineNoRenewalsIncludeCredits','1',NULL,'If enabled the value specified in OPACFineNoRenewals should include any unapplied account credits in the calculation','YesNo')
20255     });
20256
20257     SetVersion( $DBversion );
20258     print "Upgrade to $DBversion done (Bug 23293: Add 'OPACFineNoRenewalsIncludeCredits' system preference)\n";
20259 }
20260
20261 $DBversion = '19.11.00.000';
20262 if( CheckVersion( $DBversion ) ) {
20263     SetVersion( $DBversion );
20264     print "Upgrade to $DBversion done (19.11.00 release)\n";
20265 }
20266
20267 $DBversion = '19.11.00.001';
20268 if( CheckVersion( $DBversion ) ) {
20269     $dbh->do( "UPDATE marc_subfield_structure SET kohafield = NULL WHERE kohafield = 'bibliosubject.subject';" );
20270     SetVersion( $DBversion );
20271     print "Upgrade to $DBversion done (Bug 17831 - Remove non-existing bibliosubject.subject from frameworks)\n";
20272 }
20273
20274 $DBversion = "19.11.01.000";
20275 if ( CheckVersion($DBversion) ) {
20276     print "Upgrade to $DBversion done (19.11.01 release)\n";
20277     SetVersion ($DBversion);
20278 }
20279
20280 $DBversion = '19.11.01.001';
20281 if( CheckVersion( $DBversion ) ) {
20282     $dbh->do("UPDATE systempreferences SET variable = 'AllowItemsOnHoldCheckoutSIP', 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.' WHERE variable = 'AllowItemsOnHoldCheckout';" );
20283     SetVersion( $DBversion );
20284     print "Upgrade to $DBversion done (Bug 23233 - Rename AllowItemsOnHoldCheckout syspref)\n";
20285 }
20286
20287 $DBversion = '19.11.01.002';
20288 if( CheckVersion( $DBversion ) ) {
20289     $dbh->do( "ALTER TABLE action_logs MODIFY COLUMN `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP" );
20290     SetVersion( $DBversion );
20291     print "Upgrade to $DBversion done (Bug 24329 - Do not update action_log.timestamp)\n";
20292 }
20293
20294 $DBversion = '19.11.01.003';
20295 if( CheckVersion( $DBversion ) ) {
20296     $dbh->do( q|UPDATE borrowers SET relationship = NULL WHERE relationship = ""|);
20297     SetVersion( $DBversion );
20298     print "Upgrade to $DBversion done (Bug 24215 - Replace relationship with NULL when empty string)\n";
20299 }
20300
20301 $DBversion = "19.11.02.000";
20302 if ( CheckVersion($DBversion) ) {
20303     print "Upgrade to $DBversion done (19.11.02 release)\n";
20304     SetVersion ($DBversion);
20305 }
20306
20307 $DBversion = '19.11.02.001';
20308 if( CheckVersion( $DBversion ) ) {
20309     $dbh->do( 'UPDATE systempreferences SET value = REPLACE(value, "http://worldcat.org", "https://worldcat.org") WHERE variable = "OPACSearchForTitleIn"' );
20310     $dbh->do( 'UPDATE systempreferences SET value = REPLACE(value, "http://www.bookfinder.com", "https://www.bookfinder.com") WHERE variable = "OPACSearchForTitleIn"' );
20311     $dbh->do( 'UPDATE systempreferences SET value = REPLACE(value, "https://openlibrary.org/search/?", "https://openlibrary.org/search?") WHERE variable = "OPACSearchForTitleIn"' );
20312     SetVersion( $DBversion );
20313     print "Upgrade to $DBversion done (Bug 24206 - Update OpacSearchForTitleIn system preference)\n";
20314 }
20315
20316 $DBversion = '19.11.02.002';
20317 if( CheckVersion( $DBversion ) ) {
20318     my $exists;
20319     eval { $exists = $dbh->do("SELECT 1 FROM authorised_values WHERE category = 'PAYMENT_TYPE' AND authorised_value = 'CASH'"); };
20320     if ( $exists == 0 ) {
20321        $dbh->do(qq{
20322            INSERT INTO
20323              authorised_values (category,authorised_value,lib, lib_opac)
20324            VALUES
20325              ('PAYMENT_TYPE','CASH','Cash','Cash')
20326        });
20327     }
20328     SetVersion( $DBversion );
20329     print "Upgrade to $DBversion done (Bug 24338 - Add 'CASH' to default 'PAYMENT_TYPE')\n";
20330 }
20331
20332 $DBversion = '19.11.02.003';
20333 if( CheckVersion( $DBversion ) ) {
20334     if( !foreign_key_exists( 'repeatable_holidays', 'repeatable_holidays_ibfk_1' ) ) {
20335        $dbh->do(q|
20336            DELETE h
20337            FROM repeatable_holidays h
20338            LEFT JOIN branches b ON h.branchcode=b.branchcode
20339            WHERE b.branchcode IS NULL;
20340        |);
20341        $dbh->do(q|
20342            ALTER TABLE repeatable_holidays
20343            ADD FOREIGN KEY repeatable_holidays_ibfk_1 (branchcode) REFERENCES branches (branchcode) ON DELETE CASCADE ON UPDATE CASCADE
20344        |);
20345     }
20346
20347     if( !foreign_key_exists( 'special_holidays', 'special_holidays_ibfk_1' ) ) {
20348        $dbh->do(q|
20349            DELETE h
20350            FROM special_holidays h
20351            LEFT JOIN branches b ON h.branchcode=b.branchcode
20352            WHERE b.branchcode IS NULL;
20353        |);
20354        $dbh->do(q|
20355            ALTER TABLE special_holidays
20356            ADD FOREIGN KEY special_holidays_ibfk_1 (branchcode) REFERENCES branches (branchcode) ON DELETE CASCADE ON UPDATE CASCADE
20357        |);
20358     }
20359
20360     SetVersion( $DBversion );
20361     print "Upgrade to $DBversion done (Bug 24289 - Adding foreign keys on *_holidays.branchcode tables)\n";
20362 }
20363
20364 $DBversion = '19.11.02.004';
20365 if( CheckVersion( $DBversion ) ) {
20366     $dbh->do(q{
20367         INSERT IGNORE INTO `userflags` (`bit`, `flag`, `flagdesc`, `defaulton`)
20368         VALUES (12, 'suggestions', 'Suggestion management', 0)
20369     });
20370
20371     $dbh->do(q{
20372         UPDATE permissions SET module_bit=12
20373         WHERE code="suggestions_manage"
20374     });
20375
20376     $dbh->do(q{
20377         UPDATE borrowers SET flags = flags | (1<<12) WHERE flags & (1 << 11)
20378     });
20379
20380     SetVersion( $DBversion );
20381     print "Upgrade to $DBversion done (Bug 22868 - Move suggestions_manage subpermission out of acquisition permission)\n";
20382 }
20383
20384 $DBversion = "19.11.03.000";
20385 if ( CheckVersion($DBversion) ) {
20386     print "Upgrade to $DBversion done (19.11.03 release)\n";
20387     SetVersion ($DBversion);
20388 }
20389
20390 $DBversion = '19.11.03.001';
20391 if( CheckVersion( $DBversion ) ) {
20392     $dbh->do( "ALTER TABLE items MODIFY COLUMN uri MEDIUMTEXT" );
20393     $dbh->do( "ALTER TABLE deleteditems MODIFY COLUMN uri MEDIUMTEXT" );
20394
20395     SetVersion( $DBversion );
20396     print "Upgrade to $DBversion done (Bug 20882 - items.uri to MEDIUMTEXT)\n";
20397 }
20398
20399 $DBversion = '19.11.03.002';
20400 if( CheckVersion( $DBversion ) ) {
20401     $dbh->do( "ALTER TABLE quotes MODIFY timestamp datetime NULL" );
20402
20403     SetVersion( $DBversion );
20404     print "Upgrade to $DBversion done (Bug 24640 - Allow quotes.timestamp to be NULL)\n";
20405 }
20406
20407 $DBversion = '19.11.03.003';
20408 if( CheckVersion( $DBversion ) ) {
20409     $dbh->do(q{
20410         UPDATE systempreferences SET value = 'off'
20411         WHERE variable = 'finesMode' AND (value <> 'production' OR value IS NULL)
20412     });
20413     $dbh->do(q{
20414         UPDATE systempreferences SET options = 'off|production',
20415         explanation = "Choose the fines mode, 'off' (do not accrue fines) or 'production' (accrue overdue fines).  Requires accruefines cronjob or CalculateFinesOnReturn system preference."
20416         WHERE variable = 'finesMode'
20417     });
20418     SetVersion( $DBversion );
20419     print "Upgrade to $DBversion done (Bug 21633  - Remove finesMode 'test')\n";
20420 }
20421
20422 $DBversion = '19.11.03.004';
20423 if( CheckVersion( $DBversion ) ) {
20424
20425     # Add any pathalogical incorrect debit_types as credit_types as appropriate
20426     $dbh->do(
20427         qq{
20428           INSERT IGNORE INTO account_credit_types (
20429             code,
20430             description,
20431             can_be_added_manually,
20432             is_system
20433           )
20434           SELECT
20435             DISTINCT(debit_type_code),
20436             "Unexpected type found during upgrade",
20437             1,
20438             0
20439           FROM
20440             accountlines
20441           WHERE
20442             amount < 0
20443           AND
20444             debit_type_code IS NOT NULL
20445         }
20446     );
20447
20448     # Correct any pathalogical cases
20449     $dbh->do( qq{
20450       UPDATE
20451          accountlines
20452       SET
20453          credit_type_code = debit_type_code,
20454          debit_type_code = NULL
20455       WHERE
20456          amount < 0
20457       AND
20458          debit_type_code IS NOT NULL
20459     });
20460
20461     # Always end with this (adjust the bug info)
20462     SetVersion( $DBversion );
20463     print "Upgrade to $DBversion done (Bug 24532 - Fix misidentified credit_types from bug 23049 )\n";
20464 }
20465
20466
20467 $DBversion = '19.11.03.005';
20468 if( CheckVersion( $DBversion ) ) {
20469     $dbh->do(qq{
20470        INSERT IGNORE permissions (module_bit, code, description)
20471        VALUES
20472           (13, 'batch_extend_due_dates', 'Perform batch extend due dates')
20473     });
20474
20475     SetVersion($DBversion);
20476     print "Upgrade to $DBversion done (Bug 24846 - Add a new permission for new tool batch extend due dates)\n";
20477 }
20478
20479 $DBversion = "19.11.04.000";
20480 if ( CheckVersion($DBversion) ) {
20481     print "Upgrade to $DBversion done (19.11.04 release)\n";
20482     SetVersion ($DBversion);
20483 }
20484
20485 $DBversion = '19.11.04.001';
20486 if( CheckVersion( $DBversion ) ) {
20487     $dbh->do(q{
20488         INSERT IGNORE INTO `systempreferences` (variable,value,options,explanation,type)
20489         VALUES ('DumpSearchQueryTemplate',0,'','Add the search query being passed to the search engine into the template for debugging','YesNo')
20490     });
20491     SetVersion( $DBversion );
20492     print "Upgrade to $DBversion done (Bug 24103 - add DumpSearchQueryTemplate syspref)\n";
20493 }
20494
20495 $DBversion = '19.11.04.002';
20496 if( CheckVersion( $DBversion ) ) {
20497     $dbh->do( q|
20498         ALTER TABLE article_requests MODIFY COLUMN created_on timestamp NULL, MODIFY COLUMN updated_on timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
20499     |);
20500     SetVersion( $DBversion );
20501     print "Upgrade to $DBversion done (Bug 22273: Column article_requests.created_on should not be updated)\n";
20502 }
20503
20504 $DBversion = "19.11.05.000";
20505 if ( CheckVersion($DBversion) ) {
20506     print "Upgrade to $DBversion done (19.11.05 release)\n";
20507     SetVersion ($DBversion);
20508 }
20509
20510 $DBversion = '19.11.05.001';
20511 if( CheckVersion( $DBversion ) ) {
20512     $dbh->do( "UPDATE account_debit_types SET description = REPLACE(description,'Rewewal','Renewal') WHERE description like '%Rewewal%'" );
20513     SetVersion( $DBversion );
20514     print "Upgrade to $DBversion done (Bug 25010: Fix typo in account_debit_type description)\n";
20515 }
20516
20517 $DBversion = '19.11.05.002';
20518 if( CheckVersion( $DBversion ) ) {
20519     # From: https://stackoverflow.com/questions/3311903/remove-duplicate-rows-in-mysql
20520     $dbh->do(q|
20521             DELETE a
20522             FROM virtualshelfshares as a, virtualshelfshares as b
20523             WHERE a.id < b.id AND a.borrowernumber IS NOT NULL AND a.borrowernumber=b.borrowernumber AND a.shelfnumber=b.shelfnumber
20524              |);
20525     SetVersion( $DBversion );
20526     print "Upgrade to $DBversion done (Bug 20754: Remove double accepted list shares)\n";
20527 }
20528
20529 $DBversion = '19.11.05.003';
20530 if( CheckVersion( $DBversion ) ) {
20531     $dbh->do( "ALTER TABLE borrower_modifications MODIFY changed_fields MEDIUMTEXT DEFAULT NULL" );
20532     SetVersion( $DBversion );
20533     print "Upgrade to $DBversion done (Bug 25086: Set changed_fields column of borrower_modifications as nullable)\n";
20534 }
20535
20536 $DBversion = '19.11.05.004';
20537 if( CheckVersion( $DBversion ) ) {
20538     $dbh->do( "UPDATE items set issues=0 where issues is null" );
20539     $dbh->do( "UPDATE deleteditems set issues=0 where issues is null" );
20540     $dbh->do( "ALTER TABLE items ALTER issues set default 0" );
20541     $dbh->do( "ALTER TABLE deleteditems ALTER issues set default 0" );
20542     SetVersion( $DBversion );
20543     print "Upgrade to $DBversion done (Bug 23081: Set default to 0 for items.issues)\n";
20544 }
20545
20546 $DBversion = '19.11.05.005';
20547 if( CheckVersion( $DBversion ) ) {
20548     $dbh->do(q{
20549             INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
20550             ('TrapHoldsOnOrder','1',NULL,'If enabled, Koha will trap holds for on order items ( notforloan < 0 )','YesNo')
20551              });
20552     SetVersion( $DBversion );
20553     print "Upgrade to $DBversion done (Bug 25184: Items with a negative notforloan status should not be captured for holds)\n";
20554 }
20555
20556 $DBversion = '19.11.05.006';
20557 if( CheckVersion( $DBversion ) ) {
20558     # Migrate LOST_RETURNED to LOST_RETURN
20559     $dbh->do(qq{
20560             UPDATE
20561             accountlines
20562             SET
20563             credit_type_code = 'LOST_RETURN'
20564             WHERE
20565             credit_type_code = 'LOST_RETURNED'
20566             });
20567
20568     # Drop LOST_RETURNED credit type
20569     $dbh->do(qq{
20570             DELETE FROM account_credit_types WHERE code = 'LOST_RETURNED'
20571             });
20572     SetVersion( $DBversion );
20573     print "Upgrade to $DBversion done (Bug 25389: Catch errant cases of LOST_RETURNED)\n";
20574 }
20575
20576 $DBversion = '19.11.05.007';
20577 if( CheckVersion( $DBversion ) ) {
20578     my $ft_enabled = $dbh->selectrow_array(q|
20579         SELECT COUNT(*) FROM systempreferences WHERE variable like "IDreamBooks%" and value="1"
20580     |);
20581     if ( $ft_enabled ) {
20582         $dbh->do(q|
20583             UPDATE systempreferences
20584             SET value="0"
20585             WHERE variable like "IDreamBooks%"
20586         |);
20587     }
20588
20589     SetVersion( $DBversion );
20590     print "Upgrade to $DBversion done (Bug 24854 - Disable IDreamBooks)\n";
20591 }
20592
20593 $DBversion = "19.11.06.000";
20594 if ( CheckVersion($DBversion) ) {
20595     print "Upgrade to $DBversion done (19.11.06 release)\n";
20596     SetVersion ($DBversion);
20597 }
20598
20599 $DBversion = '19.11.06.001';
20600 if( CheckVersion( $DBversion ) ) {
20601
20602     # Default to the homologous OpacPublic syspref
20603     my $opac_public = C4::Context->preference('OpacPublic') ? 1 : 0;
20604
20605     $dbh->do(qq{
20606         INSERT IGNORE INTO `systempreferences`
20607             (`variable`,`value`,`explanation`,`options`,`type`)
20608         VALUES
20609             ('RESTPublicAnonymousRequests', $opac_public, NULL,"If enabled, the API will allow anonymous access to public routes that don\'t require authenticated access.",'YesNo');
20610     });
20611
20612     SetVersion ($DBversion);
20613     print "Upgrade to $DBversion done ( Bug 25045 - Add a way to restrict anonymous access to public routes (OpacPublic behaviour) )\n";
20614 }
20615
20616 $DBversion = "19.11.07.000";
20617 if ( CheckVersion($DBversion) ) {
20618     print "Upgrade to $DBversion done (19.11.07 release)\n";
20619     SetVersion ($DBversion);
20620 }
20621
20622 $DBversion = '19.11.07.001';
20623 if( CheckVersion( $DBversion ) ) {
20624
20625     for my $f (qw( streetnumber streettype zipcode mobile B_streetnumber B_streettype B_zipcode ) ) {
20626         $dbh->do(qq|
20627             ALTER TABLE borrowers MODIFY $f TINYTEXT DEFAULT NULL
20628         |);
20629         $dbh->do(qq|
20630             ALTER TABLE deletedborrowers MODIFY $f TINYTEXT DEFAULT NULL
20631         |);
20632     }
20633     for my $f ( qw( B_address altcontactfirstname altcontactsurname altcontactaddress1 altcontactaddress2 altcontactaddress3 altcontactzipcode altcontactphone ) ) {
20634         $dbh->do(qq|
20635             ALTER TABLE borrowers MODIFY $f MEDIUMTEXT DEFAULT NULL
20636         |);
20637         $dbh->do(qq|
20638             ALTER TABLE deletedborrowers MODIFY $f MEDIUMTEXT DEFAULT NULL
20639         |);
20640     }
20641
20642     SetVersion( $DBversion );
20643     print "Upgrade to $DBversion done (Bug 24986 - Switch borrowers address related fields to TINYTEXT or MEDIUMTEXT)\n";
20644 }
20645
20646 $DBversion = "19.11.08.000";
20647 if ( CheckVersion($DBversion) ) {
20648     print "Upgrade to $DBversion done (19.11.08 release)\n";
20649     SetVersion ($DBversion);
20650 }
20651
20652 $DBversion = "19.11.08.001";
20653 if( CheckVersion( $DBversion ) ) {
20654     $dbh->do( "UPDATE systempreferences SET variable='NotesToHide' WHERE variable = 'NotesBlacklist'" );
20655     print "Upgrade to $DBversion done (Bug 25709 - Rename systempreference to NotesToHide)\n";
20656     SetVersion( $DBversion );
20657 }
20658
20659 $DBversion = "19.11.08.002";
20660 if( CheckVersion( $DBversion ) ) {
20661     $dbh->do( "UPDATE borrowers SET login_attempts=0 WHERE login_attempts IS NULL" );
20662     $dbh->do( "ALTER TABLE borrowers MODIFY COLUMN login_attempts int(4) NOT NULL DEFAULT 0" );
20663     $dbh->do( "UPDATE deletedborrowers SET login_attempts=0 WHERE login_attempts IS NULL" );
20664     $dbh->do( "ALTER TABLE deletedborrowers MODIFY COLUMN login_attempts int(4) NOT NULL DEFAULT 0" );
20665     print "Upgrade to $DBversion done (Bug 24379 - Set login_attempts NOT NULL)\n";
20666     SetVersion( $DBversion );
20667 }
20668
20669 $DBversion = "19.11.08.003";
20670 if( CheckVersion( $DBversion ) ) {
20671     $dbh->do("DELETE FROM systempreferences WHERE variable = 'GoogleIndicTransliteration'");
20672     print "Upgrade to $DBversion done (Bug 26070 - Remove references to deprecated Google Transliterate API)\n";
20673     SetVersion( $DBversion );
20674 }
20675
20676 $DBversion = "19.11.09.000";
20677 if ( CheckVersion($DBversion) ) {
20678     print "Upgrade to $DBversion done (19.11.09 release)\n";
20679     SetVersion ($DBversion);
20680 }
20681
20682 $DBversion = "19.11.09.001";
20683 if( CheckVersion( $DBversion ) ) {
20684     $dbh->do(q{
20685         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
20686         ('DefaultLongOverdueSkipLostStatuses', '', NULL, 'Skip these lost statuses by default in longoverdue.pl', 'Free')
20687     });
20688
20689     print "Upgrade to $DBversion done (Bug 25958 - Allow LongOverdue cron to exclude specified lost values)\n";
20690     SetVersion( $DBversion );
20691 }
20692
20693 $DBversion = "19.11.10.000";
20694 if ( CheckVersion( $DBversion ) ) {
20695     print "Upgrade to $DBversion done (19.11.10 release)\n";
20696     SetVersion( $DBversion );
20697 }
20698
20699 $DBversion = "19.11.10.001";
20700 if( CheckVersion( $DBversion ) ) {
20701
20702     if( !column_exists( 'hold_fill_targets', 'reserve_id' ) ) {
20703         $dbh->do( "ALTER TABLE hold_fill_targets ADD COLUMN reserve_id int(11) DEFAULT NULL AFTER item_level_request" );
20704     }
20705
20706     print "Upgrade to $DBversion done (Bug 18958 - Add reserve_id to hold_fill_targets)\n";
20707     SetVersion( $DBversion );
20708 }
20709
20710 $DBversion = "19.11.11.000";
20711 if ( CheckVersion( $DBversion ) ) {
20712     print "Upgrade to $DBversion done (19.11.11 release)\n";
20713     SetVersion( $DBversion );
20714 }
20715
20716 $DBversion = '19.11.11.001';
20717 if( CheckVersion( $DBversion ) ) {
20718     $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'" );
20719     $dbh->do( "UPDATE systempreferences SET explanation='If enabled, the patron can set checkouts to be visible to their guarantor' WHERE variable='AllowPatronToSetCheckoutsVisibilityForGuarantor'" );
20720     $dbh->do( "UPDATE systempreferences SET explanation='If enabled, the patron can set fines to be visible to their guarantor' WHERE variable='AllowPatronToSetFinesVisibilityForGuarantor'" );
20721     $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'" );
20722     $dbh->do( "UPDATE systempreferences SET explanation='If ON, the next user will automatically get the last searches in their history' WHERE variable='LoadSearchHistoryToTheFirstLoggedUser'" );
20723     $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'" );
20724
20725     print "Upgrade to $DBversion done (Bug 26569 - Use gender neutral pronouns in system preference explanations)\n";
20726     SetVersion( $DBversion );
20727 }
20728
20729 $DBversion = '19.11.11.002';
20730 if( CheckVersion( $DBversion ) ) {
20731     my $count_missing_budget = $dbh->selectrow_arrayref(q|
20732         SELECT COUNT(*) FROM aqbudgets ab WHERE NOT EXISTS
20733             (SELECT * FROM aqbudgetperiods abp WHERE abp.budget_period_id = ab.budget_period_id)
20734             AND budget_period_id IS NOT NULL;
20735
20736     |);
20737
20738     my $message = "";
20739     if($count_missing_budget->[0] > 0) {
20740         $dbh->do(q|
20741             CREATE TABLE _bug_18050_aqbudgets AS
20742             SELECT * FROM aqbudgets ab WHERE NOT EXISTS
20743                 (SELECT * FROM aqbudgetperiods abp WHERE abp.budget_period_id = ab.budget_period_id)
20744         |);
20745
20746         $dbh->do(q|
20747             UPDATE aqbudgets ab SET budget_period_id = NULL
20748             WHERE NOT EXISTS
20749                 (SELECT * FROM aqbudgetperiods abp WHERE abp.budget_period_id = ab.budget_period_id)
20750         |);
20751         $message = ". There are $count_missing_budget->[0] funds in your database that are not linked
20752         to a valid budget. Setting invalid budget id (budget_period_id) to null. The table _bug_18050_aqbudgets
20753         was created with original data. Please check that table and place valid ids in aqbudget table as soon as possible."
20754
20755     }
20756
20757     if ( !foreign_key_exists( 'aqbudgets', 'aqbudgetperiods_ibfk_1' ) ) {
20758         $dbh->do(q|
20759             ALTER TABLE aqbudgets ADD CONSTRAINT `aqbudgetperiods_ibfk_1` FOREIGN KEY (`budget_period_id`) REFERENCES `aqbudgetperiods` (`budget_period_id`) ON UPDATE CASCADE ON DELETE CASCADE
20760         |);
20761         print "Upgrade to $DBversion done (Bug 18050 - Add FK constraint on aqbudgets.budget_period_id$message)\n";
20762         SetVersion( $DBversion );
20763     } else {
20764         print "Upgrade to $DBversion done (Bug 18050 - FK constraint on aqbudgets.budget already exists)\n";
20765         SetVersion( $DBversion );
20766     }
20767 }
20768
20769 $DBversion = "19.11.12.000";
20770 if ( CheckVersion( $DBversion ) ) {
20771     print "Upgrade to $DBversion done (19.11.12 release)\n";
20772     SetVersion( $DBversion );
20773 }
20774
20775 $DBversion = "19.11.13.000";
20776 if ( CheckVersion( $DBversion ) ) {
20777     print "Upgrade to $DBversion done (19.11.13 release)\n";
20778     SetVersion( $DBversion );
20779 }
20780
20781 $DBversion = '19.11.13.001';
20782 if( CheckVersion( $DBversion ) ) {
20783     $dbh->do(q{
20784         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
20785        ('ElasticsearchCrossFields', '0', '', 'Enable "cross_fields" option for searches using Elastic search.', 'YesNo')
20786     });
20787     print "Upgrade to $DBversion done (Bug 27252 - Add ElasticsearchCrossFields system preference)\n";
20788     SetVersion( $DBversion );
20789 }
20790
20791 $DBversion = "19.11.14.000";
20792 if ( CheckVersion( $DBversion ) ) {
20793     print "Upgrade to $DBversion done (19.11.14 release)\n";
20794     SetVersion( $DBversion );
20795 }
20796
20797 $DBversion = "19.11.15.000";
20798 if ( CheckVersion( $DBversion ) ) {
20799     print "Upgrade to $DBversion done (19.11.15 release)\n";
20800     SetVersion( $DBversion );
20801 }
20802
20803 # SEE bug 13068
20804 # if there is anything in the atomicupdate, read and execute it.
20805 my $update_dir = C4::Context->config('intranetdir') . '/installer/data/mysql/atomicupdate/';
20806 opendir( my $dirh, $update_dir );
20807 foreach my $file ( sort readdir $dirh ) {
20808     next if $file !~ /\.(sql|perl)$/;  #skip other files
20809     next if $file eq 'skeleton.perl'; # skip the skeleton file
20810     print "DEV atomic update: $file\n";
20811     if ( $file =~ /\.sql$/ ) {
20812         my $installer = C4::Installer->new();
20813         my $rv = $installer->load_sql( $update_dir . $file ) ? 0 : 1;
20814     } elsif ( $file =~ /\.perl$/ ) {
20815         my $code = read_file( $update_dir . $file );
20816         eval $code;
20817         say "Atomic update generated errors: $@" if $@;
20818     }
20819 }
20820
20821 =head1 FUNCTIONS
20822
20823 =head2 DropAllForeignKeys($table)
20824
20825 Drop all foreign keys of the table $table
20826
20827 =cut
20828
20829 sub DropAllForeignKeys {
20830     my ($table) = @_;
20831     # get the table description
20832     my $sth = $dbh->prepare("SHOW CREATE TABLE $table");
20833     $sth->execute;
20834     my $vsc_structure = $sth->fetchrow;
20835     # split on CONSTRAINT keyword
20836     my @fks = split /CONSTRAINT /,$vsc_structure;
20837     # parse each entry
20838     foreach (@fks) {
20839         # isolate what is before FOREIGN KEY, if there is something, it's a foreign key to drop
20840         $_ = /(.*) FOREIGN KEY.*/;
20841         my $id = $1;
20842         if ($id) {
20843             # we have found 1 foreign, drop it
20844             $dbh->do("ALTER TABLE $table DROP FOREIGN KEY $id");
20845             $id="";
20846         }
20847     }
20848 }
20849
20850
20851 =head2 TransformToNum
20852
20853 Transform the Koha version from a 4 parts string
20854 to a number, with just 1 .
20855
20856 =cut
20857
20858 sub TransformToNum {
20859     my $version = shift;
20860     # remove the 3 last . to have a Perl number
20861     $version =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
20862     # three X's at the end indicate that you are testing patch with dbrev
20863     # change it into 999
20864     # prevents error on a < comparison between strings (should be: lt)
20865     $version =~ s/XXX$/999/;
20866     return $version;
20867 }
20868
20869 =head2 SetVersion
20870
20871 set the DBversion in the systempreferences
20872
20873 =cut
20874
20875 sub SetVersion {
20876     return if $_[0]=~ /XXX$/;
20877       #you are testing a patch with a db revision; do not change version
20878     my $kohaversion = TransformToNum($_[0]);
20879     if (C4::Context->preference('Version')) {
20880       my $finish=$dbh->prepare("UPDATE systempreferences SET value=? WHERE variable='Version'");
20881       $finish->execute($kohaversion);
20882     } else {
20883       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')");
20884       $finish->execute($kohaversion);
20885     }
20886     C4::Context::clear_syspref_cache(); # invalidate cached preferences
20887 }
20888
20889 =head2 CheckVersion
20890
20891 Check whether a given update should be run when passed the proposed version
20892 number. The update will always be run if the proposed version is greater
20893 than the current database version and less than or equal to the version in
20894 kohaversion.pl. The update is also run if the version contains XXX, though
20895 this behavior will be changed following the adoption of non-linear updates
20896 as implemented in bug 7167.
20897
20898 =cut
20899
20900 sub CheckVersion {
20901     my ($proposed_version) = @_;
20902     my $version_number = TransformToNum($proposed_version);
20903
20904     # The following line should be deleted when bug 7167 is pushed
20905     return 1 if ( $proposed_version =~ m/XXX/ );
20906
20907     if ( C4::Context->preference("Version") < $version_number
20908         && $version_number <= TransformToNum( $Koha::VERSION ) )
20909     {
20910         return 1;
20911     }
20912     else {
20913         return 0;
20914     }
20915 }
20916
20917 exit;