Bug 20922: Remove use of Koha::Number::Price in updatedatabase.pl
[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 strict;
31 use warnings;
32
33 use feature 'say';
34
35 # CPAN modules
36 use DBI;
37 use Getopt::Long;
38 # Koha modules
39 use C4::Context;
40 use C4::Installer;
41 use Koha::Database;
42 use Koha;
43 use Koha::DateUtils;
44
45 use MARC::Record;
46 use MARC::File::XML ( BinaryEncoding => 'utf8' );
47
48 use File::Path qw[remove_tree]; # perl core module
49 use File::Spec;
50 use File::Slurp;
51
52 # FIXME - The user might be installing a new database, so can't rely
53 # on /etc/koha.conf anyway.
54
55 my $debug = 0;
56
57 my (
58     $sth, $sti,
59     $query,
60     %existingtables,    # tables already in database
61     %types,
62     $table,
63     $column,
64     $type, $null, $key, $default, $extra,
65     $prefitem,          # preference item in systempreferences table
66 );
67
68 my $schema = Koha::Database->new()->schema();
69
70 my $silent;
71 GetOptions(
72     's' =>\$silent
73     );
74 my $dbh = C4::Context->dbh;
75 $|=1; # flushes output
76
77 local $dbh->{RaiseError} = 0;
78
79 # Record the version we are coming from
80
81 my $original_version = C4::Context->preference("Version");
82
83 # Deal with virtualshelves
84 my $DBversion = "3.00.00.001";
85 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
86     # update virtualshelves table to
87     #
88     $dbh->do("ALTER TABLE `bookshelf` RENAME `virtualshelves`");
89     $dbh->do("ALTER TABLE `shelfcontents` RENAME `virtualshelfcontents`");
90     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD `biblionumber` INT( 11 ) NOT NULL default '0' AFTER shelfnumber");
91     $dbh->do("UPDATE `virtualshelfcontents` SET biblionumber=(SELECT biblionumber FROM items WHERE items.itemnumber=virtualshelfcontents.itemnumber)");
92     # drop all foreign keys : otherwise, we can't drop itemnumber field.
93     DropAllForeignKeys('virtualshelfcontents');
94     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD KEY biblionumber (biblionumber)");
95     # create the new foreign keys (on biblionumber)
96     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD CONSTRAINT `virtualshelfcontents_ibfk_1` FOREIGN KEY (`shelfnumber`) REFERENCES `virtualshelves` (`shelfnumber`) ON DELETE CASCADE ON UPDATE CASCADE");
97     # re-create the foreign key on virtualshelf
98     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD CONSTRAINT `shelfcontents_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE");
99     $dbh->do("ALTER TABLE `virtualshelfcontents` DROP `itemnumber`");
100     print "Upgrade to $DBversion done (virtualshelves)\n";
101     SetVersion ($DBversion);
102 }
103
104
105 $DBversion = "3.00.00.002";
106 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
107     $dbh->do("DROP TABLE sessions");
108     $dbh->do("CREATE TABLE `sessions` (
109   `id` varchar(32) NOT NULL,
110   `a_session` text NOT NULL,
111   UNIQUE KEY `id` (`id`)
112 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
113     print "Upgrade to $DBversion done (sessions uses CGI::session, new table structure for sessions)\n";
114     SetVersion ($DBversion);
115 }
116
117
118 $DBversion = "3.00.00.003";
119 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
120     if (C4::Context->preference("opaclanguages") eq "fr") {
121         $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')");
122     } else {
123         $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')");
124     }
125     print "Upgrade to $DBversion done (adding ReservesNeedReturns systempref, in circulation)\n";
126     SetVersion ($DBversion);
127 }
128
129
130 $DBversion = "3.00.00.004";
131 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
132     $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')");
133     print "Upgrade to $DBversion done (adding DebugLevel systempref, in 'Admin' tab)\n";
134     SetVersion ($DBversion);
135 }
136
137 $DBversion = "3.00.00.005";
138 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
139     $dbh->do("CREATE TABLE `tags` (
140                     `entry` varchar(255) NOT NULL default '',
141                     `weight` bigint(20) NOT NULL default 0,
142                     PRIMARY KEY  (`entry`)
143                     ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
144                 ");
145         $dbh->do("CREATE TABLE `nozebra` (
146                 `server` varchar(20)     NOT NULL,
147                 `indexname` varchar(40)  NOT NULL,
148                 `value` varchar(250)     NOT NULL,
149                 `biblionumbers` longtext NOT NULL,
150                 KEY `indexname` (`server`,`indexname`),
151                 KEY `value` (`server`,`value`))
152                 ENGINE=InnoDB DEFAULT CHARSET=utf8;
153                 ");
154     print "Upgrade to $DBversion done (adding tags and nozebra tables )\n";
155     SetVersion ($DBversion);
156 }
157
158 $DBversion = "3.00.00.006";
159 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
160     $dbh->do("UPDATE issues SET issuedate=timestamp WHERE issuedate='0000-00-00'");
161     print "Upgrade to $DBversion done (filled issues.issuedate with timestamp)\n";
162     SetVersion ($DBversion);
163 }
164
165 $DBversion = "3.00.00.007";
166 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
167     $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')");
168     print "Upgrade to $DBversion done (set SessionStorage variable)\n";
169     SetVersion ($DBversion);
170 }
171
172 $DBversion = "3.00.00.008";
173 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
174     $dbh->do("ALTER TABLE `biblio` ADD `datecreated` DATE NOT NULL AFTER `timestamp` ;");
175     $dbh->do("UPDATE biblio SET datecreated=timestamp");
176     print "Upgrade to $DBversion done (biblio creation date)\n";
177     SetVersion ($DBversion);
178 }
179
180 $DBversion = "3.00.00.009";
181 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
182
183     # Create backups of call number columns
184     # in case default migration needs to be customized
185     #
186     # UPGRADE NOTE: temp_upg_biblioitems_call_num should be dropped
187     #               after call numbers have been transformed to the new structure
188     #
189     # Not bothering to do the same with deletedbiblioitems -- assume
190     # default is good enough.
191     $dbh->do("CREATE TABLE `temp_upg_biblioitems_call_num` AS
192               SELECT `biblioitemnumber`, `biblionumber`,
193                      `classification`, `dewey`, `subclass`,
194                      `lcsort`, `ccode`
195               FROM `biblioitems`");
196
197     # biblioitems changes
198     $dbh->do("ALTER TABLE `biblioitems` CHANGE COLUMN `volumeddesc` `volumedesc` TEXT,
199                                     ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
200                                     ADD `cn_class` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
201                                     ADD `cn_item` VARCHAR(10) DEFAULT NULL AFTER `cn_class`,
202                                     ADD `cn_suffix` VARCHAR(10) DEFAULT NULL AFTER `cn_item`,
203                                     ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_suffix`,
204                                     ADD `totalissues` INT(10) AFTER `cn_sort`");
205
206     # default mapping of call number columns:
207     #   cn_class = concatentation of classification + dewey,
208     #              trimmed to fit -- assumes that most users do not
209     #              populate both classification and dewey in a single record
210     #   cn_item  = subclass
211     #   cn_source = left null
212     #   cn_sort = lcsort
213     #
214     # After upgrade, cn_sort will have to be set based on whatever
215     # default call number scheme user sets as a preference.  Misc
216     # script will be added at some point to do that.
217     #
218     $dbh->do("UPDATE `biblioitems`
219               SET cn_class = SUBSTR(TRIM(CONCAT_WS(' ', `classification`, `dewey`)), 1, 30),
220                     cn_item = subclass,
221                     `cn_sort` = `lcsort`
222             ");
223
224     # Now drop the old call number columns
225     $dbh->do("ALTER TABLE `biblioitems` DROP COLUMN `classification`,
226                                         DROP COLUMN `dewey`,
227                                         DROP COLUMN `subclass`,
228                                         DROP COLUMN `lcsort`,
229                                         DROP COLUMN `ccode`");
230
231     # deletedbiblio changes
232     $dbh->do("ALTER TABLE `deletedbiblio` ALTER COLUMN `frameworkcode` SET DEFAULT '',
233                                         DROP COLUMN `marc`,
234                                         ADD `datecreated` DATE NOT NULL AFTER `timestamp`");
235     $dbh->do("UPDATE deletedbiblio SET datecreated = timestamp");
236
237     # deletedbiblioitems changes
238     $dbh->do("ALTER TABLE `deletedbiblioitems`
239                         MODIFY `publicationyear` TEXT,
240                         CHANGE `volumeddesc` `volumedesc` TEXT,
241                         MODIFY `collectiontitle` MEDIUMTEXT DEFAULT NULL AFTER `volumedesc`,
242                         MODIFY `collectionissn` TEXT DEFAULT NULL AFTER `collectiontitle`,
243                         MODIFY `collectionvolume` MEDIUMTEXT DEFAULT NULL AFTER `collectionissn`,
244                         MODIFY `editionstatement` TEXT DEFAULT NULL AFTER `collectionvolume`,
245                         MODIFY `editionresponsibility` TEXT DEFAULT NULL AFTER `editionstatement`,
246                         MODIFY `place` VARCHAR(255) DEFAULT NULL AFTER `size`,
247                         MODIFY `marc` LONGBLOB,
248                         ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `url`,
249                         ADD `cn_class` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
250                         ADD `cn_item` VARCHAR(10) DEFAULT NULL AFTER `cn_class`,
251                         ADD `cn_suffix` VARCHAR(10) DEFAULT NULL AFTER `cn_item`,
252                         ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_suffix`,
253                         ADD `totalissues` INT(10) AFTER `cn_sort`,
254                         ADD `marcxml` LONGTEXT NOT NULL AFTER `totalissues`,
255                         ADD KEY `isbn` (`isbn`),
256                         ADD KEY `publishercode` (`publishercode`)
257                     ");
258
259     $dbh->do("UPDATE `deletedbiblioitems`
260                 SET `cn_class` = SUBSTR(TRIM(CONCAT_WS(' ', `classification`, `dewey`)), 1, 30),
261                `cn_item` = `subclass`,
262                 `cn_sort` = `lcsort`
263             ");
264     $dbh->do("ALTER TABLE `deletedbiblioitems`
265                         DROP COLUMN `classification`,
266                         DROP COLUMN `dewey`,
267                         DROP COLUMN `subclass`,
268                         DROP COLUMN `lcsort`,
269                         DROP COLUMN `ccode`
270             ");
271
272     # deleteditems changes
273     $dbh->do("ALTER TABLE `deleteditems`
274                         MODIFY `barcode` VARCHAR(20) DEFAULT NULL,
275                         MODIFY `price` DECIMAL(8,2) DEFAULT NULL,
276                         MODIFY `replacementprice` DECIMAL(8,2) DEFAULT NULL,
277                         DROP `bulk`,
278                         MODIFY `itemcallnumber` VARCHAR(30) DEFAULT NULL AFTER `wthdrawn`,
279                         MODIFY `holdingbranch` VARCHAR(10) DEFAULT NULL,
280                         DROP `interim`,
281                         MODIFY `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP AFTER `paidfor`,
282                         DROP `cutterextra`,
283                         ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `onloan`,
284                         ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
285                         ADD `ccode` VARCHAR(10) DEFAULT NULL AFTER `cn_sort`,
286                         ADD `materials` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
287                         ADD `uri` VARCHAR(255) DEFAULT NULL AFTER `materials`,
288                         MODIFY `marc` LONGBLOB AFTER `uri`,
289                         DROP KEY `barcode`,
290                         DROP KEY `itembarcodeidx`,
291                         DROP KEY `itembinoidx`,
292                         DROP KEY `itembibnoidx`,
293                         ADD UNIQUE KEY `delitembarcodeidx` (`barcode`),
294                         ADD KEY `delitembinoidx` (`biblioitemnumber`),
295                         ADD KEY `delitembibnoidx` (`biblionumber`),
296                         ADD KEY `delhomebranch` (`homebranch`),
297                         ADD KEY `delholdingbranch` (`holdingbranch`)");
298     $dbh->do("UPDATE deleteditems SET `ccode` = `itype`");
299     $dbh->do("ALTER TABLE deleteditems DROP `itype`");
300     $dbh->do("UPDATE `deleteditems` SET `cn_sort` = `itemcallnumber`");
301
302     # items changes
303     $dbh->do("ALTER TABLE `items` ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `onloan`,
304                                 ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
305                                 ADD `ccode` VARCHAR(10) DEFAULT NULL AFTER `cn_sort`,
306                                 ADD `materials` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
307                                 ADD `uri` VARCHAR(255) DEFAULT NULL AFTER `materials`
308             ");
309     $dbh->do("ALTER TABLE `items`
310                         DROP KEY `itembarcodeidx`,
311                         ADD UNIQUE KEY `itembarcodeidx` (`barcode`)");
312
313     # map items.itype to items.ccode and
314     # set cn_sort to itemcallnumber -- as with biblioitems.cn_sort,
315     # will have to be subsequently updated per user's default
316     # classification scheme
317     $dbh->do("UPDATE `items` SET `cn_sort` = `itemcallnumber`,
318                             `ccode` = `itype`");
319
320     $dbh->do("ALTER TABLE `items` DROP `cutterextra`,
321                                 DROP `itype`");
322
323     print "Upgrade to $DBversion done (major changes to biblio, biblioitems, items, and deleted* versions of same\n";
324     SetVersion ($DBversion);
325 }
326
327 $DBversion = "3.00.00.010";
328 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
329     $dbh->do("CREATE INDEX `userid` ON borrowers (`userid`) ");
330     print "Upgrade to $DBversion done (userid index added)\n";
331     SetVersion ($DBversion);
332 }
333
334 $DBversion = "3.00.00.011";
335 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
336     $dbh->do("ALTER TABLE `branchcategories` CHANGE `categorycode` `categorycode` varchar(10) ");
337     $dbh->do("ALTER TABLE `branchcategories` CHANGE `categoryname` `categoryname` varchar(32) ");
338     $dbh->do("ALTER TABLE `branchcategories` ADD COLUMN `categorytype` varchar(16) ");
339     $dbh->do("UPDATE `branchcategories` SET `categorytype` = 'properties'");
340     $dbh->do("ALTER TABLE `branchrelations` CHANGE `categorycode` `categorycode` varchar(10) ");
341     print "Upgrade to $DBversion done (added branchcategory type)\n";
342     SetVersion ($DBversion);
343 }
344
345 $DBversion = "3.00.00.012";
346 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
347     $dbh->do("CREATE TABLE `class_sort_rules` (
348                                `class_sort_rule` varchar(10) NOT NULL default '',
349                                `description` mediumtext,
350                                `sort_routine` varchar(30) NOT NULL default '',
351                                PRIMARY KEY (`class_sort_rule`),
352                                UNIQUE KEY `class_sort_rule_idx` (`class_sort_rule`)
353                              ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
354     $dbh->do("CREATE TABLE `class_sources` (
355                                `cn_source` varchar(10) NOT NULL default '',
356                                `description` mediumtext,
357                                `used` tinyint(4) NOT NULL default 0,
358                                `class_sort_rule` varchar(10) NOT NULL default '',
359                                PRIMARY KEY (`cn_source`),
360                                UNIQUE KEY `cn_source_idx` (`cn_source`),
361                                KEY `used_idx` (`used`),
362                                CONSTRAINT `class_source_ibfk_1` FOREIGN KEY (`class_sort_rule`)
363                                           REFERENCES `class_sort_rules` (`class_sort_rule`)
364                              ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
365     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type)
366               VALUES('DefaultClassificationSource','ddc',
367                      'Default classification scheme used by the collection. E.g., Dewey, LCC, etc.', NULL,'free')");
368     $dbh->do("INSERT INTO `class_sort_rules` (`class_sort_rule`, `description`, `sort_routine`) VALUES
369                                ('dewey', 'Default filing rules for DDC', 'Dewey'),
370                                ('lcc', 'Default filing rules for LCC', 'LCC'),
371                                ('generic', 'Generic call number filing rules', 'Generic')");
372     $dbh->do("INSERT INTO `class_sources` (`cn_source`, `description`, `used`, `class_sort_rule`) VALUES
373                             ('ddc', 'Dewey Decimal Classification', 1, 'dewey'),
374                             ('lcc', 'Library of Congress Classification', 1, 'lcc'),
375                             ('udc', 'Universal Decimal Classification', 0, 'generic'),
376                             ('sudocs', 'SuDoc Classification (U.S. GPO)', 0, 'generic'),
377                             ('z', 'Other/Generic Classification Scheme', 0, 'generic')");
378     print "Upgrade to $DBversion done (classification sources added)\n";
379     SetVersion ($DBversion);
380 }
381
382 $DBversion = "3.00.00.013";
383 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
384     $dbh->do("CREATE TABLE `import_batches` (
385               `import_batch_id` int(11) NOT NULL auto_increment,
386               `template_id` int(11) default NULL,
387               `branchcode` varchar(10) default NULL,
388               `num_biblios` int(11) NOT NULL default 0,
389               `num_items` int(11) NOT NULL default 0,
390               `upload_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
391               `overlay_action` enum('replace', 'create_new', 'use_template') NOT NULL default 'create_new',
392               `import_status` enum('staging', 'staged', 'importing', 'imported', 'reverting', 'reverted', 'cleaned') NOT NULL default 'staging',
393               `batch_type` enum('batch', 'z3950') NOT NULL default 'batch',
394               `file_name` varchar(100),
395               `comments` mediumtext,
396               PRIMARY KEY (`import_batch_id`),
397               KEY `branchcode` (`branchcode`)
398               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
399     $dbh->do("CREATE TABLE `import_records` (
400               `import_record_id` int(11) NOT NULL auto_increment,
401               `import_batch_id` int(11) NOT NULL,
402               `branchcode` varchar(10) default NULL,
403               `record_sequence` int(11) NOT NULL default 0,
404               `upload_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
405               `import_date` DATE default NULL,
406               `marc` longblob NOT NULL,
407               `marcxml` longtext NOT NULL,
408               `marcxml_old` longtext NOT NULL,
409               `record_type` enum('biblio', 'auth', 'holdings') NOT NULL default 'biblio',
410               `overlay_status` enum('no_match', 'auto_match', 'manual_match', 'match_applied') NOT NULL default 'no_match',
411               `status` enum('error', 'staged', 'imported', 'reverted', 'items_reverted') NOT NULL default 'staged',
412               `import_error` mediumtext,
413               `encoding` varchar(40) NOT NULL default '',
414               `z3950random` varchar(40) default NULL,
415               PRIMARY KEY (`import_record_id`),
416               CONSTRAINT `import_records_ifbk_1` FOREIGN KEY (`import_batch_id`)
417                           REFERENCES `import_batches` (`import_batch_id`) ON DELETE CASCADE ON UPDATE CASCADE,
418               KEY `branchcode` (`branchcode`),
419               KEY `batch_sequence` (`import_batch_id`, `record_sequence`)
420               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
421     $dbh->do("CREATE TABLE `import_record_matches` (
422               `import_record_id` int(11) NOT NULL,
423               `candidate_match_id` int(11) NOT NULL,
424               `score` int(11) NOT NULL default 0,
425               CONSTRAINT `import_record_matches_ibfk_1` FOREIGN KEY (`import_record_id`)
426                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
427               KEY `record_score` (`import_record_id`, `score`)
428               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
429     $dbh->do("CREATE TABLE `import_biblios` (
430               `import_record_id` int(11) NOT NULL,
431               `matched_biblionumber` int(11) default NULL,
432               `control_number` varchar(25) default NULL,
433               `original_source` varchar(25) default NULL,
434               `title` varchar(128) default NULL,
435               `author` varchar(80) default NULL,
436               `isbn` varchar(14) default NULL,
437               `issn` varchar(9) default NULL,
438               `has_items` tinyint(1) NOT NULL default 0,
439               CONSTRAINT `import_biblios_ibfk_1` FOREIGN KEY (`import_record_id`)
440                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
441               KEY `matched_biblionumber` (`matched_biblionumber`),
442               KEY `title` (`title`),
443               KEY `isbn` (`isbn`)
444               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
445     $dbh->do("CREATE TABLE `import_items` (
446               `import_items_id` int(11) NOT NULL auto_increment,
447               `import_record_id` int(11) NOT NULL,
448               `itemnumber` int(11) default NULL,
449               `branchcode` varchar(10) default NULL,
450               `status` enum('error', 'staged', 'imported', 'reverted') NOT NULL default 'staged',
451               `marcxml` longtext NOT NULL,
452               `import_error` mediumtext,
453               PRIMARY KEY (`import_items_id`),
454               CONSTRAINT `import_items_ibfk_1` FOREIGN KEY (`import_record_id`)
455                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
456               KEY `itemnumber` (`itemnumber`),
457               KEY `branchcode` (`branchcode`)
458               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
459
460     $dbh->do("INSERT INTO `import_batches`
461                 (`overlay_action`, `import_status`, `batch_type`, `file_name`)
462               SELECT distinct 'create_new', 'staged', 'z3950', `file`
463               FROM   `marc_breeding`");
464
465     $dbh->do("INSERT INTO `import_records`
466                 (`import_batch_id`, `import_record_id`, `record_sequence`, `marc`, `record_type`, `status`,
467                 `encoding`, `z3950random`, `marcxml`, `marcxml_old`)
468               SELECT `import_batch_id`, `id`, 1, `marc`, 'biblio', 'staged', `encoding`, `z3950random`, '', ''
469               FROM `marc_breeding`
470               JOIN `import_batches` ON (`file_name` = `file`)");
471
472     $dbh->do("INSERT INTO `import_biblios`
473                 (`import_record_id`, `title`, `author`, `isbn`)
474               SELECT `import_record_id`, `title`, `author`, `isbn`
475               FROM   `marc_breeding`
476               JOIN   `import_records` ON (`import_record_id` = `id`)");
477
478     $dbh->do("UPDATE `import_batches`
479               SET `num_biblios` = (
480               SELECT COUNT(*)
481               FROM `import_records`
482               WHERE `import_batch_id` = `import_batches`.`import_batch_id`
483               )");
484
485     $dbh->do("DROP TABLE `marc_breeding`");
486
487     print "Upgrade to $DBversion done (import_batches et al. added)\n";
488     SetVersion ($DBversion);
489 }
490
491 $DBversion = "3.00.00.014";
492 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
493     $dbh->do("ALTER TABLE subscription ADD lastbranch VARCHAR(4)");
494     print "Upgrade to $DBversion done (userid index added)\n";
495     SetVersion ($DBversion);
496 }
497
498 $DBversion = "3.00.00.015";
499 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
500     $dbh->do("CREATE TABLE `saved_sql` (
501            `id` int(11) NOT NULL auto_increment,
502            `borrowernumber` int(11) default NULL,
503            `date_created` datetime default NULL,
504            `last_modified` datetime default NULL,
505            `savedsql` text,
506            `last_run` datetime default NULL,
507            `report_name` varchar(255) default NULL,
508            `type` varchar(255) default NULL,
509            `notes` text,
510            PRIMARY KEY  (`id`),
511            KEY boridx (`borrowernumber`)
512         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
513     $dbh->do("CREATE TABLE `saved_reports` (
514            `id` int(11) NOT NULL auto_increment,
515            `report_id` int(11) default NULL,
516            `report` longtext,
517            `date_run` datetime default NULL,
518            PRIMARY KEY  (`id`)
519         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
520     print "Upgrade to $DBversion done (saved_sql and saved_reports added)\n";
521     SetVersion ($DBversion);
522 }
523
524 $DBversion = "3.00.00.016";
525 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
526     $dbh->do(" CREATE TABLE reports_dictionary (
527           id int(11) NOT NULL auto_increment,
528           name varchar(255) default NULL,
529           description text,
530           date_created datetime default NULL,
531           date_modified datetime default NULL,
532           saved_sql text,
533           area int(11) default NULL,
534           PRIMARY KEY  (id)
535         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
536     print "Upgrade to $DBversion done (reports_dictionary) added)\n";
537     SetVersion ($DBversion);
538 }
539
540 $DBversion = "3.00.00.017";
541 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
542     $dbh->do("ALTER TABLE action_logs DROP PRIMARY KEY");
543     $dbh->do("ALTER TABLE action_logs ADD KEY  timestamp (timestamp,user)");
544     $dbh->do("ALTER TABLE action_logs ADD action_id INT(11) NOT NULL FIRST");
545     $dbh->do("UPDATE action_logs SET action_id = if (\@a, \@a:=\@a+1, \@a:=1)");
546     $dbh->do("ALTER TABLE action_logs MODIFY action_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY");
547     print "Upgrade to $DBversion done (added column to action_logs)\n";
548     SetVersion ($DBversion);
549 }
550
551 $DBversion = "3.00.00.018";
552 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
553     $dbh->do("ALTER TABLE `zebraqueue`
554                     ADD `done` INT NOT NULL DEFAULT '0',
555                     ADD `time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ;
556             ");
557     print "Upgrade to $DBversion done (adding timestamp and done columns to zebraque table to improve problem tracking) added)\n";
558     SetVersion ($DBversion);
559 }
560
561 $DBversion = "3.00.00.019";
562 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
563     $dbh->do("ALTER TABLE biblio MODIFY biblionumber INT(11) NOT NULL AUTO_INCREMENT");
564     $dbh->do("ALTER TABLE biblioitems MODIFY biblioitemnumber INT(11) NOT NULL AUTO_INCREMENT");
565     $dbh->do("ALTER TABLE items MODIFY itemnumber INT(11) NOT NULL AUTO_INCREMENT");
566     print "Upgrade to $DBversion done (made bib/item PKs auto_increment)\n";
567     SetVersion ($DBversion);
568 }
569
570 $DBversion = "3.00.00.020";
571 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
572     $dbh->do("ALTER TABLE deleteditems
573               DROP KEY `delitembarcodeidx`,
574               ADD KEY `delitembarcodeidx` (`barcode`)");
575     print "Upgrade to $DBversion done (dropped uniqueness of key on deleteditems.barcode)\n";
576     SetVersion ($DBversion);
577 }
578
579 $DBversion = "3.00.00.021";
580 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
581     $dbh->do("ALTER TABLE items CHANGE homebranch homebranch VARCHAR(10)");
582     $dbh->do("ALTER TABLE deleteditems CHANGE homebranch homebranch VARCHAR(10)");
583     $dbh->do("ALTER TABLE statistics CHANGE branch branch VARCHAR(10)");
584     $dbh->do("ALTER TABLE subscription CHANGE lastbranch lastbranch VARCHAR(10)");
585     print "Upgrade to $DBversion done (extended missed branchcode columns to 10 chars)\n";
586     SetVersion ($DBversion);
587 }
588
589 $DBversion = "3.00.00.022";
590 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
591     $dbh->do("ALTER TABLE items
592                 ADD `damaged` tinyint(1) default NULL AFTER notforloan");
593     $dbh->do("ALTER TABLE deleteditems
594                 ADD `damaged` tinyint(1) default NULL AFTER notforloan");
595     print "Upgrade to $DBversion done (adding damaged column to items table)\n";
596     SetVersion ($DBversion);
597 }
598
599 $DBversion = "3.00.00.023";
600 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
601      $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
602          VALUES ('yuipath','http://yui.yahooapis.com/2.3.1/build','Insert the path to YUI libraries','','free')");
603     print "Upgrade to $DBversion done (adding new system preference for controlling YUI path)\n";
604     SetVersion ($DBversion);
605 }
606 $DBversion = "3.00.00.024";
607 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
608     $dbh->do("ALTER TABLE biblioitems CHANGE  itemtype itemtype VARCHAR(10)");
609     print "Upgrade to $DBversion done (changing itemtype to (10))\n";
610     SetVersion ($DBversion);
611 }
612
613 $DBversion = "3.00.00.025";
614 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
615     $dbh->do("ALTER TABLE items ADD COLUMN itype VARCHAR(10)");
616     $dbh->do("ALTER TABLE deleteditems ADD COLUMN itype VARCHAR(10) AFTER uri");
617     if(C4::Context->preference('item-level_itypes')){
618         $dbh->do('update items,biblioitems set items.itype=biblioitems.itemtype where items.biblionumber=biblioitems.biblionumber and itype is null');
619     }
620     print "Upgrade to $DBversion done (reintroduce items.itype - fill from itemtype)\n ";
621     SetVersion ($DBversion);
622 }
623
624 $DBversion = "3.00.00.026";
625 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
626     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
627        VALUES ('HomeOrHoldingBranch','homebranch','homebranch|holdingbranch','With independent branches turned on this decides whether to check the items holdingbranch or homebranch at circulatilon','choice')");
628     print "Upgrade to $DBversion done (adding new system preference for choosing whether homebranch or holdingbranch is checked in circulation)\n";
629     SetVersion ($DBversion);
630 }
631
632 $DBversion = "3.00.00.027";
633 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
634     $dbh->do("CREATE TABLE `marc_matchers` (
635                 `matcher_id` int(11) NOT NULL auto_increment,
636                 `code` varchar(10) NOT NULL default '',
637                 `description` varchar(255) NOT NULL default '',
638                 `record_type` varchar(10) NOT NULL default 'biblio',
639                 `threshold` int(11) NOT NULL default 0,
640                 PRIMARY KEY (`matcher_id`),
641                 KEY `code` (`code`),
642                 KEY `record_type` (`record_type`)
643               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
644     $dbh->do("CREATE TABLE `matchpoints` (
645                 `matcher_id` int(11) NOT NULL,
646                 `matchpoint_id` int(11) NOT NULL auto_increment,
647                 `search_index` varchar(30) NOT NULL default '',
648                 `score` int(11) NOT NULL default 0,
649                 PRIMARY KEY (`matchpoint_id`),
650                 CONSTRAINT `matchpoints_ifbk_1` FOREIGN KEY (`matcher_id`)
651                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE
652               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
653     $dbh->do("CREATE TABLE `matchpoint_components` (
654                 `matchpoint_id` int(11) NOT NULL,
655                 `matchpoint_component_id` int(11) NOT NULL auto_increment,
656                 sequence int(11) NOT NULL default 0,
657                 tag varchar(3) NOT NULL default '',
658                 subfields varchar(40) NOT NULL default '',
659                 offset int(4) NOT NULL default 0,
660                 length int(4) NOT NULL default 0,
661                 PRIMARY KEY (`matchpoint_component_id`),
662                 KEY `by_sequence` (`matchpoint_id`, `sequence`),
663                 CONSTRAINT `matchpoint_components_ifbk_1` FOREIGN KEY (`matchpoint_id`)
664                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
665               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
666     $dbh->do("CREATE TABLE `matchpoint_component_norms` (
667                 `matchpoint_component_id` int(11) NOT NULL,
668                 `sequence`  int(11) NOT NULL default 0,
669                 `norm_routine` varchar(50) NOT NULL default '',
670                 KEY `matchpoint_component_norms` (`matchpoint_component_id`, `sequence`),
671                 CONSTRAINT `matchpoint_component_norms_ifbk_1` FOREIGN KEY (`matchpoint_component_id`)
672                            REFERENCES `matchpoint_components` (`matchpoint_component_id`) ON DELETE CASCADE ON UPDATE CASCADE
673               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
674     $dbh->do("CREATE TABLE `matcher_matchpoints` (
675                 `matcher_id` int(11) NOT NULL,
676                 `matchpoint_id` int(11) NOT NULL,
677                 CONSTRAINT `matcher_matchpoints_ifbk_1` FOREIGN KEY (`matcher_id`)
678                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE,
679                 CONSTRAINT `matcher_matchpoints_ifbk_2` FOREIGN KEY (`matchpoint_id`)
680                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
681               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
682     $dbh->do("CREATE TABLE `matchchecks` (
683                 `matcher_id` int(11) NOT NULL,
684                 `matchcheck_id` int(11) NOT NULL auto_increment,
685                 `source_matchpoint_id` int(11) NOT NULL,
686                 `target_matchpoint_id` int(11) NOT NULL,
687                 PRIMARY KEY (`matchcheck_id`),
688                 CONSTRAINT `matcher_matchchecks_ifbk_1` FOREIGN KEY (`matcher_id`)
689                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE,
690                 CONSTRAINT `matcher_matchchecks_ifbk_2` FOREIGN KEY (`source_matchpoint_id`)
691                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE,
692                 CONSTRAINT `matcher_matchchecks_ifbk_3` FOREIGN KEY (`target_matchpoint_id`)
693                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
694               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
695     print "Upgrade to $DBversion done (added C4::Matcher serialization tables)\n ";
696     SetVersion ($DBversion);
697 }
698
699 $DBversion = "3.00.00.028";
700 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
701     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
702        VALUES ('canreservefromotherbranches','1','','With Independent branches on, can a user from one library reserve an item from another library','YesNo')");
703     print "Upgrade to $DBversion done (adding new system preference for changing reserve/holds behaviour with independent branches)\n";
704     SetVersion ($DBversion);
705 }
706
707
708 $DBversion = "3.00.00.029";
709 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
710     $dbh->do("ALTER TABLE `import_batches` ADD `matcher_id` int(11) NULL AFTER `import_batch_id`");
711     print "Upgrade to $DBversion done (adding matcher_id to import_batches)\n";
712     SetVersion ($DBversion);
713 }
714
715 $DBversion = "3.00.00.030";
716 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
717     $dbh->do("
718 CREATE TABLE services_throttle (
719   service_type varchar(10) NOT NULL default '',
720   service_count varchar(45) default NULL,
721   PRIMARY KEY  (service_type)
722 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
723 ");
724     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
725        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')");
726  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
727        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')");
728  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
729        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')");
730  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
731        VALUES ('XISBNDailyLimit',499,'','The xISBN Web service is free for non-commercial use when usage does not exceed 500 requests per day','free')");
732  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
733        VALUES ('PINESISBN',0,'','Use with FRBRizeEditions. If ON, Koha will use PINES OISBN web service in the Editions tab on the detail pages.','YesNo')");
734  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
735        VALUES ('ThingISBN',0,'','Use with FRBRizeEditions. If ON, Koha will use the ThingISBN web service in the Editions tab on the detail pages.','YesNo')");
736     print "Upgrade to $DBversion done (adding services throttle table and sysprefs for xISBN)\n";
737     SetVersion ($DBversion);
738 }
739
740 $DBversion = "3.00.00.031";
741 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
742
743 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryStemming',1,'If ON, enables query stemming',NULL,'YesNo')");
744 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryFuzzy',1,'If ON, enables fuzzy option for searches',NULL,'YesNo')");
745 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryWeightFields',1,'If ON, enables field weighting',NULL,'YesNo')");
746 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('WebBasedSelfCheck',0,'If ON, enables the web-based self-check system',NULL,'YesNo')");
747 $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')");
748 $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')");
749 $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')");
750 $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')");
751 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('defaultSortOrder',NULL,'Specify the default sort order','asc|dsc|az|za','Choice')");
752 $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')");
753 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACdefaultSortOrder',NULL,'Specify the default sort order','asc|dsc|za|az','Choice')");
754 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('staffClientBaseURL','','Specify the base URL of the staff client',NULL,'free')");
755 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('minPasswordLength',3,'Specify the minimum length of a patron/staff password',NULL,'free')");
756 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('noItemTypeImages',0,'If ON, disables item-type images',NULL,'YesNo')");
757 $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')");
758 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('holdCancelLength','','Specify how many days before a hold is canceled',NULL,'free')");
759 $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')");
760 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('finesMode','test','Choose the fines mode, test or production','test|production','Choice')");
761 $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')");
762 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('itemBarcodeInputFilter','','If set, allows specification of a item barcode input filter','cuecat','Choice')");
763 $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')");
764 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('URLLinkText','','Text to display as the link anchor in the OPAC',NULL,'free')");
765 $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')");
766 $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')");
767 $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')");
768 $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')");
769 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACUserCSS',0,'Add CSS to be included in the OPAC',NULL,'free')");
770
771     print "Upgrade to $DBversion done (adding additional system preference)\n";
772     SetVersion ($DBversion);
773 }
774
775 $DBversion = "3.00.00.032";
776 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
777     $dbh->do("UPDATE `marc_subfield_structure` SET `kohafield` = 'items.wthdrawn' WHERE `kohafield` = 'items.withdrawn'");
778     print "Upgrade to $DBversion done (fixed MARC framework references to items.withdrawn)\n";
779     SetVersion ($DBversion);
780 }
781
782 $DBversion = "3.00.00.033";
783 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
784     $dbh->do("INSERT INTO `userflags` VALUES(17,'staffaccess','Modify login / permissions for staff users',0)");
785     print "Upgrade to $DBversion done (Adding permissions flag for staff member access modification.  )\n";
786     SetVersion ($DBversion);
787 }
788
789 $DBversion = "3.00.00.034";
790 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
791     $dbh->do("ALTER TABLE `virtualshelves` ADD COLUMN `sortfield` VARCHAR(16) ");
792     print "Upgrade to $DBversion done (Adding sortfield for Virtual Shelves.  )\n";
793     SetVersion ($DBversion);
794 }
795
796 $DBversion = "3.00.00.035";
797 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
798     $dbh->do("UPDATE marc_subfield_structure
799               SET authorised_value = 'cn_source'
800               WHERE kohafield IN ('items.cn_source', 'biblioitems.cn_source')
801               AND (authorised_value is NULL OR authorised_value = '')");
802     print "Upgrade to $DBversion done (MARC frameworks: make classification source a drop-down)\n";
803     SetVersion ($DBversion);
804 }
805
806 $DBversion = "3.00.00.036";
807 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
808     $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');");
809     print "Upgrade to $DBversion done (OPACItemsResultsDisplay systempreference added)\n";
810     SetVersion ($DBversion);
811 }
812
813 $DBversion = "3.00.00.037";
814 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
815     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactfirstname` varchar(255)");
816     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactsurname` varchar(255)");
817     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress1` varchar(255)");
818     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress2` varchar(255)");
819     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress3` varchar(255)");
820     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactzipcode` varchar(50)");
821     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactphone` varchar(50)");
822     print "Upgrade to $DBversion done (Adding Alternative Contact Person information to borrowers table)\n";
823     SetVersion ($DBversion);
824 }
825
826 $DBversion = "3.00.00.038";
827 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
828     $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'");
829     $dbh->do("DELETE FROM `systempreferences` WHERE variable='hideBiblioNumber'");
830     print "Upgrade to $DBversion done ('alter finesMode systempreference, remove superfluous syspref.')\n";
831     SetVersion ($DBversion);
832 }
833
834 $DBversion = "3.00.00.039";
835 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
836     $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')");
837     $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')");
838     $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')");
839     # $dbh->do("DELETE FROM `systempreferences` WHERE variable='HomeOrHoldingBranch'"); # Bug #2752
840     print "Upgrade to $DBversion done ('add circ sysprefs CircControl, finesCalendar, and uppercasesurnames, and delete HomeOrHoldingBranch.')\n";
841     SetVersion ($DBversion);
842 }
843
844 $DBversion = "3.00.00.040";
845 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
846         $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')");
847         $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')");
848         print "Upgrade to $DBversion done ('add circ sysprefs todaysIssuesDefaultSortOrder and previousIssuesDefaultSortOrder.')\n";
849     SetVersion ($DBversion);
850 }
851
852
853 $DBversion = "3.00.00.041";
854 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
855     # Strictly speaking it is not necessary to explicitly change
856     # NULL values to 0, because the ALTER TABLE statement will do that.
857     # However, setting them first avoids a warning.
858     $dbh->do("UPDATE items SET notforloan = 0 WHERE notforloan IS NULL");
859     $dbh->do("UPDATE items SET damaged = 0 WHERE damaged IS NULL");
860     $dbh->do("UPDATE items SET itemlost = 0 WHERE itemlost IS NULL");
861     $dbh->do("UPDATE items SET wthdrawn = 0 WHERE wthdrawn IS NULL");
862     $dbh->do("ALTER TABLE items
863                 MODIFY notforloan tinyint(1) NOT NULL default 0,
864                 MODIFY damaged    tinyint(1) NOT NULL default 0,
865                 MODIFY itemlost   tinyint(1) NOT NULL default 0,
866                 MODIFY wthdrawn   tinyint(1) NOT NULL default 0");
867     $dbh->do("UPDATE deleteditems SET notforloan = 0 WHERE notforloan IS NULL");
868     $dbh->do("UPDATE deleteditems SET damaged = 0 WHERE damaged IS NULL");
869     $dbh->do("UPDATE deleteditems SET itemlost = 0 WHERE itemlost IS NULL");
870     $dbh->do("UPDATE deleteditems SET wthdrawn = 0 WHERE wthdrawn IS NULL");
871     $dbh->do("ALTER TABLE deleteditems
872                 MODIFY notforloan tinyint(1) NOT NULL default 0,
873                 MODIFY damaged    tinyint(1) NOT NULL default 0,
874                 MODIFY itemlost   tinyint(1) NOT NULL default 0,
875                 MODIFY wthdrawn   tinyint(1) NOT NULL default 0");
876         print "Upgrade to $DBversion done (disallow NULL in several item status columns)\n";
877     SetVersion ($DBversion);
878 }
879
880 $DBversion = "3.00.00.04";
881 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
882     $dbh->do("ALTER TABLE aqbooksellers CHANGE name name mediumtext NOT NULL");
883         print "Upgrade to $DBversion done (disallow NULL in aqbooksellers.name; part of fix for bug 1251)\n";
884     SetVersion ($DBversion);
885 }
886
887 $DBversion = "3.00.00.043";
888 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
889     $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");
890         print "Upgrade to $DBversion done (currency table: add symbol and timestamp columns)\n";
891     SetVersion ($DBversion);
892 }
893
894 $DBversion = "3.00.00.044";
895 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
896     $dbh->do("ALTER TABLE deletedborrowers
897   ADD `altcontactfirstname` varchar(255) default NULL,
898   ADD `altcontactsurname` varchar(255) default NULL,
899   ADD `altcontactaddress1` varchar(255) default NULL,
900   ADD `altcontactaddress2` varchar(255) default NULL,
901   ADD `altcontactaddress3` varchar(255) default NULL,
902   ADD `altcontactzipcode` varchar(50) default NULL,
903   ADD `altcontactphone` varchar(50) default NULL
904   ");
905   $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES
906 ('OPACBaseURL',NULL,'Specify the Base URL of the OPAC, e.g., opac.mylibrary.com, the http:// will be added automatically by Koha.',NULL,'Free'),
907 ('language','en','Set the default language in the staff client.',NULL,'Languages'),
908 ('QueryAutoTruncate',1,'If ON, query truncation is enabled by default',NULL,'YesNo'),
909 ('QueryRemoveStopwords',0,'If ON, stopwords listed in the Administration area will be removed from queries',NULL,'YesNo')
910   ");
911         print "Upgrade to $DBversion done (syncing deletedborrowers table with borrowers table)\n";
912     SetVersion ($DBversion);
913 }
914
915 #-- http://www.w3.org/International/articles/language-tags/
916
917 #-- RFC4646
918 $DBversion = "3.00.00.045";
919 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
920     $dbh->do("
921 CREATE TABLE language_subtag_registry (
922         subtag varchar(25),
923         type varchar(25), -- language-script-region-variant-extension-privateuse
924         description varchar(25), -- only one of the possible descriptions for ease of reference, see language_descriptions for the complete list
925         added date,
926         KEY `subtag` (`subtag`)
927 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
928
929 #-- TODO: add suppress_scripts
930 #-- this maps three letter codes defined in iso639.2 back to their
931 #-- two letter equivilents in rfc4646 (LOC maintains iso639+)
932  $dbh->do("CREATE TABLE language_rfc4646_to_iso639 (
933         rfc4646_subtag varchar(25),
934         iso639_2_code varchar(25),
935         KEY `rfc4646_subtag` (`rfc4646_subtag`)
936 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
937
938  $dbh->do("CREATE TABLE language_descriptions (
939         subtag varchar(25),
940         type varchar(25),
941         lang varchar(25),
942         description varchar(255),
943         KEY `lang` (`lang`)
944 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
945
946 #-- bi-directional support, keyed by script subcode
947  $dbh->do("CREATE TABLE language_script_bidi (
948         rfc4646_subtag varchar(25), -- script subtag, Arab, Hebr, etc.
949         bidi varchar(3), -- rtl ltr
950         KEY `rfc4646_subtag` (`rfc4646_subtag`)
951 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
952
953 #-- BIDI Stuff, Arabic and Hebrew
954  $dbh->do("INSERT INTO language_script_bidi(rfc4646_subtag,bidi)
955 VALUES( 'Arab', 'rtl')");
956  $dbh->do("INSERT INTO language_script_bidi(rfc4646_subtag,bidi)
957 VALUES( 'Hebr', 'rtl')");
958
959 #-- TODO: need to map language subtags to script subtags for detection
960 #-- of bidi when script is not specified (like ar, he)
961  $dbh->do("CREATE TABLE language_script_mapping (
962         language_subtag varchar(25),
963         script_subtag varchar(25),
964         KEY `language_subtag` (`language_subtag`)
965 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
966
967 #-- Default mappings between script and language subcodes
968  $dbh->do("INSERT INTO language_script_mapping(language_subtag,script_subtag)
969 VALUES( 'ar', 'Arab')");
970  $dbh->do("INSERT INTO language_script_mapping(language_subtag,script_subtag)
971 VALUES( 'he', 'Hebr')");
972
973         print "Upgrade to $DBversion done (adding language subtag registry and basic BiDi support NOTE: You should import the subtag registry SQL)\n";
974     SetVersion ($DBversion);
975 }
976
977 $DBversion = "3.00.00.046";
978 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
979     $dbh->do("ALTER TABLE `subscription` CHANGE `numberlength` `numberlength` int(11) default '0' ,
980                  CHANGE `weeklength` `weeklength` int(11) default '0'");
981     $dbh->do("CREATE TABLE `serialitems` (`serialid` int(11) NOT NULL, `itemnumber` int(11) NOT NULL, UNIQUE KEY `serialididx` (`serialid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
982     $dbh->do("INSERT INTO `serialitems` SELECT `serialid`,`itemnumber` from serial where NOT ISNULL(itemnumber) && itemnumber <> '' && itemnumber NOT LIKE '%,%'");
983         print "Upgrade to $DBversion done (Add serialitems table to link serial issues to items. )\n";
984     SetVersion ($DBversion);
985 }
986
987 $DBversion = "3.00.00.047";
988 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
989     $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');");
990         print "Upgrade to $DBversion done ( Added OpacRenewalAllowed syspref )\n";
991     SetVersion ($DBversion);
992 }
993
994 $DBversion = "3.00.00.048";
995 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
996     $dbh->do("ALTER TABLE `items` ADD `more_subfields_xml` longtext default NULL AFTER `itype`");
997         print "Upgrade to $DBversion done (added items.more_subfields_xml)\n";
998     SetVersion ($DBversion);
999 }
1000
1001 $DBversion = "3.00.00.049";
1002 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1003         $dbh->do("ALTER TABLE `z3950servers` ADD `encoding` text default NULL AFTER type ");
1004         print "Upgrade to $DBversion done ( Added encoding field to z3950servers table )\n";
1005     SetVersion ($DBversion);
1006 }
1007
1008 $DBversion = "3.00.00.050";
1009 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1010     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacHighlightedWords','0','If Set, query matched terms are highlighted in OPAC',NULL,'YesNo');");
1011         print "Upgrade to $DBversion done ( Added OpacHighlightedWords syspref )\n";
1012     SetVersion ($DBversion);
1013 }
1014
1015 $DBversion = "3.00.00.051";
1016 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1017     $dbh->do("UPDATE systempreferences SET explanation = 'Define the current theme for the OPAC interface.' WHERE variable = 'opacthemes';");
1018         print "Upgrade to $DBversion done ( Corrected opacthemes explanation. )\n";
1019     SetVersion ($DBversion);
1020 }
1021
1022 $DBversion = "3.00.00.052";
1023 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1024     $dbh->do("ALTER TABLE `deleteditems` ADD `more_subfields_xml` LONGTEXT DEFAULT NULL AFTER `itype`");
1025         print "Upgrade to $DBversion done ( Adding missing column to deleteditems table. )\n";
1026     SetVersion ($DBversion);
1027 }
1028
1029 $DBversion = "3.00.00.053";
1030 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1031     $dbh->do("CREATE TABLE `printers_profile` (
1032             `prof_id` int(4) NOT NULL auto_increment,
1033             `printername` varchar(40) NOT NULL,
1034             `tmpl_id` int(4) NOT NULL,
1035             `paper_bin` varchar(20) NOT NULL,
1036             `offset_horz` float default NULL,
1037             `offset_vert` float default NULL,
1038             `creep_horz` float default NULL,
1039             `creep_vert` float default NULL,
1040             `unit` char(20) NOT NULL default 'POINT',
1041             PRIMARY KEY  (`prof_id`),
1042             UNIQUE KEY `printername` (`printername`,`tmpl_id`,`paper_bin`),
1043             CONSTRAINT `printers_profile_pnfk_1` FOREIGN KEY (`tmpl_id`) REFERENCES `labels_templates` (`tmpl_id`) ON DELETE CASCADE ON UPDATE CASCADE
1044             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1045     $dbh->do("CREATE TABLE `labels_profile` (
1046             `tmpl_id` int(4) NOT NULL,
1047             `prof_id` int(4) NOT NULL,
1048             UNIQUE KEY `tmpl_id` (`tmpl_id`),
1049             UNIQUE KEY `prof_id` (`prof_id`)
1050             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1051     print "Upgrade to $DBversion done ( Printer Profile tables added )\n";
1052     SetVersion ($DBversion);
1053 }
1054
1055 $DBversion = "3.00.00.054";
1056 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1057     $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';");
1058         print "Upgrade to $DBversion done ( Added another barcode autogeneration sequence to barcode.pl. )\n";
1059     SetVersion ($DBversion);
1060 }
1061
1062 $DBversion = "3.00.00.055";
1063 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1064     $dbh->do("ALTER TABLE `zebraqueue` ADD KEY `zebraqueue_lookup` (`server`, `biblio_auth_number`, `operation`, `done`)");
1065         print "Upgrade to $DBversion done ( Added index on zebraqueue. )\n";
1066     SetVersion ($DBversion);
1067 }
1068 $DBversion = "3.00.00.056";
1069 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1070     if (C4::Context->preference("marcflavour") eq 'UNIMARC') {
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 ('995', 'v', 'Note sur le N° de périodique','Note sur le N° de périodique', 0, 0, 'items.enumchron', 10, '', '', '', 0, 0, '', '', '', NULL) ");
1072     } else {
1073         $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) ");
1074     }
1075     $dbh->do("ALTER TABLE `items` ADD `enumchron` VARCHAR(80) DEFAULT NULL;");
1076     print "Upgrade to $DBversion done ( Added item.enumchron column, and framework map to 952h )\n";
1077     SetVersion ($DBversion);
1078 }
1079
1080 $DBversion = "3.00.00.057";
1081 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1082     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH','0','if ON, OAI-PMH server is enabled',NULL,'YesNo');");
1083     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH:archiveID','KOHA-OAI-TEST','OAI-PMH archive identification',NULL,'Free');");
1084     $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');");
1085     $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');");
1086     $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');");
1087     SetVersion ($DBversion);
1088 }
1089
1090 $DBversion = "3.00.00.058";
1091 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1092     $dbh->do("ALTER TABLE `opac_news`
1093                 CHANGE `lang` `lang` VARCHAR( 25 )
1094                 CHARACTER SET utf8
1095                 COLLATE utf8_general_ci
1096                 NOT NULL default ''");
1097         print "Upgrade to $DBversion done ( lang field in opac_news made longer )\n";
1098     SetVersion ($DBversion);
1099 }
1100
1101 $DBversion = "3.00.00.059";
1102 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1103
1104     $dbh->do("CREATE TABLE IF NOT EXISTS `labels_templates` (
1105             `tmpl_id` int(4) NOT NULL auto_increment,
1106             `tmpl_code` char(100)  default '',
1107             `tmpl_desc` char(100) default '',
1108             `page_width` float default '0',
1109             `page_height` float default '0',
1110             `label_width` float default '0',
1111             `label_height` float default '0',
1112             `topmargin` float default '0',
1113             `leftmargin` float default '0',
1114             `cols` int(2) default '0',
1115             `rows` int(2) default '0',
1116             `colgap` float default '0',
1117             `rowgap` float default '0',
1118             `active` int(1) default NULL,
1119             `units` char(20)  default 'PX',
1120             `fontsize` int(4) NOT NULL default '3',
1121             PRIMARY KEY  (`tmpl_id`)
1122             ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1123     $dbh->do("CREATE TABLE  IF NOT EXISTS `printers_profile` (
1124             `prof_id` int(4) NOT NULL auto_increment,
1125             `printername` varchar(40) NOT NULL,
1126             `tmpl_id` int(4) NOT NULL,
1127             `paper_bin` varchar(20) NOT NULL,
1128             `offset_horz` float default NULL,
1129             `offset_vert` float default NULL,
1130             `creep_horz` float default NULL,
1131             `creep_vert` float default NULL,
1132             `unit` char(20) NOT NULL default 'POINT',
1133             PRIMARY KEY  (`prof_id`),
1134             UNIQUE KEY `printername` (`printername`,`tmpl_id`,`paper_bin`),
1135             CONSTRAINT `printers_profile_pnfk_1` FOREIGN KEY (`tmpl_id`) REFERENCES `labels_templates` (`tmpl_id`) ON DELETE CASCADE ON UPDATE CASCADE
1136             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1137     print "Upgrade to $DBversion done ( Added labels_templates table if it did not exist. )\n";
1138     SetVersion ($DBversion);
1139 }
1140
1141 $DBversion = "3.00.00.060";
1142 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1143     $dbh->do("CREATE TABLE IF NOT EXISTS `patronimage` (
1144             `cardnumber` varchar(16) NOT NULL,
1145             `mimetype` varchar(15) NOT NULL,
1146             `imagefile` mediumblob NOT NULL,
1147             PRIMARY KEY  (`cardnumber`),
1148             CONSTRAINT `patronimage_fk1` FOREIGN KEY (`cardnumber`) REFERENCES `borrowers` (`cardnumber`) ON DELETE CASCADE ON UPDATE CASCADE
1149             ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1150         print "Upgrade to $DBversion done ( Added patronimage table. )\n";
1151     SetVersion ($DBversion);
1152 }
1153
1154 $DBversion = "3.00.00.061";
1155 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1156     $dbh->do("ALTER TABLE labels_templates ADD COLUMN font char(10) NOT NULL DEFAULT 'TR';");
1157         print "Upgrade to $DBversion done ( Added font column to labels_templates )\n";
1158     SetVersion ($DBversion);
1159 }
1160
1161 $DBversion = "3.00.00.062";
1162 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1163     $dbh->do("CREATE TABLE `old_issues` (
1164                 `borrowernumber` int(11) default NULL,
1165                 `itemnumber` int(11) default NULL,
1166                 `date_due` date default NULL,
1167                 `branchcode` varchar(10) default NULL,
1168                 `issuingbranch` varchar(18) default NULL,
1169                 `returndate` date default NULL,
1170                 `lastreneweddate` date default NULL,
1171                 `return` varchar(4) default NULL,
1172                 `renewals` tinyint(4) default NULL,
1173                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1174                 `issuedate` date default NULL,
1175                 KEY `old_issuesborridx` (`borrowernumber`),
1176                 KEY `old_issuesitemidx` (`itemnumber`),
1177                 KEY `old_bordate` (`borrowernumber`,`timestamp`),
1178                 CONSTRAINT `old_issues_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1179                     ON DELETE SET NULL ON UPDATE SET NULL,
1180                 CONSTRAINT `old_issues_ibfk_2` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`)
1181                     ON DELETE SET NULL ON UPDATE SET NULL
1182                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1183     $dbh->do("CREATE TABLE `old_reserves` (
1184                 `borrowernumber` int(11) default NULL,
1185                 `reservedate` date default NULL,
1186                 `biblionumber` int(11) default NULL,
1187                 `constrainttype` varchar(1) default NULL,
1188                 `branchcode` varchar(10) default NULL,
1189                 `notificationdate` date default NULL,
1190                 `reminderdate` date default NULL,
1191                 `cancellationdate` date default NULL,
1192                 `reservenotes` mediumtext,
1193                 `priority` smallint(6) default NULL,
1194                 `found` varchar(1) default NULL,
1195                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1196                 `itemnumber` int(11) default NULL,
1197                 `waitingdate` date default NULL,
1198                 KEY `old_reserves_borrowernumber` (`borrowernumber`),
1199                 KEY `old_reserves_biblionumber` (`biblionumber`),
1200                 KEY `old_reserves_itemnumber` (`itemnumber`),
1201                 KEY `old_reserves_branchcode` (`branchcode`),
1202                 CONSTRAINT `old_reserves_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1203                     ON DELETE SET NULL ON UPDATE SET NULL,
1204                 CONSTRAINT `old_reserves_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`)
1205                     ON DELETE SET NULL ON UPDATE SET NULL,
1206                 CONSTRAINT `old_reserves_ibfk_3` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`)
1207                     ON DELETE SET NULL ON UPDATE SET NULL
1208                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1209
1210     # move closed transactions to old_* tables
1211     $dbh->do("INSERT INTO old_issues SELECT * FROM issues WHERE returndate IS NOT NULL");
1212     $dbh->do("DELETE FROM issues WHERE returndate IS NOT NULL");
1213     $dbh->do("INSERT INTO old_reserves SELECT * FROM reserves WHERE cancellationdate IS NOT NULL OR found = 'F'");
1214     $dbh->do("DELETE FROM reserves WHERE cancellationdate IS NOT NULL OR found = 'F'");
1215
1216         print "Upgrade to $DBversion done ( Added old_issues and old_reserves tables )\n";
1217     SetVersion ($DBversion);
1218 }
1219
1220 $DBversion = "3.00.00.063";
1221 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1222     $dbh->do("ALTER TABLE deleteditems
1223                 CHANGE COLUMN booksellerid booksellerid MEDIUMTEXT DEFAULT NULL,
1224                 ADD COLUMN enumchron VARCHAR(80) DEFAULT NULL AFTER more_subfields_xml,
1225                 ADD COLUMN copynumber SMALLINT(6) DEFAULT NULL AFTER enumchron;");
1226     $dbh->do("ALTER TABLE items
1227                 CHANGE COLUMN booksellerid booksellerid MEDIUMTEXT,
1228                 ADD COLUMN copynumber SMALLINT(6) DEFAULT NULL AFTER enumchron;");
1229         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";
1230     SetVersion ($DBversion);
1231 }
1232
1233 $DBversion = "3.00.00.064";
1234 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1235     $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');");
1236     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AWSAccessKeyID','','See:  http://aws.amazon.com','','free');");
1237     $dbh->do("DELETE FROM `systempreferences` WHERE variable='AmazonDevKey';");
1238     $dbh->do("DELETE FROM `systempreferences` WHERE variable='XISBNAmazonSimilarItems';");
1239     $dbh->do("DELETE FROM `systempreferences` WHERE variable='OPACXISBNAmazonSimilarItems';");
1240     print "Upgrade to $DBversion done (IMPORTANT: Upgrading to Amazon.com Associates Web Service 4.0 ) \n";
1241     SetVersion ($DBversion);
1242 }
1243
1244 $DBversion = "3.00.00.065";
1245 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1246     $dbh->do("CREATE TABLE `patroncards` (
1247                 `cardid` int(11) NOT NULL auto_increment,
1248                 `batch_id` varchar(10) NOT NULL default '1',
1249                 `borrowernumber` int(11) NOT NULL,
1250                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1251                 PRIMARY KEY  (`cardid`),
1252                 KEY `patroncards_ibfk_1` (`borrowernumber`),
1253                 CONSTRAINT `patroncards_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE
1254                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1255     print "Upgrade to $DBversion done (Adding patroncards table for patroncards generation feature. ) \n";
1256     SetVersion ($DBversion);
1257 }
1258
1259 $DBversion = "3.00.00.066";
1260 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1261     $dbh->do("ALTER TABLE `virtualshelfcontents` MODIFY `dateadded` timestamp NOT NULL
1262 DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP;
1263 ");
1264     print "Upgrade to $DBversion done (fix for bug 1873: virtualshelfcontents dateadded column empty. ) \n";
1265     SetVersion ($DBversion);
1266 }
1267
1268 $DBversion = "3.00.00.067";
1269 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1270     $dbh->do("UPDATE systempreferences SET explanation = 'Enable patron images for the Staff Client', type = 'YesNo' WHERE variable = 'patronimages'");
1271     print "Upgrade to $DBversion done (Updating patronimages syspref to reflect current kohastructure.sql. ) \n";
1272     SetVersion ($DBversion);
1273 }
1274
1275 $DBversion = "3.00.00.068";
1276 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1277     $dbh->do("CREATE TABLE `permissions` (
1278                 `module_bit` int(11) NOT NULL DEFAULT 0,
1279                 `code` varchar(30) DEFAULT NULL,
1280                 `description` varchar(255) DEFAULT NULL,
1281                 PRIMARY KEY  (`module_bit`, `code`),
1282                 CONSTRAINT `permissions_ibfk_1` FOREIGN KEY (`module_bit`) REFERENCES `userflags` (`bit`)
1283                     ON DELETE CASCADE ON UPDATE CASCADE
1284               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1285     $dbh->do("CREATE TABLE `user_permissions` (
1286                 `borrowernumber` int(11) NOT NULL DEFAULT 0,
1287                 `module_bit` int(11) NOT NULL DEFAULT 0,
1288                 `code` varchar(30) DEFAULT NULL,
1289                 CONSTRAINT `user_permissions_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1290                     ON DELETE CASCADE ON UPDATE CASCADE,
1291                 CONSTRAINT `user_permissions_ibfk_2` FOREIGN KEY (`module_bit`, `code`)
1292                     REFERENCES `permissions` (`module_bit`, `code`)
1293                     ON DELETE CASCADE ON UPDATE CASCADE
1294               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1295
1296     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
1297     (13, 'edit_news', 'Write news for the OPAC and staff interfaces'),
1298     (13, 'label_creator', 'Create printable labels and barcodes from catalog and patron data'),
1299     (13, 'edit_calendar', 'Define days when the library is closed'),
1300     (13, 'moderate_comments', 'Moderate patron comments'),
1301     (13, 'edit_notices', 'Define notices'),
1302     (13, 'edit_notice_status_triggers', 'Set notice/status triggers for overdue items'),
1303     (13, 'view_system_logs', 'Browse the system logs'),
1304     (13, 'inventory', 'Perform inventory (stocktaking) of your catalogue'),
1305     (13, 'stage_marc_import', 'Stage MARC records into the reservoir'),
1306     (13, 'manage_staged_marc', 'Managed staged MARC records, including completing and reversing imports'),
1307     (13, 'export_catalog', 'Export bibliographic and holdings data'),
1308     (13, 'import_patrons', 'Import patron data'),
1309     (13, 'delete_anonymize_patrons', 'Delete old borrowers and anonymize circulation history (deletes borrower reading history)'),
1310     (13, 'batch_upload_patron_images', 'Upload patron images in batch or one at a time'),
1311     (13, 'schedule_tasks', 'Schedule tasks to run')");
1312
1313     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('GranularPermissions','0','Use detailed staff user permissions',NULL,'YesNo')");
1314
1315     print "Upgrade to $DBversion done (adding permissions and user_permissions tables and GranularPermissions syspref) \n";
1316     SetVersion ($DBversion);
1317 }
1318 $DBversion = "3.00.00.069";
1319 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1320     $dbh->do("ALTER TABLE labels_conf CHANGE COLUMN class classification int(1) DEFAULT NULL;");
1321         print "Upgrade to $DBversion done ( Correcting columname in labels_conf )\n";
1322     SetVersion ($DBversion);
1323 }
1324
1325 $DBversion = "3.00.00.070";
1326 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1327     $sth = $dbh->prepare("SELECT value FROM systempreferences WHERE variable='yuipath'");
1328     $sth->execute;
1329     my ($value) = $sth->fetchrow;
1330     $value =~ s/2.3.1/2.5.1/;
1331     $dbh->do("UPDATE systempreferences SET value='$value' WHERE variable='yuipath';");
1332         print "Update yuipath syspref to 2.5.1 if necessary\n";
1333     SetVersion ($DBversion);
1334 }
1335
1336 $DBversion = "3.00.00.071";
1337 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1338     $dbh->do(" ALTER TABLE `subscription` ADD `serialsadditems` TINYINT( 1 ) NOT NULL DEFAULT '0';");
1339     # fill the new field with the previous systempreference value, then drop the syspref
1340     my $sth = $dbh->prepare("SELECT value FROM systempreferences WHERE variable='serialsadditems'");
1341     $sth->execute;
1342     my ($serialsadditems) = $sth->fetchrow();
1343     $dbh->do("UPDATE subscription SET serialsadditems=$serialsadditems");
1344     $dbh->do("DELETE FROM systempreferences WHERE variable='serialsadditems'");
1345     print "Upgrade to $DBversion done ( moving serialsadditems from syspref to subscription )\n";
1346     SetVersion ($DBversion);
1347 }
1348
1349 $DBversion = "3.00.00.072";
1350 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1351     $dbh->do("ALTER TABLE labels_conf ADD COLUMN formatstring mediumtext DEFAULT NULL AFTER printingtype");
1352         print "Upgrade to $DBversion done ( Adding format string to labels generator. )\n";
1353     SetVersion ($DBversion);
1354 }
1355
1356 $DBversion = "3.00.00.073";
1357 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1358         $dbh->do("DROP TABLE IF EXISTS `tags_all`;");
1359         $dbh->do(q#
1360         CREATE TABLE `tags_all` (
1361           `tag_id`         int(11) NOT NULL auto_increment,
1362           `borrowernumber` int(11) NOT NULL,
1363           `biblionumber`   int(11) NOT NULL,
1364           `term`      varchar(255) NOT NULL,
1365           `language`       int(4) default NULL,
1366           `date_created` datetime  NOT NULL,
1367           PRIMARY KEY  (`tag_id`),
1368           KEY `tags_borrowers_fk_1` (`borrowernumber`),
1369           KEY `tags_biblionumber_fk_1` (`biblionumber`),
1370           CONSTRAINT `tags_borrowers_fk_1` FOREIGN KEY (`borrowernumber`)
1371                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1372           CONSTRAINT `tags_biblionumber_fk_1` FOREIGN KEY (`biblionumber`)
1373                 REFERENCES `biblio`     (`biblionumber`)  ON DELETE CASCADE ON UPDATE CASCADE
1374         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1375         #);
1376         $dbh->do("DROP TABLE IF EXISTS `tags_approval`;");
1377         $dbh->do(q#
1378         CREATE TABLE `tags_approval` (
1379           `term`   varchar(255) NOT NULL,
1380           `approved`     int(1) NOT NULL default '0',
1381           `date_approved` datetime       default NULL,
1382           `approved_by` int(11)          default NULL,
1383           `weight_total` int(9) NOT NULL default '1',
1384           PRIMARY KEY  (`term`),
1385           KEY `tags_approval_borrowers_fk_1` (`approved_by`),
1386           CONSTRAINT `tags_approval_borrowers_fk_1` FOREIGN KEY (`approved_by`)
1387                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE
1388         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1389         #);
1390         $dbh->do("DROP TABLE IF EXISTS `tags_index`;");
1391         $dbh->do(q#
1392         CREATE TABLE `tags_index` (
1393           `term`    varchar(255) NOT NULL,
1394           `biblionumber` int(11) NOT NULL,
1395           `weight`        int(9) NOT NULL default '1',
1396           PRIMARY KEY  (`term`,`biblionumber`),
1397           KEY `tags_index_biblionumber_fk_1` (`biblionumber`),
1398           CONSTRAINT `tags_index_term_fk_1` FOREIGN KEY (`term`)
1399                 REFERENCES `tags_approval` (`term`)  ON DELETE CASCADE ON UPDATE CASCADE,
1400           CONSTRAINT `tags_index_biblionumber_fk_1` FOREIGN KEY (`biblionumber`)
1401                 REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
1402         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1403         #);
1404         $dbh->do(q#
1405         INSERT INTO `systempreferences` VALUES
1406                 ('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=',''),
1407                 ('BakerTaylorEnabled','0','','Enable or disable all Baker & Taylor features.','YesNo'),
1408                 ('BakerTaylorPassword','','','Baker & Taylor Password for Content Cafe (external content)','Textarea'),
1409                 ('BakerTaylorUsername','','','Baker & Taylor Username for Content Cafe (external content)','Textarea'),
1410                 ('TagsEnabled','1','','Enables or disables all tagging features.  This is the main switch for tags.','YesNo'),
1411                 ('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.',''),
1412                 ('TagsInputOnDetail','1','','Allow users to input tags from the detail page.',         'YesNo'),
1413                 ('TagsInputOnList',  '0','','Allow users to input tags from the search results list.', 'YesNo'),
1414                 ('TagsModeration',  NULL,'','Require tags from patrons to be approved before becoming visible.','YesNo'),
1415                 ('TagsShowOnDetail','10','','Number of tags to display on detail page.  0 is off.',        'Integer'),
1416                 ('TagsShowOnList',   '6','','Number of tags to display on search results list.  0 is off.','Integer')
1417         #);
1418         print "Upgrade to $DBversion done (Baker/Taylor,Tags: sysprefs and tables (tags_all, tags_index, tags_approval)) \n";
1419         SetVersion ($DBversion);
1420 }
1421
1422 $DBversion = "3.00.00.074";
1423 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1424     $dbh->do( q(update itemtypes set imageurl = concat( 'npl/', imageurl )
1425                   where imageurl not like 'http%'
1426                     and imageurl is not NULL
1427                     and imageurl != '') );
1428     print "Upgrade to $DBversion done (updating imagetype.imageurls to reflect new icon locations.)\n";
1429     SetVersion ($DBversion);
1430 }
1431
1432 $DBversion = "3.00.00.075";
1433 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1434     $dbh->do( q(alter table authorised_values add imageurl varchar(200) default NULL) );
1435     print "Upgrade to $DBversion done (adding imageurl field to authorised_values table)\n";
1436     SetVersion ($DBversion);
1437 }
1438
1439 $DBversion = "3.00.00.076";
1440 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1441     $dbh->do("ALTER TABLE import_batches
1442               ADD COLUMN nomatch_action enum('create_new', 'ignore') NOT NULL default 'create_new' AFTER overlay_action");
1443     $dbh->do("ALTER TABLE import_batches
1444               ADD COLUMN item_action enum('always_add', 'add_only_for_matches', 'add_only_for_new', 'ignore')
1445                   NOT NULL default 'always_add' AFTER nomatch_action");
1446     $dbh->do("ALTER TABLE import_batches
1447               MODIFY overlay_action  enum('replace', 'create_new', 'use_template', 'ignore')
1448                   NOT NULL default 'create_new'");
1449     $dbh->do("ALTER TABLE import_records
1450               MODIFY status  enum('error', 'staged', 'imported', 'reverted', 'items_reverted',
1451                                   'ignored') NOT NULL default 'staged'");
1452     $dbh->do("ALTER TABLE import_items
1453               MODIFY status enum('error', 'staged', 'imported', 'reverted', 'ignored') NOT NULL default 'staged'");
1454
1455         print "Upgrade to $DBversion done (changes to import_batches and import_records)\n";
1456         SetVersion ($DBversion);
1457 }
1458
1459 $DBversion = "3.00.00.077";
1460 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1461     # drop these tables only if they exist and none of them are empty
1462     # these tables are not defined in the packaged 2.2.9, but since it is believed
1463     # that at least one library may be using them in a post-2.2.9 but pre-3.0 Koha,
1464     # some care is taken.
1465     my ($print_error) = $dbh->{PrintError};
1466     $dbh->{PrintError} = 0;
1467     my ($raise_error) = $dbh->{RaiseError};
1468     $dbh->{RaiseError} = 1;
1469
1470     my $count = 0;
1471     my $do_drop = 1;
1472     eval { $count = $dbh->do("SELECT 1 FROM categorytable"); };
1473     if ($count > 0) {
1474         $do_drop = 0;
1475     }
1476     eval { $count = $dbh->do("SELECT 1 FROM mediatypetable"); };
1477     if ($count > 0) {
1478         $do_drop = 0;
1479     }
1480     eval { $count = $dbh->do("SELECT 1 FROM subcategorytable"); };
1481     if ($count > 0) {
1482         $do_drop = 0;
1483     }
1484
1485     if ($do_drop) {
1486         $dbh->do("DROP TABLE IF EXISTS `categorytable`");
1487         $dbh->do("DROP TABLE IF EXISTS `mediatypetable`");
1488         $dbh->do("DROP TABLE IF EXISTS `subcategorytable`");
1489     }
1490
1491     $dbh->{PrintError} = $print_error;
1492     $dbh->{RaiseError} = $raise_error;
1493         print "Upgrade to $DBversion done (drop categorytable, subcategorytable, and mediatypetable)\n";
1494         SetVersion ($DBversion);
1495 }
1496
1497 $DBversion = "3.00.00.078";
1498 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1499     my ($print_error) = $dbh->{PrintError};
1500     $dbh->{PrintError} = 0;
1501
1502     unless ($dbh->do("SELECT 1 FROM browser")) {
1503         $dbh->{PrintError} = $print_error;
1504         $dbh->do("CREATE TABLE `browser` (
1505                     `level` int(11) NOT NULL,
1506                     `classification` varchar(20) NOT NULL,
1507                     `description` varchar(255) NOT NULL,
1508                     `number` bigint(20) NOT NULL,
1509                     `endnode` tinyint(4) NOT NULL
1510                   ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1511     }
1512     $dbh->{PrintError} = $print_error;
1513         print "Upgrade to $DBversion done (add browser table if not already present)\n";
1514         SetVersion ($DBversion);
1515 }
1516
1517 $DBversion = "3.00.00.079";
1518 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1519  my ($print_error) = $dbh->{PrintError};
1520     $dbh->{PrintError} = 0;
1521
1522     $dbh->do("INSERT INTO `systempreferences` (variable, value,options,type, explanation)VALUES
1523         ('AddPatronLists','categorycode','categorycode|category_type','Choice','Allow user to choose what list to pick up from when adding patrons')");
1524     print "Upgrade to $DBversion done (add browser table if not already present)\n";
1525         SetVersion ($DBversion);
1526 }
1527
1528 $DBversion = "3.00.00.080";
1529 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1530     $dbh->do("ALTER TABLE subscription CHANGE monthlength monthlength int(11) default '0'");
1531     $dbh->do("ALTER TABLE deleteditems MODIFY marc LONGBLOB AFTER copynumber");
1532     $dbh->do("ALTER TABLE aqbooksellers CHANGE name name mediumtext NOT NULL");
1533         print "Upgrade to $DBversion done (catch up on DB schema changes since alpha and beta)\n";
1534         SetVersion ($DBversion);
1535 }
1536
1537 $DBversion = "3.00.00.081";
1538 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1539     $dbh->do("CREATE TABLE `borrower_attribute_types` (
1540                 `code` varchar(10) NOT NULL,
1541                 `description` varchar(255) NOT NULL,
1542                 `repeatable` tinyint(1) NOT NULL default 0,
1543                 `unique_id` tinyint(1) NOT NULL default 0,
1544                 `opac_display` tinyint(1) NOT NULL default 0,
1545                 `password_allowed` tinyint(1) NOT NULL default 0,
1546                 `staff_searchable` tinyint(1) NOT NULL default 0,
1547                 `authorised_value_category` varchar(10) default NULL,
1548                 PRIMARY KEY  (`code`)
1549               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1550     $dbh->do("CREATE TABLE `borrower_attributes` (
1551                 `borrowernumber` int(11) NOT NULL,
1552                 `code` varchar(10) NOT NULL,
1553                 `attribute` varchar(30) default NULL,
1554                 `password` varchar(30) default NULL,
1555                 KEY `borrowernumber` (`borrowernumber`),
1556                 KEY `code_attribute` (`code`, `attribute`),
1557                 CONSTRAINT `borrower_attributes_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1558                     ON DELETE CASCADE ON UPDATE CASCADE,
1559                 CONSTRAINT `borrower_attributes_ibfk_2` FOREIGN KEY (`code`) REFERENCES `borrower_attribute_types` (`code`)
1560                     ON DELETE CASCADE ON UPDATE CASCADE
1561             ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1562     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('ExtendedPatronAttributes','0','Use extended patron IDs and attributes',NULL,'YesNo')");
1563     print "Upgrade to $DBversion done (added borrower_attributes and  borrower_attribute_types)\n";
1564  SetVersion ($DBversion);
1565 }
1566
1567 $DBversion = "3.00.00.082";
1568 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1569     $dbh->do( q(alter table accountlines add column lastincrement decimal(28,6) default NULL) );
1570     print "Upgrade to $DBversion done (adding lastincrement column to accountlines table)\n";
1571     SetVersion ($DBversion);
1572 }
1573
1574 $DBversion = "3.00.00.083";
1575 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1576     $dbh->do( qq(UPDATE systempreferences SET value='local' where variable='yuipath' and value like "%/intranet-tmpl/prog/%"));
1577     print "Upgrade to $DBversion done (Changing yuipath behaviour in managing a local value)\n";
1578     SetVersion ($DBversion);
1579 }
1580 $DBversion = "3.00.00.084";
1581     if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1582     $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')");
1583     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('GoogleJackets','0','if ON, displays jacket covers from Google Books API',NULL,'YesNo')");
1584     print "Upgrade to $DBversion done (add new sysprefs)\n";
1585     SetVersion ($DBversion);
1586 }
1587
1588 $DBversion = "3.00.00.085";
1589 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1590     if (C4::Context->preference("marcflavour") eq 'MARC21') {
1591         $dbh->do("UPDATE marc_subfield_structure SET tab = 0 WHERE tab =  9 AND tagfield = '037'");
1592         $dbh->do("UPDATE marc_subfield_structure SET tab = 1 WHERE tab =  6 AND tagfield in ('100', '110', '111', '130')");
1593         $dbh->do("UPDATE marc_subfield_structure SET tab = 2 WHERE tab =  6 AND tagfield in ('240', '243')");
1594         $dbh->do("UPDATE marc_subfield_structure SET tab = 4 WHERE tab =  6 AND tagfield in ('400', '410', '411', '440')");
1595         $dbh->do("UPDATE marc_subfield_structure SET tab = 5 WHERE tab =  9 AND tagfield = '584'");
1596         $dbh->do("UPDATE marc_subfield_structure SET tab = 7 WHERE tab = -6 AND tagfield = '760'");
1597     }
1598     print "Upgrade to $DBversion done (move editing tab of various MARC21 subfields)\n";
1599     SetVersion ($DBversion);
1600 }
1601
1602 $DBversion = "3.00.00.086";
1603 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1604         $dbh->do(
1605         "CREATE TABLE `tmp_holdsqueue` (
1606         `biblionumber` int(11) default NULL,
1607         `itemnumber` int(11) default NULL,
1608         `barcode` varchar(20) default NULL,
1609         `surname` mediumtext NOT NULL,
1610         `firstname` text,
1611         `phone` text,
1612         `borrowernumber` int(11) NOT NULL,
1613         `cardnumber` varchar(16) default NULL,
1614         `reservedate` date default NULL,
1615         `title` mediumtext,
1616         `itemcallnumber` varchar(30) default NULL,
1617         `holdingbranch` varchar(10) default NULL,
1618         `pickbranch` varchar(10) default NULL,
1619         `notes` text
1620         ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1621
1622         $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')");
1623         $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')");
1624
1625         print "Upgrade to $DBversion done (Table structure for table `tmp_holdsqueue`)\n";
1626         SetVersion ($DBversion);
1627 }
1628
1629 $DBversion = "3.00.00.087";
1630 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1631     $dbh->do("INSERT INTO `systempreferences` VALUES ('AutoEmailOpacUser','0','','Sends notification emails containing new account details to patrons - when account is created.','YesNo')" );
1632     $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')");
1633     print "Upgrade to $DBversion done (added 2 new 'AutoEmailOpacUser' sysprefs)\n";
1634     SetVersion ($DBversion);
1635 }
1636
1637 $DBversion = "3.00.00.088";
1638 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1639         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('OPACShelfBrowser','1','','Enable/disable Shelf Browser on item details page','YesNo')");
1640         $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')");
1641         $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')");
1642         $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')");
1643         print "Upgrade to $DBversion done (added 2 new 'AutoEmailOpacUser' sysprefs)\n";
1644     SetVersion ($DBversion);
1645 }
1646
1647 $DBversion = "3.00.00.089";
1648 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1649         $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')");
1650         print "Upgrade to $DBversion done (added new AdvancedSearchTypes syspref)\n";
1651     SetVersion ($DBversion);
1652 }
1653
1654 $DBversion = "3.00.00.090";
1655 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1656     $dbh->do("
1657         CREATE TABLE `branch_borrower_circ_rules` (
1658           `branchcode` VARCHAR(10) NOT NULL,
1659           `categorycode` VARCHAR(10) NOT NULL,
1660           `maxissueqty` int(4) default NULL,
1661           PRIMARY KEY (`categorycode`, `branchcode`),
1662           CONSTRAINT `branch_borrower_circ_rules_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
1663             ON DELETE CASCADE ON UPDATE CASCADE,
1664           CONSTRAINT `branch_borrower_circ_rules_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`)
1665             ON DELETE CASCADE ON UPDATE CASCADE
1666         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1667     ");
1668     $dbh->do("
1669         CREATE TABLE `default_borrower_circ_rules` (
1670           `categorycode` VARCHAR(10) NOT NULL,
1671           `maxissueqty` int(4) default NULL,
1672           PRIMARY KEY (`categorycode`),
1673           CONSTRAINT `borrower_borrower_circ_rules_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
1674             ON DELETE CASCADE ON UPDATE CASCADE
1675         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1676     ");
1677     $dbh->do("
1678         CREATE TABLE `default_branch_circ_rules` (
1679           `branchcode` VARCHAR(10) NOT NULL,
1680           `maxissueqty` int(4) default NULL,
1681           PRIMARY KEY (`branchcode`),
1682           CONSTRAINT `default_branch_circ_rules_ibfk_1` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`)
1683             ON DELETE CASCADE ON UPDATE CASCADE
1684         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1685     ");
1686     $dbh->do("
1687         CREATE TABLE `default_circ_rules` (
1688             `singleton` enum('singleton') NOT NULL default 'singleton',
1689             `maxissueqty` int(4) default NULL,
1690             PRIMARY KEY (`singleton`)
1691         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1692     ");
1693     print "Upgrade to $DBversion done (added several circ rules tables)\n";
1694     SetVersion ($DBversion);
1695 }
1696
1697
1698 $DBversion = "3.00.00.091";
1699 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1700     $dbh->do(<<'END_SQL');
1701 ALTER TABLE borrowers
1702 ADD `smsalertnumber` varchar(50) default NULL
1703 END_SQL
1704
1705     $dbh->do(<<'END_SQL');
1706 CREATE TABLE `message_attributes` (
1707   `message_attribute_id` int(11) NOT NULL auto_increment,
1708   `message_name` varchar(20) NOT NULL default '',
1709   `takes_days` tinyint(1) NOT NULL default '0',
1710   PRIMARY KEY  (`message_attribute_id`),
1711   UNIQUE KEY `message_name` (`message_name`)
1712 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1713 END_SQL
1714
1715     $dbh->do(<<'END_SQL');
1716 CREATE TABLE `message_transport_types` (
1717   `message_transport_type` varchar(20) NOT NULL,
1718   PRIMARY KEY  (`message_transport_type`)
1719 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1720 END_SQL
1721
1722     $dbh->do(<<'END_SQL');
1723 CREATE TABLE `message_transports` (
1724   `message_attribute_id` int(11) NOT NULL,
1725   `message_transport_type` varchar(20) NOT NULL,
1726   `is_digest` tinyint(1) NOT NULL default '0',
1727   `letter_module` varchar(20) NOT NULL default '',
1728   `letter_code` varchar(20) NOT NULL default '',
1729   PRIMARY KEY  (`message_attribute_id`,`message_transport_type`,`is_digest`),
1730   KEY `message_transport_type` (`message_transport_type`),
1731   KEY `letter_module` (`letter_module`,`letter_code`),
1732   CONSTRAINT `message_transports_ibfk_1` FOREIGN KEY (`message_attribute_id`) REFERENCES `message_attributes` (`message_attribute_id`) ON DELETE CASCADE ON UPDATE CASCADE,
1733   CONSTRAINT `message_transports_ibfk_2` FOREIGN KEY (`message_transport_type`) REFERENCES `message_transport_types` (`message_transport_type`) ON DELETE CASCADE ON UPDATE CASCADE,
1734   CONSTRAINT `message_transports_ibfk_3` FOREIGN KEY (`letter_module`, `letter_code`) REFERENCES `letter` (`module`, `code`) ON DELETE CASCADE ON UPDATE CASCADE
1735 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1736 END_SQL
1737
1738     $dbh->do(<<'END_SQL');
1739 CREATE TABLE `borrower_message_preferences` (
1740   `borrower_message_preference_id` int(11) NOT NULL auto_increment,
1741   `borrowernumber` int(11) NOT NULL default '0',
1742   `message_attribute_id` int(11) default '0',
1743   `days_in_advance` int(11) default '0',
1744   `wants_digets` tinyint(1) NOT NULL default '0',
1745   PRIMARY KEY  (`borrower_message_preference_id`),
1746   KEY `borrowernumber` (`borrowernumber`),
1747   KEY `message_attribute_id` (`message_attribute_id`),
1748   CONSTRAINT `borrower_message_preferences_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1749   CONSTRAINT `borrower_message_preferences_ibfk_2` FOREIGN KEY (`message_attribute_id`) REFERENCES `message_attributes` (`message_attribute_id`) ON DELETE CASCADE ON UPDATE CASCADE
1750 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1751 END_SQL
1752
1753     $dbh->do(<<'END_SQL');
1754 CREATE TABLE `borrower_message_transport_preferences` (
1755   `borrower_message_preference_id` int(11) NOT NULL default '0',
1756   `message_transport_type` varchar(20) NOT NULL default '0',
1757   PRIMARY KEY  (`borrower_message_preference_id`,`message_transport_type`),
1758   KEY `message_transport_type` (`message_transport_type`),
1759   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,
1760   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
1761 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1762 END_SQL
1763
1764     $dbh->do(<<'END_SQL');
1765 CREATE TABLE `message_queue` (
1766   `message_id` int(11) NOT NULL auto_increment,
1767   `borrowernumber` int(11) NOT NULL,
1768   `subject` text,
1769   `content` text,
1770   `message_transport_type` varchar(20) NOT NULL,
1771   `status` enum('sent','pending','failed','deleted') NOT NULL default 'pending',
1772   `time_queued` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1773   KEY `message_id` (`message_id`),
1774   KEY `borrowernumber` (`borrowernumber`),
1775   KEY `message_transport_type` (`message_transport_type`),
1776   CONSTRAINT `messageq_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1777   CONSTRAINT `messageq_ibfk_2` FOREIGN KEY (`message_transport_type`) REFERENCES `message_transport_types` (`message_transport_type`) ON DELETE RESTRICT ON UPDATE CASCADE
1778 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1779 END_SQL
1780
1781     $dbh->do(<<'END_SQL');
1782 INSERT INTO `systempreferences`
1783   (variable,value,explanation,options,type)
1784 VALUES
1785 ('EnhancedMessagingPreferences',0,'If ON, allows patrons to select to receive additional messages about items due or nearly due.','','YesNo')
1786 END_SQL
1787
1788     $dbh->do( <<'END_SQL');
1789 INSERT INTO `letter`
1790 (module, code, name, title, content)
1791 VALUES
1792 ('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>>'),
1793 ('circulation','DUEDGST','Item Due Reminder (Digest)','Item Due Reminder','You have <<count>> items due'),
1794 ('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>>'),
1795 ('circulation','PREDUEDGST','Advance Notice of Item Due (Digest)','Advance Notice of Item Due','You have <<count>> items due soon'),
1796 ('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.');
1797 END_SQL
1798
1799     my @sql_scripts = (
1800         'installer/data/mysql/en/mandatory/message_transport_types.sql',
1801         'installer/data/mysql/en/optional/sample_notices_message_attributes.sql',
1802         'installer/data/mysql/en/optional/sample_notices_message_transports.sql',
1803     );
1804
1805     my $installer = C4::Installer->new();
1806     foreach my $script ( @sql_scripts ) {
1807         my $full_path = $installer->get_file_path_from_name($script);
1808         my $error = $installer->load_sql($full_path);
1809         warn $error if $error;
1810     }
1811
1812     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";
1813     SetVersion ($DBversion);
1814 }
1815
1816 $DBversion = "3.00.00.092";
1817 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1818     $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')");
1819     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES('AllowHoldsOnDamagedItems', '1', '', 'Allow hold requests to be placed on damaged items', 'YesNo')");
1820         print "Upgrade to $DBversion done (added new AllowOnShelfHolds syspref)\n";
1821     SetVersion ($DBversion);
1822 }
1823
1824 $DBversion = "3.00.00.093";
1825 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1826     $dbh->do("ALTER TABLE `items` MODIFY COLUMN `copynumber` VARCHAR(32) DEFAULT NULL");
1827     $dbh->do("ALTER TABLE `deleteditems` MODIFY COLUMN `copynumber` VARCHAR(32) DEFAULT NULL");
1828         print "Upgrade to $DBversion done (Change data type of items.copynumber to allow free text)\n";
1829     SetVersion ($DBversion);
1830 }
1831
1832 $DBversion = "3.00.00.094";
1833 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1834     $dbh->do("ALTER TABLE `marc_subfield_structure` MODIFY `tagsubfield` VARCHAR(1) NOT NULL DEFAULT '' COLLATE utf8_bin");
1835         print "Upgrade to $DBversion done (Change Collation of marc_subfield_structure to allow mixed case in subfield labels.)\n";
1836     SetVersion ($DBversion);
1837 }
1838
1839 $DBversion = "3.00.00.095";
1840 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1841     if (C4::Context->preference("marcflavour") eq 'MARC21') {
1842         $dbh->do("UPDATE marc_subfield_structure SET authtypecode = 'MEETI_NAME' WHERE authtypecode = 'Meeting Name'");
1843         $dbh->do("UPDATE marc_subfield_structure SET authtypecode = 'CORPO_NAME' WHERE authtypecode = 'CORP0_NAME'");
1844     }
1845         print "Upgrade to $DBversion done (fix invalid authority types in MARC21 frameworks [bug 2254])\n";
1846     SetVersion ($DBversion);
1847 }
1848
1849 $DBversion = "3.00.00.096";
1850 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1851     $sth = $dbh->prepare("SHOW COLUMNS FROM borrower_message_preferences LIKE 'wants_digets'");
1852     $sth->execute();
1853     if (my $row = $sth->fetchrow_hashref) {
1854         $dbh->do("ALTER TABLE borrower_message_preferences CHANGE wants_digets wants_digest tinyint(1) NOT NULL default 0");
1855     }
1856         print "Upgrade to $DBversion done (fix name borrower_message_preferences.wants_digest)\n";
1857     SetVersion ($DBversion);
1858 }
1859
1860 $DBversion = '3.00.00.097';
1861 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1862
1863     $dbh->do('ALTER TABLE message_queue ADD to_address   mediumtext default NULL');
1864     $dbh->do('ALTER TABLE message_queue ADD from_address mediumtext default NULL');
1865     $dbh->do('ALTER TABLE message_queue ADD content_type text');
1866     $dbh->do('ALTER TABLE message_queue CHANGE borrowernumber borrowernumber int(11) default NULL');
1867
1868     print "Upgrade to $DBversion done (updating 4 fields in message_queue table)\n";
1869     SetVersion($DBversion);
1870 }
1871
1872 $DBversion = '3.00.00.098';
1873 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1874
1875     $dbh->do(q(DELETE FROM message_transport_types WHERE message_transport_type = 'rss'));
1876     $dbh->do(q(DELETE FROM message_transports WHERE message_transport_type = 'rss'));
1877
1878     print "Upgrade to $DBversion done (removing unused RSS message_transport_type)\n";
1879     SetVersion($DBversion);
1880 }
1881
1882 $DBversion = '3.00.00.099';
1883 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1884     $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')");
1885     print "Upgrade to $DBversion done (Adding OpacSuppression syspref)\n";
1886     SetVersion($DBversion);
1887 }
1888
1889 $DBversion = '3.00.00.100';
1890 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1891         $dbh->do('ALTER TABLE virtualshelves ADD COLUMN lastmodified timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP');
1892     print "Upgrade to $DBversion done (Adding lastmodified column to virtualshelves)\n";
1893     SetVersion($DBversion);
1894 }
1895
1896 $DBversion = '3.00.00.101';
1897 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1898         $dbh->do('ALTER TABLE `overduerules` CHANGE `categorycode` `categorycode` VARCHAR(10) NOT NULL');
1899         $dbh->do('ALTER TABLE `deletedborrowers` CHANGE `categorycode` `categorycode` VARCHAR(10) NOT NULL');
1900     print "Upgrade to $DBversion done (Updating columnd definitions for patron category codes in notice/statsu triggers and deletedborrowers tables.)\n";
1901     SetVersion($DBversion);
1902 }
1903
1904 $DBversion = '3.00.00.102';
1905 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1906         $dbh->do('ALTER TABLE serialitems MODIFY `serialid` int(11) NOT NULL AFTER itemnumber' );
1907         $dbh->do('ALTER TABLE serialitems DROP KEY serialididx' );
1908         $dbh->do('ALTER TABLE serialitems ADD CONSTRAINT UNIQUE KEY serialitemsidx (itemnumber)' );
1909         # before setting constraint, delete any unvalid data
1910         $dbh->do('DELETE from serialitems WHERE serialid not in (SELECT serial.serialid FROM serial)');
1911         $dbh->do('ALTER TABLE serialitems ADD CONSTRAINT serialitems_sfk_1 FOREIGN KEY (serialid) REFERENCES serial (serialid) ON DELETE CASCADE ON UPDATE CASCADE' );
1912     print "Upgrade to $DBversion done (Updating serialitems table to allow for multiple items per serial fixing kohabug 2380)\n";
1913     SetVersion($DBversion);
1914 }
1915
1916 $DBversion = "3.00.00.103";
1917 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1918     $dbh->do("DELETE FROM systempreferences WHERE variable='serialsadditems'");
1919     print "Upgrade to $DBversion done ( Verifying the removal of serialsadditems from syspref fixing kohabug 2219)\n";
1920     SetVersion ($DBversion);
1921 }
1922
1923 $DBversion = "3.00.00.104";
1924 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1925     $dbh->do("DELETE FROM systempreferences WHERE variable='noOPACHolds'");
1926     print "Upgrade to $DBversion done (remove superseded 'noOPACHolds' system preference per bug 2413)\n";
1927     SetVersion ($DBversion);
1928 }
1929
1930 $DBversion = '3.00.00.105';
1931 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
1932
1933     # it is possible that this syspref is already defined since the feature was added some time ago.
1934     unless ( $dbh->do(q(SELECT variable FROM systempreferences WHERE variable = 'SMSSendDriver')) ) {
1935         $dbh->do(<<'END_SQL');
1936 INSERT INTO `systempreferences`
1937   (variable,value,explanation,options,type)
1938 VALUES
1939 ('SMSSendDriver','','Sets which SMS::Send driver is used to send SMS messages.','','free')
1940 END_SQL
1941     }
1942     print "Upgrade to $DBversion done (added SMSSendDriver system preference)\n";
1943     SetVersion($DBversion);
1944 }
1945
1946 $DBversion = "3.00.00.106";
1947 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1948     $dbh->do("DELETE FROM systempreferences WHERE variable='noOPACHolds'");
1949
1950 # db revision 105 didn't apply correctly, so we're rolling this into 106
1951         $dbh->do("INSERT INTO `systempreferences`
1952    (variable,value,explanation,options,type)
1953         VALUES
1954         ('SMSSendDriver','','Sets which SMS::Send driver is used to send SMS messages.','','free')");
1955
1956     print "Upgrade to $DBversion done (remove default '0000-00-00' in subscriptionhistory.enddate field)\n";
1957     $dbh->do("ALTER TABLE `subscriptionhistory` CHANGE `enddate` `enddate` DATE NULL DEFAULT NULL ");
1958     $dbh->do("UPDATE subscriptionhistory SET enddate=NULL WHERE enddate='0000-00-00'");
1959     SetVersion ($DBversion);
1960 }
1961
1962 $DBversion = '3.00.00.107';
1963 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1964     $dbh->do(<<'END_SQL');
1965 UPDATE systempreferences
1966   SET explanation = CONCAT( explanation, '. WARNING: this feature is very resource consuming on collections with large numbers of items.' )
1967   WHERE variable = 'OPACShelfBrowser'
1968     AND explanation NOT LIKE '%WARNING%'
1969 END_SQL
1970     $dbh->do(<<'END_SQL');
1971 UPDATE systempreferences
1972   SET explanation = CONCAT( explanation, '. WARNING: this feature is very resource consuming.' )
1973   WHERE variable = 'CataloguingLog'
1974     AND explanation NOT LIKE '%WARNING%'
1975 END_SQL
1976     $dbh->do(<<'END_SQL');
1977 UPDATE systempreferences
1978   SET explanation = CONCAT( explanation, '. WARNING: using NoZebra on even modest sized collections is very slow.' )
1979   WHERE variable = 'NoZebra'
1980     AND explanation NOT LIKE '%WARNING%'
1981 END_SQL
1982     print "Upgrade to $DBversion done (warning added to OPACShelfBrowser system preference)\n";
1983     SetVersion ($DBversion);
1984 }
1985
1986 $DBversion = '3.01.00.000';
1987 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1988     print "Upgrade to $DBversion done (start of 3.1)\n";
1989     SetVersion ($DBversion);
1990 }
1991
1992 $DBversion = '3.01.00.001';
1993 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1994     $dbh->do("
1995         CREATE TABLE hold_fill_targets (
1996             `borrowernumber` int(11) NOT NULL,
1997             `biblionumber` int(11) NOT NULL,
1998             `itemnumber` int(11) NOT NULL,
1999             `source_branchcode`  varchar(10) default NULL,
2000             `item_level_request` tinyint(4) NOT NULL default 0,
2001             PRIMARY KEY `itemnumber` (`itemnumber`),
2002             KEY `bib_branch` (`biblionumber`, `source_branchcode`),
2003             CONSTRAINT `hold_fill_targets_ibfk_1` FOREIGN KEY (`borrowernumber`)
2004                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
2005             CONSTRAINT `hold_fill_targets_ibfk_2` FOREIGN KEY (`biblionumber`)
2006                 REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
2007             CONSTRAINT `hold_fill_targets_ibfk_3` FOREIGN KEY (`itemnumber`)
2008                 REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
2009             CONSTRAINT `hold_fill_targets_ibfk_4` FOREIGN KEY (`source_branchcode`)
2010                 REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
2011         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2012     ");
2013     $dbh->do("
2014         ALTER TABLE tmp_holdsqueue
2015             ADD item_level_request tinyint(4) NOT NULL default 0
2016     ");
2017
2018     print "Upgrade to $DBversion done (add hold_fill_targets table and a column to tmp_holdsqueue)\n";
2019     SetVersion($DBversion);
2020 }
2021
2022 $DBversion = '3.01.00.002';
2023 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2024     # use statistics where available
2025     $dbh->do("
2026         ALTER TABLE statistics ADD KEY  tmp_stats (type, itemnumber, borrowernumber)
2027     ");
2028     $dbh->do("
2029         UPDATE issues iss
2030         SET issuedate = (
2031             SELECT max(datetime)
2032             FROM statistics
2033             WHERE type = 'issue'
2034             AND itemnumber = iss.itemnumber
2035             AND borrowernumber = iss.borrowernumber
2036         )
2037         WHERE issuedate IS NULL;
2038     ");
2039     $dbh->do("ALTER TABLE statistics DROP KEY tmp_stats");
2040
2041     # default to last renewal date
2042     $dbh->do("
2043         UPDATE issues
2044         SET issuedate = lastreneweddate
2045         WHERE issuedate IS NULL
2046         and lastreneweddate IS NOT NULL
2047     ");
2048
2049     my $num_bad_issuedates = $dbh->selectrow_array("SELECT COUNT(*) FROM issues WHERE issuedate IS NULL");
2050     if ($num_bad_issuedates > 0) {
2051         print STDERR "After the upgrade to $DBversion, there are still $num_bad_issuedates loan(s) with a NULL (blank) loan date. ",
2052                      "Please check the issues table in your database.";
2053     }
2054     print "Upgrade to $DBversion done (bug 2582: set null issues.issuedate to lastreneweddate)\n";
2055     SetVersion($DBversion);
2056 }
2057
2058 $DBversion = "3.01.00.003";
2059 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2060     $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')");
2061     print "Upgrade to $DBversion done (add new syspref)\n";
2062     SetVersion ($DBversion);
2063 }
2064
2065 $DBversion = '3.01.00.004';
2066 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2067     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACDisplayRequestPriority','0','Show patrons the priority level on holds in the OPAC','','YesNo')");
2068     print "Upgrade to $DBversion done (added OPACDisplayRequestPriority system preference)\n";
2069     SetVersion ($DBversion);
2070 }
2071
2072 $DBversion = '3.01.00.005';
2073 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2074     $dbh->do("
2075         INSERT INTO `letter` (module, code, name, title, content)
2076         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>>')
2077     ");
2078     $dbh->do("INSERT INTO `message_attributes` (message_attribute_id, message_name, takes_days) values(4, 'Hold Filled', 0)");
2079     $dbh->do("INSERT INTO `message_transports` (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) values(4, 'sms', 0, 'reserves', 'HOLD')");
2080     $dbh->do("INSERT INTO `message_transports` (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) values(4, 'email', 0, 'reserves', 'HOLD')");
2081     print "Upgrade to $DBversion done (Add letter for holds notifications)\n";
2082     SetVersion ($DBversion);
2083 }
2084
2085 $DBversion = '3.01.00.006';
2086 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2087     $dbh->do("ALTER TABLE `biblioitems` ADD KEY issn (issn)");
2088     print "Upgrade to $DBversion done (add index on biblioitems.issn)\n";
2089     SetVersion ($DBversion);
2090 }
2091
2092 $DBversion = "3.01.00.007";
2093 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2094     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='intranetmainUserblock'");
2095     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='intranetuserjs'");
2096     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='opacheader'");
2097     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='OpacMainUserBlock'");
2098     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='OpacNav'");
2099     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='opacuserjs'");
2100     $dbh->do("UPDATE `systempreferences` SET options='30|10', type='Textarea' WHERE variable='OAI-PMH:Set'");
2101     $dbh->do("UPDATE `systempreferences` SET options='50' WHERE variable='intranetstylesheet'");
2102     $dbh->do("UPDATE `systempreferences` SET options='50' WHERE variable='intranetcolorstylesheet'");
2103     $dbh->do("UPDATE `systempreferences` SET options='10' WHERE variable='globalDueDate'");
2104     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='numSearchResults'");
2105     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='OPACnumSearchResults'");
2106     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='ReservesMaxPickupDelay'");
2107     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='TransfersMaxDaysWarning'");
2108     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='StaticHoldsQueueWeight'");
2109     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='holdCancelLength'");
2110     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='XISBNDailyLimit'");
2111     $dbh->do("UPDATE `systempreferences` SET type='Float' WHERE variable='gist'");
2112     $dbh->do("UPDATE `systempreferences` SET type='Free' WHERE variable='BakerTaylorUsername'");
2113     $dbh->do("UPDATE `systempreferences` SET type='Free' WHERE variable='BakerTaylorPassword'");
2114     $dbh->do("UPDATE `systempreferences` SET type='Textarea', options='70|10' WHERE variable='ISBD'");
2115     $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'");
2116     print "Upgrade to $DBversion done (fix display of many sysprefs)\n";
2117     SetVersion ($DBversion);
2118 }
2119
2120 $DBversion = '3.01.00.008';
2121 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2122
2123     $dbh->do("CREATE TABLE branch_transfer_limits (
2124                           limitId int(8) NOT NULL auto_increment,
2125                           toBranch varchar(4) NOT NULL,
2126                           fromBranch varchar(4) NOT NULL,
2127                           itemtype varchar(4) NOT NULL,
2128                           PRIMARY KEY  (limitId)
2129                           ) ENGINE=InnoDB DEFAULT CHARSET=utf8"
2130                         );
2131
2132     $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')");
2133
2134     print "Upgrade to $DBversion done (added branch_transfer_limits table and UseBranchTransferLimits system preference)\n";
2135     SetVersion ($DBversion);
2136 }
2137
2138 $DBversion = "3.01.00.009";
2139 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2140     $dbh->do("ALTER TABLE permissions MODIFY `code` varchar(64) DEFAULT NULL");
2141     $dbh->do("ALTER TABLE user_permissions MODIFY `code` varchar(64) DEFAULT NULL");
2142     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'circulate_remaining_permissions', 'Remaining circulation permissions')");
2143     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'override_renewals', 'Override blocked renewals')");
2144     print "Upgrade to $DBversion done (added subpermissions for circulate permission)\n";
2145 }
2146
2147 $DBversion = '3.01.00.010';
2148 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2149     $dbh->do("ALTER TABLE `borrower_attributes` MODIFY COLUMN `attribute` VARCHAR(64) DEFAULT NULL");
2150     $dbh->do("ALTER TABLE `borrower_attributes` MODIFY COLUMN `password` VARCHAR(64) DEFAULT NULL");
2151     print "Upgrade to $DBversion done (bug 2687: increase length of borrower attribute fields)\n";
2152     SetVersion ($DBversion);
2153 }
2154
2155 $DBversion = '3.01.00.011';
2156 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2157
2158     # Yes, the old value was ^M terminated.
2159     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);";
2160
2161     my $intranetuserjs = C4::Context->preference('intranetuserjs');
2162     if ($intranetuserjs  and  $intranetuserjs eq $bad_value) {
2163         my $sql = <<'END_SQL';
2164 UPDATE systempreferences
2165 SET value = ''
2166 WHERE variable = 'intranetuserjs'
2167 END_SQL
2168         $dbh->do($sql);
2169     }
2170     print "Upgrade to $DBversion done (removed bogus intranetuserjs syspref)\n";
2171     SetVersion($DBversion);
2172 }
2173
2174 $DBversion = "3.01.00.012";
2175 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2176     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowHoldPolicyOverride', '0', 'Allow staff to override hold policies when placing holds',NULL,'YesNo')");
2177     $dbh->do("
2178         CREATE TABLE `branch_item_rules` (
2179           `branchcode` varchar(10) NOT NULL,
2180           `itemtype` varchar(10) NOT NULL,
2181           `holdallowed` tinyint(1) default NULL,
2182           PRIMARY KEY  (`itemtype`,`branchcode`),
2183           KEY `branch_item_rules_ibfk_2` (`branchcode`),
2184           CONSTRAINT `branch_item_rules_ibfk_1` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE,
2185           CONSTRAINT `branch_item_rules_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
2186         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2187     ");
2188     $dbh->do("
2189         CREATE TABLE `default_branch_item_rules` (
2190           `itemtype` varchar(10) NOT NULL,
2191           `holdallowed` tinyint(1) default NULL,
2192           PRIMARY KEY  (`itemtype`),
2193           CONSTRAINT `default_branch_item_rules_ibfk_1` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE
2194         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2195     ");
2196     $dbh->do("
2197         ALTER TABLE default_branch_circ_rules
2198             ADD COLUMN holdallowed tinyint(1) NULL
2199     ");
2200     $dbh->do("
2201         ALTER TABLE default_circ_rules
2202             ADD COLUMN holdallowed tinyint(1) NULL
2203     ");
2204     print "Upgrade to $DBversion done (Add tables and system preferences for holds policies)\n";
2205     SetVersion ($DBversion);
2206 }
2207
2208 $DBversion = '3.01.00.013';
2209 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2210     $dbh->do("
2211         CREATE TABLE item_circulation_alert_preferences (
2212             id           int(11) AUTO_INCREMENT,
2213             branchcode   varchar(10) NOT NULL,
2214             categorycode varchar(10) NOT NULL,
2215             item_type    varchar(10) NOT NULL,
2216             notification varchar(16) NOT NULL,
2217             PRIMARY KEY (id),
2218             KEY (branchcode, categorycode, item_type, notification)
2219         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2220     ");
2221
2222     $dbh->do(q{ ALTER TABLE `message_queue` ADD metadata text DEFAULT NULL           AFTER content;  });
2223     $dbh->do(q{ ALTER TABLE `message_queue` ADD letter_code varchar(64) DEFAULT NULL AFTER metadata; });
2224
2225     $dbh->do(q{
2226         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
2227         ('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.');
2228     });
2229     $dbh->do(q{
2230         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
2231         ('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>>.');
2232     });
2233
2234     $dbh->do(q{INSERT INTO message_attributes (message_attribute_id, message_name, takes_days) VALUES (5, 'Item Check-in', 0);});
2235     $dbh->do(q{INSERT INTO message_attributes (message_attribute_id, message_name, takes_days) VALUES (6, 'Item Checkout', 0);});
2236
2237     $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');});
2238     $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');});
2239     $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');});
2240     $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');});
2241
2242     print "Upgrade to $DBversion done (data for Email Checkout Slips project)\n";
2243          SetVersion ($DBversion);
2244 }
2245
2246 $DBversion = "3.01.00.014";
2247 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2248     $dbh->do("ALTER TABLE `branch_transfer_limits` CHANGE `itemtype` `itemtype` VARCHAR( 4 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL");
2249     $dbh->do("ALTER TABLE `branch_transfer_limits` ADD `ccode` VARCHAR( 10 ) NULL ;");
2250     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2251     VALUES (
2252     'BranchTransferLimitsType', 'ccode', 'itemtype|ccode', 'When using branch transfer limits, choose whether to limit by itemtype or collection code.', 'Choice'
2253     );");
2254
2255     print "Upgrade to $DBversion done ( Updated table for Branch Transfer Limits)\n";
2256     SetVersion ($DBversion);
2257 }
2258
2259 $DBversion = '3.01.00.015';
2260 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2261     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsClientCode', '0', 'Client Code for using Syndetics Solutions content','','free')");
2262
2263     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsEnabled', '0', 'Turn on Syndetics Enhanced Content','','YesNo')");
2264
2265     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsCoverImages', '0', 'Display Cover Images from Syndetics','','YesNo')");
2266
2267     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsTOC', '0', 'Display Table of Content information from Syndetics','','YesNo')");
2268
2269     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsSummary', '0', 'Display Summary Information from Syndetics','','YesNo')");
2270
2271     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsEditions', '0', 'Display Editions from Syndetics','','YesNo')");
2272
2273     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsExcerpt', '0', 'Display Excerpts and first chapters on OPAC from Syndetics','','YesNo')");
2274
2275     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsReviews', '0', 'Display Reviews on OPAC from Syndetics','','YesNo')");
2276
2277     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsAuthorNotes', '0', 'Display Notes about the Author on OPAC from Syndetics','','YesNo')");
2278
2279     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsAwards', '0', 'Display Awards on OPAC from Syndetics','','YesNo')");
2280
2281     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsSeries', '0', 'Display Series information on OPAC from Syndetics','','YesNo')");
2282
2283     $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')");
2284
2285     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAmazonCoverImages', '0', 'Display cover images on OPAC from Amazon Web Services','','YesNo')");
2286
2287     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AmazonCoverImages', '0', 'Display Cover Images in Staff Client from Amazon Web Services','','YesNo')");
2288
2289     $dbh->do("UPDATE systempreferences SET variable='AmazonEnabled' WHERE variable = 'AmazonContent'");
2290
2291     $dbh->do("UPDATE systempreferences SET variable='OPACAmazonEnabled' WHERE variable = 'OPACAmazonContent'");
2292
2293     print "Upgrade to $DBversion done (added Syndetics Enhanced Content system preferences)\n";
2294     SetVersion ($DBversion);
2295 }
2296
2297 $DBversion = "3.01.00.016";
2298 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2299     $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')");
2300     print "Upgrade to $DBversion done (Added Babeltheque syspref)\n";
2301     SetVersion ($DBversion);
2302 }
2303
2304 $DBversion = "3.01.00.017";
2305 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2306     $dbh->do("ALTER TABLE `subscription` ADD `staffdisplaycount` VARCHAR(10) NULL;");
2307     $dbh->do("ALTER TABLE `subscription` ADD `opacdisplaycount` VARCHAR(10) NULL;");
2308     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2309     VALUES (
2310     'StaffSerialIssueDisplayCount', '3', '', 'Number of serial issues to display per subscription in the Staff client', 'Integer'
2311     );");
2312         $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2313     VALUES (
2314     'OPACSerialIssueDisplayCount', '3', '', 'Number of serial issues to display per subscription in the OPAC', 'Integer'
2315     );");
2316
2317     print "Upgrade to $DBversion done ( Updated table for Serials Display)\n";
2318     SetVersion ($DBversion);
2319 }
2320
2321 $DBversion = "3.01.00.018";
2322 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2323     $dbh->do("ALTER TABLE deletedborrowers ADD `smsalertnumber` varchar(50) default NULL");
2324     print "Upgrade to $DBversion done (added deletedborrowers.smsalertnumber, missed in 3.00.00.091)\n";
2325     SetVersion ($DBversion);
2326 }
2327
2328 $DBversion = "3.01.00.019";
2329 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2330         $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')");
2331     print "Upgrade to $DBversion done (adding OPACShowCheckoutName systempref)\n";
2332     SetVersion ($DBversion);
2333 }
2334
2335 $DBversion = "3.01.00.020";
2336 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2337     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesID','','See:http://librarything.com/forlibraries/','','free')");
2338     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesEnabled','0','Enable or Disable Library Thing for Libraries Features','','YesNo')");
2339     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesTabbedView','0','Put LibraryThingForLibraries Content in Tabs.','','YesNo')");
2340     print "Upgrade to $DBversion done (adding LibraryThing for Libraries sysprefs)\n";
2341     SetVersion ($DBversion);
2342 }
2343
2344 $DBversion = "3.01.00.021";
2345 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2346     my $enable_reviews = C4::Context->preference('OPACAmazonEnabled') ? '1' : '0';
2347     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAmazonReviews', '$enable_reviews', 'Display Amazon readers reviews on OPAC','','YesNo')");
2348     print "Upgrade to $DBversion done (adding OPACAmazonReviews syspref)\n";
2349     SetVersion ($DBversion);
2350 }
2351
2352 $DBversion = '3.01.00.022';
2353 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2354     $dbh->do("ALTER TABLE `labels_conf` MODIFY COLUMN `formatstring` mediumtext DEFAULT NULL");
2355     print "Upgrade to $DBversion done (bug 2945: increase size of labels_conf.formatstring)\n";
2356     SetVersion ($DBversion);
2357 }
2358
2359 $DBversion = '3.01.00.023';
2360 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2361     $dbh->do("ALTER TABLE biblioitems        MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2362     $dbh->do("ALTER TABLE deletedbiblioitems MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2363     $dbh->do("ALTER TABLE import_biblios     MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2364     $dbh->do("ALTER TABLE suggestions        MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2365     print "Upgrade to $DBversion done (bug 2765: increase width of isbn column in several tables)\n";
2366     SetVersion ($DBversion);
2367 }
2368
2369 $DBversion = "3.01.00.024";
2370 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2371     $dbh->do("ALTER TABLE labels MODIFY COLUMN batch_id int(10) NOT NULL default 1;");
2372     print "Upgrade to $DBversion done (change labels.batch_id from varchar to int)\n";
2373     SetVersion ($DBversion);
2374 }
2375
2376 $DBversion = '3.01.00.025';
2377 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2378     $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')");
2379
2380     print "Upgrade to $DBversion done (added ceilingDueDate system preference)\n";
2381     SetVersion ($DBversion);
2382 }
2383
2384 $DBversion = '3.01.00.026';
2385 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2386     $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')");
2387
2388     print "Upgrade to $DBversion done (added numReturnedItemsToShow system preference)\n";
2389     SetVersion ($DBversion);
2390 }
2391
2392 $DBversion = '3.01.00.027';
2393 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2394     $dbh->do("ALTER TABLE zebraqueue CHANGE `biblio_auth_number` `biblio_auth_number` bigint(20) unsigned NOT NULL default 0");
2395     print "Upgrade to $DBversion done (Increased size of zebraqueue biblio_auth_number to address bug 3148.)\n";
2396     SetVersion ($DBversion);
2397 }
2398
2399 $DBversion = '3.01.00.028';
2400 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2401     my $enable_reviews = C4::Context->preference('AmazonEnabled') ? '1' : '0';
2402     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AmazonReviews', '$enable_reviews', 'Display Amazon reviews on staff interface','','YesNo')");
2403     print "Upgrade to $DBversion done (added AmazonReviews)\n";
2404     SetVersion ($DBversion);
2405 }
2406
2407 $DBversion = '3.01.00.029';
2408 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2409     $dbh->do(q( UPDATE language_rfc4646_to_iso639
2410                 SET iso639_2_code = 'spa'
2411                 WHERE rfc4646_subtag = 'es'
2412                 AND   iso639_2_code = 'rus' )
2413             );
2414     print "Upgrade to $DBversion done (fixed bug 2599: using Spanish search limit retrieves Russian results)\n";
2415     SetVersion ($DBversion);
2416 }
2417
2418 $DBversion = "3.01.00.030";
2419 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2420     $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')");
2421     print "Upgrade to $DBversion done (added AllowNotForLoanOverride system preference)\n";
2422     SetVersion ($DBversion);
2423 }
2424
2425 $DBversion = "3.01.00.031";
2426 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2427     $dbh->do("ALTER TABLE branch_transfer_limits
2428               MODIFY toBranch   varchar(10) NOT NULL,
2429               MODIFY fromBranch varchar(10) NOT NULL,
2430               MODIFY itemtype   varchar(10) NULL");
2431     print "Upgrade to $DBversion done (fix column widths in branch_transfer_limits)\n";
2432     SetVersion ($DBversion);
2433 }
2434
2435 $DBversion = "3.01.00.032";
2436 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2437     $dbh->do(<<ENDOFRENEWAL);
2438 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');
2439 ENDOFRENEWAL
2440     print "Upgrade to $DBversion done (Change the field)\n";
2441     SetVersion ($DBversion);
2442 }
2443
2444 $DBversion = "3.01.00.033";
2445 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2446     $dbh->do(q/
2447         ALTER TABLE borrower_message_preferences
2448         MODIFY borrowernumber int(11) default NULL,
2449         ADD    categorycode varchar(10) default NULL AFTER borrowernumber,
2450         ADD KEY `categorycode` (`categorycode`),
2451         ADD CONSTRAINT `borrower_message_preferences_ibfk_3`
2452                        FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
2453                        ON DELETE CASCADE ON UPDATE CASCADE
2454     /);
2455     print "Upgrade to $DBversion done (DB changes to allow patron category defaults for messaging preferences)\n";
2456     SetVersion ($DBversion);
2457 }
2458
2459 $DBversion = "3.01.00.034";
2460 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2461     $dbh->do("ALTER TABLE `subscription` ADD COLUMN `graceperiod` INT(11) NOT NULL default '0';");
2462     print "Upgrade to $DBversion done (Adding graceperiod column to subscription table)\n";
2463     SetVersion ($DBversion);
2464 }
2465
2466 $DBversion = '3.01.00.035';
2467 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2468     $dbh->do(q{ ALTER TABLE `subscription` ADD location varchar(80) NULL DEFAULT '' AFTER callnumber; });
2469    print "Upgrade to $DBversion done (Adding location to subscription table)\n";
2470     SetVersion ($DBversion);
2471 }
2472
2473 $DBversion = '3.01.00.036';
2474 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2475     $dbh->do("UPDATE systempreferences SET explanation = 'Choose the default detail view in the staff interface; choose between normal, labeled_marc, marc or isbd'
2476               WHERE variable = 'IntranetBiblioDefaultView'
2477               AND   explanation = 'IntranetBiblioDefaultView'");
2478     $dbh->do("UPDATE systempreferences SET type = 'Choice', options = 'normal|marc|isbd|labeled_marc'
2479               WHERE variable = 'IntranetBiblioDefaultView'");
2480     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewISBD','1','Allow display of ISBD view of bibiographic records','','YesNo')");
2481     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewLabeledMARC','0','Allow display of labeled MARC view of bibiographic records','','YesNo')");
2482     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewMARC','1','Allow display of MARC view of bibiographic records','','YesNo')");
2483     print "Upgrade to $DBversion done (new viewISBD, viewLabeledMARC, viewMARC sysprefs and tweak IntranetBiblioDefaultView)\n";
2484     SetVersion ($DBversion);
2485 }
2486
2487 $DBversion = '3.01.00.037';
2488 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2489     $dbh->do('ALTER TABLE authorised_values ADD KEY `lib` (`lib`)');
2490     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('FilterBeforeOverdueReport','0','Do not run overdue report until filter selected','','YesNo')");
2491     SetVersion ($DBversion);
2492     print "Upgrade to $DBversion done (added FilterBeforeOverdueReport syspref and new index on authorised_values)\n";
2493 }
2494
2495 $DBversion = "3.01.00.038";
2496 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2497     # update branches table
2498     #
2499     $dbh->do("ALTER TABLE branches ADD `branchzip` varchar(25) default NULL AFTER `branchaddress3`");
2500     $dbh->do("ALTER TABLE branches ADD `branchcity` mediumtext AFTER `branchzip`");
2501     $dbh->do("ALTER TABLE branches ADD `branchcountry` text AFTER `branchcity`");
2502     $dbh->do("ALTER TABLE branches ADD `branchurl` mediumtext AFTER `branchemail`");
2503     $dbh->do("ALTER TABLE branches ADD `branchnotes` mediumtext AFTER `branchprinter`");
2504     print "Upgrade to $DBversion done (add ZIP, city, country, URL, and notes column to branches)\n";
2505     SetVersion ($DBversion);
2506 }
2507
2508 $DBversion = '3.01.00.039';
2509 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2510     $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')");
2511     $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')");
2512     SetVersion ($DBversion);
2513     print "Upgrade to $DBversion done (added SpineLabelFormat and SpineLabelAutoPrint sysprefs)\n";
2514 }
2515
2516 $DBversion = '3.01.00.040';
2517 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2518     $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')");
2519     $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')");
2520     SetVersion ($DBversion);
2521     print "Upgrade to $DBversion done (AllowHoldDateInFuture and OPACAllowHoldDateInFuture sysprefs)\n";
2522 }
2523
2524 $DBversion = '3.01.00.041';
2525 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2526     $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')");
2527     SetVersion ($DBversion);
2528     print "Upgrade to $DBversion done (added AWSPrivateKey syspref - note that if you use enhanced content from Amazon, this should be set right away.)\n";
2529 }
2530
2531 $DBversion = '3.01.00.042';
2532 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2533     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACFineNoRenewals','99999','Fine Limit above which user canmot renew books via OPAC','','Integer')");
2534     SetVersion ($DBversion);
2535     print "Upgrade to $DBversion done (added OPACFineNoRenewals syspref)\n";
2536 }
2537
2538 $DBversion = '3.01.00.043';
2539 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2540     $dbh->do('ALTER TABLE items ADD COLUMN permanent_location VARCHAR(80) DEFAULT NULL AFTER location');
2541     $dbh->do('UPDATE items SET permanent_location = location');
2542     $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 )', '')");
2543     $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')");
2544     $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')");
2545     SetVersion ($DBversion);
2546     print "Upgrade to $DBversion done (amended Item added NewItemsDefaultLocation, InProcessingToShelvingCart, ReturnToShelvingCart sysprefs)\n";
2547 }
2548
2549 $DBversion = '3.01.00.044';
2550 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2551     $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')");
2552     SetVersion ($DBversion);
2553     print "Upgrade to $DBversion done (added DisplayClearScreenButton system preference)\n";
2554 }
2555
2556 $DBversion = '3.01.00.045';
2557 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2558     $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')");
2559     SetVersion ($DBversion);
2560     print "Upgrade to $DBversion done (added a preference to hide the patrons name in the staff catalog)\n";
2561 }
2562
2563 $DBversion = "3.01.00.046";
2564 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2565     # update borrowers table
2566     #
2567     $dbh->do("ALTER TABLE borrowers ADD `country` text AFTER zipcode");
2568     $dbh->do("ALTER TABLE borrowers ADD `B_country` text AFTER B_zipcode");
2569     $dbh->do("ALTER TABLE deletedborrowers ADD `country` text AFTER zipcode");
2570     $dbh->do("ALTER TABLE deletedborrowers ADD `B_country` text AFTER B_zipcode");
2571     print "Upgrade to $DBversion done (add country and B_country to borrowers)\n";
2572     SetVersion ($DBversion);
2573 }
2574
2575 $DBversion = '3.01.00.047';
2576 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2577     $dbh->do("ALTER TABLE items MODIFY itemcallnumber varchar(255);");
2578     $dbh->do("ALTER TABLE deleteditems MODIFY itemcallnumber varchar(255);");
2579     $dbh->do("ALTER TABLE tmp_holdsqueue MODIFY itemcallnumber varchar(255);");
2580     SetVersion ($DBversion);
2581     print " Upgrade to $DBversion done (bug 2761: change max length of itemcallnumber to 255 from 30)\n";
2582 }
2583
2584 $DBversion = '3.01.00.048';
2585 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2586     $dbh->do("UPDATE userflags SET flagdesc='View Catalog (Librarian Interface)' WHERE bit=2;");
2587     $dbh->do("UPDATE userflags SET flagdesc='Edit Catalog (Modify bibliographic/holdings data)' WHERE bit=9;");
2588     $dbh->do("UPDATE userflags SET flagdesc='Allow to edit authorities' WHERE bit=14;");
2589     $dbh->do("UPDATE userflags SET flagdesc='Allow to access to the reports module' WHERE bit=16;");
2590     $dbh->do("UPDATE userflags SET flagdesc='Allow to manage serials subscriptions' WHERE bit=15;");
2591     SetVersion ($DBversion);
2592     print " Upgrade to $DBversion done (bug 2611: fix spelling/capitalization in permission flag descriptions)\n";
2593 }
2594
2595 $DBversion = '3.01.00.049';
2596 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2597     $dbh->do("UPDATE permissions SET description = 'Perform inventory (stocktaking) of your catalog' WHERE code = 'inventory';");
2598      SetVersion ($DBversion);
2599     print "Upgrade to $DBversion done (bug 2611: changed catalogue to catalog per the standard)\n";
2600 }
2601
2602 $DBversion = '3.01.00.050';
2603 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2604     $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');");
2605     SetVersion ($DBversion);
2606     print "Upgrade to $DBversion done (bug 1934: Add OPACSearchForTitleIn syspref)\n";
2607 }
2608
2609 $DBversion = '3.01.00.051';
2610 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2611     $dbh->do("UPDATE systempreferences SET explanation='Fine limit above which user cannot renew books via OPAC' WHERE variable='OPACFineNoRenewals';");
2612     $dbh->do("UPDATE systempreferences SET explanation='If set to ON, a clear screen button will appear on the circulation page.' WHERE variable='DisplayClearScreenButton';");
2613     SetVersion ($DBversion);
2614     print "Upgrade to $DBversion done (fixed typos in new sysprefs)\n";
2615 }
2616
2617 $DBversion = '3.01.00.052';
2618 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2619     $dbh->do('ALTER TABLE deleteditems ADD COLUMN permanent_location VARCHAR(80) DEFAULT NULL AFTER location');
2620     SetVersion ($DBversion);
2621     print "Upgrade to $DBversion done (bug 3481: add permanent_location column to deleteditems)\n";
2622 }
2623
2624 $DBversion = '3.01.00.053';
2625 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2626     my $upgrade_script = C4::Context->config("intranetdir") . "/installer/data/mysql/labels_upgrade.pl";
2627     system("perl $upgrade_script");
2628     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";
2629     SetVersion ($DBversion);
2630 }
2631
2632 $DBversion = '3.01.00.054';
2633 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2634     $dbh->do("ALTER TABLE borrowers ADD `B_address2` text AFTER B_address");
2635     $dbh->do("ALTER TABLE borrowers ADD `altcontactcountry` text AFTER altcontactzipcode");
2636     $dbh->do("ALTER TABLE deletedborrowers ADD `B_address2` text AFTER B_address");
2637     $dbh->do("ALTER TABLE deletedborrowers ADD `altcontactcountry` text AFTER altcontactzipcode");
2638     SetVersion ($DBversion);
2639     print "Upgrade to $DBversion done (bug 1600, bug 3454: add altcontactcountry and B_address2 to borrowers and deletedborrowers)\n";
2640 }
2641
2642 $DBversion = '3.01.00.055';
2643 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2644     $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'|);
2645     SetVersion ($DBversion);
2646     print "Upgrade to $DBversion done (changed OPACSearchForTitleIn per requests in bug 1934)\n";
2647 }
2648
2649 $DBversion = '3.01.00.056';
2650 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2651     $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');");
2652     SetVersion ($DBversion);
2653     print "Upgrade to $DBversion done (Bug 1172 : Add OPACPatronDetails syspref)\n";
2654 }
2655
2656 $DBversion = '3.01.00.057';
2657 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2658     $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');");
2659     SetVersion ($DBversion);
2660     print "Upgrade to $DBversion done (Bug 2576 : Add OPACFinesTab syspref)\n";
2661 }
2662
2663 $DBversion = '3.01.00.058';
2664 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2665     $dbh->do("ALTER TABLE `language_subtag_registry` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2666     $dbh->do("ALTER TABLE `language_rfc4646_to_iso639` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2667     $dbh->do("ALTER TABLE `language_descriptions` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2668     SetVersion ($DBversion);
2669     print "Upgrade to $DBversion done (Added primary keys to language tables)\n";
2670 }
2671
2672 $DBversion = '3.01.00.059';
2673 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2674     $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')");
2675     SetVersion ($DBversion);
2676     print "Upgrade to $DBversion done (added DisplayOPACiconsXSLT sysprefs)\n";
2677 }
2678
2679 $DBversion = '3.01.00.060';
2680 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2681     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowAllMessageDeletion','0','Allow any Library to delete any message','','YesNo');");
2682     $dbh->do('DROP TABLE IF EXISTS messages');
2683     $dbh->do("CREATE TABLE messages ( `message_id` int(11) NOT NULL auto_increment,
2684         `borrowernumber` int(11) NOT NULL,
2685         `branchcode` varchar(4) default NULL,
2686         `message_type` varchar(1) NOT NULL,
2687         `message` text NOT NULL,
2688         `message_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
2689         PRIMARY KEY (`message_id`)
2690         ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
2691
2692         print "Upgrade to $DBversion done ( Added AllowAllMessageDeletion syspref and messages table )\n";
2693     SetVersion ($DBversion);
2694 }
2695
2696 $DBversion = '3.01.00.061';
2697 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2698     $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')");
2699         print "Upgrade to $DBversion done ( Added ShowPatronImageInWebBasedSelfCheck system preference )\n";
2700     SetVersion ($DBversion);
2701 }
2702
2703 $DBversion = "3.01.00.062";
2704 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2705     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'manage_csv_profiles', 'Manage CSV export profiles')");
2706     $dbh->do(q/
2707         CREATE TABLE `export_format` (
2708           `export_format_id` int(11) NOT NULL auto_increment,
2709           `profile` varchar(255) NOT NULL,
2710           `description` mediumtext NOT NULL,
2711           `marcfields` mediumtext NOT NULL,
2712           PRIMARY KEY  (`export_format_id`)
2713         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Used for CSV export';
2714     /);
2715     print "Upgrade to $DBversion done (added csv export profiles)\n";
2716 }
2717
2718 $DBversion = "3.01.00.063";
2719 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2720     $dbh->do("
2721         CREATE TABLE `fieldmapping` (
2722           `id` int(11) NOT NULL auto_increment,
2723           `field` varchar(255) NOT NULL,
2724           `frameworkcode` char(4) NOT NULL default '',
2725           `fieldcode` char(3) NOT NULL,
2726           `subfieldcode` char(1) NOT NULL,
2727           PRIMARY KEY  (`id`)
2728         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2729              ");
2730     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";
2731 }
2732
2733 $DBversion = '3.01.00.065';
2734 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2735     $dbh->do('ALTER TABLE issuingrules ADD COLUMN `renewalsallowed` smallint(6) NOT NULL default "0" AFTER `issuelength`;');
2736     $sth = $dbh->prepare("SELECT itemtype, renewalsallowed FROM itemtypes");
2737     $sth->execute();
2738
2739     my $sthupd = $dbh->prepare("UPDATE issuingrules SET renewalsallowed = ? WHERE itemtype = ?");
2740
2741     while(my $row = $sth->fetchrow_hashref){
2742         $sthupd->execute($row->{renewalsallowed}, $row->{itemtype});
2743     }
2744
2745     $dbh->do('ALTER TABLE itemtypes DROP COLUMN `renewalsallowed`;');
2746
2747     SetVersion ($DBversion);
2748     print "Upgrade to $DBversion done (Moving allowed renewals from itemtypes to issuingrule)\n";
2749 }
2750
2751 $DBversion = '3.01.00.066';
2752 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2753     $dbh->do('ALTER TABLE issuingrules ADD COLUMN `reservesallowed` smallint(6) NOT NULL default "0" AFTER `renewalsallowed`;');
2754
2755     my $maxreserves = C4::Context->preference('maxreserves');
2756     $sth = $dbh->prepare('UPDATE issuingrules SET reservesallowed = ?;');
2757     $sth->execute($maxreserves);
2758
2759     $dbh->do('DELETE FROM systempreferences WHERE variable = "maxreserves";');
2760
2761     $dbh->do("INSERT INTO systempreferences (variable,value, options, explanation, type) VALUES('ReservesControlBranch','PatronLibrary','ItemHomeLibrary|PatronLibrary','Branch checked for members reservations rights','Choice')");
2762
2763     SetVersion ($DBversion);
2764     print "Upgrade to $DBversion done (Moving max allowed reserves from system preference to issuingrule)\n";
2765 }
2766
2767 $DBversion = "3.01.00.067";
2768 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2769     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'batchmod', 'Perform batch modification of items')");
2770     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'batchdel', 'Perform batch deletion of items')");
2771     print "Upgrade to $DBversion done (added permissions for batch modification and deletion)\n";
2772     SetVersion ($DBversion);
2773 }
2774
2775 $DBversion = "3.01.00.068";
2776 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2777         $dbh->do("ALTER TABLE issuingrules ADD COLUMN `finedays` int(11) default NULL AFTER `fine` ");
2778         print "Upgrade to $DBversion done (Adding finedays in issuingrules table)\n";
2779     SetVersion ($DBversion);
2780 }
2781
2782
2783 $DBversion = "3.01.00.069";
2784 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2785         $dbh->do("INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('EnableOpacSearchHistory', '1', '', 'Enable or disable opac search history', 'YesNo')");
2786
2787         my $create = <<SEARCHHIST;
2788 CREATE TABLE IF NOT EXISTS `search_history` (
2789   `userid` int(11) NOT NULL,
2790   `sessionid` varchar(32) NOT NULL,
2791   `query_desc` varchar(255) NOT NULL,
2792   `query_cgi` varchar(255) NOT NULL,
2793   `total` int(11) NOT NULL,
2794   `time` timestamp NOT NULL default CURRENT_TIMESTAMP,
2795   KEY `userid` (`userid`),
2796   KEY `sessionid` (`sessionid`)
2797 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Opac search history results';
2798 SEARCHHIST
2799         $dbh->do($create);
2800
2801         print "Upgrade to $DBversion done (added OPAC search history preference and table)\n";
2802 }
2803
2804 $DBversion = "3.01.00.070";
2805 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2806         $dbh->do("ALTER TABLE authorised_values ADD COLUMN `lib_opac` VARCHAR(80) default NULL AFTER `lib`");
2807         print "Upgrade to $DBversion done (Added a lib_opac field in authorised_values table)\n";
2808 }
2809
2810 $DBversion = "3.01.00.071";
2811 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2812         $dbh->do("ALTER TABLE `subscription` ADD `enddate` date default NULL");
2813         $dbh->do("ALTER TABLE subscriptionhistory CHANGE enddate histenddate DATE default NULL");
2814         print "Upgrade to $DBversion done ( Adding enddate to subscription)\n";
2815 }
2816
2817 # Acquisitions update
2818
2819 $DBversion = "3.01.00.072";
2820 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2821     $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')");
2822     # create a new syspref for the 'Mr anonymous' patron
2823     $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,'')");
2824     # fill AnonymousPatron with AnonymousSuggestion value (copy)
2825     my $sth=$dbh->prepare("SELECT value FROM systempreferences WHERE variable='AnonSuggestions'");
2826     $sth->execute;
2827     my ($value) = $sth->fetchrow() || 0;
2828     $dbh->do("UPDATE systempreferences SET value='$value' WHERE variable='AnonymousPatron'");
2829     # set AnonymousSuggestion do YesNo
2830     # 1st, set the value (1/True if it had a borrowernumber)
2831     $dbh->do("UPDATE systempreferences SET value=1 WHERE variable='AnonSuggestions' AND value>0");
2832     # 2nd, change the type to Choice
2833     $dbh->do("UPDATE systempreferences SET type='YesNo' WHERE variable='AnonSuggestions'");
2834         # borrower reading record privacy : 0 : forever, 1 : laws, 2 : don't keep at all
2835     $dbh->do("ALTER TABLE `borrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
2836     print "Upgrade to $DBversion done (add new syspref and column in borrowers)\n";
2837     SetVersion ($DBversion);
2838 }
2839
2840 $DBversion = '3.01.00.073';
2841 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2842     $dbh->do('SET FOREIGN_KEY_CHECKS=0 ');
2843     $dbh->do(<<'END_SQL');
2844 CREATE TABLE IF NOT EXISTS `aqcontract` (
2845   `contractnumber` int(11) NOT NULL auto_increment,
2846   `contractstartdate` date default NULL,
2847   `contractenddate` date default NULL,
2848   `contractname` varchar(50) default NULL,
2849   `contractdescription` mediumtext,
2850   `booksellerid` int(11) not NULL,
2851     PRIMARY KEY  (`contractnumber`),
2852         CONSTRAINT `booksellerid_fk1` FOREIGN KEY (`booksellerid`)
2853         REFERENCES `aqbooksellers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
2854 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
2855 END_SQL
2856     $dbh->do('SET FOREIGN_KEY_CHECKS=1 ');
2857     print "Upgrade to $DBversion done (adding aqcontract table)\n";
2858     SetVersion ($DBversion);
2859 }
2860
2861 $DBversion = '3.01.00.074';
2862 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2863     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `basketname` varchar(50) default NULL AFTER `basketno`");
2864     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `note` mediumtext AFTER `basketname`");
2865     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `booksellernote` mediumtext AFTER `note`");
2866     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `contractnumber` int(11) AFTER `booksellernote`");
2867     $dbh->do("ALTER TABLE `aqbasket` ADD FOREIGN KEY (`contractnumber`) REFERENCES `aqcontract` (`contractnumber`)");
2868     print "Upgrade to $DBversion done (edit aqbasket table done)\n";
2869     SetVersion ($DBversion);
2870 }
2871
2872 $DBversion = '3.01.00.075';
2873 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2874     $dbh->do("ALTER TABLE `aqorders` ADD COLUMN `uncertainprice` tinyint(1)");
2875
2876     print "Upgrade to $DBversion done (adding uncertainprices)\n";
2877     SetVersion ($DBversion);
2878 }
2879
2880 $DBversion = '3.01.00.076';
2881 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2882     $dbh->do('SET FOREIGN_KEY_CHECKS=0 ');
2883     $dbh->do("CREATE TABLE IF NOT EXISTS `aqbasketgroups` (
2884                          `id` int(11) NOT NULL auto_increment,
2885                          `name` varchar(50) default NULL,
2886                          `closed` tinyint(1) default NULL,
2887                          `booksellerid` int(11) NOT NULL,
2888                          PRIMARY KEY (`id`),
2889                          KEY `booksellerid` (`booksellerid`),
2890                          CONSTRAINT `aqbasketgroups_ibfk_1` FOREIGN KEY (`booksellerid`) REFERENCES `aqbooksellers` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
2891                          ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
2892     $dbh->do("ALTER TABLE aqbasket ADD COLUMN `basketgroupid` int(11)");
2893     $dbh->do("ALTER TABLE aqbasket ADD FOREIGN KEY (`basketgroupid`) REFERENCES `aqbasketgroups` (`id`) ON UPDATE CASCADE ON DELETE SET NULL");
2894     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('pdfformat','pdfformat::layout2pages','Controls what script is used for printing (basketgroups)','','free')");
2895     $dbh->do('SET FOREIGN_KEY_CHECKS=1 ');
2896     print "Upgrade to $DBversion done (adding basketgroups)\n";
2897     SetVersion ($DBversion);
2898 }
2899 $DBversion = '3.01.00.077';
2900 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2901
2902     $dbh->do("SET FOREIGN_KEY_CHECKS=0 ");
2903     # create a mapping table holding the info we need to match orders to budgets
2904     $dbh->do('DROP TABLE IF EXISTS fundmapping');
2905     $dbh->do(
2906         q|CREATE TABLE fundmapping AS
2907         SELECT aqorderbreakdown.ordernumber, branchcode, bookfundid, budgetdate, entrydate
2908         FROM aqorderbreakdown JOIN aqorders ON aqorderbreakdown.ordernumber = aqorders.ordernumber|);
2909     # match the new type of the corresponding field
2910     $dbh->do('ALTER TABLE fundmapping modify column bookfundid varchar(30)');
2911     # System did not ensure budgetdate was valid historically
2912     $dbh->do(q|UPDATE fundmapping SET budgetdate = entrydate WHERE budgetdate = '0000-00-00' OR budgetdate IS NULL|);
2913     # We save the map in fundmapping in case you need later processing
2914     $dbh->do(q|ALTER TABLE fundmapping add column aqbudgetid integer|);
2915     # these can speed processing up
2916     $dbh->do(q|CREATE INDEX fundmaporder ON fundmapping (ordernumber)|);
2917     $dbh->do(q|CREATE INDEX fundmapid ON fundmapping (bookfundid)|);
2918
2919     $dbh->do("DROP TABLE IF EXISTS `aqbudgetperiods` ");
2920
2921     $dbh->do(qq|
2922                     CREATE TABLE `aqbudgetperiods` (
2923                     `budget_period_id` int(11) NOT NULL auto_increment,
2924                     `budget_period_startdate` date NOT NULL,
2925                     `budget_period_enddate` date NOT NULL,
2926                     `budget_period_active` tinyint(1) default '0',
2927                     `budget_period_description` mediumtext,
2928                     `budget_period_locked` tinyint(1) default NULL,
2929                     `sort1_authcat` varchar(10) default NULL,
2930                     `sort2_authcat` varchar(10) default NULL,
2931                     PRIMARY KEY  (`budget_period_id`)
2932                     ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 |);
2933
2934    $dbh->do(<<ADDPERIODS);
2935 INSERT INTO aqbudgetperiods (budget_period_startdate,budget_period_enddate,budget_period_active,budget_period_description,budget_period_locked)
2936 SELECT DISTINCT startdate, enddate, NOW() BETWEEN startdate and enddate, concat(startdate," ",enddate),NOT NOW() BETWEEN startdate AND enddate from aqbudget
2937 ADDPERIODS
2938 # SORRY , NO AQBUDGET/AQBOOKFUND -> AQBUDGETS IMPORT JUST YET,
2939 # BUT A NEW CLEAN AQBUDGETS TABLE CREATE FOR NOW..
2940 # DROP TABLE IF EXISTS `aqbudget`;
2941 #CREATE TABLE `aqbudget` (
2942 #  `bookfundid` varchar(10) NOT NULL default ',
2943 #    `startdate` date NOT NULL default 0,
2944 #         `enddate` date default NULL,
2945 #           `budgetamount` decimal(13,2) default NULL,
2946 #                 `aqbudgetid` tinyint(4) NOT NULL auto_increment,
2947 #                   `branchcode` varchar(10) default NULL,
2948     DropAllForeignKeys('aqbudget');
2949   #$dbh->do("drop table aqbudget;");
2950
2951
2952     my $maxbudgetid = $dbh->selectcol_arrayref(<<IDsBUDGET);
2953 SELECT MAX(aqbudgetid) from aqbudget
2954 IDsBUDGET
2955
2956 $$maxbudgetid[0] = 0 if !$$maxbudgetid[0];
2957
2958     $dbh->do(<<BUDGETAUTOINCREMENT);
2959 ALTER TABLE aqbudget AUTO_INCREMENT=$$maxbudgetid[0]
2960 BUDGETAUTOINCREMENT
2961
2962     $dbh->do(<<BUDGETNAME);
2963 ALTER TABLE aqbudget RENAME `aqbudgets`
2964 BUDGETNAME
2965
2966     $dbh->do(<<BUDGETS);
2967 ALTER TABLE `aqbudgets`
2968    CHANGE  COLUMN aqbudgetid `budget_id` int(11) NOT NULL AUTO_INCREMENT,
2969    CHANGE  COLUMN branchcode `budget_branchcode` varchar(10) default NULL,
2970    CHANGE  COLUMN budgetamount `budget_amount` decimal(28,6) NOT NULL default '0.00',
2971    CHANGE  COLUMN bookfundid   `budget_code` varchar(30) default NULL,
2972    ADD     COLUMN `budget_parent_id` int(11) default NULL,
2973    ADD     COLUMN `budget_name` varchar(80) default NULL,
2974    ADD     COLUMN `budget_encumb` decimal(28,6) default '0.00',
2975    ADD     COLUMN `budget_expend` decimal(28,6) default '0.00',
2976    ADD     COLUMN `budget_notes` mediumtext,
2977    ADD     COLUMN `budget_description` mediumtext,
2978    ADD     COLUMN `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
2979    ADD     COLUMN `budget_amount_sublevel`  decimal(28,6) AFTER `budget_amount`,
2980    ADD     COLUMN `budget_period_id` int(11) default NULL,
2981    ADD     COLUMN `sort1_authcat` varchar(80) default NULL,
2982    ADD     COLUMN `sort2_authcat` varchar(80) default NULL,
2983    ADD     COLUMN `budget_owner_id` int(11) default NULL,
2984    ADD     COLUMN `budget_permission` int(1) default '0';
2985 BUDGETS
2986
2987     $dbh->do(<<BUDGETCONSTRAINTS);
2988 ALTER TABLE `aqbudgets`
2989    ADD CONSTRAINT `aqbudgets_ifbk_1` FOREIGN KEY (`budget_period_id`) REFERENCES `aqbudgetperiods` (`budget_period_id`) ON DELETE CASCADE ON UPDATE CASCADE
2990 BUDGETCONSTRAINTS
2991 #    $dbh->do(<<BUDGETPKDROP);
2992 #ALTER TABLE `aqbudgets`
2993 #   DROP PRIMARY KEY
2994 #BUDGETPKDROP
2995 #    $dbh->do(<<BUDGETPKADD);
2996 #ALTER TABLE `aqbudgets`
2997 #   ADD PRIMARY KEY budget_id
2998 #BUDGETPKADD
2999
3000
3001         my $query_period= $dbh->prepare(qq|SELECT budget_period_id from aqbudgetperiods where budget_period_startdate=? and budget_period_enddate=?|);
3002         my $query_bookfund= $dbh->prepare(qq|SELECT * from aqbookfund where bookfundid=?|);
3003         my $selectbudgets=$dbh->prepare(qq|SELECT * from aqbudgets|);
3004         my $updatebudgets=$dbh->prepare(qq|UPDATE aqbudgets SET budget_period_id= ? , budget_name=?, budget_branchcode=? where budget_id=?|);
3005         $selectbudgets->execute;
3006         while (my $databudget=$selectbudgets->fetchrow_hashref){
3007                 $query_period->execute ($$databudget{startdate},$$databudget{enddate});
3008                 my ($budgetperiodid)=$query_period->fetchrow;
3009                 $query_bookfund->execute ($$databudget{budget_code});
3010                 my $databf=$query_bookfund->fetchrow_hashref;
3011                 my $branchcode=$$databudget{budget_branchcode}||$$databf{branchcode};
3012                 $updatebudgets->execute($budgetperiodid,$$databf{bookfundname},$branchcode,$$databudget{budget_id});
3013         }
3014     $dbh->do(<<BUDGETDROPDATES);
3015 ALTER TABLE `aqbudgets`
3016    DROP startdate,
3017    DROP enddate
3018 BUDGETDROPDATES
3019
3020
3021     $dbh->do("DROP TABLE IF EXISTS `aqbudgets_planning` ");
3022     $dbh->do("CREATE TABLE  `aqbudgets_planning` (
3023                     `plan_id` int(11) NOT NULL auto_increment,
3024                     `budget_id` int(11) NOT NULL,
3025                     `budget_period_id` int(11) NOT NULL,
3026                     `estimated_amount` decimal(28,6) default NULL,
3027                     `authcat` varchar(30) NOT NULL,
3028                     `authvalue` varchar(30) NOT NULL,
3029                                         `display` tinyint(1) DEFAULT 1,
3030                         PRIMARY KEY  (`plan_id`),
3031                         CONSTRAINT `aqbudgets_planning_ifbk_1` FOREIGN KEY (`budget_id`) REFERENCES `aqbudgets` (`budget_id`) ON DELETE CASCADE ON UPDATE CASCADE
3032                         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
3033
3034     $dbh->do("ALTER TABLE `aqorders`
3035                     ADD COLUMN `budget_id` tinyint(4) NOT NULL,
3036                     ADD COLUMN `budgetgroup_id` int(11) NOT NULL,
3037                     ADD COLUMN  `sort1_authcat` varchar(10) default NULL,
3038                     ADD COLUMN  `sort2_authcat` varchar(10) default NULL" );
3039                 # We need to map the orders to the budgets
3040                 # For Historic reasons this is more complex than it should be on occasions
3041                 my $budg_arr = $dbh->selectall_arrayref(
3042                     q|SELECT aqbudgets.budget_id, aqbudgets.budget_code, aqbudgetperiods.budget_period_startdate,
3043                     aqbudgetperiods.budget_period_enddate
3044                     FROM aqbudgets JOIN aqbudgetperiods ON aqbudgets.budget_period_id = aqbudgetperiods.budget_period_id
3045                     ORDER BY budget_code, budget_period_startdate|, { Slice => {} });
3046                 # We arbitarily order on start date, this means if you have overlapping periods the order will be
3047                 # linked to the latest matching budget YMMV
3048                 my $b_sth = $dbh->prepare(
3049                     'UPDATE fundmapping set aqbudgetid = ? where bookfundid =? AND budgetdate >= ? AND budgetdate <= ?');
3050                 for my $b ( @{$budg_arr}) {
3051                     $b_sth->execute($b->{budget_id}, $b->{budget_code}, $b->{budget_period_startdate}, $b->{budget_period_enddate});
3052                 }
3053                 # move the budgetids to aqorders
3054                 $dbh->do(q|UPDATE aqorders, fundmapping SET aqorders.budget_id = fundmapping.aqbudgetid
3055                     WHERE aqorders.ordernumber = fundmapping.ordernumber AND fundmapping.aqbudgetid IS NOT NULL|);
3056                 # NB fundmapping is left as an accontants trail also if you have budgetids that werent set
3057                 # you can decide what to do with them
3058
3059      $dbh->do(
3060          q|UPDATE aqorders, aqbudgets SET aqorders.budgetgroup_id = aqbudgets.budget_period_id
3061          WHERE aqorders.budget_id = aqbudgets.budget_id|);
3062                 # cannot do until aqorderbreakdown removed
3063 #    $dbh->do("DROP TABLE aqbookfund ");
3064 #    $dbh->do("ALTER TABLE aqorders  ADD FOREIGN KEY (`budget_id`) REFERENCES `aqbudgets` (`budget_id`) ON UPDATE CASCADE  " ); ????
3065     $dbh->do("SET FOREIGN_KEY_CHECKS=1 ");
3066
3067     print "Upgrade to $DBversion done (Adding new aqbudgetperiods, aqbudgets and aqbudget_planning tables  )\n";
3068     SetVersion ($DBversion);
3069 }
3070
3071
3072
3073 $DBversion = '3.01.00.078';
3074 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3075     $dbh->do("ALTER TABLE aqbudgetperiods ADD COLUMN budget_period_total decimal(28,6)");
3076     print "Upgrade to $DBversion done (adds 'budget_period_total' column to aqbudgetperiods table)\n";
3077     SetVersion($DBversion);
3078 }
3079
3080
3081 $DBversion = '3.01.00.079';
3082 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3083     $dbh->do("ALTER TABLE currency ADD COLUMN active  tinyint(1)");
3084
3085     print "Upgrade to $DBversion done (adds 'active' column to currencies table)\n";
3086     SetVersion($DBversion);
3087 }
3088
3089 $DBversion = '3.01.00.080';
3090 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3091     $dbh->do(<<BUDG_PERM );
3092 INSERT INTO permissions (module_bit, code, description) VALUES
3093             (11, 'vendors_manage', 'Manage vendors'),
3094             (11, 'contracts_manage', 'Manage contracts'),
3095             (11, 'period_manage', 'Manage periods'),
3096             (11, 'budget_manage', 'Manage budgets'),
3097             (11, 'budget_modify', "Modify budget (can't create lines but can modify existing ones)"),
3098             (11, 'planning_manage', 'Manage budget plannings'),
3099             (11, 'order_manage', 'Manage orders & basket'),
3100             (11, 'group_manage', 'Manage orders & basketgroups'),
3101             (11, 'order_receive', 'Manage orders & basket'),
3102             (11, 'budget_add_del', "Add and delete budgets (but can't modify budgets)");
3103 BUDG_PERM
3104
3105     print "Upgrade to $DBversion done (adds permissions for the acquisitions module)\n";
3106     SetVersion($DBversion);
3107 }
3108
3109
3110 $DBversion = '3.01.00.081';
3111 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3112     $dbh->do("ALTER TABLE aqbooksellers ADD COLUMN `gstrate` decimal(6,4) default NULL");
3113     if (my $gist=C4::Context->preference("gist")){
3114                 my $sql=$dbh->prepare("UPDATE aqbooksellers set `gstrate`=? ");
3115         $sql->execute($gist) ;
3116         }
3117     print "Upgrade to $DBversion done (added per-supplier gstrate setting)\n";
3118     SetVersion($DBversion);
3119 }
3120
3121 $DBversion = "3.01.00.082";
3122 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3123     if (C4::Context->preference("opaclanguages") eq "fr") {
3124         $dbh->do(qq#INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AcqCreateItem','ordering',"Définit quand l'exemplaire est créé : à la commande, à la livraison, au catalogage",'ordering|receiving|cataloguing','Choice')#);
3125     } else {
3126         $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AcqCreateItem','ordering','Define when the item is created : when ordering, when receiving, or in cataloguing module','ordering|receiving|cataloguing','Choice')");
3127     }
3128     print "Upgrade to $DBversion done (adding ReservesNeedReturns systempref, in circulation)\n";
3129     SetVersion ($DBversion);
3130 }
3131
3132 $DBversion = "3.01.00.083";
3133 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3134     $dbh->do(qq|
3135  CREATE TABLE `aqorders_items` (
3136   `ordernumber` int(11) NOT NULL,
3137   `itemnumber` int(11) NOT NULL,
3138   `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
3139   PRIMARY KEY  (`itemnumber`),
3140   KEY `ordernumber` (`ordernumber`)
3141 ) ENGINE=InnoDB DEFAULT CHARSET=utf8   |
3142     );
3143
3144     $dbh->do(qq| DROP TABLE aqorderbreakdown |);
3145     $dbh->do('DROP TABLE aqbookfund');
3146     print "Upgrade to $DBversion done (New aqorders_items table for acqui)\n";
3147     SetVersion ($DBversion);
3148 }
3149
3150 $DBversion = "3.01.00.084";
3151 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3152     $dbh->do(  qq# INSERT INTO `systempreferences` VALUES ('CurrencyFormat','US','US|FR','Determines the display format of currencies. eg: ''36000'' is displayed as ''360 000,00''  in ''FR'' or 360,000.00''  in ''US''.','Choice')  #);
3153
3154     print "Upgrade to $DBversion done (CurrencyFormat syspref added)\n";
3155     SetVersion ($DBversion);
3156 }
3157
3158 $DBversion = "3.01.00.085";
3159 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3160     $dbh->do("ALTER table aqorders drop column title");
3161     $dbh->do("ALTER TABLE `aqorders` CHANGE `budget_id` `budget_id` INT( 11 ) NOT NULL");
3162     print "Upgrade to $DBversion done update budget_id size that should not be a tinyint\n";
3163     SetVersion ($DBversion);
3164 }
3165
3166 $DBversion = "3.01.00.086";
3167 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3168     $dbh->do(<<SUGGESTIONS);
3169 ALTER table suggestions
3170     ADD budgetid INT(11),
3171     ADD branchcode VARCHAR(10) default NULL,
3172     ADD acceptedby INT(11) default NULL,
3173     ADD accepteddate date default NULL,
3174     ADD suggesteddate date default NULL,
3175     ADD manageddate date default NULL,
3176     ADD rejectedby INT(11) default NULL,
3177     ADD rejecteddate date default NULL,
3178     ADD collectiontitle text default NULL,
3179     ADD itemtype VARCHAR(30) default NULL
3180     ;
3181 SUGGESTIONS
3182     print "Upgrade to $DBversion done (Suggestions)\n";
3183     SetVersion ($DBversion);
3184 }
3185
3186 $DBversion = "3.01.00.087";
3187 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3188     $dbh->do("ALTER table aqbudgets drop column budget_amount_sublevel;");
3189     print "Upgrade to $DBversion done (Drop column budget_amount_sublevel from aqbudgets)\n";
3190     SetVersion ($DBversion);
3191 }
3192
3193 $DBversion = "3.01.00.088";
3194 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3195     $dbh->do(  qq# INSERT INTO `systempreferences` VALUES ('intranetbookbag','1','','If ON, enables display of Cart feature in the intranet','YesNo')  #);
3196
3197     print "Upgrade to $DBversion done (intranetbookbag syspref added)\n";
3198     SetVersion ($DBversion);
3199 }
3200
3201 $DBversion = "3.01.00.090";
3202 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3203 $dbh->do("
3204        INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3205                 (16, 'execute_reports', 'Execute SQL reports'),
3206                 (16, 'create_reports', 'Create SQL Reports')
3207         ");
3208
3209     print "Upgrade to $DBversion done (granular permissions for guided reports added)\n";
3210     SetVersion ($DBversion);
3211 }
3212
3213 $DBversion = "3.01.00.091";
3214 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3215 $dbh->do("
3216         UPDATE `systempreferences` SET `options` = 'holdings|serialcollection|subscriptions'
3217         WHERE `systempreferences`.`variable` = 'opacSerialDefaultTab' LIMIT 1
3218         ");
3219
3220     print "Upgrade to $DBversion done (opac-detail default tag updated)\n";
3221     SetVersion ($DBversion);
3222 }
3223
3224 $DBversion = "3.01.00.092";
3225 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3226     if (C4::Context->preference("opaclanguages") =~ /fr/) {
3227         $dbh->do(qq{
3228 INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('RoutingListAddReserves','1','Si activé, des reservations sont automatiquement créées pour chaque lecteur de la liste de circulation d''un numéro de périodique','','YesNo');
3229         });
3230         }else{
3231         $dbh->do(qq{
3232 INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('RoutingListAddReserves','1','If ON the patrons on routing lists are automatically added to holds on the issue.','','YesNo');
3233         });
3234         }
3235     print "Upgrade to $DBversion done (Added RoutingListAddReserves syspref)\n";
3236     SetVersion ($DBversion);
3237 }
3238
3239 $DBversion = "3.01.00.093";
3240 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3241         $dbh->do(qq{
3242         ALTER TABLE biblioitems ADD INDEX issn_idx (issn);
3243         });
3244     print "Upgrade to $DBversion done (added index to ISSN)\n";
3245     SetVersion ($DBversion);
3246 }
3247
3248 $DBversion = "3.01.00.094";
3249 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3250         $dbh->do(qq{
3251         ALTER TABLE aqbasketgroups ADD deliveryplace VARCHAR(10) default NULL, ADD deliverycomment VARCHAR(255) default NULL;
3252         });
3253
3254     print "Upgrade to $DBversion done (adding deliveryplace deliverycomment to basketgroups)\n";
3255     SetVersion ($DBversion);
3256 }
3257
3258 $DBversion = "3.01.00.095";
3259 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3260         $dbh->do(qq{
3261         ALTER TABLE items ADD stocknumber VARCHAR(32) DEFAULT NULL COMMENT "stores the inventory number";
3262         });
3263         $dbh->do(qq{
3264         ALTER TABLE items ADD UNIQUE INDEX itemsstocknumberidx (stocknumber);
3265         });
3266         $dbh->do(qq{
3267         ALTER TABLE deleteditems ADD stocknumber VARCHAR(32) DEFAULT NULL COMMENT "stores the inventory number of deleted items";
3268         });
3269         $dbh->do(qq{
3270         ALTER TABLE deleteditems ADD UNIQUE INDEX deleteditemsstocknumberidx (stocknumber);
3271         });
3272         if (C4::Context->preference('marcflavour') eq 'UNIMARC'){
3273                 $dbh->do(qq{
3274         INSERT IGNORE INTO marc_subfield_structure (frameworkcode,tagfield, tagsubfield, tab, repeatable, mandatory,kohafield)
3275         SELECT DISTINCT (frameworkcode),995,"j",10,0,0,"items.stocknumber" from biblio_framework ;
3276                 });
3277                 #Previously, copynumber was used as stocknumber
3278                 $dbh->do(qq{
3279         UPDATE items set stocknumber=copynumber;
3280                 });
3281                 $dbh->do(qq{
3282         UPDATE items set copynumber=NULL;
3283                 });
3284         }
3285     print "Upgrade to $DBversion done (stocknumber field added)\n";
3286     SetVersion ($DBversion);
3287 }
3288
3289 $DBversion = "3.01.00.096";
3290 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3291     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OrderPdfTemplate','','Uploads a PDF template to use for printing baskets','NULL','Upload')");
3292     $dbh->do("UPDATE systempreferences SET variable='OrderPdfFormat' WHERE variable='pdfformat'");
3293     print "Upgrade to $DBversion done (PDF orders system preferences added and updated)\n";
3294     SetVersion ($DBversion);
3295 }
3296
3297 $DBversion = "3.01.00.097";
3298 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3299         $dbh->do(qq{
3300         ALTER TABLE aqbasketgroups ADD billingplace VARCHAR(10) NOT NULL AFTER deliverycomment;
3301         });
3302
3303     print "Upgrade to $DBversion done (Adding billingplace to aqbasketgroups)\n";
3304     SetVersion ($DBversion);
3305 }
3306
3307 $DBversion = "3.01.00.098";
3308 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3309         $dbh->do(qq{
3310         ALTER TABLE auth_subfield_structure MODIFY frameworkcode VARCHAR(10) NULL;
3311         });
3312
3313     print "Upgrade to $DBversion done (changing frameworkcode length in auth_subfield_structure)\n";
3314     SetVersion ($DBversion);
3315 }
3316
3317 $DBversion = "3.01.00.099";
3318 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3319         $dbh->do(qq{
3320                 INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3321                 (9, 'edit_catalogue', 'Edit catalogue'),
3322                 (9, 'fast_cataloging', 'Fast cataloging')
3323         });
3324
3325     print "Upgrade to $DBversion done (granular permissions for cataloging added)\n";
3326     SetVersion ($DBversion);
3327 }
3328
3329 $DBversion = "3.01.00.100";
3330 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3331         $dbh->do("INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('casAuthentication', '0', '', 'Enable or disable CAS authentication', 'YesNo'), ('casLogout', '1', '', 'Does a logout from Koha should also log out of CAS ?', 'YesNo'), ('casServerUrl', 'https://localhost:8443/cas', '', 'URL of the cas server', 'Free')");
3332         print "Upgrade to $DBversion done (added CAS authentication system preferences)\n";
3333     SetVersion ($DBversion);
3334 }
3335
3336 $DBversion = "3.01.00.101";
3337 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3338         $dbh->do(
3339         "INSERT INTO systempreferences
3340            (variable, value, options, explanation, type)
3341          VALUES (
3342             'OverdueNoticeBcc', '', '',
3343             'Email address to Bcc outgoing notices sent by email',
3344             'free')
3345          ");
3346         print "Upgrade to $DBversion done (added OverdueNoticeBcc system preferences)\n";
3347     SetVersion ($DBversion);
3348 }
3349 $DBversion = "3.01.00.102";
3350 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3351     $dbh->do(
3352     "UPDATE permissions set description = 'Edit catalog (Modify bibliographic/holdings data)' where module_bit = 9 and code = 'edit_catalogue'"
3353     );
3354         print "Upgrade to $DBversion done (fixed spelling error in edit_catalogue permission)\n";
3355     SetVersion ($DBversion);
3356 }
3357
3358 $DBversion = "3.01.00.103";
3359 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3360         $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES (13, 'moderate_tags', 'Moderate patron tags')");
3361         print "Upgrade to $DBversion done (adding patron permissions for tags tool)\n";
3362     SetVersion ($DBversion);
3363 }
3364
3365 $DBversion = "3.01.00.104";
3366 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3367
3368     my ($maninv_count, $borrnotes_count);
3369     eval { $maninv_count = $dbh->do("SELECT 1 FROM authorised_values WHERE category='MANUAL_INV'"); };
3370     if ($maninv_count == 0) {
3371         $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('MANUAL_INV','Copier Fees','.25')");
3372     }
3373     eval { $borrnotes_count = $dbh->do("SELECT 1 FROM authorised_values WHERE category='BOR_NOTES'"); };
3374     if ($borrnotes_count == 0) {
3375         $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('BOR_NOTES','ADDR','Address Notes')");
3376     }
3377
3378     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('LOC','CART','Book Cart')");
3379     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('LOC','PROC','Processing Center')");
3380
3381         print "Upgrade to $DBversion done ( add defaults to authorized values for MANUAL_INV and BOR_NOTES and add new default LOC authorized values for shelf to cart processing )\n";
3382         SetVersion ($DBversion);
3383 }
3384
3385
3386 $DBversion = "3.01.00.105";
3387 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3388     $dbh->do("
3389       CREATE TABLE `collections` (
3390         `colId` int(11) NOT NULL auto_increment,
3391         `colTitle` varchar(100) NOT NULL default '',
3392         `colDesc` text NOT NULL,
3393         `colBranchcode` varchar(4) default NULL COMMENT 'branchcode for branch where item should be held.',
3394         PRIMARY KEY  (`colId`)
3395       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3396     ");
3397
3398     $dbh->do("
3399       CREATE TABLE `collections_tracking` (
3400         `ctId` int(11) NOT NULL auto_increment,
3401         `colId` int(11) NOT NULL default '0' COMMENT 'collections.colId',
3402         `itemnumber` int(11) NOT NULL default '0' COMMENT 'items.itemnumber',
3403         PRIMARY KEY  (`ctId`)
3404       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3405     ");
3406     $dbh->do("
3407         INSERT INTO permissions (module_bit, code, description)
3408         VALUES ( 13, 'rotating_collections', 'Manage Rotating collections')" );
3409         print "Upgrade to $DBversion done (added collection and collection_tracking tables for rotating collections functionality)\n";
3410     SetVersion ($DBversion);
3411 }
3412 $DBversion = "3.01.00.106";
3413 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3414         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ( 'OpacAddMastheadLibraryPulldown', '0', '', 'Adds a pulldown menu to select the library to search on the opac masthead.', 'YesNo' )");
3415         print "Upgrade to $DBversion done (added OpacAddMastheadLibraryPulldown system preferences)\n";
3416     SetVersion ($DBversion);
3417 }
3418
3419 $DBversion = '3.01.00.107';
3420 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3421     my $upgrade_script = C4::Context->config("intranetdir") . "/installer/data/mysql/patroncards_upgrade.pl";
3422     system("perl $upgrade_script");
3423     print "Upgrade to $DBversion done (Migrated labels and patroncards tables and data to new schema.)\n";
3424     SetVersion ($DBversion);
3425 }
3426
3427 $DBversion = '3.01.00.108';
3428 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3429         $dbh->do(qq{
3430     ALTER TABLE `export_format` ADD `csv_separator` VARCHAR( 2 ) NOT NULL AFTER `marcfields` ,
3431     ADD `field_separator` VARCHAR( 2 ) NOT NULL AFTER `csv_separator` ,
3432     ADD `subfield_separator` VARCHAR( 2 ) NOT NULL AFTER `field_separator`
3433     });
3434         print "Upgrade to $DBversion done (added separators for csv export)\n";
3435     SetVersion ($DBversion);
3436 }
3437
3438 $DBversion = "3.01.00.109";
3439 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3440         $dbh->do(qq{
3441         ALTER TABLE `export_format` ADD `encoding` VARCHAR(255) NOT NULL AFTER `subfield_separator`
3442         });
3443         print "Upgrade to $DBversion done (added encoding for csv export)\n";
3444     SetVersion ($DBversion);
3445 }
3446
3447 $DBversion = '3.01.00.110';
3448 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3449     $dbh->do('ALTER TABLE `categories` ADD COLUMN `enrolmentperioddate` DATE NULL DEFAULT NULL AFTER `enrolmentperiod`');
3450     print "Upgrade to $DBversion done (Add enrolment period date support)\n";
3451     SetVersion ($DBversion);
3452 }
3453
3454 $DBversion = '3.01.00.111';
3455 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3456     print "Upgrade to $DBversion done (mark DBrev for 3.2-alpha release)\n";
3457     SetVersion ($DBversion);
3458 }
3459
3460 $DBversion = '3.01.00.112';
3461 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3462         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('SpineLabelShowPrintOnBibDetails', '0', '', 'If turned on, a \"Print Label\" link will appear for each item on the bib details page in the staff interface.', 'YesNo');");
3463         print "Upgrade to $DBversion done ( added Show Spine Label Printer on Bib Items Details preferences )\n";
3464     SetVersion ($DBversion);
3465 }
3466
3467 $DBversion = '3.01.00.113';
3468 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3469     my $value = C4::Context->preference("XSLTResultsDisplay");
3470     $dbh->do(
3471         "INSERT INTO systempreferences (variable,value,type)
3472          VALUES('OPACXSLTResultsDisplay',?,'YesNo')", {}, $value ? 1 : 0);
3473     $value = C4::Context->preference("XSLTDetailsDisplay");
3474     $dbh->do(
3475         "INSERT INTO systempreferences (variable,value,type)
3476          VALUES('OPACXSLTDetailsDisplay',?,'YesNo')", {}, $value ? 1 : 0);
3477     print "Upgrade to $DBversion done (added two new syspref: OPACXSLTResultsDisplay and OPACXSLTDetailDisplay). You may have to go in Admin > System preference to tweak XSLT related syspref both in OPAC and Search tabs.\n";
3478     SetVersion ($DBversion);
3479 }
3480
3481 $DBversion = '3.01.00.114';
3482 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3483     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('AutoSelfCheckAllowed', '0', 'For corporate and special libraries which want web-based self-check available from any PC without the need for a manual staff login. Most libraries will want to leave this turned off. If on, requires self-check ID and password to be entered in AutoSelfCheckID and AutoSelfCheckPass sysprefs.', '', 'YesNo')");
3484     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AutoSelfCheckID','','Staff ID with circulation rights to be used for automatic web-based self-check. Only applies if AutoSelfCheckAllowed syspref is turned on.','','free')");
3485     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AutoSelfCheckPass','','Password to be used for automatic web-based self-check. Only applies if AutoSelfCheckAllowed syspref is turned on.','','free')");
3486         print "Upgrade to $DBversion done ( Added AutoSelfCheckAllowed, AutoSelfCheckID, and AutoShelfCheckPass system preference )\n";
3487     SetVersion ($DBversion);
3488 }
3489
3490 $DBversion = '3.01.00.115';
3491 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3492     $dbh->do('UPDATE aqorders SET quantityreceived = 0 WHERE quantityreceived IS NULL');
3493     $dbh->do('ALTER TABLE aqorders MODIFY COLUMN quantityreceived smallint(6) NOT NULL DEFAULT 0');
3494         print "Upgrade to $DBversion done ( Default aqorders.quantityreceived to 0 )\n";
3495     SetVersion ($DBversion);
3496 }
3497
3498 $DBversion = '3.01.00.116';
3499 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3500         if (C4::Context->preference('OrderPdfFormat') eq 'pdfformat::example'){
3501                 $dbh->do("UPDATE `systempreferences` set value='pdfformat::layout2pages' WHERE variable='OrderPdfFormat'");
3502         }
3503         print "Upgrade to $DBversion done (corrected default OrderPdfFormat value if still set wrong )\n";
3504     SetVersion ($DBversion);
3505 }
3506
3507 $DBversion = '3.01.00.117';
3508 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3509     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'por' WHERE rfc4646_subtag='pt' ");
3510     print "Upgrade to $DBversion done (corrected ISO 639-2 language code for Portuguese)\n";
3511     SetVersion ($DBversion);
3512 }
3513
3514 $DBversion = '3.01.00.118';
3515 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3516     my ($count) = $dbh->selectrow_array("SELECT count(*) FROM information_schema.columns
3517                                          WHERE table_name = 'aqbudgets_planning'
3518                                          AND column_name = 'display'");
3519     if ($count < 1) {
3520         $dbh->do("ALTER TABLE aqbudgets_planning ADD COLUMN display tinyint(1) DEFAULT 1");
3521     }
3522     print "Upgrade to $DBversion done (bug 4203: add display column to aqbudgets_planning if missing)\n";
3523     SetVersion ($DBversion);
3524 }
3525
3526 $DBversion = '3.01.00.119';
3527 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3528     eval{require Locale::Currency::Format};
3529     if (!$@) {
3530         print "Upgrade to $DBversion done (Locale::Currency::Format installed.)\n";
3531         SetVersion ($DBversion);
3532     }
3533     else {
3534         print "Upgrade to $DBversion done.\n";
3535         print "NOTICE: The Locale::Currency::Format package is not installed on your system or not found in \@INC.\nThis dependency is required in order to include fine information in overdue notices.\nPlease ask your system administrator to install this package.\n";
3536         SetVersion ($DBversion);
3537     }
3538 }
3539
3540 $DBversion = '3.01.00.120';
3541 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3542     $dbh->do(q{
3543 INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('soundon','0','Enable circulation sounds during checkin and checkout in the staff interface.  Not supported by all web browsers yet.','','YesNo');
3544 });
3545     print "Upgrade to $DBversion done (bug 1080: add soundon system preference for circulation sounds)\n";
3546     SetVersion ($DBversion);
3547 }
3548
3549 $DBversion = '3.01.00.121';
3550 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3551     $dbh->do("ALTER TABLE `reserves` ADD `expirationdate` DATE DEFAULT NULL");
3552     $dbh->do("ALTER TABLE `reserves` ADD `lowestPriority` tinyint(1) NOT NULL");
3553     $dbh->do("ALTER TABLE `old_reserves` ADD `expirationdate` DATE DEFAULT NULL");
3554     $dbh->do("ALTER TABLE `old_reserves` ADD `lowestPriority` tinyint(1) NOT NULL");
3555     print "Upgrade to $DBversion done ( Added Additional Fields to Reserves tables )\n";
3556     SetVersion ($DBversion);
3557 }
3558
3559 $DBversion = '3.01.00.122';
3560 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3561     $dbh->do(q{
3562       INSERT INTO systempreferences (variable,value,explanation,options,type)
3563       VALUES ('OAI-PMH:ConfFile', '', 'If empty, Koha OAI Server operates in normal mode, otherwise it operates in extended mode.','','File');
3564 });
3565     print "Upgrade to $DBversion done. — Add a new system preference OAI-PMF:ConfFile\n";
3566     SetVersion ($DBversion);
3567 }
3568
3569 $DBversion = "3.01.00.123";
3570 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3571     $dbh->do("INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3572         (6, 'place_holds', 'Place holds for patrons')");
3573     $dbh->do("INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3574         (6, 'modify_holds_priority', 'Modify holds priority')");
3575     $dbh->do("UPDATE `userflags` SET `flagdesc` = 'Place and modify holds for patrons' WHERE `flag` = 'reserveforothers'");
3576     print "Upgrade to $DBversion done (Add granular permission for holds modification and update description of reserveforothers permission)\n";
3577     SetVersion ($DBversion);
3578 }
3579
3580 $DBversion = '3.01.00.124';
3581 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3582     $dbh->do("
3583         INSERT INTO `letter` (module, code, name, title, content)         VALUES('reserves', 'HOLDPLACED', 'Hold Placed on Item', 'Hold Placed on Item','A hold has been placed on the following item : <<title>> (<<biblionumber>>) by the user <<firstname>> <<surname>> (<<cardnumber>>).');
3584     ");
3585     print "Upgrade to $DBversion done (bug 3242: add HOLDPLACED letter template, which is used when emailLibrarianWhenHoldIsPlaced is enabled)\n";
3586     SetVersion ($DBversion);
3587 }
3588
3589 $DBversion = '3.01.00.125';
3590 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3591     $dbh->do("
3592         INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` ) VALUES ( 'PrintNoticesMaxLines', '0', '', 'If greater than 0, sets the maximum number of lines an overdue notice will print. If the number of items is greater than this number, the notice will end with a warning asking the borrower to check their online account for a full list of overdue items.', 'Integer' );
3593     ");
3594     $dbh->do("
3595         INSERT INTO message_transport_types (message_transport_type) values ('print');
3596     ");
3597     print "Upgrade to $DBversion done (bug 3482: Printable hold and overdue notices)\n";
3598     SetVersion ($DBversion);
3599 }
3600
3601 $DBversion = "3.01.00.126";
3602 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3603         $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('ILS-DI','0','Enable ILS-DI services. See http://your.opac.name/cgi-bin/koha/ilsdi.pl for online documentation.','','YesNo')");
3604         $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('ILS-DI:AuthorizedIPs','127.0.0.1','A comma separated list of IP addresses authorized to access the web services.','','free')");
3605
3606     print "Upgrade to $DBversion done (Adding ILS-DI updates and ILS-DI:AuthorizedIPs)\n";
3607     SetVersion ($DBversion);
3608 }
3609
3610 $DBversion = '3.01.00.127';
3611 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3612     $dbh->do("ALTER TABLE messages CHANGE branchcode branchcode varchar(10);");
3613     print "Upgrade to $DBversion done (bug 4190: messages in patron account did not work with branchcodes > 4)\n";
3614     SetVersion ($DBversion);
3615 }
3616
3617 $DBversion = '3.01.00.128';
3618 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3619     $dbh->do('CREATE INDEX budget_id ON aqorders (budget_id );');
3620     print "Upgrade to $DBversion done (bug 4331: index orders by budget_id)\n";
3621     SetVersion ($DBversion);
3622 }
3623
3624 $DBversion = "3.01.00.129";
3625 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3626         $dbh->do("UPDATE `permissions` SET `code` = 'items_batchdel' WHERE `permissions`.`module_bit` =13 AND `permissions`.`code` = 'batchdel' LIMIT 1 ;");
3627         $dbh->do("UPDATE `permissions` SET `code` = 'items_batchmod' WHERE `permissions`.`module_bit` =13 AND `permissions`.`code` = 'batchmod' LIMIT 1 ;");
3628         print "Upgrade to $DBversion done (Change permissions names for item batch modification / deletion)\n";
3629
3630     SetVersion ($DBversion);
3631 }
3632
3633 $DBversion = "3.01.00.130";
3634 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3635     $dbh->do("UPDATE reserves SET expirationdate = NULL WHERE expirationdate = '0000-00-00'");
3636     print "Upgrade to $DBversion done (change reserves.expirationdate values of 0000-00-00 to NULL (bug 1532)\n";
3637     SetVersion ($DBversion);
3638 }
3639
3640 $DBversion = "3.01.00.131";
3641 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3642         $dbh->do(q{
3643 INSERT IGNORE INTO message_transport_types (message_transport_type) VALUES ('print'),('feed');
3644     });
3645     print "Upgrade to $DBversion done (adding print and feed message transport types)\n";
3646     SetVersion ($DBversion);
3647 }
3648
3649 $DBversion = "3.01.00.132";
3650 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3651         $dbh->do(q{
3652     ALTER TABLE language_descriptions ADD INDEX subtag_type_lang (subtag, type, lang);
3653     });
3654     print "Upgrade to $DBversion done (Adding index to language_descriptions table)\n";
3655     SetVersion ($DBversion);
3656 }
3657
3658 $DBversion = '3.01.00.133';
3659 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3660     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OverduesBlockCirc','noblock','When checking out an item should overdues block checkout, generate a confirmation dialogue, or allow checkout','noblock|confirmation|block','Choice')");
3661     print "Upgrade to $DBversion done (bug 4405: added OverduesBlockCirc syspref to control whether circulation is blocked if a borrower has overdues)\n";
3662     SetVersion ($DBversion);
3663 }
3664
3665 $DBversion = '3.01.00.134';
3666 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3667     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('DisplayMultiPlaceHold','1','Display the ability to place multiple holds or not','','YesNo')");
3668     print "Upgrade to $DBversion done (adding syspref DisplayMultiPlaceHold to control whether multiple holds can be placed from the search results page)\n";
3669     SetVersion ($DBversion);
3670 }
3671
3672 $DBversion = '3.01.00.135';
3673 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3674     $dbh->do("
3675         INSERT INTO `letter` (module, code, name, title, content) VALUES
3676 ('reserves', 'HOLD_PRINT', 'Hold Available for Pickup (print notice)', 'Hold Available for Pickup (print notice)', '<<branches.branchname>>\r\n<<branches.branchaddress1>>\r\n<<branches.branchaddress2>>\r\n\r\n\r\nChange Service Requested\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n<<borrowers.firstname>> <<borrowers.surname>>\r\n<<borrowers.address>>\r\n<<borrowers.city>> <<borrowers.zipcode>>\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n<<borrowers.firstname>> <<borrowers.surname>> <<borrowers.cardnumber>>\r\n\r\nYou have a hold available for pickup as of <<reserves.waitingdate>>:\r\n\r\nTitle: <<biblio.title>>\r\nAuthor: <<biblio.author>>\r\nCopy: <<items.copynumber>>\r\n')
3677 ");
3678     print "Upgrade to $DBversion done (bug 4377: added HOLD_PRINT message template)\n";
3679     SetVersion ($DBversion);
3680 }
3681
3682 $DBversion = '3.01.00.136';
3683 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3684     $dbh->do(qq{
3685 INSERT INTO permissions (module_bit, code, description) VALUES
3686    ( 9, 'edit_items', 'Edit Items');});
3687     print "Upgrade to $DBversion done (Adding a new permission to edit items)\n";
3688     SetVersion ($DBversion);
3689 }
3690
3691 $DBversion = "3.01.00.137";
3692 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3693         $dbh->do("
3694           INSERT INTO permissions (module_bit, code, description) VALUES
3695           (15, 'check_expiration', 'Check the expiration of a serial'),
3696           (15, 'claim_serials', 'Claim missing serials'),
3697           (15, 'create_subscription', 'Create a new subscription'),
3698           (15, 'delete_subscription', 'Delete an existing subscription'),
3699           (15, 'edit_subscription', 'Edit an existing subscription'),
3700           (15, 'receive_serials', 'Serials receiving'),
3701           (15, 'renew_subscription', 'Renew a subscription'),
3702           (15, 'routing', 'Routing');
3703                  ");
3704     print "Upgrade to $DBversion done (adding granular permissions for serials)\n";
3705     SetVersion ($DBversion);
3706 }
3707
3708 $DBversion = "3.01.00.138";
3709 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3710     $dbh->do("DELETE FROM systempreferences WHERE variable = 'GranularPermissions'");
3711     print "Upgrade to $DBversion done (bug 4896: removing GranularPermissions syspref; use of granular permissions is now the default)\n";
3712     SetVersion ($DBversion);
3713 }
3714
3715 $DBversion = '3.01.00.139';
3716 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3717     $dbh->do("ALTER TABLE message_attributes CHANGE message_name message_name varchar(40);");
3718     print "Upgrade to $DBversion done (bug 3682: change message_name from varchar(20) to varchar(40))\n";
3719     SetVersion ($DBversion);
3720 }
3721
3722 $DBversion = '3.01.00.140';
3723 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3724     $dbh->do("UPDATE systempreferences SET value = '0' WHERE variable = 'TagsModeration' AND value is NULL");
3725     print "Upgrade to $DBversion done (bug 4312 TagsModeration changed from NULL to 0)\n";
3726     SetVersion ($DBversion);
3727 }
3728
3729 $DBversion = '3.01.00.141';
3730 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3731     $dbh->do(qq{DELETE FROM message_attributes WHERE message_attribute_id=3;});
3732     $dbh->do(qq{DELETE FROM letter WHERE code='EVENT' AND title='Upcoming Library Event';});
3733     print "Upgrade to $DBversion done Remove upcoming events messaging option (bug 2434)\n";
3734     SetVersion ($DBversion);
3735 }
3736
3737 $DBversion = '3.01.00.142';
3738 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3739     $dbh->do(qq{DELETE FROM message_transports WHERE message_attribute_id=3;});
3740     print "Upgrade to $DBversion done (Remove upcoming events messaging option part 2 (bug 2434))\n";
3741     SetVersion ($DBversion);
3742 }
3743
3744 $DBversion = '3.01.00.143';
3745 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3746     $dbh->do(qq{CREATE INDEX auth_value_idx ON authorised_values (authorised_value)});
3747     $dbh->do(qq{CREATE INDEX auth_val_cat_idx ON borrower_attribute_types (authorised_value_category)});
3748     print "Upgrade to $DBversion done (Create index on authorised_values and borrower_attribute_types (bug 4139))\n";
3749     SetVersion ($DBversion);
3750 }
3751
3752 $DBversion = '3.01.00.144';
3753 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3754     $dbh->do(qq{UPDATE systempreferences SET value='normal' where value='default' and variable='IntranetBiblioDefaultView'});
3755     print "Upgrade to $DBversion done (Update the 'default' to 'normal' for the IntranetBiblioDefaultView syspref (bug 5007))\n";
3756     SetVersion ($DBversion);
3757 }
3758
3759 $DBversion = "3.01.00.145";
3760 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3761     $dbh->do("ALTER TABLE borrowers ADD KEY `guarantorid` (guarantorid);");
3762     print "Upgrade to $DBversion done (Add index on guarantorid)\n";
3763     SetVersion ($DBversion);
3764 }
3765
3766 $DBversion = '3.01.00.999';
3767 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3768     print "Upgrade to $DBversion done (3.2.0 release candidate)\n";
3769     SetVersion ($DBversion);
3770 }
3771
3772 $DBversion = "3.02.00.000";
3773 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3774     my $value = $dbh->selectrow_array("SELECT value FROM systempreferences WHERE variable = 'HomeOrHoldingBranch'");
3775     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('HomeOrHoldingBranchReturn','$value','Used by Circulation to determine which branch of an item to check checking-in items','holdingbranch|homebranch','Choice');");
3776     print "Upgrade to $DBversion done (Add HomeOrHoldingBranchReturn system preference)\n";
3777     SetVersion ($DBversion);
3778 }
3779
3780 $DBversion = "3.02.00.001";
3781 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3782     $dbh->do(q{DELETE FROM systempreferences WHERE variable IN (
3783                 'holdCancelLength',
3784                 'PINESISBN',
3785                 'sortbynonfiling',
3786                 'TemplateEncoding',
3787                 'OPACSubscriptionDisplay',
3788                 'OPACDisplayExtendedSubInfo',
3789                 'OAI-PMH:Set',
3790                 'OAI-PMH:Subset',
3791                 'libraryAddress',
3792                 'kohaspsuggest',
3793                 'OrderPdfTemplate',
3794                 'marc',
3795                 'acquisitions',
3796                 'MIME')
3797                }
3798     );
3799     print "Upgrade to $DBversion done (bug 3756: remove disused system preferences)\n";
3800     SetVersion ($DBversion);
3801 }
3802
3803 $DBversion = "3.02.00.002";
3804 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3805     $dbh->do(q{DELETE FROM systempreferences WHERE variable = 'OpacPrivacy'});
3806     print "Upgrade to $DBversion done (bug 3881: remove unused OpacPrivacy system preference)\n";
3807     SetVersion ($DBversion);
3808 }
3809
3810 $DBversion = "3.02.00.003";
3811 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3812     $dbh->do(q{UPDATE systempreferences SET variable = 'ILS-DI:AuthorizedIPs' WHERE variable = 'ILS-DI:Authorized_IPs'});
3813     print "Upgrade to $DBversion done (correct ILS-DI:AuthorizedIPs)\n";
3814     SetVersion ($DBversion);
3815 }
3816
3817 $DBversion = "3.02.00.004";
3818 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3819     print "Upgrade to $DBversion done (3.2.0 general release)\n";
3820     SetVersion ($DBversion);
3821 }
3822 # This is the point where 3.2.x and master diverged, we can use $original_version to make sure we don't
3823
3824 # apply updates that have already been done
3825
3826 $DBversion = "3.03.00.001";
3827 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.005")) {
3828     $dbh->do("DELETE FROM subscriptionroutinglist WHERE borrowernumber IS NULL;");
3829     $dbh->do("ALTER TABLE subscriptionroutinglist MODIFY COLUMN `borrowernumber` int(11) NOT NULL;");
3830     $dbh->do("DELETE FROM subscriptionroutinglist WHERE subscriptionid IS NULL;");
3831     $dbh->do("ALTER TABLE subscriptionroutinglist MODIFY COLUMN `subscriptionid` int(11) NOT NULL;");
3832     $dbh->do("CREATE TEMPORARY TABLE del_subscriptionroutinglist
3833               SELECT s1.routingid FROM subscriptionroutinglist s1
3834               WHERE EXISTS (SELECT * FROM subscriptionroutinglist s2
3835                             WHERE s2.borrowernumber = s1.borrowernumber
3836                             AND   s2.subscriptionid = s1.subscriptionid
3837                             AND   s2.routingid < s1.routingid);");
3838     $dbh->do("DELETE FROM subscriptionroutinglist
3839               WHERE routingid IN (SELECT routingid FROM del_subscriptionroutinglist);");
3840     $dbh->do("ALTER TABLE subscriptionroutinglist ADD UNIQUE (subscriptionid, borrowernumber);");
3841     $dbh->do("ALTER TABLE subscriptionroutinglist
3842                 ADD CONSTRAINT `subscriptionroutinglist_ibfk_1` FOREIGN KEY (`borrowernumber`)
3843                 REFERENCES `borrowers` (`borrowernumber`)
3844                 ON DELETE CASCADE ON UPDATE CASCADE");
3845     $dbh->do("ALTER TABLE subscriptionroutinglist
3846                 ADD CONSTRAINT `subscriptionroutinglist_ibfk_2` FOREIGN KEY (`subscriptionid`)
3847                 REFERENCES `subscription` (`subscriptionid`)
3848                 ON DELETE CASCADE ON UPDATE CASCADE");
3849     print "Upgrade to $DBversion done (Make subscriptionroutinglist more strict)\n";
3850     SetVersion ($DBversion);
3851 }
3852
3853 $DBversion = '3.03.00.002';
3854 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.006")) {
3855     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='arm' WHERE rfc4646_subtag='hy';");
3856     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='eng' WHERE rfc4646_subtag='en';");
3857     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'fi','fin');");
3858     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='fre' WHERE rfc4646_subtag='fr';");
3859     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'lo','lao');");
3860     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='ita' WHERE rfc4646_subtag='it';");
3861     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'sr','srp');");
3862     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'tet','tet');");
3863     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'ur','urd');");
3864
3865     print "Upgrade to $DBversion done (Correct language mappings)\n";
3866     SetVersion ($DBversion);
3867 }
3868
3869 $DBversion = '3.03.00.003';
3870 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.007")) {
3871     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('UseTablesortForCirc','0','If on, use the JQuery tablesort function on the list of current borrower checkouts on the circulation page. Note that the use of this function may slow down circ for patrons with may checkouts.','','YesNo');");
3872     print "Upgrade to $DBversion done (Add UseTablesortForCirc syspref)\n";
3873     SetVersion ($DBversion);
3874 }
3875
3876 $DBversion = '3.03.00.004';
3877 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.001")) {
3878     my $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'ACCEPTED');
3879     $dbh->do(q/
3880 INSERT INTO `letter`
3881 (module, code, name, title, content)
3882 VALUES
3883 ('suggestions','ACCEPTED','Suggestion accepted', 'Purchase suggestion accepted','Dear <<borrowers.firstname>> <<borrowers.surname>>,\n\nYou have suggested that the library acquire <<suggestions.title>> by <<suggestions.author>>.\n\nThe library has reviewed your suggestion today. The item will be ordered as soon as possible. You will be notified by mail when the order is completed, and again when the item arrives at the library.\n\nIf you have any questions, please email us at <<branches.branchemail>>.\n\nThank you,\n\n<<branches.branchname>>')
3884 /) unless $count > 0;
3885     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'AVAILABLE');
3886     $dbh->do(q/
3887 INSERT INTO `letter`
3888 (module, code, name, title, content)
3889 VALUES
3890 ('suggestions','AVAILABLE','Suggestion available', 'Suggested purchase available','Dear <<borrowers.firstname>> <<borrowers.surname>>,\n\nYou have suggested that the library acquire <<suggestions.title>> by <<suggestions.author>>.\n\nWe are pleased to inform you that the item you requested is now part of the collection.\n\nIf you have any questions, please email us at <<branches.branchemail>>.\n\nThank you,\n\n<<branches.branchname>>')
3891 /) unless $count > 0;
3892     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'ORDERED');
3893     $dbh->do(q/
3894 INSERT INTO `letter`
3895 (module, code, name, title, content)
3896 VALUES
3897 ('suggestions','ORDERED','Suggestion ordered', 'Suggested item ordered','Dear <<borrowers.firstname>> <<borrowers.surname>>,\n\nYou have suggested that the library acquire <<suggestions.title>> by <<suggestions.author>>.\n\nWe are pleased to inform you that the item you requested has now been ordered. It should arrive soon, at which time it will be processed for addition into the collection.\n\nYou will be notified again when the book is available.\n\nIf you have any questions, please email us at <<branches.branchemail>>\n\nThank you,\n\n<<branches.branchname>>')
3898 /) unless $count > 0;
3899     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'REJECTED');
3900     $dbh->do(q/
3901 INSERT INTO `letter`
3902 (module, code, name, title, content)
3903 VALUES
3904 ('suggestions','REJECTED','Suggestion rejected', 'Purchase suggestion declined','Dear <<borrowers.firstname>> <<borrowers.surname>>,\n\nYou have suggested that the library acquire <<suggestions.title>> by <<suggestions.author>>.\n\nThe library has reviewed your request today, and has decided not to accept the suggestion at this time.\n\nThe reason given is: <<suggestions.reason>>\n\nIf you have any questions, please email us at <<branches.branchemail>>.\n\nThank you,\n\n<<branches.branchname>>')
3905 /) unless $count > 0;
3906     print "Upgrade to $DBversion done (bug 5127: add default templates for suggestion status change notifications)\n";
3907     SetVersion ($DBversion);
3908 };
3909
3910 $DBversion = '3.03.00.005';
3911 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3912     $dbh->do("update `systempreferences` set options='whitespace|T-prefix|cuecat|libsuite8' where variable='itemBarcodeInputFilter'");
3913     print "Upgrade to $DBversion done (Add itemBarcodeInputFilter choice libsuite8)\n";
3914 }
3915
3916 $DBversion = '3.03.00.006';
3917 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.002")) {
3918     $dbh->do("ALTER TABLE deletedborrowers ADD `privacy` int(11) AFTER smsalertnumber;");
3919     $dbh->do("ALTER TABLE deletedborrowers CHANGE `cardnumber` `cardnumber` varchar(16);");
3920     print "Upgrade to $DBversion done (Fix differences between borrowers and deletedborrowers)\n";
3921     SetVersion ($DBversion);
3922 }
3923
3924 $DBversion = '3.03.00.007';
3925 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3926     $dbh->do("ALTER table suggestions ADD quantity SMALLINT(6) default NULL,
3927                 ADD currency VARCHAR(3) default NULL,
3928                 ADD price DECIMAL(28,6) default NULL,
3929                 ADD total DECIMAL(28,6) default NULL;
3930                 ");
3931     print "Upgrade to $DBversion done (Added acq related columns to suggestions)\n";
3932     SetVersion ($DBversion);
3933 }
3934
3935 $DBversion = '3.03.00.008';
3936 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3937     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACNoResultsFound','','Display this HTML when no results are found for a search in the OPAC','70|10','Textarea')");
3938     print "Upgrade to $DBversion done (adding syspref OPACNoResultsFound to control what displays when no results are found for a search in the OPAC.)\n";
3939     SetVersion ($DBversion);
3940 }
3941
3942 $DBversion = '3.03.00.009';
3943 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.003")) {
3944     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('IntranetUserCSS','','Add CSS to be included in the Intranet',NULL,'free')");
3945     print "Upgrade to $DBversion done (Add IntranetUserCSS syspref)\n";
3946     SetVersion ($DBversion);
3947 }
3948
3949 $DBversion = "3.03.00.010";
3950 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.02.001")) {
3951     $dbh->do("UPDATE `marc_subfield_structure` SET liblibrarian = 'Distance from earth' WHERE liblibrarian = 'Distrance from earth' AND tagfield = '034' AND tagsubfield = 'r';");
3952     $dbh->do("UPDATE `marc_subfield_structure` SET libopac = 'Distance from earth' WHERE libopac = 'Distrance from earth' AND tagfield = '034' AND tagsubfield = 'r';");
3953     print "Upgrade to $DBversion done (Fix misspelled 034r subfield in MARC21 Frameworks)\n";
3954     SetVersion ($DBversion);
3955 }
3956
3957 $DBversion = "3.03.00.011";
3958 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3959     $dbh->do("UPDATE aqbooksellers SET gstrate=NULL WHERE gstrate=0.0");
3960     print "Upgrade to $DBversion done (Bug 5186: allow GST rate to be set to 0)\n";
3961     SetVersion ($DBversion);
3962 }
3963
3964 $DBversion = "3.03.00.012";
3965 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3966    $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('maxItemsInSearchResults',20,'Specify the maximum number of items to display for each result on a page of results',NULL,'free')");
3967    print "Upgrade to $DBversion done (Bug 2142: maxItemsInSearchResults syspref resurrected)\n";
3968    SetVersion ($DBversion);
3969 }
3970
3971 $DBversion = "3.03.00.013";
3972 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3973     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OpacPublic','1','If set to OFF and user is not logged in, all  OPAC pages require authentication, and OPAC searchbar is removed)','','YesNo')");
3974     print "Upgrade to $DBversion done (added 'OpacPublic' syspref)\n";
3975    SetVersion ($DBversion);
3976 }
3977
3978 $DBversion = "3.03.00.014";
3979 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3980     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('ShelfBrowserUsesLocation','1','Use the item location when finding items for the shelf browser.','1','YesNo')");
3981     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('ShelfBrowserUsesHomeBranch','1','Use the item home branch when finding items for the shelf browser.','1','YesNo')");
3982     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('ShelfBrowserUsesCcode','0','Use the item collection code when finding items for the shelf browser.','1','YesNo')");
3983     print "Upgrade to $DBversion done (Add flexible shelf browser constraints)\n";
3984     SetVersion ($DBversion);
3985 }
3986
3987 $DBversion = "3.03.00.015";
3988 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3989     if ( C4::Context->preference("marcflavour") eq "MARC21" ) {
3990         my $sth = $dbh->prepare(
3991 "INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`,
3992                              `tab`, `authorised_value`, `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`)
3993                              VALUES ( ?, '9', '9 (RLIN)', '9 (RLIN)', 0, 0, '', 6, '', '', '', 0, -5, '', '', '', NULL)"
3994         );
3995         $sth->execute('648');
3996         $sth->execute('654');
3997         $sth->execute('655');
3998         $sth->execute('656');
3999         $sth->execute('657');
4000         $sth->execute('658');
4001         $sth->execute('662');
4002         $sth->finish;
4003         print
4004 "Upgrade to $DBversion done (Bug 5619: Add subfield 9 to marc21 648,654,655,656,657,658,662)\n";
4005     }
4006     SetVersion($DBversion);
4007 }
4008
4009 $DBversion = '3.03.00.016';
4010 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4011     # reimplement OpacPrivacy system preference
4012     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacPrivacy', '0', 'if ON, allows patrons to define their privacy rules (reading history)',NULL,'YesNo')");
4013     $dbh->do("ALTER TABLE `borrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
4014     $dbh->do("ALTER TABLE `deletedborrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
4015     print "Upgrade to $DBversion done (OpacPrivacy reimplementation)\n";
4016     SetVersion($DBversion);
4017 };
4018
4019 $DBversion = '3.03.00.017';
4020 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.001")) {
4021     $dbh->do("ALTER TABLE  `currency` CHANGE `rate` `rate` FLOAT( 15, 5 ) NULL DEFAULT NULL;");
4022     print "Upgrade to $DBversion done (Enable currency rates >= 100)\n";
4023     SetVersion ($DBversion);
4024 }
4025
4026 $DBversion = '3.03.00.018';
4027 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.002")) {
4028     $dbh->do( q|update language_descriptions set description = 'Nederlands' where lang = 'nl' and subtag = 'nl'|);
4029     $dbh->do( q|update language_descriptions set description = 'Dansk' where lang = 'da' and subtag = 'da'|);
4030     print "Upgrade to $DBversion done (Correct language descriptions)\n";
4031     SetVersion ($DBversion);
4032 }
4033
4034 $DBversion = '3.03.00.019';
4035 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.003")) {
4036     # Fix bokmål
4037     $dbh->do("UPDATE language_subtag_registry SET description = 'Norwegian bokm&#229;l' WHERE subtag = 'nb';");
4038     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'nb','nob');");
4039     $dbh->do("UPDATE language_descriptions SET description = 'Norsk bokm&#229;l' WHERE subtag = 'nb' AND lang = 'nb';");
4040     $dbh->do("UPDATE language_descriptions SET description = 'Norwegian bokm&#229;l' WHERE subtag = 'nb' AND lang = 'en';");
4041     $dbh->do("UPDATE language_descriptions SET description = 'Norvégien bokm&#229;l' WHERE subtag = 'nb' AND lang = 'fr';");
4042     # Add nynorsk
4043     $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'nn', 'language', 'Norwegian nynorsk','2011-02-14' )");
4044     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'nn','nno')");
4045     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'nb', 'Norsk nynorsk')");
4046     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'nn', 'Norsk nynorsk')");
4047     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'en', 'Norwegian nynorsk')");
4048     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'fr', 'Norvégien nynorsk')");
4049     print "Upgrade to $DBversion done (Correct language descriptions for Norwegian)\n";
4050     SetVersion ($DBversion);
4051 }
4052
4053 $DBversion = '3.03.00.020';
4054 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4055     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('AllowFineOverride','0','If on, staff will be able to issue books to patrons with fines greater than noissuescharge.','0','YesNo')");
4056     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('AllFinesNeedOverride','1','If on, staff will be asked to override every fine, even if it is below noissuescharge.','0','YesNo')");
4057     print "Upgrade to $DBversion done (Bug 5811: Add sysprefs controlling overriding fines)\n";
4058     SetVersion($DBversion);
4059 };
4060
4061 $DBversion = '3.03.00.021';
4062 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.001")) {
4063     $dbh->do("ALTER TABLE items MODIFY enumchron TEXT");
4064     $dbh->do("ALTER TABLE deleteditems MODIFY enumchron TEXT");
4065     print "Upgrade to $DBversion done (bug 5642: longer serial enumeration)\n";
4066     SetVersion ($DBversion);
4067 }
4068
4069 $DBversion = '3.03.00.022';
4070 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4071     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('AuthoritiesLog','0','If ON, log edit/create/delete actions on authorities.','','YesNo');");
4072     print "Upgrade to $DBversion done (Add AuthoritiesLog syspref)\n";
4073     SetVersion ($DBversion);
4074 }
4075
4076 # due to a mismatch in kohastructure.sql some koha will have missing columns in aqbasketgroup
4077 # this attempts to fix that
4078 $DBversion = '3.03.00.023';
4079 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.002")) {
4080     my $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'billingplace'");
4081     $sth->execute;
4082     $dbh->do("ALTER TABLE aqbasketgroups ADD billingplace VARCHAR(10)") if ! $sth->fetchrow_hashref;
4083     $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'deliveryplace'");
4084     $sth->execute;
4085     $dbh->do("ALTER TABLE aqbasketgroups ADD deliveryplace VARCHAR(10)") if ! $sth->fetchrow_hashref;
4086     $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'deliverycomment'");
4087     $sth->execute;
4088     $dbh->do("ALTER TABLE aqbasketgroups ADD deliverycomment VARCHAR(255)") if ! $sth->fetchrow_hashref;
4089     print "Upgrade to $DBversion done (Reconcile aqbasketgroups)\n";
4090     SetVersion ($DBversion);
4091 }
4092
4093 $DBversion = '3.03.00.024';
4094 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4095     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('TraceCompleteSubfields','0','Force subject tracings to only match complete subfields.','0','YesNo')");
4096     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('UseAuthoritiesForTracings','1','Use authority record numbers for subject tracings instead of heading strings.','0','YesNo')");
4097     print "Upgrade to $DBversion done (Add syspref to force whole-subfield matching on subject tracings)\n";
4098     SetVersion($DBversion);
4099 };
4100
4101 $DBversion = "3.03.00.025";
4102 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4103     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAllowUserToChooseBranch', 1, 'Allow the user to choose the branch they want to pickup their hold from','1','YesNo')");
4104     print "Upgrade to $DBversion done (Add syspref to control if user can choose pickup branch for holds)\n";
4105     SetVersion ($DBversion);
4106 }
4107
4108 $DBversion = '3.03.00.026';
4109 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.003")) {
4110     $dbh->do("UPDATE `message_attributes` SET message_name='Item Due' WHERE message_attribute_id=1 AND message_name LIKE 'Item DUE'");
4111         print "Upgrade to $DBversion done ( fix capitalization in message type )\n";
4112     SetVersion ($DBversion);
4113 }
4114
4115 $DBversion = '3.03.00.027';
4116 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4117     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('displayFacetCount', '0', NULL, NULL, 'YesNo')");
4118     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('maxRecordsForFacets', '20', NULL, NULL, 'Integer')");
4119     print "Upgrade to $DBversion done (Preferences for facet count)\n";
4120     SetVersion ($DBversion);
4121 }
4122
4123 $DBversion = "3.03.00.028";
4124 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4125     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('FacetLabelTruncationLength', 20, 'Truncate facets length to','','free')");
4126     print "Upgrade to $DBversion done (Add FacetLabelTruncationLength syspref to control facets displayed length)\n";
4127     SetVersion ($DBversion);
4128 }
4129
4130 $DBversion = "3.03.00.029";
4131 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4132     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AllowPurchaseSuggestionBranchChoice', 0, 'Allow user to choose branch when making a purchase suggestion','1','YesNo')");
4133     print "Upgrade to $DBversion done (Add syspref to control if user can choose branch when making purchase suggestion)\n";
4134     SetVersion ($DBversion);
4135 }
4136
4137 $DBversion = "3.03.00.030";
4138 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4139     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacFavicon','','Enter a complete URL to an image to replace the default Koha favicon on the OPAC','','free')");
4140     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('IntranetFavicon','','Enter a complete URL to an image to replace the default Koha favicon on the Staff client','','free')");
4141     print "Upgrade to $DBversion done (Add sysprefs to control custom favicons)\n";
4142     SetVersion ($DBversion);
4143 }
4144
4145 $DBversion = "3.03.00.031";
4146 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4147     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('FineNotifyAtCheckin',0,'If ON notify librarians of overdue fines on the items they are checking in.',NULL,'YesNo');");
4148     print "Upgrade to $DBversion done (Add syspref FineNotifyAtCheckin)\n";
4149     SetVersion ($DBversion);
4150 }
4151
4152 $DBversion = '3.03.00.032';
4153 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4154     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('TraceSubjectSubdivisions', 1, 'Create searches on all subdivisions for subject tracings.','1','YesNo')");
4155     print "Upgrade to $DBversion done ( include subdivisions when generating subject tracing searches )\n";
4156 }
4157
4158
4159 $DBversion = '3.03.00.033';
4160 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4161     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('StaffAuthorisedValueImages', '1', '', NULL, 'YesNo')");
4162     print "Upgrade to $DBversion done (System pref StaffAuthorisedValueImages)\n";
4163     SetVersion ($DBversion);
4164 }
4165
4166 $DBversion = '3.03.00.034';
4167 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4168     $dbh->do("ALTER TABLE `categories` ADD `hidelostitems` tinyint(1) NOT NULL default '0' AFTER `reservefee`");
4169     print "Upgrade to $DBversion done (Add hidelostitems preference to borrower categories)\n";
4170     SetVersion ($DBversion);
4171 }
4172
4173 $DBversion = '3.03.00.035';
4174 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4175     $dbh->do("ALTER TABLE `issuingrules` ADD hardduedate date default NULL AFTER issuelength");
4176     $dbh->do("ALTER TABLE `issuingrules` ADD hardduedatecompare tinyint NOT NULL default 0 AFTER hardduedate");
4177     my $duedate;
4178     if (C4::Context->preference("globalDueDate")) {
4179       $duedate = eval { output_pref( { dt => dt_from_string( C4::Context->preference("globalDueDate") ), dateonly => 1, dateformat => 'iso' } ); };
4180       $dbh->do("UPDATE `issuingrules` SET hardduedate = '$duedate', hardduedatecompare = 0");
4181     } elsif (C4::Context->preference("ceilingDueDate")) {
4182       $duedate = eval { output_pref( { dt => dt_from_string( C4::Context->preference("ceilingDueDate") ), dateonly => 1, dateformat => 'iso' } ); };
4183       $dbh->do("UPDATE `issuingrules` SET hardduedate = '$duedate', hardduedatecompare = -1");
4184     }
4185     $dbh->do("DELETE FROM `systempreferences` WHERE variable = 'globalDueDate' OR variable = 'ceilingDueDate'");
4186     print "Upgrade to $DBversion done (Move global and ceiling due dates to Circ Rules level)\n";
4187     SetVersion ($DBversion);
4188 }
4189
4190 $DBversion = '3.03.00.036';
4191 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4192     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('COinSinOPACResults', 1, 'If ON, use COinS in OPAC search results page.  NOTE: this can slow down search response time significantly','','YesNo')");
4193     print "Upgrade to $DBversion done ( Make COinS optional in OPAC search results )\n";
4194     SetVersion ($DBversion);
4195 }
4196
4197 $DBversion = '3.03.00.037';
4198 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4199     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACDisplay856uAsImage','OFF','Display the URI in the 856u field as an image, the corresponding OPACXSLT option must be on','OFF|Details|Results|Both','Choice')");
4200     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('Display856uAsImage','OFF','Display the URI in the 856u field as an image, the corresponding Staff Client XSLT option must be on','OFF|Details|Results|Both','Choice')");
4201     print "Upgrade to $DBversion done (Add 'Display856uAsImage' and 'OPACDisplay856uAsImage' syspref)\n";
4202     SetVersion ($DBversion);
4203 }
4204
4205 $DBversion = '3.03.00.038';
4206 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4207     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('SelfCheckTimeout',120,'Define the number of seconds before the Web-based Self Checkout times out a patron','','Integer')");
4208     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('AllowSelfCheckReturns',0,'If enabled, patrons may return items through the Web-based Self Checkout','','YesNo')");
4209     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('SelfCheckHelpMessage','','Enter HTML to include under the basic Web-based Self Checkout instructions on the Help page','70|10','Textarea')");
4210     print "Upgrade to $DBversion done ( Add Self-checkout by Login system preferences )\n";
4211 }
4212
4213 $DBversion = "3.03.00.039";
4214 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4215     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('ShowReviewer',1,'If ON, name of reviewer will be shown above comments in OPAC',NULL,'YesNo');");
4216     print "Upgrade to $DBversion done (Add syspref ShowReviewer)\n";
4217 }
4218
4219 $DBversion = "3.03.00.040";
4220 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4221     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('UseControlNumber',0,'If ON, record control number (w subfields) and control number (001) are used for linking of bibliographic records.','','YesNo');");
4222     print "Upgrade to $DBversion done (Add syspref UseControlNumber)\n";
4223 }
4224
4225 $DBversion = "3.03.00.041";
4226 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4227     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AlternateHoldingsField','','The MARC field/subfield that contains alternate holdings information for bibs taht do not have items attached (e.g. 852abchi for libraries converting from MARC Magician).',NULL,'free')");
4228     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AlternateHoldingsSeparator','','The string to use to separate subfields in alternate holdings displays.',NULL,'free')");
4229     print "Upgrade to $DBversion done (Add sysprefs to control alternate holdings information display)\n";
4230     SetVersion ($DBversion);
4231 }
4232
4233 $DBversion = '3.03.00.042';
4234 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4235     stocknumber_checker();
4236     print "Upgrade to $DBversion done (5860 Index itemstocknumber)\n";
4237     SetVersion ($DBversion);
4238 }
4239
4240 sub stocknumber_checker { #code reused later on
4241   my @row;
4242   #drop the obsolete itemSStocknumber idx if it exists
4243   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemsstocknumberidx'");
4244   $dbh->do("ALTER TABLE `items` DROP INDEX `itemsstocknumberidx`;") if @row;
4245
4246   #check itemstocknumber idx; remove it if it is unique
4247   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemstocknumberidx' AND non_unique=0");
4248   $dbh->do("ALTER TABLE `items` DROP INDEX `itemstocknumberidx`;") if @row;
4249
4250   #add itemstocknumber index non-unique IF it still not exists
4251   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemstocknumberidx'");
4252   $dbh->do("ALTER TABLE items ADD INDEX itemstocknumberidx (stocknumber);") unless @row;
4253 }
4254
4255 $DBversion = "3.03.00.043";
4256 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4257
4258     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib,lib_opac) VALUES ('YES_NO','0','No','No')");
4259     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib,lib_opac) VALUES ('YES_NO','1','Yes','Yes')");
4260
4261         print "Upgrade to $DBversion done ( add generic boolean YES_NO authorised_values pair )\n";
4262         SetVersion ($DBversion);
4263 }
4264
4265 $DBversion = '3.03.00.044';
4266 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4267     $dbh->do("ALTER TABLE `aqbasketgroups` ADD `freedeliveryplace` TEXT NULL AFTER `deliveryplace`;");
4268     print "Upgrade to $DBversion done (adding freedeliveryplace to basketgroups)\n";
4269 }
4270
4271 $DBversion = '3.03.00.045';
4272 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4273     #Remove obsolete columns from aqbooksellers if needed
4274     my $a = $dbh->selectall_hashref('SHOW columns from aqbooksellers','Field');
4275     my $sqldrop="ALTER TABLE aqbooksellers DROP COLUMN ";
4276     foreach(qw/deliverydays followupdays followupscancel invoicedisc nocalc specialty/) {
4277       $dbh->do($sqldrop.$_) if exists $a->{$_};
4278     }
4279     #Remove obsolete column from aqbudgets if needed
4280     #The correct column is budget_notes
4281     $a = $dbh->selectall_hashref('SHOW columns from aqbudgets','Field');
4282     if(exists $a->{budget_description}) {
4283       $dbh->do("ALTER TABLE aqbudgets DROP COLUMN budget_description");
4284     }
4285     print "Upgrade to $DBversion done (Remove obsolete columns from aqbooksellers and aqbudgets if needed)\n";
4286     SetVersion ($DBversion);
4287 }
4288
4289 $DBversion = "3.03.00.046";
4290 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4291     $dbh->do("ALTER TABLE overduerules ALTER delay1 SET DEFAULT NULL, ALTER delay2 SET DEFAULT NULL, ALTER delay3 SET DEFAULT NULL");
4292     print "Upgrade to $DBversion done (Setting NULL default value for delayn columns in table overduerules)\n";
4293     SetVersion($DBversion);
4294 }
4295
4296 $DBversion = '3.03.00.047';
4297 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4298     $dbh->do("ALTER TABLE borrowers ADD `state` mediumtext AFTER city;");
4299     $dbh->do("ALTER TABLE borrowers ADD `B_state` mediumtext AFTER B_city;");
4300     $dbh->do("ALTER TABLE borrowers ADD `altcontactstate` mediumtext AFTER altcontactaddress3;");
4301     $dbh->do("ALTER TABLE deletedborrowers ADD `state` mediumtext AFTER city;");
4302     $dbh->do("ALTER TABLE deletedborrowers ADD `B_state` mediumtext AFTER B_city;");
4303     $dbh->do("ALTER TABLE deletedborrowers ADD `altcontactstate` mediumtext AFTER altcontactaddress3;");
4304     print "Upgrade to $DBversion done (Add state field to patron's addresses)\n";
4305 }
4306
4307 $DBversion = '3.03.00.048';
4308 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4309     $dbh->do("ALTER TABLE branches ADD `branchstate` mediumtext AFTER `branchcity`;");
4310     print "Upgrade to $DBversion done (Add state to branch address)\n";
4311     SetVersion ($DBversion);
4312 }
4313
4314 $DBversion = '3.03.00.049';
4315 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4316     $dbh->do("ALTER TABLE `accountlines` ADD `note` text NULL default NULL");
4317     $dbh->do("ALTER TABLE `accountlines` ADD `manager_id` int( 11 ) NULL ");
4318     print "Upgrade to $DBversion done (adding note and manager_id fields in accountlines table)\n";
4319     SetVersion($DBversion);
4320 }
4321
4322 $DBversion = "3.03.00.050";
4323 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4324     $dbh->do("
4325         INSERT IGNORE INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacHiddenItems','','This syspref allows to define custom rules for hiding specific items at opac. See docs/opac/OpacHiddenItems.txt for more informations.','','Textarea');
4326         ");
4327     print "Upgrade to $DBversion done (Adding OpacHiddenItems syspref)\n";
4328     SetVersion($DBversion);
4329 }
4330
4331 $DBversion = "3.03.00.051";
4332 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4333     print "Upgrade to $DBversion done (Remove spaces and dashes from message_attribute names)\n";
4334     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Due' WHERE message_name='Item Due'");
4335     $dbh->do("UPDATE message_attributes SET message_name = 'Advance_Notice' WHERE message_name='Advance Notice'");
4336     $dbh->do("UPDATE message_attributes SET message_name = 'Hold_Filled' WHERE message_name='Hold Filled'");
4337     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Check_in' WHERE message_name='Item Check-in'");
4338     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Checkout' WHERE message_name='Item Checkout'");
4339     SetVersion ($DBversion);
4340 }
4341
4342 $DBversion = "3.03.00.052";
4343 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4344     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('WaitingNotifyAtCheckin',0,'If ON, notify librarians of waiting holds for the patron whose items they are checking in.',NULL,'YesNo');");
4345     print "Upgrade to $DBversion done (Add syspref WaitingNotifyAtCheckin)\n";
4346     SetVersion ($DBversion);
4347 }
4348
4349 $DBversion = "3.04.00.000";
4350 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4351     print "Upgrade to $DBversion done Koha 3.4.0 release \n";
4352     SetVersion ($DBversion);
4353 }
4354
4355 $DBversion = "3.05.00.001";
4356 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4357     $dbh->do(qq{
4358     INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('numSearchRSSResults',50,'Specify the maximum number of results to display on a RSS page of results',NULL,'Integer');
4359     });
4360     print "Upgrade to $DBversion done (Adds New System preference numSearchRSSResults)\n";
4361     SetVersion($DBversion);
4362 }
4363
4364 $DBversion = '3.05.00.002';
4365 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4366     #follow up fix 5860: some installs already past 3.3.0.42
4367     stocknumber_checker();
4368     print "Upgrade to $DBversion done (Fix for stocknumber index)\n";
4369     SetVersion ($DBversion);
4370 }
4371
4372 $DBversion = "3.05.00.003";
4373 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4374     $dbh->do(qq{
4375     INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacRenewalBranch','checkoutbranch','Choose how the branch for an OPAC renewal is recorded in statistics','itemhomebranch|patronhomebranch|checkoutbranch|null','Choice');
4376     });
4377     print "Upgrade to $DBversion done (Adds New System preference OpacRenewalBranch)\n";
4378     SetVersion($DBversion);
4379 }
4380
4381 $DBversion = "3.05.00.004";
4382 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4383     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('ShowReviewerPhoto',1,'If ON, photo of reviewer will be shown beside comments in OPAC',NULL,'YesNo');");
4384     print "Upgrade to $DBversion done (Add syspref ShowReviewerPhoto)\n";
4385     SetVersion($DBversion);
4386 }
4387
4388 $DBversion = "3.05.00.005";
4389 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4390     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('BasketConfirmations', '1', 'When closing or reopening a basket,', 'always ask for confirmation.|do not ask for confirmation.', 'Choice');");
4391     print "Upgrade to $DBversion done (Adds pref BasketConfirmations)\n";
4392     SetVersion($DBversion);
4393 }
4394
4395 $DBversion = "3.05.00.006";
4396 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4397     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('MARCAuthorityControlField008', '|| aca||aabn           | a|a     d', NULL, NULL, 'Textarea')");
4398     print "Upgrade to $DBversion done (Add syspref MARCAuthorityControlField008)\n";
4399     SetVersion ($DBversion);
4400 }
4401
4402 $DBversion = "3.05.00.007";
4403 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4404     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpenLibraryCovers',0,'If ON Openlibrary book covers will be show',NULL,'YesNo');");
4405     print "Upgrade to $DBversion done (Add syspref OpenLibraryCovers)\n";
4406     SetVersion($DBversion);
4407 }
4408
4409 $DBversion = "3.05.00.008";
4410 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4411     $dbh->do("ALTER TABLE `cities` ADD `city_state` VARCHAR( 100 ) NULL DEFAULT NULL AFTER  `city_name`;");
4412     $dbh->do("ALTER TABLE `cities` ADD `city_country` VARCHAR( 100 ) NULL DEFAULT NULL AFTER  `city_zipcode`;");
4413     print "Add state and country to cities table corresponding to new columns in borrowers\n";
4414     SetVersion($DBversion);
4415 }
4416
4417 $DBversion = "3.05.00.009";
4418 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4419     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4420               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE borrowernumber IS NULL");
4421     $dbh->do("DELETE FROM issues WHERE borrowernumber IS NULL");
4422
4423     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4424               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE itemnumber IS NULL");
4425     $dbh->do("DELETE FROM issues WHERE itemnumber IS NULL");
4426
4427     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4428               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowernumber = issues.borrowernumber)");
4429     $dbh->do("DELETE FROM issues WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowernumber = issues.borrowernumber)");
4430
4431     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4432               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE NOT EXISTS (SELECT * FROM items WHERE itemnumber = issues.itemnumber)");
4433     $dbh->do("DELETE FROM issues WHERE NOT EXISTS (SELECT * FROM items WHERE itemnumber = issues.itemnumber)");
4434
4435     $dbh->do("ALTER TABLE issues DROP FOREIGN KEY `issues_ibfk_1`");
4436     $dbh->do("ALTER TABLE issues DROP FOREIGN KEY `issues_ibfk_2`");
4437     $dbh->do("ALTER TABLE issues ALTER COLUMN borrowernumber DROP DEFAULT");
4438     $dbh->do("ALTER TABLE issues ALTER COLUMN itemnumber DROP DEFAULT");
4439     $dbh->do("ALTER TABLE issues MODIFY COLUMN borrowernumber int(11) NOT NULL");
4440     $dbh->do("ALTER TABLE issues MODIFY COLUMN itemnumber int(11) NOT NULL");
4441     $dbh->do("ALTER TABLE issues DROP KEY `issuesitemidx`");
4442     $dbh->do("ALTER TABLE issues ADD PRIMARY KEY (`itemnumber`)");
4443     $dbh->do("ALTER TABLE issues ADD CONSTRAINT `issues_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE RESTRICT ON UPDATE CASCADE");
4444     $dbh->do("ALTER TABLE issues ADD CONSTRAINT `issues_ibfk_2` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE RESTRICT ON UPDATE CASCADE");
4445
4446     print "Upgrade to $DBversion done (issues referential integrity)\n";
4447     SetVersion ($DBversion);
4448 }
4449
4450 $DBversion = "3.05.00.010";
4451 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4452     $dbh->do("CREATE INDEX priorityfoundidx ON reserves (priority,found)");
4453     print "Create an index on reserves to speed up holds awaiting pickup report bug 5866\n";
4454     SetVersion($DBversion);
4455 }
4456
4457
4458 $DBversion = "3.05.00.011";
4459 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4460     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACResultsSidebar','','Define HTML to be included on the search results page, underneath the facets sidebar','70|10','Textarea')");
4461     print "Upgrade to $DBversion done (add OPACResultsSidebar syspref (enh 6165))\n";
4462     SetVersion($DBversion);
4463 }
4464
4465 $DBversion = "3.05.00.012";
4466 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4467     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('RecordLocalUseOnReturn',0,'If ON, statistically record returns of unissued items as local use, instead of return',NULL,'YesNo')");
4468     print "Upgrade to $DBversion done (add RecordLocalUseOnReturn syspref (enh 6403))\n";
4469     SetVersion($DBversion);
4470 }
4471
4472 $DBversion = "3.05.00.013";
4473 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4474     $dbh->do(qq|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OpacKohaUrl','0',"Show 'Powered by Koha' text on OPAC footer.",NULL,NULL)|);
4475     print "Upgrade to $DBversion done (Add syspref 'OpacKohaUrl')\n";
4476     SetVersion($DBversion);
4477 }
4478
4479 $DBversion = "3.05.00.014";
4480 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4481     $dbh->do("ALTER TABLE `borrowers` MODIFY `userid` VARCHAR(75)");
4482     print "Modified userid column length into 75 in borrowers\n";
4483     SetVersion($DBversion);
4484 }
4485
4486 $DBversion = "3.05.00.015";
4487 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4488     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectEnabled',0,'Enable Novelist Select content.  Requires Novelist Profile and Password',NULL,'YesNo')");
4489     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectProfile',NULL,'Novelist Select user Password',NULL,'free')");
4490     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectPassword',NULL,'Enable Novelist user Profile',NULL,'free')");
4491     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectView','tab','Where to display Novelist Select content','tab|above|below|right','Choice')");
4492     print "Upgrade to $DBversion done (Add support for EBSCO's NoveList Select (enh 6902))\n";
4493     SetVersion($DBversion);
4494 }
4495
4496 $DBversion = '3.05.00.016';
4497 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4498     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('EasyAnalyticalRecords','0','If on, display in the catalogue screens tools to easily setup analytical record relationships','','YesNo');");
4499     print "Upgrade to $DBversion done (Add EasyAnalyticalRecords syspref)\n";
4500     SetVersion ($DBversion);
4501 }
4502
4503 $DBversion = '3.05.00.017';
4504 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4505     if (C4::Context->preference("marcflavour") eq 'MARC21' ||
4506         C4::Context->preference("marcflavour") eq 'NORMARC'){
4507         $dbh->do("INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`, `tab`, `authorised_value` , `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`) VALUES ('773', '0', 'Host Biblionumber', 'Host Biblionumber', 0, 0, NULL, 7, NULL, NULL, '', NULL, -6, '', '', '', NULL)");
4508         $dbh->do("INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`, `tab`, `authorised_value` , `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`) VALUES ('773', '9', 'Host Itemnumber', 'Host Itemnumber', 0, 0, NULL, 7, NULL, NULL, '', NULL, -6, '', '', '', NULL)");
4509         print "Upgrade to $DBversion done (Add 773 subfield 9 and 0 to default framework)\n";
4510         SetVersion ($DBversion);
4511     } elsif (C4::Context->preference("marcflavour") eq 'UNIMARC'){
4512         $dbh->do("INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`, `tab`, `authorised_value` , `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`) VALUES ('461', '9', 'Host Itemnumber', 'Host Itemnumber', 0, 0, NULL, 7, NULL, NULL, '', NULL, -6, '', '', '', NULL)");
4513         print "Upgrade to $DBversion done (Add 461 subfield 9 to default framework)\n";
4514         SetVersion ($DBversion);
4515     }
4516 }
4517
4518 $DBversion = "3.05.00.018";
4519 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4520     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacNavBottom','','Links after OpacNav links','70|10','Textarea')");
4521     print "Upgrade to $DBversion done (add OpacNavBottom syspref (enh 6825): if appropriate, you can split OpacNav into OpacNav and OpacNavBottom)\n";
4522     SetVersion($DBversion);
4523 }
4524
4525 $DBversion = "3.05.00.019";
4526 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4527     $dbh->do("UPDATE itemtypes SET imageurl = 'vokal/Book.png' WHERE imageurl = 'vokal/BOOK.png'");
4528     $dbh->do("UPDATE itemtypes SET imageurl = 'vokal/Book-32px.png' WHERE imageurl = 'vokal/BOOK-32px.png'");
4529     $dbh->do("UPDATE authorised_values SET imageurl = 'vokal/Book.png' WHERE imageurl = 'vokal/BOOK.png'");
4530     $dbh->do("UPDATE authorised_values SET imageurl = 'vokal/Book-32px.png' WHERE imageurl = 'vokal/BOOK-32px.png'");
4531     print "Upgrade to $DBversion done (remove duplicate VOKAL Book icons, bug 6862)\n";
4532     SetVersion($DBversion);
4533 }
4534
4535 $DBversion = "3.05.00.020";
4536 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4537     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('AcqViewBaskets','user','user|branch|all','Define which baskets a user is allowed to view: his own only, any within his branch or all','Choice')");
4538     print "Upgrade to $DBversion done (Add syspref AcqViewBaskets)\n";
4539     SetVersion($DBversion);
4540 }
4541
4542 $DBversion = "3.05.00.021";
4543 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4544     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN display_checkout TINYINT(1) NOT NULL DEFAULT '0';");
4545     print "Upgrade to $DBversion done (Added a display_checkout field in borrower_attribute_types table)\n";
4546     SetVersion($DBversion);
4547 }
4548
4549 $DBversion = "3.05.00.022";
4550 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4551     $dbh->do("CREATE TABLE need_merge_authorities (id int NOT NULL auto_increment PRIMARY KEY, authid bigint NOT NULL, done tinyint DEFAULT 0) ENGINE=InnoDB DEFAULT CHARSET=utf8");
4552     print "Upgrade to $DBversion done (6094: Fixing ModAuthority problems, add a need_merge_authorities table)\n";
4553     SetVersion($DBversion);
4554 }
4555
4556 $DBversion = "3.05.00.023";
4557 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4558     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacShowRecentComments',0,'If ON a link to recent comments will appear in the OPAC masthead',NULL,'YesNo');");
4559     print "Upgrade to $DBversion done (Add syspref OpacShowRecentComments. When the preference is turned on a link to recent comments will appear in the OPAC masthead. )\n";
4560     SetVersion($DBversion);
4561 }
4562
4563 $DBversion = "3.06.00.000";
4564 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4565     print "Upgrade to $DBversion done Koha 3.6.0 release \n";
4566     SetVersion ($DBversion);
4567 }
4568
4569 $DBversion = "3.07.00.001";
4570 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4571     my $borrowers = $dbh->selectcol_arrayref( "SELECT borrowernumber from borrowers where debarred =1;", { Columns => [1] } );
4572     $dbh->do("ALTER TABLE borrowers MODIFY debarred DATE DEFAULT NULL;");
4573     $dbh->do( "UPDATE borrowers set debarred='9999-12-31' where borrowernumber IN (" . join( ",", @$borrowers ) . ");" ) if ($borrowers and scalar(@$borrowers)>0);
4574     $dbh->do("ALTER TABLE borrowers ADD COLUMN debarredcomment VARCHAR(255) DEFAULT NULL AFTER debarred;");
4575     $dbh->do("ALTER TABLE deletedborrowers MODIFY debarred DATE DEFAULT NULL;");
4576     $dbh->do("ALTER TABLE deletedborrowers ADD COLUMN debarredcomment VARCHAR(255) DEFAULT NULL AFTER debarred;");
4577     print "Upgrade done (Change borrowers.debarred into Date )\n";
4578     SetVersion($DBversion);
4579 }
4580
4581 $DBversion = "3.07.00.002";
4582 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4583     $dbh->do("UPDATE borrowers SET debarred=NULL WHERE debarred='0000-00-00';");
4584     print "Setting NULL to debarred where 0000-00-00 is stored (bug 7272)\n";
4585     SetVersion($DBversion);
4586 }
4587
4588 $DBversion = "3.07.00.003";
4589 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4590     $dbh->do(" UPDATE `message_attributes` SET message_name='Item_Due' WHERE message_name='Item_DUE'");
4591     print "Updating message_name in message_attributes\n";
4592     SetVersion($DBversion);
4593 }
4594
4595 $DBversion = "3.07.00.004";
4596 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4597     $dbh->do("ALTER TABLE  `suggestions` ADD  `patronreason` TEXT NULL AFTER  `reason`");
4598     print "Upgrade to $DBversion done (Add column to suggestions table to store patrons' reasons for submitting a suggestion. )\n";
4599     SetVersion($DBversion);
4600 }
4601
4602 $DBversion = "3.07.00.005";
4603 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4604     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('BorrowerUnwantedField','','Name the fields you don''t need to store for a patron''s account',NULL,'free')");
4605     print "Upgrade to $DBversion done (BorrowerUnwantedField syspref)\n";
4606     SetVersion ($DBversion);
4607 }
4608
4609 $DBversion = "3.07.00.006";
4610 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4611     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('CircAutoPrintQuickSlip', '1', 'Choose what should happen when an empty barcode field is submitted in circulation: Display a print quick slip window or Clear the screen.',NULL,'YesNo');");
4612     print "Upgrade to $DBversion done (Add syspref CircAutoPrintQuickSlip to control what should happen when an empty barcode field is submitted in circulation: Display a print quick slip window (default value, 3.6 behaviour) or clear the screen (previous 3.6 behaviour). )\n";
4613     SetVersion($DBversion);
4614 }
4615
4616 $DBversion = "3.07.00.007";
4617 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4618     $dbh->do("ALTER TABLE items MODIFY materials text;");
4619     print "Upgrade to $DBversion done alter items.material from varchar(10) to text \n";
4620     SetVersion($DBversion);
4621 }
4622
4623 $DBversion = '3.07.00.008';
4624 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4625     if (C4::Context->preference("marcflavour") eq 'MARC21') {
4626         if (C4::Context->preference("opaclanguages") eq "de") {
4627             $dbh->do("INSERT INTO `marc_tag_structure` (`tagfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `authorised_value`, `frameworkcode`) VALUES ('545', 'Fußnote zu biografischen oder historischen Daten', 'Fußnote zu biografischen oder historischen Daten', 1, 0, NULL, '');");
4628         } else {
4629             $dbh->do("INSERT INTO `marc_tag_structure` (`tagfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `authorised_value`, `frameworkcode`) VALUES ('545', 'BIOGRAPHICAL OR HISTORICAL DATA', 'BIOGRAPHICAL OR HISTORICAL DATA', 1, 0, NULL, '');");
4630         }
4631     }
4632     print "Upgrade to $DBversion done (add MARC21 field 545 to framework)\n";
4633     SetVersion ($DBversion);
4634 }
4635
4636 $DBversion = "3.07.00.009";
4637 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4638     $dbh->do("ALTER TABLE `aqorders` ADD COLUMN `claims_count` INT(11)  DEFAULT 0, ADD COLUMN `claimed_date` DATE  DEFAULT NULL AFTER `claims_count`");
4639     print "Upgrade to $DBversion done (Add claims_count and claimed_date fields in aqorders table)\n";
4640     SetVersion($DBversion);
4641 }
4642
4643 $DBversion = "3.07.00.010";
4644 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4645     $dbh->do(
4646         q|CREATE TABLE `biblioimages` (
4647           `imagenumber` int(11) NOT NULL AUTO_INCREMENT,
4648           `biblionumber` int(11) NOT NULL,
4649           `mimetype` varchar(15) NOT NULL,
4650           `imagefile` mediumblob NOT NULL,
4651           `thumbnail` mediumblob NOT NULL,
4652           PRIMARY KEY (`imagenumber`),
4653           CONSTRAINT `bibliocoverimage_fk1` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
4654           ) ENGINE=InnoDB DEFAULT CHARSET=utf8|
4655     );
4656     $dbh->do(
4657         q|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OPACLocalCoverImages','0','Display local cover images on OPAC search and details pages.','1','YesNo')|
4658         );
4659     $dbh->do(
4660         q|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('LocalCoverImages','0','Display local cover images on intranet search and details pages.','1','YesNo')|
4661         );
4662     $dbh->do(
4663         q|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('AllowMultipleCovers','0','Allow multiple cover images to be attached to each bibliographic record.','1','YesNo')|
4664     );
4665     $dbh->do(
4666         q|INSERT INTO permissions (module_bit, code, description) VALUES (13, 'upload_local_cover_images', 'Upload local cover images')|
4667     );
4668     print "Upgrade to $DBversion done (Added support for local cover images)\n";
4669     SetVersion($DBversion);
4670 }
4671
4672 $DBversion = "3.07.00.011";
4673 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4674     $dbh->do(<<ENDOFRENEWAL);
4675     INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('BorrowerRenewalPeriodBase', 'now', 'Set whether the borrower renewal date should be counted from the dateexpiry or from the current date ','dateexpiry|now','Choice');
4676 ENDOFRENEWAL
4677     print "Upgrade to $DBversion done (Added a system preference to allow renewal of Patron account either from todays date or from existing expiry date in the patrons account.)\n";
4678     SetVersion($DBversion);
4679 }
4680
4681 $DBversion = "3.07.00.012";
4682 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4683     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AllowItemsOnHoldCheckout',0,'Do not generate RESERVE_WAITING and RESERVED warning when checking out items reserved to someone else. This allows self checkouts for those items.','','YesNo')");
4684     print "Upgrade to $DBversion add 'AllowItemsOnHoldCheckout' syspref \n";
4685     SetVersion ($DBversion);
4686 }
4687
4688 $DBversion = "3.07.00.013";
4689 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4690     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacExportOptions','bibtex|dc|marcxml|marc8|utf8|marcstd|mods|ris','Define available export options on OPAC detail page.','','free');");
4691     print "Upgrade to $DBversion done (Bug 7345: Add system preference OpacExportOptions.)\n";
4692     SetVersion ($DBversion);
4693 }
4694
4695 $DBversion = "3.07.00.014";
4696 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4697     print "RELTERMS category available for English-, French-, and Spanish-language relator terms. They are not loaded during upgrade but can be easily inserted using the provided marc21_relatorterms.sql SQL script (MARC21 only, and currently available for en, es, and fr only).\n";
4698     SetVersion($DBversion);
4699 }
4700
4701 $DBversion = "3.07.00.015";
4702 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4703     my $sth = $dbh->prepare(q|
4704         SELECT COUNT(*) FROM marc_subfield_structure where kohafield="biblioitems.editionstatement"
4705         |);
4706     $sth->execute;
4707     my $already_exists = $sth->fetchrow;
4708     if ( not $already_exists ) {
4709         my $field = C4::Context->preference("marcflavour") eq "UNIMARC" ? "205" : "250";
4710         my $subfield = "a";
4711         my $sth = $dbh->prepare( q|
4712             UPDATE marc_subfield_structure SET kohafield = "biblioitems.editionstatement"
4713             WHERE tagfield = ? AND tagsubfield = ?
4714         |);
4715         $sth->execute( $field, $subfield );
4716         print "Upgrade to $DBversion done (Added a mapping for biblioitems.editionstatement.)\n";
4717     } else {
4718         print "Upgrade to $DBversion done (Added a mapping for biblioitems.editionstatement (already exists, nothing to do).)\n";
4719     }
4720     SetVersion($DBversion);
4721 }
4722
4723 $DBversion = "3.07.00.016";
4724 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4725     $dbh->do("ALTER TABLE items ADD KEY `itemcallnumber` (itemcallnumber)");
4726     print "Upgrade to $DBversion done (Added index on items.itemcallnumber)\n";
4727     SetVersion($DBversion);
4728 }
4729
4730 $DBversion = "3.07.00.017";
4731 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4732     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('TransferWhenCancelAllWaitingHolds','0','Transfer items when cancelling all waiting holds',NULL,'YesNo')");
4733     print "Upgrade to $DBversion done (Add sysprefs to control transfer when cancel all waiting holds)\n";
4734     SetVersion ($DBversion);
4735 }
4736
4737 $DBversion = "3.07.00.018";
4738 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4739     $dbh->do("CREATE TABLE pending_offline_operations ( operationid int(11) NOT NULL AUTO_INCREMENT, userid varchar(30) NOT NULL, branchcode varchar(10) NOT NULL, timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, action varchar(10) NOT NULL, barcode varchar(20) NOT NULL, cardnumber varchar(16) DEFAULT NULL, PRIMARY KEY (operationid) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;");
4740     print "Upgrade to $DBversion done ( adding offline operations table )\n";
4741     SetVersion($DBversion);
4742 }
4743
4744 $DBversion = "3.07.00.019";
4745 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4746     $dbh->do(" UPDATE `systempreferences` SET  `value` =  'none', `options` =  'none|full|first|surname|firstandinitial|username', `explanation` =  'Choose how a commenter''s identity is presented alongside comments in the OPAC', `type` =  'Choice' WHERE  `systempreferences`.`variable` =  'ShowReviewer' AND `systempreferences`.`variable` = 0");
4747     $dbh->do(" UPDATE `systempreferences` SET  `value` =  'full', `options` =  'none|full|first|surname|firstandinitial|username', `explanation` =  'Choose how a commenter''s identity is presented alongside comments in the OPAC', `type` =  'Choice' WHERE  `systempreferences`.`variable` =  'ShowReviewer' AND `systempreferences`.`variable` = 1");
4748     print "Upgrade to $DBversion done ( Adding additional options for the display of commenter's identity in the OPAC: Full name, first name, last name, first name and last name first initial, username, or no information)\n";
4749     SetVersion($DBversion);
4750 }
4751
4752 $DBversion = "3.07.00.020";
4753 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4754     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OPACpatronimages',0,'Enable patron images in the OPAC',NULL,'YesNo');");
4755     print "Upgrade to $DBversion done (Bug 3516: Add the option to show patron images in the OPAC.)\n";
4756     SetVersion($DBversion);
4757 }
4758
4759 $DBversion = "3.07.00.021";
4760 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4761     $dbh->do(
4762     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('LinkerModule','Default','Chooses which linker module to use (see documentation).','Default|FirstMatchLastMatch','Choice');"
4763     );
4764     $dbh->do(
4765     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('LinkerOptions','','A pipe-separated list of options for the linker.','','free');"
4766     );
4767     $dbh->do(
4768     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('LinkerRelink',1,'If ON the authority linker will relink headings that have previously been linked every time it runs.',NULL,'YesNo');"
4769     );
4770     $dbh->do(
4771     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('LinkerKeepStale',0,'If ON the authority linker will keep existing authority links for headings where it is unable to find a match.',NULL,'YesNo');"
4772     );
4773     $dbh->do(
4774     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AutoCreateAuthorities',0,'Automatically create authorities that do not exist when cataloging records.',NULL,'YesNo');"
4775     );
4776     $dbh->do(
4777     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('CatalogModuleRelink',0,'If OFF the linker will never replace the authids that are set in the cataloging module.',NULL,'YesNo');"
4778     );
4779     print "Upgrade to $DBversion done (Enhancement 7284, improved authority matching, see http://wiki.koha-community.org/wiki/Bug7284_authority_matching_improvement wiki page for configuration update needed)\n";
4780     SetVersion($DBversion);
4781 }
4782
4783 $DBversion = "3.07.00.022";
4784 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4785     $dbh->do("DELETE FROM reviews WHERE biblionumber NOT IN (SELECT biblionumber from biblio)");
4786     $dbh->do("UPDATE reviews SET borrowernumber = NULL WHERE borrowernumber NOT IN (SELECT borrowernumber FROM borrowers)");
4787     $dbh->do("ALTER TABLE reviews ADD CONSTRAINT reviews_ibfk_2 FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE");
4788     $dbh->do("ALTER TABLE reviews ADD CONSTRAINT reviews_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber ) ON UPDATE CASCADE ON DELETE SET NULL");
4789     print "Upgrade to $DBversion done (Bug 7493 - Add constraint linking OPAC comment biblionumber to biblio, OPAC comment borrowernumber to borrowers.)\n";
4790     SetVersion($DBversion);
4791 }
4792
4793 $DBversion = "3.07.00.023";
4794 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4795     $dbh->do("ALTER TABLE `message_transports` DROP FOREIGN KEY `message_transports_ibfk_3`");
4796     $dbh->do("ALTER TABLE `letter` DROP PRIMARY KEY");
4797     $dbh->do("ALTER TABLE `letter` ADD `branchcode` varchar(10) default NULL AFTER `code`");
4798     $dbh->do("ALTER TABLE `letter` ADD PRIMARY KEY  (`module`,`code`, `branchcode`)");
4799     $dbh->do("ALTER TABLE `message_transports` ADD `branchcode` varchar(10) NOT NULL default ''");
4800     $dbh->do("ALTER TABLE `message_transports` ADD CONSTRAINT `message_transports_ibfk_3` FOREIGN KEY (`letter_module`, `letter_code`, `branchcode`) REFERENCES `letter` (`module`, `code`, `branchcode`) ON DELETE CASCADE ON UPDATE CASCADE");
4801     $dbh->do("ALTER TABLE `letter` ADD `is_html` tinyint(1) default 0 AFTER `name`");
4802
4803     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4804               VALUES ('circulation','ISSUESLIP','Issue Slip','Issue Slip', '<h3><<branches.branchname>></h3>
4805 Checked out to <<borrowers.title>> <<borrowers.firstname>> <<borrowers.initials>> <<borrowers.surname>> <br />
4806 (<<borrowers.cardnumber>>) <br />
4807
4808 <<today>><br />
4809
4810 <h4>Checked Out</h4>
4811 <checkedout>
4812 <p>
4813 <<biblio.title>> <br />
4814 Barcode: <<items.barcode>><br />
4815 Date due: <<issues.date_due>><br />
4816 </p>
4817 </checkedout>
4818
4819 <h4>Overdues</h4>
4820 <overdue>
4821 <p>
4822 <<biblio.title>> <br />
4823 Barcode: <<items.barcode>><br />
4824 Date due: <<issues.date_due>><br />
4825 </p>
4826 </overdue>
4827
4828 <hr>
4829
4830 <h4 style=\"text-align: center; font-style:italic;\">News</h4>
4831 <news>
4832 <div class=\"newsitem\">
4833 <h5 style=\"margin-bottom: 1px; margin-top: 1px\"><b><<opac_news.title>></b></h5>
4834 <p style=\"margin-bottom: 1px; margin-top: 1px\"><<opac_news.new>></p>
4835 <p class=\"newsfooter\" style=\"font-size: 8pt; font-style:italic; margin-bottom: 1px; margin-top: 1px\">Posted on <<opac_news.timestamp>></p>
4836 <hr />
4837 </div>
4838 </news>', 1)");
4839     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4840               VALUES ('circulation','ISSUEQSLIP','Issue Quick Slip','Issue Quick Slip', '<h3><<branches.branchname>></h3>
4841 Checked out to <<borrowers.title>> <<borrowers.firstname>> <<borrowers.initials>> <<borrowers.surname>> <br />
4842 (<<borrowers.cardnumber>>) <br />
4843
4844 <<today>><br />
4845
4846 <h4>Checked Out Today</h4>
4847 <checkedout>
4848 <p>
4849 <<biblio.title>> <br />
4850 Barcode: <<items.barcode>><br />
4851 Date due: <<issues.date_due>><br />
4852 </p>
4853 </checkedout>', 1)");
4854     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4855               VALUES ('circulation','RESERVESLIP','Reserve Slip','Reserve Slip', '<h5>Date: <<today>></h5>
4856
4857 <h3> Transfer to/Hold in <<branches.branchname>></h3>
4858
4859 <h3><<borrowers.surname>>, <<borrowers.firstname>></h3>
4860
4861 <ul>
4862     <li><<borrowers.cardnumber>></li>
4863     <li><<borrowers.phone>></li>
4864     <li> <<borrowers.address>><br />
4865          <<borrowers.address2>><br />
4866          <<borrowers.city >>  <<borrowers.zipcode>>
4867     </li>
4868     <li><<borrowers.email>></li>
4869 </ul>
4870 <br />
4871 <h3>ITEM ON HOLD</h3>
4872 <h4><<biblio.title>></h4>
4873 <h5><<biblio.author>></h5>
4874 <ul>
4875    <li><<items.barcode>></li>
4876    <li><<items.itemcallnumber>></li>
4877    <li><<reserves.waitingdate>></li>
4878 </ul>
4879 <p>Notes:
4880 <pre><<reserves.reservenotes>></pre>
4881 </p>', 1)");
4882     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4883               VALUES ('circulation','TRANSFERSLIP','Transfer Slip','Transfer Slip', '<h5>Date: <<today>></h5>
4884 <h3>Transfer to <<branches.branchname>></h3>
4885
4886 <h3>ITEM</h3>
4887 <h4><<biblio.title>></h4>
4888 <h5><<biblio.author>></h5>
4889 <ul>
4890    <li><<items.barcode>></li>
4891    <li><<items.itemcallnumber>></li>
4892 </ul>', 1)");
4893
4894     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('NoticeCSS','','Notices CSS url.',NULL,'free')");
4895     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('SlipCSS','','Slips CSS url.',NULL,'free')");
4896
4897     $dbh->do("UPDATE `letter` SET content = replace(content, '<<title>>', '<<biblio.title>>') WHERE code = 'HOLDPLACED'");
4898
4899     print "Upgrade to $DBversion done (Add branchcode and is_html to letter table; Default ISSUESLIP, RESERVESLIP and TRANSFERSLIP letters; Add NoticeCSS and SlipCSS sysprefs)\n";
4900     SetVersion($DBversion);
4901 }
4902
4903 $DBversion = "3.07.00.024";
4904 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4905     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('ExpireReservesMaxPickUpDelayCharge', '0', NULL , 'If ExpireReservesMaxPickUpDelay is enabled, and this field has a non-zero value, than a borrower whose waiting hold has expired will be charged this amount.',  'free')");
4906     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('ExpireReservesMaxPickUpDelay', '0', '', 'Enabling this allows holds to expire automatically if they have not been picked by within the time period specified in ReservesMaxPickUpDelay', 'YesNo')");
4907     print "Upgrade to $DBversion done (Added system preference ExpireReservesMaxPickUpDelay, system preference ExpireReservesMaxPickUpDelayCharge, add reseves.charge_if_expired)\n";
4908 }
4909
4910 $DBversion = "3.07.00.025";
4911 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4912     if (TableExists('bibliocoverimage')) {
4913         $dbh->do( q|DROP TABLE bibliocoverimage;| );
4914         $dbh->do(
4915             q|CREATE TABLE biblioimages (
4916               imagenumber int(11) NOT NULL AUTO_INCREMENT,
4917               biblionumber int(11) NOT NULL,
4918               mimetype varchar(15) NOT NULL,
4919               imagefile mediumblob NOT NULL,
4920               thumbnail mediumblob NOT NULL,
4921               PRIMARY KEY (imagenumber),
4922               CONSTRAINT bibliocoverimage_fk1 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
4923               ) ENGINE=InnoDB DEFAULT CHARSET=utf8;|
4924         );
4925     }
4926     print "Upgrade to $DBversion done (Correct table name for local cover images if needed. )\n";
4927     SetVersion($DBversion);
4928 }
4929
4930 $DBversion = "3.07.00.026";
4931 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4932     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('CalendarFirstDayOfWeek','Sunday','Select the first day of week to use in the calendar.','Sunday|Monday','Choice');");
4933     print "Upgrade to $DBversion done (Add syspref CalendarFirstDayOfWeek used to select the first day of week to use in the calendar. )\n";
4934     SetVersion($DBversion);
4935 }
4936
4937 $DBversion = "3.07.00.027";
4938 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4939     $dbh->do(q{INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('RoutingListNote','','Define a note to be shown on all routing lists','70|10','Textarea');});
4940     print "Upgrade to $DBversion done (Added system preference RoutingListNote for adding a general note to all routing lists.)\n";
4941     SetVersion($DBversion);
4942 }
4943
4944 $DBversion = "3.07.00.028";
4945 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4946     $dbh->do(qq{
4947     INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('AllowPKIAuth','None','Use the field from a client-side SSL certificate to look a user in the Koha database','None|Common Name|emailAddress','Choice');
4948     });
4949     print "Upgrade to $DBversion done (Bug 6296 New System preference AllowPKIAuth)\n";
4950 }
4951
4952 $DBversion = "3.07.00.029";
4953 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4954     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_descriptions`;});
4955     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_mappings`;});
4956     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_biblios`;});
4957     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets`;});
4958
4959     $dbh->do(q{
4960         CREATE TABLE `oai_sets` (
4961           `id` int(11) NOT NULL auto_increment,
4962           `spec` varchar(80) NOT NULL UNIQUE,
4963           `name` varchar(80) NOT NULL,
4964           PRIMARY KEY (`id`)
4965         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4966     });
4967
4968     $dbh->do(q{
4969         CREATE TABLE `oai_sets_descriptions` (
4970           `set_id` int(11) NOT NULL,
4971           `description` varchar(255) NOT NULL,
4972           CONSTRAINT `oai_sets_descriptions_ibfk_1` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4973         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4974     });
4975
4976     $dbh->do(q{
4977         CREATE TABLE `oai_sets_mappings` (
4978           `set_id` int(11) NOT NULL,
4979           `marcfield` char(3) NOT NULL,
4980           `marcsubfield` char(1) NOT NULL,
4981           `marcvalue` varchar(80) NOT NULL,
4982           CONSTRAINT `oai_sets_mappings_ibfk_1` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4983         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4984     });
4985
4986     $dbh->do(q{
4987         CREATE TABLE `oai_sets_biblios` (
4988           `biblionumber` int(11) NOT NULL,
4989           `set_id` int(11) NOT NULL,
4990           PRIMARY KEY (`biblionumber`, `set_id`),
4991           CONSTRAINT `oai_sets_biblios_ibfk_1` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
4992           CONSTRAINT `oai_sets_biblios_ibfk_2` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4993         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4994     });
4995
4996     $dbh->do(q{
4997         INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OAI-PMH:AutoUpdateSets','0','Automatically update OAI sets when a bibliographic record is created or updated','','YesNo');
4998     });
4999
5000     print "Upgrade to $DBversion done (Atomic update for OAI-PMH sets management)\n";
5001     SetVersion($DBversion);
5002 }
5003
5004 $DBversion = "3.07.00.030";
5005 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5006     $dbh->do("ALTER TABLE default_circ_rules ADD
5007             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5008     $dbh->do("ALTER TABLE branch_item_rules ADD
5009             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5010     $dbh->do("ALTER TABLE default_branch_circ_rules ADD
5011             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5012     $dbh->do("ALTER TABLE default_branch_item_rules ADD
5013             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5014     # set the default rule to the current value of HomeOrHoldingBranchReturn (default to 'homebranch' if need be)
5015     my $homeorholdingbranchreturn = C4::Context->preference('HomeOrHoldingBranchReturn') || 'homebranch';
5016     $dbh->do("UPDATE default_circ_rules SET returnbranch = '$homeorholdingbranchreturn'");
5017     print "Upgrade to $DBversion done (Atomic update for OAI-PMH sets management)\n";
5018     SetVersion($DBversion);
5019 }
5020
5021 $DBversion = "3.07.00.031";
5022 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5023     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('UseICU', '1', 'Tell Koha if ICU indexing is in use for Zebra or not.','1','YesNo')");
5024     print "Upgrade to $DBversion done (Add syspref to tell Koha if ICU indexing is in use for Zebra or not.)\n";
5025     SetVersion ($DBversion);
5026 }
5027
5028 $DBversion = "3.07.00.032";
5029 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5030     $dbh->do("ALTER TABLE virtualshelves MODIFY COLUMN owner int"); #should have been int already (fk to borrowers)
5031     $dbh->do("UPDATE virtualshelves vi LEFT JOIN borrowers bo ON bo.borrowernumber=vi.owner SET vi.owner=NULL where bo.borrowernumber IS NULL"); #before adding the constraint on borrowernumber, we need to get rid of deleted owners
5032     $dbh->do("DELETE FROM virtualshelves WHERE owner IS NULL and category=1"); #delete private lists without owner (cascades to shelfcontents)
5033     $dbh->do("ALTER TABLE virtualshelves ADD COLUMN allow_add tinyint(1) DEFAULT 0, ADD COLUMN allow_delete_own tinyint(1) DEFAULT 1, ADD COLUMN allow_delete_other tinyint(1) DEFAULT 0, ADD CONSTRAINT `virtualshelves_ibfk_1` FOREIGN KEY (`owner`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE SET NULL");
5034     $dbh->do("UPDATE virtualshelves SET allow_add=0, allow_delete_own=1, allow_delete_other=0 WHERE category=1");
5035     $dbh->do("UPDATE virtualshelves SET allow_add=0, allow_delete_own=1, allow_delete_other=0 WHERE category=2");
5036     $dbh->do("UPDATE virtualshelves SET allow_add=1, allow_delete_own=1, allow_delete_other=1 WHERE category=3");
5037     $dbh->do("UPDATE virtualshelves SET category=2 WHERE category=3");
5038
5039     $dbh->do("ALTER TABLE virtualshelfcontents ADD COLUMN borrowernumber int, ADD CONSTRAINT `shelfcontents_ibfk_3` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE SET NULL");
5040     $dbh->do("UPDATE virtualshelfcontents co LEFT JOIN virtualshelves sh USING (shelfnumber) SET co.borrowernumber=sh.owner");
5041
5042     $dbh->do("CREATE TABLE virtualshelfshares
5043     (id int AUTO_INCREMENT PRIMARY KEY, shelfnumber int NOT NULL,
5044     borrowernumber int, invitekey varchar(10), sharedate datetime,
5045     CONSTRAINT `virtualshelfshares_ibfk_1` FOREIGN KEY (`shelfnumber`) REFERENCES `virtualshelves` (`shelfnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
5046         CONSTRAINT `virtualshelfshares_ibfk_2` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE SET NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8");
5047
5048     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacAllowPublicListCreation',1,'If set, allows opac users to create public lists',NULL,'YesNo');");
5049     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacAllowSharingPrivateLists',0,'If set, allows opac users to share private lists with other patrons',NULL,'YesNo');");
5050
5051     print "Upgrade to $DBversion done (BZ7310: Improving list permissions)\n";
5052     SetVersion($DBversion);
5053 }
5054
5055 $DBversion = "3.07.00.033";
5056 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5057     $dbh->do("ALTER TABLE branches ADD opac_info text;");
5058     print "Upgrade to $DBversion done add opac_info to branches \n";
5059     SetVersion($DBversion);
5060 }
5061
5062 $DBversion = "3.07.00.034";
5063 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5064     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN category_code VARCHAR(10) NULL DEFAULT NULL AFTER `display_checkout`");
5065     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN class VARCHAR(255)  NOT NULL DEFAULT '' AFTER `category_code`");
5066     $dbh->do("ALTER TABLE borrower_attribute_types ADD CONSTRAINT category_code_fk FOREIGN KEY (category_code) REFERENCES categories(categorycode)");
5067     print "Upgrade to $DBversion done (New fields category_code and class in borrower_attribute_types table)\n";
5068     SetVersion($DBversion);
5069 }
5070
5071 $DBversion = "3.07.00.035";
5072 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5073     $dbh->do("ALTER TABLE issues CHANGE date_due date_due datetime");
5074     $dbh->do("UPDATE issues SET date_due = CONCAT(SUBSTR(date_due,1,11),'23:59:00')");
5075     $dbh->do("ALTER TABLE issues CHANGE returndate returndate datetime");
5076     $dbh->do("ALTER TABLE issues CHANGE lastreneweddate lastreneweddate datetime");
5077     $dbh->do("ALTER TABLE issues CHANGE issuedate issuedate datetime");
5078     $dbh->do("ALTER TABLE old_issues CHANGE date_due date_due datetime");
5079     $dbh->do("ALTER TABLE old_issues CHANGE returndate returndate datetime");
5080     $dbh->do("ALTER TABLE old_issues CHANGE lastreneweddate lastreneweddate datetime");
5081     $dbh->do("ALTER TABLE old_issues CHANGE issuedate issuedate datetime");
5082     $dbh->do("UPDATE accountlines SET description = CONCAT(description,' 23:59') WHERE accounttype='F' OR accounttype='FU'"); #BUG-8253
5083     print "Upgrade to $DBversion done (Setting up issues and accountlines tables for hourly loans)\n";
5084     SetVersion($DBversion);
5085 }
5086
5087 $DBversion = "3.07.00.036";
5088 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5089     $dbh->do(qq{
5090        ALTER TABLE z3950servers ADD timeout INT( 11 ) NOT NULL DEFAULT '0' AFTER syntax;
5091     });
5092     print "Upgrade to $DBversion done (New timeout field in z3950servers)\n";
5093 }
5094
5095 $DBversion = "3.07.00.037";
5096 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5097     $dbh->do("
5098        ALTER TABLE  `marc_subfield_structure` ADD  `maxlength` INT( 4 ) NOT NULL DEFAULT  '9999';
5099        ");
5100        $dbh->do("
5101        UPDATE `marc_subfield_structure` SET maxlength=24 WHERE tagfield='000';
5102        ");
5103        $dbh->do("
5104        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='MARC21','40','9999') WHERE tagfield='008';
5105        ");
5106        $dbh->do("
5107        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='NORMARC','40','9999') WHERE tagfield='008';
5108        ");
5109        $dbh->do("
5110        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='UNIMARC','36','9999') WHERE tagfield='100';
5111        ");
5112     print "Upgrade to $DBversion done (Add new field maxlength to marc_subfield_structure)\n";
5113     SetVersion($DBversion);
5114 }
5115
5116 $DBversion = "3.07.00.038";
5117 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5118     $dbh->do(qq{
5119         INSERT INTO systempreferences(variable,value,explanation,options,type)
5120         VALUES('UniqueItemFields', 'barcode', 'Space-separated list of fields that should be unique (used in acquisition module for item creation). Fields must be valid SQL column names of items table', '', 'Free')
5121     });
5122     print "Upgrade to $DBversion done (Added system preference 'UniqueItemFields')\n";
5123     SetVersion($DBversion);
5124 }
5125
5126 $DBversion = "3.07.00.039";
5127 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5128     $dbh->do( qq{INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('Babeltheque_url_js','','Url for Babeltheque javascript (e.g. http://www.babeltheque.com/bw_XX.js','','Free')} );
5129     $dbh->do( qq{CREATE TABLE IF NOT EXISTS social_data
5130       ( isbn VARCHAR(30),
5131         num_critics INT,
5132         num_critics_pro INT,
5133         num_quotations INT,
5134         num_videos INT,
5135         score_avg DECIMAL(5,2),
5136         num_scores INT,
5137         PRIMARY KEY  (isbn)
5138       ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5139     } );
5140     $dbh->do( qq{INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('Babeltheque_url_update', '', 'Url for Babeltheque update (E.G. http://www.babeltheque.com/.../file.csv.bz2)', '', 'Free')} );
5141     print "Upgrade to $DBversion done (added syspref and table for babeltheque (Babeltheque_url_js, babeltheque))\n";
5142     SetVersion($DBversion);
5143 }
5144
5145 $DBversion = "3.07.00.040";
5146 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5147     $dbh->do( qq{INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('SocialNetworks','0','Enable/Disable social networks links in opac detail','','YesNo')} );
5148     print "Upgrade to $DBversion done (added syspref SocialNetworks, to display facebook/ggl+ and other buttons)\n";
5149     SetVersion($DBversion);
5150 }
5151
5152
5153
5154 $DBversion = "3.07.00.041";
5155 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5156     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('SubscriptionDuplicateDroppedInput','','','List of fields which must not be rewritten when a subscription is duplicated (Separated by pipe |)','Free')");
5157     print "Upgrade to $DBversion done (Add system preference SubscriptionDuplicateDroppedInput)\n";
5158     SetVersion($DBversion);
5159 }
5160
5161 $DBversion = "3.07.00.042";
5162 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5163     $dbh->do("ALTER TABLE reserves ADD suspend BOOLEAN NOT NULL DEFAULT 0");
5164     $dbh->do("ALTER TABLE old_reserves ADD suspend BOOLEAN NOT NULL DEFAULT 0");
5165
5166     $dbh->do("ALTER TABLE reserves ADD suspend_until DATETIME NULL DEFAULT NULL");
5167     $dbh->do("ALTER TABLE old_reserves ADD suspend_until DATETIME NULL DEFAULT NULL");
5168
5169     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('AutoResumeSuspendedHolds',  '1', NULL ,  'Allow suspended holds to be automatically resumed by a set date.',  'YesNo')");
5170
5171     print "Upgrade to $DBversion done (Add suspend fields to reserves table, add syspref AutoResumeSuspendedHolds)\n";
5172     SetVersion ($DBversion);
5173 }
5174
5175 $DBversion = "3.07.00.043";
5176 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5177     my $countXSLTDetailsDisplay = 0;
5178     my $valueXSLTDetailsDisplay = "";
5179     my $valueXSLTResultsDisplay = "";
5180     my $valueOPACXSLTDetailsDisplay = "";
5181     my $valueOPACXSLTResultsDisplay = "";
5182     #the line below test if database comes from a BibLibre's branch
5183     $countXSLTDetailsDisplay = $dbh->do('SELECT 1 FROM systempreferences WHERE variable="IntranetXSLTDetailsDisplay"');
5184     if ($countXSLTDetailsDisplay > 0)
5185     {
5186         #the two lines below will only be used to update the databases from the BibLibre's branch. They will not affect the others
5187         $dbh->do(q|UPDATE systempreferences SET variable="XSLTDetailsDisplay" WHERE variable="IntranetXSLTDetailsDisplay"|);
5188         $dbh->do(q|UPDATE systempreferences SET variable="XSLTResultsDisplay" WHERE variable="IntranetXSLTResultsDisplay"|);
5189     }
5190     else
5191     {
5192         $valueXSLTDetailsDisplay = "default" if (C4::Context->preference("XSLTDetailsDisplay"));
5193         $valueXSLTResultsDisplay = "default" if (C4::Context->preference("XSLTResultsDisplay"));
5194         $valueOPACXSLTDetailsDisplay = "default" if (C4::Context->preference("OPACXSLTDetailsDisplay"));
5195         $valueOPACXSLTResultsDisplay = "default" if (C4::Context->preference("OPACXSLTResultsDisplay"));
5196         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueXSLTDetailsDisplay\" WHERE variable='XSLTDetailsDisplay'");
5197         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueXSLTResultsDisplay\" WHERE variable='XSLTResultsDisplay'");
5198         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueOPACXSLTDetailsDisplay\" WHERE variable='OPACXSLTDetailsDisplay'");
5199         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueOPACXSLTResultsDisplay\" WHERE variable='OPACXSLTResultsDisplay'");
5200     }
5201     print "Upgrade to $DBversion done (XSLT systempreference takes a path to file rather than YesNo)\n";
5202     SetVersion($DBversion);
5203 }
5204
5205 $DBversion = "3.07.00.044";
5206 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5207     $dbh->do("ALTER TABLE aqbooksellers ADD deliverytime INT DEFAULT NULL");
5208     print "Upgrade to $DBversion done (Add deliverytime field in aqbooksellers table)";
5209     SetVersion($DBversion);
5210 }
5211
5212 $DBversion = "3.07.00.045";
5213 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5214     $dbh->do("ALTER TABLE import_batches MODIFY COLUMN batch_type ENUM('batch','z3950','webservice') NOT NULL default 'batch'");
5215     print "Upgrade to $DBversion done (Add 'webservice' to batch_type enum)\n";
5216     SetVersion ($DBversion);
5217 }
5218
5219 $DBversion = "3.07.00.046";
5220 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5221     $dbh->do("ALTER TABLE issuingrules ADD COLUMN lengthunit varchar(10) DEFAULT 'days' AFTER issuelength");
5222     print "Upgrade to $DBversion done (Setting up issues tables for hourly loans (lengthunit fix))\n";
5223     SetVersion($DBversion);
5224 }
5225
5226 $DBversion = "3.07.00.047";
5227 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5228     $dbh->do("CREATE INDEX items_location ON items(location)");
5229     $dbh->do("CREATE INDEX items_ccode ON items(ccode)");
5230     print "Upgrade to $DBversion done (items_location and items_ccode indexes added for ShelfBrowser)\n";
5231     SetVersion($DBversion);
5232 }
5233
5234 $DBversion = "3.07.00.048";
5235 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5236     $dbh->do(
5237         q | CREATE TABLE ratings (
5238   borrowernumber int(11) NOT NULL,
5239   biblionumber int(11) NOT NULL,
5240   rating_value tinyint(1) NOT NULL,
5241   timestamp timestamp NOT NULL default CURRENT_TIMESTAMP,
5242   PRIMARY KEY  (borrowernumber,biblionumber),
5243   CONSTRAINT ratings_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE,
5244   CONSTRAINT ratings_ibfk_2 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
5245 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
5246     );
5247
5248     $dbh->do(
5249 q /INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OpacStarRatings','disable',NULL,'disable|all|details','Choice') /
5250     );
5251
5252     print
5253 "Upgrade to $DBversion done (Add 'ratings' table and 'OpacStarRatings' syspref)\n";
5254     SetVersion($DBversion);
5255 }
5256
5257 $DBversion = "3.07.00.049";
5258 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5259     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacBrowseResults','1','Disable/enable browsing and paging search results from the OPAC detail page.',NULL,'YesNo')");
5260     print "Upgrade to $DBversion done (Add system preference OpacBrowseResults ))\n";
5261     SetVersion($DBversion);
5262 }
5263
5264 $DBversion = "3.08.00.000";
5265 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5266     print "Upgrade to $DBversion done\n";
5267     SetVersion($DBversion);
5268 }
5269
5270 $DBversion = "3.09.00.001";
5271 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5272     $dbh->do("ALTER TABLE borrower_attribute_types MODIFY category_code VARCHAR( 1 ) NULL DEFAULT NULL");
5273     print "Upgrade to $DBversion done. (Bug 8002: Update patron attribute types table to allow NULL category_code)\n";
5274     SetVersion($DBversion);
5275 }
5276
5277 $DBversion = "3.09.00.002";
5278 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5279     $dbh->do("ALTER TABLE saved_sql
5280         ADD (
5281             cache_expiry INT NOT NULL DEFAULT 300,
5282             public BOOLEAN NOT NULL DEFAULT FALSE
5283         );
5284     ");
5285     print "Upgrade to $DBversion done (Added cache_expiry and public fields in
5286 saved_reports table.)\n";
5287     SetVersion($DBversion);
5288 }
5289
5290 $DBversion = "3.09.00.003";
5291 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5292     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('SvcMaxReportRows','10','Maximum number of rows to return via the report web service.',NULL,'Integer');");
5293     print "Upgrade to $DBversion done (Added SvcMaxReportRows syspref)\n";
5294     SetVersion($DBversion);
5295 }
5296
5297 $DBversion = "3.09.00.004";
5298 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5299     $dbh->do("INSERT IGNORE INTO permissions (module_bit, code, description) VALUES('13', 'edit_patrons', 'Perform batch modifivation of patrons')");
5300     print "Upgrade to $DBversion done (Adds permissions flag for access to the patron modifications tool)\n";
5301     SetVersion($DBversion);
5302 }
5303
5304 $DBversion = "3.09.00.005";
5305 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5306     unless (TableExists('quotes')) {
5307         $dbh->do( qq{
5308             CREATE TABLE `quotes` (
5309               `id` int(11) NOT NULL AUTO_INCREMENT,
5310               `source` text DEFAULT NULL,
5311               `text` mediumtext NOT NULL,
5312               `timestamp` datetime NOT NULL,
5313               PRIMARY KEY (`id`)
5314             ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5315         });
5316     }
5317     $dbh->do( qq{
5318         INSERT IGNORE INTO permissions VALUES (13, "edit_quotes","Edit quotes for quote-of-the-day feature");
5319     });
5320     $dbh->do( qq{
5321         INSERT IGNORE INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QuoteOfTheDay',0,'Enable or disable display of Quote of the Day on the OPAC home page',NULL,'YesNo');
5322     });
5323     print "Upgrade to $DBversion done (Adding Quote of the Day Option.)\n";
5324     SetVersion($DBversion);
5325 }
5326
5327 $DBversion = "3.09.00.006";
5328 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5329     $dbh->do("UPDATE systempreferences SET
5330                 variable = 'OPACShowHoldQueueDetails',
5331                 value = CASE value WHEN '1' THEN 'priority' ELSE 'none' END,
5332                 options = 'none|priority|holds|holds_priority',
5333                 explanation = 'Show holds details in OPAC',
5334                 type = 'Choice'
5335               WHERE variable = 'OPACDisplayRequestPriority'");
5336     print "Upgrade to $DBversion done (Changed system preference OPACDisplayRequestPriority -> OPACShowHoldQueueDetails)\n";
5337     SetVersion($DBversion);
5338 }
5339
5340 $DBversion = "3.09.00.007";
5341 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5342     unless(C4::Context->preference('ReservesControlBranch')){
5343         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('ReservesControlBranch','PatronLibrary','ItemHomeLibrary|PatronLibrary','Branch checked for members reservations rights.','Choice')");
5344     }
5345     print "Upgrade to $DBversion done (Insert ReservesControlBranch systempreference into systempreferences table )\n";
5346     SetVersion($DBversion);
5347 }
5348
5349 $DBversion = "3.09.00.008";
5350 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5351     $dbh->do("ALTER TABLE sessions ADD PRIMARY KEY (id);");
5352     $dbh->do("ALTER TABLE sessions DROP INDEX `id`;");
5353     print "Upgrade to $DBversion done (redefine the field id as PRIMARY KEY of sessions)\n";
5354     SetVersion($DBversion);
5355 }
5356
5357 $DBversion = "3.09.00.009";
5358 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5359     $dbh->do("ALTER TABLE branches ADD PRIMARY KEY (branchcode);");
5360     $dbh->do("ALTER TABLE branches DROP INDEX branchcode;");
5361     print "Upgrade to $DBversion done (redefine the field branchcode as PRIMARY KEY of branches)\n";
5362     SetVersion ($DBversion);
5363 }
5364
5365 $DBversion = "3.09.00.010";
5366 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5367     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('IssueLostItem', 'alert', 'alert|confirm|nothing', 'Defines what should be done when an attempt is made to issue an item that has been marked as lost.', 'Choice')");
5368     print "Upgrade to $DBversion done (Add system preference issuelostitem ))\n";
5369     SetVersion($DBversion);
5370 }
5371
5372 $DBversion = "3.09.00.011";
5373 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5374     $dbh->do("ALTER TABLE `biblioitems` ADD `ean` VARCHAR( 13 ) NULL AFTER issn");
5375     $dbh->do("CREATE INDEX `ean` ON biblioitems (`ean`) ");
5376     $dbh->do("ALTER TABLE `deletedbiblioitems` ADD `ean` VARCHAR( 13 ) NULL AFTER issn");
5377     if (C4::Context->preference("marcflavour") eq 'UNIMARC') {
5378          $dbh->do("UPDATE marc_subfield_structure SET kohafield='biblioitems.ean' WHERE tagfield='073' and tagsubfield='a'");
5379     }
5380     print "Upgrade to $DBversion done (Adding ean in biblioitems and deletedbiblioitems)\n";
5381     print "If you have records with ean, please run misc/batchRebuildBiblioTables.pl to populate bibliotems.ean\n" if (C4::Context->preference("marcflavour") eq 'UNIMARC');
5382     SetVersion($DBversion);
5383 }
5384
5385 $DBversion = "3.09.00.012";
5386 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5387     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('SuspendHoldsIntranet', '1', NULL , 'Allow holds to be suspended from the intranet.', 'YesNo')");
5388     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('SuspendHoldsOpac', '1', NULL , 'Allow holds to be suspended from the OPAC.', 'YesNo')");
5389     print "Upgrade to $DBversion done (Add system preference OpacBrowseResults ))\n";
5390     SetVersion($DBversion);
5391 }
5392
5393 $DBversion ="3.09.00.013";
5394 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5395     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('DefaultLanguageField008','','Fill in the default language for field 008 Range 35-37 (e.g. eng, nor, ger, see www.loc.gov/marc/languages/language_code.html)','','Free');");
5396     print "Upgrade to $DBversion done (Add system preference DefaultLanguageField008))\n";
5397     SetVersion($DBversion);
5398 }
5399
5400 $DBversion ="3.09.00.014";
5401 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5402     # add phone message transport type
5403     $dbh->do("INSERT INTO message_transport_types (message_transport_type) VALUES ('phone')");
5404
5405     # adds HOLD_PHONE and PREDUE_PHONE letters (as placeholders)
5406     $dbh->do("INSERT INTO letter (module, code, name, title, content) VALUES
5407               ('reserves', 'HOLD_PHONE', 'Item Available for Pick-up (phone notice)', 'Item Available for Pick-up (phone notice)', 'Your item is available for pickup'),
5408               ('circulation', 'PREDUE_PHONE', 'Advance Notice of Item Due (phone notice)', 'Advance Notice of Item Due (phone notice)', 'Your item is due soon'),
5409               ('circulation', 'OVERDUE_PHONE', 'Overdue Notice (phone notice)', 'Overdue Notice (phone notice)', 'Your item is overdue')
5410               ");
5411
5412     # add phone notifications to patron message preferences options
5413     $dbh->do("INSERT INTO message_transports
5414              (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) VALUES
5415              (4, 'phone', 0, 'reserves', 'HOLD_PHONE'),
5416              (2, 'phone', 0, 'circulation', 'PREDUE_PHONE')
5417              ");
5418
5419     # add TalkingTechItivaPhoneNotification syspref
5420     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('TalkingTechItivaPhoneNotification',0,'If ON, enables Talking Tech I-tiva phone notifications',NULL,'YesNo');");
5421
5422     print "Upgrade done (Support for Talking Tech i-tiva phone notification system)\n";
5423     SetVersion($DBversion);
5424 }
5425
5426 $DBversion = "3.09.00.015";
5427 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5428     $dbh->do(qq{
5429         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('StatisticsFields','location|itype|ccode','Define Fields (from the items table) used for statistics members','location|itype|ccode','free')
5430     });
5431     print "Upgrade to $DBversion done (Add System preference StatisticsFields)\n";
5432     SetVersion($DBversion);
5433 }
5434
5435 $DBversion = "3.09.00.016";
5436 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5437     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACShowBarcode','0','Show items barcode in holding tab','','YesNo')");
5438     print "Upgrade to $DBversion done (Add syspref OPACShowBarcode)\n";
5439     SetVersion ($DBversion);
5440 }
5441
5442 $DBversion = "3.09.00.017";
5443 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5444     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('OpacNavRight', '', '70|10', 'Show the following HTML in the right hand column of the main page under the main login form', 'Textarea');");
5445     print "Upgrade to $DBversion done (Add customizable OpacNavRight region to the OPAC main page)\n";
5446     SetVersion ($DBversion);
5447 }
5448
5449 $DBversion = "3.09.00.018";
5450 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5451     $dbh->do("DROP TABLE IF EXISTS aqbudgetborrowers");
5452     $dbh->do("
5453         CREATE TABLE aqbudgetborrowers (
5454           budget_id int(11) NOT NULL,
5455           borrowernumber int(11) NOT NULL,
5456           PRIMARY KEY (budget_id, borrowernumber),
5457           CONSTRAINT aqbudgetborrowers_ibfk_1 FOREIGN KEY (budget_id)
5458             REFERENCES aqbudgets (budget_id)
5459             ON DELETE CASCADE ON UPDATE CASCADE,
5460           CONSTRAINT aqbudgetborrowers_ibfk_2 FOREIGN KEY (borrowernumber)
5461             REFERENCES borrowers (borrowernumber)
5462             ON DELETE CASCADE ON UPDATE CASCADE
5463         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
5464     ");
5465     $dbh->do("
5466         INSERT INTO permissions (module_bit, code, description)
5467         VALUES (11, 'budget_manage_all', 'Manage all budgets')
5468     ");
5469     print "Upgrade to $DBversion done (Add aqbudgetborrowers table)\n";
5470     SetVersion($DBversion);
5471 }
5472
5473 $DBversion = "3.09.00.019";
5474 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5475     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('OPACShowUnusedAuthorities','1','','Show authorities that are not being used in the OPAC.','YesNo')");
5476     print "Upgrade to $DBversion done (Add OPACShowUnusedAuthorities system preference)\n";
5477     SetVersion ($DBversion);
5478 }
5479
5480 $DBversion = "3.09.00.020";
5481 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5482     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,type) VALUES('EnableBorrowerFiles','0','If enabled, allows librarians to upload and attach arbitrary files to a borrower record.','YesNo')");
5483     $dbh->do("
5484 CREATE TABLE IF NOT EXISTS borrower_files (
5485   file_id int(11) NOT NULL AUTO_INCREMENT,
5486   borrowernumber int(11) NOT NULL,
5487   file_name varchar(255) NOT NULL,
5488   file_type varchar(255) NOT NULL,
5489   file_description varchar(255) DEFAULT NULL,
5490   file_content longblob NOT NULL,
5491   date_uploaded timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
5492   PRIMARY KEY (file_id),
5493   KEY borrowernumber (borrowernumber)
5494 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
5495     ");
5496     $dbh->do("ALTER TABLE borrower_files ADD CONSTRAINT borrower_files_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE");
5497
5498     print "Upgrade to $DBversion done (Added borrow_files table, EnableBorrowerFiles syspref)\n";
5499     SetVersion($DBversion);
5500 }
5501
5502 $DBversion = "3.09.00.021";
5503 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5504     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UpdateTotalIssuesOnCirc','0','Whether to update the totalissues field in the biblio on each circ.',NULL,'YesNo');");
5505     print "Upgrade to $DBversion done (Add syspref UpdateTotalIssuesOnCirc)\n";
5506     SetVersion($DBversion);
5507 }
5508
5509 $DBversion = "3.09.00.022";
5510 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5511     $dbh->do("ALTER TABLE search_history MODIFY COLUMN query_cgi text NOT NULL");
5512     print "Upgrade to $DBversion done (Change search_history.query_cgi type to text. bug 5981)\n";
5513     SetVersion($DBversion);
5514 }
5515
5516 $DBversion = "3.09.00.023";
5517 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5518     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('SearchEngine','Zebra','Solr|Zebra','Search Engine','Choice')");
5519     print "Upgrade to $DBversion done (Add system preference SearchEngine )\n";
5520     SetVersion($DBversion);
5521 }
5522
5523 $DBversion ="3.09.00.024";
5524 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5525     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('IntranetSlipPrinterJS','','Use this JavaScript for printing slips. Define at least function printThenClose(). For use e.g. with Firefox PlugIn jsPrintSetup, see http://jsprintsetup.mozdev.org/','','Free')");
5526     print "Upgrade to $DBversion done (Add system preference IntranetSlipPrinterJS))\n";
5527     SetVersion($DBversion);
5528 }
5529
5530 $DBversion = "3.09.00.025";
5531 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5532     $dbh->do('START TRANSACTION');
5533     $dbh->do('CREATE TABLE tmp_reserves AS SELECT * FROM old_reserves LIMIT 0');
5534     $dbh->do('ALTER TABLE tmp_reserves ADD reserve_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
5535     $dbh->do("
5536         INSERT INTO tmp_reserves (
5537           borrowernumber, reservedate, biblionumber,
5538           constrainttype, branchcode, notificationdate,
5539           reminderdate, cancellationdate, reservenotes,
5540           priority, found, timestamp, itemnumber,
5541           waitingdate, expirationdate, lowestPriority,
5542           suspend, suspend_until
5543         ) SELECT
5544           borrowernumber, reservedate, biblionumber,
5545           constrainttype, branchcode, notificationdate,
5546           reminderdate, cancellationdate, reservenotes,
5547           priority, found, timestamp, itemnumber,
5548           waitingdate, expirationdate, lowestPriority,
5549           suspend, suspend_until
5550         FROM old_reserves ORDER BY reservedate
5551     ");
5552     $dbh->do('SET @ai = ( SELECT MAX( reserve_id ) FROM tmp_reserves )');
5553     $dbh->do('TRUNCATE old_reserves');
5554     $dbh->do('ALTER TABLE old_reserves ADD reserve_id INT( 11 ) NOT NULL PRIMARY KEY FIRST');
5555     $dbh->do('INSERT INTO old_reserves SELECT * FROM tmp_reserves WHERE reserve_id <= @ai');
5556     $dbh->do("
5557         INSERT INTO tmp_reserves (
5558           borrowernumber, reservedate, biblionumber,
5559           constrainttype, branchcode, notificationdate,
5560           reminderdate, cancellationdate, reservenotes,
5561           priority, found, timestamp, itemnumber,
5562           waitingdate, expirationdate, lowestPriority,
5563           suspend, suspend_until
5564         ) SELECT
5565           borrowernumber, reservedate, biblionumber,
5566           constrainttype, branchcode, notificationdate,
5567           reminderdate, cancellationdate, reservenotes,
5568           priority, found, timestamp, itemnumber,
5569           waitingdate, expirationdate, lowestPriority,
5570           suspend, suspend_until
5571         FROM reserves ORDER BY reservedate
5572     ");
5573     $dbh->do('TRUNCATE reserves');
5574     $dbh->do('ALTER TABLE reserves ADD reserve_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
5575     $dbh->do('INSERT INTO reserves SELECT * FROM tmp_reserves WHERE reserve_id > COALESCE(@ai, 0)');
5576     $dbh->do('DROP TABLE tmp_reserves');
5577     $dbh->do('COMMIT');
5578
5579     my $sth = $dbh->prepare("
5580         SELECT COUNT( * ) AS count
5581         FROM information_schema.COLUMNS
5582         WHERE COLUMN_NAME =  'reserve_id'
5583         AND (
5584           TABLE_NAME LIKE  'reserves'
5585           OR
5586           TABLE_NAME LIKE  'old_reserves'
5587         )
5588     ");
5589     $sth->execute();
5590     my $row = $sth->fetchrow_hashref();
5591     die("Failed to add reserve_id to reserves tables, please refresh the page to try again.") unless ( $row->{'count'} );
5592
5593     print "Upgrade to $DBversion done (add reserve_id to reserves & old_reserves tables)\n";
5594     SetVersion($DBversion);
5595 }
5596
5597 $DBversion = "3.09.00.026";
5598 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5599     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
5600         ( 3, 'parameters_remaining_permissions', 'Remaining system parameters permissions'),
5601         ( 3, 'manage_circ_rules', 'manage circulation rules')");
5602     $dbh->do("INSERT INTO user_permissions (borrowernumber, module_bit, code)
5603         SELECT borrowernumber, 3, 'parameters_remaining_permissions'
5604         FROM borrowers WHERE flags & (1 << 3)");
5605     # Give new subpermissions to all users that have 'parameters' permission flag (bit 3) set
5606     # see userflags table
5607     $dbh->do("INSERT INTO user_permissions (borrowernumber, module_bit, code)
5608         SELECT borrowernumber, 3, 'manage_circ_rules'
5609         FROM borrowers WHERE flags & (1 << 3)");
5610     print "Upgrade to $DBversion done (Added parameters subpermissions)\n";
5611     SetVersion($DBversion);
5612 }
5613
5614 $DBversion = '3.09.00.027';
5615 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5616     $dbh->do("ALTER TABLE issuingrules ADD overduefinescap decimal(28,6) DEFAULT NULL");
5617     my $maxfine = C4::Context->preference('MaxFine');
5618     if ($maxfine && $maxfine < 900) { # an arbitrary value that tells us it's not "some huge value"
5619       $dbh->do("UPDATE issuingrules SET overduefinescap=?",undef,$maxfine);
5620       $dbh->do("UPDATE systempreferences SET value = NULL WHERE variable = 'MaxFine'");
5621     }
5622     $dbh->do("UPDATE systempreferences SET explanation = 'Maximum fine a patron can have for all late returns at one moment. Single item caps are specified in the circulation rules matrix.' WHERE variable = 'MaxFine'");
5623     print "Upgrade to $DBversion done (Bug 7420 add overduefinescap to circulation matrix)\n";
5624     SetVersion ($DBversion);
5625 }
5626
5627 $DBversion = "3.09.00.028";
5628 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5629     unless ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) {
5630         my %referencetypes = (  '00' => 'PERSO_NAME',
5631                                 '10' => 'CORPO_NAME',
5632                                 '11' => 'MEETI_NAME',
5633                                 '30' => 'UNIF_TITLE',
5634                                 '48' => 'CHRON_TERM',
5635                                 '50' => 'TOPIC_TERM',
5636                                 '51' => 'GEOGR_NAME',
5637                                 '55' => 'GENRE/FORM'
5638                 );
5639         my $query = q{SELECT DISTINCT authtypecode, tagfield
5640                     FROM auth_subfield_structure
5641                     WHERE (tagfield BETWEEN '400' AND '455' OR
5642                     tagfield BETWEEN '500' and '555') AND tagsubfield='a' AND
5643                     frameworkcode = '' AND ROW(authtypecode, tagfield) NOT IN
5644                     (SELECT authtypecode, tagfield FROM auth_subfield_structure
5645                     WHERE tagsubfield ='9' )};
5646         $sth = $dbh->prepare($query);
5647         $sth->execute;
5648         my $sth2 = $dbh->prepare(q{INSERT INTO auth_subfield_structure
5649                 (authtypecode, tagfield, tagsubfield, liblibrarian, libopac,
5650                  repeatable, mandatory, tab, authorised_value, value_builder,
5651                  seealso, isurl, hidden, linkid, kohafield, frameworkcode)
5652                 VALUES (?, ?, '9', '9 (RLIN)', '9 (RLIN)', 0, 0, ?, NULL, NULL,
5653                     NULL, 0, 1, '', '', '')});
5654         my $sth3 = $dbh->prepare(q{UPDATE auth_subfield_structure SET
5655                                     frameworkcode = ? WHERE authtypecode = ? AND
5656                                     tagfield = ? AND tagsubfield = 'a'});
5657         while (my $row = $sth->fetchrow_arrayref()) {
5658             my ($authtypecode, $field) = @$row;
5659             $sth2->execute($authtypecode, $field, substr($field, 0, 1));
5660             my $authtypemarker = substr $field, 1, 2;
5661             if ($authtypemarker && $referencetypes{$authtypemarker}) {
5662                 $sth3->execute($referencetypes{$authtypemarker}, $authtypecode, $field);
5663             }
5664         }
5665     }
5666
5667     print "Upgrade to $DBversion done (Add thesaurus links for MARC21/NORMARC)\n";
5668     SetVersion($DBversion);
5669 }
5670
5671 $DBversion = "3.09.00.029"; # FIXME
5672 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5673     $dbh->do("UPDATE systempreferences SET options=concat(options,'|EAN13') WHERE variable='itemBarcodeInputFilter' AND options NOT LIKE '%EAN13%'");
5674     print "Upgrade to $DBversion done (Add itemBarcodeInputFilter choice EAN13)\n";
5675
5676     $dbh->do("UPDATE systempreferences SET options = concat(options,'|EAN13'), explanation = concat(explanation,'; EAN13 - incremental') WHERE variable = 'autoBarcode' AND options NOT LIKE '%EAN13%'");
5677     print "Upgrade to $DBversion done ( Added EAN13 barcode autogeneration sequence )\n";
5678     SetVersion($DBversion);
5679 }
5680
5681 $DBversion ="3.09.00.030";
5682 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5683     my $query = "SELECT value FROM systempreferences WHERE variable='opacstylesheet'";
5684     my $remote= $dbh->selectrow_arrayref($query);
5685     $dbh->do("DELETE from systempreferences WHERE variable='opacstylesheet'");
5686     if($remote && $remote->[0]) {
5687         $query="UPDATE systempreferences SET value=? WHERE variable='opaclayoutstylesheet'";
5688         $dbh->do($query,undef,$remote->[0]);
5689         print "NOTE: The URL of your remote opac css file has been moved to preference opaclayoutstylesheet.\n";
5690     }
5691     print "Upgrade to $DBversion done (BZ 8263: Make OPAC stylesheet preferences more consistent)\n";
5692     SetVersion($DBversion);
5693 }
5694
5695 $DBversion = "3.09.00.031";
5696 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5697     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonReviews'");
5698     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonSimilarItems'");
5699     $dbh->do("DELETE FROM systempreferences WHERE variable='AWSAccessKeyID'");
5700     $dbh->do("DELETE FROM systempreferences WHERE variable='AWSPrivateKey'");
5701     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonReviews'");
5702     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonSimilarItems'");
5703     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonEnabled'");
5704     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonEnabled'");
5705     print "Upgrade to $DBversion done ('Remove preferences controlling broken Amazon features (Bug 8679')\n";
5706     SetVersion ($DBversion);
5707 }
5708
5709 $DBversion = "3.09.00.032";
5710 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5711     $dbh->do("UPDATE systempreferences SET value = 'call_number' WHERE variable = 'defaultSortField' AND value = 'callnumber'");
5712     $dbh->do("UPDATE systempreferences SET value = 'call_number' WHERE variable = 'OPACdefaultSortField' AND value = 'callnumber'");
5713     print "Upgrade to $DBversion done (Bug 8657 - Default sort by call number does not work. Correcting system preference value.)\n";
5714     SetVersion ($DBversion);
5715 }
5716
5717
5718 $DBversion = '3.09.00.033';
5719 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5720    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacSuppressionByIPRange','','Restrict the suppression to IP adresses outside of the IP range','','free');");
5721    print "Upgrade to $DBversion done (Add OpacSuppressionByIPRange syspref)\n";
5722    SetVersion ($DBversion);
5723 }
5724
5725 $DBversion ="3.09.00.034";
5726 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5727     $dbh->do("UPDATE auth_subfield_structure SET frameworkcode = 'PERSO_NAME' WHERE frameworkcode = 'PERSO_CODE'");
5728     $dbh->do("UPDATE auth_subfield_structure SET frameworkcode = 'CORPO_NAME' WHERE frameworkcode = 'ORGO_CODE'");
5729     print "Upgrade to $DBversion done (Bug 8207: correct typo in authority types)\n";
5730     SetVersion ($DBversion);
5731 }
5732
5733 $DBversion = "3.09.00.035";
5734 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5735     $dbh->do("
5736     INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('PrefillItem','0','When a new item is added, should it be prefilled with last created item values?','','YesNo');
5737     ");
5738     $dbh->do(
5739     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SubfieldsToUseWhenPrefill','','Define a list of subfields to use when prefilling items (separated by space)','','Free');
5740     ");
5741     print "Upgrade to $DBversion done (Adding PrefillItem and SubfieldsToUseWhenPrefill sysprefs)\n";
5742     SetVersion ($DBversion);
5743 }
5744
5745 $DBversion = "3.09.00.036";
5746 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5747     # biblioitems changes
5748     $dbh->do("ALTER TABLE biblioitems ADD COLUMN agerestriction VARCHAR(255) DEFAULT NULL AFTER cn_sort");
5749     $dbh->do("ALTER TABLE deletedbiblioitems ADD COLUMN agerestriction VARCHAR(255) DEFAULT NULL AFTER cn_sort");
5750     # preferences changes
5751     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AgeRestrictionMarker','','Markers for age restriction indication, e.g. FSK|PEGI|Age|. See: http://wiki.koha-community.org/wiki/Age_restriction',NULL,'free')");
5752     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AgeRestrictionOverride',0,'Allow staff to check out an item with age restriction.',NULL,'YesNo')");
5753
5754     print "Upgrade to $DBversion done (Add colum agerestriction to biblioitems and deletedbiblioitems, add system preferences AgeRestrictionMarker and AgeRestrictionOverride)\n";
5755    SetVersion ($DBversion);
5756 }
5757
5758 $DBversion = "3.09.00.037";
5759 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5760     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('UseTransportCostMatrix',0,'Use Transport Cost Matrix when filling holds','','YesNo')");
5761
5762  $dbh->do("CREATE TABLE `transport_cost` (
5763               `frombranch` varchar(10) NOT NULL,
5764               `tobranch` varchar(10) NOT NULL,
5765               `cost` decimal(6,2) NOT NULL,
5766               `disable_transfer` tinyint(1) NOT NULL DEFAULT 0,
5767               CHECK ( `frombranch` <> `tobranch` ), -- a dud check, mysql does not support that
5768               PRIMARY KEY (`frombranch`, `tobranch`),
5769               CONSTRAINT `transport_cost_ibfk_1` FOREIGN KEY (`frombranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
5770               CONSTRAINT `transport_cost_ibfk_2` FOREIGN KEY (`tobranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
5771           ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
5772
5773     print "Upgrade to $DBversion done (creating `transport_cost` table; adding UseTransportCostMatrix systempref, in circulation)\n";
5774     SetVersion($DBversion);
5775 }
5776
5777 $DBversion ="3.09.00.038";
5778 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5779     $dbh->do("ALTER TABLE borrower_attributes CHANGE  attribute  attribute VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
5780     print "Upgrade to $DBversion done (Increase the maximum size of a borrower attribute value)\n";
5781     SetVersion($DBversion);
5782 }
5783
5784 $DBversion ="3.09.00.039";
5785 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5786     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,type) VALUES('DidYouMeanFromAuthorities','0','Suggest searches based on authority file.','YesNo');");
5787     print "Upgrade to $DBversion done (Add system preference DidYouMeanFromAuthorities)\n";
5788     SetVersion($DBversion);
5789 }
5790
5791 $DBversion = "3.09.00.040";
5792 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5793     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('IncludeSeeFromInSearches','0','','Include see-from references in searches.','YesNo');");
5794     print "Upgrade to $DBversion done (Add IncludeSeeFromInSearches system preference)\n";
5795     SetVersion ($DBversion);
5796 }
5797
5798 $DBversion = "3.09.00.041";
5799 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5800     $dbh->do(qq{
5801         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ExportRemoveFields','','List of fields for non export in circulation.pl (separated by a space)','','');
5802     });
5803     print "Upgrade to $DBversion done (Add system preference ExportRemoveFields)\n";
5804     SetVersion($DBversion);
5805 }
5806
5807 $DBversion = "3.09.00.042";
5808 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5809     $dbh->do(qq{
5810         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ExportWithCsvProfile','','Set a profile name for CSV export','','');
5811     });
5812     print "Upgrade to $DBversion done (Adds New System preference ExportWithCsvProfile)\n";
5813     SetVersion($DBversion)
5814 }
5815
5816 $DBversion = "3.09.00.043";
5817 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5818     $dbh->do("
5819         ALTER TABLE aqorders
5820         ADD parent_ordernumber int(11) DEFAULT NULL
5821     ");
5822     $dbh->do("
5823         UPDATE aqorders
5824         SET parent_ordernumber = ordernumber;
5825     ");
5826     print "Upgrade to $DBversion done (Adding parent_ordernumber in aqorders)\n";
5827     SetVersion($DBversion);
5828 }
5829
5830 $DBversion = '3.09.00.044';
5831 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5832     $dbh->do("ALTER TABLE statistics ADD COLUMN ccode VARCHAR ( 10 ) NULL AFTER associatedborrower");
5833     $dbh->do("UPDATE statistics SET statistics.ccode = ( SELECT items.ccode FROM items WHERE statistics.itemnumber = items.itemnumber )");
5834     $dbh->do("UPDATE statistics SET statistics.ccode = (
5835               SELECT deleteditems.ccode FROM deleteditems
5836                   WHERE statistics.itemnumber = deleteditems.itemnumber
5837               ) WHERE statistics.ccode IS NULL");
5838     print "Upgrade done ( Added Collection Code to Statistics table. )\n";
5839     SetVersion ($DBversion);
5840 }
5841
5842 $DBversion = "3.09.00.045";
5843 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5844     $dbh->do("ALTER TABLE borrower_attribute_types MODIFY category_code VARCHAR( 10 ) NULL DEFAULT NULL");
5845     print "Upgrade to $DBversion done. (Bug 8002: Update patron attribute types table from varchar(1) to varchar(10) category_code)\nWarning to Koha System Administrators: If you use borrower attributes defined by borrower categories, you have to check your configuration. A bug may have removed your attribute links to borrower categories.\nPlease check, and fix it if necessary.";
5846     SetVersion($DBversion);
5847 }
5848
5849 $DBversion = "3.09.00.046";
5850 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5851     $dbh->do("ALTER TABLE `accountlines` ADD `accountlines_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;");
5852     print "Upgrade to $DBversion done (adding accountlines_id field in accountlines table)\n";
5853     SetVersion($DBversion);
5854 }
5855
5856 $DBversion = "3.09.00.047";
5857 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5858     # to preserve default behaviour as best as possible, set this new preference differently depending on whether IndependantBranches is set or not
5859     my $prefvalue = 'anywhere';
5860     if (C4::Context->preference("IndependantBranches")) { $prefvalue = 'homeorholdingbranch';}
5861     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowReturnToBranch', '$prefvalue', 'Where an item may be returned', 'anywhere|homebranch|holdingbranch|homeorholdingbranch', 'Choice');");
5862
5863     print "Upgrade to $DBversion done: adding AllowReturnToBranch syspref (bug 6151)";
5864     SetVersion($DBversion);
5865 }
5866
5867 $DBversion = "3.09.00.048";
5868 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5869     $dbh->do("ALTER TABLE authorised_values MODIFY lib varchar(200)");
5870     $dbh->do("ALTER TABLE authorised_values MODIFY lib_opac varchar(200)");
5871
5872     print "Upgrade to $DBversion done (Raise the length of Authorised Values descriptions)\n";
5873     SetVersion($DBversion);
5874 }
5875
5876 $DBversion ="3.09.00.049";
5877 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5878     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OPACMobileUserCSS','','Include the following CSS for the mobile view on all pages in the OPAC:',NULL,'free');");
5879     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacMainUserBlockMobile','','Show the following HTML in its own column on the main page of the OPAC (mobile version):',NULL,'free');");
5880     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacShowLibrariesPulldownMobile','1','Show the libraries pulldown on the mobile version of the OPAC.',NULL,'YesNo');");
5881     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacShowFiltersPulldownMobile','1','Show the search filters pulldown on the mobile version of the OPAC.',NULL,'YesNo');");
5882     print "Upgrade to $DBversion done (Add OPACMobileUserCSS, OpacMainUserBlockMobile, OpacShowLibrariesPulldownMobile and OpacShowFiltersPulldownMobile sysprefs)\n";
5883     SetVersion($DBversion);
5884 }
5885
5886 $DBversion = "3.09.00.050";
5887 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5888     $dbh->do("ALTER TABLE authorised_values MODIFY category varchar(16) NOT NULL DEFAULT '';");
5889     $dbh->do("INSERT INTO authorised_values (category, authorised_value, lib) VALUES
5890               ('REPORT_GROUP', 'CIRC', 'Circulation'),
5891               ('REPORT_GROUP', 'CAT', 'Catalog'),
5892               ('REPORT_GROUP', 'PAT', 'Patrons'),
5893               ('REPORT_GROUP', 'ACQ', 'Acquisitions'),
5894               ('REPORT_GROUP', 'ACC', 'Accounts');");
5895
5896     $dbh->do("ALTER TABLE reports_dictionary ADD report_area varchar(6) DEFAULT NULL;");
5897     $dbh->do("UPDATE reports_dictionary SET report_area = CASE area
5898                   WHEN 1 THEN 'CIRC'
5899                   WHEN 2 THEN 'CAT'
5900                   WHEN 3 THEN 'PAT'
5901                   WHEN 4 THEN 'ACQ'
5902                   WHEN 5 THEN 'ACC'
5903                   END;");
5904     $dbh->do("ALTER TABLE reports_dictionary DROP area;");
5905     $dbh->do("ALTER TABLE reports_dictionary ADD KEY dictionary_area_idx (report_area);");
5906
5907     $dbh->do("ALTER TABLE saved_sql ADD report_area varchar(6) DEFAULT NULL;");
5908     $dbh->do("ALTER TABLE saved_sql ADD report_group varchar(80) DEFAULT NULL;");
5909     $dbh->do("ALTER TABLE saved_sql ADD report_subgroup varchar(80) DEFAULT NULL;");
5910     $dbh->do("ALTER TABLE saved_sql ADD KEY sql_area_group_idx (report_group, report_subgroup);");
5911
5912     print "Upgrade to $DBversion done saved_sql new fields report_group and report_area; authorised_values.category 16 char \n";
5913     SetVersion($DBversion);
5914 }
5915
5916 $DBversion = "3.09.00.051";
5917 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5918     $dbh->do("
5919         CREATE TABLE aqinvoices (
5920           invoiceid int(11) NOT NULL AUTO_INCREMENT,
5921           invoicenumber mediumtext NOT NULL,
5922           booksellerid int(11) NOT NULL,
5923           shipmentdate date default NULL,
5924           billingdate date default NULL,
5925           closedate date default NULL,
5926           shipmentcost decimal(28,6) default NULL,
5927           shipmentcost_budgetid int(11) default NULL,
5928           PRIMARY KEY (invoiceid),
5929           CONSTRAINT aqinvoices_fk_aqbooksellerid FOREIGN KEY (booksellerid) REFERENCES aqbooksellers (id) ON DELETE CASCADE ON UPDATE CASCADE,
5930           CONSTRAINT aqinvoices_fk_shipmentcost_budgetid FOREIGN KEY (shipmentcost_budgetid) REFERENCES aqbudgets (budget_id) ON DELETE SET NULL ON UPDATE CASCADE
5931         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5932     ");
5933
5934     # Fill this new table with existing invoices
5935     my $sth = $dbh->prepare("
5936         SELECT aqorders.booksellerinvoicenumber AS invoicenumber, aqbasket.booksellerid, aqorders.datereceived
5937         FROM aqorders
5938           LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
5939         WHERE aqorders.booksellerinvoicenumber IS NOT NULL
5940           AND aqorders.booksellerinvoicenumber != ''
5941         GROUP BY aqorders.booksellerinvoicenumber
5942     ");
5943     $sth->execute;
5944     my $results = $sth->fetchall_arrayref({});
5945     $sth = $dbh->prepare("
5946         INSERT INTO aqinvoices (invoicenumber, booksellerid, shipmentdate) VALUES (?,?,?)
5947     ");
5948     foreach(@$results) {
5949         $sth->execute($_->{invoicenumber}, $_->{booksellerid}, $_->{datereceived});
5950     }
5951
5952     # Add the column in aqorders, fill it with correct value
5953     # and then drop booksellerinvoicenumber column
5954     $dbh->do("
5955         ALTER TABLE aqorders
5956         ADD COLUMN invoiceid int(11) default NULL AFTER booksellerinvoicenumber,
5957         ADD CONSTRAINT aqorders_ibfk_3 FOREIGN KEY (invoiceid) REFERENCES aqinvoices (invoiceid) ON DELETE SET NULL ON UPDATE CASCADE
5958     ");
5959
5960     $dbh->do("
5961         UPDATE aqorders, aqinvoices
5962         SET aqorders.invoiceid = aqinvoices.invoiceid
5963         WHERE aqorders.booksellerinvoicenumber = aqinvoices.invoicenumber
5964     ");
5965
5966     $dbh->do("
5967         ALTER TABLE aqorders
5968         DROP COLUMN booksellerinvoicenumber
5969     ");
5970
5971     print "Upgrade to $DBversion done (Add aqinvoices table) \n";
5972     SetVersion ($DBversion);
5973 }
5974
5975 $DBversion = "3.09.00.052";
5976 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5977     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('decreaseLoanHighHolds', NULL, '', 'Decreases the loan period for items with number of holds above the threshold specified in decreaseLoanHighHoldsValue', 'YesNo');");
5978     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('decreaseLoanHighHoldsValue', NULL, '', 'Specifies a threshold for the minimum number of holds needed to trigger a reduction in loan duration (used with decreaseLoanHighHolds)', 'Integer');");
5979     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('decreaseLoanHighHoldsDuration', NULL, '', 'Specifies a number of days that a loan is reduced to when used in conjunction with decreaseLoanHighHolds', 'Integer');");
5980     print "Upgrade to $DBversion done (Add systempreferences to decrease loan length on high demand items decreaseLoanHighHolds, decreaseLoanHighHoldsValue and decreaseLoanHighHoldsDuration) \n";
5981     SetVersion ($DBversion);
5982 }
5983
5984 $DBversion = "3.09.00.053";
5985 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5986     $dbh->do(
5987     q|CREATE TABLE `import_auths` (
5988         import_record_id int(11) NOT NULL,
5989         matched_authid int(11) default NULL,
5990         control_number varchar(25) default NULL,
5991         authorized_heading varchar(128) default NULL,
5992         original_source varchar(25) default NULL,
5993         CONSTRAINT import_auths_ibfk_1 FOREIGN KEY (import_record_id)
5994         REFERENCES import_records (import_record_id) ON DELETE CASCADE ON UPDATE CASCADE,
5995         KEY matched_authid (matched_authid)
5996         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;|
5997     );
5998     $dbh->do("ALTER TABLE import_batches
5999                 CHANGE COLUMN num_biblios num_records int(11) NOT NULL default 0,
6000                 ADD COLUMN record_type enum('biblio', 'auth', 'holdings') NOT NULL default 'biblio'");
6001     $dbh->do("UPDATE import_batches SET record_type='auth' WHERE import_batch_id IN
6002                 (SELECT import_batch_id FROM import_records WHERE record_type='auth')");
6003
6004     print "Upgrade to $DBversion done (Added support for staging authorities)\n";
6005     SetVersion ($DBversion);
6006 }
6007
6008 $DBversion = "3.09.00.054";
6009 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6010     $dbh->do("ALTER TABLE aqorders CHANGE COLUMN gst gstrate DECIMAL(6,4)  DEFAULT NULL");
6011     print "Upgrade to $DBversion done (Change column name in aqorders gst --> gstrate)\n";
6012     SetVersion($DBversion);
6013 }
6014
6015 $DBversion = "3.09.00.055";
6016 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6017     $dbh->do("ALTER TABLE aqorders ADD discount float(6,4) DEFAULT NULL AFTER gstrate");
6018     print "Upgrade to $DBversion done (Add discount field in aqorders table)\n";
6019     SetVersion($DBversion);
6020 }
6021
6022 $DBversion ="3.09.00.056";
6023 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6024     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('AuthDisplayHierarchy','0','Display authority hierarchies','','YesNo')");
6025     print "Upgrade to $DBversion done (Add system preference AuthDisplayHierarchy)\n";
6026     SetVersion($DBversion);
6027 }
6028
6029 $DBversion = "3.09.00.057";
6030 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6031     $dbh->do("ALTER TABLE aqbasket ADD deliveryplace VARCHAR(10) default NULL AFTER basketgroupid;");
6032     $dbh->do("ALTER TABLE aqbasket ADD billingplace VARCHAR(10) default NULL AFTER deliveryplace;");
6033     print "Upgrade to $DBversion done (Bug 5356: Added billingplace, deliveryplace to the aqbasket table)\n";
6034     SetVersion($DBversion);
6035 }
6036
6037 $DBversion ="3.09.00.058";
6038 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6039     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,type) VALUES('OPACdidyoumean',NULL,'Did you mean? configuration for the OPAC. Do not change, as this is controlled by /cgi-bin/koha/admin/didyoumean.pl.','Free');");
6040     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,type) VALUES('INTRAdidyoumean',NULL,'Did you mean? configuration for the Intranet. Do not change, as this is controlled by /cgi-bin/koha/admin/didyoumean.pl.','Free');");
6041     print "Upgrade to $DBversion done (Add Did You Mean? configuration)\n";
6042     SetVersion($DBversion);
6043 }
6044
6045 $DBversion ="3.09.00.059";
6046 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6047     $dbh->do("INSERT INTO systempreferences (variable, value, options, explanation, type) VALUES ('BlockReturnOfWithdrawnItems', '1', '0', 'If enabled, items that are marked as withdrawn cannot be returned.', 'YesNo');");
6048     print "Upgrade to $DBversion done (Add system preference BlockReturnOfWithdrawnItems)\n";
6049     SetVersion($DBversion);
6050 }
6051
6052 $DBversion = "3.09.00.060";
6053 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6054     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('HoldsToPullStartDate','2','Set the default start date for the Holds to pull list to this many days ago',NULL,'Integer')");
6055     print "Upgrade to $DBversion done (Added HoldsToPullStartDate syspref)\n";
6056     SetVersion($DBversion);
6057 }
6058
6059 $DBversion = "3.09.00.061";
6060 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6061     $dbh->do("UPDATE systempreferences set value=0 WHERE variable='OPACItemsResultsDisplay' AND value='statuses'");
6062     $dbh->do("UPDATE systempreferences set value=1 WHERE variable='OPACItemsResultsDisplay' AND value='itemdetails'");
6063     $dbh->do("UPDATE systempreferences SET explanation='If No, show only the status of items in result list. If Yes, show full location of items (branchlocation+callnumber) as in staff interface',options=NULL,type='YesNo' WHERE variable='OPACItemsResultsDisplay'");
6064     print "Upgrade to $DBversion done (Fixes Bug 5409, Set the syspref value to 1 if it is itemdetails and 0 if it is statuses, leaving it alone if it is already 1 or 0 and change the type of the syspref to YesNo.)\n";
6065     SetVersion ($DBversion);
6066 }
6067
6068 $DBversion = "3.09.00.062";
6069 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6070    $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='NoZebra'");
6071    $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='QueryRemoveStopwords'");
6072    print "Upgrade to $DBversion done (Disable obsolete NoZebra and QueryRemoveStopwords sysprefs)\n";
6073    SetVersion ($DBversion);
6074 }
6075
6076 $DBversion = "3.09.00.063";
6077 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6078     my $gst_booksellers = $dbh->selectcol_arrayref("SELECT DISTINCT(gstrate) FROM aqbooksellers");
6079     my $gist_syspref = C4::Context->preference("gist");
6080     # remove the undef values and construct and array with the syspref and the supplier values
6081     my @gstrates = map { defined $_ ? $_ : () } @$gst_booksellers;
6082     push @gstrates, split ('\|', $gist_syspref);
6083     # we want to compare integer (or float)
6084     $_ = $_ + 0 for @gstrates;
6085     use List::MoreUtils qw/uniq/;
6086     # remove duplicate values
6087     @gstrates = uniq sort @gstrates;
6088     my $new_syspref_value = join '|', @gstrates;
6089     # update the syspref with the new values
6090     my $sth = $dbh->prepare("UPDATE systempreferences set value=? WHERE variable='gist'");
6091     $sth->execute( $new_syspref_value );
6092
6093     print "Upgrade to $DBversion done (Bug 8832, Set the syspref gist with the existing values)\n";
6094     SetVersion ($DBversion);
6095 }
6096
6097 $DBversion = "3.09.00.064";
6098 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6099    $dbh->do('ALTER TABLE items ADD coded_location_qualifier varchar(10) default NULL AFTER itemcallnumber');
6100    print "Upgrade to $DBversion done (Bug 6428: Added coded_location_qualifier to the items table)\n";
6101    SetVersion ($DBversion);
6102 }
6103
6104 $DBversion = "3.09.00.065";
6105 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6106    $dbh->do('ALTER TABLE deleteditems ADD coded_location_qualifier varchar(10) default NULL AFTER itemcallnumber');
6107    print "Upgrade to $DBversion done (Bug 6428: Added coded_location_qualifier to the deleteditems table)\n";
6108    SetVersion ($DBversion);
6109 }
6110
6111 $DBversion = "3.09.00.066";
6112 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6113    $dbh->do("DELETE FROM systempreferences WHERE variable='DidYouMeanFromAuthorities'");
6114    print "Upgrade to $DBversion done (Bug 9107: remove DidYouMeanFromAuthorities syspref)\n";
6115    SetVersion ($DBversion);
6116 }
6117
6118 $DBversion = "3.09.00.067";
6119 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6120    $dbh->do("ALTER TABLE statistics CHANGE COLUMN ccode ccode varchar(10) NULL");
6121    print "Upgrade to $DBversion done (Bug 9064: statistics.ccode potentially wrongly defined)\n";
6122    SetVersion ($DBversion);
6123 }
6124
6125 $DBversion = "3.10.00.00";
6126 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6127    print "Upgrade to $DBversion done (release tag)\n";
6128    SetVersion ($DBversion);
6129 }
6130
6131 $DBversion = "3.11.00.001";
6132 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6133     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('alphabet','A B C D E F G H I J K L M N O P Q R S T U V W X Y Z','Alphabet that can be expanded into browse links, e.g. on Home > Patrons',NULL,'free')");
6134     print "Upgrade to $DBversion done (Bug 2832 - Add alphabet syspref)\n";
6135 }
6136
6137 $DBversion = "3.11.00.002";
6138 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6139     $dbh->do(q{
6140         DELETE from aqorders_items where ordernumber NOT IN (SELECT ordernumber FROM aqorders);
6141     });
6142     $dbh->do(q{
6143         ALTER TABLE aqorders_items
6144         ADD CONSTRAINT aqorders_items_ibfk_1 FOREIGN KEY (ordernumber) REFERENCES aqorders (ordernumber)
6145         ON DELETE CASCADE ON UPDATE CASCADE;
6146     });
6147     print "Upgrade to $DBversion done (Bug 9030: Add constraint on aqorders_items.ordernumber)\n";
6148     SetVersion ($DBversion);
6149 }
6150
6151 $DBversion = "3.11.00.003";
6152 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6153     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('RefundLostItemFeeOnReturn', '1', 'If enabled, the lost item fee charged to a borrower will be refunded when the lost item is returned.', NULL, 'YesNo')");
6154     print "Upgrade to $DBversion done (Bug 7189: Add system preference RefundLostItemFeeOnReturn)\n";
6155     SetVersion($DBversion);
6156 }
6157
6158 $DBversion = "3.11.00.004";
6159 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6160     $dbh->do(qq{
6161         ALTER TABLE subscription ADD COLUMN closed INT(1) NOT NULL DEFAULT 0 AFTER enddate;
6162     });
6163
6164     print "Upgrade to $DBversion done (Bug 8782: Add field subscription.closed)\n";
6165     SetVersion($DBversion);
6166 }
6167
6168 $DBversion = "3.11.00.005";
6169 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6170     $dbh->do(qq{CREATE TABLE borrower_attribute_types_branches(bat_code VARCHAR(10), b_branchcode VARCHAR(10),FOREIGN KEY (bat_code) REFERENCES borrower_attribute_types(code) ON DELETE CASCADE,FOREIGN KEY (b_branchcode) REFERENCES branches(branchcode) ON DELETE CASCADE ) ENGINE=INNODB DEFAULT CHARSET=utf8;});
6171
6172     $dbh->do(qq{CREATE TABLE categories_branches(categorycode VARCHAR(10), branchcode VARCHAR(10), FOREIGN KEY (categorycode) REFERENCES categories(categorycode) ON DELETE CASCADE, FOREIGN KEY (branchcode) REFERENCES branches(branchcode) ON DELETE CASCADE ) ENGINE=INNODB DEFAULT CHARSET=utf8;});
6173
6174     $dbh->do(qq{CREATE TABLE authorised_values_branches(av_id INTEGER, branchcode VARCHAR(10), FOREIGN KEY (av_id) REFERENCES authorised_values(id) ON DELETE CASCADE, FOREIGN KEY  (branchcode) REFERENCES branches(branchcode) ON DELETE CASCADE ) ENGINE=INNODB DEFAULT CHARSET=utf8;});
6175
6176     print "Upgrade to $DBversion done (Bug 7919: Display of values depending on the connexion library)\n";
6177     SetVersion($DBversion);
6178 }
6179
6180 $DBversion = "3.11.00.006";
6181 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6182     $dbh->do(q{
6183         UPDATE virtualshelves SET sortfield="copyrightdate" where sortfield="year";
6184     });
6185     print "Upgrade to $DBversion done (Bug 9167: Update the virtualshelves.sortfield column with 'copyrightdate' if needed)\n";
6186     SetVersion($DBversion);
6187 }
6188
6189 $DBversion = "3.11.00.007";
6190 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6191     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ar', 'language', 'de', 'Arabisch')");
6192     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hy', 'language', 'de', 'Armenisch')");
6193     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'bg', 'language', 'de', 'Bulgarisch')");
6194     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'zh', 'language', 'de', 'Chinesisch')");
6195     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'cs', 'language', 'de', 'Tschechisch')");
6196     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'da', 'language', 'de', 'Dänisch')");
6197     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nl', 'language', 'de', 'Niederländisch')");
6198     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'en', 'language', 'de', 'Englisch')");
6199     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fi', 'language', 'de', 'Finnisch')");
6200     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fr', 'language', 'de', 'Französisch')");
6201     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'lo', 'language', 'fr', 'Laotien')");
6202     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'lo', 'language', 'de', 'Laotisch')");
6203     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'el', 'language', 'de', 'Griechisch (Nach 1453)')");
6204     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'he', 'language', 'de', 'Hebräisch')");
6205     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hi', 'language', 'de', 'Hindi')");
6206     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hu', 'language', 'de', 'Ungarisch')");
6207     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'id', 'language', 'de', 'Indonesisch')");
6208     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'it', 'language', 'de', 'Italienisch')");
6209     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ja', 'language', 'de', 'Japanisch')");
6210     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ko', 'language', 'de', 'Koreanisch')");
6211     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'la', 'language', 'de', 'Latein')");
6212     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'gl', 'language', 'fr', 'Galicien')");
6213     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'gl', 'language', 'de', 'Galizisch')");
6214     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nb', 'language', 'de', 'Norwegisch bokm&#229;l')");
6215     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nn', 'language', 'de', 'Norwegisch nynorsk')");
6216     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fa', 'language', 'de', 'Persisch')");
6217     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'pl', 'language', 'de', 'Polnisch')");
6218     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'pt', 'language', 'de', 'Portugiesisch')");
6219     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ro', 'language', 'de', 'Rumänisch')");
6220     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ru', 'language', 'de', 'Russisch')");
6221     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sr', 'language', 'fr', 'Serbe')");
6222     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sr', 'language', 'de', 'Serbisch')");
6223     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'es', 'language', 'de', 'Spanisch')");
6224     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sv', 'language', 'de', 'Schwedisch')");
6225     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tet', 'language', 'fr', 'Tétoum')");
6226     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tet', 'language', 'de', 'Tetum')");
6227     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'th', 'language', 'de', 'Thailändisch')");
6228     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tr', 'language', 'de', 'Türkisch')");
6229     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'uk', 'language', 'de', 'Ukrainisch')");
6230     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ur', 'language', 'fr', 'Ourdou')");
6231     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ur', 'language', 'de', 'Urdu')");
6232     print "Upgrade to $DBversion done (Bug 9056: add German and a couple of French translations to language_descriptions)\n";
6233     SetVersion ($DBversion);
6234 }
6235
6236 $DBversion = "3.11.00.008";
6237 if (CheckVersion($DBversion)) {
6238     $dbh->do("
6239         CREATE TABLE IF NOT EXISTS `borrower_modifications` (
6240           `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6241           `verification_token` varchar(255) NOT NULL DEFAULT '',
6242           `borrowernumber` int(11) NOT NULL DEFAULT '0',
6243           `cardnumber` varchar(16) DEFAULT NULL,
6244           `surname` mediumtext,
6245           `firstname` text,
6246           `title` mediumtext,
6247           `othernames` mediumtext,
6248           `initials` text,
6249           `streetnumber` varchar(10) DEFAULT NULL,
6250           `streettype` varchar(50) DEFAULT NULL,
6251           `address` mediumtext,
6252           `address2` text,
6253           `city` mediumtext,
6254           `state` text,
6255           `zipcode` varchar(25) DEFAULT NULL,
6256           `country` text,
6257           `email` mediumtext,
6258           `phone` text,
6259           `mobile` varchar(50) DEFAULT NULL,
6260           `fax` mediumtext,
6261           `emailpro` text,
6262           `phonepro` text,
6263           `B_streetnumber` varchar(10) DEFAULT NULL,
6264           `B_streettype` varchar(50) DEFAULT NULL,
6265           `B_address` varchar(100) DEFAULT NULL,
6266           `B_address2` text,
6267           `B_city` mediumtext,
6268           `B_state` text,
6269           `B_zipcode` varchar(25) DEFAULT NULL,
6270           `B_country` text,
6271           `B_email` text,
6272           `B_phone` mediumtext,
6273           `dateofbirth` date DEFAULT NULL,
6274           `branchcode` varchar(10) DEFAULT NULL,
6275           `categorycode` varchar(10) DEFAULT NULL,
6276           `dateenrolled` date DEFAULT NULL,
6277           `dateexpiry` date DEFAULT NULL,
6278           `gonenoaddress` tinyint(1) DEFAULT NULL,
6279           `lost` tinyint(1) DEFAULT NULL,
6280           `debarred` date DEFAULT NULL,
6281           `debarredcomment` varchar(255) DEFAULT NULL,
6282           `contactname` mediumtext,
6283           `contactfirstname` text,
6284           `contacttitle` text,
6285           `guarantorid` int(11) DEFAULT NULL,
6286           `borrowernotes` mediumtext,
6287           `relationship` varchar(100) DEFAULT NULL,
6288           `ethnicity` varchar(50) DEFAULT NULL,
6289           `ethnotes` varchar(255) DEFAULT NULL,
6290           `sex` varchar(1) DEFAULT NULL,
6291           `password` varchar(30) DEFAULT NULL,
6292           `flags` int(11) DEFAULT NULL,
6293           `userid` varchar(75) DEFAULT NULL,
6294           `opacnote` mediumtext,
6295           `contactnote` varchar(255) DEFAULT NULL,
6296           `sort1` varchar(80) DEFAULT NULL,
6297           `sort2` varchar(80) DEFAULT NULL,
6298           `altcontactfirstname` varchar(255) DEFAULT NULL,
6299           `altcontactsurname` varchar(255) DEFAULT NULL,
6300           `altcontactaddress1` varchar(255) DEFAULT NULL,
6301           `altcontactaddress2` varchar(255) DEFAULT NULL,
6302           `altcontactaddress3` varchar(255) DEFAULT NULL,
6303           `altcontactstate` text,
6304           `altcontactzipcode` varchar(50) DEFAULT NULL,
6305           `altcontactcountry` text,
6306           `altcontactphone` varchar(50) DEFAULT NULL,
6307           `smsalertnumber` varchar(50) DEFAULT NULL,
6308           `privacy` int(11) DEFAULT NULL,
6309           PRIMARY KEY (`verification_token`,`borrowernumber`),
6310           KEY `verification_token` (`verification_token`),
6311           KEY `borrowernumber` (`borrowernumber`)
6312         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6313 ");
6314
6315     $dbh->do("
6316         INSERT INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES
6317         ('PatronSelfRegistration', '0', NULL, 'If enabled, patrons will be able to register themselves via the OPAC.', 'YesNo'),
6318         ('PatronSelfRegistrationVerifyByEmail', '0', NULL, 'If enabled, any patron attempting to register themselves via the OPAC will be required to verify themselves via email to activate his or her account.', 'YesNo'),
6319         ('PatronSelfRegistrationDefaultCategory', '', '', 'A patron registered via the OPAC will receive a borrower category code set in this system preference.', 'free'),
6320         ('PatronSelfRegistrationExpireTemporaryAccountsDelay', '0', NULL, 'If PatronSelfRegistrationDefaultCategory is enabled, this system preference controls how long a patron can have a temporary status before the account is deleted automatically. It is an integer value representing a number of days to wait before deleting a temporary patron account. Setting it to 0 disables the deleting of temporary accounts.', 'Integer'),
6321         ('PatronSelfRegistrationBorrowerMandatoryField',  'surname|firstname', NULL ,  'Choose the mandatory fields for a patron''s account, when registering via the OPAC.',  'free'),
6322         ('PatronSelfRegistrationBorrowerUnwantedField',  '', NULL ,  'Name the fields you don''t want to display when registering a new patron via the OPAC.',  'free');
6323     ");
6324
6325     $dbh->do("
6326     INSERT INTO  letter ( `module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content` )
6327     VALUES ( 'members', 'OPAC_REG_VERIFY', '', 'Opac Self-Registration Verification Email', '1', 'Verify Your Account', 'Hello!
6328
6329     Your library account has been created. Please verify your email address by clicking this link to complete the signup process:
6330
6331     http://<<OPACBaseURL>>/cgi-bin/koha/opac-registration-verify.pl?token=<<borrower_modifications.verification_token>>
6332
6333     If you did not initiate this request, you may safely ignore this one-time message. The request will expire shortly.'
6334     )");
6335
6336     print "Upgrade to $DBversion done (Bug 7067: Add Patron Self Registration)\n";
6337     SetVersion ($DBversion);
6338 }
6339
6340 $DBversion = "3.11.00.009";
6341 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6342     $dbh->do("
6343         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
6344         ('SeparateHoldings', '0', 'Separate current branch holdings from other holdings', NULL, 'YesNo'),
6345         ('SeparateHoldingsBranch', 'homebranch', 'Branch used to separate holdings', 'homebranch|holdingbranch', 'Choice'),
6346         ('OpacSeparateHoldings', '0', 'Separate current branch holdings from other holdings (OPAC)', NULL, 'YesNo'),
6347         ('OpacSeparateHoldingsBranch', 'homebranch', 'Branch used to separate holdings (OPAC)', 'homebranch|holdingbranch', 'Choice')
6348     ");
6349
6350     print "Upgrade to $DBversion done (Bug 7674: Add systempreferences SeparateHoldings, SeparateHoldingsBranch, OpacSeparateHoldings and OpacSeparateHoldingsBranch) \n";
6351     SetVersion ($DBversion);
6352 }
6353
6354 $DBversion = "3.11.00.010";
6355 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6356     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('RenewalSendNotice', '0', '', NULL, 'YesNo')");
6357     $dbh->do(q{
6358         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
6359         ('circulation','RENEWAL','Item Renewals','Item Renewals','The following items have been renewed:\r\n----\r\n<<biblio.title>>\r\n----\r\nThank you for visiting <<branches.branchname>>.');
6360     });
6361     print "Upgrade to $DBversion done (Bug 9151 - Renewal notice according to patron alert preferences)\n";
6362     SetVersion($DBversion);
6363 }
6364
6365 $DBversion = "3.11.00.011";
6366 if ( CheckVersion($DBversion) ) {
6367    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('HTML5MediaEnabled','not','Show a HTML5 media player in a tab on opac-detail.pl for media files catalogued in field 856.','not|opac|staff|both','Choice');");
6368    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('HTML5MediaExtensions','webm|ogg|ogv|oga|vtt','Media file extensions','','free');");
6369    print "Upgrade to $DBversion done (Bug 8377: Add HTML5MediaEnabled and HTML5MediaExtensions sysprefs)\n";
6370    SetVersion ($DBversion);
6371 }
6372
6373 $DBversion = "3.11.00.012";
6374 if ( CheckVersion($DBversion) ) {
6375     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowHoldsOnPatronsPossessions', '1', 'Allow holds on records that patron have items of it',NULL,'YesNo')");
6376     print "Upgrade to $DBversion done (Bug 9206: Only allow place holds in records that the patron don't have in his possession)\n";
6377     SetVersion($DBversion);
6378 }
6379
6380 $DBversion = "3.11.00.013";
6381 if ( CheckVersion($DBversion) ) {
6382     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('NotesBlacklist','','List of notes fields that should not appear in the title notes/description separator of details',NULL,'free')");
6383     print "Upgrade to $DBversion done (Bug 9162 - Add a system preference to set which notes fields appears on title notes/description separator)\n";
6384     SetVersion($DBversion);
6385 }
6386
6387 $DBversion = "3.11.00.014";
6388 if ( CheckVersion($DBversion) ) {
6389    $dbh->do("INSERT INTO systempreferences ( variable, value, explanation, type ) VALUES ( 'SCOUserCSS', '', 'Add CSS to be included in the SCO module in an embedded <style> tag.', 'free' )");
6390    $dbh->do("INSERT INTO systempreferences ( variable, value, explanation, type ) VALUES ( 'SCOUserJS', '', 'Define custom javascript for inclusion in the SCO module', 'free' )");
6391    print "Upgrade to $DBversion done (Bug 9009: Add SCOUserCSS and SCOUserJS sysprefs)\n";
6392 }
6393
6394 $DBversion = "3.11.00.015";
6395 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6396     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('RentalsInNoissuesCharge', '1', 'Rental charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
6397     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('ManInvInNoissuesCharge', '1', 'MANUAL_INV charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
6398     print "Upgrade to $DBversion done (Add sysprefs RentalsInNoissuesCharge and ManInvInNoissuesCharge.)\n";
6399     SetVersion($DBversion);
6400 }
6401
6402 $DBversion = "3.11.00.016";
6403 if ( CheckVersion($DBversion) ) {
6404    $dbh->do(q{
6405         UPDATE userflags SET flagdesc="<b>Required for staff login.</b> Staff access, allows viewing of catalogue in staff client." where flagdesc="Modify login / permissions for staff users";
6406         });
6407    $dbh->do(q{
6408         UPDATE userflags SET flagdesc="Edit Authorities" where flagdesc="Allow to edit authorities";
6409         });
6410    $dbh->do(q{
6411         UPDATE userflags SET flagdesc="Allow access to the reports module" where flagdesc="Allow to access to the reports module";
6412         });
6413    $dbh->do(q{
6414         UPDATE userflags SET flagdesc="Set library management parameters (deprecated)" where flagdesc="Set library management parameters";
6415         });
6416    $dbh->do(q{
6417         UPDATE userflags SET flagdesc="Manage serial subscriptions" where flagdesc="Allow to manage serials subscriptions";
6418         });
6419    $dbh->do(q{
6420         UPDATE userflags SET flagdesc="Manage patrons fines and fees" where flagdesc="Update borrower charges";
6421         });
6422    $dbh->do(q{
6423         UPDATE userflags SET flagdesc="Check out and check in items" where flagdesc="Circulate books";
6424         });
6425    $dbh->do(q{
6426         UPDATE userflags SET flagdesc="Manage Koha system settings (Administration panel)" where flagdesc="Set Koha system parameters";
6427         });
6428    $dbh->do(q{
6429         UPDATE userflags SET flagdesc="Add or modify patrons" where flagdesc="Add or modify borrowers";
6430         });
6431    $dbh->do(q{
6432         UPDATE userflags SET flagdesc="Use all tools (expand for granular tools permissions)" where flagdesc="Use tools (export, import, barcodes)";
6433         });
6434    $dbh->do(q{
6435         UPDATE userflags SET flagdesc="Allow staff members to modify permissions for other staff members" where flagdesc="Set user permissions";
6436         });
6437    $dbh->do(q{
6438         UPDATE permissions SET description="Perform batch modification of patrons" where description="Perform batch modifivation of patrons";
6439         });
6440
6441    print "Upgrade to $DBversion done (Bug 9382 (updated with bug 9745) - refresh permission descriptions to make more sense)\n";
6442    SetVersion ($DBversion);
6443 }
6444
6445 $DBversion ="3.11.00.017";
6446 if ( CheckVersion($DBversion) ) {
6447     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksReviews','0','Display book review snippets from IDreamBooks.com','','YesNo');");
6448     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksReadometer','0','Display Readometer from IDreamBooks.com','','YesNo');");
6449     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksResults','0','Display IDreamBooks.com rating in search results','','YesNo');");
6450     print "Upgrade to $DBversion done (Add IDreamBooks enhanced content)\n";
6451     SetVersion($DBversion);
6452 }
6453
6454 $DBversion = "3.11.00.018";
6455 if ( CheckVersion($DBversion) ) {
6456    $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('OPACNumbersPreferPhrase','0', NULL, 'Control the use of phr operator in callnumber and standard number OPAC searches', 'YesNo')");
6457    $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('IntranetNumbersPreferPhrase','0', NULL, 'Control the use of phr operator in callnumber and standard number staff client searches', 'YesNo')");
6458    print "Upgrade to $DBversion done (Bug 9395: Problem with callnumber and standard number search in OPAC and Staff Client)\n";
6459    SetVersion ($DBversion);
6460 }
6461
6462 $DBversion = "3.11.00.019";
6463 if ( CheckVersion($DBversion) ) {
6464     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('UNIMARCAuthorityField100', 'afrey50      ba0', NULL, NULL, 'Textarea')");
6465     print "Upgrade to $DBversion done (Bug 9145 - Add syspref UNIMARCAuthorityField100)\n";
6466     SetVersion ($DBversion);
6467 }
6468
6469 $DBversion = "3.11.00.020";
6470 if ( CheckVersion($DBversion) ) {
6471     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UNIMARCField100Language', 'fre','UNIMARC field 100 default language',NULL,'short')");
6472     print "Upgrade to $DBversion done (Bug 8347 - Koha forces UNIMARC 100 field code language to 'fre')\n";
6473     SetVersion($DBversion);
6474 }
6475
6476 $DBversion ="3.11.00.021";
6477 if ( CheckVersion($DBversion) ) {
6478     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OPACPopupAuthorsSearch','0','Display the list of authors when clicking on one author.','','YesNo');");
6479     print "Upgrade to $DBversion done (Bug 5888 - Subject search pop-up for the OPAC)\n";
6480     SetVersion($DBversion);
6481 }
6482
6483 $DBversion = "3.11.00.022";
6484 if ( CheckVersion($DBversion) ) {
6485     $dbh->do(
6486 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('Persona',0,'Use Mozilla Persona for login','','YesNo')"
6487     );
6488     print "Upgrade to $DBversion done (Bug 9587 - Allow login via Persona)\n";
6489     SetVersion($DBversion);
6490 }
6491
6492 $DBversion = "3.11.00.023";
6493 if ( CheckVersion($DBversion) ) {
6494     $dbh->do("UPDATE z3950servers SET host = 'lx2.loc.gov', port = 210, db = 'LCDB', syntax = 'USMARC', encoding = 'utf8' WHERE name = 'LIBRARY OF CONGRESS'");
6495     print "Upgrade to $DBversion done (Bug 9520 - Update default LOC Z39.50 target)\n";
6496     SetVersion($DBversion);
6497 }
6498
6499 $DBversion = "3.11.00.024";
6500 if ( CheckVersion($DBversion) ) {
6501     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacItemLocation','callnum','Show the shelving location of items in the opac','callnum|ccode|location','Choice');");
6502     print "Upgrade to $DBversion done (Bug 5079: Add OpacItemLocation syspref)\n";
6503     SetVersion ($DBversion);
6504 }
6505
6506 $DBversion = "3.11.00.025";
6507 if ( CheckVersion($DBversion) ) {
6508     $dbh->do(
6509         "CREATE TABLE linktracker (
6510   id int(11) NOT NULL AUTO_INCREMENT,
6511   biblionumber int(11) DEFAULT NULL,
6512   itemnumber int(11) DEFAULT NULL,
6513   borrowernumber int(11) DEFAULT NULL,
6514   url text,
6515   timeclicked datetime DEFAULT NULL,
6516   PRIMARY KEY (id),
6517   KEY bibidx (biblionumber),
6518   KEY itemidx (itemnumber),
6519   KEY borridx (borrowernumber),
6520   KEY dateidx (timeclicked)
6521     ) ENGINE=InnoDB DEFAULT CHARSET=utf8;"
6522     );
6523     $dbh->do( "
6524   INSERT INTO systempreferences (variable,value,explanation,options,type)
6525   VALUES('TrackClicks','0','Track links clicked',NULL,'Integer')" );
6526     print
6527 "Upgrade to $DBversion done (Adds feature Bug 8917, the ability to track links clicked)\n";
6528     SetVersion($DBversion);
6529 }
6530
6531 $DBversion = "3.11.00.026";
6532 if ( CheckVersion($DBversion) ) {
6533     $dbh->do(qq{
6534         ALTER TABLE import_records ADD INDEX batch_id_record_type ( import_batch_id, record_type );
6535     });
6536     print "Upgrade to $DBversion done (Bug 9207: Add new index batch_id_record_type to import_records)\n";
6537     SetVersion($DBversion);
6538 }
6539
6540 $DBversion = "3.11.00.027";
6541 if ( CheckVersion($DBversion) ) {
6542     $dbh->do(q{
6543         INSERT INTO permissions ( module_bit, code, description )
6544         VALUES  ( '1', 'overdues_report', 'Execute overdue items report' )
6545     });
6546     # add new permission for users with all report permissions and circulation remaining permission
6547     $dbh->do(q{
6548         INSERT INTO user_permissions (borrowernumber, module_bit, code)
6549         SELECT user_permissions.borrowernumber, 1, 'overdues_report'
6550         FROM user_permissions
6551         LEFT JOIN borrowers USING(borrowernumber)
6552         WHERE borrowers.flags & (1 << 16)
6553         AND user_permissions.code = 'circulate_remaining_permissions'
6554     });
6555     print "Upgrade to $DBversion done ( Add circ permission overdues_report )\n";
6556     SetVersion($DBversion);
6557 }
6558
6559 $DBversion = "3.11.00.028";
6560 if ( CheckVersion($DBversion) ) {
6561     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('PatronSelfRegistrationAdditionalInstructions', '', NULL , 'A free text field to display additional instructions to newly self registered patrons.', 'free'    );");
6562     print "Upgrade to $DBversion done (Bug 9756 - Patron self registration missing the system preference PatronSelfRegistrationAdditionalInstructions)\n";
6563     SetVersion($DBversion);
6564 }
6565
6566 $DBversion = "3.11.00.029";
6567 if (CheckVersion($DBversion)) {
6568     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UseQueryParser', '0', 'If enabled, try to use QueryParser for queries.', NULL, 'YesNo')");
6569     print "Upgrade to $DBversion done (Bug 9239: Make it possible for Koha to use QueryParser)\n";
6570     SetVersion ($DBversion);
6571 }
6572
6573 $DBversion = "3.11.00.030";
6574 if ( CheckVersion($DBversion) ) {
6575     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('FinesIncludeGracePeriod','1','If enabled, fines calculations will include the grace period.',NULL,'YesNo');");
6576     print "Upgrade to $DBversion done (Add system preference FinesIncludeGracePeriod)\n";
6577     SetVersion($DBversion);
6578 }
6579
6580 $DBversion = "3.11.00.100";
6581 if ( CheckVersion($DBversion) ) {
6582     print "Upgrade to $DBversion done (3.12-alpha release)\n";
6583     SetVersion ($DBversion);
6584 }
6585
6586 $DBversion = "3.11.00.101";
6587 if ( CheckVersion($DBversion) ) {
6588    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('UNIMARCAuthorsFacetsSeparator',', ', 'UNIMARC authors facets separator', NULL, 'short')");
6589    print "Upgrade to $DBversion done (Bug 9341: Problem with UNIMARC authors facets)\n";
6590    SetVersion ($DBversion);
6591 }
6592
6593 $DBversion = "3.11.00.102";
6594 if ( CheckVersion($DBversion) ) {
6595     $dbh->do(q{
6596         DELETE FROM systempreferences WHERE variable='NoZebra'
6597     });
6598     $dbh->do(q{
6599         DELETE FROM systempreferences WHERE variable='QueryRemoveStopwords'
6600     });
6601     print "Upgrade to $DBversion done (Remove deprecated NoZebra and QueryRemoveStopwords sysprefs)\n";
6602     SetVersion($DBversion);
6603 }
6604
6605 $DBversion = "3.11.00.103";
6606 if ( CheckVersion($DBversion) ) {
6607     $dbh->do("DELETE FROM systempreferences WHERE variable = 'insecure';");
6608     print "Upgrade to $DBversion done (Bug 9827 - Remove 'insecure' system preference)\n";
6609     SetVersion($DBversion);
6610 }
6611
6612 $DBversion = "3.11.00.104";
6613 if ( CheckVersion($DBversion) ) {
6614     print "Upgrade to $DBversion done (3.12-alpha2 release)\n";
6615     SetVersion ($DBversion);
6616 }
6617
6618 $DBversion = "3.11.00.105";
6619 if ( CheckVersion($DBversion) ) {
6620     if ( C4::Context->preference("marcflavour") eq 'MARC21' ) {
6621         $sth = $dbh->prepare(
6622 "SELECT frameworkcode FROM marc_tag_structure WHERE tagfield = '029'"
6623         );
6624         $sth->execute;
6625         my $frameworkcodes = $sth->fetchall_hashref('frameworkcode');
6626
6627         for my $frameworkcode ( keys %$frameworkcodes ) {
6628             $dbh->do( "
6629     INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian,
6630     libopac, repeatable, mandatory, kohafield, tab, authorised_value, authtypecode,
6631     value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
6632     ('029', 'a', 'OCLC library identifier', 'OCLC library identifier', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6633     ('029', 'b', 'System control number', 'System control number', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6634     ('029', 'c', 'OAI set name', 'OAI set name', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6635     ('029', 't', 'Content type identifier', 'Content type identifier', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL)
6636    " );
6637         }
6638
6639         for my $tag ( '863', '864', '865' ) {
6640             $sth = $dbh->prepare(
6641 "SELECT frameworkcode FROM marc_tag_structure WHERE tagfield = '$tag'"
6642             );
6643             $sth->execute;
6644             my $frameworkcodes = $sth->fetchall_hashref('frameworkcode');
6645
6646             for my $frameworkcode ( keys %$frameworkcodes ) {
6647                 $dbh->do( "
6648      INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian,
6649      libopac, repeatable, mandatory, kohafield, tab, authorised_value, authtypecode,
6650      value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
6651      ('$tag', '6', 'Linkage', 'Linkage', 0, 0, '', 8, '', '', '', NULL, 5, '$frameworkcode', '', '', NULL),
6652      ('$tag', '8', 'Field link and sequence number', 'Field link and sequence number', 0, 0, '', 8, '', '', '', NULL, 5, '$frameworkcode', '', '', NULL),
6653      ('$tag', 'a', 'First level of enumeration', 'First level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6654      ('$tag', 'b', 'Second level of enumeration', 'Second level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6655      ('$tag', 'c', 'Third level of enumeration', 'Third level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6656      ('$tag', 'd', 'Fourth level of enumeration', 'Fourth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6657      ('$tag', 'e', 'Fifth level of enumeration', 'Fifth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6658      ('$tag', 'f', 'Sixth level of enumeration', 'Sixth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6659      ('$tag', 'g', 'Alternative numbering scheme, first level of enumeration', 'Alternative numbering scheme, first level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6660      ('$tag', 'h', 'Alternative numbering scheme, second level of enumeration', 'Alternative numbering scheme, second level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6661      ('$tag', 'i', 'First level of chronology', 'First level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6662      ('$tag', 'j', 'Second level of chronology', 'Second level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6663      ('$tag', 'k', 'Third level of chronology', 'Third level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6664      ('$tag', 'l', 'Fourth level of chronology', 'Fourth level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6665      ('$tag', 'm', 'Alternative numbering scheme, chronology', 'Alternative numbering scheme, chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6666      ('$tag', 'n', 'Converted Gregorian year', 'Converted Gregorian year', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6667      ('$tag', 'o', 'Type of unit', 'Type of unit', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6668      ('$tag', 'p', 'Piece designation', 'Piece designation', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6669      ('$tag', 'q', 'Piece physical condition', 'Piece physical condition', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6670      ('$tag', 's', 'Copyright article-fee code', 'Copyright article-fee code', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6671      ('$tag', 't', 'Copy number', 'Copy number', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6672      ('$tag', 'v', 'Issuing date', 'Issuing date', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6673      ('$tag', 'w', 'Break indicator', 'Break indicator', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6674      ('$tag', 'x', 'Nonpublic note', 'Nonpublic note', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6675      ('$tag', 'z', 'Public note', 'Public note', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL)
6676     " );
6677             }
6678         }
6679     }
6680     print "Upgrade to $DBversion done (Bug 9353: Missing subfields on MARC21 frameworks)\n";
6681     SetVersion($DBversion);
6682 }
6683
6684
6685 $DBversion = "3.11.00.106";
6686 if ( CheckVersion($DBversion) ) {
6687     $dbh->do("INSERT INTO userflags (bit, flag, flagdesc, defaulton) VALUES ('19', 'plugins', 'Koha plugins', '0')");
6688     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
6689               ('19', 'manage', 'Manage plugins ( install / uninstall )'),
6690               ('19', 'tool', 'Use tool plugins'),
6691               ('19', 'report', 'Use report plugins'),
6692               ('19', 'configure', 'Configure plugins')
6693             ");
6694     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UseKohaPlugins','0','Enable or disable the ability to use Koha Plugins.','','YesNo')");
6695
6696     $dbh->do("
6697         CREATE TABLE IF NOT EXISTS plugin_data (
6698             plugin_class varchar(255) NOT NULL,
6699             plugin_key varchar(255) NOT NULL,
6700             plugin_value text,
6701             PRIMARY KEY (plugin_class,plugin_key)
6702         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6703     ");
6704
6705     print "Upgrade to $DBversion done (Bug 7804: Added plugin system.)\n";
6706     SetVersion($DBversion);
6707 }
6708
6709 $DBversion = "3.11.00.107";
6710 if ( CheckVersion($DBversion) ) {
6711    $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('TimeFormat','24hr','12hr|24hr','Defines the global time format for visual output.','Choice')");
6712    print "Upgrade to $DBversion done (Bug 9014: Add syspref TimeFormat)\n";
6713    SetVersion ($DBversion);
6714 }
6715
6716 $DBversion = "3.11.00.108";
6717 if ( CheckVersion($DBversion) ) {
6718     $dbh->do("ALTER TABLE action_logs CHANGE timestamp timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;");
6719     $dbh->do("UPDATE action_logs SET info=(SELECT itemnumber FROM items WHERE biblionumber= action_logs.info LIMIT 1) WHERE module='CIRCULATION' AND action in ('ISSUE','RETURN');");
6720     $dbh->do("ALTER TABLE action_logs CHANGE timestamp timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;");
6721     print "Upgrade to $DBversion done (Bug 7241: Fix on circulation logs)\n";
6722     print "WARNING about bug 7241: to partially correct the broken logs, the log history is filled with the first found item for each biblio.\n";
6723     SetVersion($DBversion);
6724 }
6725
6726 $DBversion = "3.11.00.109";
6727 if ( CheckVersion($DBversion) ) {
6728    $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('DisplayIconsXSLT', '1', '', 'If ON, displays the format, audience, and material type icons in XSLT MARC21 results and detail pages.', 'YesNo');");
6729    print "Upgrade to $DBversion done (Bug 9403: Add DisplayIconsXSLT)\n";
6730    SetVersion ($DBversion);
6731 }
6732
6733 $DBversion = "3.11.00.110";
6734 if ( CheckVersion($DBversion) ) {
6735     $dbh->do("ALTER TABLE pending_offline_operations CHANGE barcode barcode VARCHAR( 20 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
6736     $dbh->do("ALTER TABLE pending_offline_operations ADD amount DECIMAL( 28, 6 ) NULL DEFAULT NULL");
6737     print "Upgrade to $DBversion done (Bug 8220 - Allow koc uploads to go to process queue)\n";
6738     SetVersion ($DBversion);
6739 }
6740
6741 $DBversion = "3.11.00.111";
6742 if ( CheckVersion($DBversion) ) {
6743     my $sth = $dbh->prepare("
6744         SELECT module, code, branchcode, content
6745         FROM letter
6746         WHERE content LIKE '%<fine>%'
6747     ");
6748     $sth->execute;
6749     my $sth_update = $dbh->prepare("UPDATE letter SET content = ? WHERE module = ? AND code = ? AND branchcode = ?");
6750     while(my $row = $sth->fetchrow_hashref){
6751         $row->{content} =~ s/<fine>\w+<\/fine>/<<items.fine>>/;
6752         $sth_update->execute($row->{content}, $row->{module}, $row->{code}, $row->{branchcode});
6753     }
6754     print "Upgrade to $DBversion done (use new <<items.fine>> syntax in notices)\n";
6755     SetVersion($DBversion);
6756 }
6757
6758 $DBversion = "3.11.00.112";
6759 if ( CheckVersion($DBversion) ) {
6760     $dbh->do(qq{
6761         ALTER TABLE issuingrules ADD COLUMN renewalperiod int(4) DEFAULT NULL AFTER renewalsallowed
6762     });
6763     $dbh->do(qq{
6764         UPDATE issuingrules SET renewalperiod = issuelength
6765     });
6766     print "Upgrade to $DBversion done (Bug 8365: Add colum issuingrules.renewalperiod)\n";
6767     SetVersion ($DBversion);
6768 }
6769
6770 $DBversion = "3.11.00.113";
6771 if ( CheckVersion($DBversion) ) {
6772     $dbh->do(q{
6773         ALTER TABLE branchcategories ADD show_in_pulldown BOOLEAN NOT NULL DEFAULT '0',
6774         ADD INDEX ( show_in_pulldown )
6775     });
6776     print "Upgrade to $DBversion done (Bug 9257 - Add groups to normal search pulldown)\n";
6777     SetVersion ($DBversion);
6778 }
6779
6780 $DBversion = "3.11.00.115";
6781 if ( CheckVersion($DBversion) ) {
6782     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('HighlightOwnItemsOnOPAC','0','','If on, and a patron is logged into the OPAC, items from his or her home library will be emphasized and shown first in search results and item details.','YesNo')");
6783     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('HighlightOwnItemsOnOPACWhich','PatronBranch','PatronBranch|OpacURLBranch','Decides which branch''s items to emphasize. If PatronBranch, emphasize the logged in user''s library''s items. If OpacURLBranch, highlight the items of the Apache var BRANCHCODE defined in Koha''s Apache configuration file.','Choice')");
6784     print "Upgrade to $DBversion done (Bug 7740: Add syspref HighlightOwnItemsOnOPAC)\n";
6785     SetVersion ($DBversion);
6786 }
6787
6788 $DBversion = "3.11.00.116";
6789 if ( CheckVersion($DBversion) ) {
6790     $dbh->do(q{ALTER TABLE aqorders DROP COLUMN serialid;});
6791     $dbh->do(q{ALTER TABLE aqorders DROP COLUMN subscription;});
6792     $dbh->do(q{ALTER TABLE aqorders ADD COLUMN subscriptionid INT(11) DEFAULT NULL;});
6793     $dbh->do(q{ALTER TABLE aqorders ADD CONSTRAINT aqorders_subscriptionid FOREIGN KEY (subscriptionid) REFERENCES subscription (subscriptionid) ON DELETE CASCADE ON UPDATE CASCADE;});
6794     $dbh->do(q{ALTER TABLE subscription ADD COLUMN reneweddate DATE DEFAULT NULL;});
6795     print "Upgrade to $DBversion done (Bug 5343: table aqorders: DROP serialid and subscription fields and ADD subscriptionid, table subscription: ADD reneweddate)\n";
6796     SetVersion ($DBversion);
6797 }
6798
6799 $DBversion = "3.11.00.200";
6800 if ( CheckVersion($DBversion) ) {
6801     print "Upgrade to $DBversion done (3.12-beta1 release)\n";
6802     SetVersion ($DBversion);
6803 }
6804
6805 $DBversion = "3.11.00.201";
6806 if ( CheckVersion($DBversion) ) {
6807     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'BIBSYS' AND host LIKE 'z3950.bibsys.no'");
6808     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'NORBOK' AND host LIKE 'z3950.nb.no'");
6809     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'SAMBOK' AND host LIKE 'z3950.nb.no'");
6810     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'DEICHMAN' AND host like 'z3950.deich.folkebibl.no'");
6811     print "Upgrade to $DBversion done (Bug 9498 - Update encoding for Norwegian sample Z39.50 servers)\n";
6812     SetVersion($DBversion);
6813 }
6814
6815 $DBversion = "3.11.00.202";
6816 if ( CheckVersion($DBversion) ) {
6817    $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ca', 'language', 'Catalan','2013-01-12' )");
6818    $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'ca','cat')");
6819    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'es', 'Catalán')");
6820    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'en', 'Catalan')");
6821    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'fr', 'Catalan')");
6822    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'ca', 'Català')");
6823    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'de', 'Katalanisch')");
6824    print "Upgrade to $DBversion done (Bug 9381: Add Catalan laguage)\n";
6825    SetVersion ($DBversion);
6826 }
6827
6828 $DBversion = "3.11.00.203";
6829 if ( CheckVersion($DBversion) ) {
6830     $dbh->do(q{ALTER TABLE suggestions CHANGE COLUMN title title VARCHAR(255) DEFAULT NULL;});
6831     print "Upgrade to $DBversion done (Bug 2046 - increasing title column length for suggestions)\n";
6832     SetVersion ($DBversion);
6833 }
6834
6835 $DBversion = "3.11.00.300";
6836 if ( CheckVersion($DBversion) ) {
6837     print "Upgrade to $DBversion done (3.12-beta3 release)\n";
6838     SetVersion ($DBversion);
6839 }
6840
6841 $DBversion = "3.11.00.301";
6842 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6843     #issues
6844     $dbh->do(q{
6845         ALTER TABLE `issues`
6846             ADD KEY `itemnumber_idx` (`itemnumber`),
6847             ADD KEY `branchcode_idx` (`branchcode`),
6848             ADD KEY `issuingbranch_idx` (`issuingbranch`)
6849     });
6850     $dbh->do(q{
6851         ALTER TABLE `old_issues`
6852             ADD KEY `branchcode_idx` (`branchcode`),
6853             ADD KEY `issuingbranch_idx` (`issuingbranch`)
6854     });
6855     #items
6856     $dbh->do(q{
6857         ALTER TABLE `items` ADD KEY `itype_idx` (`itype`)
6858     });
6859     $dbh->do(q{
6860         ALTER TABLE `deleteditems` ADD KEY `itype_idx` (`itype`)
6861     });
6862     # biblioitems
6863     $dbh->do(q{
6864         ALTER TABLE `biblioitems` ADD KEY `itemtype_idx` (`itemtype`)
6865     });
6866     $dbh->do(q{
6867         ALTER TABLE `deletedbiblioitems` ADD KEY `itemtype_idx` (`itemtype`)
6868     });
6869     # statistics
6870     $dbh->do(q{
6871         ALTER TABLE `statistics`
6872             ADD KEY `branch_idx` (`branch`),
6873             ADD KEY `proccode_idx` (`proccode`),
6874             ADD KEY `type_idx` (`type`),
6875             ADD KEY `usercode_idx` (`usercode`),
6876             ADD KEY `itemnumber_idx` (`itemnumber`),
6877             ADD KEY `itemtype_idx` (`itemtype`),
6878             ADD KEY `borrowernumber_idx` (`borrowernumber`),
6879             ADD KEY `associatedborrower_idx` (`associatedborrower`),
6880             ADD KEY `ccode_idx` (`ccode`)
6881     });
6882
6883     print "Upgrade to $DBversion done (Bug 9681: Add some database indexes)\n";
6884     SetVersion($DBversion);
6885 }
6886
6887 $DBversion = "3.12.00.000";
6888 if ( CheckVersion($DBversion) ) {
6889     print "Upgrade to $DBversion done (3.12.0 release)\n";
6890     SetVersion ($DBversion);
6891 }
6892
6893 $DBversion = '3.13.00.000';
6894 if ( CheckVersion($DBversion) ) {
6895     print "Upgrade to $DBversion done (start the journey to Koha Pi)\n";
6896     SetVersion ($DBversion);
6897 }
6898
6899 $DBversion = "3.13.00.001";
6900 if ( CheckVersion($DBversion) ) {
6901     $dbh->do("INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('UseCourseReserves', '0', NULL, 'Enable the course reserves feature.', 'YesNo')");
6902     $dbh->do("INSERT INTO userflags (bit,flag,flagdesc,defaulton) VALUES ('18','coursereserves','Course Reserves','0')");
6903     $dbh->do("
6904 CREATE TABLE `courses` (
6905   `course_id` int(11) NOT NULL AUTO_INCREMENT,
6906   `department` varchar(20) DEFAULT NULL,
6907   `course_number` varchar(255) DEFAULT NULL,
6908   `section` varchar(255) DEFAULT NULL,
6909   `course_name` varchar(255) DEFAULT NULL,
6910   `term` varchar(20) DEFAULT NULL,
6911   `staff_note` mediumtext,
6912   `public_note` mediumtext,
6913   `students_count` varchar(20) DEFAULT NULL,
6914   `enabled` enum('yes','no') NOT NULL DEFAULT 'yes',
6915   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6916    PRIMARY KEY (`course_id`)
6917 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6918     ");
6919
6920     $dbh->do("
6921 CREATE TABLE `course_instructors` (
6922   `course_id` int(11) NOT NULL,
6923   `borrowernumber` int(11) NOT NULL,
6924   PRIMARY KEY (`course_id`,`borrowernumber`),
6925   KEY `borrowernumber` (`borrowernumber`)
6926 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6927     ");
6928
6929     $dbh->do("
6930 ALTER TABLE `course_instructors`
6931   ADD CONSTRAINT `course_instructors_ibfk_2` FOREIGN KEY (`course_id`) REFERENCES `courses` (`course_id`),
6932   ADD CONSTRAINT `course_instructors_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE;
6933     ");
6934
6935     $dbh->do("
6936 CREATE TABLE `course_items` (
6937   `ci_id` int(11) NOT NULL AUTO_INCREMENT,
6938   `itemnumber` int(11) NOT NULL,
6939   `itype` varchar(10) DEFAULT NULL,
6940   `ccode` varchar(10) DEFAULT NULL,
6941   `holdingbranch` varchar(10) DEFAULT NULL,
6942   `location` varchar(80) DEFAULT NULL,
6943   `enabled` enum('yes','no') NOT NULL DEFAULT 'no',
6944   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6945    PRIMARY KEY (`ci_id`),
6946    UNIQUE KEY `itemnumber` (`itemnumber`),
6947    KEY `holdingbranch` (`holdingbranch`)
6948 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6949     ");
6950
6951     $dbh->do("
6952 ALTER TABLE `course_items`
6953   ADD CONSTRAINT `course_items_ibfk_2` FOREIGN KEY (`holdingbranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
6954   ADD CONSTRAINT `course_items_ibfk_1` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE;
6955 ");
6956
6957     $dbh->do("
6958 CREATE TABLE `course_reserves` (
6959   `cr_id` int(11) NOT NULL AUTO_INCREMENT,
6960   `course_id` int(11) NOT NULL,
6961   `ci_id` int(11) NOT NULL,
6962   `staff_note` mediumtext,
6963   `public_note` mediumtext,
6964   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6965    PRIMARY KEY (`cr_id`),
6966    UNIQUE KEY `pseudo_key` (`course_id`,`ci_id`),
6967    KEY `course_id` (`course_id`)
6968 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6969 ");
6970
6971     $dbh->do("
6972 ALTER TABLE `course_reserves`
6973   ADD CONSTRAINT `course_reserves_ibfk_1` FOREIGN KEY (`course_id`) REFERENCES `courses` (`course_id`);
6974     ");
6975
6976     $dbh->do("
6977 INSERT INTO permissions (module_bit, code, description) VALUES
6978   (18, 'manage_courses', 'Add, edit and delete courses'),
6979   (18, 'add_reserves', 'Add course reserves'),
6980   (18, 'delete_reserves', 'Remove course reserves')
6981 ;
6982     ");
6983
6984
6985     print "Upgrade to $DBversion done (Add Course Reserves ( system preference UseCourseReserves ))\n";
6986     SetVersion($DBversion);
6987 }
6988
6989 $DBversion = "3.13.00.002";
6990 if ( CheckVersion($DBversion) ) {
6991    $dbh->do("UPDATE systempreferences SET variable = 'IndependentBranches' WHERE variable = 'IndependantBranches'");
6992    print "Upgrade to $DBversion done (Bug 10080 - Change system pref IndependantBranches to IndependentBranches)\n";
6993    SetVersion ($DBversion);
6994 }
6995
6996 $DBversion = '3.13.00.003';
6997 if ( CheckVersion($DBversion) ) {
6998     $dbh->do("ALTER TABLE serial DROP itemnumber");
6999     print "Upgrade to $DBversion done (Bug 7718 - Remove itemnumber column from serials table)\n";
7000     SetVersion($DBversion);
7001 }
7002
7003 $DBversion = "3.13.00.004";
7004 if(CheckVersion($DBversion)) {
7005     $dbh->do(
7006 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacShowHoldNotes',0,'Show hold notes on OPAC','','YesNo')"
7007     );
7008     print "Upgrade to $DBversion done (Bug 9722: Allow users to add notes when placing a hold in OPAC)\n";
7009     SetVersion($DBversion);
7010 }
7011
7012 $DBversion = "3.13.00.005";
7013 if(CheckVersion($DBversion)) {
7014     my $intra= C4::Context->preference("intranetstylesheet");
7015     #if this pref is not blank or starting with http, https or / [root], then
7016     #add an additional / to the front
7017     if($intra && $intra !~ /^(\/|https?)/) {
7018         $dbh->do("UPDATE systempreferences SET value=? WHERE variable=?",
7019             undef,('/'.$intra,"intranetstylesheet"));
7020         print "WARNING: Your system preference intranetstylesheet has been prefixed with a slash to make it an absolute path.\n";
7021     }
7022     print "Upgrade to $DBversion done (Bug 10052: Make intranetstylesheet and intranetcolorstylesheet behave exactly like their opac counterparts)\n";
7023     SetVersion ($DBversion);
7024 }
7025
7026 $DBversion = "3.13.00.006";
7027 if ( CheckVersion($DBversion) ) {
7028     $dbh->do(q{
7029         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
7030         VALUES ('CalculateFinesOnReturn','1','Switch to control if overdue fines are calculated on return or not', '', 'YesNo')
7031     });
7032     print "Upgrade to $DBversion done (Bug 10120: Fines on item return controlled by a systempreference)\n";
7033     SetVersion($DBversion);
7034 }
7035
7036 $DBversion = "3.13.00.007";
7037 if ( CheckVersion($DBversion) ) {
7038     $dbh->do("UPDATE systempreferences SET variable='OpacHoldNotes' WHERE variable='OpacShowHoldNotes'");
7039     print "Upgrade to $DBversion done (Bug 10343: Rename OpacShowHoldNotes to OpacHoldNotes)\n";
7040     SetVersion($DBversion);
7041 }
7042
7043 $DBversion = "3.13.00.008";
7044 if ( CheckVersion($DBversion) ) {
7045     $dbh->do("
7046 CREATE TABLE IF NOT EXISTS borrower_files (
7047   file_id int(11) NOT NULL AUTO_INCREMENT,
7048   borrowernumber int(11) NOT NULL,
7049   file_name varchar(255) NOT NULL,
7050   file_type varchar(255) NOT NULL,
7051   file_description varchar(255) DEFAULT NULL,
7052   file_content longblob NOT NULL,
7053   date_uploaded timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
7054   PRIMARY KEY (file_id),
7055   KEY borrowernumber (borrowernumber),
7056   CONSTRAINT borrower_files_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
7057 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7058     ");
7059     print "Upgrade to $DBversion done (Bug 10443: make sure borrower_files table exists)\n";
7060     SetVersion($DBversion);
7061 }
7062
7063 $DBversion = "3.13.00.009";
7064 if ( CheckVersion($DBversion) ) {
7065     $dbh->do("ALTER TABLE aqorders DROP COLUMN biblioitemnumber");
7066     print "Upgrade to $DBversion done (Bug 9987 - Drop column aqorders.biblioitemnumber)\n";
7067     SetVersion($DBversion);
7068 }
7069
7070 $DBversion = "3.13.00.010";
7071 if ( CheckVersion($DBversion) ) {
7072     $dbh->do(
7073         q{
7074 INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AcqWarnOnDuplicateInvoice','0','Warn librarians when they try to create a duplicate invoice', '', 'YesNo');
7075 }
7076     );
7077     print
7078 "Upgrade to $DBversion done (Bug 10366 - Add system preference to enabling warning librarian when invoice is duplicated)\n";
7079     SetVersion($DBversion);
7080 }
7081
7082 $DBversion = "3.13.00.011";
7083 if ( CheckVersion($DBversion) ) {
7084     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='ita' WHERE rfc4646_subtag='it'");
7085     print "Upgrade to $DBversion done (Bug 9519: Wrong language code for Italian in the advanced search language limitations)\n";
7086     SetVersion($DBversion);
7087 }
7088
7089 $DBversion = "3.13.00.012";
7090 if ( CheckVersion($DBversion) ) {
7091     $dbh->do("ALTER TABLE issuingrules MODIFY COLUMN overduefinescap decimal(28,6) DEFAULT NULL;");
7092     print "Upgrade to $DBversion done (Bug 10490: Correct datatype for overduefinescap in issuingrules)\n";
7093     SetVersion($DBversion);
7094 }
7095
7096 $DBversion ="3.13.00.013";
7097 if ( CheckVersion($DBversion) ) {
7098     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('AllowTooManyOverride', '1', 'If on, allow staff to override and check out items when the patron has reached the maximum number of allowed checkouts', '', 'YesNo');");
7099     print "Upgrade to $DBversion done (Bug 9576: add AllowTooManyOverride syspref to enable or disable issue limit confirmation)\n";
7100     SetVersion($DBversion);
7101 }
7102
7103 $DBversion = "3.13.00.014";
7104 if ( CheckVersion($DBversion) ) {
7105     $dbh->do("ALTER TABLE courses MODIFY COLUMN department varchar(80) DEFAULT NULL;");
7106     $dbh->do("ALTER TABLE courses MODIFY COLUMN term       varchar(80) DEFAULT NULL;");
7107     print "Upgrade to $DBversion done (Bug 10604: correct width of courses.department and courses.term)\n";
7108     SetVersion($DBversion);
7109 }
7110
7111 $DBversion = "3.13.00.015";
7112 if ( CheckVersion($DBversion) ) {
7113     $dbh->do(
7114 "INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('itemBarcodeFallbackSearch','','If set, enables the automatic use of a keyword catalog search if the phrase entered as a barcode on the checkout page does not turn up any results during an item barcode search',NULL,'YesNo')"
7115     );
7116     print "Upgrade to $DBversion done (Bug 7494: Add itemBarcodeFallbackSearch syspref)\n";
7117     SetVersion($DBversion);
7118 }
7119
7120 $DBversion = "3.13.00.016";
7121 if ( CheckVersion($DBversion) ) {
7122     $dbh->do(q{
7123         ALTER TABLE items CHANGE wthdrawn withdrawn TINYINT( 1 ) NOT NULL DEFAULT  '0'
7124     });
7125
7126     $dbh->do(q{
7127         ALTER TABLE deleteditems CHANGE wthdrawn withdrawn TINYINT( 1 ) NOT NULL DEFAULT  '0'
7128     });
7129
7130     $dbh->do(q{
7131         UPDATE saved_sql SET savedsql = REPLACE(savedsql, 'wthdrawn', 'withdrawn')
7132     });
7133
7134     $dbh->do(q{
7135         UPDATE marc_subfield_structure SET kohafield = 'items.withdrawn' WHERE kohafield = 'items.wthdrawn'
7136     });
7137
7138     print "Upgrade to $DBversion done (Bug 10550 - Fix database typo wthdrawn)\n";
7139     SetVersion($DBversion);
7140 }
7141
7142 $DBversion = "3.13.00.017";
7143 if ( CheckVersion($DBversion) ) {
7144     $dbh->do(
7145 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveClientKey','','Client key for OverDrive integration','30','Free')"
7146     );
7147     $dbh->do(
7148 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveClientSecret','','Client key for OverDrive integration','30','YesNo')"
7149     );
7150     $dbh->do(
7151 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveLibraryID','','Library ID for OverDrive integration','','Integer')"
7152     );
7153     print "Upgrade to $DBversion done (Bug 10320 - Show results from library's OverDrive collection in OPAC search)\n";
7154     SetVersion($DBversion);
7155 }
7156
7157 $DBversion = "3.13.00.018";
7158 if ( CheckVersion($DBversion) ) {
7159     $dbh->do(qq{DROP TABLE IF EXISTS aqorders_transfers;});
7160     $dbh->do(qq{
7161         CREATE TABLE aqorders_transfers (
7162           ordernumber_from int(11) NULL,
7163           ordernumber_to int(11) NULL,
7164           timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
7165           UNIQUE KEY ordernumber_from (ordernumber_from),
7166           UNIQUE KEY ordernumber_to (ordernumber_to),
7167           CONSTRAINT aqorders_transfers_ordernumber_from FOREIGN KEY (ordernumber_from) REFERENCES aqorders (ordernumber) ON DELETE SET NULL ON UPDATE CASCADE,
7168           CONSTRAINT aqorders_transfers_ordernumber_to FOREIGN KEY (ordernumber_to) REFERENCES aqorders (ordernumber) ON DELETE SET NULL ON UPDATE CASCADE
7169         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7170     });
7171     print "Upgrade to $DBversion done (Bug 5349: Add aqorders_transfers table)\n";
7172     SetVersion($DBversion);
7173 }
7174
7175 $DBversion = "3.13.00.019";
7176 if ( CheckVersion($DBversion) ) {
7177     $dbh->do("ALTER TABLE itemtypes ADD COLUMN checkinmsg VARCHAR(255) AFTER summary;");
7178     $dbh->do("ALTER TABLE itemtypes ADD COLUMN checkinmsgtype CHAR(16) DEFAULT 'message' NOT NULL AFTER checkinmsg;");
7179     print "Upgrade to $DBversion done (Bug 10513 - Light up a warning/message when returning a chosen item type)\n";
7180     SetVersion($DBversion);
7181 }
7182
7183 $DBversion = "3.13.00.020";
7184 if ( CheckVersion($DBversion) ) {
7185     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('WhenLostForgiveFine','0',NULL,'If ON, Forgives the fines on an item when it is lost.','YesNo')");
7186     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('WhenLostChargeReplacementFee','1',NULL,'If ON, Charge the replacement price when a patron loses an item.','YesNo')");
7187     print "Upgrade to $DBversion done (Bug 7639: system preferences to forgive fines on lost items)\n";
7188     SetVersion($DBversion);
7189 }
7190
7191 $DBversion ="3.13.00.021";
7192 if ( CheckVersion($DBversion) ) {
7193     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ConfirmFutureHolds','0','Number of days for confirming future holds','','Integer');");
7194     print "Upgrade to $DBversion done (Bug 9761: Add ConfirmFutureHolds pref)\n";
7195     SetVersion($DBversion);
7196 }
7197
7198 $DBversion = "3.13.00.022";
7199 if ( CheckVersion($DBversion) ) {
7200     $dbh->do("DELETE from auth_tag_structure WHERE tagfield IN ('68a','68b')");
7201     $dbh->do("DELETE from auth_subfield_structure WHERE tagfield IN ('68a','68b')");
7202     print "Upgrade to $DBversion done (Bug 10687 - Delete erroneous tags 68a and 68b on default MARC21 auth framework)\n";
7203     SetVersion($DBversion);
7204 }
7205
7206 $DBversion = "3.13.00.023";
7207 if ( CheckVersion($DBversion) ) {
7208     $dbh->do("ALTER TABLE borrowers CHANGE password password VARCHAR(60);");
7209     print "Upgrade to $DBversion done (Bug 9611 upgrading password storage system)\n";
7210     SetVersion($DBversion);
7211 }
7212
7213 $DBversion = "3.13.00.024";
7214 if ( CheckVersion($DBversion) ) {
7215     $dbh->do(q{ALTER TABLE z3950servers ADD COLUMN recordtype VARCHAR(45) NOT NULL DEFAULT 'biblio' AFTER description;});
7216     print "Upgrade to $DBversion done (Bug 10096 - Add a Z39.50 interface for authority searching)\n";
7217 }
7218
7219 $DBversion = "3.13.00.025";
7220 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
7221    $dbh->do("ALTER TABLE oai_sets_mappings ADD COLUMN operator varchar(8) NOT NULL default 'equal' AFTER marcsubfield;");
7222    print "Upgrade to $DBversion done (Bug 9295: OAI notequal: add operator column to OAI mappings table)\n";
7223    SetVersion ($DBversion);
7224 }
7225
7226 $DBversion = "3.13.00.026";
7227 if ( CheckVersion($DBversion) ) {
7228     $dbh->do(q|
7229         ALTER TABLE auth_subfield_structure ADD COLUMN defaultvalue TEXT DEFAULT NULL AFTER frameworkcode
7230     |);
7231     print "Upgrade to $DBversion done (Bug 10602: Add the column auth_subfield_structure.defaultvalue)\n";
7232     SetVersion($DBversion);
7233 }
7234
7235 $DBversion = "3.13.00.027";
7236 if ( CheckVersion($DBversion) ) {
7237     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('AllowOfflineCirculation','0','','If on, enables HTML5 offline circulation functionality.','YesNo')");
7238     print "Upgrade to $DBversion done (Bug 10240: Add syspref AllowOfflineCirculation)\n";
7239     SetVersion ($DBversion);
7240 }
7241
7242 $DBversion = "3.13.00.028";
7243 if ( CheckVersion($DBversion) ) {
7244     $dbh->do(q{
7245         ALTER TABLE export_format ADD type VARCHAR(255) DEFAULT 'marc' AFTER encoding
7246     });
7247     $dbh->do(q{
7248         ALTER TABLE export_format CHANGE marcfields content mediumtext NOT NULL
7249     });
7250     print "Upgrade to $DBversion done (Bug 10853: Add new field export_format.type and rename export_format.marcfields with export_format.content)\n";
7251     SetVersion($DBversion);
7252 }
7253
7254 $DBversion = "3.13.00.029";
7255 if ( CheckVersion($DBversion) ) {
7256     $dbh->do(q{
7257         INSERT IGNORE INTO export_format( profile, description, content, csv_separator, type )
7258         VALUES ( "issues to claim", "Default CSV export for serial issue claims",
7259                 "SUPPLIER=aqbooksellers.name|TITLE=subscription.title|ISSUE NUMBER=serial.serialseq|LATE SINCE=serial.planneddate",
7260                 ",", "sql" )
7261     });
7262     print "Upgrade to $DBversion done (Bug 10854: Add the default CSV profile for claiming issues)\n";
7263     SetVersion($DBversion);
7264 }
7265
7266 $DBversion = "3.13.00.030";
7267 if ( CheckVersion($DBversion) ) {
7268     $dbh->do(qq{
7269         DELETE FROM patronimage WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowers.cardnumber = patronimage.cardnumber)
7270     });
7271
7272     $dbh->do(qq{
7273         ALTER TABLE patronimage ADD borrowernumber INT( 11 ) NULL FIRST
7274     });
7275
7276     $dbh->{AutoCommit} = 0;
7277     $dbh->{RaiseError} = 1;
7278
7279     eval {
7280         $dbh->do(qq{
7281             UPDATE patronimage LEFT JOIN borrowers USING ( cardnumber ) SET patronimage.borrowernumber = borrowers.borrowernumber
7282         });
7283         $dbh->commit();
7284     };
7285
7286     if ($@) {
7287         print "Upgrade to $DBversion done (Bug 10636 - patronimage should have borrowernumber as PK, not cardnumber) failed! Transaction aborted because $@\n";
7288         eval { $dbh->rollback };
7289     }
7290     else {
7291         $dbh->do(qq{
7292             ALTER TABLE patronimage DROP FOREIGN KEY patronimage_fk1
7293         });
7294         $dbh->do(qq{
7295             ALTER TABLE patronimage DROP PRIMARY KEY, ADD PRIMARY KEY( borrowernumber )
7296         });
7297         $dbh->do(qq{
7298             ALTER TABLE patronimage DROP cardnumber
7299         });
7300         $dbh->do(qq{
7301             ALTER TABLE patronimage ADD FOREIGN KEY ( borrowernumber ) REFERENCES borrowers ( borrowernumber ) ON DELETE CASCADE ON UPDATE CASCADE
7302         });
7303
7304         print "Upgrade to $DBversion done (Bug 10636 - patronimage should have borrowernumber as PK, not cardnumber)\n";
7305         SetVersion($DBversion);
7306     }
7307
7308     $dbh->{AutoCommit} = 1;
7309     $dbh->{RaiseError} = 0;
7310 }
7311
7312 $DBversion = "3.13.00.031";
7313 if ( CheckVersion($DBversion) ) {
7314
7315     $dbh->do(q{
7316         CREATE TABLE IF NOT EXISTS `patron_lists` (
7317           patron_list_id int(11) NOT NULL AUTO_INCREMENT,
7318           name varchar(255) CHARACTER SET utf8 NOT NULL,
7319           owner int(11) NOT NULL,
7320           PRIMARY KEY (patron_list_id),
7321           KEY owner (owner)
7322         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7323     });
7324
7325     $dbh->do(q{
7326         ALTER TABLE `patron_lists`
7327           ADD CONSTRAINT patron_lists_ibfk_1 FOREIGN KEY (`owner`) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE;
7328     });
7329
7330     $dbh->do(q{
7331         CREATE TABLE patron_list_patrons (
7332           patron_list_patron_id int(11) NOT NULL AUTO_INCREMENT,
7333           patron_list_id int(11) NOT NULL,
7334           borrowernumber int(11) NOT NULL,
7335           PRIMARY KEY (patron_list_patron_id),
7336           KEY patron_list_id (patron_list_id),
7337           KEY borrowernumber (borrowernumber)
7338         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7339     });
7340
7341     $dbh->do(q{
7342         ALTER TABLE `patron_list_patrons`
7343           ADD CONSTRAINT patron_list_patrons_ibfk_1 FOREIGN KEY (patron_list_id) REFERENCES patron_lists (patron_list_id) ON DELETE CASCADE ON UPDATE CASCADE,
7344           ADD CONSTRAINT patron_list_patrons_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE;
7345     });
7346
7347     $dbh->do(q{
7348         INSERT INTO permissions (module_bit, code, description) VALUES
7349         (13, 'manage_patron_lists', 'Add, edit and delete patron lists and their contents')
7350     });
7351
7352     print "Upgrade to $DBversion done (Bug 10565 - Add a 'Patron List' feature for storing and manipulating collections of patrons)\n";
7353     SetVersion($DBversion);
7354 }
7355
7356 $DBversion = "3.13.00.032";
7357 if ( CheckVersion($DBversion) ) {
7358     $dbh->do("ALTER TABLE aqorders ADD COLUMN orderstatus varchar(16) DEFAULT 'new' AFTER parent_ordernumber");
7359     $dbh->do("UPDATE aqorders SET orderstatus='ordered' WHERE basketno IN (SELECT basketno FROM aqbasket WHERE closedate IS NOT NULL)");
7360     $dbh->do(q{
7361         UPDATE aqorders SET orderstatus='partial'
7362         WHERE quantity > quantityreceived
7363         AND quantityreceived > 0
7364         AND ordernumber IN (
7365             SELECT parent_ordernumber
7366             FROM (
7367                 SELECT DISTINCT(parent_ordernumber)
7368                 FROM aqorders
7369                 WHERE ordernumber != parent_ordernumber
7370             ) AS aq
7371         )
7372         AND basketno IN (SELECT basketno FROM aqbasket WHERE closedate IS NOT NULL)
7373     });
7374     $dbh->do("UPDATE aqorders SET orderstatus='complete' WHERE quantity=quantityreceived");
7375     $dbh->do("UPDATE aqorders SET orderstatus='cancelled' WHERE datecancellationprinted IS NOT NULL");
7376     print "Upgrade to $DBversion done (Bug 5336: Add the new column aqorders.orderstatus)\n";
7377     SetVersion($DBversion);
7378 }
7379
7380 $DBversion = "3.13.00.033";
7381 if ( CheckVersion($DBversion) ) {
7382     $dbh->do(qq|
7383         DROP TABLE IF EXISTS subscription_frequencies
7384     |);
7385     $dbh->do(qq|
7386         CREATE TABLE subscription_frequencies (
7387             id INTEGER NOT NULL AUTO_INCREMENT,
7388             description TEXT NOT NULL,
7389             displayorder INT DEFAULT NULL,
7390             unit ENUM('day','week','month','year') DEFAULT NULL,
7391             unitsperissue INTEGER NOT NULL DEFAULT '1',
7392             issuesperunit INTEGER NOT NULL DEFAULT '1',
7393             PRIMARY KEY (id)
7394         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
7395     |);
7396
7397     $dbh->do(qq|
7398         DROP TABLE IF EXISTS subscription_numberpatterns
7399     |);
7400     $dbh->do(qq|
7401         CREATE TABLE subscription_numberpatterns (
7402             id INTEGER NOT NULL AUTO_INCREMENT,
7403             label VARCHAR(255) NOT NULL,
7404             displayorder INTEGER DEFAULT NULL,
7405             description TEXT NOT NULL,
7406             numberingmethod VARCHAR(255) NOT NULL,
7407             label1 VARCHAR(255) DEFAULT NULL,
7408             add1 INTEGER DEFAULT NULL,
7409             every1 INTEGER DEFAULT NULL,
7410             whenmorethan1 INTEGER DEFAULT NULL,
7411             setto1 INTEGER DEFAULT NULL,
7412             numbering1 VARCHAR(255) DEFAULT NULL,
7413             label2 VARCHAR(255) DEFAULT NULL,
7414             add2 INTEGER DEFAULT NULL,
7415             every2 INTEGER DEFAULT NULL,
7416             whenmorethan2 INTEGER DEFAULT NULL,
7417             setto2 INTEGER DEFAULT NULL,
7418             numbering2 VARCHAR(255) DEFAULT NULL,
7419             label3 VARCHAR(255) DEFAULT NULL,
7420             add3 INTEGER DEFAULT NULL,
7421             every3 INTEGER DEFAULT NULL,
7422             whenmorethan3 INTEGER DEFAULT NULL,
7423             setto3 INTEGER DEFAULT NULL,
7424             numbering3 VARCHAR(255) DEFAULT NULL,
7425             PRIMARY KEY (id)
7426         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
7427     |);
7428
7429     $dbh->do(qq|
7430         INSERT INTO subscription_frequencies (description, unit, unitsperissue, issuesperunit, displayorder)
7431         VALUES
7432             ('2/day', 'day', 1, 2, 1),
7433             ('1/day', 'day', 1, 1, 2),
7434             ('3/week', 'week', 1, 3, 3),
7435             ('1/week', 'week', 1, 1, 4),
7436             ('1/2 weeks', 'week', 2, 1, 5),
7437             ('1/3 weeks', 'week', 3, 1, 6),
7438             ('1/month', 'month', 1, 1, 7),
7439             ('1/2 months', 'month', 2, 1, 8),
7440             ('1/3 months', 'month', 3, 1, 9),
7441             ('2/year', 'month', 6, 1, 10),
7442             ('1/year', 'year', 1, 1, 11),
7443             ('1/2 year', 'year', 2, 1, 12),
7444             ('Irregular', NULL, 1, 1, 13)
7445     |);
7446
7447     # Used to link existing subscription to newly created frequencies
7448     my $frequencies_mapping = {     # keys are old frequency numbers, values are the new ones
7449         1 => 2,     # daily (n/week)
7450         2 => 4,     # 1/week
7451         3 => 5,     # 1/2 weeks
7452         4 => 6,     # 1/3 weeks
7453         5 => 7,     # 1/month
7454         6 => 8,     # 1/2 months (6/year)
7455         7 => 9,     # 1/3 months (1/quarter)
7456         8 => 9,    # 1/quarter (seasonal)
7457         9 => 10,    # 2/year
7458         10 => 11,   # 1/year
7459         11 => 12,   # 1/2 years
7460         12 => 1,    # 2/day
7461         16 => 13,   # Without periodicity
7462         32 => 13,   # Irregular
7463         48 => 13    # Unknown
7464     };
7465
7466     $dbh->do(qq|
7467         INSERT INTO subscription_numberpatterns
7468             (label, displayorder, description, numberingmethod,
7469             label1, add1, every1, whenmorethan1, setto1, numbering1,
7470             label2, add2, every2, whenmorethan2, setto2, numbering2,
7471             label3, add3, every3, whenmorethan3, setto3, numbering3)
7472         VALUES
7473             ('Number', 1, 'Simple Numbering method', 'No.{X}',
7474             'Number', 1, 1, 99999, 1, NULL,
7475             NULL, NULL, NULL, NULL, NULL, NULL,
7476             NULL, NULL, NULL, NULL, NULL, NULL),
7477
7478             ('Volume, Number, Issue', 2, 'Volume Number Issue 1', 'Vol.{X}, Number {Y}, Issue {Z}',
7479             'Volume', 1, 48, 99999, 1, NULL,
7480             'Number', 1, 4, 12, 1, NULL,
7481             'Issue', 1, 1, 4, 1, NULL),
7482
7483             ('Volume, Number', 3, 'Volume Number 1', 'Vol {X}, No {Y}',
7484             'Volume', 1, 12, 99999, 1, NULL,
7485             'Number', 1, 1, 12, 1, NULL,
7486             NULL, NULL, NULL, NULL, NULL, NULL),
7487
7488             ('Seasonal', 4, 'Season Year', '{X} {Y}',
7489             'Season', 1, 1, 3, 0, 'season',
7490             'Year', 1, 4, 99999, 1, NULL,
7491             NULL, NULL, NULL, NULL, NULL, NULL)
7492     |);
7493
7494     $dbh->do(qq|
7495         ALTER TABLE subscription
7496         MODIFY COLUMN numberpattern INTEGER DEFAULT NULL,
7497         MODIFY COLUMN periodicity INTEGER DEFAULT NULL
7498     |);
7499
7500     # Update existing subscriptions
7501
7502     my $query = qq|
7503         SELECT subscriptionid, periodicity, numberingmethod,
7504             add1, every1, whenmorethan1, setto1,
7505             add2, every2, whenmorethan2, setto2,
7506             add3, every3, whenmorethan3, setto3
7507         FROM subscription
7508         ORDER BY subscriptionid
7509     |;
7510     my $sth = $dbh->prepare($query);
7511     $sth->execute;
7512     my $insert_numberpatterns_sth = $dbh->prepare(qq|
7513         INSERT INTO subscription_numberpatterns
7514              (label, displayorder, description, numberingmethod,
7515             label1, add1, every1, whenmorethan1, setto1, numbering1,
7516             label2, add2, every2, whenmorethan2, setto2, numbering2,
7517             label3, add3, every3, whenmorethan3, setto3, numbering3)
7518         VALUES
7519             (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
7520     |);
7521     my $check_numberpatterns_sth = $dbh->prepare(qq|
7522         SELECT * FROM subscription_numberpatterns
7523         WHERE (add1 = ? OR (add1 IS NULL AND ? IS NULL)) AND (add2 = ? OR (add2 IS NULL AND ? IS NULL))
7524         AND (add3 = ? OR (add3 IS NULL AND ? IS NULL)) AND (every1 = ? OR (every1 IS NULL AND ? IS NULL))
7525         AND (every2 = ? OR (every2 IS NULL AND ? IS NULL)) AND (every3 = ? OR (every3 IS NULL AND ? IS NULL))
7526         AND (whenmorethan1 = ? OR (whenmorethan1 IS NULL AND ? IS NULL)) AND (whenmorethan2 = ? OR (whenmorethan2 IS NULL AND ? IS NULL))
7527         AND (whenmorethan3 = ? OR (whenmorethan3 IS NULL AND ? IS NULL)) AND (setto1 = ? OR (setto1 IS NULL AND ? IS NULL))
7528         AND (setto2 = ? OR (setto2 IS NULL AND ? IS NULL)) AND (setto3 = ? OR (setto3 IS NULL AND ? IS NULL))
7529         AND (numberingmethod = ? OR (numberingmethod IS NULL AND ? IS NULL))
7530         LIMIT 1
7531     |);
7532     my $update_subscription_sth = $dbh->prepare(qq|
7533         UPDATE subscription
7534         SET numberpattern = ?,
7535             periodicity = ?
7536         WHERE subscriptionid = ?
7537     |);
7538
7539     my $i = 1;
7540     while(my $sub = $sth->fetchrow_hashref) {
7541         $check_numberpatterns_sth->execute(
7542             $sub->{add1}, $sub->{add1}, $sub->{add2}, $sub->{add2}, $sub->{add3}, $sub->{add3},
7543             $sub->{every1}, $sub->{every1}, $sub->{every2}, $sub->{every2}, $sub->{every3}, $sub->{every3},
7544             $sub->{whenmorethan1}, $sub->{whenmorethan1}, $sub->{whenmorethan2}, $sub->{whenmorethan2},
7545             $sub->{whenmorethan3}, $sub->{whenmorethan3}, $sub->{setto1}, $sub->{setto1}, $sub->{setto2},
7546             $sub->{setto2}, $sub->{setto3}, $sub->{setto3}, $sub->{numberingmethod}, $sub->{numberingmethod}
7547         );
7548         my $p = $check_numberpatterns_sth->fetchrow_hashref;
7549         if (defined $p) {
7550             # Pattern already exists, link to it
7551             $update_subscription_sth->execute($p->{id},
7552                 $frequencies_mapping->{$sub->{periodicity}},
7553                 $sub->{subscriptionid});
7554         } else {
7555             # Create a new numbering pattern for this subscription
7556             my $ok = $insert_numberpatterns_sth->execute(
7557                 "Backup pattern $i", 4+$i, "Automatically created pattern by updatedatabase", $sub->{numberingmethod},
7558                 "X", $sub->{add1}, $sub->{every1}, $sub->{whenmorethan1}, $sub->{setto1}, undef,
7559                 "Y", $sub->{add2}, $sub->{every2}, $sub->{whenmorethan2}, $sub->{setto2}, undef,
7560                 "Z", $sub->{add3}, $sub->{every3}, $sub->{whenmorethan3}, $sub->{setto3}, undef
7561             );
7562             if($ok) {
7563                 my $id = $dbh->last_insert_id(undef, undef, 'subscription_numberpatterns', undef);
7564                 # Link to subscription_numberpatterns and subscription_frequencies
7565                 $update_subscription_sth->execute($id,
7566                     $frequencies_mapping->{$sub->{periodicity}},
7567                     $sub->{subscriptionid});
7568             }
7569             $i++;
7570         }
7571     }
7572
7573     # Remove now useless columns
7574     $dbh->do(qq|
7575         ALTER TABLE subscription
7576         DROP COLUMN numberingmethod,
7577         DROP COLUMN add1,
7578         DROP COLUMN every1,
7579         DROP COLUMN whenmorethan1,
7580         DROP COLUMN setto1,
7581         DROP COLUMN add2,
7582         DROP COLUMN every2,
7583         DROP COLUMN whenmorethan2,
7584         DROP COLUMN setto2,
7585         DROP COLUMN add3,
7586         DROP COLUMN every3,
7587         DROP COLUMN whenmorethan3,
7588         DROP COLUMN setto3,
7589         DROP COLUMN dow,
7590         DROP COLUMN issuesatonce,
7591         DROP COLUMN hemisphere,
7592         ADD COLUMN countissuesperunit INTEGER NOT NULL DEFAULT 1 AFTER periodicity,
7593         ADD COLUMN skip_serialseq BOOLEAN NOT NULL DEFAULT 0 AFTER irregularity,
7594         ADD COLUMN locale VARCHAR(80) DEFAULT NULL AFTER numberpattern,
7595         ADD CONSTRAINT subscription_ibfk_1 FOREIGN KEY (periodicity) REFERENCES subscription_frequencies (id) ON DELETE SET NULL ON UPDATE CASCADE,
7596         ADD CONSTRAINT subscription_ibfk_2 FOREIGN KEY (numberpattern) REFERENCES subscription_numberpatterns (id) ON DELETE SET NULL ON UPDATE CASCADE
7597     |);
7598
7599     # Set firstacquidate if not already set (firstacquidate is now mandatory)
7600     my $get_first_planneddate_sth = $dbh->prepare(qq|
7601         SELECT planneddate
7602         FROM serial
7603         WHERE subscriptionid = ?
7604         ORDER BY serialid
7605         LIMIT 1
7606     |);
7607     my $update_firstacquidate_sth = $dbh->prepare(qq|
7608         UPDATE subscription
7609         SET firstacquidate = ?
7610         WHERE subscriptionid = ?
7611     |);
7612     my $get_subscriptions_sth = $dbh->prepare(qq|
7613         SELECT subscriptionid, startdate
7614         FROM subscription
7615         WHERE firstacquidate IS NULL
7616           OR firstacquidate = '0000-00-00'
7617     |);
7618     $get_subscriptions_sth->execute;
7619     while ( my ($subscriptionid, $startdate) = $get_subscriptions_sth->fetchrow ) {
7620         # Try to get the planned date of the first serial
7621         $get_first_planneddate_sth->execute($subscriptionid);
7622         my ($first_planneddate) = $get_first_planneddate_sth->fetchrow;
7623         if ($first_planneddate and $first_planneddate =~ /^\d{4}-\d{2}-\d{2}$/) {
7624             $update_firstacquidate_sth->execute($first_planneddate, $subscriptionid);
7625         } else {
7626             # Defaults to subscription start date
7627             $update_firstacquidate_sth->execute($startdate, $subscriptionid);
7628         }
7629     }
7630
7631     print "Upgrade to $DBversion done (Bug 7688: add subscription_frequencies and subscription_numberpatterns tables)\n";
7632     SetVersion($DBversion);
7633 }
7634
7635 $DBversion = "3.13.00.034";
7636 if ( CheckVersion($DBversion) ) {
7637     $dbh->do("
7638         ALTER TABLE `import_batches`
7639         CHANGE `item_action` `item_action`
7640           ENUM( 'always_add', 'add_only_for_matches', 'add_only_for_new', 'ignore', 'replace' )
7641           NOT NULL DEFAULT 'always_add'
7642     ");
7643     print "Upgrade to $DBversion done (Bug 7131 - way to overlay items in in marc import)\n";
7644     SetVersion($DBversion);
7645 }
7646
7647 $DBversion ="3.13.00.035";
7648 if ( CheckVersion($DBversion) ) {
7649     $dbh->do(q{
7650 CREATE TABLE borrower_debarments (
7651   borrower_debarment_id int(11) NOT NULL AUTO_INCREMENT,
7652   borrowernumber int(11) NOT NULL,
7653   expiration date DEFAULT NULL,
7654   `type` enum('SUSPENSION','OVERDUES','MANUAL') NOT NULL DEFAULT 'MANUAL',
7655   `comment` text,
7656   manager_id int(11) DEFAULT NULL,
7657   created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
7658   updated timestamp NULL DEFAULT NULL,
7659   PRIMARY KEY (borrower_debarment_id),
7660   KEY borrowernumber (borrowernumber) ,
7661   CONSTRAINT `borrower_debarments_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
7662     ON DELETE CASCADE ON UPDATE CASCADE
7663 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7664     });
7665
7666     # debarments with end date
7667     $dbh->do(q{
7668 INSERT INTO borrower_debarments ( borrowernumber, expiration, comment ) SELECT borrowernumber, debarred, debarredcomment FROM borrowers WHERE debarred IS NOT NULL AND debarred <> '9999-12-31'
7669     });
7670     # debarments with no end date
7671     $dbh->do(q{
7672 INSERT INTO borrower_debarments ( borrowernumber, comment ) SELECT borrowernumber, debarredcomment FROM borrowers WHERE debarred = '9999-12-31'
7673     });
7674
7675     $dbh->do(q{
7676 INSERT IGNORE INTO systempreferences (variable,value,explanation,type) VALUES
7677 ('AutoRemoveOverduesRestrictions','0','Defines whether an OVERDUES debarment should be lifted automatically if all overdue items are returned by the patron.','YesNo')
7678     });
7679
7680     print "Upgrade to $DBversion done (Bug 2720 - Overdues which debar automatically should undebar automatically when returned)\n";
7681     SetVersion($DBversion);
7682 }
7683
7684 $DBversion = "3.13.00.036";
7685 if ( CheckVersion($DBversion) ) {
7686     $dbh->do(qq{
7687         INSERT INTO systempreferences (variable, value, explanation, options, type)
7688         VALUES ('StaffDetailItemSelection', '1', 'Enable item selection in record detail page', NULL, 'YesNo')
7689     });
7690     print "Upgrade to $DBversion done (Add system preference StaffDetailItemSelection)\n";
7691     SetVersion($DBversion);
7692 }
7693
7694 $DBversion = "3.13.00.037";
7695 if ( CheckVersion($DBversion) ) {
7696     #add phone if it is not there already (explains the ignore option)
7697     $dbh->do("
7698 INSERT IGNORE INTO message_transport_types (message_transport_type) values ('phone');
7699     ");
7700     print "Upgrade to $DBversion done (Bug 10572: Add phone to message_transport_types table for new installs)\n";
7701     SetVersion($DBversion);
7702 }
7703
7704 $DBversion = "3.13.00.038";
7705 if ( CheckVersion($DBversion) ) {
7706     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES(15, 'superserials', 'Manage subscriptions from any branch (only applies when IndependentBranches is used)')");
7707     print "Upgrade to $DBversion done (Bug 8435: Add superserials permission)\n";
7708     SetVersion($DBversion);
7709 }
7710
7711 $DBversion = "3.13.00.039";
7712 if ( CheckVersion($DBversion) ) {
7713     $dbh->do("
7714         ALTER TABLE aqbasket ADD branch varchar(10) default NULL
7715     ");
7716     $dbh->do("
7717         ALTER TABLE aqbasket
7718         ADD CONSTRAINT aqbasket_ibfk_4 FOREIGN KEY (branch)
7719             REFERENCES branches (branchcode)
7720             ON UPDATE CASCADE ON DELETE SET NULL
7721     ");
7722     $dbh->do("
7723         DROP TABLE IF EXISTS aqbasketusers
7724     ");
7725     $dbh->do("
7726         CREATE TABLE aqbasketusers (
7727             basketno int(11) NOT NULL,
7728             borrowernumber int(11) NOT NULL,
7729             PRIMARY KEY (basketno,borrowernumber),
7730             CONSTRAINT aqbasketusers_ibfk_1 FOREIGN KEY (basketno) REFERENCES aqbasket (basketno) ON DELETE CASCADE ON UPDATE CASCADE,
7731             CONSTRAINT aqbasketusers_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
7732         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7733     ");
7734     $dbh->do("
7735         INSERT INTO permissions (module_bit, code, description)
7736         VALUES (11, 'order_manage_all', 'Manage all orders and baskets, regardless of restrictions on them')
7737     ");
7738
7739     print "Upgrade to $DBversion done (Add branch and users list to baskets. "
7740         . "New permission order_manage_all)\n";
7741     SetVersion($DBversion);
7742 }
7743
7744 $DBversion = "3.13.00.040";
7745 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
7746     $dbh->do("CREATE TABLE IF NOT EXISTS marc_modification_templates (
7747               template_id int(11) NOT NULL auto_increment,
7748               name text NOT NULL,
7749               PRIMARY KEY  (template_id)
7750               ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;"
7751     );
7752
7753     $dbh->do("
7754       CREATE TABLE IF NOT EXISTS marc_modification_template_actions (
7755       mmta_id int(11) NOT NULL auto_increment,
7756       template_id int(11) NOT NULL,
7757       ordering int(3) NOT NULL,
7758       action enum('delete_field','update_field','move_field','copy_field') NOT NULL,
7759       field_number smallint(6) NOT NULL default '0',
7760       from_field varchar(3) NOT NULL,
7761       from_subfield varchar(1) NULL,
7762       field_value varchar(100) default NULL,
7763       to_field varchar(3) default NULL,
7764       to_subfield varchar(1) default NULL,
7765       to_regex_search text,
7766       to_regex_replace text,
7767       to_regex_modifiers varchar(8) default '',
7768       conditional enum('if','unless') default NULL,
7769       conditional_field varchar(3) default NULL,
7770       conditional_subfield varchar(1) default NULL,
7771       conditional_comparison enum('exists','not_exists','equals','not_equals') default NULL,
7772       conditional_value text,
7773       conditional_regex tinyint(1) NOT NULL default '0',
7774       description text,
7775       PRIMARY KEY  (mmta_id),
7776       CONSTRAINT `mmta_ibfk_1` FOREIGN KEY (`template_id`) REFERENCES `marc_modification_templates` (`template_id`) ON DELETE CASCADE ON UPDATE CASCADE
7777       ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7778     ");
7779
7780     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('13', 'marc_modification_templates', 'Manage marc modification templates')");
7781
7782     print "Upgrade to $DBversion done ( Bug 8015: Added tables for MARC Modification Framework )\n";
7783     SetVersion($DBversion);
7784 }
7785
7786 $DBversion = "3.13.00.041";
7787 if(CheckVersion($DBversion)) {
7788     $dbh->do(q{
7789         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');
7790     });
7791     print "Upgrade to $DBversion done (Bug 10986: Added AcqItemSetSubfieldsWhenReceived syspref)\n";
7792     SetVersion($DBversion);
7793 }
7794
7795 $DBversion = "3.13.00.042";
7796 if(CheckVersion($DBversion)) {
7797     print "Upgrade to $DBversion done (Koha 3.14 beta)\n";
7798     SetVersion($DBversion);
7799 }
7800
7801 $DBversion = "3.13.00.043";
7802 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
7803     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('SearchEngine','Zebra','Solr|Zebra','Search Engine','Choice')");
7804     print "Upgrade to $DBversion done (Bug 11196: Add system preference SearchEngine if missing )\n";
7805     SetVersion($DBversion);
7806 }
7807
7808 $DBversion = "3.14.00.000";
7809 if ( CheckVersion($DBversion) ) {
7810     print "Upgrade to $DBversion done (3.14.0 release)\n";
7811     SetVersion ($DBversion);
7812 }
7813
7814 $DBversion = '3.15.00.000';
7815 if ( CheckVersion($DBversion) ) {
7816     print "Upgrade to $DBversion done (the road goes ever on)\n";
7817     SetVersion ($DBversion);
7818 }
7819
7820 $DBversion = "3.15.00.001";
7821 if ( CheckVersion($DBversion) ) {
7822     $dbh->do("UPDATE systempreferences SET value='clear' where variable = 'CircAutoPrintQuickSlip' and value = '0'");
7823     $dbh->do("UPDATE systempreferences SET value='qslip' where variable = 'CircAutoPrintQuickSlip' and value = '1'");
7824     $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'");
7825     print "Upgrade to $DBversion done (Bug 11040: Add option to print full slip when checking out a null barcode)\n";
7826     SetVersion($DBversion);
7827 }
7828
7829 $DBversion = "3.15.00.002";
7830 if(CheckVersion($DBversion)) {
7831     $dbh->do("ALTER TABLE deleteditems MODIFY materials text;");
7832     print "Upgrade to $DBversion done (Bug 11275: alter deleteditems.materials from varchar(10) to text)\n";
7833     SetVersion($DBversion);
7834 }
7835
7836 $DBversion = "3.15.00.003";
7837 if ( CheckVersion($DBversion) ) {
7838     $dbh->do(q{
7839         UPDATE accountlines
7840         SET description = ''
7841         WHERE description IN (
7842             ' New Card',
7843             ' Fine',
7844             ' Sundry',
7845             'Writeoff',
7846             ' Account Management fee',
7847             'Payment,thanks', 'Payment,thanks - ',
7848             ' Lost Item'
7849         )
7850     });
7851     print "Upgrade to $DBversion done (Bug 2546: Update fine descriptions)\n";
7852     SetVersion($DBversion);
7853 }
7854
7855 $DBversion = "3.15.00.004";
7856 if ( CheckVersion($DBversion) ) {
7857     if ( C4::Context->preference("marcflavour") eq 'MARC21' ) {
7858         $dbh->do(qq{
7859             INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian, libopac, repeatable, mandatory,
7860             kohafield, tab, authorised_value, authtypecode, value_builder, isurl, hidden, frameworkcode, seealso, link,
7861             defaultvalue) VALUES
7862             ('015', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7863             ('020', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7864             ('024', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7865             ('027', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7866             ('800', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7867             ('810', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7868             ('811', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7869             ('830', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL);
7870         });
7871         $dbh->do(qq{
7872             INSERT IGNORE INTO auth_subfield_structure (authtypecode, tagfield, tagsubfield, liblibrarian, libopac, repeatable,
7873             mandatory, tab, authorised_value, value_builder, seealso, isurl, hidden, linkid, kohafield, frameworkcode) VALUES
7874             ('', '020', 'q', 'Qualifying information', 'Qualifying information', 1, 0, 0, NULL, NULL, NULL, 0, 0, '', '', ''),
7875             ('', '024', 'q', 'Qualifying information', 'Qualifying information', 1, 0, 0, NULL, NULL, NULL, 0, 0, '', '', '');
7876         });
7877     }
7878     print "Upgrade to $DBversion done (Bug 10970 - Update MARC21 frameworks to Update Nr. 17 - DB update)\n";
7879     SetVersion($DBversion);
7880 }
7881
7882 $DBversion = "3.15.00.005";
7883 if ( CheckVersion($DBversion) ) {
7884    $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('AcquisitionDetails', '1', '', 'Hide/Show acquisition details on the biblio detail page.', 'YesNo');");
7885    print "Upgrade to $DBversion done (Bug 8230: Add AcquisitionDetails system preference)\n";
7886    SetVersion ($DBversion);
7887 }
7888
7889 $DBversion = "3.15.00.006";
7890 if(CheckVersion($DBversion)) {
7891     $dbh->do(q{
7892         ALTER TABLE `borrowers`
7893         ADD KEY `surname_idx` (`surname`(255)),
7894         ADD KEY `firstname_idx` (`firstname`(255)),
7895         ADD KEY `othernames_idx` (`othernames`(255))
7896     });
7897     print "Upgrade to $DBversion done (Bug 11249 - Add DB indexes on borrower names)\n";
7898     SetVersion($DBversion);
7899 }
7900
7901 $DBversion = "3.15.00.007";
7902 if ( CheckVersion($DBversion) ) {
7903    $dbh->do("ALTER TABLE items ADD itemlost_on DATETIME NULL AFTER itemlost");
7904    $dbh->do("ALTER TABLE items ADD withdrawn_on DATETIME NULL AFTER withdrawn");
7905    $dbh->do("ALTER TABLE deleteditems ADD itemlost_on DATETIME NULL AFTER itemlost");
7906    $dbh->do("ALTER TABLE deleteditems ADD withdrawn_on DATETIME NULL AFTER withdrawn");
7907    print "Upgrade to $DBversion done (Bug 9673 - Track when items are marked as lost or withdrawn)\n";
7908    SetVersion ($DBversion);
7909 }
7910
7911 $DBversion = "3.15.00.008";
7912 if ( CheckVersion($DBversion) ) {
7913     $dbh->do(q{
7914         ALTER TABLE collections_tracking CHANGE ctId collections_tracking_id integer(11) NOT NULL auto_increment;
7915     });
7916     print "Upgrade to $DBversion done (Bug 11384) - change name of collections_tracker.ctId column)\n";
7917    SetVersion ($DBversion);
7918 }
7919
7920 $DBversion = "3.15.00.009";
7921 if ( CheckVersion($DBversion) ) {
7922     $dbh->do(q{
7923         ALTER TABLE suggestions MODIFY suggesteddate DATE NOT NULL
7924     });
7925     print "Upgrade to $DBversion done (Bug 11391) - drop default value on suggestions.suggesteddate column)\n";
7926    SetVersion ($DBversion);
7927 }
7928
7929 $DBversion = "3.15.00.010";
7930 if(CheckVersion($DBversion)) {
7931     $dbh->do("ALTER TABLE deleteditems DROP COLUMN marc");
7932     print "Upgrade to $DBversion done (Bug 6331: remove obsolete column in deleteditems.marc)\n";
7933     SetVersion ($DBversion);
7934 }
7935
7936 $DBversion = "3.15.00.011";
7937 if(CheckVersion($DBversion)) {
7938     $dbh->do("UPDATE marc_subfield_structure SET maxlength=9999 WHERE maxlength IS NULL OR maxlength=0;");
7939     print "Upgrade to $DBversion done (Bug 8018: set 9999 as default max length for subfields)\n";
7940     SetVersion ($DBversion);
7941 }
7942
7943 $DBversion = "3.15.00.012";
7944 if ( CheckVersion($DBversion) ) {
7945     $dbh->do(q{
7946         INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'force_checkout', 'Force checkout if a limitation exists')
7947     });
7948     $dbh->do(q{
7949         INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'manage_restrictions', 'Manage restrictions for accounts')
7950     });
7951     $dbh->do(q{
7952         INSERT INTO user_permissions (borrowernumber, module_bit, code)
7953             SELECT user_permissions.borrowernumber, 1, 'force_checkout'
7954             FROM user_permissions
7955             LEFT JOIN borrowers USING(borrowernumber)
7956             WHERE borrowers.flags & (1 << 1)
7957     });
7958     $dbh->do(q{
7959         INSERT INTO user_permissions (borrowernumber, module_bit, code)
7960             SELECT user_permissions.borrowernumber, 1, 'manage_restrictions'
7961             FROM user_permissions
7962             LEFT JOIN borrowers USING(borrowernumber)
7963             WHERE borrowers.flags & (1 << 1)
7964     });
7965
7966     print "Upgrade to $DBversion done (Bug 10863 - Add permissions force_checkout and manage_restrictions)\n";
7967     SetVersion($DBversion);
7968 }
7969
7970 $DBversion = "3.15.00.013";
7971 if(CheckVersion($DBversion)) {
7972     $dbh->do(q{
7973         UPDATE systempreferences
7974         SET explanation = 'Upon receiving items, update their subfields if they were created when placing an order (e.g. o=5|a="foo bar")'
7975         WHERE variable = "AcqItemSetSubfieldsWhenReceived"
7976     });
7977
7978     $dbh->do(q{
7979         UPDATE systempreferences
7980         SET value = ''
7981         WHERE variable = "AcqItemSetSubfieldsWhenReceived"
7982             AND value = "0"
7983     });
7984     print "Upgrade to $DBversion done (Bug 11237: Update explanation and default value for AcqItemSetSubfieldsWhenReceived syspref)\n";
7985     SetVersion($DBversion);
7986 }
7987
7988 $DBversion = "3.15.00.014";
7989 if (CheckVersion($DBversion)) {
7990     $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');");
7991     print "Upgrade to $DBversion done (Bug 11415: add system preference for automatic self checkout receipt printing)\n";
7992     SetVersion($DBversion);
7993 }
7994
7995 $DBversion = "3.15.00.015";
7996 if (CheckVersion($DBversion)) {
7997     $dbh->do("INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
7998         ('OpacSuggestionManagedBy',1,'','Show the name of the staff member who managed a suggestion in OPAC','YesNo');");
7999     print "Upgrade to $DBversion done (Bug 10907: Add OpacSuggestionManagedBy system preference)\n";
8000     SetVersion($DBversion);
8001 }
8002
8003 $DBversion = "3.15.00.016";
8004 if (CheckVersion($DBversion)) {
8005     $dbh->do("ALTER TABLE biblioitems CHANGE url url TEXT NULL DEFAULT NULL");
8006     $dbh->do("ALTER TABLE deletedbiblioitems CHANGE url url TEXT NULL DEFAULT NULL");
8007     print "Upgrade to $DBversion done (Bug 11268 - Biblioitems URL field is too small for some URLs)\n";
8008     SetVersion($DBversion);
8009 }
8010
8011 $DBversion = "3.15.00.017";
8012 if(CheckVersion($DBversion)) {
8013     $dbh->do(q{
8014         UPDATE systempreferences
8015         SET explanation = 'Define the contents of UNIMARC authority control field 100 position 08-35'
8016         WHERE variable = "UNIMARCAuthorityField100"
8017     });
8018     $dbh->do(q{
8019         UPDATE systempreferences
8020         SET explanation = 'Define the contents of MARC21 authority control field 008 position 06-39'
8021         WHERE variable = "MARCAuthorityControlField008"
8022     });
8023     $dbh->do(q{
8024         UPDATE systempreferences
8025         SET explanation = 'Define MARC Organization Code for MARC21 records - http://www.loc.gov/marc/organizations/orgshome.html'
8026         WHERE variable = "MARCOrgCode"
8027     });
8028     print "Upgrade to $DBversion done (Bug 11611 - fix possible confusion between UNIMARC and MARC21 in some sysprefs)\n";
8029     SetVersion($DBversion);
8030 }
8031
8032 $DBversion = "3.15.00.018";
8033 if ( CheckVersion($DBversion) ) {
8034     $dbh->{AutoCommit} = 0;
8035     $dbh->{RaiseError} = 1;
8036
8037     eval {
8038         $dbh->selectcol_arrayref(q|SELECT COUNT(*) FROM roadtype|);
8039     };
8040     unless ( $@ ) {
8041         my $av_added = $dbh->do(q|
8042             INSERT INTO authorised_values(category, authorised_value, lib, lib_opac)
8043                 SELECT 'ROADTYPE', roadtypeid, road_type, road_type
8044                 FROM roadtype;
8045         |);
8046
8047         my $rt_deleted = $dbh->do(q|
8048             DELETE FROM roadtype
8049         |);
8050
8051         if ( $av_added == $rt_deleted or $rt_deleted eq "0E0" ) {
8052             $dbh->do(q|
8053                 DROP TABLE roadtype;
8054             |);
8055             $dbh->commit;
8056             print "Upgrade to $DBversion done (Bug 7372: Move road types from the roadtype table to the ROADTYPE authorised values)\n";
8057             SetVersion($DBversion);
8058         } else {
8059             print "Upgrade to $DBversion failed (Bug 7372: Move road types from the roadtype table to the ROADTYPE authorised values.\nTransaction aborted because $@\n)";
8060             $dbh->rollback;
8061         }
8062     }
8063     $dbh->{AutoCommit} = 1;
8064     $dbh->{RaiseError} = 0;
8065 }
8066
8067 $DBversion = "3.15.00.019";
8068 if ( CheckVersion($DBversion) ) {
8069     $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')");
8070     print "Upgrade to $DBversion done (Bug 11256: Add system preference OpacMaxItemsToDisplay)\n";
8071     SetVersion($DBversion);
8072 }
8073
8074 $DBversion = "3.15.00.020";
8075 if ( CheckVersion($DBversion) ) {
8076     $dbh->do(q|
8077         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')
8078     |);
8079     print "Upgrade to $DBversion done (Bug 11343: Add system preference MaxItemsForBatch )\n";
8080     SetVersion($DBversion);
8081 }
8082
8083 $DBversion = "3.15.00.021";
8084 if(CheckVersion($DBversion)) {
8085     $dbh->do(q{
8086         ALTER TABLE `action_logs`
8087             DROP KEY timestamp,
8088             ADD KEY `timestamp_idx` (`timestamp`),
8089             ADD KEY `user_idx` (`user`),
8090             ADD KEY `module_idx` (`module`(255)),
8091             ADD KEY `action_idx` (`action`(255)),
8092             ADD KEY `object_idx` (`object`),
8093             ADD KEY `info_idx` (`info`(255))
8094     });
8095     print "Upgrade to $DBversion done (Bug 3445: Add indexes to action_logs table)\n";
8096     SetVersion($DBversion);
8097 }
8098
8099 $DBversion = "3.15.00.022";
8100 if (CheckVersion($DBversion)) {
8101     $dbh->do(q|
8102         DELETE FROM systempreferences WHERE variable= "memberofinstitution"
8103     |);
8104     print "Upgrade to $DBversion done (Bug 11751: Remove memberofinstitytion system preference)\n";
8105     SetVersion($DBversion);
8106 }
8107
8108 $DBversion = "3.15.00.023";
8109 if ( CheckVersion($DBversion) ) {
8110    $dbh->do("
8111        INSERT INTO systempreferences (variable,value,options,explanation,type)
8112        VALUES('CardnumberLength', '', '', 'Set a length for card numbers.', 'Free');
8113     ");
8114    print "Upgrade to $DBversion done (Bug 10861: Add CardnumberLength syspref)\n";
8115    SetVersion ($DBversion);
8116 }
8117
8118 $DBversion = "3.15.00.024";
8119 if ( CheckVersion($DBversion) ) {
8120     $dbh->do(q{
8121         DELETE FROM systempreferences WHERE variable = 'NoZebraIndexes'
8122     });
8123     print "Upgrade to $DBversion done (Bug 10012 - remove last vestiges of NoZebra)\n";
8124     SetVersion($DBversion);
8125 }
8126
8127 $DBversion = "3.15.00.025";
8128 if ( CheckVersion($DBversion) ) {
8129     $dbh->do(q{
8130         DROP TABLE aqorderdelivery;
8131     });
8132     print "Upgrade to $DBversion done (Bug 11928 - remove unused table)\n";
8133     SetVersion($DBversion);
8134 }
8135
8136 $DBversion = "3.15.00.026";
8137 if ( CheckVersion($DBversion) ) {
8138     $dbh->do(q{
8139         UPDATE language_descriptions SET description = 'Հայերեն' WHERE subtag = 'hy' AND lang = 'hy';
8140     });
8141     print "Upgrade to $DBversion done (Bug 11973 - Fix Armenian language description)\n";
8142     SetVersion($DBversion);
8143 }
8144
8145 $DBversion = "3.15.00.027";
8146 if (CheckVersion($DBversion)) {
8147     $dbh->do(q{
8148         ALTER TABLE opac_news ADD branchcode varchar(10) DEFAULT NULL
8149                                   AFTER idnew,
8150                               ADD CONSTRAINT opac_news_branchcode_ibfk
8151                                   FOREIGN KEY (branchcode)
8152                                   REFERENCES branches (branchcode)
8153                                   ON DELETE CASCADE ON UPDATE CASCADE;
8154     });
8155     print "Upgrade to $DBversion done (Bug 7567: Add branchcode to opac_news)\n";
8156     SetVersion($DBversion);
8157 }
8158
8159 $DBversion = "3.15.00.028";
8160 if(CheckVersion($DBversion)) {
8161     $dbh->do(q{
8162         ALTER TABLE issuingrules ADD norenewalbefore int(4) default NULL AFTER renewalperiod
8163     });
8164     print "Upgrade to $DBversion done (Bug 7413: Allow OPAC renewal x days before due date)\n";
8165     SetVersion($DBversion);
8166 }
8167
8168 $DBversion = "3.15.00.029";
8169 if ( CheckVersion($DBversion) ) {
8170     $dbh->do(q{
8171         UPDATE borrower_debarments SET expiration = NULL WHERE expiration = '9999-12-31'
8172     });
8173     print "Upgrade to $DBversion done (Bug 11846 - correct borrower_debarments with expiration 9999-12-31)\n";
8174     SetVersion($DBversion);
8175 }
8176
8177 $DBversion = "3.15.00.030";
8178 if(CheckVersion($DBversion)) {
8179     $dbh->do(q|
8180         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')
8181     |);
8182     print "Upgrade to $DBversion done (Bug 12052: Add OPACMySummaryNote syspref)\n";
8183     SetVersion($DBversion);
8184 }
8185
8186 $DBversion = "3.15.00.031";
8187 if ( CheckVersion($DBversion) ) {
8188    $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('10', 'writeoff', 'Write off fines and fees')");
8189    $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('10', 'remaining_permissions', 'Remaining permissions for managing fines and fees')");
8190    print "Upgrade to $DBversion done (Bug 9448 - Add separate permission for writing off fees)\n";
8191    SetVersion ($DBversion);
8192 }
8193
8194 $DBversion = "3.15.00.032";
8195 if ( CheckVersion($DBversion) ) {
8196     $dbh->do("ALTER TABLE aqorders CHANGE notes order_internalnote MEDIUMTEXT;");
8197     $dbh->do("ALTER TABLE aqorders ADD COLUMN order_vendornote MEDIUMTEXT AFTER order_internalnote;");
8198     print "Upgrade to $DBversion done (Bug 9416 - In each order, add a new note made for the vendor)\n";
8199    SetVersion ($DBversion);
8200 }
8201
8202 $DBversion = "3.15.00.033";
8203 if ( CheckVersion($DBversion) ) {
8204     $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')");
8205     print "Upgrade to $DBversion done (Bug 10951: Add NoLoginInstructions pref)\n";
8206     SetVersion($DBversion);
8207 }
8208
8209 $DBversion = "3.15.00.034";
8210 if ( CheckVersion($DBversion) ) {
8211     $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')");
8212     print "Upgrade to $DBversion done (Bug 10986: system preferences to limit languages in advanced search )\n";
8213     SetVersion ($DBversion);
8214 }
8215
8216 $DBversion = "3.15.00.035";
8217 if ( CheckVersion($DBversion) ) {
8218     #insert a notice for sharing a list and accepting a share
8219     $dbh->do("
8220 INSERT INTO letter (module, code, branchcode, name, is_html, title, content)
8221 VALUES ( 'members', 'SHARE_INVITE', '', 'Invitation for sharing a list', '0', 'Share list <<listname>>', 'Dear patron,
8222
8223 One of our patrons, <<borrowers.firstname>> <<borrowers.surname>>, invites you to share a list <<listname>> in our library catalog.
8224
8225 To access this shared list, please click on the following URL or copy-and-paste it into your browser address bar.
8226
8227 <<shareurl>>
8228
8229 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.
8230
8231 Thank you.
8232
8233 Your library.'
8234     )");
8235     $dbh->do("
8236 INSERT INTO letter (module, code, branchcode, name, is_html, title, content)
8237 VALUES ( 'members', 'SHARE_ACCEPT', '', 'Notification about an accepted share', '0', 'Share on list <<listname>> accepted', 'Dear patron,
8238
8239 We want to inform you that <<borrowers.firstname>> <<borrowers.surname>> accepted your invitation to share your list <<listname>> in our library catalog.
8240
8241 Thank you.
8242
8243 Your library.'
8244     )");
8245     print "Upgrade to $DBversion done (Bug 9032: Share a list)\n";
8246     SetVersion($DBversion);
8247 }
8248
8249 $DBversion = "3.15.00.036";
8250 if ( CheckVersion($DBversion) ) {
8251     $dbh->do(q{
8252         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
8253         VALUES('AllowMultipleIssuesOnABiblio',1,'Allow/Don\'t allow patrons to check out multiple items from one biblio','','YesNo')
8254     });
8255
8256     print "Upgrade to $DBversion done (Bug 10859 - Add system preference AllowMultipleIssuesOnABiblio)\n";
8257     SetVersion($DBversion);
8258 }
8259
8260 $DBversion = "3.15.00.037";
8261 if(CheckVersion($DBversion)) {
8262     $dbh->do(q{
8263         ALTER TABLE itemtypes ADD sip_media_type VARCHAR( 3 ) DEFAULT NULL AFTER checkinmsgtype
8264     });
8265     $dbh->do(q{
8266         INSERT INTO authorised_values (category, authorised_value, lib) VALUES
8267          ('SIP_MEDIA_TYPE', '000', 'Other'),
8268          ('SIP_MEDIA_TYPE', '001', 'Book'),
8269          ('SIP_MEDIA_TYPE', '002', 'Magazine'),
8270          ('SIP_MEDIA_TYPE', '003', 'Bound journal'),
8271          ('SIP_MEDIA_TYPE', '004', 'Audio tape'),
8272          ('SIP_MEDIA_TYPE', '005', 'Video tape'),
8273          ('SIP_MEDIA_TYPE', '006', 'CD/CDROM'),
8274          ('SIP_MEDIA_TYPE', '007', 'Diskette'),
8275          ('SIP_MEDIA_TYPE', '008', 'Book with diskette'),
8276          ('SIP_MEDIA_TYPE', '009', 'Book with CD'),
8277          ('SIP_MEDIA_TYPE', '010', 'Book with audio tape')
8278     });
8279     print "Upgrade to $DBversion done (Bug 11351 - Add support for SIP2 media type)\n";
8280     SetVersion($DBversion);
8281 }
8282
8283 $DBversion = '3.15.00.038';
8284 if ( CheckVersion($DBversion) ) {
8285     $dbh->do(q{
8286         INSERT INTO  systempreferences (
8287             variable,
8288             value,
8289             options,
8290             explanation,
8291             type
8292             )
8293         VALUES (
8294             'DisplayLibraryFacets',  'holding',  'home|holding|both',  'Defines which library facets to display.',  'Choice'
8295         );
8296     });
8297     print "Upgrade to $DBversion done (Bug 11334 - Add facet for home library)\n";
8298     SetVersion ($DBversion);
8299 }
8300
8301 $DBversion = "3.15.00.039";
8302 if ( CheckVersion($DBversion) ) {
8303
8304     $dbh->do( q{
8305         ALTER TABLE letter ADD COLUMN message_transport_type VARCHAR(20) NOT NULL DEFAULT 'email' AFTER content
8306     } );
8307
8308     $dbh->do( q{
8309         ALTER TABLE letter ADD CONSTRAINT message_transport_type_fk FOREIGN KEY (message_transport_type) REFERENCES message_transport_types(message_transport_type);
8310     } );
8311
8312     $dbh->do( q{
8313         ALTER TABLE letter DROP PRIMARY KEY, ADD PRIMARY KEY (`module`,`code`,`branchcode`, message_transport_type);
8314     } );
8315
8316     $dbh->do( q{
8317         CREATE TABLE overduerules_transport_types(
8318             id INT(11) NOT NULL AUTO_INCREMENT,
8319             branchcode varchar(10) NOT NULL DEFAULT '',
8320             categorycode VARCHAR(10) NOT NULL DEFAULT '',
8321             letternumber INT(1) NOT NULL DEFAULT 1,
8322             message_transport_type VARCHAR(20) NOT NULL DEFAULT 'email',
8323             PRIMARY KEY (id),
8324             CONSTRAINT overduerules_fk FOREIGN KEY (branchcode, categorycode) REFERENCES overduerules (branchcode, categorycode) ON DELETE CASCADE ON UPDATE CASCADE,
8325             CONSTRAINT mtt_fk FOREIGN KEY (message_transport_type) REFERENCES message_transport_types (message_transport_type) ON DELETE CASCADE ON UPDATE CASCADE
8326         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
8327     } );
8328
8329     my $sth = $dbh->prepare( q{
8330         SELECT * FROM overduerules;
8331     } );
8332
8333     $sth->execute;
8334     my $sth_insert_mtt = $dbh->prepare( q{
8335         INSERT INTO overduerules_transport_types (branchcode, categorycode, letternumber, message_transport_type) VALUES ( ?, ?, ?, ? )
8336     } );
8337     while ( my $row = $sth->fetchrow_hashref ) {
8338         my $branchcode = $row->{branchcode};
8339         my $categorycode = $row->{categorycode};
8340         for my $letternumber ( 1 .. 3 ) {
8341             next unless $row->{"letter$letternumber"};
8342             $sth_insert_mtt->execute(
8343                 $branchcode, $categorycode, $letternumber, 'email'
8344             );
8345         }
8346     }
8347
8348     print "Upgrade done (Bug 9016: Adds multi transport types management for notices)\n";
8349     SetVersion($DBversion);
8350 }
8351
8352 $DBversion = "3.15.00.040";
8353 if ( CheckVersion($DBversion) ) {
8354     $dbh->do(q|
8355         UPDATE message_transports SET letter_code='HOLD' WHERE letter_code='HOLD_PHONE' OR letter_code='HOLD_PRINT'
8356     |);
8357     $dbh->do(q|
8358         UPDATE letter SET code='HOLD', message_transport_type='print' WHERE code='HOLD_PRINT'
8359     |);
8360     $dbh->do(q|
8361         UPDATE letter SET code='HOLD', message_transport_type='phone' WHERE code='HOLD_PHONE'
8362     |);
8363     print "Upgrade to $DBversion done (Bug 10845: Multi transport types for holds)\n";
8364     SetVersion($DBversion);
8365 }
8366
8367 $DBversion = "3.15.00.041";
8368 if ( CheckVersion($DBversion) ) {
8369     my ( $name ) = $dbh->selectrow_array(q|
8370         SELECT name FROM letter WHERE code="HOLD"
8371     |);
8372     $dbh->do(q|
8373         UPDATE letter
8374         SET code="HOLD",
8375             message_transport_type="phone",
8376             name= ?
8377         WHERE code="HOLD_PHONE"
8378     |, {}, $name);
8379
8380     ( $name ) = $dbh->selectrow_array(q|
8381         SELECT name FROM letter WHERE code="PREDUE"
8382     |);
8383     $dbh->do(q|
8384         UPDATE letter
8385         SET code="PREDUE",
8386             message_transport_type="phone",
8387             name= ?
8388         WHERE code="PREDUE_PHONE"
8389     |, {}, $name);
8390
8391     ( $name ) = $dbh->selectrow_array(q|
8392         SELECT name FROM letter WHERE code="OVERDUE"
8393     |);
8394     $dbh->do(q|
8395         UPDATE letter
8396         SET code="OVERDUE",
8397             message_transport_type="phone",
8398             name= ?
8399         WHERE code="OVERDUE_PHONE"
8400     |, {}, $name);
8401
8402     print "Upgrade to $DBversion done (Bug 11867: Update letters *_PHONE)\n";
8403     SetVersion($DBversion);
8404 }
8405
8406 $DBversion = "3.15.00.042";
8407 if ( CheckVersion($DBversion) ) {
8408     $dbh->do(q{
8409         INSERT INTO systempreferences
8410             (variable,value,explanation,options,type)
8411         VALUES
8412             ('SpecifyReturnDate',0,'Define whether to display \"Specify Return Date\" form in Circulation','','YesNo')
8413     });
8414     print "Upgrade to $DBversion done (Bug 10694 - Allow arbitrary backdating of returns)\n";
8415     SetVersion($DBversion);
8416 }
8417
8418 $DBversion = "3.15.00.043";
8419 if ( CheckVersion($DBversion) ) {
8420     $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')");
8421    print "Upgrade to $DBversion done (Bug 7180: Added MarcFieldsToOrder syspref)\n";
8422    SetVersion ($DBversion);
8423 }
8424
8425 $DBversion = "3.15.00.044";
8426 if ( CheckVersion($DBversion) ) {
8427     $dbh->do("ALTER TABLE currency ADD isocode VARCHAR(5) default NULL AFTER symbol;");
8428     print "Upgrade to $DBversion done (Added isocode to the currency table)\n";
8429     SetVersion($DBversion);
8430 }
8431
8432 $DBversion = "3.15.00.045";
8433 if ( CheckVersion($DBversion) ) {
8434     $dbh->do("
8435         INSERT INTO systempreferences (variable,value,explanation,options,type)
8436         VALUES (
8437             'BlockExpiredPatronOpacActions',
8438             '0',
8439             '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',
8440             NULL,
8441             'YesNo'
8442         )
8443     ");
8444     $dbh->do("ALTER TABLE `categories` ADD COLUMN `BlockExpiredPatronOpacActions` TINYINT(1) DEFAULT -1 NOT NULL AFTER category_type");
8445     print "Upgraded to $DBversion done (Bug 6739 - expired patrons not blocked from opac actions)\n";
8446     SetVersion ($DBversion);
8447 }
8448
8449 $DBversion = "3.15.00.046";
8450 if ( CheckVersion($DBversion) ) {
8451     $dbh->do(q|
8452         ALTER TABLE search_history ADD COLUMN type VARCHAR(16) NOT NULL DEFAULT 'biblio' AFTER query_cgi
8453     |);
8454     print "Upgrade to $DBversion done (Bug 10807 - Add db field search_history.type)\n";
8455     SetVersion($DBversion);
8456 }
8457
8458 $DBversion = "3.15.00.047";
8459 if ( CheckVersion($DBversion) ) {
8460     $dbh->do(q|
8461         INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('EnableSearchHistory','0','','Enable or disable search history','YesNo')
8462     |);
8463     print "Upgrade to $DBversion done (Bug 10862: Add EnableSearchHistory syspref)\n";
8464     SetVersion($DBversion);
8465 }
8466
8467 $DBversion = "3.15.00.048";
8468 if ( CheckVersion($DBversion) ) {
8469     $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')");
8470     $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')");
8471     print "Upgrade to $DBversion done (Bug 10195: Records hidden with OpacSuppression can still be accessed)\n";
8472     SetVersion($DBversion);
8473 }
8474
8475 $DBversion = "3.15.00.049";
8476 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
8477     $dbh->do("ALTER TABLE biblioitems DROP INDEX isbn");
8478     $dbh->do("ALTER TABLE biblioitems DROP INDEX issn");
8479     $dbh->do("ALTER TABLE biblioitems DROP INDEX issn_idx");
8480     $dbh->do("ALTER TABLE biblioitems
8481               CHANGE isbn isbn MEDIUMTEXT NULL DEFAULT NULL,
8482               CHANGE issn issn MEDIUMTEXT NULL DEFAULT NULL
8483     ");
8484     $dbh->do("ALTER TABLE biblioitems
8485               ADD INDEX isbn ( isbn ( 255 ) ),
8486               ADD INDEX issn ( issn ( 255 ) )
8487     ");
8488
8489     $dbh->do("ALTER TABLE deletedbiblioitems DROP INDEX isbn");
8490     $dbh->do("ALTER TABLE deletedbiblioitems
8491               CHANGE isbn isbn MEDIUMTEXT NULL DEFAULT NULL,
8492               CHANGE issn issn MEDIUMTEXT NULL DEFAULT NULL
8493     ");
8494     $dbh->do("ALTER TABLE deletedbiblioitems
8495               ADD INDEX isbn ( isbn ( 255 ) )
8496     ");
8497
8498     print "Upgrade to $DBversion done (Bug 5377 - Biblioitems isbn and issn fields too small for multiple ISBN and ISSN)\n";
8499     SetVersion($DBversion);
8500 }
8501
8502 $DBversion = "3.15.00.050";
8503 if ( CheckVersion($DBversion) ) {
8504     $dbh->do("
8505         INSERT INTO systempreferences (
8506             variable,
8507             value,
8508             explanation,
8509             type
8510         ) VALUES (
8511             'AggressiveMatchOnISBN',
8512             '0',
8513             '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',
8514             'YesNo'
8515         )
8516     ");
8517
8518     print "Upgrade to $DBversion done (Bug 10500 - Improve isbn matching when importing records)\n";
8519     SetVersion($DBversion);
8520 }
8521
8522 $DBversion = "3.15.00.051";
8523 if ( CheckVersion($DBversion) ) {
8524     print "Upgrade to $DBversion done (Koha 3.16 beta)\n";
8525     SetVersion($DBversion);
8526 }
8527
8528 $DBversion = "3.15.00.052";
8529 if ( CheckVersion($DBversion) ) {
8530     print "Upgrade to $DBversion done (Koha 3.16 RC)\n";
8531     SetVersion($DBversion);
8532 }
8533
8534 $DBversion = "3.16.00.000";
8535 if ( CheckVersion($DBversion) ) {
8536     print "Upgrade to $DBversion done (3.16.0 release)\n";
8537     SetVersion ($DBversion);
8538 }
8539
8540 $DBversion = '3.17.00.000';
8541 if ( CheckVersion($DBversion) ) {
8542     print "Upgrade to $DBversion done (there is no time to rest on our laurels)\n";
8543     SetVersion ($DBversion);
8544 }
8545
8546 $DBversion = '3.17.00.001';
8547 if ( CheckVersion($DBversion) ) {
8548    $dbh->do("UPDATE systempreferences SET variable = 'AuthoritySeparator' WHERE variable = 'authoritysep'");
8549    print "Upgrade to $DBversion done (Bug 10330 - Rename system preference authoritysep to AuthoritySeparator)\n";
8550    SetVersion ($DBversion);
8551 }
8552
8553 $DBversion = "3.17.00.002";
8554 if (CheckVersion($DBversion)) {
8555     $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')");
8556     $dbh->do("
8557 CREATE TABLE IF NOT EXISTS `misc_files` (
8558   `file_id` int(11) NOT NULL AUTO_INCREMENT,
8559   `table_tag` varchar(255) NOT NULL,
8560   `record_id` int(11) NOT NULL,
8561   `file_name` varchar(255) NOT NULL,
8562   `file_type` varchar(255) NOT NULL,
8563   `file_description` varchar(255) DEFAULT NULL,
8564   `file_content` longblob NOT NULL, -- file content
8565   `date_uploaded` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
8566   PRIMARY KEY (`file_id`),
8567   KEY `table_tag` (`table_tag`),
8568   KEY `record_id` (`record_id`)
8569 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
8570     ");
8571     print "Upgrade to $DBversion done (Bug 3050 - Add an option to upload scanned invoices)\n";
8572     SetVersion($DBversion);
8573 }
8574
8575 $DBversion = "3.17.00.003";
8576 if (CheckVersion($DBversion)) {
8577     $dbh->do("UPDATE systempreferences SET type = 'Choice', options = '0|1|force' WHERE variable = 'OPACItemHolds'");
8578     print "Upgrade to $DBversion done (Bug 7825 - Changed OPACItemHolds syspref to Choice)\n";
8579     SetVersion($DBversion);
8580 }
8581
8582 $DBversion = "3.17.00.004";
8583 if (CheckVersion($DBversion)) {
8584     $dbh->do("ALTER TABLE categories ADD default_privacy ENUM( 'default', 'never', 'forever' ) NOT NULL DEFAULT 'default' AFTER category_type");
8585     print "Upgrade to $DBversion done (Bug 6254 - can't set patron privacy by default)\n";
8586     SetVersion($DBversion);
8587 }
8588
8589 $DBversion = "3.17.00.005";
8590 if (CheckVersion($DBversion)) {
8591     $dbh->do(q|
8592         ALTER TABLE issuingrules
8593         ADD maxsuspensiondays INT(11) DEFAULT NULL AFTER finedays;
8594     |);
8595     print "Upgrade to $DBversion done (Bug 12230: Add new issuing rule maxsuspensiondays)\n";
8596     SetVersion($DBversion);
8597 }
8598
8599 $DBversion = "3.17.00.006";
8600 if ( CheckVersion($DBversion) ) {
8601     $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')");
8602     $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')");
8603     print "Upgrade to $DBversion done (Bug 7720 - Ambiguity in OPAC Details location.)\n";
8604     SetVersion($DBversion);
8605 }
8606
8607 $DBversion = "3.17.00.007";
8608 if (CheckVersion($DBversion)) {
8609     $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');");
8610     print "Upgrade to $DBversion done (Bug 11629 - Add ability to update not for loan status on checkin)\n";
8611     SetVersion($DBversion);
8612 }
8613
8614 $DBversion = "3.17.00.008";
8615 if ( CheckVersion($DBversion) ) {
8616     $dbh->do(q|
8617         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('OPACAcquisitionDetails','0', '','Show the acquisition details at the OPAC','YesNo')
8618     |);
8619     print "Upgrade to $DBversion done (Bug 11169 - Add OPACAcquisitionDetails syspref)\n";
8620     SetVersion($DBversion);
8621 }
8622
8623 $DBversion = "3.17.00.009";
8624 if ( CheckVersion($DBversion) ) {
8625     $dbh->do(q{
8626         DELETE FROM systempreferences WHERE variable = 'UseTablesortForCirc'
8627     });
8628
8629     print "Upgrade to $DBversion done (Bug 11703 - Remove UseTablesortForCirc syspref)\n";
8630     SetVersion($DBversion);
8631 }
8632
8633 $DBversion = "3.17.00.010";
8634 if ( CheckVersion($DBversion) ) {
8635     $dbh->do("DELETE FROM systempreferences WHERE variable='opacsmallimage'");
8636     print "Upgrade to $DBversion done (Bug 11347 - PROG/CCSR deprecation: Remove opacsmallimage system preference)\n";
8637     SetVersion($DBversion);
8638 }
8639
8640 $DBversion = "3.17.00.011";
8641 if ( CheckVersion($DBversion) ) {
8642     $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'hr', 'language', 'Croatian','2014-07-24' )");
8643     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'hr','hrv')");
8644     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'hr', 'Hrvatski')");
8645     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'en', 'Croatian')");
8646     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'fr', 'Croate')");
8647     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'de', 'Kroatisch')");
8648     print "Upgrade to $DBversion done (Bug 12649: Add Croatian language)\n";
8649     SetVersion ($DBversion);
8650 }
8651
8652 $DBversion = "3.17.00.012";
8653 if ( CheckVersion($DBversion) ) {
8654     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacShowFiltersPulldownMobile'");
8655     print "Upgrade to $DBversion done ( Bug 12512 - PROG/CCSR deprecation: Remove OpacShowFiltersPulldownMobile system preference )\n";
8656     SetVersion ($DBversion);
8657 }
8658
8659 $DBversion = "3.17.00.013";
8660 if ( CheckVersion($DBversion) ) {
8661     $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')");
8662     print "Upgrade to $DBversion done (Re-add system preference maxreserves)\n";
8663     SetVersion ($DBversion);
8664 }
8665
8666 $DBversion = '3.17.00.014';
8667 if ( CheckVersion($DBversion) ) {
8668     $dbh->do("
8669         INSERT INTO systempreferences (variable,value,explanation,type) VALUES
8670         ('OverdueNoticeCalendar',0,'Take calendar into consideration when working out sending overdue notices','YesNo')
8671     ");
8672     print "Upgrade to $DBversion done (Bug 12529 - Adding a syspref to allow the overdue notices to consider the calendar when generating notices)\n";
8673     SetVersion($DBversion);
8674 }
8675
8676 $DBversion = "3.17.00.015";
8677 if ( CheckVersion($DBversion) ) {
8678     $dbh->do(q{
8679         CREATE TABLE IF NOT EXISTS columns_settings (
8680             module varchar(255) NOT NULL,
8681             page varchar(255) NOT NULL,
8682             tablename varchar(255) NOT NULL,
8683             columnname varchar(255) NOT NULL,
8684             cannot_be_toggled int(1) NOT NULL DEFAULT 0,
8685             is_hidden int(1) NOT NULL DEFAULT 0,
8686             PRIMARY KEY(module, page, tablename, columnname)
8687         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
8688     });
8689     print "Upgrade to $DBversion done (Bug 10212 - Create new table columns_settings)\n";
8690     SetVersion ($DBversion);
8691 }
8692
8693 $DBversion = "3.17.00.016";
8694 if ( CheckVersion($DBversion) ) {
8695     $dbh->do("CREATE TABLE aqcontacts (
8696         id int(11) NOT NULL auto_increment,
8697         name varchar(100) default NULL,
8698         position varchar(100) default NULL,
8699         phone varchar(100) default NULL,
8700         altphone varchar(100) default NULL,
8701         fax varchar(100) default NULL,
8702         email varchar(100) default NULL,
8703         notes mediumtext,
8704         claimacquisition BOOLEAN NOT NULL DEFAULT 0,
8705         claimissues BOOLEAN NOT NULL DEFAULT 0,
8706         acqprimary BOOLEAN NOT NULL DEFAULT 0,
8707         serialsprimary BOOLEAN NOT NULL DEFAULT 0,
8708         booksellerid int(11) not NULL,
8709         PRIMARY KEY  (id),
8710         CONSTRAINT booksellerid_aqcontacts_fk FOREIGN KEY (booksellerid)
8711             REFERENCES aqbooksellers (id) ON DELETE CASCADE ON UPDATE CASCADE
8712         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;");
8713     $dbh->do("INSERT INTO aqcontacts (name, position, phone, altphone, fax,
8714             email, notes, booksellerid, claimacquisition, claimissues, acqprimary, serialsprimary)
8715         SELECT contact, contpos, contphone, contaltphone, contfax, contemail,
8716             contnotes, id, 1, 1, 1, 1 FROM aqbooksellers;");
8717     $dbh->do("ALTER TABLE aqbooksellers DROP COLUMN contact,
8718         DROP COLUMN contpos, DROP COLUMN contphone,
8719         DROP COLUMN contaltphone, DROP COLUMN contfax,
8720         DROP COLUMN contemail, DROP COLUMN contnotes;");
8721     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contact>>', '<<aqcontacts.name>>')");
8722     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contpos>>', '<<aqcontacts.position>>')");
8723     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contphone>>', '<<aqcontacts.phone>>')");
8724     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contaltphone>>', '<<aqcontacts.altphone>>')");
8725     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contfax>>', '<<aqcontacts.contfax>>')");
8726     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contemail>>', '<<aqcontacts.contemail>>')");
8727     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contnotes>>', '<<aqcontacts.contnotes>>')");
8728     print "Upgrade to $DBversion done (Bug 10402: Move bookseller contacts to separate table)\n";
8729     SetVersion($DBversion);
8730 }
8731
8732 $DBversion = "3.17.00.017";
8733 if ( CheckVersion($DBversion) ) {
8734     # Correct invalid recordtypes (should be very exceptional)
8735     $dbh->do(q{
8736         UPDATE z3950servers set recordtype='biblio' WHERE recordtype NOT IN ('authority','biblio')
8737     });
8738     # Correct invalid server types (should also be very exceptional)
8739     $dbh->do(q{
8740         UPDATE z3950servers set type='zed' WHERE type <> 'zed'
8741     });
8742     # Adjust table
8743     $dbh->do(q{
8744         ALTER TABLE z3950servers
8745         DROP COLUMN icon,
8746         DROP COLUMN description,
8747         DROP COLUMN position,
8748         MODIFY COLUMN id int NOT NULL AUTO_INCREMENT FIRST,
8749         MODIFY COLUMN recordtype enum('authority','biblio') NOT NULL DEFAULT 'biblio',
8750         CHANGE COLUMN name servername mediumtext NOT NULL,
8751         CHANGE COLUMN type servertype enum('zed','sru') NOT NULL DEFAULT 'zed',
8752         ADD COLUMN sru_options varchar(255) default NULL,
8753         ADD COLUMN sru_fields mediumtext default NULL,
8754         ADD COLUMN add_xslt mediumtext default NULL
8755     });
8756     print "Upgrade to $DBversion done (Bug 6536: Z3950 improvements)\n";
8757     SetVersion ($DBversion);
8758 }
8759
8760 $DBversion = "3.17.00.018";
8761 if ( CheckVersion($DBversion) ) {
8762     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('HoldsInNoissuesCharge', '0', 'Hold charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
8763     print "Upgrade to $DBversion done (Bug 12205: Add HoldsInNoissuesCharge systempreference)\n";
8764     SetVersion($DBversion);
8765 }
8766
8767 $DBversion = "3.17.00.019";
8768 if ( CheckVersion($DBversion) ) {
8769     $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')"
8770     );
8771     print "Upgrade to $DBversion done (Bug 6149: Operator highlighted in search results)\n";
8772     SetVersion($DBversion);
8773 }
8774
8775 $DBversion = "3.17.00.020";
8776 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
8777     $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')");
8778     print "Upgrade to $DBversion done (Bug 8735 - Expire holds waiting only on days the library is open)\n";
8779     SetVersion ($DBversion);
8780 }
8781
8782 $DBversion = "3.17.00.021";
8783 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
8784     my $pref = C4::Context->preference('HomeOrHoldingBranch');
8785     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
8786        VALUES ('StaffSearchResultsDisplayBranch', ?,'homebranch|holdingbranch','Controls the display of the home or holding branch for staff search results','choice')", undef, $pref);
8787     print "Upgrade to $DBversion done (Bug 12582 - Control of branch displayed in search results linked to HomeOrHoldingBranch)\n";
8788     SetVersion ($DBversion);
8789 }
8790
8791 $DBversion = '3.17.00.022';
8792 if ( CheckVersion($DBversion) ) {
8793     my @temp= $dbh->selectrow_array(qq|
8794         SELECT count(*)
8795         FROM marc_subfield_structure
8796         WHERE kohafield='permanent_location' OR kohafield='items.permanent_location'
8797     |);
8798     print "Upgrade to $DBversion done (Bug 7817: Check for permanent_location)\n";
8799     if( $temp[0] ) {
8800         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";
8801     }
8802     SetVersion($DBversion);
8803 }
8804
8805 $DBversion = "3.17.00.023";
8806 if ( CheckVersion($DBversion) ) {
8807     $dbh->do(q{
8808         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')
8809     });
8810     print "Upgrade to $DBversion done (Bug 11169 - Add AcqItemSetSubfieldsWhenReceiptIsCancelled syspref)\n";
8811     SetVersion($DBversion);
8812 }
8813
8814 $DBversion = "3.17.00.024";
8815 if(CheckVersion($DBversion)) {
8816     $dbh->do(q{
8817         ALTER TABLE issues ADD auto_renew BOOLEAN default FALSE AFTER renewals
8818     });
8819     $dbh->do(q{
8820         ALTER TABLE old_issues ADD auto_renew BOOLEAN default FALSE AFTER renewals
8821     });
8822     $dbh->do(q{
8823         ALTER TABLE issuingrules ADD auto_renew BOOLEAN default FALSE AFTER norenewalbefore
8824     });
8825     print "Upgrade to $DBversion done (Bug 11577: [ENH] Automatic renewal feature)\n";
8826     SetVersion($DBversion);
8827 }
8828
8829 $DBversion = '3.17.00.025';
8830 if ( CheckVersion($DBversion) ) {
8831     $dbh->do(qq{
8832         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')
8833     });
8834     print "Upgrade to $DBversion done (Bug 12728: Checked syspref StatisticsFields)\n";
8835 }
8836
8837 $DBversion = "3.17.00.026";
8838 if ( CheckVersion($DBversion) ) {
8839     if ( C4::Context->preference('marcflavour') eq 'MARC21' ) {
8840         $dbh->do("UPDATE marc_subfield_structure SET liblibrarian = 'Encoded bitrate', libopac = 'Encoded bitrate' WHERE tagfield = '347' AND tagsubfield = 'f'");
8841         $dbh->do("UPDATE marc_subfield_structure SET repeatable = 1 WHERE tagfield IN ('110','111','610','611','710','711','810','811') AND tagsubfield = 'c'");
8842         $dbh->do("UPDATE auth_subfield_structure SET repeatable = 1 WHERE tagfield IN ('110','111','410','411','510','511','710','711') AND tagsubfield = 'c'");
8843         print "Upgrade to $DBversion done (Bug 12435 - Update MARC21 frameworks to Update No. 18 (April 2014))\n";
8844     }
8845     SetVersion($DBversion);
8846 }
8847
8848 $DBversion = "3.17.00.027";
8849 if ( CheckVersion($DBversion) ) {
8850     $dbh->do(q{
8851         DELETE FROM systempreferences WHERE variable = 'SearchEngine'
8852     });
8853     print "Upgrade to $DBversion done (Bug 12538 - Remove SearchEngine syspref)\n";
8854     SetVersion($DBversion);
8855 }
8856
8857 $DBversion = "3.17.00.028";
8858 if ( CheckVersion($DBversion) ) {
8859     $dbh->do(q{
8860         INSERT INTO systempreferences (variable,value) VALUES('OpacCustomSearch','');
8861     });
8862     print "Upgrade to $DBversion done (Bug 12296 - search box replaceable with a system preference)\n";
8863     SetVersion($DBversion);
8864 }
8865
8866 $DBversion = "3.17.00.029";
8867 if ( CheckVersion($DBversion) ) {
8868     $dbh->do("ALTER TABLE  `items` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8869     $dbh->do("ALTER TABLE  `deleteditems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8870     $dbh->do("ALTER TABLE  `biblioitems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8871     $dbh->do("ALTER TABLE  `deletedbiblioitems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8872     print "Upgrade to $DBversion done (Bug 12424 - ddc sorting of call numbers truncates long Cutter parts)\n";
8873     SetVersion ($DBversion);
8874 }
8875
8876 $DBversion = "3.17.00.030";
8877 if ( CheckVersion($DBversion) ) {
8878     $dbh->do(
8879         q{
8880        INSERT INTO systempreferences (variable, value, options, explanation, type )
8881        VALUES
8882         ('UsageStatsCountry', '', NULL, 'The country where your library is located, to be shown on the Hea Koha community website', 'YesNo'),
8883         ('UsageStatsID', '', NULL, 'This preference is part of Koha but it should not be deleted or updated manually.',  'Free'),
8884         ('UsageStatsLastUpdateTime', '', NULL, 'This preference is part of Koha but it should not be deleted or updated manually.', 'Free'),
8885         ('UsageStatsLibraryName', '', NULL, 'The library name to be shown on Hea Koha community website', 'Free'),
8886         ('UsageStatsLibraryType', 'public', 'public|university', 'The library type to be shown on the Hea Koha community website', 'Choice'),
8887         ('UsageStatsLibraryUrl', '', NULL, 'The library URL to be shown on Hea Koha community website', 'Free'),
8888         ('UsageStats', 0, NULL, 'Share anonymous usage data on the Hea Koha community website.', 'YesNo')
8889     });
8890     print "Upgrade to $DBversion done (Bug 11926: Add UsageStats systempreferences (HEA))\n";
8891     SetVersion ($DBversion);
8892 }
8893
8894 $DBversion = "3.17.00.031";
8895 if ( CheckVersion($DBversion) ) {
8896    $dbh->do("ALTER TABLE saved_sql CHANGE report_name report_name VARCHAR( 255 ) NOT NULL DEFAULT '' ");
8897    print "Upgrade to $DBversion done (Bug 2969: Report Name should be mandatory for saved reports)\n";
8898    SetVersion ($DBversion);
8899 }
8900
8901 $DBversion = "3.17.00.032";
8902 if ( CheckVersion($DBversion) ) {
8903     $dbh->do(
8904 "INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('ReplytoDefault',  '',  NULL,  'The default email address to be set as replyto.',  'Free')"
8905     );
8906     $dbh->do(
8907 "INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('ReturnpathDefault',  '',  NULL,  'The default email address to be set as return-path',  'Free')"
8908     );
8909     $dbh->do("ALTER TABLE branches ADD branchreplyto mediumtext AFTER branchemail");
8910     $dbh->do("ALTER TABLE branches ADD branchreturnpath mediumtext AFTER branchreplyto");
8911     print "Upgrade to $DBversion done (Bug 9530: Adding replyto and returnpath addresses.)\n";
8912     SetVersion($DBversion);
8913 }
8914
8915 $DBversion = "3.17.00.033";
8916 if ( CheckVersion($DBversion) ) {
8917     $dbh->do(q{
8918         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
8919         VALUES('FacetMaxCount', '20','Specify the max facet count for each category',NULL,'Integer')
8920     });
8921     print "Upgrade to $DBversion done (Bug 13088 - Allow the user to specify a max amount of facets to show)\n";
8922     SetVersion($DBversion);
8923 }
8924
8925 $DBversion = "3.17.00.034";
8926 if ( CheckVersion($DBversion) ) {
8927     $dbh->do(q|
8928         ALTER TABLE aqorders DROP COLUMN cancelledby;
8929     |);
8930
8931     print "Upgrade to $DBversion done (Bug 11007 - DROP column aqorders.cancelledby)\n";
8932     SetVersion($DBversion);
8933 }
8934
8935 $DBversion = "3.17.00.035";
8936 if ( CheckVersion($DBversion) ) {
8937     $dbh->do(q|
8938         ALTER TABLE serial ADD COLUMN claims_count INT(11) DEFAULT 0 after claimdate
8939     |);
8940     $dbh->do(q|
8941         UPDATE serial
8942         SET claims_count = 1
8943         WHERE claimdate IS NOT NULL
8944     |);
8945     print "Upgrade to $DBversion done (Bug 5342: Add claims_count field in serial table)\n";
8946     SetVersion($DBversion);
8947 }
8948
8949 $DBversion = "3.17.00.036";
8950 if ( CheckVersion($DBversion) ) {
8951     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacShowLibrariesPulldownMobile'");
8952     print "Upgrade to $DBversion done ( Bug 12513 - PROG/CCSR deprecation: Remove OpacShowLibrariesPulldownMobile system preference )\n";
8953     SetVersion ($DBversion);
8954 }
8955
8956 $DBversion = "3.17.00.037";
8957 if ( CheckVersion($DBversion) ) {
8958     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacMainUserBlockMobile'");
8959     print "Upgrade to $DBversion done ( Bug 12246 - PROG/CCSR deprecation: Remove OpacMainUserBlockMobile system preference )\n";
8960     SetVersion ($DBversion);
8961 }
8962
8963 $DBversion = "3.17.00.038";
8964 if ( CheckVersion($DBversion) ) {
8965     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACMobileUserCSS'");
8966     print "Upgrade to $DBversion done ( Bug 12245 - PROG/CCSR deprecation: Remove OPACMobileUserCSS system preference )\n";
8967     SetVersion ($DBversion);
8968 }
8969
8970 $DBversion = "3.17.00.039";
8971 if ( CheckVersion($DBversion) ) {
8972     $dbh->do("INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES
8973     ('OPACFallback', 'prog', 'bootstrap|prog', 'Define the fallback theme for the OPAC interface.', 'Themes')");
8974     print "Upgrade to $DBversion done (Bug 12539 - PROG/CCSR deprecation: Remove hardcoded theme from C4/Templates.pm)\n";
8975     SetVersion ($DBversion);
8976 }
8977
8978 $DBversion = "3.17.00.040";
8979 if ( CheckVersion($DBversion) ) {
8980     my $opac_theme = C4::Context->preference( 'opacthemes' );
8981     if ( !defined $opac_theme || $opac_theme eq 'prog' || $opac_theme eq 'ccsr' ) {
8982         $dbh->do("UPDATE systempreferences SET value='bootstrap' WHERE variable='opacthemes'");
8983     }
8984     print "Upgrade to $DBversion done (Bug 12223: 'prog' and 'ccsr' themes removed)\n";
8985     SetVersion($DBversion);
8986 }
8987
8988 $DBversion = "3.17.00.041";
8989 if ( CheckVersion($DBversion) ) {
8990     print "Upgrade to $DBversion done (Bug 11346: Deprecate the 'prog' and 'CCSR' themes)\n";
8991     SetVersion($DBversion);
8992 }
8993
8994 $DBversion = "3.17.00.042";
8995 if ( CheckVersion($DBversion) ) {
8996     $dbh->do("DELETE FROM systempreferences WHERE variable='yuipath'");
8997     print "Upgrade to $DBversion done (Bug 12494: Remove yuipath system preference)\n";
8998     SetVersion ($DBversion);
8999 }
9000
9001 $DBversion = "3.17.00.043";
9002 if ( CheckVersion($DBversion) ) {
9003     $dbh->do("
9004         ALTER TABLE aqorders
9005         ADD COLUMN cancellationreason TEXT DEFAULT NULL AFTER datecancellationprinted
9006     ");
9007     print "Upgrade to $DBversion done (Bug 7162: Add aqorders.cancellationreason)\n";
9008     SetVersion ($DBversion);
9009 }
9010
9011 $DBversion = "3.17.00.044";
9012 if ( CheckVersion($DBversion) ) {
9013     $dbh->do(q{
9014         INSERT IGNORE INTO systempreferences
9015             (variable,value,explanation,options,type)
9016             VALUES('OnSiteCheckouts','0','Enable/Disable the on-site checkouts feature','','YesNo');
9017     });
9018     $dbh->do(q{
9019         INSERT IGNORE INTO systempreferences
9020             (variable,value,explanation,options,type)
9021             VALUES('OnSiteCheckoutsForce','0','Enable/Disable the on-site for all cases (Even if a user is debarred, etc.)','','YesNo');
9022     });
9023     $dbh->do(q{
9024         ALTER TABLE issues ADD COLUMN onsite_checkout INT(1) NOT NULL DEFAULT 0 AFTER issuedate;
9025     });
9026     $dbh->do(q{
9027         ALTER TABLE old_issues ADD COLUMN onsite_checkout INT(1) NOT NULL DEFAULT 0 AFTER issuedate;
9028     });
9029     print "Upgrade to $DBversion done (Bug 10860: Add new system preference OnSiteCheckouts + fields [old_]issues.onsite_checkout)\n";
9030     SetVersion($DBversion);
9031 }
9032
9033 $DBversion = "3.17.00.045";
9034 if ( CheckVersion($DBversion) ) {
9035     $dbh->do(q{
9036         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
9037         ('LocalHoldsPriority',  '0', NULL,  'Enables the LocalHoldsPriority feature',  'YesNo'),
9038         ('LocalHoldsPriorityItemControl',  'holdingbranch',  'holdingbranch|homebranch',  'decides if the feature operates using the item''s home or holding library.',  'Choice'),
9039         ('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')
9040     });
9041     print "Upgrade to $DBversion done (Bug 11126 - Make the holds system optionally give precedence to local holds)\n";
9042     SetVersion($DBversion);
9043 }
9044
9045 $DBversion = "3.17.00.046";
9046 if ( CheckVersion($DBversion) ) {
9047     $dbh->do(q{
9048         CREATE TABLE IF NOT EXISTS items_search_fields (
9049           name VARCHAR(255) NOT NULL,
9050           label VARCHAR(255) NOT NULL,
9051           tagfield CHAR(3) NOT NULL,
9052           tagsubfield CHAR(1) NULL DEFAULT NULL,
9053           authorised_values_category VARCHAR(16) NULL DEFAULT NULL,
9054           PRIMARY KEY(name),
9055           CONSTRAINT items_search_fields_authorised_values_category
9056             FOREIGN KEY (authorised_values_category) REFERENCES authorised_values (category)
9057             ON DELETE SET NULL ON UPDATE CASCADE
9058         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
9059     });
9060     print "Upgrade to $DBversion done (Bug 11425: Add items_search_fields table)\n";
9061     SetVersion($DBversion);
9062 }
9063
9064 $DBversion = "3.17.00.047";
9065 if ( CheckVersion($DBversion) ) {
9066     $dbh->do(q{
9067         ALTER TABLE collections
9068             CHANGE colBranchcode colBranchcode VARCHAR( 10 ) NULL DEFAULT NULL,
9069             ADD INDEX ( colBranchcode ),
9070             ADD CONSTRAINT collections_ibfk_1 FOREIGN KEY (colBranchcode) REFERENCES branches (branchcode) ON DELETE CASCADE ON UPDATE CASCADE
9071     });
9072     print "Upgrade to $DBversion done (Bug 8836 - Resurrect Rotating Collections)\n";
9073     SetVersion($DBversion);
9074 }
9075
9076 $DBversion = "3.17.00.048";
9077 if ( CheckVersion($DBversion) ) {
9078     $dbh->do(q|
9079         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')
9080     |);
9081     print "Upgrade to $DBversion done (Bug 12448 - Add RentalFeesCheckoutConfirmation syspref)\n";
9082     SetVersion($DBversion);
9083 }
9084
9085 $DBversion = "3.17.00.049";
9086 if ( CheckVersion($DBversion) ) {
9087     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'am', 'language', 'Amharic','2014-10-29')");
9088     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'am','amh')");
9089     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'am', 'language', 'am', 'አማርኛ')");
9090     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'am', 'language', 'en', 'Amharic')");
9091
9092     $dbh->do("UPDATE language_descriptions SET description = 'لعربية' WHERE subtag = 'ar' AND type = 'language' AND lang = 'ar'");
9093
9094     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'az', 'language', 'Azerbaijani','2014-10-30')");
9095     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'az','aze')");
9096     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'az', 'language', 'az', 'Azərbaycan dili')");
9097     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'az', 'language', 'en', 'Azerbaijani')");
9098
9099     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'be', 'language', 'Byelorussian','2014-10-30')");
9100     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'be','bel')");
9101     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'be', 'language', 'be', 'Беларуская мова')");
9102     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'be', 'language', 'en', 'Byelorussian')");
9103
9104     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'bn', 'language', 'Bengali','2014-10-30')");
9105     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'bn','ben')");
9106     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'bn', 'language', 'bn', 'বাংলা')");
9107     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'bn', 'language', 'en', 'Bengali')");
9108
9109     $dbh->do("UPDATE language_descriptions SET description = 'Български' WHERE subtag = 'bg' AND type = 'language' AND lang = 'bg'");
9110     $dbh->do("UPDATE language_descriptions SET description = 'Ceština' WHERE subtag = 'cs' AND type = 'language' AND lang = 'cs'");
9111     $dbh->do("UPDATE language_descriptions SET description = 'Ελληνικά' WHERE subtag = 'el' AND type = 'language' AND lang = 'el'");
9112     $dbh->do("UPDATE language_descriptions SET description = 'Español' WHERE subtag = 'es' AND type = 'language' AND lang = 'es'");
9113
9114     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'eu', 'language', 'Basque','2014-10-30')");
9115     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'eu','eus')");
9116     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'eu', 'language', 'eu', 'Euskera')");
9117     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'eu', 'language', 'en', 'Basque')");
9118
9119     $dbh->do("UPDATE language_descriptions SET description = 'فارسى' WHERE subtag = 'fa' AND type = 'language' AND lang = 'fa'");
9120     $dbh->do("UPDATE language_descriptions SET description = 'Suomi' WHERE subtag = 'fi' AND type = 'language' AND lang = 'fi'");
9121
9122     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'fo', 'language', 'Faroese','2014-10-30')");
9123     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'fo','fao')");
9124     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'fo', 'language', 'fo', 'Føroyskt')");
9125     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'fo', 'language', 'en', 'Faroese')");
9126
9127     $dbh->do("UPDATE language_descriptions SET description = 'Français' WHERE subtag = 'fr' AND type = 'language' AND lang = 'fr'");
9128     $dbh->do("UPDATE language_descriptions SET description = 'עִבְרִית' WHERE subtag = 'he' AND type = 'language' AND lang = 'he'");
9129     $dbh->do("UPDATE language_descriptions SET description = 'हिन्दी' WHERE subtag = 'hi' AND type = 'language' AND lang = 'hi'");
9130
9131     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'is', 'language', 'Icelandic','2014-10-30')");
9132     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'is','ice')");
9133     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'is', 'language', 'is', 'Íslenska')");
9134     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'is', 'language', 'en', 'Icelandic')");
9135
9136     $dbh->do("UPDATE language_descriptions SET description = '日本語' WHERE subtag = 'ja' AND type = 'language' AND lang = 'ja'");
9137
9138     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ka', 'language', 'Kannada','2014-10-30')");
9139     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ka','kan')");
9140     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'ka', 'ಕನ್ನಡ')");
9141     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'en', 'Kannada')");
9142
9143     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'km', 'language', 'Khmer','2014-10-30')");
9144     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'km','khm')");
9145     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'km', 'language', 'km', 'ភាសាខ្មែរ')");
9146     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'km', 'language', 'en', 'Khmer')");
9147
9148     $dbh->do("UPDATE language_descriptions SET description = '한국어' WHERE subtag = 'ko' AND type = 'language' AND lang = 'ko'");
9149
9150     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ku', 'language', 'Kurdish','2014-05-13')");
9151     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ku','kur')");
9152     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'ku', 'کوردی')");
9153     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'en', 'Kurdish')");
9154     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'fr', 'Kurde')");
9155     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'de', 'Kurdisch')");
9156     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'es', 'Kurdo')");
9157
9158     $dbh->do("UPDATE language_descriptions SET description = 'ພາສາລາວ' WHERE subtag = 'lo' AND type = 'language' AND lang = 'lo'");
9159
9160     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mi', 'language', 'Maori','2014-10-30')");
9161     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mi','mri')");
9162     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mi', 'language', 'mi', 'Te Reo Māori')");
9163     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mi', 'language', 'en', 'Maori')");
9164
9165     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mn', 'language', 'Mongolian','2014-10-30')");
9166     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mn','mon')");
9167     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mn', 'language', 'mn', 'Mонгол')");
9168     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mn', 'language', 'en', 'Mongolian')");
9169
9170     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mr', 'language', 'Marathi','2014-10-30')");
9171     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mr','mar')");
9172     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mr', 'language', 'mr', 'मराठी')");
9173     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mr', 'language', 'en', 'Marathi')");
9174
9175     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ms', 'language', 'Malay','2014-10-30')");
9176     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ms','may')");
9177     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ms', 'language', 'ms', 'Bahasa melayu')");
9178     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ms', 'language', 'en', 'Malay')");
9179
9180     $dbh->do("UPDATE language_descriptions SET description = 'Norsk bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'nb'");
9181     $dbh->do("UPDATE language_descriptions SET description = 'Norwegian bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'en'");
9182     $dbh->do("UPDATE language_descriptions SET description = 'Norvégien bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'fr'");
9183     $dbh->do("UPDATE language_descriptions SET description = 'Norwegisch bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'de'");
9184
9185     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ne', 'language', 'Nepali','2014-10-30')");
9186     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ne','nep')");
9187     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)VALUES ( 'ne', 'language', 'ne', 'नेपाली')");
9188     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ne', 'language', 'en', 'Nepali')");
9189
9190     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'pbr', 'language', 'Pangwa','2014-10-30')");
9191     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'pbr','pbr')");
9192     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'pbr', 'language', 'pbr', 'Ekipangwa')");
9193     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'pbr', 'language', 'en', 'Pangwa')");
9194
9195     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'prs', 'language', 'Dari','2014-10-30')");
9196     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'prs','prs')");
9197     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'prs', 'language', 'prs', 'درى')");
9198     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'prs', 'language', 'en', 'Dari')");
9199
9200     $dbh->do("UPDATE language_descriptions SET description = 'Português' WHERE subtag = 'pt' AND type = 'language' AND lang = 'pt'");
9201     $dbh->do("UPDATE language_descriptions SET description = 'Român' WHERE subtag = 'ro' AND type = 'language' AND lang = 'ro'");
9202     $dbh->do("UPDATE language_descriptions SET description = 'Русский' WHERE subtag = 'ru' AND type = 'language' AND lang = 'ru'");
9203
9204     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'rw', 'language', 'Kinyarwanda','2014-10-30')");
9205     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'rw','kin')");
9206     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'rw', 'language', 'rw', 'Ikinyarwanda')");
9207     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'rw', 'language', 'en', 'Kinyarwanda')");
9208
9209     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sd', 'language', 'Sindhi','2014-10-30')");
9210     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sd','snd')");
9211     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sd', 'language', 'sd', 'سنڌي')");
9212     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sd', 'language', 'en', 'Sindhi')");
9213
9214     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sk', 'language', 'Slovak','2014-10-30')");
9215     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sk','slk')");
9216     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sk', 'language', 'sk', 'Slovenčina')");
9217     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sk', 'language', 'en', 'Slovak')");
9218
9219     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sl', 'language', 'Slovene','2014-10-30')");
9220     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sl','slv')");
9221     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sl', 'language', 'sl', 'Slovenščina')");
9222     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sl', 'language', 'en', 'Slovene')");
9223
9224     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sq', 'language', 'Albanian','2014-10-30')");
9225     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sq','sqi')");
9226     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sq', 'language', 'sq', 'Shqip')");
9227     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sq', 'language', 'en', 'Albanian')");
9228
9229     $dbh->do("UPDATE language_descriptions SET description = 'Cрпски' WHERE subtag = 'sr' AND type = 'language' AND lang = 'sr'");
9230
9231     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sw', 'language', 'Swahili','2014-10-30')");
9232     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sw','swa')");
9233     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sw', 'language', 'sw', 'Kiswahili')");
9234     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sw', 'language', 'en', 'Swahili')");
9235
9236     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ta', 'language', 'Tamil','2014-10-30')");
9237     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ta','tam')");
9238     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ta', 'language', 'ta', 'தமிழ்')");
9239     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ta', 'language', 'en', 'Tamil')");
9240
9241     $dbh->do("UPDATE language_descriptions SET description = 'Tetun' WHERE subtag = 'tet' AND type = 'language' AND lang = 'tet'");
9242     $dbh->do("UPDATE language_descriptions SET description = 'ภาษาไทย' WHERE subtag = 'th' AND type = 'language' AND lang = 'th'");
9243
9244     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'tl', 'language', 'Tagalog','2014-10-30')");
9245     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'tl','tgl')");
9246     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'tl', 'language', 'tl', 'Tagalog')");
9247     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'tl', 'language', 'en', 'Tagalog')");
9248
9249     $dbh->do("UPDATE language_descriptions SET description = 'Türkçe' WHERE subtag = 'tr' AND type = 'language' AND lang = 'tr'");
9250     $dbh->do("UPDATE language_descriptions SET description = 'Українська' WHERE subtag = 'uk' AND type = 'language' AND lang = 'uk'");
9251     $dbh->do("UPDATE language_descriptions SET description = 'اردو' WHERE subtag = 'ur' AND type = 'language' AND lang = 'ur'");
9252
9253     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'vi', 'language', 'Vietnamese','2014-10-30')");
9254     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'vi','vie')");
9255     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'vi', 'language', 'vi', '㗂越')");
9256     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'vi', 'language', 'en', 'Vietnamese')");
9257
9258     $dbh->do("UPDATE language_descriptions SET description = '中文' WHERE subtag = 'zh' AND type = 'language' AND lang = 'zh'");
9259     $dbh->do("UPDATE language_descriptions SET description = '' WHERE subtag = 'Arab,script' AND type = 'Arab' AND lang = 'العربية'");
9260
9261     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Armn', 'script', 'Armenian','2014-10-30')");
9262     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Armn', 'script', 'Armn', 'Հայոց այբուբեն')");
9263     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Armn', 'script', 'en', 'Armenian')");
9264
9265     $dbh->do("UPDATE language_descriptions SET description = 'Кирилица' WHERE subtag = 'Cyrl' AND type = 'script' AND lang = 'Cyrl'");
9266
9267     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Ethi', 'script', 'Ethiopic','2014-10-30')");
9268     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Ethi', 'script', 'Ethi', 'ግዕዝ')");
9269     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Ethi', 'script', 'en', 'Ethiopic')");
9270
9271     $dbh->do("UPDATE language_descriptions SET description = 'Ελληνικό αλφάβητο' WHERE subtag = 'Grek' AND type = 'script' AND lang = 'Grek'");
9272     $dbh->do("UPDATE language_descriptions SET description = '简体字' WHERE subtag = 'Hans' AND type = 'script' AND lang = 'Hans'");
9273     $dbh->do("UPDATE language_descriptions SET description = '繁體字' WHERE subtag = 'Hant' AND type = 'script' AND lang = 'Hant'");
9274     $dbh->do("UPDATE language_descriptions SET description = 'אָלֶף־בֵּית עִבְרִי' WHERE subtag = 'Hebr' AND type = 'script' AND lang = 'Hebr'");
9275
9276     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Jpan', 'script', 'Japanese','2014-10-30')");
9277     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Jpan', 'script', 'Jpan', '漢字')");
9278     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Jpan', 'script', 'en', 'Japanese')");
9279
9280     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Knda', 'script', 'Kannada','2014-10-30')");
9281     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Knda', 'script', 'Knda', 'ಕನ್ನಡ ಲಿಪಿ')");
9282     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Knda', 'script', 'en', 'Kannada')");
9283
9284     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Kore', 'script', 'Korean','2014-10-30')");
9285     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Kore', 'script', 'Kore', '한글')");
9286     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Kore', 'script', 'en', 'Korean')");
9287
9288     $dbh->do("UPDATE language_descriptions SET description = 'ອັກສອນລາວ' WHERE subtag = 'Laoo' AND type = 'script' AND lang = 'Laoo'");
9289
9290     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'AL', 'region', 'Albania','2014-10-30')");
9291     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AL', 'region', 'en', 'Albania')");
9292     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AL', 'region', 'sq', 'Shqipërisë')");
9293
9294     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'AZ', 'region', 'Azerbaijan','2014-10-30')");
9295     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AZ', 'region', 'en', 'Azerbaijan')");
9296     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AZ', 'region', 'az', 'Azərbaycan')");
9297
9298     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BE', 'region', 'Belgium','2014-10-30')");
9299     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BE', 'region', 'en', 'Belgium')");
9300     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BE', 'region', 'nl', 'België')");
9301
9302     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BR', 'region', 'Brazil','2014-10-30')");
9303     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BR', 'region', 'en', 'Brazil')");
9304     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BR', 'region', 'pt', 'Brasil')");
9305
9306     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BY', 'region', 'Belarus','2014-10-30')");
9307     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BY', 'region', 'en', 'Belarus')");
9308     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BY', 'region', 'be', 'Беларусь')");
9309
9310     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CA', 'region', 'fr', 'Canada')");
9311
9312     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CH', 'region', 'Switzerland','2014-10-30')");
9313     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CH', 'region', 'en', 'Switzerland')");
9314     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CH', 'region', 'de', 'Schweiz')");
9315
9316     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CN', 'region', 'China','2014-10-30')");
9317     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CN', 'region', 'en', 'China')");
9318     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CN', 'region', 'zh', '中国')");
9319
9320     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CZ', 'region', 'Czech Republic','2014-10-30')");
9321     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CZ', 'region', 'en', 'Czech Republic')");
9322     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CZ', 'region', 'cs', 'Česká republika')");
9323
9324     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'DE', 'region', 'Germany','2014-10-30')");
9325     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DE', 'region', 'en', 'Germany')");
9326     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DE', 'region', 'de', 'Deutschland')");
9327
9328     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DK', 'region', 'en', 'Denmark')");
9329
9330     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ES', 'region', 'Spain','2014-10-30')");
9331     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ES', 'region', 'en', 'Spain')");
9332     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ES', 'region', 'es', 'España')");
9333
9334     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'FI', 'region', 'Finland','2014-10-30')");
9335     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FI', 'region', 'en', 'Finland')");
9336     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FI', 'region', 'fi', 'Suomi')");
9337
9338     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'FO', 'region', 'Faroe Islands','2014-10-30')");
9339     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FO', 'region', 'en', 'Faroe Islands')");
9340     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FO', 'region', 'fo', 'Føroyar')");
9341
9342     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'GR', 'region', 'Greece','2014-10-30')");
9343     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'GR', 'region', 'en', 'Greece')");
9344     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'GR', 'region', 'el', 'Ελλάδα')");
9345
9346     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'HR', 'region', 'Croatia','2014-10-30')");
9347     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HR', 'region', 'en', 'Croatia')");
9348     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HR', 'region', 'hr', 'Hrvatska')");
9349
9350     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'HU', 'region', 'Hungary','2014-10-30')");
9351     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HU', 'region', 'en', 'Hungary')");
9352     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HU', 'region', 'hu', 'Magyarország')");
9353
9354     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ID', 'region', 'Indonesia','2014-10-30')");
9355     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ID', 'region', 'en', 'Indonesia')");
9356     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ID', 'region', 'id', 'Indonesia')");
9357
9358     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'IS', 'region', 'Iceland','2014-10-30')");
9359     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IS', 'region', 'en', 'Iceland')");
9360     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IS', 'region', 'is', 'Ísland')");
9361
9362     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'IT', 'region', 'Italy','2014-10-30')");
9363     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IT', 'region', 'en', 'Italy')");
9364     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IT', 'region', 'it', 'Italia')");
9365
9366     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'JP', 'region', 'Japan','2014-10-30')");
9367     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'JP', 'region', 'en', 'Japan')");
9368     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'JP', 'region', 'ja', '日本')");
9369
9370     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KE', 'region', 'Kenya','2014-10-30')");
9371     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KE', 'region', 'en', 'Kenya')");
9372     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KE', 'region', 'rw', 'Kenya')");
9373
9374     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KH', 'region', 'Cambodia','2014-10-30')");
9375     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KH', 'region', 'en', 'Cambodia')");
9376     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KH', 'region', 'km', 'កម្ពុជា')");
9377
9378     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KP', 'region', 'North Korea','2014-10-30')");
9379     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KP', 'region', 'en', 'North Korea')");
9380     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KP', 'region', 'ko', '조선민주주의인민공화국')");
9381
9382     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'LK', 'region', 'Sri Lanka','2014-10-30')");
9383     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'LK', 'region', 'en', 'Sri Lanka')");
9384     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'LK', 'region', 'ta', 'இலங்கை')");
9385
9386     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'MY', 'region', 'Malaysia','2014-10-30')");
9387     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'MY', 'region', 'en', 'Malaysia')");
9388     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'MY', 'region', 'ms', 'Malaysia')");
9389
9390     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NE', 'region', 'Niger','2014-10-30')");
9391     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NE', 'region', 'en', 'Niger')");
9392     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NE', 'region', 'ne', 'Niger')");
9393
9394     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NL', 'region', 'Netherlands','2014-10-30')");
9395     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NL', 'region', 'en', 'Netherlands')");
9396     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NL', 'region', 'nl', 'Nederland')");
9397
9398     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NO', 'region', 'Norway','2014-10-30')");
9399     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'en', 'Norway')");
9400     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'ne', 'Noreg')");
9401     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'nn', 'Noreg')");
9402
9403     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PH', 'region', 'Philippines','2014-10-30')");
9404     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PH', 'region', 'en', 'Philippines')");
9405     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PH', 'region', 'tl', 'Pilipinas')");
9406
9407     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PK', 'region', 'Pakistan','2014-10-30')");
9408     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PK', 'region', 'en', 'Pakistan')");
9409     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PK', 'region', 'sd', 'پاكستان')");
9410
9411     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PL', 'region', 'Poland','2014-10-30')");
9412     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PL', 'region', 'en', 'Poland')");
9413     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PL', 'region', 'pl', 'Polska')");
9414
9415     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PT', 'region', 'Portugal','2014-10-30')");
9416     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PT', 'region', 'en', 'Portugal')");
9417     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PT', 'region', 'pt', 'Portugal')");
9418
9419     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RO', 'region', 'Romania','2014-10-30')");
9420     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RO', 'region', 'en', 'Romania')");
9421     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RO', 'region', 'ro', 'România')");
9422
9423     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RU', 'region', 'Russia','2014-10-30')");
9424     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RU', 'region', 'en', 'Russia')");
9425     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RU', 'region', 'ru', 'Россия')");
9426
9427     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RW', 'region', 'Rwanda','2014-10-30')");
9428     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RW', 'region', 'en', 'Rwanda')");
9429     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RW', 'region', 'rw', 'Rwanda')");
9430
9431     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SE', 'region', 'Sweden','2014-10-30')");
9432     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SE', 'region', 'en', 'Sweden')");
9433     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SE', 'region', 'sv', 'Sverige')");
9434
9435     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SI', 'region', 'Slovenia','2014-10-30')");
9436     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SI', 'region', 'en', 'Slovenia')");
9437     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SI', 'region', 'sl', 'Slovenija')");
9438
9439     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SK', 'region', 'Slovakia','2014-10-30')");
9440     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SK', 'region', 'en', 'Slovakia')");
9441     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SK', 'region', 'sk', 'Slovensko')");
9442
9443     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TH', 'region', 'Thailand','2014-10-30')");
9444     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TH', 'region', 'en', 'Thailand')");
9445     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TH', 'region', 'th', 'ประเทศไทย')");
9446
9447     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TR', 'region', 'Turkey','2014-10-30')");
9448     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TR', 'region', 'en', 'Turkey')");
9449     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TR', 'region', 'tr', 'Türkiye')");
9450
9451     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TW', 'region', 'Taiwan','2014-10-30')");
9452     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TW', 'region', 'en', 'Taiwan')");
9453     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TW', 'region', 'zh', '台灣')");
9454
9455     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'UA', 'region', 'Ukraine','2014-10-30')");
9456     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'UA', 'region', 'en', 'Ukraine')");
9457     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'UA', 'region', 'uk', 'Україна')");
9458
9459     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'VN', 'region', 'Vietnam','2014-10-30')");
9460     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'VN', 'region', 'en', 'Vietnam')");
9461     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'VN', 'region', 'vi', 'Việt Nam')");
9462
9463     print "Upgrade to $DBversion done (Bug 12250: Update descriptions for languages, scripts and regions)\n";
9464     SetVersion($DBversion);
9465 }
9466
9467 $DBversion = "3.17.00.050";
9468 if ( CheckVersion($DBversion) ) {
9469     $dbh->do(q|
9470         INSERT INTO permissions (module_bit, code, description) VALUES
9471           (13, 'records_batchdel', 'Perform batch deletion of records (bibliographic or authority)')
9472     |);
9473     print "Upgrade to $DBversion done (Bug 12403: Add permission tools_records_batchdelitem)\n";
9474     SetVersion($DBversion);
9475 }
9476
9477 $DBversion = "3.17.00.051";
9478 if ( CheckVersion($DBversion) ) {
9479     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('GoogleIndicTransliteration','0','','GoogleIndicTransliteration on the OPAC.','YesNo')");
9480     print "Upgrade to $DBversion done (Bug 13211: Added system preferences GoogleIndicTransliteration on the OPAC)\n";
9481     SetVersion($DBversion);
9482 }
9483
9484 $DBversion = "3.17.00.052";
9485 if ( CheckVersion($DBversion) ) {
9486     $dbh->do(q{
9487         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');
9488     });
9489
9490     $dbh->do(q{
9491         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');
9492    });
9493    print "Upgrade to $DBversion done (Bug 9043: Add system preference OpacAdvSearchOptions and OpacAdvSearchMoreOptions)\n";
9494    SetVersion ($DBversion);
9495 }
9496
9497 $DBversion = "3.17.00.053";
9498 if ( CheckVersion($DBversion) ) {
9499     $dbh->do(q{
9500         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)');
9501     });
9502
9503     $dbh->do(q{
9504         INSERT INTO permissions (module_bit, code, description) VALUES ('9', 'delete_all_items', 'Delete all items at once');
9505     });
9506
9507     $dbh->do(q{
9508         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)');
9509     });
9510
9511     # The delete_all_items permission should be added to users having the edit_items permission.
9512     $dbh->do(q{
9513         INSERT INTO user_permissions (borrowernumber, module_bit, code) SELECT borrowernumber, module_bit, "delete_all_items" FROM user_permissions WHERE code="edit_items";
9514     });
9515
9516     # Add 2 new prefs
9517     $dbh->do(q{
9518         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');
9519     });
9520
9521     $dbh->do(q{
9522         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');
9523     });
9524
9525     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";
9526     SetVersion($DBversion);
9527 }
9528
9529 $DBversion = "3.17.00.054";
9530 if (CheckVersion($DBversion)) {
9531     $dbh->do(q{
9532         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
9533         ('AllowRenewalIfOtherItemsAvailable','0',NULL,'If enabled, allow a patron to renew an item with unfilled holds if other available items can fill that hold.','YesNo')
9534     });
9535     print "Upgrade to $DBversion done (Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds)\n";
9536     SetVersion($DBversion);
9537 }
9538
9539 $DBversion = "3.17.00.055";
9540 if ( CheckVersion($DBversion) ) {
9541     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBEnable', '0', NULL, 'Enable communication with the Norwegian national patron database.', 'YesNo')");
9542     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBEndpoint', '', NULL, 'Which NL endpoint to use.', 'Free')");
9543     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBUsername', '', NULL, 'Username for communication with the Norwegian national patron database.', 'Free')");
9544     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBPassword', '', NULL, 'Password for communication with the Norwegian national patron database.', 'Free')");
9545     $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')");
9546     $dbh->do("
9547 CREATE TABLE borrower_sync (
9548     borrowersyncid int(11) NOT NULL AUTO_INCREMENT,
9549     borrowernumber int(11) NOT NULL,
9550     synctype varchar(32) NOT NULL,
9551     sync tinyint(1) NOT NULL DEFAULT '0',
9552     syncstatus varchar(10) DEFAULT NULL,
9553     lastsync varchar(50) DEFAULT NULL,
9554     hashed_pin varchar(64) DEFAULT NULL,
9555     PRIMARY KEY (borrowersyncid),
9556     KEY borrowernumber (borrowernumber),
9557     CONSTRAINT borrower_sync_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
9558 ) ENGINE=InnoDB DEFAULT CHARSET=utf8"
9559 );
9560     print "Upgrade to $DBversion done (Bug 11401 - Add support for Norwegian national library card)\n";
9561     SetVersion($DBversion);
9562 }
9563
9564 $DBversion = "3.17.00.056";
9565 if ( CheckVersion($DBversion) ) {
9566     $dbh->do(q{
9567         UPDATE systempreferences SET value = 'pubdate,itemtype,language,sorting,location' WHERE variable='OpacAdvSearchOptions'
9568     });
9569
9570     $dbh->do(q{
9571         UPDATE systempreferences SET value = 'pubdate,itemtype,language,subtype,sorting,location' WHERE variable='OpacAdvSearchMoreOptions'
9572     });
9573
9574     print "Upgrade to $DBversion done (Bug 9043 - Update the values for OpacAdvSearchOptions and OpacAdvSearchOptions)\n";
9575     SetVersion($DBversion);
9576 }
9577
9578 $DBversion = "3.17.00.057";
9579 if ( CheckVersion($DBversion) ) {
9580     print "Upgrade to $DBversion done (Koha 3.18 beta)\n";
9581     SetVersion ($DBversion);
9582 }
9583
9584 $DBversion = "3.17.00.058";
9585 if( CheckVersion($DBversion) ){
9586     $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')");
9587     $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')");
9588     $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')");
9589     print "Upgrade to $DBversion done (Bug 8337: System preferences for longoverdue cron)\n";
9590     SetVersion($DBversion);
9591 }
9592
9593 $DBversion = "3.17.00.059";
9594 if ( CheckVersion($DBversion) ) {
9595     $dbh->do(q{
9596         UPDATE permissions SET description = "Add and delete budgets (but can't modifiy budgets)" WHERE description = "Add and delete budgets (but cant modify budgets)";
9597     });
9598     print "Upgrade to $DBversion done (Bug 10749: Fix typo in budget_add_del permission description)\n";
9599     SetVersion ($DBversion);
9600 }
9601
9602 $DBversion = "3.17.00.060";
9603 if ( CheckVersion($DBversion) ) {
9604     my $count_l = $dbh->selectcol_arrayref(q|
9605         SELECT COUNT(*) FROM letter WHERE message_transport_type='feed'
9606     |);
9607     my $count_mq = $dbh->selectcol_arrayref(q|
9608         SELECT COUNT(*) FROM message_queue WHERE message_transport_type='feed'
9609     |);
9610     my $count_ott = $dbh->selectcol_arrayref(q|
9611         SELECT COUNT(*) FROM overduerules_transport_types WHERE message_transport_type='feed'
9612     |);
9613     my $count_mt = $dbh->selectcol_arrayref(q|
9614         SELECT COUNT(*) FROM message_transports WHERE message_transport_type='feed'
9615     |);
9616     my $count_bmtp = $dbh->selectcol_arrayref(q|
9617         SELECT COUNT(*) FROM borrower_message_transport_preferences WHERE message_transport_type='feed'
9618     |);
9619
9620     my $deleted = 0;
9621     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 ) {
9622         $deleted = $dbh->do(q|
9623             DELETE FROM message_transport_types where message_transport_type='feed'
9624         |);
9625         $deleted = $deleted ne '0E0' ? 1 : 0;
9626     }
9627
9628     print "Upgrade to $DBversion done (Bug 12298: Delete the 'feed' message transport type " . ($deleted ? '(deleted!)' : '(not deleted)') . ")\n";
9629     SetVersion($DBversion);
9630 }
9631
9632 $DBversion = "3.18.00.000";
9633 if ( CheckVersion($DBversion) ) {
9634     print "Upgrade to $DBversion done (3.18.0 release)\n";
9635     SetVersion($DBversion);
9636 }
9637
9638 $DBversion = "3.19.00.000";
9639 if ( CheckVersion($DBversion) ) {
9640     print "Upgrade to $DBversion done (there's life after 3.18)\n";
9641     SetVersion ($DBversion);
9642 }
9643
9644 $DBversion = "3.19.00.001";
9645 if ( CheckVersion($DBversion) ) {
9646     $dbh->do("
9647         UPDATE systempreferences
9648         SET options = 'public|school|academic|research|private|societyAssociation|corporate|government|religiousOrg|subscription'
9649         WHERE variable = 'UsageStatsLibraryType'
9650     ");
9651     if ( C4::Context->preference("UsageStatsLibraryType") eq "university" ) {
9652         C4::Context->set_preference("UsageStatsLibraryType", "academic")
9653     }
9654     print "Upgrade to $DBversion done (Bug 13436: Add more options to UsageStatsLibraryType)\n";
9655     SetVersion ($DBversion);
9656 }
9657
9658 $DBversion = "3.19.00.002";
9659 if ( CheckVersion($DBversion) ) {
9660     $dbh->do(q|
9661         UPDATE suggestions SET branchcode="" WHERE branchcode="__ANY__"
9662     |);
9663     print "upgrade to $DBversion done (Bug 10753: replace __ANY__ with empty string in suggestions.branchcode)\n";
9664     SetVersion ($DBversion);
9665 }
9666
9667 $DBversion = "3.19.00.003";
9668 if ( CheckVersion($DBversion) ) {
9669     my ($count) = $dbh->selectrow_array("SELECT COUNT(*) FROM borrowers GROUP BY userid HAVING COUNT(userid) > 1");
9670
9671     if ( $count ) {
9672         print "Upgrade to $DBversion done (Bug 1861 - Unique patrons logins not (totally) enforced) FAILED!\n";
9673         print "Your database has users with duplicate user logins. Please have your administrator deduplicate your user logins.\n";
9674         print "Afterward, your Koha administrator should execute the following database query: ALTER TABLE borrowers DROP INDEX userid, ADD UNIQUE userid (userid)";
9675     } else {
9676         $dbh->do(q{
9677             ALTER TABLE borrowers
9678                 DROP INDEX userid ,
9679                 ADD UNIQUE userid (userid)
9680         });
9681         print "Upgrade to $DBversion done (Bug 1861: Unique patrons logins not (totally) enforced)\n";
9682     }
9683     SetVersion ($DBversion);
9684 }
9685
9686 $DBversion = "3.19.00.004";
9687 if ( CheckVersion($DBversion) ) {
9688     my $pref_value = C4::Context->preference('OpacExportOptions');
9689     $pref_value =~ s/\|/,/g; # multiple is separated by ,
9690     $dbh->do(q{
9691         UPDATE systempreferences
9692             SET value = ?,
9693                 type = 'multiple'
9694         WHERE variable = 'OpacExportOptions'
9695     }, {}, $pref_value );
9696     print "Upgrade to $DBversion done (Bug 13346: OpacExportOptions is now multiple)\n";
9697     SetVersion ($DBversion);
9698 }
9699
9700 $DBversion = "3.19.00.005";
9701 if(CheckVersion($DBversion)) {
9702     $dbh->do(q{
9703         ALTER TABLE authorised_values MODIFY COLUMN category VARCHAR(32) NOT NULL DEFAULT ''
9704     });
9705
9706     $dbh->do(q{
9707         ALTER TABLE borrower_attribute_types MODIFY COLUMN authorised_value_category VARCHAR(32) DEFAULT NULL
9708     });
9709
9710     print "Upgrade to $DBversion done (Bug 13379: Modify authorised_values.category to varchar(32))\n";
9711     SetVersion($DBversion);
9712 }
9713
9714 $DBversion = "3.19.00.006";
9715 if ( CheckVersion($DBversion) ) {
9716     $dbh->do(q|SET foreign_key_checks = 0|);
9717     my $sth = $dbh->table_info( '','','','TABLE' );
9718     my ( $cat, $schema, $name, $type, $remarks );
9719     while ( ( $cat, $schema, $name, $type, $remarks ) = $sth->fetchrow_array ) {
9720         my $table_sth = $dbh->prepare(qq|SHOW CREATE TABLE $name|);
9721         $table_sth->execute;
9722         my @table = $table_sth->fetchrow_array;
9723         unless ( $table[1] =~ /COLLATE=utf8mb4_unicode_ci/ ) { #catches utf8mb4 collated tables
9724             if ( $name eq 'marc_subfield_structure' ) {
9725                 $dbh->do(q|
9726                     ALTER TABLE marc_subfield_structure
9727                     MODIFY COLUMN tagfield varchar(3) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9728                     MODIFY COLUMN tagsubfield varchar(1) COLLATE utf8_bin NOT NULL DEFAULT '',
9729                     MODIFY COLUMN liblibrarian varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9730                     MODIFY COLUMN libopac varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9731                     MODIFY COLUMN kohafield varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
9732                     MODIFY COLUMN authorised_value varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
9733                     MODIFY COLUMN authtypecode varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
9734                     MODIFY COLUMN value_builder varchar(80) COLLATE utf8_unicode_ci DEFAULT NULL,
9735                     MODIFY COLUMN frameworkcode varchar(4) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9736                     MODIFY COLUMN seealso varchar(1100) COLLATE utf8_unicode_ci DEFAULT NULL,
9737                     MODIFY COLUMN link varchar(80) COLLATE utf8_unicode_ci DEFAULT NULL
9738                 |);
9739                 $dbh->do(qq|ALTER TABLE $name CHARACTER SET utf8 COLLATE utf8_unicode_ci|);
9740             }
9741             else {
9742                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci|);
9743             }
9744         }
9745     }
9746     $dbh->do(q|SET foreign_key_checks = 1|);;
9747
9748     print "Upgrade to $DBversion done (Bug 11944: Convert DB tables to utf8_unicode_ci)\n";
9749     SetVersion($DBversion);
9750 }
9751
9752 $DBversion = "3.19.00.007";
9753 if ( CheckVersion($DBversion) ) {
9754     my $orphan_budgets = $dbh->selectall_arrayref(q|
9755         SELECT budget_id, budget_name, budget_code
9756         FROM aqbudgets
9757         WHERE   budget_parent_id IS NOT NULL
9758             AND budget_parent_id NOT IN (
9759                 SELECT DISTINCT budget_id FROM aqbudgets
9760             )
9761     |, { Slice => {} } );
9762
9763     if ( @$orphan_budgets ) {
9764         for my $b ( @$orphan_budgets ) {
9765             print "Fund $b->{budget_name} (code:$b->{budget_code}, id:$b->{budget_id}) does not have a parent, it may cause problem\n";
9766         }
9767         print "Upgrade to $DBversion done (Bug 12905: Check budget integrity: FAIL)\n";
9768     } else {
9769         print "Upgrade to $DBversion done (Bug 12905: Check budget integrity: OK)\n";
9770     }
9771     SetVersion ($DBversion);
9772 }
9773
9774 $DBversion = "3.19.00.008";
9775 if ( CheckVersion($DBversion) ) {
9776     my $number_of_orders_not_linked = $dbh->selectcol_arrayref(q|
9777         SELECT COUNT(*)
9778         FROM aqorders o
9779         WHERE NOT EXISTS (
9780             SELECT NULL
9781             FROM aqbudgets b
9782             WHERE b.budget_id = o.budget_id
9783         );
9784     |);
9785
9786     if ( $number_of_orders_not_linked->[0] > 0 ) {
9787         $dbh->do(q|
9788             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)
9789         |);
9790         my $budget_period_id = $dbh->last_insert_id( undef, undef, 'aqbudgetperiods', undef );
9791         $dbh->do(qq|
9792             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 );
9793         |);
9794         my $budget_id = $dbh->last_insert_id( undef, undef, 'aqbudgets', undef );
9795         $dbh->do(qq|
9796             UPDATE aqorders o
9797             SET budget_id = $budget_id
9798             WHERE NOT EXISTS (
9799                 SELECT NULL
9800                 FROM aqbudgets b
9801                 WHERE b.budget_id = o.budget_id
9802             )
9803         |);
9804     }
9805
9806     $dbh->do(q|
9807         ALTER TABLE aqorders
9808         ADD CONSTRAINT aqorders_budget_id_fk FOREIGN KEY (budget_id) REFERENCES aqbudgets(budget_id) ON DELETE CASCADE ON UPDATE CASCADE
9809     |);
9810
9811     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";
9812     SetVersion($DBversion);
9813 }
9814
9815 $DBversion = "3.19.00.009";
9816 if ( CheckVersion($DBversion) ) {
9817     $dbh->do(q|
9818         UPDATE suggestions s SET s.budgetid = NULL
9819         WHERE NOT EXISTS (
9820             SELECT NULL
9821             FROM aqbudgets b
9822             WHERE b.budget_id = s.budgetid
9823         );
9824     |);
9825
9826     $dbh->do(q|
9827         ALTER TABLE suggestions
9828         ADD CONSTRAINT suggestions_budget_id_fk FOREIGN KEY (budgetid) REFERENCES aqbudgets(budget_id) ON DELETE SET NULL ON UPDATE CASCADE
9829     |);
9830
9831     print "Upgrade to $DBversion done (Bug 13007: Add new foreign key suggestions.budgetid)\n";
9832     SetVersion($DBversion);
9833 }
9834
9835 $DBversion = "3.19.00.010";
9836 if ( CheckVersion($DBversion) ) {
9837     $dbh->do(q|
9838         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
9839         VALUES('SessionRestrictionByIP','1','Check for Change in  Remote IP address for Session Security. Disable when remote ip address changes frequently.','','YesNo')
9840     |);
9841     print "Upgrade to $DBversion done (Bug 5511: SessionRestrictionByIP)\n";
9842     SetVersion ($DBversion);
9843 }
9844
9845 $DBversion = "3.19.00.011";
9846 if ( CheckVersion($DBversion) ) {
9847     $dbh->do(q|
9848         INSERT INTO userflags (bit, flag, flagdesc, defaulton) VALUES
9849         (20, 'lists', 'Lists', 0)
9850     |);
9851     $dbh->do(q|
9852         INSERT INTO permissions (module_bit, code, description) VALUES
9853         (20, 'delete_public_lists', 'Delete public lists')
9854     |);
9855     print "Upgrade to $DBversion done (Bug 13417: Add permission to delete public lists)\n";
9856     SetVersion ($DBversion);
9857 }
9858
9859 $DBversion = "3.19.00.012";
9860 if(CheckVersion($DBversion)) {
9861     $dbh->do(q{
9862         ALTER TABLE biblioitems MODIFY COLUMN marcxml longtext
9863     });
9864
9865     $dbh->do(q{
9866         ALTER TABLE deletedbiblioitems MODIFY COLUMN marcxml longtext
9867     });
9868
9869     print "Upgrade to $DBversion done (Bug 13523 Remove NOT NULL restriction on field marcxml due to mysql STRICT_TRANS_TABLES)\n";
9870     SetVersion ($DBversion);
9871 }
9872
9873 $DBversion = "3.19.00.013";
9874 if ( CheckVersion($DBversion) ) {
9875     $dbh->do(q|
9876         INSERT INTO permissions (module_bit, code, description) VALUES
9877           (13, 'records_batchmod', 'Perform batch modification of records (biblios or authorities)')
9878     |);
9879     print "Upgrade to $DBversion done (Bug 11395: Add permission tools_records_batchmod)\n";
9880     SetVersion($DBversion);
9881 }
9882
9883 $DBversion = "3.19.00.014";
9884 if ( CheckVersion($DBversion) ) {
9885     $dbh->do(q|
9886         CREATE TABLE aqorder_users (
9887             ordernumber int(11) NOT NULL,
9888             borrowernumber int(11) NOT NULL,
9889             PRIMARY KEY (ordernumber, borrowernumber),
9890             CONSTRAINT aqorder_users_ibfk_1 FOREIGN KEY (ordernumber) REFERENCES aqorders (ordernumber) ON DELETE CASCADE ON UPDATE CASCADE,
9891             CONSTRAINT aqorder_users_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
9892         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
9893     |);
9894
9895     $dbh->do(q|
9896         INSERT INTO letter(module, code, branchcode, name, title, content, message_transport_type)
9897         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')
9898     |);
9899     print "Upgrade to $DBversion done (Bug 12648: Add letter ACQ_NOTIF_ON_RECEIV )\n";
9900     SetVersion ($DBversion);
9901 }
9902
9903 $DBversion = "3.19.00.015";
9904 if ( CheckVersion($DBversion) ) {
9905     $dbh->do(q|
9906         ALTER TABLE search_history ADD COLUMN id INT(11) NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY(id);
9907     |);
9908     print "Upgrade to $DBversion done (Bug 11430: Add primary key for search_history)\n";
9909     SetVersion ($DBversion);
9910 }
9911
9912 $DBversion = "3.19.00.016";
9913 if(CheckVersion($DBversion)) {
9914     my @order_cancellation_reason = $dbh->selectrow_array("SELECT count(*) FROM authorised_values WHERE category='ORDER_CANCELLATION_REASON'");
9915     if ($order_cancellation_reason[0] == 0) {
9916         $dbh->do(q{
9917             INSERT INTO authorised_values (category, authorised_value, lib) VALUES
9918              ('ORDER_CANCELLATION_REASON', 0, 'No reason provided'),
9919              ('ORDER_CANCELLATION_REASON', 1, 'Out of stock'),
9920              ('ORDER_CANCELLATION_REASON', 2, 'Restocking')
9921         });
9922
9923         my $already_existing_reasons = $dbh->selectcol_arrayref(q{
9924             SELECT DISTINCT( cancellationreason )
9925             FROM aqorders;
9926         }, { Slice => {} });
9927
9928         my $update_orders_sth = $dbh->prepare(q{
9929             UPDATE aqorders
9930             SET cancellationreason = ?
9931             WHERE cancellationreason = ?
9932         });
9933
9934         my $insert_av_sth = $dbh->prepare(q{
9935             INSERT INTO authorised_values (category, authorised_value, lib) VALUES
9936              ('ORDER_CANCELLATION_REASON', ?, ?)
9937         });
9938         my $i = 3;
9939         for my $reason ( @$already_existing_reasons ) {
9940             next unless $reason;
9941             $insert_av_sth->execute( $i, $reason );
9942             $update_orders_sth->execute( $i, $reason );
9943             $i++;
9944         }
9945         print "Upgrade to $DBversion done (Bug 13380: Add the ORDER_CANCELLATION_REASON authorised value)\n";
9946     }
9947     else {
9948         print "Upgrade to $DBversion done (Bug 13380: ORDER_CANCELLATION_REASON authorised value already existed from earlier update!)\n";
9949     }
9950
9951     SetVersion($DBversion);
9952 }
9953
9954 $DBversion = '3.19.00.017';
9955 if ( CheckVersion($DBversion) ) {
9956     # First create the column
9957     $dbh->do("ALTER TABLE issuingrules ADD onshelfholds tinyint(1) default 0 NOT NULL");
9958     # Now update the column
9959     if (C4::Context->preference("AllowOnShelfHolds")){
9960         # Pref is on, set allow for all rules
9961         $dbh->do("UPDATE issuingrules SET onshelfholds=1");
9962     } else {
9963         # If the preference is not set, leave off
9964         $dbh->do("UPDATE issuingrules SET onshelfholds=0");
9965     }
9966     # Remove from the systempreferences table
9967     $dbh->do("DELETE FROM systempreferences WHERE variable = 'AllowOnShelfHolds'");
9968
9969     # First create the column
9970     $dbh->do("ALTER TABLE issuingrules ADD opacitemholds char(1) DEFAULT 'N' NOT NULL");
9971     # Now update the column
9972     my $opacitemholds = C4::Context->preference("OPACItemHolds") || '';
9973     if (lc ($opacitemholds) eq 'force') {
9974         $opacitemholds = 'F';
9975     }
9976     else {
9977         $opacitemholds = $opacitemholds ? 'Y' : 'N';
9978     }
9979     # Set allow for all rules
9980     $dbh->do("UPDATE issuingrules SET opacitemholds='$opacitemholds'");
9981
9982     # Remove from the systempreferences table
9983     $dbh->do("DELETE FROM systempreferences WHERE variable = 'OPACItemHolds'");
9984
9985     print "Upgrade to $DBversion done (Bug 5786: Move AllowOnShelfHolds to circulation matrix; Move OPACItemHolds system preference to circulation matrix)\n";
9986     SetVersion ($DBversion);
9987 }
9988
9989
9990 $DBversion = "3.19.00.018";
9991 if ( CheckVersion($DBversion) ) {
9992     $dbh->do(q|
9993         UPDATE systempreferences set variable="OpacAdditionalStylesheet" WHERE variable="opaccolorstylesheet"
9994     |);
9995     print "Upgrade to $DBversion done (Bug 10328: Rename opaccolorstylesheet to OpacAdditionalStylesheet\n";
9996     SetVersion ($DBversion);
9997 }
9998
9999 $DBversion = "3.19.00.019";
10000 if ( CheckVersion($DBversion) ) {
10001     $dbh->do(q{
10002         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
10003         VALUES('Coce','0', 'If on, enables cover retrieval from the configured Coce server', NULL, 'YesNo')
10004     });
10005     $dbh->do(q{
10006         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
10007         VALUES('CoceHost', NULL, 'Coce server URL', NULL,'Free')
10008     });
10009     $dbh->do(q{
10010         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
10011         VALUES('CoceProviders', NULL, 'Coce providers', 'aws,gb,ol', 'multiple')
10012     });
10013     print "Upgrade to $DBversion done (Bug 9580: Cover image from Coce, a remote image URL cache)\n";
10014     SetVersion($DBversion);
10015 }
10016
10017 $DBversion = "3.19.00.020";
10018 if ( CheckVersion($DBversion) ) {
10019     $dbh->do(q|
10020         ALTER TABLE aqorders DROP COLUMN supplierreference;
10021     |);
10022
10023     print "Upgrade to $DBversion done (Bug 11008: DROP column aqorders.supplierreference)\n";
10024     SetVersion($DBversion);
10025 }
10026
10027 $DBversion = "3.19.00.021";
10028 if ( CheckVersion($DBversion) ) {
10029     $dbh->do(q|
10030         ALTER TABLE issues DROP COLUMN issuingbranch
10031     |);
10032     $dbh->do(q|
10033         ALTER TABLE old_issues DROP COLUMN issuingbranch
10034     |);
10035     print "Upgrade to $DBversion done (Bug 2806: Remove issuingbranch columns)\n";
10036     SetVersion ($DBversion);
10037 }
10038
10039 $DBversion = '3.19.00.022';
10040 if ( CheckVersion($DBversion) ) {
10041     $dbh->do(q{
10042         ALTER TABLE suggestions DROP COLUMN mailoverseeing;
10043     });
10044     print "Upgrade to $DBversion done (Bug 13006: Drop column suggestion.mailoverseeing)\n";
10045     SetVersion($DBversion);
10046 }
10047
10048 $DBversion = "3.19.00.023";
10049 if ( CheckVersion($DBversion) ) {
10050     $dbh->do(q|
10051         DELETE FROM systempreferences where variable = 'AddPatronLists'
10052     |);
10053     print "Upgrade to $DBversion done (Bug 13497: Remove the AddPatronLists system preferences)\n";
10054     SetVersion ($DBversion);
10055 }
10056
10057 $DBversion = "3.19.00.024";
10058 if ( CheckVersion($DBversion) ) {
10059     $dbh->do(qq|DROP table patroncards;|);
10060     print "Upgrade to $DBversion done (Bug 13539: Remove table patroncards from database as it's no longer in use)\n";
10061     SetVersion ($DBversion);
10062 }
10063
10064 $DBversion = "3.19.00.025";
10065 if ( CheckVersion($DBversion) ) {
10066     $dbh->do(q|
10067         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
10068         ('SearchWithISBNVariations','0',NULL,'If enabled, search on all variations of the ISBN','YesNo')
10069     |);
10070     print "Upgrade to $DBversion done (Bug 13528: Add the SearchWithISBNVariations syspref)\n";
10071     SetVersion ($DBversion);
10072 }
10073
10074 $DBversion = "3.19.00.026";
10075 if( CheckVersion($DBversion) ) {
10076     if ( C4::Context->preference('marcflavour') eq 'MARC21' ) {
10077     $dbh->do(q{
10078         INSERT IGNORE INTO auth_tag_structure (authtypecode, tagfield, liblibrarian, libopac, repeatable, mandatory, authorised_value) VALUES
10079         ('', '388', 'TIME PERIOD OF CREATION', 'TIME PERIOD OF CREATION', 1, 0, NULL);
10080     });
10081
10082     $dbh->do(q{
10083         INSERT IGNORE INTO auth_subfield_structure (authtypecode, tagfield, tagsubfield, liblibrarian, libopac, repeatable,
10084         mandatory, tab, authorised_value, value_builder, seealso, isurl, hidden, linkid, kohafield, frameworkcode) VALUES
10085         ('', '388', '0', 'Authority record control number or standard number', 'Authority record control number or standard number', 1, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10086         ('', '388', '2', 'Source of term', 'Source of term', 0, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10087         ('', '388', '3', 'Materials specified', 'Materials specified', 0, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10088         ('', '388', '6', 'Linkage', 'Linkage', 0, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10089         ('', '388', '8', 'Field link and sequence number', 'Field link and sequence number', 1, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10090         ('', '388', 'a', 'Time period of creation term', 'Time period of creation term', 1, 0, 3, NULL, NULL, NULL, 0, 0, '', '', '');
10091     });
10092
10093     $dbh->do(q{
10094         UPDATE IGNORE auth_subfield_structure SET repeatable = 1 WHERE tagsubfield = 'g' AND tagfield IN
10095         ('100','110','111','130','400','410','411','430','500','510','511','530','700','710','730');
10096     });
10097
10098     $dbh->do(q{
10099         INSERT IGNORE INTO auth_subfield_structure (authtypecode, tagfield, tagsubfield, liblibrarian, libopac, repeatable,
10100         mandatory, tab, authorised_value, value_builder, seealso, isurl, hidden, linkid, kohafield, frameworkcode) VALUES
10101         ('', '150', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 1, NULL, NULL, NULL, 0, 0, '', '', ''),
10102         ('', '151', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 1, NULL, NULL, NULL, 0, 0, '', '', ''),
10103         ('', '450', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 4, NULL, NULL, NULL, 0, 0, '', '', ''),
10104         ('', '451', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 4, NULL, NULL, NULL, 0, 0, '', '', ''),
10105         ('', '550', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 5, NULL, NULL, NULL, 0, 0, '', '', ''),
10106         ('', '551', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 5, NULL, NULL, NULL, 0, 0, '', '', ''),
10107         ('', '750', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10108         ('', '751', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10109         ('', '748', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10110         ('', '755', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10111         ('', '780', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10112         ('', '781', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10113         ('', '782', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10114         ('', '785', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10115         ('', '710', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10116         ('', '730', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10117         ('', '748', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10118         ('', '750', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10119         ('', '751', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10120         ('', '755', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10121         ('', '762', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10122         ('', '780', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10123         ('', '781', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10124         ('', '782', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10125         ('', '785', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10126         ('', '788', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', '');
10127     });
10128
10129     $dbh->do(q{
10130         UPDATE IGNORE auth_subfield_structure SET liblibrarian = 'Relationship information', libopac = 'Relationship information'
10131         WHERE tagsubfield = 'i' AND tagfield IN ('700','710','730','750','751','762');
10132     });
10133
10134     $dbh->do(q{
10135         UPDATE IGNORE auth_subfield_structure SET liblibrarian = 'Relationship code', libopac = 'Relationship code'
10136         WHERE tagsubfield = '4' AND tagfield IN ('700','710');
10137     });
10138
10139     $dbh->do(q{
10140         INSERT IGNORE INTO marc_tag_structure (tagfield, liblibrarian, libopac, repeatable, mandatory, authorised_value, frameworkcode) VALUES
10141         ('370', 'ASSOCIATED PLACE', 'ASSOCIATED PLACE', 1, 0, NULL, ''),
10142         ('388', 'TIME PERIOD OF CREATION', 'TIME PERIOD OF CREATION', 1, 0, NULL, '');
10143     });
10144
10145     $dbh->do(q{
10146         INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian, libopac, repeatable, mandatory,
10147         kohafield, tab, authorised_value, authtypecode, value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
10148         ('370', '0', 'Authority record control number or standard number', 'Authority record control number or standard number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10149         ('370', '2', 'Source of term', 'Source of term', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10150         ('370', '6', 'Linkage', 'Linkage', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10151         ('370', '8', 'Field link and sequence number', 'Field link and sequence number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10152         ('370', 'c', 'Associated country', 'Associated country', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10153         ('370', 'f', 'Other associated place', 'Other associated place', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10154         ('370', 'g', 'Place of origin of work', 'Place of origin of work', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10155         ('370', 's', 'Start period', 'Start period', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10156         ('370', 't', 'End period', 'End period', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10157         ('370', 'u', 'Uniform Resource Identifier', 'Uniform Resource Identifier', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10158         ('370', 'v', 'Source of information', 'Source of information', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10159         ('377', 'l', 'Language term', 'Language term', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10160         ('382', 's', 'Total number of performers', 'Total number of performers', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10161         ('388', '0', 'Authority record control number or standard number', 'Authority record control number or standard number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10162         ('388', '2', 'Source of term', 'Source of term', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10163         ('388', '3', ' Materials specified', ' Materials specified', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10164         ('388', '6', ' Linkage', ' Linkage', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10165         ('388', '8', 'Field link and sequence number', 'Field link and sequence number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10166         ('388', 'a', 'Time period of creation term', 'Time period of creation term', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10167         ('650', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, '', 6, '', '', '', 0, -1, '', '', '', NULL),
10168         ('651', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, '', 6, '', '', '', 0, -1, '', '', '', NULL);
10169     });
10170
10171     $dbh->do(q{
10172         UPDATE IGNORE marc_subfield_structure SET repeatable = 1 WHERE tagsubfield = 'g' AND
10173         tagfield IN ('100','110','111','130','240','243','246','247','600','610','611','630','700','710','711','730','800','810','811','830');
10174     });
10175     }
10176
10177     print "Upgrade to $DBversion done (Bug 13322: Update MARC21 frameworks to Update No. 19 - October 2014)\n";
10178     SetVersion($DBversion);
10179 }
10180
10181 $DBversion = '3.19.00.027';
10182 if ( CheckVersion($DBversion) ) {
10183     $dbh->do("ALTER TABLE items ADD COLUMN itemnotes_nonpublic MEDIUMTEXT AFTER itemnotes");
10184     $dbh->do("ALTER TABLE deleteditems ADD COLUMN itemnotes_nonpublic MEDIUMTEXT AFTER itemnotes");
10185     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";
10186     SetVersion($DBversion);
10187 }
10188
10189 $DBversion = "3.19.00.028";
10190 if( CheckVersion($DBversion) ) {
10191     eval {
10192         local $dbh->{PrintError} = 0;
10193         $dbh->do(q{
10194             ALTER TABLE issues DROP PRIMARY KEY
10195         });
10196     };
10197
10198     $dbh->do(q{
10199         ALTER TABLE old_issues ADD issue_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10200     });
10201
10202     $dbh->do(q{
10203         ALTER TABLE old_issues CHANGE issue_id issue_id INT( 11 ) NOT NULL
10204     });
10205
10206     $dbh->do(q{
10207         ALTER TABLE issues ADD issue_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10208     });
10209
10210     $dbh->do(q{
10211         UPDATE issues SET issue_id = issue_id + ( SELECT COUNT(*) FROM old_issues ) ORDER BY issue_id DESC
10212     });
10213
10214     my $max_issue_id = $schema->resultset('Issue')->get_column('issue_id')->max();
10215     if ($max_issue_id) {
10216         $max_issue_id++;
10217         $dbh->do(qq{
10218             ALTER TABLE issues AUTO_INCREMENT = $max_issue_id
10219         });
10220     }
10221
10222     print "Upgrade to $DBversion done (Bug 13790: Add unique id issue_id to issues and oldissues tables)\n";
10223     SetVersion($DBversion);
10224 }
10225
10226 $DBversion = "3.19.00.029";
10227 if ( CheckVersion($DBversion) ) {
10228     $dbh->do(q|
10229          ALTER TABLE sessions CHANGE COLUMN a_session a_session MEDIUMTEXT
10230     |);
10231     print "Upgrade to $DBversion done (Bug 13606: Upgrade sessions.a_session to MEDIUMTEXT)\n";
10232     SetVersion($DBversion);
10233 }
10234
10235 $DBversion = "3.19.00.030";
10236 if ( CheckVersion($DBversion) ) {
10237     $dbh->do(q|
10238 UPDATE language_subtag_registry SET subtag = 'kn' WHERE subtag = 'ka' AND description = 'Kannada';
10239     |);
10240     $dbh->do(q|
10241 UPDATE language_rfc4646_to_iso639 SET rfc4646_subtag = 'kn' WHERE rfc4646_subtag = 'ka' AND iso639_2_code = 'kan';
10242     |);
10243     $dbh->do(q|
10244 UPDATE language_descriptions SET subtag = 'kn', lang = 'kn' WHERE subtag = 'ka' AND lang = 'ka' AND description = 'ಕನ್ನಡ';
10245     |);
10246     $dbh->do(q|
10247 UPDATE language_descriptions SET subtag = 'kn' WHERE subtag = 'ka' AND description = 'Kannada';
10248     |);
10249     $dbh->do(q|
10250 INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ka', 'language', 'Georgian','2015-04-20');
10251     |);
10252     $dbh->do(q|
10253 DELETE FROM language_subtag_registry
10254        WHERE NOT id IN
10255          (SELECT id FROM
10256            (SELECT MIN(id) as id,subtag,type,description,added
10257             FROM language_subtag_registry
10258             GROUP BY subtag,type,description,added)
10259            AS subtable);
10260     |);
10261     $dbh->do(q|
10262 INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ka', 'geo');
10263     |);
10264     $dbh->do(q|
10265 DELETE FROM language_rfc4646_to_iso639
10266        WHERE NOT id IN
10267          (SELECT id FROM
10268            (SELECT MIN(id) as id,rfc4646_subtag,iso639_2_code
10269             FROM language_rfc4646_to_iso639
10270             GROUP BY rfc4646_subtag,iso639_2_code)
10271            AS subtable);
10272     |);
10273     $dbh->do(q|
10274 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'ka', 'ქართული');
10275     |);
10276     $dbh->do(q|
10277 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'en', 'Georgian');
10278     |);
10279     $dbh->do(q|
10280 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'fr', 'Géorgien');
10281     |);
10282     $dbh->do(q|
10283 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'de', 'Georgisch');
10284     |);
10285     $dbh->do(q|
10286 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'es', 'Georgiano');
10287     |);
10288     $dbh->do(q|
10289 DELETE FROM language_descriptions
10290        WHERE NOT id IN
10291          (SELECT id FROM
10292            (SELECT MIN(id) as id,subtag,type,lang,description
10293             FROM language_descriptions GROUP BY subtag,type,lang,description)
10294            AS subtable);
10295     |);
10296     print "Upgrade to $DBversion done (Bug 14030: Add Georgian language and fix Kannada language code)\n";
10297     SetVersion($DBversion);
10298 }
10299
10300 $DBversion = "3.19.00.031";
10301 if ( CheckVersion($DBversion) ) {
10302     $dbh->do(q{
10303         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10304         VALUES('IdRef','0','Disable/enable the IdRef webservice from the OPAC detail page.',NULL,'YesNo')
10305     });
10306     print "Upgrade to $DBversion done (Bug 8992: Add system preference IdRef))\n";
10307     SetVersion($DBversion);
10308 }
10309
10310 $DBversion = "3.19.00.032";
10311 if ( CheckVersion($DBversion) ) {
10312     $dbh->do(q|
10313         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10314         VALUES('AddressFormat','us','Choose format to display postal addresses','','Choice')
10315     |);
10316     print "Upgrade to $DBversion done (Bug 4041: Address Format as a I18N/L10N system preference\n";
10317     SetVersion ($DBversion);
10318 }
10319
10320 $DBversion = "3.19.00.033";
10321 if ( CheckVersion($DBversion) ) {
10322     $dbh->do(q|
10323         ALTER TABLE auth_header
10324         CHANGE COLUMN datemodified modification_time TIMESTAMP NOT NULL default CURRENT_TIMESTAMP
10325     |);
10326     $dbh->do(q|
10327         ALTER TABLE auth_header
10328         CHANGE COLUMN modification_time modification_time TIMESTAMP NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP
10329     |);
10330     print "Upgrade to $DBversion done (Bug 11165: Update auth_header.datemodified when updated)\n";
10331     SetVersion ($DBversion);
10332 }
10333
10334 $DBversion = "3.19.00.034";
10335 if ( CheckVersion($DBversion) ) {
10336     $dbh->do(q|
10337         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10338         VALUES('CardnumberLength', '', '', 'Set a length for card numbers.', 'Free')
10339     |);
10340     print "Upgrade to $DBversion done (Bug 13984: CardnumberLength syspref missing on some setups\n";
10341     SetVersion ($DBversion);
10342 }
10343
10344 $DBversion = "3.19.00.035";
10345 if ( CheckVersion($DBversion) ) {
10346     $dbh->do(q|
10347         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('useDischarge','','Allows librarians to discharge borrowers and borrowers to request a discharge','','YesNo')
10348     |);
10349     $dbh->do(q|
10350         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.')
10351     |);
10352
10353     $dbh->do(q|
10354         ALTER TABLE borrower_debarments CHANGE type type ENUM('SUSPENSION','OVERDUES','MANUAL','DISCHARGE') NOT NULL DEFAULT 'MANUAL'
10355     |);
10356
10357     $dbh->do(q|
10358         CREATE TABLE discharges (
10359           borrower int(11) DEFAULT NULL,
10360           needed timestamp NULL DEFAULT NULL,
10361           validated timestamp NULL DEFAULT NULL,
10362           KEY borrower_discharges_ibfk1 (borrower),
10363           CONSTRAINT borrower_discharges_ibfk1 FOREIGN KEY (borrower) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
10364         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
10365     |);
10366
10367     print "Upgrade to $DBversion done (Bug 8007: Add System Preferences useDischarge, the discharge notice and the new table discharges)\n";
10368     SetVersion($DBversion);
10369 }
10370
10371 $DBversion = "3.19.00.036";
10372 if ( CheckVersion($DBversion) ) {
10373     $dbh->do(q|
10374         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10375         VALUES ('CronjobLog','0',NULL,'If ON, log information from cron jobs.','YesNo')
10376     |);
10377     print "Upgrade to $DBversion done (Bug 13889: Add cron jobs information to system log)\n";
10378     SetVersion ($DBversion);
10379 }
10380
10381 $DBversion = "3.19.00.037";
10382 if ( CheckVersion($DBversion) ) {
10383     $dbh->do(q|
10384         ALTER TABLE marc_subfield_structure
10385         MODIFY COLUMN tagsubfield varchar(1) COLLATE utf8_bin NOT NULL DEFAULT ''
10386     |);
10387     print "Upgrade to $DBversion done (Bug 13810: Change collate for tagsubfield (utf8_bin))\n";
10388     SetVersion ($DBversion);
10389 }
10390
10391 $DBversion = "3.19.00.038";
10392 if ( CheckVersion($DBversion) ) {
10393     $dbh->do(q|
10394         ALTER TABLE virtualshelves
10395         ADD COLUMN created_on DATETIME NOT NULL AFTER lastmodified
10396     |);
10397     # Set created_on = lastmodified
10398     # I would say it's better than 0000-00-00
10399     # Set modified to the existing value (do not get the current ts!)
10400     $dbh->do(q|
10401         UPDATE virtualshelves
10402         SET created_on = lastmodified, lastmodified = lastmodified
10403     |);
10404     print "Upgrade to $DBversion done (Bug 13421: Add DB field virtualshelves.created_on)\n";
10405     SetVersion ($DBversion);
10406 }
10407
10408 $DBversion = "3.19.00.039";
10409 if ( CheckVersion($DBversion) ) {
10410     print "Upgrade to $DBversion done (Koha 3.20 beta)\n";
10411     SetVersion ($DBversion);
10412 }
10413
10414 $DBversion = "3.19.00.040";
10415 if ( CheckVersion($DBversion) ) {
10416     $dbh->do(q|
10417         ALTER TABLE aqorders DROP COLUMN totalamount
10418     |);
10419     print "Upgrade to $DBversion done (Bug 11006: Drop column aqorders.totalamount)\n";
10420     SetVersion ($DBversion);
10421 }
10422
10423 $DBversion = "3.19.00.041";
10424 if ( CheckVersion($DBversion) ) {
10425     unless ( index_exists( 'suggestions', 'status' ) ) {
10426         $dbh->do(q|
10427             ALTER TABLE suggestions ADD KEY status (STATUS)
10428         |);
10429     }
10430     unless ( index_exists( 'suggestions', 'biblionumber' ) ) {
10431         $dbh->do(q|
10432             ALTER TABLE suggestions ADD KEY biblionumber (biblionumber)
10433         |);
10434     }
10435     unless ( index_exists( 'suggestions', 'branchcode' ) ) {
10436         $dbh->do(q|
10437             ALTER TABLE suggestions ADD KEY branchcode (branchcode)
10438         |);
10439     }
10440     print "Upgrade to $DBversion done (Bug 14132: suggestions table is missing indexes)\n";
10441     SetVersion ($DBversion);
10442 }
10443
10444 $DBversion = "3.19.00.042";
10445 if ( CheckVersion($DBversion) ) {
10446     $dbh->do(q{
10447         DELETE ass.*
10448         FROM auth_subfield_structure AS ass
10449         LEFT JOIN auth_types USING(authtypecode)
10450         WHERE auth_types.authtypecode IS NULL
10451     });
10452
10453     unless ( foreign_key_exists( 'auth_subfield_structure', 'auth_subfield_structure_ibfk_1' ) ) {
10454         $dbh->do(q{
10455             ALTER TABLE auth_subfield_structure
10456             ADD CONSTRAINT auth_subfield_structure_ibfk_1
10457             FOREIGN KEY (authtypecode) REFERENCES auth_types(authtypecode)
10458             ON DELETE CASCADE ON UPDATE CASCADE
10459         });
10460     }
10461
10462     print "Upgrade to $DBversion done (Bug 8480: Add foreign key on auth_subfield_structure.authtypecode)\n";
10463     SetVersion($DBversion);
10464 }
10465
10466 $DBversion = "3.19.00.043";
10467 if ( CheckVersion($DBversion) ) {
10468     $dbh->do(q|
10469         INSERT IGNORE INTO authorised_values (category, authorised_value, lib) VALUES
10470         ('REPORT_GROUP', 'SER', 'Serials')
10471     |);
10472
10473     print "Upgrade to $DBversion done (Bug 5338: Add Serial to the report groups if does not exist)\n";
10474     SetVersion ($DBversion);
10475 }
10476
10477 $DBversion = "3.20.00.000";
10478 if ( CheckVersion($DBversion) ) {
10479     print "Upgrade to $DBversion done (Koha 3.20)\n";
10480     SetVersion ($DBversion);
10481 }
10482
10483 $DBversion = "3.21.00.000";
10484 if ( CheckVersion($DBversion) ) {
10485     print "Upgrade to $DBversion done (El tiempo vuela, un nuevo ciclo comienza.)\n";
10486     SetVersion ($DBversion);
10487 }
10488
10489 $DBversion = "3.21.00.001";
10490 if ( CheckVersion($DBversion) ) {
10491     $dbh->do(q|
10492         UPDATE systempreferences SET variable='IntranetUserJS' where variable='intranetuserjs'
10493     |);
10494     print "Upgrade to $DBversion done (Bug 12160: Rename intranetuserjs to IntranetUserJS)\n";
10495     SetVersion ($DBversion);
10496 }
10497
10498 $DBversion = "3.21.00.002";
10499 if ( CheckVersion($DBversion) ) {
10500     $dbh->do(q|
10501         UPDATE systempreferences SET variable='OPACUserJS' where variable='opacuserjs'
10502     |);
10503     print "Upgrade to $DBversion done (Bug 12160: Rename opacuserjs to OPACUserJS)\n";
10504     SetVersion ($DBversion);
10505 }
10506
10507 $DBversion = "3.21.00.003";
10508 if ( CheckVersion($DBversion) ) {
10509     $dbh->do(q|
10510         INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added)
10511         VALUES ( 'IN', 'region', 'India','2015-05-28');
10512     |);
10513     $dbh->do(q|
10514         INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)
10515         VALUES ( 'IN', 'region', 'en', 'India');
10516     |);
10517     $dbh->do(q|
10518         INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)
10519         VALUES ( 'IN', 'region', 'bn', 'ভারত');
10520     |);
10521     print "Upgrade to $DBversion done (Bug 14285: Add new region India)\n";
10522     SetVersion ($DBversion);
10523 }
10524
10525 $DBversion = '3.21.00.004';
10526 if ( CheckVersion($DBversion) ) {
10527     my $OPACBaseURL = C4::Context->preference('OPACBaseURL');
10528     if (defined($OPACBaseURL) && substr($OPACBaseURL,0,4) ne "http") {
10529         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.};
10530         $OPACBaseURL = 'http://' . $OPACBaseURL;
10531         my $sth_OPACBaseURL = $dbh->prepare( q{
10532             UPDATE systempreferences SET value=?,explanation=?
10533             WHERE variable='OPACBaseURL'; } );
10534         $sth_OPACBaseURL->execute($OPACBaseURL,$explanation);
10535     }
10536     if (defined($OPACBaseURL)) {
10537         $dbh->do( q{ UPDATE letter
10538                      SET content=replace(content,
10539                                          'http://<<OPACBaseURL>>',
10540                                          '<<OPACBaseURL>>')
10541                      WHERE content LIKE "%http://<<OPACBaseURL>>%"; } );
10542     }
10543
10544     print "Upgrade to $DBversion done (Bug 5010: Fix OPACBaseURL to include protocol)\n";
10545     SetVersion($DBversion);
10546 }
10547
10548 $DBversion = "3.21.00.005";
10549 if ( CheckVersion($DBversion) ) {
10550     $dbh->do(q|
10551         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10552         VALUES ('ReportsLog','0',NULL,'If ON, log information about reports.','YesNo')
10553     |);
10554     print "Upgrade to $DBversion done (Bug 14024: Add reports to action logs)\n";
10555     SetVersion ($DBversion);
10556 }
10557
10558 $DBversion = "3.21.00.006";
10559 if ( CheckVersion($DBversion) ) {
10560     # Remove the borrow permission flag (bit 7)
10561     $dbh->do(q|
10562         UPDATE borrowers
10563         SET flags = flags - ( flags & (1<<7) )
10564         WHERE flags IS NOT NULL
10565             AND flags > 0
10566     |);
10567     $dbh->do(q|
10568         DELETE FROM userflags WHERE bit=7;
10569     |);
10570     print "Upgrade to $DBversion done (Bug 7976: Remove the 'borrow' permission)\n";
10571     SetVersion($DBversion);
10572 }
10573
10574 $DBversion = "3.21.00.007";
10575 if ( CheckVersion($DBversion) ) {
10576     unless ( index_exists( 'aqbasket', 'authorisedby' ) ) {
10577         $dbh->do(q|
10578             ALTER TABLE aqbasket
10579                 ADD KEY authorisedby (authorisedby)
10580         |);
10581     }
10582     unless ( index_exists( 'aqbooksellers', 'name' ) ) {
10583         $dbh->do(q|
10584             ALTER TABLE aqbooksellers
10585                 ADD KEY name (name(255))
10586         |);
10587     }
10588     unless ( index_exists( 'aqbudgets', 'budget_parent_id' ) ) {
10589         $dbh->do(q|
10590             ALTER TABLE aqbudgets
10591                 ADD KEY budget_parent_id (budget_parent_id)|);
10592         }
10593     unless ( index_exists( 'aqbudgets', 'budget_code' ) ) {
10594         $dbh->do(q|
10595             ALTER TABLE aqbudgets
10596                 ADD KEY budget_code (budget_code)|);
10597     }
10598     unless ( index_exists( 'aqbudgets', 'budget_branchcode' ) ) {
10599         $dbh->do(q|
10600             ALTER TABLE aqbudgets
10601                 ADD KEY budget_branchcode (budget_branchcode)|);
10602     }
10603     unless ( index_exists( 'aqbudgets', 'budget_period_id' ) ) {
10604         $dbh->do(q|
10605             ALTER TABLE aqbudgets
10606                 ADD KEY budget_period_id (budget_period_id)|);
10607     }
10608     unless ( index_exists( 'aqbudgets', 'budget_owner_id' ) ) {
10609         $dbh->do(q|
10610             ALTER TABLE aqbudgets
10611                 ADD KEY budget_owner_id (budget_owner_id)|);
10612     }
10613     unless ( index_exists( 'aqbudgets_planning', 'budget_period_id' ) ) {
10614         $dbh->do(q|
10615             ALTER TABLE aqbudgets_planning
10616                 ADD KEY budget_period_id (budget_period_id)|);
10617     }
10618     unless ( index_exists( 'aqorders', 'parent_ordernumber' ) ) {
10619         $dbh->do(q|
10620             ALTER TABLE aqorders
10621                 ADD KEY parent_ordernumber (parent_ordernumber)|);
10622     }
10623     unless ( index_exists( 'aqorders', 'orderstatus' ) ) {
10624         $dbh->do(q|
10625             ALTER TABLE aqorders
10626                 ADD KEY orderstatus (orderstatus)|);
10627     }
10628     print "Upgrade to $DBversion done (Bug 14053: Acquisition db tables are missing indexes)\n";
10629     SetVersion ($DBversion);
10630 }
10631
10632 $DBversion = "3.21.00.008";
10633 if ( CheckVersion($DBversion) ) {
10634     $dbh->do(q{
10635         DELETE IGNORE FROM systempreferences
10636         WHERE variable = 'HomeOrHoldingBranchReturn';
10637     });
10638     print "Upgrade to $DBversion done (Bug 7981: Transfer message on return. HomeOrHoldingBranchReturn syspref removed in favour of circulation rules.)\n";
10639     SetVersion($DBversion);
10640 }
10641
10642 $DBversion = "3.21.00.009";
10643 if ( CheckVersion($DBversion) ) {
10644     $dbh->do(q|
10645         UPDATE aqorders SET orderstatus='cancelled'
10646         WHERE (datecancellationprinted IS NOT NULL OR
10647                datecancellationprinted<>'0000-00-00');
10648     |);
10649     print "Upgrade to $DBversion done (Bug 13993: Correct orderstatus for transferred orders)\n";
10650     SetVersion($DBversion);
10651 }
10652
10653 $DBversion = "3.21.00.010";
10654 if ( CheckVersion($DBversion) ) {
10655     $dbh->do(q|
10656         ALTER TABLE message_queue
10657             DROP message_id
10658     |);
10659     $dbh->do(q|
10660         ALTER TABLE message_queue
10661             ADD message_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10662     |);
10663     print "Upgrade to $DBversion done (Bug 7793: redefine the field message_id as PRIMARY KEY of message_queue)\n";
10664     SetVersion ($DBversion);
10665 }
10666
10667 $DBversion = "3.21.00.011";
10668 if ( CheckVersion($DBversion) ) {
10669     $dbh->do(q{
10670         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10671         VALUES ('OpacLangSelectorMode','footer','top|both|footer','Select the location to display the language selector','Choice')
10672     });
10673     print "Upgrade to $DBversion done (Bug 14252: Make the OPAC language switcher available in the masthead navbar, footer, or both)\n";
10674     SetVersion ($DBversion);
10675 }
10676
10677 $DBversion = "3.21.00.012";
10678 if ( CheckVersion($DBversion) ) {
10679     $dbh->do(q|
10680         INSERT INTO letter (module, code, name, title, content, message_transport_type)
10681         VALUES
10682         ('suggestions','TO_PROCESS','Notify fund owner', 'A suggestion is ready to be processed','Dear <<borrowers.firstname>> <<borrowers.surname>>,\n\nA new suggestion is ready to be processed: <<suggestions.title>> by <<suggestions.autho    r>>.\n\nThank you,\n\n<<branches.branchname>>', 'email')
10683     |);
10684     print "Upgrade to $DBversion done (Bug 13014: Add the TO_PROCESS letter code)\n";
10685     SetVersion($DBversion);
10686 }
10687
10688 $DBversion = "3.21.00.013";
10689 if ( CheckVersion($DBversion) ) {
10690     my $msg;
10691     if ( C4::Context->preference('OPACPrivacy') ) {
10692         if ( my $anonymous_patron = C4::Context->preference('AnonymousPatron') ) {
10693             my $anonymous_patron_exists = $dbh->selectcol_arrayref(q|
10694                 SELECT COUNT(*)
10695                 FROM borrowers
10696                 WHERE borrowernumber=?
10697             |, {}, $anonymous_patron);
10698             unless ( $anonymous_patron_exists->[0] ) {
10699                 $msg = "Configuration WARNING: OPACPrivacy is set but AnonymousPatron is not linked to an existing patron";
10700             }
10701         }
10702         else {
10703             $msg = "Configuration WARNING: OPACPrivacy is set but AnonymousPatron is not";
10704         }
10705     }
10706     else {
10707         my $patrons_have_required_anonymity = $dbh->selectcol_arrayref(q|
10708             SELECT COUNT(*)
10709             FROM borrowers
10710             WHERE privacy = 2
10711         |, {} );
10712         if ( $patrons_have_required_anonymity->[0] ) {
10713             $msg = "Configuration WARNING: OPACPrivacy is not set but $patrons_have_required_anonymity->[0] patrons have required anonymity (perhaps in a previous configuration). You should fix that asap.";
10714         }
10715     }
10716
10717     $msg //= "Privacy is correctly set";
10718     print "Upgrade to $DBversion done (Bug 9942: $msg)\n";
10719     SetVersion ($DBversion);
10720 }
10721
10722 $DBversion = "3.21.00.014";
10723 if ( CheckVersion($DBversion) ) {
10724     $dbh->do(q{
10725         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10726         VALUES ('OAI-PMH:DeletedRecord','persistent','Koha\'s deletedbiblio table will never be deleted (persistent) or might be deleted (transient)','transient|persistent','Choice')
10727     });
10728
10729     if ( foreign_key_exists( 'oai_sets_biblios', 'oai_sets_biblios_ibfk_1' ) ) {
10730         $dbh->do(q|
10731             ALTER TABLE oai_sets_biblios DROP FOREIGN KEY oai_sets_biblios_ibfk_1
10732         |);
10733     }
10734     print "Upgrade to $DBversion done (Bug 3206: OAI repository deleted record support)\n";
10735     SetVersion ($DBversion);
10736 }
10737
10738 $DBversion = "3.21.00.015";
10739 if ( CheckVersion($DBversion) ) {
10740     $dbh->do(q{
10741         UPDATE systempreferences SET value='0' WHERE variable='CalendarFirstDayOfWeek' AND value='Sunday';
10742     });
10743     $dbh->do(q{
10744         UPDATE systempreferences SET value='1' WHERE variable='CalendarFirstDayOfWeek' AND value='Monday';
10745     });
10746     $dbh->do(q{
10747         UPDATE systempreferences SET options='0|1|2|3|4|5|6' WHERE variable='CalendarFirstDayOfWeek';
10748     });
10749
10750     print "Upgrade to $DBversion done (Bug 12137: Extend functionality of CalendarFirstDayOfWeek to be any day)\n";
10751     SetVersion($DBversion);
10752 }
10753
10754 $DBversion = "3.21.00.016";
10755 if ( CheckVersion($DBversion) ) {
10756     my $rs = $schema->resultset('Systempreference');
10757     $rs->find_or_create(
10758         {
10759             variable => 'DumpTemplateVarsIntranet',
10760             value    => 0,
10761             explanation => 'If enabled, dump all Template Toolkit variable to a comment in the html source for the staff intranet.',
10762             type => 'YesNo',
10763         }
10764     );
10765     $rs->find_or_create(
10766         {
10767             variable => 'DumpTemplateVarsOpac',
10768             value    => 0,
10769             explanation => 'If enabled, dump all Template Toolkit variable to a comment in the html source for the opac.',
10770             type => 'YesNo',
10771         }
10772     );
10773     print "Upgrade to $DBversion done (Bug 13948: Add ability to dump template toolkit variables to html comment)\n";
10774     SetVersion($DBversion);
10775 }
10776
10777 $DBversion = "3.21.00.017";
10778 if ( CheckVersion($DBversion) ) {
10779     $dbh->do("
10780         CREATE TABLE uploaded_files (
10781             id int(11) NOT NULL AUTO_INCREMENT,
10782             hashvalue CHAR(40) NOT NULL,
10783             filename TEXT NOT NULL,
10784             dir TEXT NOT NULL,
10785             filesize int(11),
10786             dtcreated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
10787             categorycode tinytext,
10788             owner int(11),
10789             PRIMARY KEY (id)
10790         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
10791     ");
10792
10793     print "Upgrade to $DBversion done (Bug 6874: New cataloging plugin upload.pl)\n";
10794     print "This plugin comes with a new config variable (upload_path) and a new table (uploaded_files)\n";
10795     print "To use it, set 'upload_path' config variable and 'OPACBaseURL' system preference and link this plugin to a subfield (856\$u for instance)\n";
10796     SetVersion($DBversion);
10797 }
10798
10799 $DBversion = "3.21.00.018";
10800 if ( CheckVersion($DBversion) ) {
10801     $dbh->do(q{
10802         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10803         VALUES
10804             ('RestrictedPageLocalIPs','',NULL,'Beginning of IP addresses considered as local (comma separated ex: \"127.0.0,127.0.2\")','Free'),
10805             ('RestrictedPageContent','',NULL,'HTML content of the restricted page','TextArea'),
10806             ('RestrictedPageTitle','',NULL,'Title of the restricted page (breadcrumb and header)','Free')
10807     });
10808     print "Upgrade to $DBversion done (Bug 13485: Add a page to display links to restricted sites)\n";
10809     SetVersion ($DBversion);
10810 }
10811
10812 $DBversion = "3.21.00.019";
10813 if ( CheckVersion($DBversion) ) {
10814     if ( column_exists( 'reserves', 'constrainttype' ) ) {
10815         $dbh->do(q{
10816             ALTER TABLE reserves DROP constrainttype
10817         });
10818         $dbh->do(q{
10819             ALTER TABLE old_reserves DROP constrainttype
10820         });
10821     }
10822     $dbh->do(q{
10823         DROP TABLE IF EXISTS reserveconstraints
10824     });
10825     print "Upgrade to $DBversion done (Bug 9809: Get rid of reserveconstraints)\n";
10826     SetVersion ($DBversion);
10827 }
10828
10829 $DBversion = "3.21.00.020";
10830 if ( CheckVersion($DBversion) ) {
10831     $dbh->do(q{
10832         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`)
10833         VALUES ('FeeOnChangePatronCategory','1','','If set, when a patron changes to a category with enrolment fee, a fee is charged','YesNo')
10834     });
10835     print "Upgrade to $DBversion done (Bug 13697: Option to don't charge a fee, if the patron changes to a category with enrolment fee)\n";
10836     SetVersion($DBversion);
10837 }
10838
10839 $DBversion = "3.21.00.021";
10840 if ( CheckVersion($DBversion) ) {
10841     $dbh->do(q{
10842         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10843         VALUES ('UseWYSIWYGinSystemPreferences','0','','Show WYSIWYG editor when editing certain HTML system preferences.','YesNo')
10844     });
10845     print "Upgrade to $DBversion done (Bug 11584: Add wysiwyg editor to system preferences dealing with HTML)\n";
10846     SetVersion($DBversion);
10847 }
10848
10849 $DBversion = "3.21.00.022";
10850 if ( CheckVersion($DBversion) ) {
10851     $dbh->do(q{
10852         DELETE cr.*
10853         FROM course_reserves AS cr
10854         LEFT JOIN course_items USING(ci_id)
10855         WHERE course_items.ci_id IS NULL
10856     });
10857
10858     my ($print_error) = $dbh->{PrintError};
10859     $dbh->{RaiseError} = 0;
10860     $dbh->{PrintError} = 0;
10861     if ( foreign_key_exists('course_reserves', 'course_reserves_ibfk_2') ) {
10862         $dbh->do(q{ALTER TABLE course_reserves DROP FOREIGN KEY course_reserves_ibfk_2});
10863         $dbh->do(q{ALTER TABLE course_reserves DROP INDEX course_reserves_ibfk_2});
10864     }
10865     $dbh->{PrintError} = $print_error;
10866
10867     $dbh->do(q{
10868         ALTER TABLE course_reserves
10869             ADD CONSTRAINT course_reserves_ibfk_2
10870                 FOREIGN KEY (ci_id) REFERENCES course_items (ci_id)
10871                 ON DELETE CASCADE ON UPDATE CASCADE
10872     });
10873     print "Upgrade to $DBversion done (Bug 14205: Deleting an Item/Record does not remove link to course reserve)\n";
10874     SetVersion($DBversion);
10875 }
10876
10877 $DBversion = "3.21.00.023";
10878 if ( CheckVersion($DBversion) ) {
10879     $dbh->do(q{
10880         UPDATE borrowers SET debarred=NULL WHERE debarred='0000-00-00'
10881     });
10882     $dbh->do(q{
10883         UPDATE borrowers SET dateexpiry=NULL where dateexpiry='0000-00-00'
10884     });
10885     $dbh->do(q{
10886         UPDATE borrowers SET dateofbirth=NULL where dateofbirth='0000-00-00'
10887     });
10888     $dbh->do(q{
10889         UPDATE borrowers SET dateenrolled=NULL where dateenrolled='0000-00-00'
10890     });
10891     print "Upgrade to $DBversion done (Bug 14717: Prevent 0000-00-00 dates in patron data)\n";
10892     SetVersion($DBversion);
10893 }
10894
10895 $DBversion = "3.21.00.024";
10896 if ( CheckVersion($DBversion) ) {
10897     $dbh->do(q{
10898         ALTER TABLE marc_modification_template_actions
10899         MODIFY COLUMN action
10900             ENUM('delete_field','update_field','move_field','copy_field','copy_and_replace_field')
10901             NOT NULL
10902     });
10903     print "Upgrade to $DBversion done (Bug 14098: Regression in Marc Modification Templates)\n";
10904     SetVersion($DBversion);
10905 }
10906
10907 $DBversion = "3.21.00.025";
10908 if ( CheckVersion($DBversion) ) {
10909     $dbh->do(q{
10910         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10911         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')
10912     });
10913     $dbh->do(q{
10914         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10915         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')
10916     });
10917     print "Upgrade to $DBversion done (Bug 12357: Enhancements to RIS and BibTeX exporting)\n";
10918     SetVersion($DBversion);
10919 }
10920
10921 $DBversion = "3.21.00.026";
10922 if ( CheckVersion($DBversion) ) {
10923     $dbh->do(q{
10924         UPDATE matchpoints
10925         SET search_index='issn'
10926         WHERE matcher_id IN (SELECT matcher_id FROM marc_matchers WHERE code = 'ISSN')
10927     });
10928     print "Upgrade to $DBversion done (Bug 14472: Wrong ISSN search index in record matching rules)\n";
10929     SetVersion($DBversion);
10930 }
10931
10932 $DBversion = "3.21.00.027";
10933 if ( CheckVersion($DBversion) ) {
10934     $dbh->do(q|
10935         INSERT IGNORE INTO permissions (module_bit, code, description)
10936         VALUES (1, 'self_checkout', 'Perform self checkout at the OPAC. It should be used for the patron matching the AutoSelfCheckID')
10937     |);
10938
10939     my $AutoSelfCheckID = C4::Context->preference('AutoSelfCheckID');
10940
10941     $dbh->do(q|
10942         UPDATE borrowers
10943         SET flags=0
10944         WHERE userid=?
10945     |, undef, $AutoSelfCheckID);
10946
10947     $dbh->do(q|
10948         DELETE FROM user_permissions
10949         WHERE borrowernumber=(SELECT borrowernumber FROM borrowers WHERE userid=?)
10950     |, undef, $AutoSelfCheckID);
10951
10952     $dbh->do(q|
10953         INSERT INTO user_permissions(borrowernumber, module_bit, code)
10954         SELECT borrowernumber, 1, 'self_checkout' FROM borrowers WHERE userid=?
10955     |, undef, $AutoSelfCheckID);
10956     print "Upgrade to $DBversion done (Bug 14298: AutoSelfCheckID user should only be able to access SCO)\n";
10957     SetVersion($DBversion);
10958 }
10959
10960 $DBversion = "3.21.00.028";
10961 if ( CheckVersion($DBversion) ) {
10962     unless ( column_exists('uploaded_files', 'public') ) {
10963         $dbh->do(q{
10964             ALTER TABLE uploaded_files
10965                 ADD COLUMN public tinyint,
10966                 ADD COLUMN permanent tinyint
10967         });
10968         $dbh->do(q{
10969             UPDATE uploaded_files SET public=1, permanent=1
10970         });
10971         $dbh->do(q{
10972             ALTER TABLE uploaded_files
10973                 CHANGE COLUMN categorycode uploadcategorycode tinytext
10974         });
10975     }
10976     print "Upgrade to $DBversion done (Bug 14321: Merge UploadedFile and UploadedFiles into Koha::Upload)\n";
10977     SetVersion($DBversion);
10978 }
10979
10980 $DBversion = "3.21.00.029";
10981 if ( CheckVersion($DBversion) ) {
10982     unless ( column_exists('discharges', 'discharge_id') ) {
10983         $dbh->do(q{
10984             ALTER TABLE discharges
10985                 ADD COLUMN discharge_id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10986         });
10987     }
10988     print "Upgrade to $DBversion done (Bug 14368: Add discharges history)\n";
10989     SetVersion($DBversion);
10990 }
10991
10992 $DBversion = "3.21.00.030";
10993 if ( CheckVersion($DBversion) ) {
10994     $dbh->do(q{
10995         UPDATE marc_subfield_structure
10996         SET value_builder='marc21_leader.pl'
10997         WHERE value_builder='marc21_leader_book.pl'
10998     });
10999     $dbh->do(q{
11000         UPDATE marc_subfield_structure
11001         SET value_builder='marc21_leader.pl'
11002         WHERE value_builder='marc21_leader_computerfile.pl'
11003     });
11004     $dbh->do(q{
11005         UPDATE marc_subfield_structure
11006         SET value_builder='marc21_leader.pl'
11007         WHERE value_builder='marc21_leader_video.pl'
11008     });
11009     print "Upgrade to $DBversion done (Bug 14201: Remove unused code or template from some MARC21 leader plugins )\n";
11010     SetVersion($DBversion);
11011 }
11012
11013 $DBversion = "3.21.00.031";
11014 if ( CheckVersion($DBversion) ) {
11015     $dbh->do(q{
11016         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
11017         VALUES
11018             ('SMSSendPassword', '', '', 'Password used to send SMS messages', 'free'),
11019             ('SMSSendUsername', '', '', 'Username/Login used to send SMS messages', 'free')
11020     });
11021     print "Upgrade to $DBversion done (Bug 14820: SMSSendUsername and SMSSendPassword are not listed in the system preferences)\n";
11022     SetVersion($DBversion);
11023 }
11024
11025 $DBversion = "3.21.00.032";
11026 if ( CheckVersion($DBversion) ) {
11027     $dbh->do(q{
11028         CREATE TABLE additional_fields (
11029             id int(11) NOT NULL AUTO_INCREMENT,
11030             tablename varchar(255) NOT NULL DEFAULT '',
11031             name varchar(255) NOT NULL DEFAULT '',
11032             authorised_value_category varchar(16) NOT NULL DEFAULT '',
11033             marcfield varchar(16) NOT NULL DEFAULT '',
11034             searchable tinyint(1) NOT NULL DEFAULT '0',
11035             PRIMARY KEY (id),
11036             UNIQUE KEY fields_uniq (tablename,name)
11037         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
11038     });
11039     $dbh->do(q{
11040         CREATE TABLE additional_field_values (
11041             id int(11) NOT NULL AUTO_INCREMENT,
11042             field_id int(11) NOT NULL,
11043             record_id int(11) NOT NULL,
11044             value varchar(255) NOT NULL DEFAULT '',
11045             PRIMARY KEY (id),
11046             UNIQUE KEY field_record (field_id,record_id),
11047             CONSTRAINT afv_fk FOREIGN KEY (field_id) REFERENCES additional_fields (id) ON DELETE CASCADE ON UPDATE CASCADE
11048         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
11049     });
11050     print "Upgrade to $DBversion done (Bug 10855: Additional fields for subscriptions)\n";
11051     SetVersion($DBversion);
11052 }
11053
11054 $DBversion = "3.21.00.033";
11055 if ( CheckVersion($DBversion) ) {
11056
11057     my $done = 0;
11058     my $count_ethnicity = $dbh->selectrow_arrayref(q|
11059         SELECT COUNT(*) FROM ethnicity
11060     |);
11061     my $count_borrower_modifications = $dbh->selectrow_arrayref(q|
11062         SELECT COUNT(*)
11063         FROM borrower_modifications
11064         WHERE ethnicity IS NOT NULL
11065             OR ethnotes IS NOT NULL
11066     |);
11067     my $count_borrowers = $dbh->selectrow_arrayref(q|
11068         SELECT COUNT(*)
11069         FROM borrowers
11070         WHERE ethnicity IS NOT NULL
11071             OR ethnotes IS NOT NULL
11072     |);
11073     # We don't care about the ethnicity of the deleted borrowers, right?
11074     if ( $count_ethnicity->[0] == 0
11075             and $count_borrower_modifications->[0] == 0
11076             and $count_borrowers->[0] == 0
11077     ) {
11078         $dbh->do(q|
11079             DROP TABLE ethnicity
11080         |);
11081         $dbh->do(q|
11082             ALTER TABLE borrower_modifications
11083             DROP COLUMN ethnicity,
11084             DROP COLUMN ethnotes
11085         |);
11086         $dbh->do(q|
11087             ALTER TABLE borrowers
11088             DROP COLUMN ethnicity,
11089             DROP COLUMN ethnotes
11090         |);
11091         $dbh->do(q|
11092             ALTER TABLE deletedborrowers
11093             DROP COLUMN ethnicity,
11094             DROP COLUMN ethnotes
11095         |);
11096         $done = 1;
11097     }
11098     if ( $done ) {
11099         print "Upgrade to $DBversion done (Bug 10020: Drop table ethnicity and columns ethnicity and ethnotes)\n";
11100     }
11101     else {
11102         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";
11103     }
11104
11105     SetVersion ($DBversion);
11106 }
11107
11108 $DBversion = "3.21.00.034";
11109 if ( CheckVersion($DBversion) ) {
11110     $dbh->do(q{
11111         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11112         VALUES('MembershipExpiryDaysNotice',NULL,'Send an account expiration notice that a patron''s card is about to expire after',NULL,'Integer')
11113     });
11114     $dbh->do(q{
11115         INSERT IGNORE INTO letter (module, code, branchcode, name, title, content, message_transport_type)
11116         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')
11117     });
11118     print "Upgrade to $DBversion done (Bug 6810: Send membership expiry reminder notices)\n";
11119     SetVersion($DBversion);
11120 }
11121
11122 $DBversion = "3.21.00.035";
11123 if ( CheckVersion($DBversion) ) {
11124     $dbh->do(q|
11125         ALTER TABLE branch_borrower_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11126     |);
11127     $dbh->do(q|
11128         UPDATE branch_borrower_circ_rules SET maxonsiteissueqty = maxissueqty;
11129     |);
11130     $dbh->do(q|
11131         ALTER TABLE default_borrower_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11132     |);
11133     $dbh->do(q|
11134         UPDATE default_borrower_circ_rules SET maxonsiteissueqty = maxissueqty;
11135     |);
11136     $dbh->do(q|
11137         ALTER TABLE default_branch_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11138     |);
11139     $dbh->do(q|
11140         UPDATE default_branch_circ_rules SET maxonsiteissueqty = maxissueqty;
11141     |);
11142     $dbh->do(q|
11143         ALTER TABLE default_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11144     |);
11145     $dbh->do(q|
11146         UPDATE default_circ_rules SET maxonsiteissueqty = maxissueqty;
11147     |);
11148     $dbh->do(q|
11149         ALTER TABLE issuingrules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11150     |);
11151     $dbh->do(q|
11152         UPDATE issuingrules SET maxonsiteissueqty = maxissueqty;
11153     |);
11154     $dbh->do(q|
11155         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11156         VALUES ('ConsiderOnSiteCheckoutsAsNormalCheckouts','1',NULL,'Consider on-site checkouts as normal checkouts','YesNo');
11157     |);
11158
11159     print "Upgrade to $DBversion done (Bug 14045: Add DB fields maxonsiteissueqty and pref ConsiderOnSiteCheckoutsAsNormalCheckouts)\n";
11160     SetVersion ($DBversion);
11161 }
11162
11163 $DBversion = "3.21.00.036";
11164 if ( CheckVersion($DBversion) ) {
11165    $dbh->do(q{
11166         ALTER TABLE authorised_values_branches
11167         DROP FOREIGN KEY authorised_values_branches_ibfk_1,
11168         DROP FOREIGN KEY authorised_values_branches_ibfk_2
11169     });
11170     $dbh->do(q{
11171         ALTER TABLE authorised_values_branches
11172         MODIFY av_id INT( 11 ) NOT NULL,
11173         MODIFY branchcode VARCHAR( 10 ) NOT NULL,
11174         ADD FOREIGN KEY (`av_id`) REFERENCES `authorised_values` (`id`) ON DELETE CASCADE,
11175         ADD FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE
11176    });
11177    print "Upgrade to $DBversion done (Bug 10363: There is no package for authorised values)\n";
11178    SetVersion($DBversion);
11179 }
11180
11181 $DBversion = "3.21.00.037";
11182 if ( CheckVersion($DBversion) ) {
11183    $dbh->do(q{
11184        INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11185        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')
11186    });
11187    $dbh->do(q{
11188        INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11189        VALUES ('RestrictionBlockRenewing','0','If patron is restricted, should renewal be allowed or blocked',NULL,'YesNo')
11190     });
11191    print "Upgrade to $DBversion done (Bug 8236: Prevent renewing if overdue or restriction)\n";
11192    SetVersion($DBversion);
11193 }
11194
11195 $DBversion = "3.21.00.038";
11196 if ( CheckVersion($DBversion) ) {
11197     $dbh->do(q|
11198         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11199         VALUES ('BatchCheckouts','0','','Enable or disable batch checkouts','YesNo')
11200     |);
11201     $dbh->do(q|
11202         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11203         VALUES ('BatchCheckoutsValidCategories','',NULL,'Patron categories allowed to checkout in a batch','Free')
11204     |);
11205     print "Upgrade to $DBversion done (Bug 11759: Add the batch checkout feature)\n";
11206     SetVersion($DBversion);
11207 }
11208
11209 $DBversion = "3.21.00.039";
11210 if ( CheckVersion($DBversion) ) {
11211     $dbh->do(q|
11212         ALTER TABLE creator_layouts ADD COLUMN oblique_title INT(1) NULL DEFAULT 1 AFTER guidebox
11213     |);
11214     print "Upgrade to $DBversion done (Bug 12194: Add column oblique_title to layouts)\n";
11215     SetVersion($DBversion);
11216 }
11217
11218 $DBversion = "3.21.00.040";
11219 if ( CheckVersion($DBversion) ) {
11220     $dbh->do(q{
11221         ALTER TABLE itemtypes
11222             ADD hideinopac TINYINT(1) NOT NULL DEFAULT 0
11223               AFTER sip_media_type,
11224             ADD searchcategory VARCHAR(80) DEFAULT NULL
11225               AFTER hideinopac;
11226     });
11227     print "Upgrade to $DBversion done (Bug 10937: Option to hide and group itemtypes from advanced search)\n";
11228     SetVersion($DBversion);
11229 }
11230
11231 $DBversion = "3.21.00.041";
11232 if ( CheckVersion($DBversion) ) {
11233     $dbh->do(q|
11234         ALTER TABLE issuingrules
11235             ADD chargeperiod_charge_at BOOLEAN NOT NULL DEFAULT  '0' AFTER chargeperiod
11236     |);
11237     print "Upgrade to $DBversion done (Bug 13590: Add ability to charge fines at start of charge period)\n";
11238     SetVersion($DBversion);
11239 }
11240
11241 $DBversion = "3.21.00.042";
11242 if ( CheckVersion($DBversion) ) {
11243     $dbh->do(q|
11244         ALTER TABLE items_search_fields
11245             MODIFY COLUMN authorised_values_category VARCHAR(32) DEFAULT NULL
11246     |);
11247     print "Upgrade to $DBversion done (Bug 15069: items_search_fields.authorised_values_category is still a varchar(32))\n";
11248     SetVersion($DBversion);
11249 }
11250
11251 $DBversion = "3.21.00.043";
11252 if ( CheckVersion($DBversion) ) {
11253     $dbh->do(q|
11254         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11255         VALUES ('EnableAdvancedCatalogingEditor','0','','Enable the Rancor advanced cataloging editor','YesNo')
11256     |);
11257     print "Upgrade to $DBversion done (Bug 11559: Professional cataloger's interface)\n";
11258     SetVersion($DBversion);
11259 }
11260
11261 $DBversion = "3.21.00.044";
11262 if ( CheckVersion($DBversion) ) {
11263     $dbh->do(q|
11264         CREATE TABLE localization (
11265             localization_id int(11) NOT NULL AUTO_INCREMENT,
11266             entity varchar(16) COLLATE utf8_unicode_ci NOT NULL,
11267             code varchar(64) COLLATE utf8_unicode_ci NOT NULL,
11268             lang varchar(25) COLLATE utf8_unicode_ci NOT NULL,
11269             translation text COLLATE utf8_unicode_ci,
11270             PRIMARY KEY (localization_id),
11271             UNIQUE KEY entity_code_lang (entity,code,lang)
11272         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
11273     |);
11274     print "Upgrade to $DBversion done (Bug 14100: Generic solution for language overlay)\n";
11275     SetVersion($DBversion);
11276 }
11277
11278 $DBversion = "3.21.00.045";
11279 if ( CheckVersion($DBversion) ) {
11280     $dbh->do(q|
11281         ALTER TABLE opac_news
11282             ADD borrowernumber int(11) default NULL
11283                 AFTER number
11284     |);
11285     $dbh->do(q|
11286         ALTER TABLE opac_news
11287             ADD CONSTRAINT borrowernumber_fk
11288                 FOREIGN KEY (borrowernumber)
11289                 REFERENCES borrowers (borrowernumber)
11290                 ON DELETE SET NULL ON UPDATE CASCADE
11291     |);
11292     print "Upgrade to $DBversion done (Bug 14246: (newsauthor) Add borrowernumber to koha_news)\n";
11293     SetVersion($DBversion);
11294 }
11295
11296 $DBversion = "3.21.00.046";
11297 if ( CheckVersion($DBversion) ) {
11298     $dbh->do(q{
11299         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11300         VALUES ('NewsAuthorDisplay','none','none|opac|staff|both','Display the author name for news items.','Choice')
11301     });
11302     print "Upgrade to $DBversion done (Bug 14247: (newsauthor) System preference for news author display)\n";
11303     SetVersion($DBversion);
11304 }
11305
11306 $DBversion = "3.21.00.047";
11307 if(CheckVersion($DBversion)) {
11308     $dbh->do(q{
11309         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11310         VALUES ('IndependentBranchesPatronModifications','0','Show only modification request for the logged in branch','','YesNo')
11311     });
11312     print "Upgrade to $DBversion done (Bug 10904: Limit patron update request management by branch)\n";
11313     SetVersion($DBversion);
11314 }
11315
11316 $DBversion = '3.21.00.048';
11317 if ( CheckVersion($DBversion) ) {
11318     my $create_table_issues = @{ $dbh->selectall_arrayref(q|SHOW CREATE TABLE issues|) }[0]->[1];
11319     if ($create_table_issues !~ m|UNIQUE KEY.*itemnumber| ) {
11320         $dbh->do(q|ALTER TABLE issues ADD CONSTRAINT UNIQUE KEY (itemnumber)|);
11321     }
11322     print "Upgrade to $DBversion done (Bug 14978: Make sure issues.itemnumber is a unique key)\n";
11323     SetVersion($DBversion);
11324 }
11325
11326 $DBversion = "3.21.00.049";
11327 if ( CheckVersion($DBversion) ) {
11328     $dbh->do(q{UPDATE systempreferences SET variable = 'AudioAlerts' WHERE variable = 'soundon'});
11329
11330     $dbh->do(q{
11331         CREATE TABLE audio_alerts (
11332             id int(11) NOT NULL AUTO_INCREMENT,
11333             precedence smallint(5) unsigned NOT NULL,
11334             selector varchar(255) NOT NULL,
11335             sound varchar(255) NOT NULL,
11336             PRIMARY KEY (id),
11337             KEY precedence (precedence)
11338         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
11339     });
11340
11341     $dbh->do(q{
11342         INSERT IGNORE INTO audio_alerts VALUES
11343         (1, 1, '.audio-alert-action', 'opening.ogg'),
11344         (2, 2, '.audio-alert-warning', 'critical.ogg'),
11345         (3, 3, '.audio-alert-success', 'beep.ogg');
11346     });
11347
11348     print "Upgrade to $DBversion done (Bug 11431: Add additional sound options for warnings)\n";
11349     SetVersion($DBversion);
11350 }
11351
11352 $DBversion = "3.21.00.050";
11353 if(CheckVersion($DBversion)) {
11354     $dbh->do(q{
11355         INSERT INTO letter ( module, code, branchcode, name, is_html, title, content, message_transport_type )
11356         VALUES ( 'circulation', 'OVERDUES_SLIP', '', 'Overdues Slip', '0', 'OVERDUES_SLIP', 'The following item(s) is/are currently overdue:
11357
11358 <item>"<<biblio.title>>" by <<biblio.author>>, <<items.itemcallnumber>>, Barcode: <<items.barcode>> Fine: <<items.fine>></item>
11359 ', 'print' )
11360     });
11361     print "Upgrade to $DBversion done (Bug 12933: Add ability to print overdue slip from staff intranet)\n";
11362     SetVersion($DBversion);
11363 }
11364
11365 $DBversion = "3.21.00.051";
11366 if ( CheckVersion($DBversion) ) {
11367     $dbh->do(q{
11368         ALTER TABLE virtualshelves
11369             CHANGE COLUMN sortfield sortfield VARCHAR(16) DEFAULT 'title'
11370     });
11371     $dbh->do(q{
11372         UPDATE virtualshelves
11373         SET sortfield='title'
11374             WHERE sortfield IS NULL;
11375     });
11376     print "Upgrade to $DBversion done (Bug 14544: Move the list related code to Koha::Virtualshelves)\n";
11377     SetVersion($DBversion);
11378 }
11379
11380 $DBversion = "3.21.00.052";
11381 if ( CheckVersion($DBversion) ) {
11382     $dbh->do(q{
11383         ALTER TABLE serial
11384             ADD COLUMN publisheddatetext VARCHAR(100) DEFAULT NULL AFTER publisheddate
11385     });
11386     print "Upgrade to $DBversion done (Bug 8296: Add descriptive (text) published date field for serials)\n";
11387     SetVersion($DBversion);
11388 }
11389
11390 $DBversion = "3.21.00.053";
11391 if ( CheckVersion($DBversion) ) {
11392     my $query = q{ SELECT * FROM itemtypes ORDER BY description };
11393     my $sth   = C4::Context->dbh->prepare($query);
11394     $sth->execute;
11395     my $suggestion_formats = $sth->fetchall_arrayref( {} );
11396
11397     foreach my $format (@$suggestion_formats) {
11398         $dbh->do(
11399             q|
11400             INSERT IGNORE INTO authorised_values (category, authorised_value, lib, lib_opac, imageurl)
11401             VALUES (?, ?, ?, ?, ?)
11402         |, {},
11403             'SUGGEST_FORMAT', $format->{itemtype}, $format->{description}, $format->{description},
11404             $format->{imageurl}
11405         );
11406     }
11407     print "Upgrade to $DBversion done (Bug 9468: create new SUGGEST_FORMAT authorised_value list)\n";
11408     SetVersion($DBversion);
11409 }
11410
11411 $DBversion = "3.21.00.054";
11412 if(CheckVersion($DBversion)) {
11413     $dbh->do(q{
11414         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11415         VALUES('MergeReportFields','','Displayed fields for deleted MARC records after merge',NULL,'Free')
11416     });
11417     print "Upgrade to $DBversion done (Bug 8064: Merge several biblio records)\n";
11418     SetVersion($DBversion);
11419 }
11420
11421 $DBversion = "3.21.00.055";
11422 if ( CheckVersion($DBversion) ) {
11423     print "Upgrade to $DBversion done (Koha 3.22 beta)\n";
11424     SetVersion($DBversion);
11425 }
11426
11427 $DBversion = "3.21.00.056";
11428 if(CheckVersion($DBversion)) {
11429     $dbh->do(q{
11430         UPDATE systempreferences
11431         SET
11432             options='metric|us|iso|dmydot',
11433             explanation='Define global date format (us mm/dd/yyyy, metric dd/mm/yyy, ISO yyyy-mm-dd, DMY separated by dots dd.mm.yyyy)'
11434         WHERE variable='dateformat'
11435     });
11436     print "Upgrade to $DBversion done (Bug 12072: New dateformat dd.mm.yyyy)\n";
11437     SetVersion($DBversion);
11438 }
11439
11440 $DBversion = "3.22.00.000";
11441 if ( CheckVersion($DBversion) ) {
11442     print "Upgrade to $DBversion done (Koha 3.22)\n";
11443     SetVersion($DBversion);
11444 }
11445
11446 $DBversion = "3.23.00.000";
11447 if ( CheckVersion($DBversion) ) {
11448     print "Upgrade to $DBversion done (The year of the monkey will be here soon.)\n";
11449     SetVersion ($DBversion);
11450 }
11451
11452 $DBversion = "3.23.00.001";
11453 if(CheckVersion($DBversion)) {
11454     $dbh->do(q{
11455         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11456         VALUES (
11457             'DefaultToLoggedInLibraryCircRules',  '0', NULL ,  'If enabled, circ rules editor will default to the logged in library''s rules, rather than the ''all libraries'' rules.',  'YesNo'
11458         ), (
11459             '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'
11460         )
11461     });
11462
11463     print "Upgrade to $DBversion done (Bug 11625 - Add pref DefaultToLoggedInLibraryCircRules and DefaultToLoggedInLibraryNoticesSlips)\n";
11464     SetVersion($DBversion);
11465 }
11466
11467 $DBversion = "3.23.00.002";
11468 if(CheckVersion($DBversion)) {
11469     $dbh->do(q{
11470         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11471         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')
11472     });
11473
11474     print "Upgrade to $DBversion done (Bug 11747 - add pref DefaultToLoggedInLibraryOverdueTriggers)\n";
11475     SetVersion($DBversion);
11476 }
11477
11478 $DBversion = "3.23.00.003";
11479 if(CheckVersion($DBversion)) {
11480     $dbh->do(q{
11481         UPDATE letter SET name = "Hold Slip" WHERE name = "Reserve Slip"
11482     });
11483     $dbh->do(q{
11484         UPDATE letter SET title = "Hold Slip" WHERE title = "Reserve Slip";
11485     });
11486
11487     print "Upgrade to $DBversion done (Bug 8085 - Rename 'Reserve slip' to 'Hold slip')\n";
11488     SetVersion($DBversion);
11489 }
11490
11491 $DBversion = "3.23.00.004";
11492 if ( CheckVersion($DBversion) ) {
11493     $dbh->do(q{
11494         DROP TABLE IF EXISTS `stopwords`;
11495     });
11496     print "Upgrade to $DBversion done (Bug 9819 - stopwords related code should be removed)\n";
11497     SetVersion($DBversion);
11498 }
11499
11500 $DBversion = "3.23.00.005";
11501 if ( CheckVersion($DBversion) ) {
11502     $dbh->do(q{
11503         UPDATE permissions SET description = 'Manage circulation rules' WHERE description = 'manage circulation rules'
11504     });
11505     $dbh->do(q{
11506         UPDATE permissions SET description = 'Manage staged MARC records, including completing and reversing imports' WHERE description = 'Managed staged MARC records, including completing and reversing imports'
11507     });
11508     print "Upgrade to $DBversion done (Bug 11569 - Typo in userpermissions.sql)\n";
11509     SetVersion($DBversion);
11510 }
11511 $DBversion = "3.23.00.006";
11512 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
11513    $dbh->do("
11514        ALTER TABLE serial
11515         ADD serialseq_x VARCHAR( 100 ) NULL DEFAULT NULL AFTER serialseq,
11516         ADD serialseq_y VARCHAR( 100 ) NULL DEFAULT NULL AFTER serialseq_x,
11517         ADD serialseq_z VARCHAR( 100 ) NULL DEFAULT NULL AFTER serialseq_y
11518    ");
11519
11520     my $sth = $dbh->prepare("SELECT * FROM subscription");
11521     $sth->execute();
11522
11523     my $sth2 = $dbh->prepare("SELECT * FROM subscription_numberpatterns WHERE id = ?");
11524
11525     my $sth3 = $dbh->prepare("UPDATE serial SET serialseq_x = ?, serialseq_y = ?, serialseq_z = ? WHERE serialid = ?");
11526
11527     foreach my $subscription ( $sth->fetchrow_hashref() ) {
11528         next if !defined($subscription);
11529         $sth2->execute( $subscription->{numberpattern} );
11530         my $number_pattern = $sth2->fetchrow_hashref();
11531
11532         my $numbering_method = $number_pattern->{numberingmethod};
11533         # Get all the data between the enumeration values, we need
11534         # to split each enumeration string based on these values.
11535         my @splits = split( /\{[XYZ]\}/, $numbering_method );
11536         # Get the order in which the X Y and Z values are used
11537         my %indexes;
11538         foreach my $i (qw(X Y Z)) {
11539             $indexes{$i} = index( $numbering_method, "{$i}" );
11540             delete $indexes{$i} if $indexes{$i} == -1;
11541         }
11542         my @indexes = sort { $indexes{$a} <=> $indexes{$b} } keys(%indexes);
11543
11544         my @serials = @{
11545             $dbh->selectall_arrayref(
11546                 "SELECT * FROM serial WHERE subscriptionid = $subscription->{subscriptionid}",
11547                 { Slice => {} }
11548             )
11549         };
11550
11551         foreach my $serial (@serials) {
11552             my $serialseq = $serial->{serialseq};
11553             my %enumeration_data;
11554
11555             ## We cannot split on multiple values at once,
11556             ## so let's replace each of those values with __SPLIT__
11557             if (@splits) {
11558                 for my $split_item (@splits) {
11559                     my $quoted_split = quotemeta($split_item);
11560                     $serialseq =~ s/$quoted_split/__SPLIT__/;
11561                 }
11562                 (
11563                     undef,
11564                     $enumeration_data{ $indexes[0] // q{} },
11565                     $enumeration_data{ $indexes[1] // q{} },
11566                     $enumeration_data{ $indexes[2] // q{} }
11567                 ) = split( /__SPLIT__/, $serialseq );
11568             }
11569             else
11570             {    ## Nothing to split on means the only thing in serialseq is a single placeholder e.g. {X}
11571                 $enumeration_data{ $indexes[0] } = $serialseq;
11572             }
11573
11574             $sth3->execute(
11575                     $enumeration_data{'X'},
11576                     $enumeration_data{'Y'},
11577                     $enumeration_data{'Z'},
11578                     $serial->{serialid},
11579             );
11580         }
11581     }
11582
11583     print "Upgrade to $DBversion done ( Bug 8956 - Split serials enumeration data into separate fields )\n";
11584     SetVersion($DBversion);
11585 }
11586
11587 $DBversion = "3.23.00.007";
11588 if ( CheckVersion($DBversion) ) {
11589     $dbh->do("SET FOREIGN_KEY_CHECKS=0");
11590     $dbh->do("ALTER TABLE overduerules RENAME old_overduerules");
11591     $dbh->do("CREATE TABLE overduerules (
11592         `overduerules_id` int(11) NOT NULL AUTO_INCREMENT,
11593         `branchcode` varchar(10) NOT NULL DEFAULT '',
11594         `categorycode` varchar(10) NOT NULL DEFAULT '',
11595         `delay1` int(4) DEFAULT NULL,
11596         `letter1` varchar(20) DEFAULT NULL,
11597         `debarred1` varchar(1) DEFAULT '0',
11598         `delay2` int(4) DEFAULT NULL,
11599         `debarred2` varchar(1) DEFAULT '0',
11600         `letter2` varchar(20) DEFAULT NULL,
11601         `delay3` int(4) DEFAULT NULL,
11602         `letter3` varchar(20) DEFAULT NULL,
11603         `debarred3` int(1) DEFAULT '0',
11604         PRIMARY KEY (`overduerules_id`),
11605         UNIQUE KEY `overduerules_branch_cat` (`branchcode`,`categorycode`)
11606         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
11607     $dbh->do("INSERT INTO overduerules(branchcode, categorycode, delay1, letter1, debarred1, delay2, debarred2, letter2, delay3, letter3, debarred3) SELECT * FROM old_overduerules");
11608     $dbh->do("DROP TABLE old_overduerules");
11609     $dbh->do("ALTER TABLE overduerules_transport_types
11610               ADD COLUMN overduerules_id int(11) NOT NULL");
11611     my $mtts = $dbh->selectall_arrayref("SELECT * FROM overduerules_transport_types", { Slice => {} });
11612     $dbh->do("DELETE FROM overduerules_transport_types");
11613     $dbh->do("ALTER TABLE overduerules_transport_types
11614               DROP FOREIGN KEY overduerules_fk,
11615               ADD FOREIGN KEY overduerules_transport_types_fk (overduerules_id) REFERENCES overduerules (overduerules_id) ON DELETE CASCADE ON UPDATE CASCADE,
11616               DROP COLUMN branchcode,
11617               DROP COLUMN categorycode");
11618     my $s = $dbh->prepare("INSERT INTO overduerules_transport_types (overduerules_id, id, letternumber, message_transport_type) "
11619                          ." VALUES((SELECT overduerules_id FROM overduerules WHERE branchcode = ? AND categorycode = ?),?,?,?)");
11620     foreach my $mtt(@$mtts){
11621         $s->execute($mtt->{branchcode}, $mtt->{categorycode}, $mtt->{id}, $mtt->{letternumber}, $mtt->{message_transport_type} );
11622     }
11623     $dbh->do("SET FOREIGN_KEY_CHECKS=1");
11624
11625     print "Upgrade to $DBversion done (Bug 13624 - Remove columns branchcode, categorytype from table overduerules_transport_types)\n";
11626     SetVersion($DBversion);
11627 }
11628
11629 $DBversion = "3.23.00.008";
11630 if ( CheckVersion($DBversion) ) {
11631
11632     $dbh->do(q{ALTER TABLE borrowers ADD privacy_guarantor_checkouts BOOLEAN NOT NULL DEFAULT '0' AFTER privacy});
11633
11634     $dbh->do(q{ALTER TABLE deletedborrowers ADD privacy_guarantor_checkouts BOOLEAN NOT NULL DEFAULT '0' AFTER privacy});
11635
11636     $dbh->do(q{
11637         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type )
11638         VALUES (
11639             'AllowStaffToSetCheckoutsVisibilityForGuarantor',  '0', NULL,
11640             'If enabled, library staff can set a patron''s checkouts to be visible to linked patrons from the opac.',  'YesNo'
11641         ), (
11642             'AllowPatronToSetCheckoutsVisibilityForGuarantor',  '0', NULL,
11643             'If enabled, the patron can set checkouts to be visible to  his or her guarantor',  'YesNo'
11644         )
11645     });
11646
11647     print "Upgrade to $DBversion done (Bug 9303 - relative's checkouts in the opac)\n";
11648     SetVersion($DBversion);
11649 }
11650
11651 $DBversion = "3.23.00.009";
11652 if ( CheckVersion($DBversion) ) {
11653     $dbh->do(q{
11654         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type ) VALUES
11655         ( 'EnablePayPalOpacPayments',  '0', NULL ,  'Enables the ability to pay fees and fines from  the OPAC via PayPal',  'YesNo' ),
11656         ( 'PayPalChargeDescription',  'Koha fee payment', NULL ,  'This preference defines what the user will see the charge listed as in PayPal',  'Free' ),
11657         ( 'PayPalPwd',  '', NULL ,  'Your PayPal API password',  'Free' ),
11658         ( 'PayPalSandboxMode',  '1', NULL ,  'If enabled, the system will use PayPal''s sandbox server for testing, rather than the production server.',  'YesNo' ),
11659         ( 'PayPalSignature',  '', NULL ,  'Your PayPal API signature',  'Free' ),
11660         ( 'PayPalUser',  '', NULL ,  'Your PayPal API username ( email address )',  'Free' )
11661     });
11662
11663     print "Upgrade to $DBversion done (Bug 11622 - Add ability to pay fees and fines from OPAC via PayPal)\n";
11664     SetVersion($DBversion);
11665 }
11666
11667 $DBversion = "3.23.00.010";
11668 if ( CheckVersion($DBversion) ) {
11669     $dbh->do(q{
11670         ALTER TABLE issuingrules ADD cap_fine_to_replacement_price BOOLEAN NOT NULL DEFAULT '0' AFTER overduefinescap
11671     });
11672
11673     print "Upgrade to $DBversion done (Bug 9129 - Add the ability to set the maximum fine for an item to its replacement price)\n";
11674     SetVersion($DBversion);
11675 }
11676
11677 $DBversion = "3.23.00.011";
11678 if ( CheckVersion($DBversion) ) {
11679     $dbh->do(q{
11680         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES ('HoldFeeMode','not_always','always|not_always','Set the hold fee mode','Choice')
11681     });
11682
11683     print "Upgrade to $DBversion done (Bug 13592 - Hold fee not being applied on placing a hold)\n";
11684     SetVersion($DBversion);
11685 }
11686
11687 $DBversion = "3.23.00.012";
11688 if ( CheckVersion($DBversion) ) {
11689     $dbh->do(q{
11690         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')
11691     });
11692
11693     print "Upgrade to $DBversion done (Bug 15380 - Move the authority types related code to Koha::Authority::Type[s] - part 1)\n";
11694     SetVersion($DBversion);
11695 }
11696
11697 $DBversion = "3.23.00.013";
11698 if ( CheckVersion($DBversion) ) {
11699     $dbh->do(q{
11700         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')
11701     });
11702     $dbh->do(q{
11703         CREATE TABLE IF NOT EXISTS `items_last_borrower` (
11704   `id` int(11) NOT NULL AUTO_INCREMENT,
11705   `itemnumber` int(11) NOT NULL,
11706   `borrowernumber` int(11) NOT NULL,
11707   `created_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
11708   PRIMARY KEY (`id`),
11709   UNIQUE KEY `itemnumber` (`itemnumber`),
11710   KEY `borrowernumber` (`borrowernumber`),
11711   CONSTRAINT `items_last_borrower_ibfk_2` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
11712   CONSTRAINT `items_last_borrower_ibfk_1` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE
11713 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
11714     });
11715
11716     print "Upgrade to $DBversion done (Bug 14945 - Add the ability to store the last patron to return an item)\n";
11717     SetVersion($DBversion);
11718
11719 }
11720
11721 $DBversion = "3.23.00.014";
11722 if ( CheckVersion($DBversion) ) {
11723     $dbh->do(q{
11724         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
11725 VALUES ('ClaimsBccCopy','0','','Bcc the ClaimAcquisition and ClaimIssues alerts','YesNo')
11726     });
11727
11728     print "Upgrade to $DBversion done (Bug 10076 - Add Bcc syspref for claimacquisition and clamissues)\n";
11729     SetVersion($DBversion);
11730 }
11731
11732 $DBversion = "3.23.00.015";
11733 if ( CheckVersion($DBversion) ) {
11734     $dbh->do(q{
11735         UPDATE letter SET code = "HOLD_SLIP" WHERE code = "RESERVESLIP";
11736     });
11737
11738     print "Upgrade to $DBversion done (Bug 15443 - Re-code RESERVESLIP as HOLD_SLIP)\n";
11739     SetVersion($DBversion);
11740 }
11741
11742 $DBversion = "3.23.00.016";
11743 if ( CheckVersion($DBversion) ) {
11744     $dbh->do(q{
11745     INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
11746     VALUES ('OpacResetPassword',  '0','','Shows the ''Forgot your password?'' link in the OPAC','YesNo');
11747 });
11748     $dbh->do(q{
11749     CREATE TABLE IF NOT EXISTS borrower_password_recovery (
11750       borrowernumber int(11) NOT NULL,
11751       uuid varchar(128) NOT NULL,
11752       valid_until timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
11753       PRIMARY KEY (borrowernumber),
11754       KEY borrowernumber (borrowernumber)
11755     ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
11756 });
11757     $dbh->do(q{
11758     INSERT IGNORE INTO `letter` (module, code, branchcode, name, is_html, title, content, message_transport_type)
11759     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');
11760
11761     });
11762
11763     print "Upgrade to $DBversion done (Bug 8753 - Add forgot password link to OPAC)\n";
11764     SetVersion($DBversion);
11765 }
11766
11767 $DBversion = "3.23.00.017";
11768 if ( CheckVersion($DBversion) ) {
11769
11770 $dbh->do(q{
11771     DELETE FROM uploaded_files
11772     WHERE COALESCE(permanent,0)=0 AND dir='koha_upload'
11773 });
11774
11775 my $tmp= File::Spec->tmpdir.'/koha_upload';
11776 remove_tree( $tmp ) if -d $tmp;
11777
11778     print "Upgrade to $DBversion done (Bug 14893 - Separate temporary storage per instance in Upload.pm)\n";
11779     SetVersion($DBversion);
11780
11781 }
11782
11783 $DBversion = "3.23.00.018";
11784 if ( CheckVersion($DBversion) ) {
11785     $dbh->do(q{
11786         UPDATE systempreferences SET value="0" where type="YesNo" and value="";
11787     });
11788
11789     print "Upgrade to $DBversion done (Bug 15446 - Fix systempreferences rows where type=YesNo and value='')\n";
11790     SetVersion($DBversion);
11791 }
11792
11793 $DBversion = "3.23.00.019";
11794 if ( CheckVersion($DBversion) ) {
11795     $dbh->do(q{
11796         UPDATE `authorised_values` SET `lib`='Non-fiction' WHERE `lib`='Non Fiction';
11797     });
11798
11799     print "Upgrade to $DBversion done (Bug 15411 - Change Non Fiction to Non-fiction in authorised_values)\n";
11800     SetVersion($DBversion);
11801 }
11802
11803 $DBversion = "3.23.00.020";
11804 if ( CheckVersion($DBversion) ) {
11805     $dbh->do(q{
11806         CREATE TABLE  sms_providers (
11807            id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
11808            name VARCHAR( 255 ) NOT NULL ,
11809            domain VARCHAR( 255 ) NOT NULL ,
11810            UNIQUE (
11811                name
11812            )
11813         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
11814     });
11815
11816     $dbh->do(q{
11817         ALTER TABLE borrowers ADD sms_provider_id INT( 11 ) NULL DEFAULT NULL AFTER smsalertnumber;
11818     });
11819     $dbh->do(q{
11820         ALTER TABLE borrowers ADD FOREIGN KEY ( sms_provider_id ) REFERENCES sms_providers ( id ) ON UPDATE CASCADE ON DELETE SET NULL;
11821     });
11822     $dbh->do(q{
11823         ALTER TABLE deletedborrowers ADD sms_provider_id INT( 11 ) NULL DEFAULT NULL AFTER smsalertnumber;
11824     });
11825
11826     print "Upgrade to $DBversion done (Bug 9021 - Add SMS via email as an alternative to SMS services via SMS::Send drivers)\n";
11827     SetVersion($DBversion);
11828 }
11829
11830 $DBversion = "3.23.00.021";
11831 if ( CheckVersion($DBversion) ) {
11832     $dbh->do(q{
11833         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES ('ShowAllCheckins', '0', '', 'Show all checkins', 'YesNo');
11834     });
11835
11836     print "Upgrade to $DBversion done (Bug 15736 - Add a preference to control whether all items should be shown in checked-in items list)\n";
11837     SetVersion($DBversion);
11838 }
11839
11840 $DBversion = "3.23.00.022";
11841 if ( CheckVersion($DBversion) ) {
11842     $dbh->do(q{ ALTER TABLE tags_all MODIFY COLUMN borrowernumber INT(11) });
11843     $dbh->do(q{ ALTER TABLE tags_all drop FOREIGN KEY tags_borrowers_fk_1 });
11844     $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 });
11845     $dbh->do(q{ ALTER TABLE tags_approval DROP FOREIGN KEY tags_approval_borrowers_fk_1 });
11846     $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 });
11847
11848     print "Upgrade to $DBversion done (Bug 13534 - Deleting staff patron will delete tags approved by this patron)\n";
11849     SetVersion($DBversion);
11850 }
11851
11852 $DBversion = "3.23.00.023";
11853 if ( CheckVersion($DBversion) ) {
11854     $dbh->do(q{
11855         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11856         VALUES('OpenLibrarySearch','0','If Yes Open Library search results will show in OPAC',NULL,'YesNo');
11857     });
11858
11859     print "Upgrade to $DBversion done (Bug 6624 - Allow Koha to use the new read API from OpenLibrary)\n";
11860     SetVersion($DBversion);
11861 }
11862
11863 $DBversion = "3.23.00.024";
11864 if ( CheckVersion($DBversion) ) {
11865     $dbh->do(q{
11866         ALTER TABLE deletedborrowers MODIFY COLUMN userid VARCHAR(75) DEFAULT NULL;
11867     });
11868
11869     $dbh->do(q{
11870         ALTER TABLE deletedborrowers MODIFY COLUMN password VARCHAR(60) DEFAULT NULL;
11871     });
11872
11873     print "Upgrade to $DBversion done (Bug 15517 - Tables borrowers and deletedborrowers differ again)\n";
11874     SetVersion($DBversion);
11875 }
11876
11877 $DBversion = "3.23.00.025";
11878 if ( CheckVersion($DBversion) ) {
11879     $dbh->do(q{
11880         DROP TABLE IF EXISTS nozebra;
11881     });
11882
11883     print "Upgrade to $DBversion done (Bug 15526 - Drop nozebra database table)\n";
11884     SetVersion($DBversion);
11885 }
11886
11887 $DBversion = "3.23.00.026";
11888 if ( CheckVersion($DBversion) ) {
11889     $dbh->do(q{
11890         UPDATE systempreferences SET value = CONCAT_WS('|', IF(value='', NULL, value), "password") WHERE variable="PatronSelfRegistrationBorrowerUnwantedField" AND value NOT LIKE "%password%";
11891     });
11892
11893     print "Upgrade to $DBversion done (Bug 15343 - Allow patrons to choose their own password on self registration)\n";
11894     SetVersion($DBversion);
11895 }
11896
11897 $DBversion = "3.23.00.027";
11898 if ( CheckVersion($DBversion) ) {
11899     my ( $db_value ) = $dbh->selectrow_array(q|SELECT count(*) FROM branches|);
11900     my $pref_value = C4::Context->preference("singleBranchMode") || 0;
11901     if ( $db_value > 1 and $pref_value == 1 ) {
11902         warn "WARNING: You have more than 1 libraries in your branches tables but the singleBranchMode system preference is on.\n";
11903         warn "This configuration does not make sense. The system preference is going to be deleted,\n";
11904         warn "and this parameter will be based on the number of libraries defined.\n";
11905     }
11906     $dbh->do(q|DELETE FROM systempreferences WHERE variable="singleBranchMode"|);
11907
11908     print "Upgrade to $DBversion done (Bug 4941 - Can't set branch in staff client when singleBranchMode is enabled)\n";
11909     SetVersion($DBversion);
11910 }
11911
11912 $DBversion = "3.23.00.028";
11913 if ( CheckVersion($DBversion) ) {
11914     $dbh->do(q{
11915         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';
11916     });
11917
11918     print "Upgrade to $DBversion done (Bug 14658 - Split PatronSelfRegistrationBorrowerUnwantedField into two preferences for creating and editing)\n";
11919     SetVersion($DBversion);
11920 }
11921
11922 $DBversion = "3.23.00.029";
11923 if ( CheckVersion($DBversion) ) {
11924
11925     # move marc21_field_003.pl 040c and 040d to marc21_orgcode.pl
11926     $dbh->do(q{
11927         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' );
11928     });
11929     $dbh->do(q{
11930         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' );
11931     });
11932
11933     print "Upgrade to $DBversion done (Bug 14199 - Unify all organization code plugins)\n";
11934     SetVersion($DBversion);
11935 }
11936
11937 $DBversion = "3.23.00.030";
11938 if(CheckVersion($DBversion)) {
11939     $dbh->do(q{
11940         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
11941         VALUES ('OpacMaintenanceNotice','','','A user-defined block of HTML to appear on screen when OpacMaintenace is enabled','Textarea')
11942     });
11943
11944     print "Upgrade to $DBversion done (Bug 15311: Let libraries set text to display when OpacMaintenance = on)\n";
11945     SetVersion($DBversion);
11946 }
11947
11948 $DBversion = "3.23.00.031";
11949 if(CheckVersion($DBversion)) {
11950     $dbh->do(q{
11951         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11952         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')
11953     });
11954
11955     print "Upgrade to $DBversion done (Bug 14395 - Two different ways to calculate 'No renewal before')\n";
11956     SetVersion($DBversion);
11957 }
11958
11959 $DBversion = "3.23.00.032";
11960 if ( CheckVersion($DBversion) ) {
11961     $dbh->do(q{
11962    -- Add issue_id to accountlines table
11963     ALTER TABLE accountlines ADD issue_id INT(11) NULL DEFAULT NULL AFTER accountlines_id;
11964     });
11965
11966 ## Close out any accruing fines with no current issue
11967     $dbh->do(q{
11968     UPDATE accountlines LEFT JOIN issues USING ( itemnumber, borrowernumber ) SET accounttype = 'F' WHERE accounttype = 'FU' and issues.issue_id IS NULL;
11969     });
11970
11971 ## Close out any extra not really accruing fines, keep only the latest accring fine
11972     $dbh->do(q{
11973     UPDATE accountlines a1
11974     LEFT JOIN (SELECT MAX(accountlines_id) AS keeper,
11975                       borrowernumber,
11976                       itemnumber
11977                FROM   accountlines
11978                WHERE  accounttype = 'FU'
11979                GROUP BY borrowernumber, itemnumber
11980               ) a2 USING ( borrowernumber, itemnumber )
11981     SET    a1.accounttype = 'F'
11982     WHERE  a1.accounttype = 'FU'
11983     AND  a1.accountlines_id != a2.keeper;
11984     });
11985
11986 ## Update the unclosed fines to add the current issue_id to them
11987     $dbh->do(q{
11988     UPDATE accountlines LEFT JOIN issues USING ( itemnumber ) SET accountlines.issue_id = issues.issue_id WHERE accounttype = 'FU'; 
11989     });
11990
11991     print "Upgrade to $DBversion done (Bug 15675 - Add issue_id column to accountlines and use it for updating fines)\n";
11992     SetVersion($DBversion);
11993 }
11994
11995 $DBversion = "3.23.00.033";
11996 if ( CheckVersion($DBversion) ) {
11997     $dbh->do(q{
11998     UPDATE systempreferences SET value = CONCAT_WS('|', IF(value = '', NULL, value), 'cardnumber') WHERE variable = 'PatronSelfRegistrationBorrowerUnwantedField' AND value NOT LIKE '%cardnumber%';
11999     });
12000
12001     $dbh->do(q{
12002     UPDATE systempreferences SET value = CONCAT_WS('|', IF(value = '', NULL, value), 'categorycode') WHERE variable = 'PatronSelfRegistrationBorrowerUnwantedField' AND value NOT LIKE '%categorycode%';
12003     });
12004
12005     print "Upgrade to $DBversion done (Bug 14659 - Allow patrons to enter card number and patron category on OPAC registration page)\n";
12006     SetVersion($DBversion);
12007 }
12008
12009 $DBversion = "3.23.00.034";
12010 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12011     $dbh->do(q{
12012         ALTER TABLE `items` ADD `new` VARCHAR(32) NULL AFTER `stocknumber`;
12013     });
12014     $dbh->do(q{
12015         ALTER TABLE `deleteditems` ADD `new` VARCHAR(32) NULL AFTER `stocknumber`;
12016     });
12017     print "Upgrade to $DBversion done (Bug 11023: Adds field 'new' in items and deleteditems tables)\n";
12018     SetVersion($DBversion);
12019 }
12020
12021 $DBversion = "3.23.00.035";
12022 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12023     $dbh->do(q{
12024         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('HTML5MediaYouTube',0,'Embed|Don\'t embed','YouTube links as videos','YesNo');
12025     });
12026     print "Upgrade to $DBversion done (Bug 14168 - enhance streaming cataloging to include youtube)\n";
12027
12028     SetVersion($DBversion);
12029     }
12030
12031 $DBversion = "3.23.00.036";
12032 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12033     $dbh->do(q{
12034     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');
12035     });
12036     print "Upgrade to $DBversion done (Bug 12803 - Add ability to skip closed libraries when generating the holds queue)\n";
12037     SetVersion($DBversion);
12038     }
12039
12040 $DBversion = "3.23.00.037";
12041 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12042 ## Add the new currency.archived column
12043     $dbh->do(q{
12044     ALTER TABLE currency ADD column archived tinyint(1) DEFAULT 0;
12045     });
12046 ## Set currency=NULL if empty (just in case)
12047     $dbh->do(q{
12048     UPDATE aqorders SET currency=NULL WHERE currency="";
12049     });
12050 ## Insert the missing currency and mark them as archived before adding the FK
12051     $dbh->do(q{
12052     INSERT INTO currency(currency, archived) SELECT distinct currency, 1 FROM aqorders WHERE currency NOT IN (SELECT currency FROM currency);
12053     });
12054 ## Correct the field length in aqorders before adding FK too
12055     $dbh->do(q{ ALTER TABLE aqorders MODIFY COLUMN currency varchar(10) default NULL; });
12056 ## And finally add the FK
12057     $dbh->do(q{
12058     ALTER TABLE aqorders ADD FOREIGN KEY (currency) REFERENCES currency(currency) ON DELETE SET NULL ON UPDATE SET null;
12059     });
12060
12061     print "Upgrade to $DBversion done (Bug 15084 - Move the currency related code to Koha::Acquisition::Currenc[y|ies])\n";
12062     SetVersion($DBversion);
12063 }
12064
12065 $DBversion = "3.23.00.038";
12066 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12067     $dbh->do(q{
12068     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');
12069     });
12070     print "Upgrade to $DBversion done (Bug 14694 - Make decreaseloanHighHolds more flexible)\n";
12071     SetVersion($DBversion);
12072 }
12073
12074 $DBversion = "3.23.00.039";
12075 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12076
12077     $dbh->do(q{
12078     ALTER TABLE suggestions
12079     MODIFY COLUMN currency varchar(10) default NULL;
12080     });
12081     $dbh->do(q{
12082     ALTER TABLE aqbooksellers
12083     MODIFY COLUMN currency varchar(10) default NULL;
12084     });
12085     print "Upgrade to $DBversion done (Bug 15084 - Move the currency related code to Koha::Acquisition::Currenc[y|ies])\n";
12086     SetVersion($DBversion);
12087 }
12088
12089
12090 $DBversion = "3.23.00.040";
12091 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12092
12093     my $c = $dbh->selectrow_array('SELECT COUNT(*) FROM systempreferences WHERE variable="intranetcolorstylesheet" AND value="blue.css"');
12094
12095     if ( $c ) {
12096         print "WARNING: You are using a stylesheeet which has been removed from the Koha codebase.\n";
12097         print "Update your intranetcolorstylesheet.\n";
12098     }
12099     print "Upgrade to $DBversion done (Bug 16019 - Check intranetcolorstylesheet for blue.css)\n";
12100     SetVersion($DBversion);
12101 }
12102
12103 $DBversion = "3.23.00.041";
12104 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12105
12106     my $dbh = C4::Context->dbh;
12107     my ($print_error) = $dbh->{PrintError};
12108     $dbh->{RaiseError} = 0;
12109     $dbh->{PrintError} = 0;
12110     $dbh->do("ALTER TABLE overduerules_transport_types ADD COLUMN letternumber INT(1) NOT NULL DEFAULT 1 AFTER id");
12111     $dbh->{PrintError} = $print_error;
12112
12113     print "Upgrade to $DBversion done (Bug 16007: Make sure overduerules_transport_types.letternumber exists)\n";
12114     SetVersion($DBversion);
12115 }
12116
12117 $DBversion = "3.23.00.042";
12118 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12119
12120     $dbh->do(q{
12121             ALTER TABLE items CHANGE new new_status VARCHAR(32) NULL;
12122             });
12123     $dbh->do(q{
12124             ALTER TABLE deleteditems CHANGE new new_status VARCHAR(32) NULL;
12125             });
12126     $dbh->do(q{
12127             UPDATE systempreferences SET value=REPLACE(value, '"items.new"', '"items.new_status"') WHERE variable="automatic_item_modification_by_age_configuration";
12128             });
12129
12130     print "Upgrade to $DBversion done (Bug 16004 - Replace items.new with items.new_status)\n";
12131     SetVersion($DBversion);
12132 }
12133
12134 $DBversion = "3.23.00.043";
12135 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12136     $dbh->do(q{
12137             UPDATE systempreferences SET value="" WHERE value IS NULL;
12138             });
12139
12140     print "Upgrade to $DBversion done (Bug 16070 - Empty (undef) system preferences may cause some issues in combination with memcache)\n";
12141     SetVersion($DBversion);
12142 }
12143
12144 $DBversion = "3.23.00.044";
12145 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12146     $dbh->do(q{
12147             INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
12148             ('GoogleOpenIDConnect', '0', NULL, 'if ON, allows the use of Google OpenID Connect for login', 'YesNo'),
12149             ('GoogleOAuth2ClientID', '', NULL, 'Client ID for the web app registered with Google', 'Free'),
12150             ('GoogleOAuth2ClientSecret', '', NULL, 'Client Secret for the web app registered with Google', 'Free'),
12151             ('GoogleOpenIDConnectDomain', '', NULL, 'Restrict OpenID Connect to this domain (or subdomains of this domain). Leave blank for all Google domains', 'Free');
12152             });
12153
12154     print "Upgrade to $DBversion done (Bug 10988 - Allow login via Google OAuth2 (OpenID Connect))\n";
12155     SetVersion($DBversion);
12156 }
12157
12158 $DBversion = "3.23.00.045";
12159 if ( CheckVersion($DBversion) ) {
12160 ## Holds details for vendors supplying goods by EDI
12161    $dbh->do(q{
12162            CREATE TABLE IF NOT EXISTS vendor_edi_accounts (
12163                    id INT(11) NOT NULL auto_increment,
12164                    description TEXT NOT NULL,
12165                    host VARCHAR(40),
12166                    username VARCHAR(40),
12167                    password VARCHAR(40),
12168                    last_activity DATE,
12169                    vendor_id INT(11) REFERENCES aqbooksellers( id ),
12170                    download_directory TEXT,
12171                    upload_directory TEXT,
12172                    san VARCHAR(20),
12173                    id_code_qualifier VARCHAR(3) default '14',
12174                    transport VARCHAR(6) default 'FTP',
12175                    quotes_enabled TINYINT(1) not null default 0,
12176                    invoices_enabled TINYINT(1) not null default 0,
12177                    orders_enabled TINYINT(1) not null default 0,
12178                    responses_enabled TINYINT(1) not null default 0,
12179                    auto_orders TINYINT(1) not null default 0,
12180                    shipment_budget INTEGER(11) REFERENCES aqbudgets( budget_id ),
12181                    PRIMARY KEY  (id),
12182                    KEY vendorid (vendor_id),
12183                    KEY shipmentbudget (shipment_budget),
12184                    CONSTRAINT vfk_vendor_id FOREIGN KEY ( vendor_id ) REFERENCES aqbooksellers ( id ),
12185                    CONSTRAINT vfk_shipment_budget FOREIGN KEY ( shipment_budget ) REFERENCES aqbudgets ( budget_id )
12186                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
12187    });
12188
12189 ## Hold the actual edifact messages with links to associated baskets
12190    $dbh->do(q{
12191            CREATE TABLE IF NOT EXISTS edifact_messages (
12192                    id INT(11) NOT NULL auto_increment,
12193                    message_type VARCHAR(10) NOT NULL,
12194                    transfer_date DATE,
12195                    vendor_id INT(11) REFERENCES aqbooksellers( id ),
12196                    edi_acct  INTEGER REFERENCES vendor_edi_accounts( id ),
12197                    status TEXT,
12198                    basketno INT(11) REFERENCES aqbasket( basketno),
12199                    raw_msg MEDIUMTEXT,
12200                    filename TEXT,
12201                    deleted BOOLEAN NOT NULL DEFAULT 0,
12202                    PRIMARY KEY  (id),
12203                    KEY vendorid ( vendor_id),
12204                    KEY ediacct (edi_acct),
12205                    KEY basketno ( basketno),
12206                    CONSTRAINT emfk_vendor FOREIGN KEY ( vendor_id ) REFERENCES aqbooksellers ( id ),
12207                    CONSTRAINT emfk_edi_acct FOREIGN KEY ( edi_acct ) REFERENCES vendor_edi_accounts ( id ),
12208                    CONSTRAINT emfk_basketno FOREIGN KEY ( basketno ) REFERENCES aqbasket ( basketno )
12209                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
12210             });
12211
12212 ## invoices link back to the edifact message it was generated from
12213    $dbh->do(q{
12214            ALTER TABLE aqinvoices ADD COLUMN message_id INT(11) REFERENCES edifact_messages( id );
12215            });
12216
12217 ## clean up link on deletes
12218    $dbh->do(q{
12219            ALTER TABLE aqinvoices ADD CONSTRAINT edifact_msg_fk FOREIGN KEY ( message_id ) REFERENCES edifact_messages ( id ) ON DELETE SET NULL;
12220            });
12221
12222 ## Hold the supplier ids from quotes for ordering
12223 ## although this is an EAN-13 article number the standard says 35 characters ???
12224    $dbh->do(q{
12225            ALTER TABLE aqorders ADD COLUMN line_item_id VARCHAR(35);
12226            });
12227
12228 ## The suppliers unique reference usually a quotation line number ('QLI')
12229 ## Otherwise Suppliers unique orderline reference ('SLI')
12230    $dbh->do(q{
12231            ALTER TABLE aqorders ADD COLUMN suppliers_reference_number VARCHAR(35);
12232            });
12233    $dbh->do(q{
12234            ALTER TABLE aqorders ADD COLUMN suppliers_reference_qualifier VARCHAR(3);
12235            });
12236    $dbh->do(q{
12237            ALTER TABLE aqorders ADD COLUMN suppliers_report text;
12238            });
12239
12240 ## hold the EAN/SAN used in ordering
12241    $dbh->do(q{
12242            CREATE TABLE IF NOT EXISTS edifact_ean (
12243                    ee_id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
12244                    description VARCHAR(128) NULL DEFAULT NULL,
12245                    branchcode VARCHAR(10) NOT NULL REFERENCES branches (branchcode),
12246                    ean VARCHAR(15) NOT NULL,
12247                    id_code_qualifier VARCHAR(3) NOT NULL DEFAULT '14',
12248                    CONSTRAINT efk_branchcode FOREIGN KEY ( branchcode ) REFERENCES branches ( branchcode )
12249                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
12250            });
12251
12252 ## Add a permission for managing EDI
12253    $dbh->do(q{
12254            INSERT INTO permissions (module_bit, code, description) values (11, 'edi_manage', 'Manage EDIFACT transmissions');
12255            });
12256
12257    print "Upgrade to $DBversion done (Bug 7736 - Edifact QUOTE and ORDER functionality))\n";
12258    SetVersion($DBversion);
12259 }
12260
12261 $DBversion = "3.23.00.046";
12262 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12263
12264     $dbh->do(q{
12265     ALTER TABLE vendor_edi_accounts ADD COLUMN plugin VARCHAR(256) NOT NULL DEFAULT "";
12266     });
12267
12268     print "Upgrade to $DBversion done (Bug 15630 - Make Edifact module pluggable))\n";
12269     SetVersion($DBversion);
12270 }
12271
12272 $DBversion = "3.23.00.047";
12273 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12274
12275     $dbh->do(q{
12276          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');
12277          });
12278     $dbh->do(q{
12279          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');
12280          });
12281
12282     print "Upgrade to $DBversion done (Bug 15008 - Add custom HTML areas to circulation and reports home pages)\n";
12283     SetVersion($DBversion);
12284 }
12285
12286 $DBversion = "3.23.00.048";
12287 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12288     $dbh->do(q{
12289     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';
12290     });
12291
12292     print "Upgrade to $DBversion done (Bug 5979 - Add separate OPACISBD system preference)\n";
12293     SetVersion($DBversion);
12294 }
12295
12296
12297
12298 $DBversion = "3.23.00.049";
12299 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12300 my $dbh = C4::Context->dbh;
12301 my ( $column_has_been_used ) = $dbh->selectrow_array(q|
12302             SELECT COUNT(*)
12303                 FROM borrower_attributes
12304                     WHERE password IS NOT NULL
12305                     |);
12306
12307 if ( $column_has_been_used ) {
12308         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.|;
12309 } else {
12310         $dbh->do(q|
12311         ALTER TABLE borrower_attribute_types DROP column password_allowed
12312         |);
12313         $dbh->do(q|
12314         ALTER TABLE borrower_attributes DROP column password;
12315         |);
12316     }
12317     print "Upgrade to $DBversion done (Bug 12267 - Allow password option in Patron Attribute non functional)\n";
12318         SetVersion($DBversion);
12319 }
12320
12321
12322 $DBversion = "3.23.00.050";
12323 if ( CheckVersion($DBversion) ) {
12324     use Koha::SearchMarcMaps;
12325     use Koha::SearchFields;
12326     use Koha::SearchEngine::Elasticsearch;
12327
12328     $dbh->do(q|INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
12329                     VALUES('SearchEngine','Zebra','Choose Search Engine','','Choice')|);
12330
12331
12332     $dbh->do(q|DROP TABLE IF EXISTS search_marc_to_field|);
12333     $dbh->do(q|DROP TABLE IF EXISTS search_marc_map|);
12334     $dbh->do(q|DROP TABLE IF EXISTS search_field|);
12335
12336 # This specifies the fields that will be stored in the search engine.
12337  $dbh->do(q|
12338          CREATE TABLE `search_field` (
12339              `id` int(11) NOT NULL AUTO_INCREMENT, 
12340              `name` varchar(255) NOT NULL COMMENT 'the name of the field as it will be stored in the search engine',
12341              `label` varchar(255) NOT NULL COMMENT 'the human readable name of the field, for display', 
12342              `type` ENUM('', 'string', 'date', 'number', 'boolean', 'sum') NOT NULL COMMENT 'what type of data this holds, relevant when storing it in the search engine',
12343              PRIMARY KEY (`id`),
12344              UNIQUE KEY (`name`)
12345              ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
12346          |);
12347 # This contains a MARC field specifier for a given index, marc type, and marc
12348 # field.
12349 $dbh->do(q|
12350         CREATE TABLE `search_marc_map` (
12351             id int(11) NOT NULL AUTO_INCREMENT,
12352             index_name ENUM('biblios','authorities') NOT NULL COMMENT 'what storage index this map is for',
12353             marc_type ENUM('marc21', 'unimarc', 'normarc') NOT NULL COMMENT 'what MARC type this map is for',
12354             marc_field VARCHAR(255) NOT NULL COMMENT 'the MARC specifier for this field',
12355             PRIMARY KEY(`id`),
12356             unique key( index_name, marc_field, marc_type),
12357             INDEX (`index_name`)
12358             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
12359         |);
12360
12361 # This joins the two search tables together. We can have any combination:
12362 # one marc field could have many search fields (maybe you want one value
12363 # to go to 'author' and 'corporate-author) and many marc fields could go
12364 # to one search field (e.g. all the various author fields going into
12365 # 'author'.)
12366 #
12367 # a note about the sort field:
12368 # * if all the entries for a mapping are 'null', nothing special is done with that mapping.
12369 # * if any of the entries are not null, then a __sort field is created in ES for this mapping. In this case:
12370 #   * any mapping with sort == false WILL NOT get copied into a __sort field
12371 #   * any mapping with sort == true or is null WILL get copied into a __sort field
12372 #   * any sorts on the field name will be applied to $fieldname.'__sort' instead.
12373 # this means that we can have search for author that includes 1xx, 245$c, and 7xx, but the sort only applies to 1xx.
12374
12375 $dbh->do(q|
12376         CREATE TABLE `search_marc_to_field` (
12377             search_marc_map_id int(11) NOT NULL,
12378             search_field_id int(11) NOT NULL,
12379             facet boolean DEFAULT FALSE COMMENT 'true if a facet field should be generated for this',
12380             suggestible boolean DEFAULT FALSE COMMENT 'true if this field can be used to generate suggestions for browse',
12381             sort boolean DEFAULT NULL COMMENT 'true/false creates special sort handling, null doesn''t',
12382             PRIMARY KEY(search_marc_map_id, search_field_id),
12383             FOREIGN KEY(search_marc_map_id) REFERENCES search_marc_map(id) ON DELETE CASCADE ON UPDATE CASCADE,
12384             FOREIGN KEY(search_field_id) REFERENCES search_field(id) ON DELETE CASCADE ON UPDATE CASCADE
12385             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
12386         |);
12387
12388         # Insert default mappings
12389         Koha::SearchEngine::Elasticsearch->reset_elasticsearch_mappings;
12390
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 16274 - Make the selfregistration branchcode selection configurable)\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     require Koha::Holds;
14359
14360     $dbh->do(q{
14361         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) 
14362         VALUES ('ExcludeHolidaysFromMaxPickUpDelay', '0', 'If ON, reserves max pickup delay takes into account the closed days.', NULL, 'Integer');
14363     });
14364
14365     my $waiting_holds = Koha::Holds->search({ found => 'W', priority => 0 });
14366     my $max_pickup_delay = C4::Context->preference("ReservesMaxPickUpDelay");
14367     while ( my $hold = $waiting_holds->next ) {
14368
14369         my $requested_expiration;
14370         if ($hold->expirationdate) {
14371             $requested_expiration = dt_from_string($hold->expirationdate);
14372         }
14373
14374         my $expirationdate = dt_from_string($hold->waitingdate);
14375         if ( C4::Context->preference("ExcludeHolidaysFromMaxPickUpDelay") ) {
14376             my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
14377             $expirationdate = $calendar->days_forward( $expirationdate, $max_pickup_delay );
14378         } else {
14379             $expirationdate->add( days => $max_pickup_delay );
14380         }
14381
14382         my $cmp = $requested_expiration ? DateTime->compare($requested_expiration, $expirationdate) : 0;
14383         $hold->expirationdate($cmp == -1 ? $requested_expiration->ymd : $expirationdate->ymd)->store;
14384     }
14385
14386     SetVersion( $DBversion );
14387     print "Upgrade to $DBversion done (Bug 12063 - Update reserves.expirationdate)\n";
14388 }
14389
14390 $DBversion = '16.12.00.033';
14391 if( CheckVersion( $DBversion ) ) {
14392
14393     if( !column_exists( 'letter', 'lang' ) ) {
14394         $dbh->do( "ALTER TABLE letter ADD COLUMN lang VARCHAR(25) NOT NULL DEFAULT 'default' AFTER message_transport_type" );
14395     }
14396
14397     if( !column_exists( 'borrowers', 'lang' ) ) {
14398         $dbh->do( "ALTER TABLE borrowers ADD COLUMN lang VARCHAR(25) NOT NULL DEFAULT 'default' AFTER lastseen" );
14399         $dbh->do( "ALTER TABLE deletedborrowers ADD COLUMN lang VARCHAR(25) NOT NULL DEFAULT 'default' AFTER lastseen" );
14400     }
14401
14402     # Add test on existene of this key
14403     $dbh->do( "ALTER TABLE message_transports DROP FOREIGN KEY message_transports_ibfk_3 ");
14404     $dbh->do( "ALTER TABLE letter DROP PRIMARY KEY ");
14405     $dbh->do( "ALTER TABLE letter ADD PRIMARY KEY (`module`, `code`, `branchcode`, `message_transport_type`, `lang`) ");
14406
14407     $dbh->do( "INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
14408         VALUES ('TranslateNotices',  '0',  NULL,  'Allow notices to be translated',  'YesNo') ");
14409
14410     SetVersion( $DBversion );
14411     print "Upgrade to $DBversion done (Bug 17762 - Add columns letter.lang and borrowers.lang to allow translation of notices)\n";
14412 }
14413
14414 $DBversion = '16.12.00.034';
14415 if( CheckVersion( $DBversion ) ) {
14416     $dbh->do(q{
14417         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
14418         VALUES ('OPACFineNoRenewalsBlockAutoRenew','0','','Block/Allow auto renewals if the patron owe more than OPACFineNoRenewals','YesNo')
14419     });
14420
14421     SetVersion( $DBversion );
14422     print "Upgrade to $DBversion done (Bug 15582 - Ability to block auto renewals if the OPACFineNoRenewals amount is reached)\n";
14423 }
14424
14425 $DBversion = '16.12.00.035';
14426 if( CheckVersion( $DBversion ) ) {
14427     if( !column_exists( 'issues', 'auto_renew_error' ) ) {
14428         $dbh->do(q{
14429            ALTER TABLE issues ADD COLUMN auto_renew_error VARCHAR(32) DEFAULT NULL AFTER auto_renew;
14430         });
14431     }
14432
14433     if( !column_exists( 'old_issues', 'auto_renew_error' ) ) {
14434         $dbh->do(q{
14435             ALTER TABLE old_issues ADD COLUMN auto_renew_error VARCHAR(32) DEFAULT NULL AFTER auto_renew;
14436         });
14437     }
14438
14439     $dbh->do(q{
14440         INSERT INTO letter (module, code, name, title, content, message_transport_type) VALUES ('circulation', 'AUTO_RENEWALS', 'notification on auto renewing', 'Auto renewals',
14441 "Dear [% borrower.firstname %] [% borrower.surname %],
14442 [% IF checkout.auto_renew_error %]
14443 The following item [% biblio.title %] has not been correctly renewed
14444 [% IF checkout.auto_renew_error == 'too_many' %]
14445 You have reach the maximum of checkouts possible.
14446 [% ELSIF checkout.auto_renew_error == 'on_reserve' %]
14447 This item is on hold for another patron.
14448 [% ELSIF checkout.auto_renew_error == 'restriction' %]
14449 You are currently restricted.
14450 [% ELSIF checkout.auto_renew_error == 'overdue' %]
14451 You have overdues.
14452 [% ELSIF checkout.auto_renew_error == 'auto_too_late' %]
14453 It\'s too late to renew this checkout.
14454 [% ELSIF checkout.auto_renew_error == 'auto_too_much_oweing' %]
14455 You have too much unpaid fines.
14456 [% END %]
14457 [% ELSE %]
14458 The following item [% biblio.title %] has correctly been renewed and is now due [% checkout.date_due %]
14459 [% END %]", 'email');
14460     });
14461
14462     SetVersion( $DBversion );
14463     print "Upgrade to $DBversion done (Bug 15705 - Notify the user on auto renewing)\n";
14464 }
14465
14466 $DBversion = '16.12.00.036';
14467 if( CheckVersion( $DBversion ) ) {
14468     $dbh->do(q{
14469         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
14470         VALUES ('NumSavedReports', '20', NULL, 'By default, show this number of saved reports.', 'Integer');
14471     });
14472
14473     SetVersion( $DBversion );
14474     print "Upgrade to $DBversion done (Bug 17465 - Add a System Preference to control number of Saved Reports displayed)\n";
14475 }
14476
14477 $DBversion = '16.12.00.037';
14478 if( CheckVersion( $DBversion ) ) {
14479     $dbh->do( q|
14480         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
14481         VALUES ('FailedLoginAttempts','','','Number of login attempts before lockout the patron account','Integer');
14482     |);
14483
14484     unless( column_exists( 'borrowers', 'login_attempts' ) ) {
14485         $dbh->do(q|
14486             ALTER TABLE borrowers ADD COLUMN login_attempts INT(4) DEFAULT 0 AFTER lastseen
14487         |);
14488         $dbh->do(q|
14489             ALTER TABLE deletedborrowers ADD COLUMN login_attempts INT(4) DEFAULT 0 AFTER lastseen
14490         |);
14491     }
14492
14493     SetVersion( $DBversion );
14494     print "Upgrade to $DBversion done (Bug 18314 - Add FailedLoginAttempts and borrowers.login_attempts)\n";
14495 }
14496
14497 $DBversion = '16.12.00.038';
14498 if( CheckVersion( $DBversion ) ) {
14499     $dbh->do(q{
14500         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14501         ('ExportRemoveFields','',NULL,'List of fields for non export in circulation.pl (separated by a space)','Free');
14502     });
14503
14504     SetVersion( $DBversion );
14505     print "Upgrade to $DBversion done (Bug 18663 - Missing db update for ExportRemoveFields)\n";
14506 }
14507
14508 $DBversion = '16.12.00.039';
14509 if( CheckVersion( $DBversion ) ) {
14510     $dbh->do(q{
14511         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14512         ('TalkingTechItivaPhoneNotification','0',NULL,'If ON, enables Talking Tech I-tiva phone notifications','YesNo');
14513     });
14514
14515     SetVersion( $DBversion );
14516     print "Upgrade to $DBversion done (Bug 18600 - Missing db update for TalkingTechItivaPhoneNotification)\n";
14517 }
14518
14519 $DBversion = '17.05.00.000';
14520 if( CheckVersion( $DBversion ) ) {
14521
14522     SetVersion( $DBversion );
14523     print "Upgrade to $DBversion done (Koha 17.05)\n";
14524 }
14525
14526 $DBversion = '17.06.00.000';
14527 if( CheckVersion( $DBversion ) ) {
14528     SetVersion( $DBversion );
14529     print "Upgrade to $DBversion done (He pai ake te iti i te kore)\n";
14530 }
14531
14532 $DBversion = '17.06.00.001';
14533 if( CheckVersion( $DBversion ) ) {
14534
14535     unless ( column_exists( 'export_format', 'used_for' ) ) {
14536         $dbh->do(q|ALTER TABLE export_format ADD used_for varchar(255) DEFAULT 'export_records' AFTER type|);
14537
14538         $dbh->do(q|UPDATE export_format SET used_for = 'late_issues' WHERE type = 'sql'|);
14539         $dbh->do(q|UPDATE export_format SET used_for = 'export_records' WHERE type = 'marc'|);
14540     }
14541     SetVersion( $DBversion );
14542     print "Upgrade to $DBversion done (Bug 8612 - Add new column export_format.used_for)\n";
14543 }
14544
14545 $DBversion = '17.06.00.002';
14546 if ( CheckVersion($DBversion) ) {
14547
14548     unless ( column_exists('virtualshelves', 'allow_change_from_owner' ) ) {
14549         $dbh->do(q|
14550             ALTER TABLE virtualshelves
14551             ADD COLUMN allow_change_from_owner tinyint(1) default 1,
14552             ADD COLUMN allow_change_from_others tinyint(1) default 0
14553         |);
14554
14555         # Conversion:
14556         # Since we had no readonly lists, change_from_owner is set to true.
14557         # When adding or delete_other was granted, change_from_others is true.
14558         # Note: In my opinion the best choice; there is no exact match.
14559         $dbh->do(q|
14560             UPDATE virtualshelves
14561             SET allow_change_from_owner = 1,
14562                 allow_change_from_others = CASE WHEN allow_add=1 OR allow_delete_other=1 THEN 1 ELSE 0 END
14563         |);
14564
14565         # Remove the old columns
14566         $dbh->do(q|
14567             ALTER TABLE virtualshelves
14568             DROP COLUMN allow_add,
14569             DROP COLUMN allow_delete_own,
14570             DROP COLUMN allow_delete_other
14571         |);
14572     }
14573
14574     SetVersion($DBversion);
14575     print "Upgrade to $DBversion done (Bug 18228 - Alter table virtualshelves to simplify permissions)\n";
14576 }
14577
14578 $DBversion = '17.06.00.003';
14579 if ( CheckVersion($DBversion) ) {
14580
14581     # Fetch all auth types
14582     my $authtypes = $dbh->selectcol_arrayref(q|SELECT authtypecode FROM auth_types|);
14583
14584     if ( grep { $_ eq 'Default' } @$authtypes ) {
14585
14586         # If this exists as an authtypecode, we don't do anything
14587     }
14588     else {
14589         # Replace the incorrect Default by empty string
14590         $dbh->do(q|
14591             UPDATE auth_header SET authtypecode='' WHERE authtypecode='Default'
14592         |);
14593     }
14594
14595     SetVersion($DBversion);
14596     print "Upgrade to $DBversion done (Bug 18801 - Update incorrect Default auth type codes)\n";
14597 }
14598
14599 $DBversion = '17.06.00.004';
14600 if( CheckVersion( $DBversion ) ) {
14601     $dbh->do(q{
14602         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14603         ('GoogleOpenIDConnectAutoRegister',   '0',NULL,' Google OpenID Connect logins to auto-register patrons.','YesNo'),
14604         ('GoogleOpenIDConnectDefaultCategory','','','This category code will be used to create Google OpenID Connect patrons.','Textarea'),
14605         ('GoogleOpenIDConnectDefaultBranch',  '','','This branch code will be used to create Google OpenID Connect patrons.','Textarea');
14606     });
14607
14608     SetVersion( $DBversion );
14609     print "Upgrade to $DBversion done (Bug 16892: Add automatic patron registration via OAuth2 login)\n";
14610 }
14611
14612 $DBversion = '17.06.00.005';
14613 if( CheckVersion( $DBversion ) ) {
14614     $dbh->do(q{
14615         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')
14616         });
14617
14618     SetVersion( $DBversion );
14619     print "Upgrade to $DBversion done (Bug 18718 - Language selector in staff header menu similar to OPAC )\n";
14620 }
14621
14622 $DBversion = '17.06.00.006';
14623 if( CheckVersion( $DBversion ) ) {
14624     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.};
14625     print "\n";
14626
14627     SetVersion( $DBversion );
14628     print "Upgrade to $DBversion done (Bug 18811 - Visibility settings inconsistent between framework and authority editor)\n";
14629 }
14630
14631 $DBversion = '17.06.00.007';
14632 if( CheckVersion( $DBversion ) ) {
14633     if( !column_exists( 'branches', 'marcorgcode' ) ) {
14634         $dbh->do( "ALTER TABLE branches ADD COLUMN marcorgcode VARCHAR(16) default NULL AFTER geolocation" );
14635     }
14636
14637     SetVersion( $DBversion );
14638     print "Upgrade to $DBversion done (Bug 10132 - MARCOrgCode on branch level (branches.marcorgcode))\n";
14639 }
14640
14641 $DBversion = '17.06.00.008';
14642 if( CheckVersion( $DBversion ) ) {
14643     unless ( column_exists( 'borrowers', 'date_renewed' ) ) {
14644         $dbh->do(q{
14645             ALTER TABLE borrowers ADD COLUMN date_renewed DATE NULL DEFAULT NULL AFTER dateexpiry;
14646         });
14647     }
14648
14649     unless ( column_exists( 'deletedborrowers', 'date_renewed' ) ) {
14650         $dbh->do(q{
14651             ALTER TABLE deletedborrowers ADD COLUMN date_renewed DATE NULL DEFAULT NULL AFTER dateexpiry;
14652         });
14653     }
14654
14655     unless ( column_exists( 'borrower_modifications', 'date_renewed' ) ) {
14656         $dbh->do(q{
14657             ALTER TABLE borrower_modifications ADD COLUMN date_renewed DATE NULL DEFAULT NULL AFTER dateexpiry;
14658         });
14659     }
14660
14661     SetVersion( $DBversion );
14662     print "Upgrade to $DBversion done (Bug 6758 - Capture membership renewal date for reporting purposes (borrowers.date_renewed))\n";
14663 }
14664
14665 $DBversion = '17.06.00.009';
14666 if( CheckVersion( $DBversion ) ) {
14667     $dbh->do(q{
14668         ALTER TABLE borrowers MODIFY COLUMN login_attempts int(4) AFTER lang;
14669     });
14670     $dbh->do(q{
14671         ALTER TABLE deletedborrowers MODIFY COLUMN login_attempts int(4) AFTER lang;
14672     });
14673
14674     SetVersion( $DBversion );
14675     print "Upgrade to $DBversion done (Bug 19344 -  Reorder lang and login_attempts in the [deleted]borrowers tables)\n";
14676 }
14677
14678 $DBversion = '17.06.00.010';
14679 if ( CheckVersion($DBversion) ) {
14680     $dbh->do(q{
14681         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
14682         VALUES (
14683             'DefaultCountryField008','','',
14684             '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')
14685     });
14686     SetVersion($DBversion);
14687     print "Upgrade to $DBversion done (Bug 13912 - System preference for default place of publication (country code) for field 008, range 15-17)\n";
14688 }
14689
14690 $DBversion = '17.06.00.011';
14691 if ( CheckVersion($DBversion) ) {
14692     # Drop index that might exist because of bug 5337
14693     if( index_exists('biblioitems', 'ean')) {
14694         $dbh->do(q{ ALTER TABLE biblioitems DROP INDEX ean });
14695     }
14696     if( index_exists('deletedbiblioitems', 'ean')) {
14697         $dbh->do(q{ ALTER TABLE deletedbiblioitems DROP INDEX ean });
14698     }
14699
14700     # Change data type of column
14701     $dbh->do(q{ ALTER TABLE biblioitems MODIFY COLUMN ean MEDIUMTEXT default NULL });
14702     $dbh->do(q{ ALTER TABLE deletedbiblioitems MODIFY COLUMN ean MEDIUMTEXT default NULL });
14703
14704     # Add indexes
14705     $dbh->do(q{ ALTER TABLE biblioitems ADD INDEX ean ( ean(255) )});
14706     $dbh->do(q{ ALTER TABLE deletedbiblioitems ADD INDEX ean ( ean(255 ) )});
14707
14708     SetVersion($DBversion);
14709     print "Upgrade to $DBversion done (Bug 13766 - Make ean mediumtext and add ean indexes)\n";
14710 }
14711
14712 $DBversion = '17.06.00.012';
14713 if( CheckVersion( $DBversion ) ) {
14714     my $where = q|host='clio-db.cc.columbia.edu' AND port=7090|;
14715     my $sql = "SELECT COUNT(*) FROM z3950servers WHERE $where";
14716     my ( $cnt ) = $dbh->selectrow_array( $sql );
14717     if( $cnt ) {
14718         $dbh->do( "DELETE FROM z3950servers WHERE $where" );
14719         print "Removed $cnt Z39.50 target(s) for Columbia University\n";
14720     }
14721
14722     SetVersion( $DBversion );
14723     print "Upgrade to $DBversion done (Bug 19043 - Z39.50 target for Columbia University is no longer publicly available.)\n";
14724 }
14725
14726 $DBversion = '17.06.00.013';
14727 if( CheckVersion( $DBversion ) ) {
14728     $dbh->do( "UPDATE systempreferences SET value = CONCAT('http://', value) WHERE variable = 'staffClientBaseURL' AND value <> '' AND value NOT LIKE 'http%'" );
14729
14730     my ( $staffClientBaseURL_used_in_notices ) = $dbh->selectrow_array(q|
14731         SELECT COUNT(*) FROM letter where content like "%staffClientBaseURL%"
14732     |);
14733     if ( $staffClientBaseURL_used_in_notices ) {
14734         warn "\tYou may need to update one or more notice templates if they contain 'staffClientBaseURL'\n";
14735     }
14736
14737     SetVersion( $DBversion );
14738     print "Upgrade to $DBversion done (Bug 16401 - fix potentialy bad set staffClientBaseURL preference)\n";
14739 }
14740
14741 $DBversion = '17.06.00.014';
14742 if( CheckVersion( $DBversion ) ) {
14743     unless( column_exists('aqbasket','create_items') ){
14744         $dbh->do(q{
14745             ALTER TABLE aqbasket
14746                 ADD COLUMN create_items ENUM('ordering', 'receiving', 'cataloguing') default NULL AFTER is_standing
14747         });
14748     }
14749
14750     SetVersion( $DBversion );
14751     print "Upgrade to $DBversion done (Bug 15685 - Allow creation of items (AcqCreateItem) to be customizable per-basket)\n";
14752 }
14753
14754 $DBversion = '17.06.00.015';
14755 if( CheckVersion( $DBversion ) ) {
14756     $dbh->do(q{
14757         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES
14758         ('SelfCheckoutByLogin','0',NULL,'Have patrons login into the web-based self checkout system with their username/password or their cardnumber','YesNo')
14759     });
14760
14761     SetVersion( $DBversion );
14762     print "Upgrade to $DBversion done (Bug 19186 - Insert system preference SelfCheckoutByLogin if missing)\n";
14763 }
14764
14765 $DBversion = '17.06.00.016';
14766 if( CheckVersion( $DBversion ) ) {
14767     $dbh->do(q{
14768         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
14769         VALUES ('RequireStrongPassword','0','','Require a strong login password for staff and patrons','YesNo');
14770     });
14771
14772     SetVersion( $DBversion );
14773     print "Upgrade to $DBversion done (Bug 18298 - Allow enforcing password complexity (system preference RequireStrongPassword))\n";
14774 }
14775
14776 $DBversion = '17.06.00.017';
14777 if( CheckVersion( $DBversion ) ) {
14778     unless (TableExists('account_offsets')) {
14779         $dbh->do(q{
14780             DROP TABLE IF EXISTS `accountoffsets`;
14781         });
14782
14783         $dbh->do(q{
14784             CREATE TABLE IF NOT EXISTS `account_offset_types` (
14785               `type` varchar(16) NOT NULL, -- The type of offset this is
14786               PRIMARY KEY (`type`)
14787             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14788         });
14789
14790         $dbh->do(q{
14791             CREATE TABLE IF NOT EXISTS `account_offsets` (
14792               `id` int(11) NOT NULL auto_increment, -- unique identifier for each offset
14793               `credit_id` int(11) NULL DEFAULT NULL, -- The id of the accountline the increased the patron's balance
14794               `debit_id` int(11) NULL DEFAULT NULL, -- The id of the accountline that decreased the patron's balance
14795               `type` varchar(16) NOT NULL, -- The type of offset this is
14796               `amount` decimal(26,6) NOT NULL, -- The amount of the change
14797               `created_on` timestamp NOT NULL default CURRENT_TIMESTAMP,
14798               PRIMARY KEY (`id`),
14799               CONSTRAINT `account_offsets_ibfk_p` FOREIGN KEY (`credit_id`) REFERENCES `accountlines` (`accountlines_id`) ON DELETE CASCADE ON UPDATE CASCADE,
14800               CONSTRAINT `account_offsets_ibfk_f` FOREIGN KEY (`debit_id`) REFERENCES `accountlines` (`accountlines_id`) ON DELETE CASCADE ON UPDATE CASCADE,
14801               CONSTRAINT `account_offsets_ibfk_t` FOREIGN KEY (`type`) REFERENCES `account_offset_types` (`type`) ON DELETE CASCADE ON UPDATE CASCADE
14802             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14803         });
14804
14805         $dbh->do(q{
14806             INSERT IGNORE INTO account_offset_types ( type ) VALUES
14807             ('Writeoff'),
14808             ('Payment'),
14809             ('Lost Item'),
14810             ('Processing Fee'),
14811             ('Manual Debit'),
14812             ('Reverse Payment'),
14813             ('Forgiven'),
14814             ('Dropbox'),
14815             ('Rental Fee'),
14816             ('Fine Update'),
14817             ('Fine');
14818         });
14819     }
14820
14821     SetVersion( $DBversion );
14822     print "Upgrade to $DBversion done (Bug 14826 - Resurrect account offsets table (Add new tables account_offsets and account_offset_types))\n";
14823 }
14824
14825 $DBversion = '17.06.00.018';
14826 if( CheckVersion( $DBversion ) ) {
14827     $dbh->do(q{
14828         INSERT IGNORE INTO systempreferences (variable,value,explanation,type) VALUES ('useDefaultReplacementCost',0,'default replacement cost defined in item type','YesNo');
14829     });
14830     $dbh->do(q{
14831         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');
14832     });
14833     $dbh->do(q{
14834         ALTER TABLE `itemtypes` MODIFY COLUMN `rentalcharge` DECIMAL(28,6) NULL DEFAULT NULL;
14835     });
14836     unless ( column_exists( 'itemtypes', 'defaultreplacecost' ) ) {
14837         $dbh->do(q{
14838             ALTER TABLE `itemtypes` ADD `defaultreplacecost` DECIMAL(28,6) NULL DEFAULT NULL AFTER `rentalcharge`;
14839         });
14840     }
14841     unless ( column_exists( 'itemtypes', 'processfee' ) ) {
14842         $dbh->do(q{
14843             ALTER TABLE `itemtypes` ADD `processfee` DECIMAL(28,6) NULL DEFAULT NULL AFTER `defaultreplacecost`;
14844         });
14845
14846     }
14847     SetVersion( $DBversion );
14848     print "Upgrade to $DBversion done (Bug 12768 - Insert system preferences useDefaultReplacementCost and ProcessingFeeNote + Add new columns defaultreplacecost and processfee to the itemtypes table)\n";
14849 }
14850
14851 $DBversion = '17.06.00.019';
14852 if( CheckVersion( $DBversion ) ) {
14853     $dbh->do(q{
14854         INSERT IGNORE INTO account_offset_types ( type ) VALUES ( 'Processing Fee' );
14855     });
14856
14857     SetVersion( $DBversion );
14858     print "Upgrade to $DBversion done (Bug 12768 - Add 'Processing Fee' to the account_offset_types table if missing)\n";
14859 }
14860
14861 $DBversion = '17.06.00.020';
14862 if( CheckVersion( $DBversion ) ) {
14863     $dbh->do(q{
14864         UPDATE systempreferences
14865         SET
14866             variable='OpacLocationOnDetail',
14867             options='holding|home|both|column',
14868             explanation='In the OPAC detail, display the shelving location on its own column or under a library columns.'
14869         WHERE
14870             variable='OpacLocationBranchToDisplayShelving'
14871     });
14872
14873     SetVersion( $DBversion );
14874     print "Upgrade to $DBversion done (Bug 19028: Add 'shelving location' to holdings table in detail page (Rename syspref OpacLocationBranchToDisplayShelving with OpacLocationOnDetail))\n";
14875 }
14876
14877 $DBversion = '17.06.00.021';
14878 if( CheckVersion( $DBversion ) ) {
14879     $dbh->do(q{
14880         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')
14881     });
14882
14883     SetVersion( $DBversion );
14884     print "Upgrade to $DBversion done (Bug 17381 - Add system preference SCOMainUserBlock)\n";
14885 }
14886
14887 $DBversion = '17.06.00.022';
14888 if( CheckVersion( $DBversion ) ) {
14889     my $hide_barcode = C4::Context->preference('OPACShowBarcode') ? 0 : 1;
14890     $dbh->do(q{
14891         DELETE FROM systempreferences
14892         WHERE
14893             variable='OPACShowBarcode'
14894     });
14895
14896     # Configure column visibility if it isn't
14897     $dbh->do(q{
14898         INSERT IGNORE INTO columns_settings
14899             (module,page,tablename,columnname,cannot_be_toggled,is_hidden)
14900         VALUES
14901             ('opac','biblio-detail','holdingst','item_barcode',0,?)
14902     }, undef, $hide_barcode);
14903
14904     SetVersion( $DBversion );
14905     print "Upgrade to $DBversion done (Bug 19038: Remove OPACShowBarcode syspref)\n";
14906 }
14907
14908 $DBversion = '17.06.00.023';
14909 if( CheckVersion( $DBversion ) ) {
14910     $dbh->do(q{
14911         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14912         ('MarkLostItemsAsReturned','1','','Mark items as returned when flagged as lost','YesNo');
14913     });
14914
14915     SetVersion( $DBversion );
14916     print "Upgrade to $DBversion done (Bug 12363 - Add system preference MarkLostItemsAsReturned)\n";
14917 }
14918
14919 $DBversion = '17.06.00.024';
14920 if( CheckVersion( $DBversion ) ) {
14921     $dbh->do(q{
14922         INSERT IGNORE INTO systempreferences (`variable`,`value`,`options`,`explanation`,`type`) VALUES
14923         ('OPACUserSummary', 1, NULL, "Show the summary of a logged in user's checkouts, overdues, holds and fines on the mainpage", 'YesNo');
14924     });
14925
14926     SetVersion( $DBversion );
14927     print "Upgrade to $DBversion done (Bug 2093 - Add system preference OPACUserSummary)\n";
14928 }
14929
14930 $DBversion = '17.06.00.025';
14931 if( CheckVersion( $DBversion ) ) {
14932     $dbh->do(q{
14933         ALTER TABLE borrowers MODIFY cardnumber varchar(32);
14934     });
14935     $dbh->do(q{
14936         ALTER TABLE borrower_modifications MODIFY cardnumber varchar(32);
14937     });
14938     $dbh->do(q{
14939         ALTER TABLE deletedborrowers MODIFY cardnumber varchar(32);
14940     });
14941     $dbh->do(q{
14942         ALTER TABLE pending_offline_operations MODIFY cardnumber varchar(32);
14943     });
14944     $dbh->do(q{
14945         ALTER TABLE tmp_holdsqueue MODIFY cardnumber varchar(32);
14946     });
14947
14948     SetVersion( $DBversion );
14949     print "Upgrade to $DBversion done (Bug 13178 - Increase cardnumber fields to VARCHAR(32))\n";
14950 }
14951
14952 $DBversion = '17.06.00.026';
14953 if( CheckVersion( $DBversion ) ) {
14954     $dbh->do(q{
14955         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14956         ('BlockReturnOfLostItems','0','0','If enabled, items that are marked as lost cannot be returned.','YesNo');
14957     });
14958
14959     SetVersion( $DBversion );
14960     print "Upgrade to $DBversion done (Bug 10748 - Add system preference BlockReturnOfLostItems)\n";
14961 }
14962
14963 $DBversion = '17.06.00.027';
14964 if( CheckVersion( $DBversion ) ) {
14965     if ( !column_exists( 'statistics', 'location' ) ) {
14966         $dbh->do('ALTER TABLE statistics ADD COLUMN location VARCHAR(80) default NULL AFTER itemtype');
14967     }
14968
14969     SetVersion($DBversion);
14970     print "Upgrade to $DBversion done (Bug 18882 - Add location code to statistics table for checkouts and renewals)\n";
14971 }
14972
14973 $DBversion = '17.06.00.028';
14974 if( CheckVersion( $DBversion ) ) {
14975     if ( !TableExists( 'illrequests' ) ) {
14976         $dbh->do(q{
14977             CREATE TABLE illrequests (
14978                illrequest_id serial PRIMARY KEY,           -- ILL request number
14979                borrowernumber integer DEFAULT NULL,        -- Patron associated with request
14980                biblio_id integer DEFAULT NULL,             -- Potential bib linked to request
14981                branchcode varchar(50) NOT NULL,            -- The branch associated with the request
14982                status varchar(50) DEFAULT NULL,            -- Current Koha status of request
14983                placed date DEFAULT NULL,                   -- Date the request was placed
14984                replied date DEFAULT NULL,                  -- Last API response
14985                updated timestamp DEFAULT CURRENT_TIMESTAMP -- Last modification to request
14986                  ON UPDATE CURRENT_TIMESTAMP,
14987                completed date DEFAULT NULL,                -- Date the request was completed
14988                medium varchar(30) DEFAULT NULL,            -- The Koha request type
14989                accessurl varchar(500) DEFAULT NULL,        -- Potential URL for accessing item
14990                cost varchar(20) DEFAULT NULL,              -- Cost of request
14991                notesopac text DEFAULT NULL,                -- Patron notes attached to request
14992                notesstaff text DEFAULT NULL,               -- Staff notes attached to request
14993                orderid varchar(50) DEFAULT NULL,           -- Backend id attached to request
14994                backend varchar(20) DEFAULT NULL,           -- The backend used to create request
14995                CONSTRAINT `illrequests_bnfk`
14996                  FOREIGN KEY (`borrowernumber`)
14997                  REFERENCES `borrowers` (`borrowernumber`)
14998                  ON UPDATE CASCADE ON DELETE CASCADE,
14999                CONSTRAINT `illrequests_bcfk_2`
15000                  FOREIGN KEY (`branchcode`)
15001                  REFERENCES `branches` (`branchcode`)
15002                  ON UPDATE CASCADE ON DELETE CASCADE
15003            ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
15004         });
15005     }
15006
15007     if ( !TableExists( 'illrequestattributes' ) ) {
15008         $dbh->do(q{
15009             CREATE TABLE illrequestattributes (
15010                 illrequest_id bigint(20) unsigned NOT NULL, -- ILL request number
15011                 type varchar(200) NOT NULL,                 -- API ILL property name
15012                 value text NOT NULL,                        -- API ILL property value
15013                 PRIMARY KEY  (`illrequest_id`,`type`),
15014                 CONSTRAINT `illrequestattributes_ifk`
15015                   FOREIGN KEY (illrequest_id)
15016                   REFERENCES `illrequests` (`illrequest_id`)
15017                   ON UPDATE CASCADE ON DELETE CASCADE
15018             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
15019         });
15020     }
15021
15022     # System preferences
15023     $dbh->do(q{
15024         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
15025             ('ILLModule','0','If ON, enables the interlibrary loans module.','','YesNo');
15026     });
15027
15028     $dbh->do(q{
15029         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
15030             ('ILLModuleCopyrightClearance','','70|10','Enter text to enable the copyright clearance stage of request creation. Text will be displayed','Textarea');
15031     });
15032     # userflags
15033     $dbh->do(q{
15034         INSERT IGNORE INTO userflags (bit,flag,flagdesc,defaulton) VALUES
15035             (22,'ill','The Interlibrary Loans Module',0);
15036     });
15037
15038     SetVersion( $DBversion );
15039     print "Upgrade to $DBversion done (Bug 7317 - Add an Interlibrary Loan Module to Circulation and OPAC)\n";
15040 }
15041
15042 $DBversion = '17.11.00.000';
15043 if( CheckVersion( $DBversion ) ) {
15044     SetVersion( $DBversion );
15045     print "Upgrade to $DBversion done (Koha 17.11)\n";
15046 }
15047
15048 $DBversion = '17.12.00.000';
15049 if( CheckVersion( $DBversion ) ) {
15050     SetVersion( $DBversion );
15051     print "Upgrade to $DBversion done (Tē tōia, tē haumatia)\n";
15052 }
15053
15054 $DBversion = '17.12.00.001';
15055 if( CheckVersion( $DBversion ) ) {
15056     foreach my $table (qw(biblio_metadata deletedbiblio_metadata)) {
15057         if (!column_exists($table, 'timestamp')) {
15058             $dbh->do(qq{
15059                 ALTER TABLE `$table`
15060                 ADD COLUMN `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER `metadata`,
15061                 ADD KEY `timestamp` (`timestamp`)
15062             });
15063             $dbh->do(qq{
15064                 UPDATE $table metadata
15065                     LEFT JOIN biblioitems ON (biblioitems.biblionumber = metadata.biblionumber)
15066                     LEFT JOIN biblio ON (biblio.biblionumber = metadata.biblionumber)
15067                 SET metadata.timestamp = GREATEST(biblioitems.timestamp, biblio.timestamp);
15068             });
15069         }
15070     }
15071
15072     SetVersion( $DBversion );
15073     print "Upgrade to $DBversion done (Bug 19724 - Add [deleted]biblio_metadata.timestamp)\n";
15074 }
15075
15076 $DBversion = '17.12.00.002';
15077 if( CheckVersion( $DBversion ) ) {
15078
15079     my $msss = $dbh->selectall_arrayref(q|
15080         SELECT kohafield, tagfield, tagsubfield, frameworkcode
15081         FROM marc_subfield_structure
15082         WHERE   frameworkcode != ''
15083     |, { Slice => {} });
15084
15085
15086     my $sth = $dbh->prepare(q|
15087         SELECT kohafield
15088         FROM marc_subfield_structure
15089         WHERE frameworkcode = ''
15090         AND tagfield = ?
15091         AND tagsubfield = ?
15092     |);
15093
15094     my @exceptions;
15095     for my $mss ( @$msss ) {
15096         $sth->execute($mss->{tagfield}, $mss->{tagsubfield} );
15097         my ( $default_kohafield ) = $sth->fetchrow_array();
15098         if( $mss->{kohafield} ) {
15099             push @exceptions, { frameworkcode => $mss->{frameworkcode}, tagfield => $mss->{tagfield}, tagsubfield => $mss->{tagsubfield}, kohafield => $mss->{kohafield} } if not $default_kohafield or $default_kohafield ne $mss->{kohafield};
15100         } else {
15101             push @exceptions, { frameworkcode => $mss->{frameworkcode}, tagfield => $mss->{tagfield}, tagsubfield => $mss->{tagsubfield}, kohafield => q{} } if $default_kohafield;
15102         }
15103     }
15104
15105     if (@exceptions) {
15106         print "WARNING: The Default framework is now considered as authoritative for Koha to MARC mappings. We have found that your additional frameworks contained "
15107           . scalar(@exceptions)
15108           . " 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";
15109         for my $exception (@exceptions) {
15110             print "Field "
15111               . $exception->{tagfield} . '$'
15112               . $exception->{tagsubfield}
15113               . " in framework "
15114               . $exception->{frameworkcode} . ': ';
15115             if ( $exception->{kohafield} ) {
15116                 print "Mapping to "
15117                   . $exception->{kohafield}
15118                   . " has been adjusted.\n";
15119             }
15120             else {
15121                 print "Mapping has been reset.\n";
15122             }
15123         }
15124
15125         # Sync kohafield
15126
15127         # Clear the destination frameworks first
15128         $dbh->do(q|
15129             UPDATE marc_subfield_structure
15130             SET kohafield = NULL
15131             WHERE   frameworkcode > ''
15132                 AND     Kohafield > ''
15133         |);
15134
15135         # Now copy from Default
15136         my $msss = $dbh->selectall_arrayref(q|
15137             SELECT kohafield, tagfield, tagsubfield
15138             FROM marc_subfield_structure
15139             WHERE   frameworkcode = ''
15140                 AND     kohafield > ''
15141         |, { Slice => {} });
15142         my $sth = $dbh->prepare(q|
15143             UPDATE marc_subfield_structure
15144             SET kohafield = ?
15145             WHERE frameworkcode > ''
15146             AND tagfield = ?
15147             AND tagsubfield = ?
15148         |);
15149         for my $mss (@$msss) {
15150             $sth->execute( $mss->{kohafield}, $mss->{tagfield},
15151                 $mss->{tagsubfield} );
15152         }
15153
15154         # Clear the cache
15155         my @frameworkcodes = $dbh->selectall_arrayref(q|
15156             SELECT frameworkcode FROM biblio_framework WHERE frameworkcode > ''
15157         |);
15158         for my $frameworkcode (@frameworkcodes) {
15159             Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
15160         }
15161         Koha::Caches->get_instance->clear_from_cache("default_value_for_mod_marc-");
15162     }
15163
15164     SetVersion( $DBversion );
15165     print "Upgrade to $DBversion done (Bug 19096 - Make Default authoritative for Koha to MARC mappings)\n";
15166 }
15167
15168 $DBversion = '17.12.00.003';
15169 if( CheckVersion( $DBversion ) ) {
15170     $dbh->do(q|DROP TABLE IF EXISTS notifys|);
15171
15172     if( column_exists( 'accountlines', 'notify_id' ) ) {
15173         $dbh->do(q|ALTER TABLE accountlines DROP COLUMN notify_id|);
15174         $dbh->do(q|ALTER TABLE accountlines DROP COLUMN notify_level|);
15175     }
15176
15177     SetVersion( $DBversion );
15178     print "Upgrade to $DBversion done (Bug 10021 - Drop notifys-related table and columns)\n";
15179 }
15180
15181 $DBversion = '17.12.00.004';
15182 if( CheckVersion( $DBversion ) ) {
15183     $dbh->do(q{
15184         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
15185         VALUES
15186             ('RESTdefaultPageSize','20','','Set the default number of results returned by the REST API endpoints','Integer')
15187     });
15188
15189     SetVersion( $DBversion );
15190     print "Upgrade to $DBversion done (Bug 19278 - Add a configurable default page size for REST endpoints)\n";
15191 }
15192
15193 $DBversion = '17.12.00.005';
15194 if( CheckVersion( $DBversion ) ) {
15195     # For installations having the note already
15196     $dbh->do(q{
15197         UPDATE letter
15198         SET code    = 'CHECKOUT_NOTE',
15199             name    = 'Checkout note on item set by patron',
15200             title   = 'Checkout note',
15201             content = REPLACE(content, "<<biblio.item>>", "<<biblio.title>>")
15202         WHERE code = 'PATRON_NOTE'
15203     });
15204     # For installations coming from 17.11
15205     $dbh->do(q{
15206         INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`)
15207         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')
15208     });
15209
15210     SetVersion( $DBversion );
15211     print "Upgrade to $DBversion done (Bug 18915 - Correct CHECKOUT_NOTE notice template)\n";
15212 }
15213
15214 $DBversion = '17.12.00.006';
15215 if( CheckVersion( $DBversion ) ) {
15216     $dbh->do(q{
15217         UPDATE systempreferences SET value=replace(value, "http://www.scholar", "https://scholar") WHERE variable='OPACSearchForTitleIn';
15218     });
15219
15220     SetVersion( $DBversion );
15221     print "Upgrade to $DBversion done (Bug 17682 - Update URL for Google Scholar in OPACSearchForTitleIn)\n";
15222 }
15223
15224 $DBversion = '17.12.00.007';
15225 if( CheckVersion( $DBversion ) ) {
15226
15227     unless ( TableExists( 'library_groups' ) ) {
15228         $dbh->do(q{
15229             CREATE TABLE library_groups (
15230                 id INT(11) NOT NULL auto_increment,    -- unique id for each group
15231                 parent_id INT(11) NULL DEFAULT NULL,   -- if this is a child group, the id of the parent group
15232                 branchcode VARCHAR(10) NULL DEFAULT NULL, -- The branchcode of a branch belonging to the parent group
15233                 title VARCHAR(100) NULL DEFAULT NULL,     -- Short description of the goup
15234                 description TEXT NULL DEFAULT NULL,    -- Longer explanation of the group, if necessary
15235                 created_on TIMESTAMP NULL,             -- Date and time of creation
15236                 updated_on TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- Date and time of last
15237                 PRIMARY KEY id ( id ),
15238                 FOREIGN KEY (parent_id) REFERENCES library_groups(id) ON UPDATE CASCADE ON DELETE CASCADE,
15239                 FOREIGN KEY (branchcode) REFERENCES branches(branchcode) ON UPDATE CASCADE ON DELETE CASCADE,
15240                 UNIQUE KEY title ( title )
15241             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
15242         });
15243     }
15244
15245     SetVersion( $DBversion );
15246     print "Upgrade to $DBversion done (Bug 15707 - Add new table library_groups)\n";
15247 }
15248
15249 $DBversion = '17.12.00.008';
15250 if ( CheckVersion($DBversion) ) {
15251
15252     if ( TableExists( 'branchcategories' ) and TableExists('branchrelations' )) {
15253         $dbh->do(q{
15254             INSERT INTO library_groups ( title, description, created_on ) VALUES ( '__SEARCH_GROUPS__', 'Library search groups', NOW() )
15255         });
15256         my $search_groups_root_id = $dbh->last_insert_id(undef, undef, 'library_groups', undef);
15257
15258         my $sth = $dbh->prepare("SELECT * FROM branchcategories");
15259
15260         my $sth2 = $dbh->prepare("INSERT INTO library_groups ( parent_id, title, description, created_on ) VALUES ( ?, ?, ?, NOW() )");
15261
15262         my $sth3 = $dbh->prepare("SELECT * FROM branchrelations WHERE categorycode = ?");
15263
15264         my $sth4 = $dbh->prepare("INSERT INTO library_groups ( parent_id, branchcode, created_on ) VALUES ( ?, ?, NOW() )");
15265
15266         $sth->execute();
15267         while ( my $lc = $sth->fetchrow_hashref ) {
15268             my $description = $lc->{categorycode};
15269             $description .= " - " . $lc->{codedescription} if $lc->{codedescription};
15270
15271             $sth2->execute($search_groups_root_id, $lc->{categoryname}, $description);
15272
15273             my $subgroup_id = $dbh->last_insert_id(undef, undef, 'library_groups', undef);
15274
15275             $sth3->execute( $lc->{categorycode} );
15276
15277             while ( my $l = $sth3->fetchrow_hashref ) {
15278                 $sth4->execute( $subgroup_id, $l->{branchcode} );
15279             }
15280         }
15281
15282         $dbh->do("DROP TABLE branchrelations");
15283         $dbh->do("DROP TABLE branchcategories");
15284     }
15285
15286     print "Upgrade to $DBversion done (Bug 16735 - Migrate library search groups into the new hierarchical groups)\n";
15287     SetVersion($DBversion);
15288 }
15289
15290 $DBversion = '17.12.00.009';
15291 if ( CheckVersion($DBversion) ) {
15292     $dbh->do(q|
15293         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
15294         (4, 'edit_borrowers', 'Add, modify and view patron information'),
15295         (4, 'view_borrower_infos_from_any_libraries', 'View patron infos from any libraries');
15296     |);
15297
15298     # We are lucky here, there is nothing else to do: flags 4-borrowers did not contain sub permissions
15299
15300     SetVersion( $DBversion );
15301     print "Upgrade to $DBversion done (Bug 18403 - Add the view_borrower_infos_from_any_libraries permission )\n";
15302 }
15303
15304 $DBversion = '17.12.00.010';
15305 if( CheckVersion( $DBversion ) ) {
15306
15307     if( !column_exists( 'library_groups', 'ft_hide_patron_info' ) ) {
15308         $dbh->do( "ALTER TABLE library_groups ADD COLUMN ft_hide_patron_info tinyint(1) NOT NULL DEFAULT 0 AFTER description" );
15309     }
15310
15311     SetVersion( $DBversion );
15312     print "Upgrade to $DBversion done (Bug 20133 - Add library_groups.ft_hide_patron_info)\n";
15313 }
15314
15315 $DBversion = '17.12.00.011';
15316 if( CheckVersion( $DBversion ) ) {
15317
15318     if( !column_exists( 'library_groups', 'ft_search_groups_opac' ) ) {
15319         $dbh->do( "ALTER TABLE library_groups ADD COLUMN ft_search_groups_opac tinyint(1) NOT NULL DEFAULT 0 AFTER ft_hide_patron_info" );
15320         $dbh->do( "ALTER TABLE library_groups ADD COLUMN ft_search_groups_staff tinyint(1) NOT NULL DEFAULT 0 AFTER ft_search_groups_opac" );
15321         $dbh->do( "UPDATE library_groups SET ft_search_groups_staff = 1 AND ft_search_groups_opac = 1 WHERE title = '__SEARCH_GROUPS__'" );
15322     }
15323
15324     SetVersion( $DBversion );
15325     print "Upgrade to $DBversion done (Bug 20157 - Use group 'features' to decide which groups to use for group searching functionality)\n";
15326 }
15327
15328 $DBversion = '17.12.00.012';
15329 if( CheckVersion( $DBversion ) ) {
15330
15331     $dbh->do( q|
15332         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15333         VALUES ('AutoSwitchPatron', '0', '', 'Auto switch to patron', 'YesNo');
15334     |);
15335
15336     SetVersion( $DBversion );
15337     print "Upgrade to $DBversion done (Bug 15752 - Add system preference AutoSwitchPatron)\n";
15338 }
15339
15340 $DBversion = '17.12.00.013';
15341 if( CheckVersion( $DBversion ) ) {
15342
15343     $dbh->do(q|
15344         ALTER TABLE club_enrollments MODIFY date_created timestamp NULL DEFAULT NULL;
15345     |);
15346
15347     SetVersion( $DBversion );
15348     print "Upgrade to $DBversion done (Bug 20175 - Set DEFAULT NULL value for club_enrollments.date_created)\n";
15349 }
15350
15351 $DBversion = '17.12.00.014';
15352 if( CheckVersion( $DBversion ) ) {
15353     $dbh->do( "UPDATE marc_subfield_structure SET kohafield=NULL where kohafield='additionalauthors.author'" );
15354     SetVersion( $DBversion );
15355     print "Upgrade to $DBversion done (Bug 19790 - Remove additionalauthors.author from installer files)\n";
15356 }
15357
15358 $DBversion = '17.12.00.015';
15359 if( CheckVersion( $DBversion ) ) {
15360     $dbh->do(q|
15361         ALTER TABLE borrowers
15362         MODIFY surname MEDIUMTEXT,
15363         MODIFY address MEDIUMTEXT,
15364         MODIFY city MEDIUMTEXT
15365     |);
15366     $dbh->do(q|
15367         ALTER TABLE deletedborrowers
15368         MODIFY surname MEDIUMTEXT,
15369         MODIFY address MEDIUMTEXT,
15370         MODIFY city MEDIUMTEXT
15371     |);
15372
15373     $dbh->do(q|
15374         ALTER TABLE export_format
15375         MODIFY csv_separator VARCHAR(2) NOT NULL DEFAULT ',',
15376         MODIFY field_separator VARCHAR(2),
15377         MODIFY subfield_separator VARCHAR(2)
15378     |);
15379     $dbh->do(q|
15380         ALTER TABLE export_format MODIFY encoding VARCHAR(255) NOT NULL DEFAULT 'utf8'
15381     |);
15382
15383     $dbh->do(q|
15384         ALTER TABLE reserves MODIFY lowestPriority tinyint(1) NOT NULL DEFAULT 0
15385     |);
15386     $dbh->do(q|
15387         ALTER TABLE old_reserves MODIFY lowestPriority tinyint(1) NOT NULL DEFAULT 0
15388     |);
15389
15390     SetVersion( $DBversion );
15391     print "Upgrade to $DBversion done (Bug 20144 - Adapt DB structure to work with new SQL modes)\n";
15392 }
15393
15394 $DBversion = '17.12.00.016';
15395 if( CheckVersion( $DBversion ) ) {
15396     $dbh->do(q|SET foreign_key_checks = 0|);
15397     my $sth = $dbh->table_info( '','','','TABLE' );
15398
15399     while ( my ( $cat, $schema, $name, $type, $remarks ) = $sth->fetchrow_array ) {
15400         my $table_sth = $dbh->prepare(qq|SHOW CREATE TABLE $name|);
15401         $table_sth->execute;
15402         my @table = $table_sth->fetchrow_array;
15403         unless ( $table[1] =~ /COLLATE=utf8mb4_unicode_ci/ ) {
15404             # Some users might have done the upgrade to utf8mb4 on their own
15405             # to support supplemental chars (japanese, chinese, etc)
15406             if ( $name eq 'additional_fields' ) {
15407                 $dbh->do(qq|
15408                     ALTER TABLE $name
15409                         DROP KEY `fields_uniq`,
15410                         ADD UNIQUE KEY `fields_uniq` (`tablename` (191), `name` (191))
15411                 |);
15412                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15413             }
15414             elsif ( $name eq 'authorised_values' ) {
15415                 $dbh->do(qq|
15416                     ALTER TABLE $name
15417                         DROP KEY `lib`,
15418                         ADD KEY `lib` (`lib` (191))
15419                 |);
15420                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15421             }
15422             elsif ( $name eq 'borrower_modifications' ) {
15423                 $dbh->do(qq|
15424                     ALTER TABLE $name
15425                         DROP PRIMARY KEY,
15426                         DROP KEY `verification_token`,
15427                         ADD PRIMARY KEY (`verification_token` (191),`borrowernumber`),
15428                         ADD KEY `verification_token` (`verification_token` (191))
15429                 |);
15430                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15431             }
15432             elsif ( $name eq 'columns_settings' ) {
15433                 $dbh->do(qq|
15434                     ALTER TABLE $name
15435                         DROP PRIMARY KEY,
15436                         ADD PRIMARY KEY (`module` (191), `page` (191), `tablename` (191), `columnname` (191))
15437                 |);
15438                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15439             }
15440             elsif ( $name eq 'illrequestattributes' ) {
15441                 $dbh->do(qq|
15442                     ALTER TABLE $name
15443                         DROP PRIMARY KEY,
15444                         ADD PRIMARY KEY  (`illrequest_id`, `type` (191))
15445                 |);
15446                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15447             }
15448             elsif ( $name eq 'items_search_fields' ) {
15449                 $dbh->do(qq|
15450                     ALTER TABLE $name
15451                         DROP PRIMARY KEY,
15452                         ADD PRIMARY KEY (`name` (191))
15453                 |);
15454                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15455             }
15456             elsif ( $name eq 'marc_subfield_structure' ) {
15457                 # In this case we convert each column explicitly
15458                 # to preserve 'tagsubield' collation (utf8mb4_bin)
15459                 $dbh->do(qq|
15460                     ALTER TABLE $name
15461                         MODIFY COLUMN tagfield
15462                             VARCHAR(3) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
15463                         MODIFY COLUMN tagsubfield
15464                             VARCHAR(1) COLLATE utf8mb4_bin NOT NULL DEFAULT '',
15465                         MODIFY COLUMN liblibrarian
15466                             VARCHAR(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
15467                         MODIFY COLUMN libopac
15468                             VARCHAR(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
15469                         MODIFY COLUMN kohafield
15470                             VARCHAR(40) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15471                         MODIFY COLUMN authorised_value
15472                             VARCHAR(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15473                         MODIFY COLUMN authtypecode
15474                             VARCHAR(20) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15475                         MODIFY COLUMN value_builder
15476                             VARCHAR(80) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15477                         MODIFY COLUMN frameworkcode
15478                             VARCHAR(4) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
15479                         MODIFY COLUMN seealso
15480                             VARCHAR(1100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15481                         MODIFY COLUMN link
15482                             VARCHAR(80) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15483                         MODIFY COLUMN defaultvalue
15484                             MEDIUMTEXT COLLATE utf8mb4_unicode_ci default NULL
15485                 |);
15486                 $dbh->do(qq|ALTER TABLE $name CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15487             }
15488             elsif ( $name eq 'plugin_data' ) {
15489                 $dbh->do(qq|
15490                     ALTER TABLE $name
15491                         DROP PRIMARY KEY,
15492                         ADD PRIMARY KEY (`plugin_class` (191), `plugin_key` (191))
15493                 |);
15494                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15495             }
15496             elsif ( $name eq 'search_field' ) {
15497                 $dbh->do(qq|
15498                     ALTER TABLE $name
15499                         DROP KEY `name`,
15500                         ADD UNIQUE KEY `name` (`name` (191))
15501                 |);
15502                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15503             }
15504             elsif ( $name eq 'search_marc_map' ) {
15505                 $dbh->do(qq|
15506                     ALTER TABLE $name
15507                         DROP KEY `index_name`,
15508                         ADD UNIQUE KEY `index_name` (`index_name`, `marc_field` (191), `marc_type`)
15509                 |);
15510                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15511             }
15512             elsif ( $name eq 'sms_providers' ) {
15513                 $dbh->do(qq|
15514                     ALTER TABLE $name
15515                         DROP KEY `name`,
15516                         ADD UNIQUE KEY `name` (`name` (191))
15517                 |);
15518                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15519             }
15520             elsif ( $name eq 'tags' ) {
15521                 $dbh->do(qq|
15522                     ALTER TABLE $name
15523                         DROP PRIMARY KEY,
15524                         ADD PRIMARY KEY (`entry` (191))
15525                 |);
15526                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15527             }
15528             elsif ( $name eq 'tags_approval' ) {
15529                 $dbh->do(qq|
15530                     ALTER TABLE $name
15531                         MODIFY COLUMN `term` VARCHAR(191) NOT NULL
15532                 |);
15533                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15534             }
15535             elsif ( $name eq 'tags_index' ) {
15536                 $dbh->do(qq|
15537                     ALTER TABLE $name
15538                         MODIFY COLUMN `term` VARCHAR(191) NOT NULL
15539                 |);
15540                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15541             }
15542             else {
15543                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15544             }
15545         }
15546     }
15547     $dbh->do(q|SET foreign_key_checks = 1|);
15548
15549     print "Upgrade to $DBversion done (Bug 18336 - Convert DB tables to utf8mb4 🎁)\n";
15550     SetVersion($DBversion);
15551 }
15552
15553
15554 $DBversion = '17.12.00.017';
15555 if( CheckVersion( $DBversion ) ) {
15556
15557     if( !column_exists( 'items', 'damaged_on' ) ) {
15558         $dbh->do( "ALTER TABLE items ADD COLUMN damaged_on DATETIME NULL AFTER damaged");
15559     }
15560     if( !column_exists( 'deleteditems', 'damaged_on' ) ) {
15561         $dbh->do( "ALTER TABLE deleteditems ADD COLUMN damaged_on DATETIME NULL AFTER damaged");
15562     }
15563
15564     SetVersion( $DBversion );
15565     print "Upgrade to $DBversion done (Bug 17672 - Add damaged_on to items and deleteditems tables)\n";
15566 }
15567
15568 $DBversion = '17.12.00.018';
15569 if( CheckVersion( $DBversion ) ) {
15570
15571     $dbh->do( q|
15572         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')
15573     |);
15574
15575     SetVersion( $DBversion );
15576     print "Upgrade to $DBversion done (Bug 19290 - Add system preference BrowseResultSelection)\n";
15577 }
15578
15579 $DBversion = '17.12.00.019';
15580 if( CheckVersion( $DBversion ) ) {
15581
15582     $dbh->do(q|UPDATE auth_subfield_structure SET hidden=1 WHERE hidden<>0|);
15583
15584     SetVersion( $DBversion );
15585     print "Upgrade to $DBversion done (Bug 20074 - Auth_subfield_structure changes hidden attribute)\n";
15586 }
15587
15588 $DBversion = '17.12.00.020';
15589 if( CheckVersion( $DBversion ) ) {
15590
15591     $dbh->do(q|
15592         INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)
15593         VALUES ('vi', 'language', 'de', 'Vietnamesisch')
15594     |);
15595
15596     $dbh->do(q|
15597         UPDATE language_descriptions SET description = 'Tiếng Việt'
15598         WHERE subtag = 'vi' and type = 'language' and lang = 'vi'
15599     |);
15600
15601     SetVersion( $DBversion );
15602     print "Upgrade to $DBversion done (Bug 20082 - Update descriptions of Vietnamese language)\n";
15603 }
15604
15605 $DBversion = '17.12.00.021';
15606 if( CheckVersion( $DBversion ) ) {
15607
15608     $dbh->do(q|
15609         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
15610         ('PurgeSuggestionsOlderThan', '', NULL, 'Default value for cronjob purge_suggestions.pl', 'Integer');
15611     |);
15612
15613     SetVersion( $DBversion );
15614     print "Upgrade to $DBversion done (Bug 13287 - Add system preference PurgeSuggestionsOlderThan)\n";
15615 }
15616
15617 $DBversion = '17.12.00.022';
15618 if( CheckVersion( $DBversion ) ) {
15619
15620     if( !column_exists( 'currency', 'p_sep_by_space' ) ) {
15621         $dbh->do(q|
15622             ALTER TABLE currency ADD COLUMN p_sep_by_space tinyint(1) default 0 after archived
15623         |);
15624     }
15625
15626     SetVersion( $DBversion );
15627     print "Upgrade to $DBversion done (Bug 4078 - Add column currency.p_sep_by_space)\n";
15628 }
15629
15630 $DBversion = '17.12.00.023';
15631 if( CheckVersion( $DBversion ) ) {
15632     $dbh->do(q{
15633         DELETE FROM systempreferences
15634         WHERE variable='checkdigit'
15635     });
15636
15637     SetVersion( $DBversion );
15638     print "Upgrade to $DBversion done (Bug 20264 - Remove system preference 'checkdigit')\n";
15639 }
15640
15641 $DBversion = '17.12.00.024';
15642 if( CheckVersion( $DBversion ) ) {
15643
15644     $dbh->do(q{
15645         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15646         VALUES ('SelfCheckInMainUserBlock', '', '70|10', 'Add a block of HTML that will display on the self check-in screen.', 'Textarea');
15647     });
15648
15649     $dbh->do(q{
15650         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15651         VALUES ('SelfCheckInModule', 0, NULL, 'Enable the standalone self-checkin module.', 'YesNo');
15652     });
15653
15654     $dbh->do(q{
15655         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15656         VALUES ('SelfCheckInModuleUserID', NULL, NULL, 'Patron ID (borrowernumber) to be allowed on the self-checkin module.', 'Integer');
15657     });
15658
15659     $dbh->do(q{
15660         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15661         VALUES ('SelfCheckInTimeout', 120, NULL, 'Define the number of seconds before the self check-in module times out.', 'Integer');
15662     });
15663
15664     $dbh->do(q{
15665         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15666         VALUES ('SelfCheckInUserCSS', '', NULL, 'Add CSS to be included in the self check-in module in an embedded <style> tag.', 'free');
15667     });
15668
15669     $dbh->do(q{
15670         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15671         VALUES ('SelfCheckInUserJS', '', NULL, 'Define custom javascript for inclusion in the self check-in module.', 'free');
15672     });
15673
15674     # Add new userflag for self check
15675     $dbh->do(q{
15676         INSERT IGNORE INTO userflags (bit,flag,flagdesc,defaulton) VALUES
15677             (23,'self_check','Self check modules',0);
15678     });
15679
15680     # Add self check-in module subpermission
15681     $dbh->do(q{
15682         INSERT IGNORE INTO permissions (module_bit,code,description)
15683         VALUES (23, 'self_checkin_module', 'Log into the self check-in module');
15684     });
15685
15686     # Add self check-in module subpermission
15687     $dbh->do(q{
15688         INSERT IGNORE INTO permissions (module_bit,code,description)
15689         VALUES (23, 'self_checkout_module', 'Perform self checkout at the OPAC. It should be used for the patron matching the AutoSelfCheckID');
15690     });
15691
15692     # Update patrons with self_checkout permission
15693     # IMPORTANT: Needs to happen before removing the old subpermission
15694     $dbh->do(q{
15695         UPDATE user_permissions
15696         SET module_bit = 23,
15697                   code = 'self_checkout_module'
15698         WHERE module_bit = 1 AND code = 'self_checkout';
15699     });
15700
15701     # Remove old self_checkout permission
15702     $dbh->do(q{
15703         DELETE IGNORE FROM permissions
15704         WHERE  code='self_checkout';
15705     });
15706
15707     SetVersion( $DBversion );
15708     print "Upgrade to $DBversion done (Bug 15492 - Add a standalone self-checkin module)\n";
15709 }
15710
15711 $DBversion = '17.12.00.025';
15712 if( CheckVersion( $DBversion ) ) {
15713     $dbh->do(q|
15714         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
15715         VALUES ('StaffLoginInstructions','','HTML to go into the login box for the staff client',NULL,'Free')
15716     |);
15717     $dbh->do(q|
15718         UPDATE systempreferences
15719         SET variable = 'OpacLoginInstructions'
15720         WHERE variable = 'NoLoginInstructions'
15721     |);
15722
15723     SetVersion( $DBversion );
15724     print "Upgrade to $DBversion done (Bug 20291 - Add StaffLoginInstructions system preference and rename NoLoginInstructions with OpacLoginInstructions)\n";
15725 }
15726
15727 $DBversion = '17.12.00.026';
15728 if( CheckVersion( $DBversion ) ) {
15729     if( !column_exists( 'issuingrules', 'suspension_chargeperiod' ) ) {
15730         $dbh->do(q|
15731             ALTER TABLE issuingrules ADD COLUMN suspension_chargeperiod int(11) DEFAULT '1' AFTER maxsuspensiondays;
15732         |);
15733     }
15734
15735     SetVersion( $DBversion );
15736     print "Upgrade to $DBversion done (Bug 19804 - Add issuingrules.suspension_chargeperiod)\n";
15737 }
15738
15739 $DBversion = '17.12.00.027';
15740 if( CheckVersion( $DBversion ) ) {
15741     $dbh->do(q|
15742         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
15743         VALUES ('UseACQFrameworkForBiblioRecords','0','','Use the ACQ framework for the catalog details','YesNo')
15744     |);
15745
15746     SetVersion( $DBversion );
15747     print "Upgrade to $DBversion done (Bug 19289 - Add system preference UseACQFrameworkForBiblioRecords)\n";
15748 }
15749
15750 $DBversion = '17.12.00.028';
15751 if( CheckVersion( $DBversion ) ) {
15752     if( !column_exists( 'marc_tag_structure', 'ind1_defaultvalue' ) ) {
15753         $dbh->do(q|
15754             ALTER TABLE marc_tag_structure
15755             ADD COLUMN ind2_defaultvalue VARCHAR(1) NOT NULL DEFAULT '' AFTER authorised_value,
15756             ADD COLUMN ind1_defaultvalue VARCHAR(1) NOT NULL DEFAULT '' AFTER authorised_value;
15757         |);
15758     }
15759
15760     SetVersion( $DBversion );
15761     print "Upgrade to $DBversion done (Bug 9701 - Add default indicators (marc_tag_structure.indX_defaultvalue))\n";
15762 }
15763
15764 $DBversion = '17.12.00.029';
15765 if( CheckVersion( $DBversion ) ) {
15766     my $pref =
15767 q|# PERSO_NAME  100 600 696 700 796 800 896
15768 marc21, 100, ind1:auth1
15769 marc21, 600, ind1:auth1, ind2:thesaurus
15770 marc21, 696, ind1:auth1
15771 marc21, 700, ind1:auth1
15772 marc21, 796, ind1:auth1
15773 marc21, 800, ind1:auth1
15774 marc21, 896, ind1:auth1
15775 # CORPO_NAME  110 610 697 710 797 810 897
15776 marc21, 110, ind1:auth1
15777 marc21, 610, ind1:auth1, ind2:thesaurus
15778 marc21, 697, ind1:auth1
15779 marc21, 710, ind1:auth1
15780 marc21, 797, ind1:auth1
15781 marc21, 810, ind1:auth1
15782 marc21, 897, ind1:auth1
15783 # MEETI_NAME    111 611 698 711 798 811 898
15784 marc21, 111, ind1:auth1
15785 marc21, 611, ind1:auth1, ind2:thesaurus
15786 marc21, 698, ind1:auth1
15787 marc21, 711, ind1:auth1
15788 marc21, 798, ind1:auth1
15789 marc21, 811, ind1:auth1
15790 marc21, 898, ind1:auth1
15791 # UNIF_TITLE        130 440 630 699 730 799 830 899 / 240
15792 marc21, 130, ind1:auth2
15793 marc21, 240, , ind2:auth2
15794 marc21, 440, , ind2:auth2
15795 marc21, 630, ind1:auth2, ind2:thesaurus
15796 marc21, 699, ind1:auth2
15797 marc21, 730, ind1:auth2
15798 marc21, 799, ind1:auth2
15799 marc21, 830, , ind2:auth2
15800 marc21, 899, ind1:auth2
15801 # CHRON_TERM    648
15802 marc21, 648, , ind2:thesaurus
15803 # TOPIC_TERM      650 654 656 657 658 690
15804 marc21, 650, , ind2:thesaurus
15805 # GEOGR_NAME   651 662 691 / 751
15806 marc21, 651, , ind2:thesaurus
15807 # GENRE/FORM    655
15808 marc21, 655, , ind2:thesaurus
15809
15810 # UNIMARC: Always copy the indicators from the authority
15811 unimarc, *, ind1:auth1, ind2:auth2|;
15812
15813     $dbh->do( q|
15814         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
15815         VALUES ( 'AuthorityControlledIndicators', ?, 'Authority controlled indicators per biblio field', NULL, 'Free' );
15816     |, undef, $pref );
15817
15818     SetVersion( $DBversion );
15819     print "Upgrade to $DBversion done (Bug 14769 - Authorities merge: Set correct indicators in biblio field (new system preference AuthorityControlledIndicators))\n";
15820 }
15821
15822 $DBversion = '17.12.00.030';
15823 if( CheckVersion( $DBversion ) ) {
15824     $dbh->do(q|
15825         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
15826         VALUES ('NovelistSelectStaffProfile',NULL,'Novelist staff client user Profile',NULL,'free')
15827     |);
15828
15829     SetVersion( $DBversion );
15830     print "Upgrade to $DBversion done (Bug 19882 - Add system preference NovelistSelectStaffProfile)\n";
15831 }
15832
15833 $DBversion = '17.12.00.031';
15834 if( CheckVersion( $DBversion ) ) {
15835     $dbh->do(q|
15836         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
15837         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')
15838     |);
15839
15840     SetVersion( $DBversion );
15841     print "Upgrade to $DBversion done (Bug 11674 - Add system preference MarcFieldDocURL)\n";
15842 }
15843
15844 $DBversion = '17.12.00.032';
15845 if( CheckVersion( $DBversion ) ) {
15846     $dbh->do(q|
15847         UPDATE letter SET code = "SERIAL_ALERT" WHERE code = "RLIST";
15848     |);
15849     $dbh->do(q|
15850         UPDATE letter SET name = "New serial issue" WHERE name = "Routing List";
15851     |);
15852     $dbh->do(q|
15853         UPDATE subscription SET letter = "SERIAL_ALERT" WHERE letter = "RLIST";
15854     |);
15855
15856     SetVersion( $DBversion );
15857     print "Upgrade to $DBversion done (Bug 19794 - Rename RLIST notice to SERIAL_ALERT)\n";
15858 }
15859
15860 $DBversion = '17.12.00.033';
15861 if( CheckVersion( $DBversion ) ) {
15862     if ( !column_exists( 'accountlines', 'payment_type' ) ) {
15863         $dbh->do(q{
15864             ALTER TABLE accountlines ADD payment_type varchar(80) default NULL AFTER accounttype
15865         });
15866     }
15867
15868     $dbh->do(q{
15869         INSERT IGNORE INTO authorised_value_categories( category_name ) VALUES ('PAYMENT_TYPE')
15870     });
15871
15872     SetVersion( $DBversion );
15873     print "Upgrade to $DBversion done (Bug 18786 - Add ability to create custom payment types)\n";
15874 }
15875
15876 $DBversion = '17.12.00.034';
15877 if( CheckVersion( $DBversion ) ) {
15878
15879     $dbh->do( q{
15880         INSERT IGNORE INTO account_offset_types ( type ) VALUES ('Void Payment')
15881     } );
15882
15883     SetVersion( $DBversion );
15884     print "Upgrade to $DBversion done (Bug 18790 - Add ability to void payment)\n";
15885 }
15886
15887 $DBversion = '17.12.00.035';
15888 if( CheckVersion( $DBversion ) ) {
15889     my ( $original_value ) = $dbh->selectrow_array(q|
15890         SELECT value FROM systempreferences WHERE variable="MarkLostItemsAsReturned"
15891     |);
15892     if ( $original_value and $original_value eq '1' ) {
15893         $dbh->do(q{
15894             UPDATE systempreferences
15895             SET type="multiple",
15896                 options="batchmod|moredetail|cronjob|additem",
15897                 value="batchmod,moredetail,cronjob,additem"
15898             WHERE variable="MarkLostItemsAsReturned"
15899         });
15900     } else {
15901         $dbh->do(q{
15902             UPDATE systempreferences
15903             SET type="multiple",
15904                 options="batchmod|moredetail|cronjob|additem",
15905                 value=""
15906             WHERE variable="MarkLostItemsAsReturned"
15907         });
15908     }
15909
15910     SetVersion( $DBversion );
15911     print "Upgrade to $DBversion done (Bug 19974 - Make MarkLostItemsAsReturned multiple)\n";
15912 }
15913
15914 $DBversion = '17.12.00.036';
15915 if( CheckVersion( $DBversion ) ) {
15916
15917     $dbh->do( q{
15918         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');
15919     } );
15920     $dbh->do( q{
15921         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');
15922     } );
15923     $dbh->do( q{
15924         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');
15925     } );
15926     $dbh->do( q{
15927         UPDATE systempreferences SET options="batchmod|moredetail|cronjob|additem|pendingreserves", value="batchmod|moredetail|cronjob|additem|pendingreserves" WHERE variable="MarkLostItemsAsReturned";
15928     } );
15929
15930     SetVersion( $DBversion );
15931     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";
15932 }
15933
15934 $DBversion = '17.12.00.037';
15935 if( CheckVersion( $DBversion ) ) {
15936
15937     SetVersion( $DBversion );
15938     print "Upgrade to $DBversion done (This change has been reverted, nothing done!)\n";
15939 }
15940
15941 $DBversion = '17.12.00.038';
15942 if( CheckVersion( $DBversion ) ) {
15943
15944     $dbh->do( q{
15945         UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'slo' WHERE iso639_2_code = 'slk' AND rfc4646_subtag = 'sk';
15946     } );
15947
15948     SetVersion( $DBversion );
15949     print "Upgrade to $DBversion done (Bug 20245 - Use Bibliographic code value for Slovak language)\n";
15950 }
15951
15952 $DBversion = '17.12.00.039';
15953 if( CheckVersion( $DBversion ) ) {
15954
15955     $dbh->do( q{
15956         UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'baq' WHERE iso639_2_code = 'eus' AND rfc4646_subtag = 'eu';
15957     } );
15958     $dbh->do( q{
15959         UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'mao' WHERE iso639_2_code = 'mri' AND rfc4646_subtag = 'mi';
15960     } );
15961     $dbh->do( q{
15962         UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'alb' WHERE iso639_2_code = 'sqi' AND rfc4646_subtag = 'sq';
15963     } );
15964
15965     SetVersion( $DBversion );
15966     print "Upgrade to $DBversion done (Bug 20482 - Use Bibliographic code value for Basque, Maori and Albanian languages)\n";
15967 }
15968
15969 $DBversion = '17.12.00.040';
15970 if( CheckVersion( $DBversion ) ) {
15971
15972     $dbh->do( q{
15973         INSERT IGNORE INTO systempreferences ( value, variable, options, explanation, type )
15974         VALUES ( '0', 'ProtectSuperlibrarianPrivileges', NULL, 'If enabled, non-superlibrarians cannot set superlibrarian privileges', 'YesNo' )
15975     } );
15976
15977     SetVersion( $DBversion );
15978     print "Upgrade to $DBversion done (Bug 20100 - Add new system preference ProtectSuperlibrarianPrivileges)\n";
15979 }
15980
15981 $DBversion = '17.12.00.041';
15982 if( CheckVersion( $DBversion ) ) {
15983
15984     $dbh->do( q{
15985         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES (13, 'access_files', 'Access to the files stored on the server');
15986     } );
15987
15988     SetVersion( $DBversion );
15989     print "Upgrade to $DBversion done (Bug 11317 - Add a new permission to access files stored on the server)\n";
15990 }
15991
15992 $DBversion = '17.12.00.042';
15993 if( CheckVersion( $DBversion ) ) {
15994
15995     if (!TableExists('oauth_access_tokens')) {
15996         $dbh->do(q{
15997             CREATE TABLE oauth_access_tokens (
15998                 `access_token` VARCHAR(191) NOT NULL,
15999                 `client_id`    VARCHAR(191) NOT NULL,
16000                 `expires`      INT NOT NULL,
16001                 PRIMARY KEY (`access_token`)
16002             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
16003         });
16004     }
16005
16006     SetVersion( $DBversion );
16007     print "Upgrade to $DBversion done (Bug 20402 - Implement OAuth2 authentication for REST API)\n";
16008 }
16009
16010 $DBversion = '17.12.00.043';
16011 if(CheckVersion($DBversion)) {
16012
16013     if (!TableExists('api_keys')) {
16014         $dbh->do(q{
16015             CREATE TABLE `api_keys` (
16016                 `client_id`   VARCHAR(191) NOT NULL,
16017                 `secret`      VARCHAR(191) NOT NULL,
16018                 `description` VARCHAR(255) NOT NULL,
16019                 `patron_id`   INT(11) NOT NULL,
16020                 `active`      TINYINT(1) DEFAULT 1 NOT NULL,
16021                 PRIMARY KEY `client_id` (`client_id`),
16022                 UNIQUE KEY `secret` (`secret`),
16023                 KEY `patron_id` (`patron_id`),
16024                 CONSTRAINT `api_keys_fk_patron_id`
16025                   FOREIGN KEY (`patron_id`)
16026                   REFERENCES `borrowers` (`borrowernumber`)
16027                   ON DELETE CASCADE ON UPDATE CASCADE
16028             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16029         });
16030     }
16031
16032     print "Upgrade to $DBversion done (Bug 20568 - Add API key management interface for patrons)\n";
16033     SetVersion($DBversion);
16034 }
16035
16036 $DBversion = '17.12.00.044';
16037 if(CheckVersion($DBversion)) {
16038
16039     $dbh->do(q{
16040         INSERT IGNORE INTO systempreferences (`variable`,`value`,`options`,`explanation`,`type`)
16041         VALUES
16042             ('RESTOAuth2ClientCredentials','0',NULL,'If enabled, the OAuth2 client credentials flow is enabled for the REST API.','YesNo');
16043     });
16044
16045     print "Upgrade to $DBversion done (Bug 20624 - Disable OAuth2 client credentials grant by default)\n";
16046     SetVersion($DBversion);
16047 }
16048
16049 $DBversion = '18.05.00.000';
16050 if( CheckVersion( $DBversion ) ) {
16051     SetVersion( $DBversion );
16052     print "Upgrade to $DBversion done (Koha 18.05)\n";
16053 }
16054
16055 $DBversion = '18.06.00.000';
16056 if( CheckVersion( $DBversion ) ) {
16057     SetVersion( $DBversion );
16058     print "Upgrade to $DBversion done (Koha 18.06 - It's Adventure time!)\n";
16059 }
16060
16061 $DBversion = '18.06.00.001';
16062 if( CheckVersion( $DBversion ) ) {
16063     $dbh->do(q{UPDATE permissions SET description = 'Manage budgets' WHERE code = 'period_manage';});
16064     $dbh->do(q{UPDATE permissions SET description = 'Manage funds' WHERE code = 'budget_manage';});
16065     $dbh->do(q{UPDATE permissions SET description = 'Modify funds (can''t create lines, but can modify existing ones)' WHERE code = 'budget_modify';});
16066     $dbh->do(q{UPDATE permissions SET description = 'Manage baskets and order lines' WHERE code = 'order_manage';});
16067     $dbh->do(q{UPDATE permissions SET description = 'Manage all baskets and order lines, regardless of restrictions on them' WHERE code = 'order_manage_all';});
16068     $dbh->do(q{UPDATE permissions SET description = 'Manage basket groups' WHERE code = 'group_manage';});
16069     $dbh->do(q{UPDATE permissions SET description = 'Receive orders and manage shipments' WHERE code = 'order_receive';});
16070     $dbh->do(q{UPDATE permissions SET description = 'Add and delete funds (but can''t modify funds)' WHERE code = 'budget_add_del';});
16071     $dbh->do(q{UPDATE permissions SET description = 'Manage all funds' WHERE code = 'budget_manage_all';});
16072     SetVersion( $DBversion );
16073     print "Upgrade to $DBversion done (Bug 3849- Improve descriptions of granular acquisition permissions)\n";
16074 }
16075
16076 $DBversion = '18.06.00.002';
16077 if( CheckVersion( $DBversion ) ) {
16078     $dbh->do(q{DELETE FROM userflags WHERE bit = 12 AND flag = 'management';});
16079     $dbh->do(q{UPDATE borrowers SET flags = flags - ( flags & (1<<12) ) WHERE flags & (1 << 12);});
16080     SetVersion( $DBversion );
16081     print "Upgrade to $DBversion done (Bug 2426 - Remove deprecated management permission)\n";
16082 }
16083
16084 # SEE bug 13068
16085 # if there is anything in the atomicupdate, read and execute it.
16086
16087 my $update_dir = C4::Context->config('intranetdir') . '/installer/data/mysql/atomicupdate/';
16088 opendir( my $dirh, $update_dir );
16089 foreach my $file ( sort readdir $dirh ) {
16090     next if $file !~ /\.(sql|perl)$/;  #skip other files
16091     next if $file eq 'skeleton.perl'; # skip the skeleton file
16092     print "DEV atomic update: $file\n";
16093     if ( $file =~ /\.sql$/ ) {
16094         my $installer = C4::Installer->new();
16095         my $rv = $installer->load_sql( $update_dir . $file ) ? 0 : 1;
16096     } elsif ( $file =~ /\.perl$/ ) {
16097         my $code = read_file( $update_dir . $file );
16098         eval $code;
16099         say "Atomic update generated errors: $@" if $@;
16100     }
16101 }
16102
16103 =head1 FUNCTIONS
16104
16105 =head2 TableExists($table)
16106
16107 =cut
16108
16109 sub TableExists {
16110     my $table = shift;
16111     eval {
16112                 local $dbh->{PrintError} = 0;
16113                 local $dbh->{RaiseError} = 1;
16114                 $dbh->do(qq{SELECT * FROM $table WHERE 1 = 0 });
16115             };
16116     return 1 unless $@;
16117     return 0;
16118 }
16119
16120 =head2 DropAllForeignKeys($table)
16121
16122 Drop all foreign keys of the table $table
16123
16124 =cut
16125
16126 sub DropAllForeignKeys {
16127     my ($table) = @_;
16128     # get the table description
16129     my $sth = $dbh->prepare("SHOW CREATE TABLE $table");
16130     $sth->execute;
16131     my $vsc_structure = $sth->fetchrow;
16132     # split on CONSTRAINT keyword
16133     my @fks = split /CONSTRAINT /,$vsc_structure;
16134     # parse each entry
16135     foreach (@fks) {
16136         # isolate what is before FOREIGN KEY, if there is something, it's a foreign key to drop
16137         $_ = /(.*) FOREIGN KEY.*/;
16138         my $id = $1;
16139         if ($id) {
16140             # we have found 1 foreign, drop it
16141             $dbh->do("ALTER TABLE $table DROP FOREIGN KEY $id");
16142             $id="";
16143         }
16144     }
16145 }
16146
16147
16148 =head2 TransformToNum
16149
16150 Transform the Koha version from a 4 parts string
16151 to a number, with just 1 .
16152
16153 =cut
16154
16155 sub TransformToNum {
16156     my $version = shift;
16157     # remove the 3 last . to have a Perl number
16158     $version =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
16159     # three X's at the end indicate that you are testing patch with dbrev
16160     # change it into 999
16161     # prevents error on a < comparison between strings (should be: lt)
16162     $version =~ s/XXX$/999/;
16163     return $version;
16164 }
16165
16166 =head2 SetVersion
16167
16168 set the DBversion in the systempreferences
16169
16170 =cut
16171
16172 sub SetVersion {
16173     return if $_[0]=~ /XXX$/;
16174       #you are testing a patch with a db revision; do not change version
16175     my $kohaversion = TransformToNum($_[0]);
16176     if (C4::Context->preference('Version')) {
16177       my $finish=$dbh->prepare("UPDATE systempreferences SET value=? WHERE variable='Version'");
16178       $finish->execute($kohaversion);
16179     } else {
16180       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')");
16181       $finish->execute($kohaversion);
16182     }
16183     C4::Context::clear_syspref_cache(); # invalidate cached preferences
16184 }
16185
16186 =head2 CheckVersion
16187
16188 Check whether a given update should be run when passed the proposed version
16189 number. The update will always be run if the proposed version is greater
16190 than the current database version and less than or equal to the version in
16191 kohaversion.pl. The update is also run if the version contains XXX, though
16192 this behavior will be changed following the adoption of non-linear updates
16193 as implemented in bug 7167.
16194
16195 =cut
16196
16197 sub CheckVersion {
16198     my ($proposed_version) = @_;
16199     my $version_number = TransformToNum($proposed_version);
16200
16201     # The following line should be deleted when bug 7167 is pushed
16202     return 1 if ( $proposed_version =~ m/XXX/ );
16203
16204     if ( C4::Context->preference("Version") < $version_number
16205         && $version_number <= TransformToNum( $Koha::VERSION ) )
16206     {
16207         return 1;
16208     }
16209     else {
16210         return 0;
16211     }
16212 }
16213
16214 exit;