Bug 21961: DBRev 18.12.00.001
[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::Slurp;
50
51 # FIXME - The user might be installing a new database, so can't rely
52 # on /etc/koha.conf anyway.
53
54 my $debug = 0;
55
56 my (
57     $sth, $sti,
58     $query,
59     %existingtables,    # tables already in database
60     %types,
61     $table,
62     $column,
63     $type, $null, $key, $default, $extra,
64     $prefitem,          # preference item in systempreferences table
65 );
66
67 my $schema = Koha::Database->new()->schema();
68
69 my $silent;
70 GetOptions(
71     's' =>\$silent
72     );
73 my $dbh = C4::Context->dbh;
74 $|=1; # flushes output
75
76 local $dbh->{RaiseError} = 0;
77
78 # Record the version we are coming from
79
80 my $original_version = C4::Context->preference("Version");
81
82 # Deal with virtualshelves
83 my $DBversion = "3.00.00.001";
84 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
85     # update virtualshelves table to
86     #
87     $dbh->do("ALTER TABLE `bookshelf` RENAME `virtualshelves`");
88     $dbh->do("ALTER TABLE `shelfcontents` RENAME `virtualshelfcontents`");
89     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD `biblionumber` INT( 11 ) NOT NULL default '0' AFTER shelfnumber");
90     $dbh->do("UPDATE `virtualshelfcontents` SET biblionumber=(SELECT biblionumber FROM items WHERE items.itemnumber=virtualshelfcontents.itemnumber)");
91     # drop all foreign keys : otherwise, we can't drop itemnumber field.
92     DropAllForeignKeys('virtualshelfcontents');
93     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD KEY biblionumber (biblionumber)");
94     # create the new foreign keys (on biblionumber)
95     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD CONSTRAINT `virtualshelfcontents_ibfk_1` FOREIGN KEY (`shelfnumber`) REFERENCES `virtualshelves` (`shelfnumber`) ON DELETE CASCADE ON UPDATE CASCADE");
96     # re-create the foreign key on virtualshelf
97     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD CONSTRAINT `shelfcontents_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE");
98     $dbh->do("ALTER TABLE `virtualshelfcontents` DROP `itemnumber`");
99     print "Upgrade to $DBversion done (virtualshelves)\n";
100     SetVersion ($DBversion);
101 }
102
103
104 $DBversion = "3.00.00.002";
105 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
106     $dbh->do("DROP TABLE sessions");
107     $dbh->do("CREATE TABLE `sessions` (
108   `id` varchar(32) NOT NULL,
109   `a_session` text NOT NULL,
110   UNIQUE KEY `id` (`id`)
111 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
112     print "Upgrade to $DBversion done (sessions uses CGI::session, new table structure for sessions)\n";
113     SetVersion ($DBversion);
114 }
115
116
117 $DBversion = "3.00.00.003";
118 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
119     if (C4::Context->preference("opaclanguages") eq "fr") {
120         $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')");
121     } else {
122         $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')");
123     }
124     print "Upgrade to $DBversion done (adding ReservesNeedReturns systempref, in circulation)\n";
125     SetVersion ($DBversion);
126 }
127
128
129 $DBversion = "3.00.00.004";
130 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
131     $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')");
132     print "Upgrade to $DBversion done (adding DebugLevel systempref, in 'Admin' tab)\n";
133     SetVersion ($DBversion);
134 }
135
136 $DBversion = "3.00.00.005";
137 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
138     $dbh->do("CREATE TABLE `tags` (
139                     `entry` varchar(255) NOT NULL default '',
140                     `weight` bigint(20) NOT NULL default 0,
141                     PRIMARY KEY  (`entry`)
142                     ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
143                 ");
144         $dbh->do("CREATE TABLE `nozebra` (
145                 `server` varchar(20)     NOT NULL,
146                 `indexname` varchar(40)  NOT NULL,
147                 `value` varchar(250)     NOT NULL,
148                 `biblionumbers` longtext NOT NULL,
149                 KEY `indexname` (`server`,`indexname`),
150                 KEY `value` (`server`,`value`))
151                 ENGINE=InnoDB DEFAULT CHARSET=utf8;
152                 ");
153     print "Upgrade to $DBversion done (adding tags and nozebra tables )\n";
154     SetVersion ($DBversion);
155 }
156
157 $DBversion = "3.00.00.006";
158 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
159     $dbh->do("UPDATE issues SET issuedate=timestamp WHERE issuedate='0000-00-00'");
160     print "Upgrade to $DBversion done (filled issues.issuedate with timestamp)\n";
161     SetVersion ($DBversion);
162 }
163
164 $DBversion = "3.00.00.007";
165 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
166     $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')");
167     print "Upgrade to $DBversion done (set SessionStorage variable)\n";
168     SetVersion ($DBversion);
169 }
170
171 $DBversion = "3.00.00.008";
172 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
173     $dbh->do("ALTER TABLE `biblio` ADD `datecreated` DATE NOT NULL AFTER `timestamp` ;");
174     $dbh->do("UPDATE biblio SET datecreated=timestamp");
175     print "Upgrade to $DBversion done (biblio creation date)\n";
176     SetVersion ($DBversion);
177 }
178
179 $DBversion = "3.00.00.009";
180 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
181
182     # Create backups of call number columns
183     # in case default migration needs to be customized
184     #
185     # UPGRADE NOTE: temp_upg_biblioitems_call_num should be dropped
186     #               after call numbers have been transformed to the new structure
187     #
188     # Not bothering to do the same with deletedbiblioitems -- assume
189     # default is good enough.
190     $dbh->do("CREATE TABLE `temp_upg_biblioitems_call_num` AS
191               SELECT `biblioitemnumber`, `biblionumber`,
192                      `classification`, `dewey`, `subclass`,
193                      `lcsort`, `ccode`
194               FROM `biblioitems`");
195
196     # biblioitems changes
197     $dbh->do("ALTER TABLE `biblioitems` CHANGE COLUMN `volumeddesc` `volumedesc` TEXT,
198                                     ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
199                                     ADD `cn_class` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
200                                     ADD `cn_item` VARCHAR(10) DEFAULT NULL AFTER `cn_class`,
201                                     ADD `cn_suffix` VARCHAR(10) DEFAULT NULL AFTER `cn_item`,
202                                     ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_suffix`,
203                                     ADD `totalissues` INT(10) AFTER `cn_sort`");
204
205     # default mapping of call number columns:
206     #   cn_class = concatentation of classification + dewey,
207     #              trimmed to fit -- assumes that most users do not
208     #              populate both classification and dewey in a single record
209     #   cn_item  = subclass
210     #   cn_source = left null
211     #   cn_sort = lcsort
212     #
213     # After upgrade, cn_sort will have to be set based on whatever
214     # default call number scheme user sets as a preference.  Misc
215     # script will be added at some point to do that.
216     #
217     $dbh->do("UPDATE `biblioitems`
218               SET cn_class = SUBSTR(TRIM(CONCAT_WS(' ', `classification`, `dewey`)), 1, 30),
219                     cn_item = subclass,
220                     `cn_sort` = `lcsort`
221             ");
222
223     # Now drop the old call number columns
224     $dbh->do("ALTER TABLE `biblioitems` DROP COLUMN `classification`,
225                                         DROP COLUMN `dewey`,
226                                         DROP COLUMN `subclass`,
227                                         DROP COLUMN `lcsort`,
228                                         DROP COLUMN `ccode`");
229
230     # deletedbiblio changes
231     $dbh->do("ALTER TABLE `deletedbiblio` ALTER COLUMN `frameworkcode` SET DEFAULT '',
232                                         DROP COLUMN `marc`,
233                                         ADD `datecreated` DATE NOT NULL AFTER `timestamp`");
234     $dbh->do("UPDATE deletedbiblio SET datecreated = timestamp");
235
236     # deletedbiblioitems changes
237     $dbh->do("ALTER TABLE `deletedbiblioitems`
238                         MODIFY `publicationyear` TEXT,
239                         CHANGE `volumeddesc` `volumedesc` TEXT,
240                         MODIFY `collectiontitle` MEDIUMTEXT DEFAULT NULL AFTER `volumedesc`,
241                         MODIFY `collectionissn` TEXT DEFAULT NULL AFTER `collectiontitle`,
242                         MODIFY `collectionvolume` MEDIUMTEXT DEFAULT NULL AFTER `collectionissn`,
243                         MODIFY `editionstatement` TEXT DEFAULT NULL AFTER `collectionvolume`,
244                         MODIFY `editionresponsibility` TEXT DEFAULT NULL AFTER `editionstatement`,
245                         MODIFY `place` VARCHAR(255) DEFAULT NULL AFTER `size`,
246                         MODIFY `marc` LONGBLOB,
247                         ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `url`,
248                         ADD `cn_class` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
249                         ADD `cn_item` VARCHAR(10) DEFAULT NULL AFTER `cn_class`,
250                         ADD `cn_suffix` VARCHAR(10) DEFAULT NULL AFTER `cn_item`,
251                         ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_suffix`,
252                         ADD `totalissues` INT(10) AFTER `cn_sort`,
253                         ADD `marcxml` LONGTEXT NOT NULL AFTER `totalissues`,
254                         ADD KEY `isbn` (`isbn`),
255                         ADD KEY `publishercode` (`publishercode`)
256                     ");
257
258     $dbh->do("UPDATE `deletedbiblioitems`
259                 SET `cn_class` = SUBSTR(TRIM(CONCAT_WS(' ', `classification`, `dewey`)), 1, 30),
260                `cn_item` = `subclass`,
261                 `cn_sort` = `lcsort`
262             ");
263     $dbh->do("ALTER TABLE `deletedbiblioitems`
264                         DROP COLUMN `classification`,
265                         DROP COLUMN `dewey`,
266                         DROP COLUMN `subclass`,
267                         DROP COLUMN `lcsort`,
268                         DROP COLUMN `ccode`
269             ");
270
271     # deleteditems changes
272     $dbh->do("ALTER TABLE `deleteditems`
273                         MODIFY `barcode` VARCHAR(20) DEFAULT NULL,
274                         MODIFY `price` DECIMAL(8,2) DEFAULT NULL,
275                         MODIFY `replacementprice` DECIMAL(8,2) DEFAULT NULL,
276                         DROP `bulk`,
277                         MODIFY `itemcallnumber` VARCHAR(30) DEFAULT NULL AFTER `wthdrawn`,
278                         MODIFY `holdingbranch` VARCHAR(10) DEFAULT NULL,
279                         DROP `interim`,
280                         MODIFY `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP AFTER `paidfor`,
281                         DROP `cutterextra`,
282                         ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `onloan`,
283                         ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
284                         ADD `ccode` VARCHAR(10) DEFAULT NULL AFTER `cn_sort`,
285                         ADD `materials` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
286                         ADD `uri` VARCHAR(255) DEFAULT NULL AFTER `materials`,
287                         MODIFY `marc` LONGBLOB AFTER `uri`,
288                         DROP KEY `barcode`,
289                         DROP KEY `itembarcodeidx`,
290                         DROP KEY `itembinoidx`,
291                         DROP KEY `itembibnoidx`,
292                         ADD UNIQUE KEY `delitembarcodeidx` (`barcode`),
293                         ADD KEY `delitembinoidx` (`biblioitemnumber`),
294                         ADD KEY `delitembibnoidx` (`biblionumber`),
295                         ADD KEY `delhomebranch` (`homebranch`),
296                         ADD KEY `delholdingbranch` (`holdingbranch`)");
297     $dbh->do("UPDATE deleteditems SET `ccode` = `itype`");
298     $dbh->do("ALTER TABLE deleteditems DROP `itype`");
299     $dbh->do("UPDATE `deleteditems` SET `cn_sort` = `itemcallnumber`");
300
301     # items changes
302     $dbh->do("ALTER TABLE `items` ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `onloan`,
303                                 ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
304                                 ADD `ccode` VARCHAR(10) DEFAULT NULL AFTER `cn_sort`,
305                                 ADD `materials` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
306                                 ADD `uri` VARCHAR(255) DEFAULT NULL AFTER `materials`
307             ");
308     $dbh->do("ALTER TABLE `items`
309                         DROP KEY `itembarcodeidx`,
310                         ADD UNIQUE KEY `itembarcodeidx` (`barcode`)");
311
312     # map items.itype to items.ccode and
313     # set cn_sort to itemcallnumber -- as with biblioitems.cn_sort,
314     # will have to be subsequently updated per user's default
315     # classification scheme
316     $dbh->do("UPDATE `items` SET `cn_sort` = `itemcallnumber`,
317                             `ccode` = `itype`");
318
319     $dbh->do("ALTER TABLE `items` DROP `cutterextra`,
320                                 DROP `itype`");
321
322     print "Upgrade to $DBversion done (major changes to biblio, biblioitems, items, and deleted* versions of same\n";
323     SetVersion ($DBversion);
324 }
325
326 $DBversion = "3.00.00.010";
327 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
328     $dbh->do("CREATE INDEX `userid` ON borrowers (`userid`) ");
329     print "Upgrade to $DBversion done (userid index added)\n";
330     SetVersion ($DBversion);
331 }
332
333 $DBversion = "3.00.00.011";
334 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
335     $dbh->do("ALTER TABLE `branchcategories` CHANGE `categorycode` `categorycode` varchar(10) ");
336     $dbh->do("ALTER TABLE `branchcategories` CHANGE `categoryname` `categoryname` varchar(32) ");
337     $dbh->do("ALTER TABLE `branchcategories` ADD COLUMN `categorytype` varchar(16) ");
338     $dbh->do("UPDATE `branchcategories` SET `categorytype` = 'properties'");
339     $dbh->do("ALTER TABLE `branchrelations` CHANGE `categorycode` `categorycode` varchar(10) ");
340     print "Upgrade to $DBversion done (added branchcategory type)\n";
341     SetVersion ($DBversion);
342 }
343
344 $DBversion = "3.00.00.012";
345 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
346     $dbh->do("CREATE TABLE `class_sort_rules` (
347                                `class_sort_rule` varchar(10) NOT NULL default '',
348                                `description` mediumtext,
349                                `sort_routine` varchar(30) NOT NULL default '',
350                                PRIMARY KEY (`class_sort_rule`),
351                                UNIQUE KEY `class_sort_rule_idx` (`class_sort_rule`)
352                              ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
353     $dbh->do("CREATE TABLE `class_sources` (
354                                `cn_source` varchar(10) NOT NULL default '',
355                                `description` mediumtext,
356                                `used` tinyint(4) NOT NULL default 0,
357                                `class_sort_rule` varchar(10) NOT NULL default '',
358                                PRIMARY KEY (`cn_source`),
359                                UNIQUE KEY `cn_source_idx` (`cn_source`),
360                                KEY `used_idx` (`used`),
361                                CONSTRAINT `class_source_ibfk_1` FOREIGN KEY (`class_sort_rule`)
362                                           REFERENCES `class_sort_rules` (`class_sort_rule`)
363                              ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
364     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type)
365               VALUES('DefaultClassificationSource','ddc',
366                      'Default classification scheme used by the collection. E.g., Dewey, LCC, etc.', NULL,'free')");
367     $dbh->do("INSERT INTO `class_sort_rules` (`class_sort_rule`, `description`, `sort_routine`) VALUES
368                                ('dewey', 'Default filing rules for DDC', 'Dewey'),
369                                ('lcc', 'Default filing rules for LCC', 'LCC'),
370                                ('generic', 'Generic call number filing rules', 'Generic')");
371     $dbh->do("INSERT INTO `class_sources` (`cn_source`, `description`, `used`, `class_sort_rule`) VALUES
372                             ('ddc', 'Dewey Decimal Classification', 1, 'dewey'),
373                             ('lcc', 'Library of Congress Classification', 1, 'lcc'),
374                             ('udc', 'Universal Decimal Classification', 0, 'generic'),
375                             ('sudocs', 'SuDoc Classification (U.S. GPO)', 0, 'generic'),
376                             ('z', 'Other/Generic Classification Scheme', 0, 'generic')");
377     print "Upgrade to $DBversion done (classification sources added)\n";
378     SetVersion ($DBversion);
379 }
380
381 $DBversion = "3.00.00.013";
382 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
383     $dbh->do("CREATE TABLE `import_batches` (
384               `import_batch_id` int(11) NOT NULL auto_increment,
385               `template_id` int(11) default NULL,
386               `branchcode` varchar(10) default NULL,
387               `num_biblios` int(11) NOT NULL default 0,
388               `num_items` int(11) NOT NULL default 0,
389               `upload_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
390               `overlay_action` enum('replace', 'create_new', 'use_template') NOT NULL default 'create_new',
391               `import_status` enum('staging', 'staged', 'importing', 'imported', 'reverting', 'reverted', 'cleaned') NOT NULL default 'staging',
392               `batch_type` enum('batch', 'z3950') NOT NULL default 'batch',
393               `file_name` varchar(100),
394               `comments` mediumtext,
395               PRIMARY KEY (`import_batch_id`),
396               KEY `branchcode` (`branchcode`)
397               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
398     $dbh->do("CREATE TABLE `import_records` (
399               `import_record_id` int(11) NOT NULL auto_increment,
400               `import_batch_id` int(11) NOT NULL,
401               `branchcode` varchar(10) default NULL,
402               `record_sequence` int(11) NOT NULL default 0,
403               `upload_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
404               `import_date` DATE default NULL,
405               `marc` longblob NOT NULL,
406               `marcxml` longtext NOT NULL,
407               `marcxml_old` longtext NOT NULL,
408               `record_type` enum('biblio', 'auth', 'holdings') NOT NULL default 'biblio',
409               `overlay_status` enum('no_match', 'auto_match', 'manual_match', 'match_applied') NOT NULL default 'no_match',
410               `status` enum('error', 'staged', 'imported', 'reverted', 'items_reverted') NOT NULL default 'staged',
411               `import_error` mediumtext,
412               `encoding` varchar(40) NOT NULL default '',
413               `z3950random` varchar(40) default NULL,
414               PRIMARY KEY (`import_record_id`),
415               CONSTRAINT `import_records_ifbk_1` FOREIGN KEY (`import_batch_id`)
416                           REFERENCES `import_batches` (`import_batch_id`) ON DELETE CASCADE ON UPDATE CASCADE,
417               KEY `branchcode` (`branchcode`),
418               KEY `batch_sequence` (`import_batch_id`, `record_sequence`)
419               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
420     $dbh->do("CREATE TABLE `import_record_matches` (
421               `import_record_id` int(11) NOT NULL,
422               `candidate_match_id` int(11) NOT NULL,
423               `score` int(11) NOT NULL default 0,
424               CONSTRAINT `import_record_matches_ibfk_1` FOREIGN KEY (`import_record_id`)
425                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
426               KEY `record_score` (`import_record_id`, `score`)
427               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
428     $dbh->do("CREATE TABLE `import_biblios` (
429               `import_record_id` int(11) NOT NULL,
430               `matched_biblionumber` int(11) default NULL,
431               `control_number` varchar(25) default NULL,
432               `original_source` varchar(25) default NULL,
433               `title` varchar(128) default NULL,
434               `author` varchar(80) default NULL,
435               `isbn` varchar(14) default NULL,
436               `issn` varchar(9) default NULL,
437               `has_items` tinyint(1) NOT NULL default 0,
438               CONSTRAINT `import_biblios_ibfk_1` FOREIGN KEY (`import_record_id`)
439                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
440               KEY `matched_biblionumber` (`matched_biblionumber`),
441               KEY `title` (`title`),
442               KEY `isbn` (`isbn`)
443               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
444     $dbh->do("CREATE TABLE `import_items` (
445               `import_items_id` int(11) NOT NULL auto_increment,
446               `import_record_id` int(11) NOT NULL,
447               `itemnumber` int(11) default NULL,
448               `branchcode` varchar(10) default NULL,
449               `status` enum('error', 'staged', 'imported', 'reverted') NOT NULL default 'staged',
450               `marcxml` longtext NOT NULL,
451               `import_error` mediumtext,
452               PRIMARY KEY (`import_items_id`),
453               CONSTRAINT `import_items_ibfk_1` FOREIGN KEY (`import_record_id`)
454                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
455               KEY `itemnumber` (`itemnumber`),
456               KEY `branchcode` (`branchcode`)
457               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
458
459     $dbh->do("INSERT INTO `import_batches`
460                 (`overlay_action`, `import_status`, `batch_type`, `file_name`)
461               SELECT distinct 'create_new', 'staged', 'z3950', `file`
462               FROM   `marc_breeding`");
463
464     $dbh->do("INSERT INTO `import_records`
465                 (`import_batch_id`, `import_record_id`, `record_sequence`, `marc`, `record_type`, `status`,
466                 `encoding`, `z3950random`, `marcxml`, `marcxml_old`)
467               SELECT `import_batch_id`, `id`, 1, `marc`, 'biblio', 'staged', `encoding`, `z3950random`, '', ''
468               FROM `marc_breeding`
469               JOIN `import_batches` ON (`file_name` = `file`)");
470
471     $dbh->do("INSERT INTO `import_biblios`
472                 (`import_record_id`, `title`, `author`, `isbn`)
473               SELECT `import_record_id`, `title`, `author`, `isbn`
474               FROM   `marc_breeding`
475               JOIN   `import_records` ON (`import_record_id` = `id`)");
476
477     $dbh->do("UPDATE `import_batches`
478               SET `num_biblios` = (
479               SELECT COUNT(*)
480               FROM `import_records`
481               WHERE `import_batch_id` = `import_batches`.`import_batch_id`
482               )");
483
484     $dbh->do("DROP TABLE `marc_breeding`");
485
486     print "Upgrade to $DBversion done (import_batches et al. added)\n";
487     SetVersion ($DBversion);
488 }
489
490 $DBversion = "3.00.00.014";
491 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
492     $dbh->do("ALTER TABLE subscription ADD lastbranch VARCHAR(4)");
493     print "Upgrade to $DBversion done (userid index added)\n";
494     SetVersion ($DBversion);
495 }
496
497 $DBversion = "3.00.00.015";
498 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
499     $dbh->do("CREATE TABLE `saved_sql` (
500            `id` int(11) NOT NULL auto_increment,
501            `borrowernumber` int(11) default NULL,
502            `date_created` datetime default NULL,
503            `last_modified` datetime default NULL,
504            `savedsql` text,
505            `last_run` datetime default NULL,
506            `report_name` varchar(255) default NULL,
507            `type` varchar(255) default NULL,
508            `notes` text,
509            PRIMARY KEY  (`id`),
510            KEY boridx (`borrowernumber`)
511         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
512     $dbh->do("CREATE TABLE `saved_reports` (
513            `id` int(11) NOT NULL auto_increment,
514            `report_id` int(11) default NULL,
515            `report` longtext,
516            `date_run` datetime default NULL,
517            PRIMARY KEY  (`id`)
518         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
519     print "Upgrade to $DBversion done (saved_sql and saved_reports added)\n";
520     SetVersion ($DBversion);
521 }
522
523 $DBversion = "3.00.00.016";
524 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
525     $dbh->do(" CREATE TABLE reports_dictionary (
526           id int(11) NOT NULL auto_increment,
527           name varchar(255) default NULL,
528           description text,
529           date_created datetime default NULL,
530           date_modified datetime default NULL,
531           saved_sql text,
532           area int(11) default NULL,
533           PRIMARY KEY  (id)
534         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
535     print "Upgrade to $DBversion done (reports_dictionary) added)\n";
536     SetVersion ($DBversion);
537 }
538
539 $DBversion = "3.00.00.017";
540 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
541     $dbh->do("ALTER TABLE action_logs DROP PRIMARY KEY");
542     $dbh->do("ALTER TABLE action_logs ADD KEY  timestamp (timestamp,user)");
543     $dbh->do("ALTER TABLE action_logs ADD action_id INT(11) NOT NULL FIRST");
544     $dbh->do("UPDATE action_logs SET action_id = if (\@a, \@a:=\@a+1, \@a:=1)");
545     $dbh->do("ALTER TABLE action_logs MODIFY action_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY");
546     print "Upgrade to $DBversion done (added column to action_logs)\n";
547     SetVersion ($DBversion);
548 }
549
550 $DBversion = "3.00.00.018";
551 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
552     $dbh->do("ALTER TABLE `zebraqueue`
553                     ADD `done` INT NOT NULL DEFAULT '0',
554                     ADD `time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ;
555             ");
556     print "Upgrade to $DBversion done (adding timestamp and done columns to zebraque table to improve problem tracking) added)\n";
557     SetVersion ($DBversion);
558 }
559
560 $DBversion = "3.00.00.019";
561 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
562     $dbh->do("ALTER TABLE biblio MODIFY biblionumber INT(11) NOT NULL AUTO_INCREMENT");
563     $dbh->do("ALTER TABLE biblioitems MODIFY biblioitemnumber INT(11) NOT NULL AUTO_INCREMENT");
564     $dbh->do("ALTER TABLE items MODIFY itemnumber INT(11) NOT NULL AUTO_INCREMENT");
565     print "Upgrade to $DBversion done (made bib/item PKs auto_increment)\n";
566     SetVersion ($DBversion);
567 }
568
569 $DBversion = "3.00.00.020";
570 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
571     $dbh->do("ALTER TABLE deleteditems
572               DROP KEY `delitembarcodeidx`,
573               ADD KEY `delitembarcodeidx` (`barcode`)");
574     print "Upgrade to $DBversion done (dropped uniqueness of key on deleteditems.barcode)\n";
575     SetVersion ($DBversion);
576 }
577
578 $DBversion = "3.00.00.021";
579 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
580     $dbh->do("ALTER TABLE items CHANGE homebranch homebranch VARCHAR(10)");
581     $dbh->do("ALTER TABLE deleteditems CHANGE homebranch homebranch VARCHAR(10)");
582     $dbh->do("ALTER TABLE statistics CHANGE branch branch VARCHAR(10)");
583     $dbh->do("ALTER TABLE subscription CHANGE lastbranch lastbranch VARCHAR(10)");
584     print "Upgrade to $DBversion done (extended missed branchcode columns to 10 chars)\n";
585     SetVersion ($DBversion);
586 }
587
588 $DBversion = "3.00.00.022";
589 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
590     $dbh->do("ALTER TABLE items
591                 ADD `damaged` tinyint(1) default NULL AFTER notforloan");
592     $dbh->do("ALTER TABLE deleteditems
593                 ADD `damaged` tinyint(1) default NULL AFTER notforloan");
594     print "Upgrade to $DBversion done (adding damaged column to items table)\n";
595     SetVersion ($DBversion);
596 }
597
598 $DBversion = "3.00.00.023";
599 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
600      $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
601          VALUES ('yuipath','http://yui.yahooapis.com/2.3.1/build','Insert the path to YUI libraries','','free')");
602     print "Upgrade to $DBversion done (adding new system preference for controlling YUI path)\n";
603     SetVersion ($DBversion);
604 }
605 $DBversion = "3.00.00.024";
606 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
607     $dbh->do("ALTER TABLE biblioitems CHANGE  itemtype itemtype VARCHAR(10)");
608     print "Upgrade to $DBversion done (changing itemtype to (10))\n";
609     SetVersion ($DBversion);
610 }
611
612 $DBversion = "3.00.00.025";
613 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
614     $dbh->do("ALTER TABLE items ADD COLUMN itype VARCHAR(10)");
615     $dbh->do("ALTER TABLE deleteditems ADD COLUMN itype VARCHAR(10) AFTER uri");
616     if(C4::Context->preference('item-level_itypes')){
617         $dbh->do('update items,biblioitems set items.itype=biblioitems.itemtype where items.biblionumber=biblioitems.biblionumber and itype is null');
618     }
619     print "Upgrade to $DBversion done (reintroduce items.itype - fill from itemtype)\n ";
620     SetVersion ($DBversion);
621 }
622
623 $DBversion = "3.00.00.026";
624 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
625     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
626        VALUES ('HomeOrHoldingBranch','homebranch','homebranch|holdingbranch','With independent branches turned on this decides whether to check the items holdingbranch or homebranch at circulatilon','choice')");
627     print "Upgrade to $DBversion done (adding new system preference for choosing whether homebranch or holdingbranch is checked in circulation)\n";
628     SetVersion ($DBversion);
629 }
630
631 $DBversion = "3.00.00.027";
632 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
633     $dbh->do("CREATE TABLE `marc_matchers` (
634                 `matcher_id` int(11) NOT NULL auto_increment,
635                 `code` varchar(10) NOT NULL default '',
636                 `description` varchar(255) NOT NULL default '',
637                 `record_type` varchar(10) NOT NULL default 'biblio',
638                 `threshold` int(11) NOT NULL default 0,
639                 PRIMARY KEY (`matcher_id`),
640                 KEY `code` (`code`),
641                 KEY `record_type` (`record_type`)
642               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
643     $dbh->do("CREATE TABLE `matchpoints` (
644                 `matcher_id` int(11) NOT NULL,
645                 `matchpoint_id` int(11) NOT NULL auto_increment,
646                 `search_index` varchar(30) NOT NULL default '',
647                 `score` int(11) NOT NULL default 0,
648                 PRIMARY KEY (`matchpoint_id`),
649                 CONSTRAINT `matchpoints_ifbk_1` FOREIGN KEY (`matcher_id`)
650                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE
651               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
652     $dbh->do("CREATE TABLE `matchpoint_components` (
653                 `matchpoint_id` int(11) NOT NULL,
654                 `matchpoint_component_id` int(11) NOT NULL auto_increment,
655                 sequence int(11) NOT NULL default 0,
656                 tag varchar(3) NOT NULL default '',
657                 subfields varchar(40) NOT NULL default '',
658                 offset int(4) NOT NULL default 0,
659                 length int(4) NOT NULL default 0,
660                 PRIMARY KEY (`matchpoint_component_id`),
661                 KEY `by_sequence` (`matchpoint_id`, `sequence`),
662                 CONSTRAINT `matchpoint_components_ifbk_1` FOREIGN KEY (`matchpoint_id`)
663                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
664               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
665     $dbh->do("CREATE TABLE `matchpoint_component_norms` (
666                 `matchpoint_component_id` int(11) NOT NULL,
667                 `sequence`  int(11) NOT NULL default 0,
668                 `norm_routine` varchar(50) NOT NULL default '',
669                 KEY `matchpoint_component_norms` (`matchpoint_component_id`, `sequence`),
670                 CONSTRAINT `matchpoint_component_norms_ifbk_1` FOREIGN KEY (`matchpoint_component_id`)
671                            REFERENCES `matchpoint_components` (`matchpoint_component_id`) ON DELETE CASCADE ON UPDATE CASCADE
672               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
673     $dbh->do("CREATE TABLE `matcher_matchpoints` (
674                 `matcher_id` int(11) NOT NULL,
675                 `matchpoint_id` int(11) NOT NULL,
676                 CONSTRAINT `matcher_matchpoints_ifbk_1` FOREIGN KEY (`matcher_id`)
677                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE,
678                 CONSTRAINT `matcher_matchpoints_ifbk_2` FOREIGN KEY (`matchpoint_id`)
679                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
680               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
681     $dbh->do("CREATE TABLE `matchchecks` (
682                 `matcher_id` int(11) NOT NULL,
683                 `matchcheck_id` int(11) NOT NULL auto_increment,
684                 `source_matchpoint_id` int(11) NOT NULL,
685                 `target_matchpoint_id` int(11) NOT NULL,
686                 PRIMARY KEY (`matchcheck_id`),
687                 CONSTRAINT `matcher_matchchecks_ifbk_1` FOREIGN KEY (`matcher_id`)
688                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE,
689                 CONSTRAINT `matcher_matchchecks_ifbk_2` FOREIGN KEY (`source_matchpoint_id`)
690                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE,
691                 CONSTRAINT `matcher_matchchecks_ifbk_3` FOREIGN KEY (`target_matchpoint_id`)
692                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
693               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
694     print "Upgrade to $DBversion done (added C4::Matcher serialization tables)\n ";
695     SetVersion ($DBversion);
696 }
697
698 $DBversion = "3.00.00.028";
699 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
700     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
701        VALUES ('canreservefromotherbranches','1','','With Independent branches on, can a user from one library reserve an item from another library','YesNo')");
702     print "Upgrade to $DBversion done (adding new system preference for changing reserve/holds behaviour with independent branches)\n";
703     SetVersion ($DBversion);
704 }
705
706
707 $DBversion = "3.00.00.029";
708 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
709     $dbh->do("ALTER TABLE `import_batches` ADD `matcher_id` int(11) NULL AFTER `import_batch_id`");
710     print "Upgrade to $DBversion done (adding matcher_id to import_batches)\n";
711     SetVersion ($DBversion);
712 }
713
714 $DBversion = "3.00.00.030";
715 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
716     $dbh->do("
717 CREATE TABLE services_throttle (
718   service_type varchar(10) NOT NULL default '',
719   service_count varchar(45) default NULL,
720   PRIMARY KEY  (service_type)
721 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
722 ");
723     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
724        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')");
725  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
726        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')");
727  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
728        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')");
729  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
730        VALUES ('XISBNDailyLimit',499,'','The xISBN Web service is free for non-commercial use when usage does not exceed 500 requests per day','free')");
731  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
732        VALUES ('PINESISBN',0,'','Use with FRBRizeEditions. If ON, Koha will use PINES OISBN web service in the Editions tab on the detail pages.','YesNo')");
733  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
734        VALUES ('ThingISBN',0,'','Use with FRBRizeEditions. If ON, Koha will use the ThingISBN web service in the Editions tab on the detail pages.','YesNo')");
735     print "Upgrade to $DBversion done (adding services throttle table and sysprefs for xISBN)\n";
736     SetVersion ($DBversion);
737 }
738
739 $DBversion = "3.00.00.031";
740 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
741
742 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryStemming',1,'If ON, enables query stemming',NULL,'YesNo')");
743 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryFuzzy',1,'If ON, enables fuzzy option for searches',NULL,'YesNo')");
744 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryWeightFields',1,'If ON, enables field weighting',NULL,'YesNo')");
745 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('WebBasedSelfCheck',0,'If ON, enables the web-based self-check system',NULL,'YesNo')");
746 $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')");
747 $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')");
748 $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')");
749 $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')");
750 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('defaultSortOrder',NULL,'Specify the default sort order','asc|dsc|az|za','Choice')");
751 $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')");
752 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACdefaultSortOrder',NULL,'Specify the default sort order','asc|dsc|za|az','Choice')");
753 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('staffClientBaseURL','','Specify the base URL of the staff client',NULL,'free')");
754 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('minPasswordLength',3,'Specify the minimum length of a patron/staff password',NULL,'free')");
755 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('noItemTypeImages',0,'If ON, disables item-type images',NULL,'YesNo')");
756 $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')");
757 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('holdCancelLength','','Specify how many days before a hold is canceled',NULL,'free')");
758 $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')");
759 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('finesMode','test','Choose the fines mode, test or production','test|production','Choice')");
760 $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')");
761 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('itemBarcodeInputFilter','','If set, allows specification of a item barcode input filter','cuecat','Choice')");
762 $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')");
763 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('URLLinkText','','Text to display as the link anchor in the OPAC',NULL,'free')");
764 $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')");
765 $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')");
766 $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')");
767 $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')");
768 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACUserCSS',0,'Add CSS to be included in the OPAC',NULL,'free')");
769
770     print "Upgrade to $DBversion done (adding additional system preference)\n";
771     SetVersion ($DBversion);
772 }
773
774 $DBversion = "3.00.00.032";
775 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
776     $dbh->do("UPDATE `marc_subfield_structure` SET `kohafield` = 'items.wthdrawn' WHERE `kohafield` = 'items.withdrawn'");
777     print "Upgrade to $DBversion done (fixed MARC framework references to items.withdrawn)\n";
778     SetVersion ($DBversion);
779 }
780
781 $DBversion = "3.00.00.033";
782 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
783     $dbh->do("INSERT INTO `userflags` VALUES(17,'staffaccess','Modify login / permissions for staff users',0)");
784     print "Upgrade to $DBversion done (Adding permissions flag for staff member access modification.  )\n";
785     SetVersion ($DBversion);
786 }
787
788 $DBversion = "3.00.00.034";
789 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
790     $dbh->do("ALTER TABLE `virtualshelves` ADD COLUMN `sortfield` VARCHAR(16) ");
791     print "Upgrade to $DBversion done (Adding sortfield for Virtual Shelves.  )\n";
792     SetVersion ($DBversion);
793 }
794
795 $DBversion = "3.00.00.035";
796 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
797     $dbh->do("UPDATE marc_subfield_structure
798               SET authorised_value = 'cn_source'
799               WHERE kohafield IN ('items.cn_source', 'biblioitems.cn_source')
800               AND (authorised_value is NULL OR authorised_value = '')");
801     print "Upgrade to $DBversion done (MARC frameworks: make classification source a drop-down)\n";
802     SetVersion ($DBversion);
803 }
804
805 $DBversion = "3.00.00.036";
806 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
807     $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');");
808     print "Upgrade to $DBversion done (OPACItemsResultsDisplay systempreference added)\n";
809     SetVersion ($DBversion);
810 }
811
812 $DBversion = "3.00.00.037";
813 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
814     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactfirstname` varchar(255)");
815     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactsurname` varchar(255)");
816     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress1` varchar(255)");
817     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress2` varchar(255)");
818     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress3` varchar(255)");
819     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactzipcode` varchar(50)");
820     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactphone` varchar(50)");
821     print "Upgrade to $DBversion done (Adding Alternative Contact Person information to borrowers table)\n";
822     SetVersion ($DBversion);
823 }
824
825 $DBversion = "3.00.00.038";
826 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
827     $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'");
828     $dbh->do("DELETE FROM `systempreferences` WHERE variable='hideBiblioNumber'");
829     print "Upgrade to $DBversion done ('alter finesMode systempreference, remove superfluous syspref.')\n";
830     SetVersion ($DBversion);
831 }
832
833 $DBversion = "3.00.00.039";
834 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
835     $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')");
836     $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')");
837     $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')");
838     # $dbh->do("DELETE FROM `systempreferences` WHERE variable='HomeOrHoldingBranch'"); # Bug #2752
839     print "Upgrade to $DBversion done ('add circ sysprefs CircControl, finesCalendar, and uppercasesurnames, and delete HomeOrHoldingBranch.')\n";
840     SetVersion ($DBversion);
841 }
842
843 $DBversion = "3.00.00.040";
844 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
845         $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')");
846         $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')");
847         print "Upgrade to $DBversion done ('add circ sysprefs todaysIssuesDefaultSortOrder and previousIssuesDefaultSortOrder.')\n";
848     SetVersion ($DBversion);
849 }
850
851
852 $DBversion = "3.00.00.041";
853 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
854     # Strictly speaking it is not necessary to explicitly change
855     # NULL values to 0, because the ALTER TABLE statement will do that.
856     # However, setting them first avoids a warning.
857     $dbh->do("UPDATE items SET notforloan = 0 WHERE notforloan IS NULL");
858     $dbh->do("UPDATE items SET damaged = 0 WHERE damaged IS NULL");
859     $dbh->do("UPDATE items SET itemlost = 0 WHERE itemlost IS NULL");
860     $dbh->do("UPDATE items SET wthdrawn = 0 WHERE wthdrawn IS NULL");
861     $dbh->do("ALTER TABLE items
862                 MODIFY notforloan tinyint(1) NOT NULL default 0,
863                 MODIFY damaged    tinyint(1) NOT NULL default 0,
864                 MODIFY itemlost   tinyint(1) NOT NULL default 0,
865                 MODIFY wthdrawn   tinyint(1) NOT NULL default 0");
866     $dbh->do("UPDATE deleteditems SET notforloan = 0 WHERE notforloan IS NULL");
867     $dbh->do("UPDATE deleteditems SET damaged = 0 WHERE damaged IS NULL");
868     $dbh->do("UPDATE deleteditems SET itemlost = 0 WHERE itemlost IS NULL");
869     $dbh->do("UPDATE deleteditems SET wthdrawn = 0 WHERE wthdrawn IS NULL");
870     $dbh->do("ALTER TABLE deleteditems
871                 MODIFY notforloan tinyint(1) NOT NULL default 0,
872                 MODIFY damaged    tinyint(1) NOT NULL default 0,
873                 MODIFY itemlost   tinyint(1) NOT NULL default 0,
874                 MODIFY wthdrawn   tinyint(1) NOT NULL default 0");
875         print "Upgrade to $DBversion done (disallow NULL in several item status columns)\n";
876     SetVersion ($DBversion);
877 }
878
879 $DBversion = "3.00.00.04";
880 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
881     $dbh->do("ALTER TABLE aqbooksellers CHANGE name name mediumtext NOT NULL");
882         print "Upgrade to $DBversion done (disallow NULL in aqbooksellers.name; part of fix for bug 1251)\n";
883     SetVersion ($DBversion);
884 }
885
886 $DBversion = "3.00.00.043";
887 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
888     $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");
889         print "Upgrade to $DBversion done (currency table: add symbol and timestamp columns)\n";
890     SetVersion ($DBversion);
891 }
892
893 $DBversion = "3.00.00.044";
894 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
895     $dbh->do("ALTER TABLE deletedborrowers
896   ADD `altcontactfirstname` varchar(255) default NULL,
897   ADD `altcontactsurname` varchar(255) default NULL,
898   ADD `altcontactaddress1` varchar(255) default NULL,
899   ADD `altcontactaddress2` varchar(255) default NULL,
900   ADD `altcontactaddress3` varchar(255) default NULL,
901   ADD `altcontactzipcode` varchar(50) default NULL,
902   ADD `altcontactphone` varchar(50) default NULL
903   ");
904   $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES
905 ('OPACBaseURL',NULL,'Specify the Base URL of the OPAC, e.g., opac.mylibrary.com, the http:// will be added automatically by Koha.',NULL,'Free'),
906 ('language','en','Set the default language in the staff client.',NULL,'Languages'),
907 ('QueryAutoTruncate',1,'If ON, query truncation is enabled by default',NULL,'YesNo'),
908 ('QueryRemoveStopwords',0,'If ON, stopwords listed in the Administration area will be removed from queries',NULL,'YesNo')
909   ");
910         print "Upgrade to $DBversion done (syncing deletedborrowers table with borrowers table)\n";
911     SetVersion ($DBversion);
912 }
913
914 #-- http://www.w3.org/International/articles/language-tags/
915
916 #-- RFC4646
917 $DBversion = "3.00.00.045";
918 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
919     $dbh->do("
920 CREATE TABLE language_subtag_registry (
921         subtag varchar(25),
922         type varchar(25), -- language-script-region-variant-extension-privateuse
923         description varchar(25), -- only one of the possible descriptions for ease of reference, see language_descriptions for the complete list
924         added date,
925         KEY `subtag` (`subtag`)
926 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
927
928 #-- TODO: add suppress_scripts
929 #-- this maps three letter codes defined in iso639.2 back to their
930 #-- two letter equivilents in rfc4646 (LOC maintains iso639+)
931  $dbh->do("CREATE TABLE language_rfc4646_to_iso639 (
932         rfc4646_subtag varchar(25),
933         iso639_2_code varchar(25),
934         KEY `rfc4646_subtag` (`rfc4646_subtag`)
935 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
936
937  $dbh->do("CREATE TABLE language_descriptions (
938         subtag varchar(25),
939         type varchar(25),
940         lang varchar(25),
941         description varchar(255),
942         KEY `lang` (`lang`)
943 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
944
945 #-- bi-directional support, keyed by script subcode
946  $dbh->do("CREATE TABLE language_script_bidi (
947         rfc4646_subtag varchar(25), -- script subtag, Arab, Hebr, etc.
948         bidi varchar(3), -- rtl ltr
949         KEY `rfc4646_subtag` (`rfc4646_subtag`)
950 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
951
952 #-- BIDI Stuff, Arabic and Hebrew
953  $dbh->do("INSERT INTO language_script_bidi(rfc4646_subtag,bidi)
954 VALUES( 'Arab', 'rtl')");
955  $dbh->do("INSERT INTO language_script_bidi(rfc4646_subtag,bidi)
956 VALUES( 'Hebr', 'rtl')");
957
958 #-- TODO: need to map language subtags to script subtags for detection
959 #-- of bidi when script is not specified (like ar, he)
960  $dbh->do("CREATE TABLE language_script_mapping (
961         language_subtag varchar(25),
962         script_subtag varchar(25),
963         KEY `language_subtag` (`language_subtag`)
964 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
965
966 #-- Default mappings between script and language subcodes
967  $dbh->do("INSERT INTO language_script_mapping(language_subtag,script_subtag)
968 VALUES( 'ar', 'Arab')");
969  $dbh->do("INSERT INTO language_script_mapping(language_subtag,script_subtag)
970 VALUES( 'he', 'Hebr')");
971
972         print "Upgrade to $DBversion done (adding language subtag registry and basic BiDi support NOTE: You should import the subtag registry SQL)\n";
973     SetVersion ($DBversion);
974 }
975
976 $DBversion = "3.00.00.046";
977 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
978     $dbh->do("ALTER TABLE `subscription` CHANGE `numberlength` `numberlength` int(11) default '0' ,
979                  CHANGE `weeklength` `weeklength` int(11) default '0'");
980     $dbh->do("CREATE TABLE `serialitems` (`serialid` int(11) NOT NULL, `itemnumber` int(11) NOT NULL, UNIQUE KEY `serialididx` (`serialid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
981     $dbh->do("INSERT INTO `serialitems` SELECT `serialid`,`itemnumber` from serial where NOT ISNULL(itemnumber) && itemnumber <> '' && itemnumber NOT LIKE '%,%'");
982         print "Upgrade to $DBversion done (Add serialitems table to link serial issues to items. )\n";
983     SetVersion ($DBversion);
984 }
985
986 $DBversion = "3.00.00.047";
987 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
988     $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');");
989         print "Upgrade to $DBversion done ( Added OpacRenewalAllowed syspref )\n";
990     SetVersion ($DBversion);
991 }
992
993 $DBversion = "3.00.00.048";
994 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
995     $dbh->do("ALTER TABLE `items` ADD `more_subfields_xml` longtext default NULL AFTER `itype`");
996         print "Upgrade to $DBversion done (added items.more_subfields_xml)\n";
997     SetVersion ($DBversion);
998 }
999
1000 $DBversion = "3.00.00.049";
1001 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1002         $dbh->do("ALTER TABLE `z3950servers` ADD `encoding` text default NULL AFTER type ");
1003         print "Upgrade to $DBversion done ( Added encoding field to z3950servers table )\n";
1004     SetVersion ($DBversion);
1005 }
1006
1007 $DBversion = "3.00.00.050";
1008 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1009     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacHighlightedWords','0','If Set, query matched terms are highlighted in OPAC',NULL,'YesNo');");
1010         print "Upgrade to $DBversion done ( Added OpacHighlightedWords syspref )\n";
1011     SetVersion ($DBversion);
1012 }
1013
1014 $DBversion = "3.00.00.051";
1015 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1016     $dbh->do("UPDATE systempreferences SET explanation = 'Define the current theme for the OPAC interface.' WHERE variable = 'opacthemes';");
1017         print "Upgrade to $DBversion done ( Corrected opacthemes explanation. )\n";
1018     SetVersion ($DBversion);
1019 }
1020
1021 $DBversion = "3.00.00.052";
1022 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1023     $dbh->do("ALTER TABLE `deleteditems` ADD `more_subfields_xml` LONGTEXT DEFAULT NULL AFTER `itype`");
1024         print "Upgrade to $DBversion done ( Adding missing column to deleteditems table. )\n";
1025     SetVersion ($DBversion);
1026 }
1027
1028 $DBversion = "3.00.00.053";
1029 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1030     $dbh->do("CREATE TABLE `printers_profile` (
1031             `prof_id` int(4) NOT NULL auto_increment,
1032             `printername` varchar(40) NOT NULL,
1033             `tmpl_id` int(4) NOT NULL,
1034             `paper_bin` varchar(20) NOT NULL,
1035             `offset_horz` float default NULL,
1036             `offset_vert` float default NULL,
1037             `creep_horz` float default NULL,
1038             `creep_vert` float default NULL,
1039             `unit` char(20) NOT NULL default 'POINT',
1040             PRIMARY KEY  (`prof_id`),
1041             UNIQUE KEY `printername` (`printername`,`tmpl_id`,`paper_bin`),
1042             CONSTRAINT `printers_profile_pnfk_1` FOREIGN KEY (`tmpl_id`) REFERENCES `labels_templates` (`tmpl_id`) ON DELETE CASCADE ON UPDATE CASCADE
1043             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1044     $dbh->do("CREATE TABLE `labels_profile` (
1045             `tmpl_id` int(4) NOT NULL,
1046             `prof_id` int(4) NOT NULL,
1047             UNIQUE KEY `tmpl_id` (`tmpl_id`),
1048             UNIQUE KEY `prof_id` (`prof_id`)
1049             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1050     print "Upgrade to $DBversion done ( Printer Profile tables added )\n";
1051     SetVersion ($DBversion);
1052 }
1053
1054 $DBversion = "3.00.00.054";
1055 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1056     $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';");
1057         print "Upgrade to $DBversion done ( Added another barcode autogeneration sequence to barcode.pl. )\n";
1058     SetVersion ($DBversion);
1059 }
1060
1061 $DBversion = "3.00.00.055";
1062 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1063     $dbh->do("ALTER TABLE `zebraqueue` ADD KEY `zebraqueue_lookup` (`server`, `biblio_auth_number`, `operation`, `done`)");
1064         print "Upgrade to $DBversion done ( Added index on zebraqueue. )\n";
1065     SetVersion ($DBversion);
1066 }
1067 $DBversion = "3.00.00.056";
1068 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1069     if (C4::Context->preference("marcflavour") eq 'UNIMARC') {
1070         $dbh->do("INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`, `tab`, `authorised_value` , `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`) VALUES ('995', 'v', 'Note sur le N° de périodique','Note sur le N° de périodique', 0, 0, 'items.enumchron', 10, '', '', '', 0, 0, '', '', '', NULL) ");
1071     } else {
1072         $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) ");
1073     }
1074     $dbh->do("ALTER TABLE `items` ADD `enumchron` VARCHAR(80) DEFAULT NULL;");
1075     print "Upgrade to $DBversion done ( Added item.enumchron column, and framework map to 952h )\n";
1076     SetVersion ($DBversion);
1077 }
1078
1079 $DBversion = "3.00.00.057";
1080 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1081     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH','0','if ON, OAI-PMH server is enabled',NULL,'YesNo');");
1082     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH:archiveID','KOHA-OAI-TEST','OAI-PMH archive identification',NULL,'Free');");
1083     $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');");
1084     $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');");
1085     $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');");
1086     SetVersion ($DBversion);
1087 }
1088
1089 $DBversion = "3.00.00.058";
1090 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1091     $dbh->do("ALTER TABLE `opac_news`
1092                 CHANGE `lang` `lang` VARCHAR( 25 )
1093                 CHARACTER SET utf8
1094                 COLLATE utf8_general_ci
1095                 NOT NULL default ''");
1096         print "Upgrade to $DBversion done ( lang field in opac_news made longer )\n";
1097     SetVersion ($DBversion);
1098 }
1099
1100 $DBversion = "3.00.00.059";
1101 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1102
1103     $dbh->do("CREATE TABLE IF NOT EXISTS `labels_templates` (
1104             `tmpl_id` int(4) NOT NULL auto_increment,
1105             `tmpl_code` char(100)  default '',
1106             `tmpl_desc` char(100) default '',
1107             `page_width` float default '0',
1108             `page_height` float default '0',
1109             `label_width` float default '0',
1110             `label_height` float default '0',
1111             `topmargin` float default '0',
1112             `leftmargin` float default '0',
1113             `cols` int(2) default '0',
1114             `rows` int(2) default '0',
1115             `colgap` float default '0',
1116             `rowgap` float default '0',
1117             `active` int(1) default NULL,
1118             `units` char(20)  default 'PX',
1119             `fontsize` int(4) NOT NULL default '3',
1120             PRIMARY KEY  (`tmpl_id`)
1121             ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1122     $dbh->do("CREATE TABLE  IF NOT EXISTS `printers_profile` (
1123             `prof_id` int(4) NOT NULL auto_increment,
1124             `printername` varchar(40) NOT NULL,
1125             `tmpl_id` int(4) NOT NULL,
1126             `paper_bin` varchar(20) NOT NULL,
1127             `offset_horz` float default NULL,
1128             `offset_vert` float default NULL,
1129             `creep_horz` float default NULL,
1130             `creep_vert` float default NULL,
1131             `unit` char(20) NOT NULL default 'POINT',
1132             PRIMARY KEY  (`prof_id`),
1133             UNIQUE KEY `printername` (`printername`,`tmpl_id`,`paper_bin`),
1134             CONSTRAINT `printers_profile_pnfk_1` FOREIGN KEY (`tmpl_id`) REFERENCES `labels_templates` (`tmpl_id`) ON DELETE CASCADE ON UPDATE CASCADE
1135             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1136     print "Upgrade to $DBversion done ( Added labels_templates table if it did not exist. )\n";
1137     SetVersion ($DBversion);
1138 }
1139
1140 $DBversion = "3.00.00.060";
1141 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1142     $dbh->do("CREATE TABLE IF NOT EXISTS `patronimage` (
1143             `cardnumber` varchar(16) NOT NULL,
1144             `mimetype` varchar(15) NOT NULL,
1145             `imagefile` mediumblob NOT NULL,
1146             PRIMARY KEY  (`cardnumber`),
1147             CONSTRAINT `patronimage_fk1` FOREIGN KEY (`cardnumber`) REFERENCES `borrowers` (`cardnumber`) ON DELETE CASCADE ON UPDATE CASCADE
1148             ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1149         print "Upgrade to $DBversion done ( Added patronimage table. )\n";
1150     SetVersion ($DBversion);
1151 }
1152
1153 $DBversion = "3.00.00.061";
1154 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1155     $dbh->do("ALTER TABLE labels_templates ADD COLUMN font char(10) NOT NULL DEFAULT 'TR';");
1156         print "Upgrade to $DBversion done ( Added font column to labels_templates )\n";
1157     SetVersion ($DBversion);
1158 }
1159
1160 $DBversion = "3.00.00.062";
1161 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1162     $dbh->do("CREATE TABLE `old_issues` (
1163                 `borrowernumber` int(11) default NULL,
1164                 `itemnumber` int(11) default NULL,
1165                 `date_due` date default NULL,
1166                 `branchcode` varchar(10) default NULL,
1167                 `issuingbranch` varchar(18) default NULL,
1168                 `returndate` date default NULL,
1169                 `lastreneweddate` date default NULL,
1170                 `return` varchar(4) default NULL,
1171                 `renewals` tinyint(4) default NULL,
1172                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1173                 `issuedate` date default NULL,
1174                 KEY `old_issuesborridx` (`borrowernumber`),
1175                 KEY `old_issuesitemidx` (`itemnumber`),
1176                 KEY `old_bordate` (`borrowernumber`,`timestamp`),
1177                 CONSTRAINT `old_issues_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1178                     ON DELETE SET NULL ON UPDATE SET NULL,
1179                 CONSTRAINT `old_issues_ibfk_2` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`)
1180                     ON DELETE SET NULL ON UPDATE SET NULL
1181                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1182     $dbh->do("CREATE TABLE `old_reserves` (
1183                 `borrowernumber` int(11) default NULL,
1184                 `reservedate` date default NULL,
1185                 `biblionumber` int(11) default NULL,
1186                 `constrainttype` varchar(1) default NULL,
1187                 `branchcode` varchar(10) default NULL,
1188                 `notificationdate` date default NULL,
1189                 `reminderdate` date default NULL,
1190                 `cancellationdate` date default NULL,
1191                 `reservenotes` mediumtext,
1192                 `priority` smallint(6) default NULL,
1193                 `found` varchar(1) default NULL,
1194                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1195                 `itemnumber` int(11) default NULL,
1196                 `waitingdate` date default NULL,
1197                 KEY `old_reserves_borrowernumber` (`borrowernumber`),
1198                 KEY `old_reserves_biblionumber` (`biblionumber`),
1199                 KEY `old_reserves_itemnumber` (`itemnumber`),
1200                 KEY `old_reserves_branchcode` (`branchcode`),
1201                 CONSTRAINT `old_reserves_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1202                     ON DELETE SET NULL ON UPDATE SET NULL,
1203                 CONSTRAINT `old_reserves_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`)
1204                     ON DELETE SET NULL ON UPDATE SET NULL,
1205                 CONSTRAINT `old_reserves_ibfk_3` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`)
1206                     ON DELETE SET NULL ON UPDATE SET NULL
1207                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1208
1209     # move closed transactions to old_* tables
1210     $dbh->do("INSERT INTO old_issues SELECT * FROM issues WHERE returndate IS NOT NULL");
1211     $dbh->do("DELETE FROM issues WHERE returndate IS NOT NULL");
1212     $dbh->do("INSERT INTO old_reserves SELECT * FROM reserves WHERE cancellationdate IS NOT NULL OR found = 'F'");
1213     $dbh->do("DELETE FROM reserves WHERE cancellationdate IS NOT NULL OR found = 'F'");
1214
1215         print "Upgrade to $DBversion done ( Added old_issues and old_reserves tables )\n";
1216     SetVersion ($DBversion);
1217 }
1218
1219 $DBversion = "3.00.00.063";
1220 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1221     $dbh->do("ALTER TABLE deleteditems
1222                 CHANGE COLUMN booksellerid booksellerid MEDIUMTEXT DEFAULT NULL,
1223                 ADD COLUMN enumchron VARCHAR(80) DEFAULT NULL AFTER more_subfields_xml,
1224                 ADD COLUMN copynumber SMALLINT(6) DEFAULT NULL AFTER enumchron;");
1225     $dbh->do("ALTER TABLE items
1226                 CHANGE COLUMN booksellerid booksellerid MEDIUMTEXT,
1227                 ADD COLUMN copynumber SMALLINT(6) DEFAULT NULL AFTER enumchron;");
1228         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";
1229     SetVersion ($DBversion);
1230 }
1231
1232 $DBversion = "3.00.00.064";
1233 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1234     $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');");
1235     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AWSAccessKeyID','','See:  http://aws.amazon.com','','free');");
1236     $dbh->do("DELETE FROM `systempreferences` WHERE variable='AmazonDevKey';");
1237     $dbh->do("DELETE FROM `systempreferences` WHERE variable='XISBNAmazonSimilarItems';");
1238     $dbh->do("DELETE FROM `systempreferences` WHERE variable='OPACXISBNAmazonSimilarItems';");
1239     print "Upgrade to $DBversion done (IMPORTANT: Upgrading to Amazon.com Associates Web Service 4.0 ) \n";
1240     SetVersion ($DBversion);
1241 }
1242
1243 $DBversion = "3.00.00.065";
1244 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1245     $dbh->do("CREATE TABLE `patroncards` (
1246                 `cardid` int(11) NOT NULL auto_increment,
1247                 `batch_id` varchar(10) NOT NULL default '1',
1248                 `borrowernumber` int(11) NOT NULL,
1249                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1250                 PRIMARY KEY  (`cardid`),
1251                 KEY `patroncards_ibfk_1` (`borrowernumber`),
1252                 CONSTRAINT `patroncards_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE
1253                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1254     print "Upgrade to $DBversion done (Adding patroncards table for patroncards generation feature. ) \n";
1255     SetVersion ($DBversion);
1256 }
1257
1258 $DBversion = "3.00.00.066";
1259 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1260     $dbh->do("ALTER TABLE `virtualshelfcontents` MODIFY `dateadded` timestamp NOT NULL
1261 DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP;
1262 ");
1263     print "Upgrade to $DBversion done (fix for bug 1873: virtualshelfcontents dateadded column empty. ) \n";
1264     SetVersion ($DBversion);
1265 }
1266
1267 $DBversion = "3.00.00.067";
1268 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1269     $dbh->do("UPDATE systempreferences SET explanation = 'Enable patron images for the Staff Client', type = 'YesNo' WHERE variable = 'patronimages'");
1270     print "Upgrade to $DBversion done (Updating patronimages syspref to reflect current kohastructure.sql. ) \n";
1271     SetVersion ($DBversion);
1272 }
1273
1274 $DBversion = "3.00.00.068";
1275 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1276     $dbh->do("CREATE TABLE `permissions` (
1277                 `module_bit` int(11) NOT NULL DEFAULT 0,
1278                 `code` varchar(30) DEFAULT NULL,
1279                 `description` varchar(255) DEFAULT NULL,
1280                 PRIMARY KEY  (`module_bit`, `code`),
1281                 CONSTRAINT `permissions_ibfk_1` FOREIGN KEY (`module_bit`) REFERENCES `userflags` (`bit`)
1282                     ON DELETE CASCADE ON UPDATE CASCADE
1283               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1284     $dbh->do("CREATE TABLE `user_permissions` (
1285                 `borrowernumber` int(11) NOT NULL DEFAULT 0,
1286                 `module_bit` int(11) NOT NULL DEFAULT 0,
1287                 `code` varchar(30) DEFAULT NULL,
1288                 CONSTRAINT `user_permissions_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1289                     ON DELETE CASCADE ON UPDATE CASCADE,
1290                 CONSTRAINT `user_permissions_ibfk_2` FOREIGN KEY (`module_bit`, `code`)
1291                     REFERENCES `permissions` (`module_bit`, `code`)
1292                     ON DELETE CASCADE ON UPDATE CASCADE
1293               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1294
1295     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
1296     (13, 'edit_news', 'Write news for the OPAC and staff interfaces'),
1297     (13, 'label_creator', 'Create printable labels and barcodes from catalog and patron data'),
1298     (13, 'edit_calendar', 'Define days when the library is closed'),
1299     (13, 'moderate_comments', 'Moderate patron comments'),
1300     (13, 'edit_notices', 'Define notices'),
1301     (13, 'edit_notice_status_triggers', 'Set notice/status triggers for overdue items'),
1302     (13, 'view_system_logs', 'Browse the system logs'),
1303     (13, 'inventory', 'Perform inventory (stocktaking) of your catalogue'),
1304     (13, 'stage_marc_import', 'Stage MARC records into the reservoir'),
1305     (13, 'manage_staged_marc', 'Managed staged MARC records, including completing and reversing imports'),
1306     (13, 'export_catalog', 'Export bibliographic and holdings data'),
1307     (13, 'import_patrons', 'Import patron data'),
1308     (13, 'delete_anonymize_patrons', 'Delete old borrowers and anonymize circulation history (deletes borrower reading history)'),
1309     (13, 'batch_upload_patron_images', 'Upload patron images in batch or one at a time'),
1310     (13, 'schedule_tasks', 'Schedule tasks to run')");
1311
1312     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('GranularPermissions','0','Use detailed staff user permissions',NULL,'YesNo')");
1313
1314     print "Upgrade to $DBversion done (adding permissions and user_permissions tables and GranularPermissions syspref) \n";
1315     SetVersion ($DBversion);
1316 }
1317 $DBversion = "3.00.00.069";
1318 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1319     $dbh->do("ALTER TABLE labels_conf CHANGE COLUMN class classification int(1) DEFAULT NULL;");
1320         print "Upgrade to $DBversion done ( Correcting columname in labels_conf )\n";
1321     SetVersion ($DBversion);
1322 }
1323
1324 $DBversion = "3.00.00.070";
1325 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1326     $sth = $dbh->prepare("SELECT value FROM systempreferences WHERE variable='yuipath'");
1327     $sth->execute;
1328     my ($value) = $sth->fetchrow;
1329     $value =~ s/2.3.1/2.5.1/;
1330     $dbh->do("UPDATE systempreferences SET value='$value' WHERE variable='yuipath';");
1331         print "Update yuipath syspref to 2.5.1 if necessary\n";
1332     SetVersion ($DBversion);
1333 }
1334
1335 $DBversion = "3.00.00.071";
1336 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1337     $dbh->do(" ALTER TABLE `subscription` ADD `serialsadditems` TINYINT( 1 ) NOT NULL DEFAULT '0';");
1338     # fill the new field with the previous systempreference value, then drop the syspref
1339     my $sth = $dbh->prepare("SELECT value FROM systempreferences WHERE variable='serialsadditems'");
1340     $sth->execute;
1341     my ($serialsadditems) = $sth->fetchrow();
1342     $dbh->do("UPDATE subscription SET serialsadditems=$serialsadditems");
1343     $dbh->do("DELETE FROM systempreferences WHERE variable='serialsadditems'");
1344     print "Upgrade to $DBversion done ( moving serialsadditems from syspref to subscription )\n";
1345     SetVersion ($DBversion);
1346 }
1347
1348 $DBversion = "3.00.00.072";
1349 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1350     $dbh->do("ALTER TABLE labels_conf ADD COLUMN formatstring mediumtext DEFAULT NULL AFTER printingtype");
1351         print "Upgrade to $DBversion done ( Adding format string to labels generator. )\n";
1352     SetVersion ($DBversion);
1353 }
1354
1355 $DBversion = "3.00.00.073";
1356 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1357         $dbh->do("DROP TABLE IF EXISTS `tags_all`;");
1358         $dbh->do(q#
1359         CREATE TABLE `tags_all` (
1360           `tag_id`         int(11) NOT NULL auto_increment,
1361           `borrowernumber` int(11) NOT NULL,
1362           `biblionumber`   int(11) NOT NULL,
1363           `term`      varchar(255) NOT NULL,
1364           `language`       int(4) default NULL,
1365           `date_created` datetime  NOT NULL,
1366           PRIMARY KEY  (`tag_id`),
1367           KEY `tags_borrowers_fk_1` (`borrowernumber`),
1368           KEY `tags_biblionumber_fk_1` (`biblionumber`),
1369           CONSTRAINT `tags_borrowers_fk_1` FOREIGN KEY (`borrowernumber`)
1370                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1371           CONSTRAINT `tags_biblionumber_fk_1` FOREIGN KEY (`biblionumber`)
1372                 REFERENCES `biblio`     (`biblionumber`)  ON DELETE CASCADE ON UPDATE CASCADE
1373         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1374         #);
1375         $dbh->do("DROP TABLE IF EXISTS `tags_approval`;");
1376         $dbh->do(q#
1377         CREATE TABLE `tags_approval` (
1378           `term`   varchar(255) NOT NULL,
1379           `approved`     int(1) NOT NULL default '0',
1380           `date_approved` datetime       default NULL,
1381           `approved_by` int(11)          default NULL,
1382           `weight_total` int(9) NOT NULL default '1',
1383           PRIMARY KEY  (`term`),
1384           KEY `tags_approval_borrowers_fk_1` (`approved_by`),
1385           CONSTRAINT `tags_approval_borrowers_fk_1` FOREIGN KEY (`approved_by`)
1386                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE
1387         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1388         #);
1389         $dbh->do("DROP TABLE IF EXISTS `tags_index`;");
1390         $dbh->do(q#
1391         CREATE TABLE `tags_index` (
1392           `term`    varchar(255) NOT NULL,
1393           `biblionumber` int(11) NOT NULL,
1394           `weight`        int(9) NOT NULL default '1',
1395           PRIMARY KEY  (`term`,`biblionumber`),
1396           KEY `tags_index_biblionumber_fk_1` (`biblionumber`),
1397           CONSTRAINT `tags_index_term_fk_1` FOREIGN KEY (`term`)
1398                 REFERENCES `tags_approval` (`term`)  ON DELETE CASCADE ON UPDATE CASCADE,
1399           CONSTRAINT `tags_index_biblionumber_fk_1` FOREIGN KEY (`biblionumber`)
1400                 REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
1401         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1402         #);
1403         $dbh->do(q#
1404         INSERT INTO `systempreferences` VALUES
1405                 ('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=',''),
1406                 ('BakerTaylorEnabled','0','','Enable or disable all Baker & Taylor features.','YesNo'),
1407                 ('BakerTaylorPassword','','','Baker & Taylor Password for Content Cafe (external content)','Textarea'),
1408                 ('BakerTaylorUsername','','','Baker & Taylor Username for Content Cafe (external content)','Textarea'),
1409                 ('TagsEnabled','1','','Enables or disables all tagging features.  This is the main switch for tags.','YesNo'),
1410                 ('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.',''),
1411                 ('TagsInputOnDetail','1','','Allow users to input tags from the detail page.',         'YesNo'),
1412                 ('TagsInputOnList',  '0','','Allow users to input tags from the search results list.', 'YesNo'),
1413                 ('TagsModeration',  NULL,'','Require tags from patrons to be approved before becoming visible.','YesNo'),
1414                 ('TagsShowOnDetail','10','','Number of tags to display on detail page.  0 is off.',        'Integer'),
1415                 ('TagsShowOnList',   '6','','Number of tags to display on search results list.  0 is off.','Integer')
1416         #);
1417         print "Upgrade to $DBversion done (Baker/Taylor,Tags: sysprefs and tables (tags_all, tags_index, tags_approval)) \n";
1418         SetVersion ($DBversion);
1419 }
1420
1421 $DBversion = "3.00.00.074";
1422 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1423     $dbh->do( q(update itemtypes set imageurl = concat( 'npl/', imageurl )
1424                   where imageurl not like 'http%'
1425                     and imageurl is not NULL
1426                     and imageurl != '') );
1427     print "Upgrade to $DBversion done (updating imagetype.imageurls to reflect new icon locations.)\n";
1428     SetVersion ($DBversion);
1429 }
1430
1431 $DBversion = "3.00.00.075";
1432 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1433     $dbh->do( q(alter table authorised_values add imageurl varchar(200) default NULL) );
1434     print "Upgrade to $DBversion done (adding imageurl field to authorised_values table)\n";
1435     SetVersion ($DBversion);
1436 }
1437
1438 $DBversion = "3.00.00.076";
1439 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1440     $dbh->do("ALTER TABLE import_batches
1441               ADD COLUMN nomatch_action enum('create_new', 'ignore') NOT NULL default 'create_new' AFTER overlay_action");
1442     $dbh->do("ALTER TABLE import_batches
1443               ADD COLUMN item_action enum('always_add', 'add_only_for_matches', 'add_only_for_new', 'ignore')
1444                   NOT NULL default 'always_add' AFTER nomatch_action");
1445     $dbh->do("ALTER TABLE import_batches
1446               MODIFY overlay_action  enum('replace', 'create_new', 'use_template', 'ignore')
1447                   NOT NULL default 'create_new'");
1448     $dbh->do("ALTER TABLE import_records
1449               MODIFY status  enum('error', 'staged', 'imported', 'reverted', 'items_reverted',
1450                                   'ignored') NOT NULL default 'staged'");
1451     $dbh->do("ALTER TABLE import_items
1452               MODIFY status enum('error', 'staged', 'imported', 'reverted', 'ignored') NOT NULL default 'staged'");
1453
1454         print "Upgrade to $DBversion done (changes to import_batches and import_records)\n";
1455         SetVersion ($DBversion);
1456 }
1457
1458 $DBversion = "3.00.00.077";
1459 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1460     # drop these tables only if they exist and none of them are empty
1461     # these tables are not defined in the packaged 2.2.9, but since it is believed
1462     # that at least one library may be using them in a post-2.2.9 but pre-3.0 Koha,
1463     # some care is taken.
1464     my ($print_error) = $dbh->{PrintError};
1465     $dbh->{PrintError} = 0;
1466     my ($raise_error) = $dbh->{RaiseError};
1467     $dbh->{RaiseError} = 1;
1468
1469     my $count = 0;
1470     my $do_drop = 1;
1471     eval { $count = $dbh->do("SELECT 1 FROM categorytable"); };
1472     if ($count > 0) {
1473         $do_drop = 0;
1474     }
1475     eval { $count = $dbh->do("SELECT 1 FROM mediatypetable"); };
1476     if ($count > 0) {
1477         $do_drop = 0;
1478     }
1479     eval { $count = $dbh->do("SELECT 1 FROM subcategorytable"); };
1480     if ($count > 0) {
1481         $do_drop = 0;
1482     }
1483
1484     if ($do_drop) {
1485         $dbh->do("DROP TABLE IF EXISTS `categorytable`");
1486         $dbh->do("DROP TABLE IF EXISTS `mediatypetable`");
1487         $dbh->do("DROP TABLE IF EXISTS `subcategorytable`");
1488     }
1489
1490     $dbh->{PrintError} = $print_error;
1491     $dbh->{RaiseError} = $raise_error;
1492         print "Upgrade to $DBversion done (drop categorytable, subcategorytable, and mediatypetable)\n";
1493         SetVersion ($DBversion);
1494 }
1495
1496 $DBversion = "3.00.00.078";
1497 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1498     my ($print_error) = $dbh->{PrintError};
1499     $dbh->{PrintError} = 0;
1500
1501     unless ($dbh->do("SELECT 1 FROM browser")) {
1502         $dbh->{PrintError} = $print_error;
1503         $dbh->do("CREATE TABLE `browser` (
1504                     `level` int(11) NOT NULL,
1505                     `classification` varchar(20) NOT NULL,
1506                     `description` varchar(255) NOT NULL,
1507                     `number` bigint(20) NOT NULL,
1508                     `endnode` tinyint(4) NOT NULL
1509                   ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1510     }
1511     $dbh->{PrintError} = $print_error;
1512         print "Upgrade to $DBversion done (add browser table if not already present)\n";
1513         SetVersion ($DBversion);
1514 }
1515
1516 $DBversion = "3.00.00.079";
1517 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1518  my ($print_error) = $dbh->{PrintError};
1519     $dbh->{PrintError} = 0;
1520
1521     $dbh->do("INSERT INTO `systempreferences` (variable, value,options,type, explanation)VALUES
1522         ('AddPatronLists','categorycode','categorycode|category_type','Choice','Allow user to choose what list to pick up from when adding patrons')");
1523     print "Upgrade to $DBversion done (add browser table if not already present)\n";
1524         SetVersion ($DBversion);
1525 }
1526
1527 $DBversion = "3.00.00.080";
1528 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1529     $dbh->do("ALTER TABLE subscription CHANGE monthlength monthlength int(11) default '0'");
1530     $dbh->do("ALTER TABLE deleteditems MODIFY marc LONGBLOB AFTER copynumber");
1531     $dbh->do("ALTER TABLE aqbooksellers CHANGE name name mediumtext NOT NULL");
1532         print "Upgrade to $DBversion done (catch up on DB schema changes since alpha and beta)\n";
1533         SetVersion ($DBversion);
1534 }
1535
1536 $DBversion = "3.00.00.081";
1537 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1538     $dbh->do("CREATE TABLE `borrower_attribute_types` (
1539                 `code` varchar(10) NOT NULL,
1540                 `description` varchar(255) NOT NULL,
1541                 `repeatable` tinyint(1) NOT NULL default 0,
1542                 `unique_id` tinyint(1) NOT NULL default 0,
1543                 `opac_display` tinyint(1) NOT NULL default 0,
1544                 `password_allowed` tinyint(1) NOT NULL default 0,
1545                 `staff_searchable` tinyint(1) NOT NULL default 0,
1546                 `authorised_value_category` varchar(10) default NULL,
1547                 PRIMARY KEY  (`code`)
1548               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1549     $dbh->do("CREATE TABLE `borrower_attributes` (
1550                 `borrowernumber` int(11) NOT NULL,
1551                 `code` varchar(10) NOT NULL,
1552                 `attribute` varchar(30) default NULL,
1553                 `password` varchar(30) default NULL,
1554                 KEY `borrowernumber` (`borrowernumber`),
1555                 KEY `code_attribute` (`code`, `attribute`),
1556                 CONSTRAINT `borrower_attributes_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1557                     ON DELETE CASCADE ON UPDATE CASCADE,
1558                 CONSTRAINT `borrower_attributes_ibfk_2` FOREIGN KEY (`code`) REFERENCES `borrower_attribute_types` (`code`)
1559                     ON DELETE CASCADE ON UPDATE CASCADE
1560             ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1561     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('ExtendedPatronAttributes','0','Use extended patron IDs and attributes',NULL,'YesNo')");
1562     print "Upgrade to $DBversion done (added borrower_attributes and  borrower_attribute_types)\n";
1563  SetVersion ($DBversion);
1564 }
1565
1566 $DBversion = "3.00.00.082";
1567 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1568     $dbh->do( q(alter table accountlines add column lastincrement decimal(28,6) default NULL) );
1569     print "Upgrade to $DBversion done (adding lastincrement column to accountlines table)\n";
1570     SetVersion ($DBversion);
1571 }
1572
1573 $DBversion = "3.00.00.083";
1574 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1575     $dbh->do( qq(UPDATE systempreferences SET value='local' where variable='yuipath' and value like "%/intranet-tmpl/prog/%"));
1576     print "Upgrade to $DBversion done (Changing yuipath behaviour in managing a local value)\n";
1577     SetVersion ($DBversion);
1578 }
1579 $DBversion = "3.00.00.084";
1580     if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1581     $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')");
1582     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('GoogleJackets','0','if ON, displays jacket covers from Google Books API',NULL,'YesNo')");
1583     print "Upgrade to $DBversion done (add new sysprefs)\n";
1584     SetVersion ($DBversion);
1585 }
1586
1587 $DBversion = "3.00.00.085";
1588 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1589     if (C4::Context->preference("marcflavour") eq 'MARC21') {
1590         $dbh->do("UPDATE marc_subfield_structure SET tab = 0 WHERE tab =  9 AND tagfield = '037'");
1591         $dbh->do("UPDATE marc_subfield_structure SET tab = 1 WHERE tab =  6 AND tagfield in ('100', '110', '111', '130')");
1592         $dbh->do("UPDATE marc_subfield_structure SET tab = 2 WHERE tab =  6 AND tagfield in ('240', '243')");
1593         $dbh->do("UPDATE marc_subfield_structure SET tab = 4 WHERE tab =  6 AND tagfield in ('400', '410', '411', '440')");
1594         $dbh->do("UPDATE marc_subfield_structure SET tab = 5 WHERE tab =  9 AND tagfield = '584'");
1595         $dbh->do("UPDATE marc_subfield_structure SET tab = 7 WHERE tab = -6 AND tagfield = '760'");
1596     }
1597     print "Upgrade to $DBversion done (move editing tab of various MARC21 subfields)\n";
1598     SetVersion ($DBversion);
1599 }
1600
1601 $DBversion = "3.00.00.086";
1602 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1603         $dbh->do(
1604         "CREATE TABLE `tmp_holdsqueue` (
1605         `biblionumber` int(11) default NULL,
1606         `itemnumber` int(11) default NULL,
1607         `barcode` varchar(20) default NULL,
1608         `surname` mediumtext NOT NULL,
1609         `firstname` text,
1610         `phone` text,
1611         `borrowernumber` int(11) NOT NULL,
1612         `cardnumber` varchar(16) default NULL,
1613         `reservedate` date default NULL,
1614         `title` mediumtext,
1615         `itemcallnumber` varchar(30) default NULL,
1616         `holdingbranch` varchar(10) default NULL,
1617         `pickbranch` varchar(10) default NULL,
1618         `notes` text
1619         ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1620
1621         $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')");
1622         $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')");
1623
1624         print "Upgrade to $DBversion done (Table structure for table `tmp_holdsqueue`)\n";
1625         SetVersion ($DBversion);
1626 }
1627
1628 $DBversion = "3.00.00.087";
1629 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1630     $dbh->do("INSERT INTO `systempreferences` VALUES ('AutoEmailOpacUser','0','','Sends notification emails containing new account details to patrons - when account is created.','YesNo')" );
1631     $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')");
1632     print "Upgrade to $DBversion done (added 2 new 'AutoEmailOpacUser' sysprefs)\n";
1633     SetVersion ($DBversion);
1634 }
1635
1636 $DBversion = "3.00.00.088";
1637 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1638         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('OPACShelfBrowser','1','','Enable/disable Shelf Browser on item details page','YesNo')");
1639         $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')");
1640         $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')");
1641         $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')");
1642         print "Upgrade to $DBversion done (added 2 new 'AutoEmailOpacUser' sysprefs)\n";
1643     SetVersion ($DBversion);
1644 }
1645
1646 $DBversion = "3.00.00.089";
1647 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1648         $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')");
1649         print "Upgrade to $DBversion done (added new AdvancedSearchTypes syspref)\n";
1650     SetVersion ($DBversion);
1651 }
1652
1653 $DBversion = "3.00.00.090";
1654 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1655     $dbh->do("
1656         CREATE TABLE `branch_borrower_circ_rules` (
1657           `branchcode` VARCHAR(10) NOT NULL,
1658           `categorycode` VARCHAR(10) NOT NULL,
1659           `maxissueqty` int(4) default NULL,
1660           PRIMARY KEY (`categorycode`, `branchcode`),
1661           CONSTRAINT `branch_borrower_circ_rules_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
1662             ON DELETE CASCADE ON UPDATE CASCADE,
1663           CONSTRAINT `branch_borrower_circ_rules_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`)
1664             ON DELETE CASCADE ON UPDATE CASCADE
1665         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1666     ");
1667     $dbh->do("
1668         CREATE TABLE `default_borrower_circ_rules` (
1669           `categorycode` VARCHAR(10) NOT NULL,
1670           `maxissueqty` int(4) default NULL,
1671           PRIMARY KEY (`categorycode`),
1672           CONSTRAINT `borrower_borrower_circ_rules_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
1673             ON DELETE CASCADE ON UPDATE CASCADE
1674         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1675     ");
1676     $dbh->do("
1677         CREATE TABLE `default_branch_circ_rules` (
1678           `branchcode` VARCHAR(10) NOT NULL,
1679           `maxissueqty` int(4) default NULL,
1680           PRIMARY KEY (`branchcode`),
1681           CONSTRAINT `default_branch_circ_rules_ibfk_1` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`)
1682             ON DELETE CASCADE ON UPDATE CASCADE
1683         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1684     ");
1685     $dbh->do("
1686         CREATE TABLE `default_circ_rules` (
1687             `singleton` enum('singleton') NOT NULL default 'singleton',
1688             `maxissueqty` int(4) default NULL,
1689             PRIMARY KEY (`singleton`)
1690         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1691     ");
1692     print "Upgrade to $DBversion done (added several circ rules tables)\n";
1693     SetVersion ($DBversion);
1694 }
1695
1696
1697 $DBversion = "3.00.00.091";
1698 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1699     $dbh->do(<<'END_SQL');
1700 ALTER TABLE borrowers
1701 ADD `smsalertnumber` varchar(50) default NULL
1702 END_SQL
1703
1704     $dbh->do(<<'END_SQL');
1705 CREATE TABLE `message_attributes` (
1706   `message_attribute_id` int(11) NOT NULL auto_increment,
1707   `message_name` varchar(20) NOT NULL default '',
1708   `takes_days` tinyint(1) NOT NULL default '0',
1709   PRIMARY KEY  (`message_attribute_id`),
1710   UNIQUE KEY `message_name` (`message_name`)
1711 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1712 END_SQL
1713
1714     $dbh->do(<<'END_SQL');
1715 CREATE TABLE `message_transport_types` (
1716   `message_transport_type` varchar(20) NOT NULL,
1717   PRIMARY KEY  (`message_transport_type`)
1718 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1719 END_SQL
1720
1721     $dbh->do(<<'END_SQL');
1722 CREATE TABLE `message_transports` (
1723   `message_attribute_id` int(11) NOT NULL,
1724   `message_transport_type` varchar(20) NOT NULL,
1725   `is_digest` tinyint(1) NOT NULL default '0',
1726   `letter_module` varchar(20) NOT NULL default '',
1727   `letter_code` varchar(20) NOT NULL default '',
1728   PRIMARY KEY  (`message_attribute_id`,`message_transport_type`,`is_digest`),
1729   KEY `message_transport_type` (`message_transport_type`),
1730   KEY `letter_module` (`letter_module`,`letter_code`),
1731   CONSTRAINT `message_transports_ibfk_1` FOREIGN KEY (`message_attribute_id`) REFERENCES `message_attributes` (`message_attribute_id`) ON DELETE CASCADE ON UPDATE CASCADE,
1732   CONSTRAINT `message_transports_ibfk_2` FOREIGN KEY (`message_transport_type`) REFERENCES `message_transport_types` (`message_transport_type`) ON DELETE CASCADE ON UPDATE CASCADE,
1733   CONSTRAINT `message_transports_ibfk_3` FOREIGN KEY (`letter_module`, `letter_code`) REFERENCES `letter` (`module`, `code`) ON DELETE CASCADE ON UPDATE CASCADE
1734 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1735 END_SQL
1736
1737     $dbh->do(<<'END_SQL');
1738 CREATE TABLE `borrower_message_preferences` (
1739   `borrower_message_preference_id` int(11) NOT NULL auto_increment,
1740   `borrowernumber` int(11) NOT NULL default '0',
1741   `message_attribute_id` int(11) default '0',
1742   `days_in_advance` int(11) default '0',
1743   `wants_digets` tinyint(1) NOT NULL default '0',
1744   PRIMARY KEY  (`borrower_message_preference_id`),
1745   KEY `borrowernumber` (`borrowernumber`),
1746   KEY `message_attribute_id` (`message_attribute_id`),
1747   CONSTRAINT `borrower_message_preferences_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1748   CONSTRAINT `borrower_message_preferences_ibfk_2` FOREIGN KEY (`message_attribute_id`) REFERENCES `message_attributes` (`message_attribute_id`) ON DELETE CASCADE ON UPDATE CASCADE
1749 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1750 END_SQL
1751
1752     $dbh->do(<<'END_SQL');
1753 CREATE TABLE `borrower_message_transport_preferences` (
1754   `borrower_message_preference_id` int(11) NOT NULL default '0',
1755   `message_transport_type` varchar(20) NOT NULL default '0',
1756   PRIMARY KEY  (`borrower_message_preference_id`,`message_transport_type`),
1757   KEY `message_transport_type` (`message_transport_type`),
1758   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,
1759   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
1760 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1761 END_SQL
1762
1763     $dbh->do(<<'END_SQL');
1764 CREATE TABLE `message_queue` (
1765   `message_id` int(11) NOT NULL auto_increment,
1766   `borrowernumber` int(11) NOT NULL,
1767   `subject` text,
1768   `content` text,
1769   `message_transport_type` varchar(20) NOT NULL,
1770   `status` enum('sent','pending','failed','deleted') NOT NULL default 'pending',
1771   `time_queued` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1772   KEY `message_id` (`message_id`),
1773   KEY `borrowernumber` (`borrowernumber`),
1774   KEY `message_transport_type` (`message_transport_type`),
1775   CONSTRAINT `messageq_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1776   CONSTRAINT `messageq_ibfk_2` FOREIGN KEY (`message_transport_type`) REFERENCES `message_transport_types` (`message_transport_type`) ON DELETE RESTRICT ON UPDATE CASCADE
1777 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1778 END_SQL
1779
1780     $dbh->do(<<'END_SQL');
1781 INSERT INTO `systempreferences`
1782   (variable,value,explanation,options,type)
1783 VALUES
1784 ('EnhancedMessagingPreferences',0,'If ON, allows patrons to select to receive additional messages about items due or nearly due.','','YesNo')
1785 END_SQL
1786
1787     $dbh->do( <<'END_SQL');
1788 INSERT INTO `letter`
1789 (module, code, name, title, content)
1790 VALUES
1791 ('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>>'),
1792 ('circulation','DUEDGST','Item Due Reminder (Digest)','Item Due Reminder','You have <<count>> items due'),
1793 ('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>>'),
1794 ('circulation','PREDUEDGST','Advance Notice of Item Due (Digest)','Advance Notice of Item Due','You have <<count>> items due soon'),
1795 ('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.');
1796 END_SQL
1797
1798     my @sql_scripts = (
1799         'installer/data/mysql/en/mandatory/message_transport_types.sql',
1800         'installer/data/mysql/en/optional/sample_notices_message_attributes.sql',
1801         'installer/data/mysql/en/optional/sample_notices_message_transports.sql',
1802     );
1803
1804     my $installer = C4::Installer->new();
1805     foreach my $script ( @sql_scripts ) {
1806         my $full_path = $installer->get_file_path_from_name($script);
1807         my $error = $installer->load_sql($full_path);
1808         warn $error if $error;
1809     }
1810
1811     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";
1812     SetVersion ($DBversion);
1813 }
1814
1815 $DBversion = "3.00.00.092";
1816 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1817     $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')");
1818     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES('AllowHoldsOnDamagedItems', '1', '', 'Allow hold requests to be placed on damaged items', 'YesNo')");
1819         print "Upgrade to $DBversion done (added new AllowOnShelfHolds syspref)\n";
1820     SetVersion ($DBversion);
1821 }
1822
1823 $DBversion = "3.00.00.093";
1824 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1825     $dbh->do("ALTER TABLE `items` MODIFY COLUMN `copynumber` VARCHAR(32) DEFAULT NULL");
1826     $dbh->do("ALTER TABLE `deleteditems` MODIFY COLUMN `copynumber` VARCHAR(32) DEFAULT NULL");
1827         print "Upgrade to $DBversion done (Change data type of items.copynumber to allow free text)\n";
1828     SetVersion ($DBversion);
1829 }
1830
1831 $DBversion = "3.00.00.094";
1832 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1833     $dbh->do("ALTER TABLE `marc_subfield_structure` MODIFY `tagsubfield` VARCHAR(1) NOT NULL DEFAULT '' COLLATE utf8_bin");
1834         print "Upgrade to $DBversion done (Change Collation of marc_subfield_structure to allow mixed case in subfield labels.)\n";
1835     SetVersion ($DBversion);
1836 }
1837
1838 $DBversion = "3.00.00.095";
1839 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1840     if (C4::Context->preference("marcflavour") eq 'MARC21') {
1841         $dbh->do("UPDATE marc_subfield_structure SET authtypecode = 'MEETI_NAME' WHERE authtypecode = 'Meeting Name'");
1842         $dbh->do("UPDATE marc_subfield_structure SET authtypecode = 'CORPO_NAME' WHERE authtypecode = 'CORP0_NAME'");
1843     }
1844         print "Upgrade to $DBversion done (fix invalid authority types in MARC21 frameworks [bug 2254])\n";
1845     SetVersion ($DBversion);
1846 }
1847
1848 $DBversion = "3.00.00.096";
1849 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1850     $sth = $dbh->prepare("SHOW COLUMNS FROM borrower_message_preferences LIKE 'wants_digets'");
1851     $sth->execute();
1852     if (my $row = $sth->fetchrow_hashref) {
1853         $dbh->do("ALTER TABLE borrower_message_preferences CHANGE wants_digets wants_digest tinyint(1) NOT NULL default 0");
1854     }
1855         print "Upgrade to $DBversion done (fix name borrower_message_preferences.wants_digest)\n";
1856     SetVersion ($DBversion);
1857 }
1858
1859 $DBversion = '3.00.00.097';
1860 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1861
1862     $dbh->do('ALTER TABLE message_queue ADD to_address   mediumtext default NULL');
1863     $dbh->do('ALTER TABLE message_queue ADD from_address mediumtext default NULL');
1864     $dbh->do('ALTER TABLE message_queue ADD content_type text');
1865     $dbh->do('ALTER TABLE message_queue CHANGE borrowernumber borrowernumber int(11) default NULL');
1866
1867     print "Upgrade to $DBversion done (updating 4 fields in message_queue table)\n";
1868     SetVersion($DBversion);
1869 }
1870
1871 $DBversion = '3.00.00.098';
1872 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1873
1874     $dbh->do(q(DELETE FROM message_transport_types WHERE message_transport_type = 'rss'));
1875     $dbh->do(q(DELETE FROM message_transports WHERE message_transport_type = 'rss'));
1876
1877     print "Upgrade to $DBversion done (removing unused RSS message_transport_type)\n";
1878     SetVersion($DBversion);
1879 }
1880
1881 $DBversion = '3.00.00.099';
1882 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1883     $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')");
1884     print "Upgrade to $DBversion done (Adding OpacSuppression syspref)\n";
1885     SetVersion($DBversion);
1886 }
1887
1888 $DBversion = '3.00.00.100';
1889 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1890         $dbh->do('ALTER TABLE virtualshelves ADD COLUMN lastmodified timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP');
1891     print "Upgrade to $DBversion done (Adding lastmodified column to virtualshelves)\n";
1892     SetVersion($DBversion);
1893 }
1894
1895 $DBversion = '3.00.00.101';
1896 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1897         $dbh->do('ALTER TABLE `overduerules` CHANGE `categorycode` `categorycode` VARCHAR(10) NOT NULL');
1898         $dbh->do('ALTER TABLE `deletedborrowers` CHANGE `categorycode` `categorycode` VARCHAR(10) NOT NULL');
1899     print "Upgrade to $DBversion done (Updating columnd definitions for patron category codes in notice/statsu triggers and deletedborrowers tables.)\n";
1900     SetVersion($DBversion);
1901 }
1902
1903 $DBversion = '3.00.00.102';
1904 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1905         $dbh->do('ALTER TABLE serialitems MODIFY `serialid` int(11) NOT NULL AFTER itemnumber' );
1906         $dbh->do('ALTER TABLE serialitems DROP KEY serialididx' );
1907         $dbh->do('ALTER TABLE serialitems ADD CONSTRAINT UNIQUE KEY serialitemsidx (itemnumber)' );
1908         # before setting constraint, delete any unvalid data
1909         $dbh->do('DELETE from serialitems WHERE serialid not in (SELECT serial.serialid FROM serial)');
1910         $dbh->do('ALTER TABLE serialitems ADD CONSTRAINT serialitems_sfk_1 FOREIGN KEY (serialid) REFERENCES serial (serialid) ON DELETE CASCADE ON UPDATE CASCADE' );
1911     print "Upgrade to $DBversion done (Updating serialitems table to allow for multiple items per serial fixing kohabug 2380)\n";
1912     SetVersion($DBversion);
1913 }
1914
1915 $DBversion = "3.00.00.103";
1916 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1917     $dbh->do("DELETE FROM systempreferences WHERE variable='serialsadditems'");
1918     print "Upgrade to $DBversion done ( Verifying the removal of serialsadditems from syspref fixing kohabug 2219)\n";
1919     SetVersion ($DBversion);
1920 }
1921
1922 $DBversion = "3.00.00.104";
1923 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1924     $dbh->do("DELETE FROM systempreferences WHERE variable='noOPACHolds'");
1925     print "Upgrade to $DBversion done (remove superseded 'noOPACHolds' system preference per bug 2413)\n";
1926     SetVersion ($DBversion);
1927 }
1928
1929 $DBversion = '3.00.00.105';
1930 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
1931
1932     # it is possible that this syspref is already defined since the feature was added some time ago.
1933     unless ( $dbh->do(q(SELECT variable FROM systempreferences WHERE variable = 'SMSSendDriver')) ) {
1934         $dbh->do(<<'END_SQL');
1935 INSERT INTO `systempreferences`
1936   (variable,value,explanation,options,type)
1937 VALUES
1938 ('SMSSendDriver','','Sets which SMS::Send driver is used to send SMS messages.','','free')
1939 END_SQL
1940     }
1941     print "Upgrade to $DBversion done (added SMSSendDriver system preference)\n";
1942     SetVersion($DBversion);
1943 }
1944
1945 $DBversion = "3.00.00.106";
1946 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1947     $dbh->do("DELETE FROM systempreferences WHERE variable='noOPACHolds'");
1948
1949 # db revision 105 didn't apply correctly, so we're rolling this into 106
1950         $dbh->do("INSERT INTO `systempreferences`
1951    (variable,value,explanation,options,type)
1952         VALUES
1953         ('SMSSendDriver','','Sets which SMS::Send driver is used to send SMS messages.','','free')");
1954
1955     print "Upgrade to $DBversion done (remove default '0000-00-00' in subscriptionhistory.enddate field)\n";
1956     $dbh->do("ALTER TABLE `subscriptionhistory` CHANGE `enddate` `enddate` DATE NULL DEFAULT NULL ");
1957     $dbh->do("UPDATE subscriptionhistory SET enddate=NULL WHERE enddate='0000-00-00'");
1958     SetVersion ($DBversion);
1959 }
1960
1961 $DBversion = '3.00.00.107';
1962 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1963     $dbh->do(<<'END_SQL');
1964 UPDATE systempreferences
1965   SET explanation = CONCAT( explanation, '. WARNING: this feature is very resource consuming on collections with large numbers of items.' )
1966   WHERE variable = 'OPACShelfBrowser'
1967     AND explanation NOT LIKE '%WARNING%'
1968 END_SQL
1969     $dbh->do(<<'END_SQL');
1970 UPDATE systempreferences
1971   SET explanation = CONCAT( explanation, '. WARNING: this feature is very resource consuming.' )
1972   WHERE variable = 'CataloguingLog'
1973     AND explanation NOT LIKE '%WARNING%'
1974 END_SQL
1975     $dbh->do(<<'END_SQL');
1976 UPDATE systempreferences
1977   SET explanation = CONCAT( explanation, '. WARNING: using NoZebra on even modest sized collections is very slow.' )
1978   WHERE variable = 'NoZebra'
1979     AND explanation NOT LIKE '%WARNING%'
1980 END_SQL
1981     print "Upgrade to $DBversion done (warning added to OPACShelfBrowser system preference)\n";
1982     SetVersion ($DBversion);
1983 }
1984
1985 $DBversion = '3.01.00.000';
1986 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1987     print "Upgrade to $DBversion done (start of 3.1)\n";
1988     SetVersion ($DBversion);
1989 }
1990
1991 $DBversion = '3.01.00.001';
1992 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1993     $dbh->do("
1994         CREATE TABLE hold_fill_targets (
1995             `borrowernumber` int(11) NOT NULL,
1996             `biblionumber` int(11) NOT NULL,
1997             `itemnumber` int(11) NOT NULL,
1998             `source_branchcode`  varchar(10) default NULL,
1999             `item_level_request` tinyint(4) NOT NULL default 0,
2000             PRIMARY KEY `itemnumber` (`itemnumber`),
2001             KEY `bib_branch` (`biblionumber`, `source_branchcode`),
2002             CONSTRAINT `hold_fill_targets_ibfk_1` FOREIGN KEY (`borrowernumber`)
2003                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
2004             CONSTRAINT `hold_fill_targets_ibfk_2` FOREIGN KEY (`biblionumber`)
2005                 REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
2006             CONSTRAINT `hold_fill_targets_ibfk_3` FOREIGN KEY (`itemnumber`)
2007                 REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
2008             CONSTRAINT `hold_fill_targets_ibfk_4` FOREIGN KEY (`source_branchcode`)
2009                 REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
2010         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2011     ");
2012     $dbh->do("
2013         ALTER TABLE tmp_holdsqueue
2014             ADD item_level_request tinyint(4) NOT NULL default 0
2015     ");
2016
2017     print "Upgrade to $DBversion done (add hold_fill_targets table and a column to tmp_holdsqueue)\n";
2018     SetVersion($DBversion);
2019 }
2020
2021 $DBversion = '3.01.00.002';
2022 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2023     # use statistics where available
2024     $dbh->do("
2025         ALTER TABLE statistics ADD KEY  tmp_stats (type, itemnumber, borrowernumber)
2026     ");
2027     $dbh->do("
2028         UPDATE issues iss
2029         SET issuedate = (
2030             SELECT max(datetime)
2031             FROM statistics
2032             WHERE type = 'issue'
2033             AND itemnumber = iss.itemnumber
2034             AND borrowernumber = iss.borrowernumber
2035         )
2036         WHERE issuedate IS NULL;
2037     ");
2038     $dbh->do("ALTER TABLE statistics DROP KEY tmp_stats");
2039
2040     # default to last renewal date
2041     $dbh->do("
2042         UPDATE issues
2043         SET issuedate = lastreneweddate
2044         WHERE issuedate IS NULL
2045         and lastreneweddate IS NOT NULL
2046     ");
2047
2048     my $num_bad_issuedates = $dbh->selectrow_array("SELECT COUNT(*) FROM issues WHERE issuedate IS NULL");
2049     if ($num_bad_issuedates > 0) {
2050         print STDERR "After the upgrade to $DBversion, there are still $num_bad_issuedates loan(s) with a NULL (blank) loan date. ",
2051                      "Please check the issues table in your database.";
2052     }
2053     print "Upgrade to $DBversion done (bug 2582: set null issues.issuedate to lastreneweddate)\n";
2054     SetVersion($DBversion);
2055 }
2056
2057 $DBversion = "3.01.00.003";
2058 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2059     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowRenewalLimitOverride', '0', 'if ON, allows renewal limits to be overridden on the circulation screen',NULL,'YesNo')");
2060     print "Upgrade to $DBversion done (add new syspref)\n";
2061     SetVersion ($DBversion);
2062 }
2063
2064 $DBversion = '3.01.00.004';
2065 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2066     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACDisplayRequestPriority','0','Show patrons the priority level on holds in the OPAC','','YesNo')");
2067     print "Upgrade to $DBversion done (added OPACDisplayRequestPriority system preference)\n";
2068     SetVersion ($DBversion);
2069 }
2070
2071 $DBversion = '3.01.00.005';
2072 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2073     $dbh->do("
2074         INSERT INTO `letter` (module, code, name, title, content)
2075         VALUES('reserves', 'HOLD', 'Hold Available for Pickup', 'Hold Available for Pickup at <<branches.branchname>>', 'Dear <<borrowers.firstname>> <<borrowers.surname>>,\r\n\r\nYou have a hold available for pickup as of <<reserves.waitingdate>>:\r\n\r\nTitle: <<biblio.title>>\r\nAuthor: <<biblio.author>>\r\nCopy: <<items.copynumber>>\r\nLocation: <<branches.branchname>>\r\n<<branches.branchaddress1>>\r\n<<branches.branchaddress2>>\r\n<<branches.branchaddress3>>')
2076     ");
2077     $dbh->do("INSERT INTO `message_attributes` (message_attribute_id, message_name, takes_days) values(4, 'Hold Filled', 0)");
2078     $dbh->do("INSERT INTO `message_transports` (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) values(4, 'sms', 0, 'reserves', 'HOLD')");
2079     $dbh->do("INSERT INTO `message_transports` (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) values(4, 'email', 0, 'reserves', 'HOLD')");
2080     print "Upgrade to $DBversion done (Add letter for holds notifications)\n";
2081     SetVersion ($DBversion);
2082 }
2083
2084 $DBversion = '3.01.00.006';
2085 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2086     $dbh->do("ALTER TABLE `biblioitems` ADD KEY issn (issn)");
2087     print "Upgrade to $DBversion done (add index on biblioitems.issn)\n";
2088     SetVersion ($DBversion);
2089 }
2090
2091 $DBversion = "3.01.00.007";
2092 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2093     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='intranetmainUserblock'");
2094     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='intranetuserjs'");
2095     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='opacheader'");
2096     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='OpacMainUserBlock'");
2097     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='OpacNav'");
2098     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='opacuserjs'");
2099     $dbh->do("UPDATE `systempreferences` SET options='30|10', type='Textarea' WHERE variable='OAI-PMH:Set'");
2100     $dbh->do("UPDATE `systempreferences` SET options='50' WHERE variable='intranetstylesheet'");
2101     $dbh->do("UPDATE `systempreferences` SET options='50' WHERE variable='intranetcolorstylesheet'");
2102     $dbh->do("UPDATE `systempreferences` SET options='10' WHERE variable='globalDueDate'");
2103     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='numSearchResults'");
2104     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='OPACnumSearchResults'");
2105     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='ReservesMaxPickupDelay'");
2106     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='TransfersMaxDaysWarning'");
2107     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='StaticHoldsQueueWeight'");
2108     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='holdCancelLength'");
2109     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='XISBNDailyLimit'");
2110     $dbh->do("UPDATE `systempreferences` SET type='Float' WHERE variable='gist'");
2111     $dbh->do("UPDATE `systempreferences` SET type='Free' WHERE variable='BakerTaylorUsername'");
2112     $dbh->do("UPDATE `systempreferences` SET type='Free' WHERE variable='BakerTaylorPassword'");
2113     $dbh->do("UPDATE `systempreferences` SET type='Textarea', options='70|10' WHERE variable='ISBD'");
2114     $dbh->do("UPDATE `systempreferences` SET type='Textarea', options='70|10', explanation='Enter a specific hash for NoZebra indexes. Enter : \\\'indexname\\\' => \\\'100a,245a,500*\\\',\\\'index2\\\' => \\\'...\\\'' WHERE variable='NoZebraIndexes'");
2115     print "Upgrade to $DBversion done (fix display of many sysprefs)\n";
2116     SetVersion ($DBversion);
2117 }
2118
2119 $DBversion = '3.01.00.008';
2120 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2121
2122     $dbh->do("CREATE TABLE branch_transfer_limits (
2123                           limitId int(8) NOT NULL auto_increment,
2124                           toBranch varchar(4) NOT NULL,
2125                           fromBranch varchar(4) NOT NULL,
2126                           itemtype varchar(4) NOT NULL,
2127                           PRIMARY KEY  (limitId)
2128                           ) ENGINE=InnoDB DEFAULT CHARSET=utf8"
2129                         );
2130
2131     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` ) VALUES ( 'UseBranchTransferLimits', '0', '', 'If ON, Koha will will use the rules defined in branch_transfer_limits to decide if an item transfer should be allowed.', 'YesNo')");
2132
2133     print "Upgrade to $DBversion done (added branch_transfer_limits table and UseBranchTransferLimits system preference)\n";
2134     SetVersion ($DBversion);
2135 }
2136
2137 $DBversion = "3.01.00.009";
2138 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2139     $dbh->do("ALTER TABLE permissions MODIFY `code` varchar(64) DEFAULT NULL");
2140     $dbh->do("ALTER TABLE user_permissions MODIFY `code` varchar(64) DEFAULT NULL");
2141     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'circulate_remaining_permissions', 'Remaining circulation permissions')");
2142     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'override_renewals', 'Override blocked renewals')");
2143     print "Upgrade to $DBversion done (added subpermissions for circulate permission)\n";
2144 }
2145
2146 $DBversion = '3.01.00.010';
2147 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2148     $dbh->do("ALTER TABLE `borrower_attributes` MODIFY COLUMN `attribute` VARCHAR(64) DEFAULT NULL");
2149     $dbh->do("ALTER TABLE `borrower_attributes` MODIFY COLUMN `password` VARCHAR(64) DEFAULT NULL");
2150     print "Upgrade to $DBversion done (bug 2687: increase length of borrower attribute fields)\n";
2151     SetVersion ($DBversion);
2152 }
2153
2154 $DBversion = '3.01.00.011';
2155 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2156
2157     # Yes, the old value was ^M terminated.
2158     my $bad_value = "function prepareEmailPopup(){\r\n  if (!document.getElementById) return false;\r\n  if (!document.getElementById('reserveemail')) return false;\r\n  rsvlink = document.getElementById('reserveemail');\r\n  rsvlink.onclick = function() {\r\n      doReservePopup();\r\n      return false;\r\n  }\r\n}\r\n\r\nfunction doReservePopup(){\r\n}\r\n\r\nfunction prepareReserveList(){\r\n}\r\n\r\naddLoadEvent(prepareEmailPopup);\r\naddLoadEvent(prepareReserveList);";
2159
2160     my $intranetuserjs = C4::Context->preference('intranetuserjs');
2161     if ($intranetuserjs  and  $intranetuserjs eq $bad_value) {
2162         my $sql = <<'END_SQL';
2163 UPDATE systempreferences
2164 SET value = ''
2165 WHERE variable = 'intranetuserjs'
2166 END_SQL
2167         $dbh->do($sql);
2168     }
2169     print "Upgrade to $DBversion done (removed bogus intranetuserjs syspref)\n";
2170     SetVersion($DBversion);
2171 }
2172
2173 $DBversion = "3.01.00.012";
2174 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2175     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowHoldPolicyOverride', '0', 'Allow staff to override hold policies when placing holds',NULL,'YesNo')");
2176     $dbh->do("
2177         CREATE TABLE `branch_item_rules` (
2178           `branchcode` varchar(10) NOT NULL,
2179           `itemtype` varchar(10) NOT NULL,
2180           `holdallowed` tinyint(1) default NULL,
2181           PRIMARY KEY  (`itemtype`,`branchcode`),
2182           KEY `branch_item_rules_ibfk_2` (`branchcode`),
2183           CONSTRAINT `branch_item_rules_ibfk_1` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE,
2184           CONSTRAINT `branch_item_rules_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
2185         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2186     ");
2187     $dbh->do("
2188         CREATE TABLE `default_branch_item_rules` (
2189           `itemtype` varchar(10) NOT NULL,
2190           `holdallowed` tinyint(1) default NULL,
2191           PRIMARY KEY  (`itemtype`),
2192           CONSTRAINT `default_branch_item_rules_ibfk_1` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE
2193         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2194     ");
2195     $dbh->do("
2196         ALTER TABLE default_branch_circ_rules
2197             ADD COLUMN holdallowed tinyint(1) NULL
2198     ");
2199     $dbh->do("
2200         ALTER TABLE default_circ_rules
2201             ADD COLUMN holdallowed tinyint(1) NULL
2202     ");
2203     print "Upgrade to $DBversion done (Add tables and system preferences for holds policies)\n";
2204     SetVersion ($DBversion);
2205 }
2206
2207 $DBversion = '3.01.00.013';
2208 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2209     $dbh->do("
2210         CREATE TABLE item_circulation_alert_preferences (
2211             id           int(11) AUTO_INCREMENT,
2212             branchcode   varchar(10) NOT NULL,
2213             categorycode varchar(10) NOT NULL,
2214             item_type    varchar(10) NOT NULL,
2215             notification varchar(16) NOT NULL,
2216             PRIMARY KEY (id),
2217             KEY (branchcode, categorycode, item_type, notification)
2218         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2219     ");
2220
2221     $dbh->do(q{ ALTER TABLE `message_queue` ADD metadata text DEFAULT NULL           AFTER content;  });
2222     $dbh->do(q{ ALTER TABLE `message_queue` ADD letter_code varchar(64) DEFAULT NULL AFTER metadata; });
2223
2224     $dbh->do(q{
2225         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
2226         ('circulation','CHECKIN','Item Check-in','Check-ins','The following items have been checked in:\r\n----\r\n<<biblio.title>>\r\n----\r\nThank you.');
2227     });
2228     $dbh->do(q{
2229         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
2230         ('circulation','CHECKOUT','Item Checkout','Checkouts','The following items have been checked out:\r\n----\r\n<<biblio.title>>\r\n----\r\nThank you for visiting <<branches.branchname>>.');
2231     });
2232
2233     $dbh->do(q{INSERT INTO message_attributes (message_attribute_id, message_name, takes_days) VALUES (5, 'Item Check-in', 0);});
2234     $dbh->do(q{INSERT INTO message_attributes (message_attribute_id, message_name, takes_days) VALUES (6, 'Item Checkout', 0);});
2235
2236     $dbh->do(q{INSERT INTO message_transports (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) VALUES (5, 'email', 0, 'circulation', 'CHECKIN');});
2237     $dbh->do(q{INSERT INTO message_transports (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) VALUES (5, 'sms',   0, 'circulation', 'CHECKIN');});
2238     $dbh->do(q{INSERT INTO message_transports (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) VALUES (6, 'email', 0, 'circulation', 'CHECKOUT');});
2239     $dbh->do(q{INSERT INTO message_transports (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) VALUES (6, 'sms',   0, 'circulation', 'CHECKOUT');});
2240
2241     print "Upgrade to $DBversion done (data for Email Checkout Slips project)\n";
2242          SetVersion ($DBversion);
2243 }
2244
2245 $DBversion = "3.01.00.014";
2246 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2247     $dbh->do("ALTER TABLE `branch_transfer_limits` CHANGE `itemtype` `itemtype` VARCHAR( 4 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL");
2248     $dbh->do("ALTER TABLE `branch_transfer_limits` ADD `ccode` VARCHAR( 10 ) NULL ;");
2249     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2250     VALUES (
2251     'BranchTransferLimitsType', 'ccode', 'itemtype|ccode', 'When using branch transfer limits, choose whether to limit by itemtype or collection code.', 'Choice'
2252     );");
2253
2254     print "Upgrade to $DBversion done ( Updated table for Branch Transfer Limits)\n";
2255     SetVersion ($DBversion);
2256 }
2257
2258 $DBversion = '3.01.00.015';
2259 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2260     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsClientCode', '0', 'Client Code for using Syndetics Solutions content','','free')");
2261
2262     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsEnabled', '0', 'Turn on Syndetics Enhanced Content','','YesNo')");
2263
2264     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsCoverImages', '0', 'Display Cover Images from Syndetics','','YesNo')");
2265
2266     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsTOC', '0', 'Display Table of Content information from Syndetics','','YesNo')");
2267
2268     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsSummary', '0', 'Display Summary Information from Syndetics','','YesNo')");
2269
2270     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsEditions', '0', 'Display Editions from Syndetics','','YesNo')");
2271
2272     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsExcerpt', '0', 'Display Excerpts and first chapters on OPAC from Syndetics','','YesNo')");
2273
2274     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsReviews', '0', 'Display Reviews on OPAC from Syndetics','','YesNo')");
2275
2276     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsAuthorNotes', '0', 'Display Notes about the Author on OPAC from Syndetics','','YesNo')");
2277
2278     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsAwards', '0', 'Display Awards on OPAC from Syndetics','','YesNo')");
2279
2280     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsSeries', '0', 'Display Series information on OPAC from Syndetics','','YesNo')");
2281
2282     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsCoverImageSize', 'MC', 'Choose the size of the Syndetics Cover Image to display on the OPAC detail page, MC is Medium, LC is Large','MC|LC','Choice')");
2283
2284     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAmazonCoverImages', '0', 'Display cover images on OPAC from Amazon Web Services','','YesNo')");
2285
2286     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AmazonCoverImages', '0', 'Display Cover Images in Staff Client from Amazon Web Services','','YesNo')");
2287
2288     $dbh->do("UPDATE systempreferences SET variable='AmazonEnabled' WHERE variable = 'AmazonContent'");
2289
2290     $dbh->do("UPDATE systempreferences SET variable='OPACAmazonEnabled' WHERE variable = 'OPACAmazonContent'");
2291
2292     print "Upgrade to $DBversion done (added Syndetics Enhanced Content system preferences)\n";
2293     SetVersion ($DBversion);
2294 }
2295
2296 $DBversion = "3.01.00.016";
2297 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2298     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('Babeltheque',0,'Turn ON Babeltheque content  - See babeltheque.com to subscribe to this service','','YesNo')");
2299     print "Upgrade to $DBversion done (Added Babeltheque syspref)\n";
2300     SetVersion ($DBversion);
2301 }
2302
2303 $DBversion = "3.01.00.017";
2304 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2305     $dbh->do("ALTER TABLE `subscription` ADD `staffdisplaycount` VARCHAR(10) NULL;");
2306     $dbh->do("ALTER TABLE `subscription` ADD `opacdisplaycount` VARCHAR(10) NULL;");
2307     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2308     VALUES (
2309     'StaffSerialIssueDisplayCount', '3', '', 'Number of serial issues to display per subscription in the Staff client', 'Integer'
2310     );");
2311         $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2312     VALUES (
2313     'OPACSerialIssueDisplayCount', '3', '', 'Number of serial issues to display per subscription in the OPAC', 'Integer'
2314     );");
2315
2316     print "Upgrade to $DBversion done ( Updated table for Serials Display)\n";
2317     SetVersion ($DBversion);
2318 }
2319
2320 $DBversion = "3.01.00.018";
2321 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2322     $dbh->do("ALTER TABLE deletedborrowers ADD `smsalertnumber` varchar(50) default NULL");
2323     print "Upgrade to $DBversion done (added deletedborrowers.smsalertnumber, missed in 3.00.00.091)\n";
2324     SetVersion ($DBversion);
2325 }
2326
2327 $DBversion = "3.01.00.019";
2328 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2329         $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACShowCheckoutName','0','Displays in the OPAC the name of patron who has checked out the material. WARNING: Most sites should leave this off. It is intended for corporate or special sites which need to track who has the item.','','YesNo')");
2330     print "Upgrade to $DBversion done (adding OPACShowCheckoutName systempref)\n";
2331     SetVersion ($DBversion);
2332 }
2333
2334 $DBversion = "3.01.00.020";
2335 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2336     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesID','','See:http://librarything.com/forlibraries/','','free')");
2337     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesEnabled','0','Enable or Disable Library Thing for Libraries Features','','YesNo')");
2338     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesTabbedView','0','Put LibraryThingForLibraries Content in Tabs.','','YesNo')");
2339     print "Upgrade to $DBversion done (adding LibraryThing for Libraries sysprefs)\n";
2340     SetVersion ($DBversion);
2341 }
2342
2343 $DBversion = "3.01.00.021";
2344 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2345     my $enable_reviews = C4::Context->preference('OPACAmazonEnabled') ? '1' : '0';
2346     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAmazonReviews', '$enable_reviews', 'Display Amazon readers reviews on OPAC','','YesNo')");
2347     print "Upgrade to $DBversion done (adding OPACAmazonReviews syspref)\n";
2348     SetVersion ($DBversion);
2349 }
2350
2351 $DBversion = '3.01.00.022';
2352 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2353     $dbh->do("ALTER TABLE `labels_conf` MODIFY COLUMN `formatstring` mediumtext DEFAULT NULL");
2354     print "Upgrade to $DBversion done (bug 2945: increase size of labels_conf.formatstring)\n";
2355     SetVersion ($DBversion);
2356 }
2357
2358 $DBversion = '3.01.00.023';
2359 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2360     $dbh->do("ALTER TABLE biblioitems        MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2361     $dbh->do("ALTER TABLE deletedbiblioitems MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2362     $dbh->do("ALTER TABLE import_biblios     MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2363     $dbh->do("ALTER TABLE suggestions        MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2364     print "Upgrade to $DBversion done (bug 2765: increase width of isbn column in several tables)\n";
2365     SetVersion ($DBversion);
2366 }
2367
2368 $DBversion = "3.01.00.024";
2369 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2370     $dbh->do("ALTER TABLE labels MODIFY COLUMN batch_id int(10) NOT NULL default 1;");
2371     print "Upgrade to $DBversion done (change labels.batch_id from varchar to int)\n";
2372     SetVersion ($DBversion);
2373 }
2374
2375 $DBversion = '3.01.00.025';
2376 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2377     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` ) VALUES ( 'ceilingDueDate', '', '', 'If set, date due will not be past this date.  Enter date according to the dateformat System Preference', 'free')");
2378
2379     print "Upgrade to $DBversion done (added ceilingDueDate system preference)\n";
2380     SetVersion ($DBversion);
2381 }
2382
2383 $DBversion = '3.01.00.026';
2384 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2385     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` ) VALUES ( 'numReturnedItemsToShow', '20', '', 'Number of returned items to show on the check-in page', 'Integer')");
2386
2387     print "Upgrade to $DBversion done (added numReturnedItemsToShow system preference)\n";
2388     SetVersion ($DBversion);
2389 }
2390
2391 $DBversion = '3.01.00.027';
2392 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2393     $dbh->do("ALTER TABLE zebraqueue CHANGE `biblio_auth_number` `biblio_auth_number` bigint(20) unsigned NOT NULL default 0");
2394     print "Upgrade to $DBversion done (Increased size of zebraqueue biblio_auth_number to address bug 3148.)\n";
2395     SetVersion ($DBversion);
2396 }
2397
2398 $DBversion = '3.01.00.028';
2399 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2400     my $enable_reviews = C4::Context->preference('AmazonEnabled') ? '1' : '0';
2401     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AmazonReviews', '$enable_reviews', 'Display Amazon reviews on staff interface','','YesNo')");
2402     print "Upgrade to $DBversion done (added AmazonReviews)\n";
2403     SetVersion ($DBversion);
2404 }
2405
2406 $DBversion = '3.01.00.029';
2407 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2408     $dbh->do(q( UPDATE language_rfc4646_to_iso639
2409                 SET iso639_2_code = 'spa'
2410                 WHERE rfc4646_subtag = 'es'
2411                 AND   iso639_2_code = 'rus' )
2412             );
2413     print "Upgrade to $DBversion done (fixed bug 2599: using Spanish search limit retrieves Russian results)\n";
2414     SetVersion ($DBversion);
2415 }
2416
2417 $DBversion = "3.01.00.030";
2418 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2419     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` ) VALUES ( 'AllowNotForLoanOverride', '0', '', 'If ON, Koha will allow the librarian to loan a not for loan item.', 'YesNo')");
2420     print "Upgrade to $DBversion done (added AllowNotForLoanOverride system preference)\n";
2421     SetVersion ($DBversion);
2422 }
2423
2424 $DBversion = "3.01.00.031";
2425 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2426     $dbh->do("ALTER TABLE branch_transfer_limits
2427               MODIFY toBranch   varchar(10) NOT NULL,
2428               MODIFY fromBranch varchar(10) NOT NULL,
2429               MODIFY itemtype   varchar(10) NULL");
2430     print "Upgrade to $DBversion done (fix column widths in branch_transfer_limits)\n";
2431     SetVersion ($DBversion);
2432 }
2433
2434 $DBversion = "3.01.00.032";
2435 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2436     $dbh->do(<<ENDOFRENEWAL);
2437 INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('RenewalPeriodBase', 'now', 'Set whether the renewal date should be counted from the date_due or from the moment the Patron asks for renewal ','date_due|now','Choice');
2438 ENDOFRENEWAL
2439     print "Upgrade to $DBversion done (Change the field)\n";
2440     SetVersion ($DBversion);
2441 }
2442
2443 $DBversion = "3.01.00.033";
2444 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2445     $dbh->do(q/
2446         ALTER TABLE borrower_message_preferences
2447         MODIFY borrowernumber int(11) default NULL,
2448         ADD    categorycode varchar(10) default NULL AFTER borrowernumber,
2449         ADD KEY `categorycode` (`categorycode`),
2450         ADD CONSTRAINT `borrower_message_preferences_ibfk_3`
2451                        FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
2452                        ON DELETE CASCADE ON UPDATE CASCADE
2453     /);
2454     print "Upgrade to $DBversion done (DB changes to allow patron category defaults for messaging preferences)\n";
2455     SetVersion ($DBversion);
2456 }
2457
2458 $DBversion = "3.01.00.034";
2459 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2460     $dbh->do("ALTER TABLE `subscription` ADD COLUMN `graceperiod` INT(11) NOT NULL default '0';");
2461     print "Upgrade to $DBversion done (Adding graceperiod column to subscription table)\n";
2462     SetVersion ($DBversion);
2463 }
2464
2465 $DBversion = '3.01.00.035';
2466 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2467     $dbh->do(q{ ALTER TABLE `subscription` ADD location varchar(80) NULL DEFAULT '' AFTER callnumber; });
2468    print "Upgrade to $DBversion done (Adding location to subscription table)\n";
2469     SetVersion ($DBversion);
2470 }
2471
2472 $DBversion = '3.01.00.036';
2473 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2474     $dbh->do("UPDATE systempreferences SET explanation = 'Choose the default detail view in the staff interface; choose between normal, labeled_marc, marc or isbd'
2475               WHERE variable = 'IntranetBiblioDefaultView'
2476               AND   explanation = 'IntranetBiblioDefaultView'");
2477     $dbh->do("UPDATE systempreferences SET type = 'Choice', options = 'normal|marc|isbd|labeled_marc'
2478               WHERE variable = 'IntranetBiblioDefaultView'");
2479     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewISBD','1','Allow display of ISBD view of bibiographic records','','YesNo')");
2480     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewLabeledMARC','0','Allow display of labeled MARC view of bibiographic records','','YesNo')");
2481     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewMARC','1','Allow display of MARC view of bibiographic records','','YesNo')");
2482     print "Upgrade to $DBversion done (new viewISBD, viewLabeledMARC, viewMARC sysprefs and tweak IntranetBiblioDefaultView)\n";
2483     SetVersion ($DBversion);
2484 }
2485
2486 $DBversion = '3.01.00.037';
2487 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2488     $dbh->do('ALTER TABLE authorised_values ADD KEY `lib` (`lib`)');
2489     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('FilterBeforeOverdueReport','0','Do not run overdue report until filter selected','','YesNo')");
2490     SetVersion ($DBversion);
2491     print "Upgrade to $DBversion done (added FilterBeforeOverdueReport syspref and new index on authorised_values)\n";
2492 }
2493
2494 $DBversion = "3.01.00.038";
2495 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2496     # update branches table
2497     #
2498     $dbh->do("ALTER TABLE branches ADD `branchzip` varchar(25) default NULL AFTER `branchaddress3`");
2499     $dbh->do("ALTER TABLE branches ADD `branchcity` mediumtext AFTER `branchzip`");
2500     $dbh->do("ALTER TABLE branches ADD `branchcountry` text AFTER `branchcity`");
2501     $dbh->do("ALTER TABLE branches ADD `branchurl` mediumtext AFTER `branchemail`");
2502     $dbh->do("ALTER TABLE branches ADD `branchnotes` mediumtext AFTER `branchprinter`");
2503     print "Upgrade to $DBversion done (add ZIP, city, country, URL, and notes column to branches)\n";
2504     SetVersion ($DBversion);
2505 }
2506
2507 $DBversion = '3.01.00.039';
2508 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2509     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type)VALUES('SpineLabelFormat', '<itemcallnumber><copynumber>', '30|10', 'This preference defines the format for the quick spine label printer. Just list the fields you would like to see in the order you would like to see them, surrounded by <>, for example <itemcallnumber>.', 'Textarea')");
2510     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type)VALUES('SpineLabelAutoPrint', '0', '', 'If this setting is turned on, a print dialog will automatically pop up for the quick spine label printer.', 'YesNo')");
2511     SetVersion ($DBversion);
2512     print "Upgrade to $DBversion done (added SpineLabelFormat and SpineLabelAutoPrint sysprefs)\n";
2513 }
2514
2515 $DBversion = '3.01.00.040';
2516 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2517     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('AllowHoldDateInFuture','0','If set a date field is displayed on the Hold screen of the Staff Interface, allowing the hold date to be set in the future.','','YesNo')");
2518     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('OPACAllowHoldDateInFuture','0','If set, along with the AllowHoldDateInFuture system preference, OPAC users can set the date of a hold to be in the future.','','YesNo')");
2519     SetVersion ($DBversion);
2520     print "Upgrade to $DBversion done (AllowHoldDateInFuture and OPACAllowHoldDateInFuture sysprefs)\n";
2521 }
2522
2523 $DBversion = '3.01.00.041';
2524 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2525     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AWSPrivateKey','','See:  http://aws.amazon.com.  Note that this is required after 2009/08/15 in order to retrieve any enhanced content other than book covers from Amazon.','','free')");
2526     SetVersion ($DBversion);
2527     print "Upgrade to $DBversion done (added AWSPrivateKey syspref - note that if you use enhanced content from Amazon, this should be set right away.)\n";
2528 }
2529
2530 $DBversion = '3.01.00.042';
2531 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2532     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACFineNoRenewals','99999','Fine Limit above which user canmot renew books via OPAC','','Integer')");
2533     SetVersion ($DBversion);
2534     print "Upgrade to $DBversion done (added OPACFineNoRenewals syspref)\n";
2535 }
2536
2537 $DBversion = '3.01.00.043';
2538 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2539     $dbh->do('ALTER TABLE items ADD COLUMN permanent_location VARCHAR(80) DEFAULT NULL AFTER location');
2540     $dbh->do('UPDATE items SET permanent_location = location');
2541     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` ) VALUES ( 'NewItemsDefaultLocation', '', '', 'If set, all new items will have a location of the given Location Code ( Authorized Value type LOC )', '')");
2542     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` ) VALUES ( 'InProcessingToShelvingCart', '0', '', 'If set, when any item with a location code of PROC is ''checked in'', it''s location code will be changed to CART.', 'YesNo')");
2543     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` ) VALUES ( 'ReturnToShelvingCart', '0', '', 'If set, when any item is ''checked in'', it''s location code will be changed to CART.', 'YesNo')");
2544     SetVersion ($DBversion);
2545     print "Upgrade to $DBversion done (amended Item added NewItemsDefaultLocation, InProcessingToShelvingCart, ReturnToShelvingCart sysprefs)\n";
2546 }
2547
2548 $DBversion = '3.01.00.044';
2549 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2550     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES( 'DisplayClearScreenButton', '0', 'If set to yes, a clear screen button will appear on the circulation page.', 'If set to yes, a clear screen button will appear on the circulation page.', 'YesNo')");
2551     SetVersion ($DBversion);
2552     print "Upgrade to $DBversion done (added DisplayClearScreenButton system preference)\n";
2553 }
2554
2555 $DBversion = '3.01.00.045';
2556 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2557     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type)VALUES('HidePatronName', '0', '', 'If this is switched on, patron''s cardnumber will be shown instead of their name on the holds and catalog screens', 'YesNo')");
2558     SetVersion ($DBversion);
2559     print "Upgrade to $DBversion done (added a preference to hide the patrons name in the staff catalog)\n";
2560 }
2561
2562 $DBversion = "3.01.00.046";
2563 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2564     # update borrowers table
2565     #
2566     $dbh->do("ALTER TABLE borrowers ADD `country` text AFTER zipcode");
2567     $dbh->do("ALTER TABLE borrowers ADD `B_country` text AFTER B_zipcode");
2568     $dbh->do("ALTER TABLE deletedborrowers ADD `country` text AFTER zipcode");
2569     $dbh->do("ALTER TABLE deletedborrowers ADD `B_country` text AFTER B_zipcode");
2570     print "Upgrade to $DBversion done (add country and B_country to borrowers)\n";
2571     SetVersion ($DBversion);
2572 }
2573
2574 $DBversion = '3.01.00.047';
2575 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2576     $dbh->do("ALTER TABLE items MODIFY itemcallnumber varchar(255);");
2577     $dbh->do("ALTER TABLE deleteditems MODIFY itemcallnumber varchar(255);");
2578     $dbh->do("ALTER TABLE tmp_holdsqueue MODIFY itemcallnumber varchar(255);");
2579     SetVersion ($DBversion);
2580     print " Upgrade to $DBversion done (bug 2761: change max length of itemcallnumber to 255 from 30)\n";
2581 }
2582
2583 $DBversion = '3.01.00.048';
2584 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2585     $dbh->do("UPDATE userflags SET flagdesc='View Catalog (Librarian Interface)' WHERE bit=2;");
2586     $dbh->do("UPDATE userflags SET flagdesc='Edit Catalog (Modify bibliographic/holdings data)' WHERE bit=9;");
2587     $dbh->do("UPDATE userflags SET flagdesc='Allow to edit authorities' WHERE bit=14;");
2588     $dbh->do("UPDATE userflags SET flagdesc='Allow to access to the reports module' WHERE bit=16;");
2589     $dbh->do("UPDATE userflags SET flagdesc='Allow to manage serials subscriptions' WHERE bit=15;");
2590     SetVersion ($DBversion);
2591     print " Upgrade to $DBversion done (bug 2611: fix spelling/capitalization in permission flag descriptions)\n";
2592 }
2593
2594 $DBversion = '3.01.00.049';
2595 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2596     $dbh->do("UPDATE permissions SET description = 'Perform inventory (stocktaking) of your catalog' WHERE code = 'inventory';");
2597      SetVersion ($DBversion);
2598     print "Upgrade to $DBversion done (bug 2611: changed catalogue to catalog per the standard)\n";
2599 }
2600
2601 $DBversion = '3.01.00.050';
2602 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2603     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OPACSearchForTitleIn','<li class=\"yuimenuitem\">\n<a target=\"_blank\" class=\"yuimenuitemlabel\" href=\"http://worldcat.org/search?q=TITLE\">Other Libraries (WorldCat)</a></li>\n<li class=\"yuimenuitem\">\n<a class=\"yuimenuitemlabel\" href=\"http://www.scholar.google.com/scholar?q=TITLE\" target=\"_blank\">Other Databases (Google Scholar)</a></li>\n<li class=\"yuimenuitem\">\n<a class=\"yuimenuitemlabel\" href=\"http://www.bookfinder.com/search/?author=AUTHOR&amp;title=TITLE&amp;st=xl&amp;ac=qr\" target=\"_blank\">Online Stores (Bookfinder.com)</a></li>','Enter the HTML that will appear in the ''Search for this title in'' box on the detail page in the OPAC.  Enter TITLE, AUTHOR, or ISBN in place of their respective variables in the URL.  Leave blank to disable ''More Searches'' menu.','70|10','Textarea');");
2604     SetVersion ($DBversion);
2605     print "Upgrade to $DBversion done (bug 1934: Add OPACSearchForTitleIn syspref)\n";
2606 }
2607
2608 $DBversion = '3.01.00.051';
2609 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2610     $dbh->do("UPDATE systempreferences SET explanation='Fine limit above which user cannot renew books via OPAC' WHERE variable='OPACFineNoRenewals';");
2611     $dbh->do("UPDATE systempreferences SET explanation='If set to ON, a clear screen button will appear on the circulation page.' WHERE variable='DisplayClearScreenButton';");
2612     SetVersion ($DBversion);
2613     print "Upgrade to $DBversion done (fixed typos in new sysprefs)\n";
2614 }
2615
2616 $DBversion = '3.01.00.052';
2617 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2618     $dbh->do('ALTER TABLE deleteditems ADD COLUMN permanent_location VARCHAR(80) DEFAULT NULL AFTER location');
2619     SetVersion ($DBversion);
2620     print "Upgrade to $DBversion done (bug 3481: add permanent_location column to deleteditems)\n";
2621 }
2622
2623 $DBversion = '3.01.00.053';
2624 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2625     my $upgrade_script = C4::Context->config("intranetdir") . "/installer/data/mysql/labels_upgrade.pl";
2626     system("perl $upgrade_script");
2627     print "Upgrade to $DBversion done (Migrated labels tables and data to new schema.) NOTE: All existing label batches have been assigned to the first branch in the list of branches. This is ONLY true of migrated label batches.\n";
2628     SetVersion ($DBversion);
2629 }
2630
2631 $DBversion = '3.01.00.054';
2632 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2633     $dbh->do("ALTER TABLE borrowers ADD `B_address2` text AFTER B_address");
2634     $dbh->do("ALTER TABLE borrowers ADD `altcontactcountry` text AFTER altcontactzipcode");
2635     $dbh->do("ALTER TABLE deletedborrowers ADD `B_address2` text AFTER B_address");
2636     $dbh->do("ALTER TABLE deletedborrowers ADD `altcontactcountry` text AFTER altcontactzipcode");
2637     SetVersion ($DBversion);
2638     print "Upgrade to $DBversion done (bug 1600, bug 3454: add altcontactcountry and B_address2 to borrowers and deletedborrowers)\n";
2639 }
2640
2641 $DBversion = '3.01.00.055';
2642 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2643     $dbh->do(qq|UPDATE systempreferences set explanation='Enter the HTML that will appear in the ''Search for this title in'' box on the detail page in the OPAC.  Enter {TITLE}, {AUTHOR}, or {ISBN} in place of their respective variables in the URL. Leave blank to disable ''More Searches'' menu.', value='<li><a  href="http://worldcat.org/search?q={TITLE}" target="_blank">Other Libraries (WorldCat)</a></li>\n<li><a href="http://www.scholar.google.com/scholar?q={TITLE}" target="_blank">Other Databases (Google Scholar)</a></li>\n<li><a href="http://www.bookfinder.com/search/?author={AUTHOR}&amp;title={TITLE}&amp;st=xl&amp;ac=qr" target="_blank">Online Stores (Bookfinder.com)</a></li>' WHERE variable='OPACSearchForTitleIn'|);
2644     SetVersion ($DBversion);
2645     print "Upgrade to $DBversion done (changed OPACSearchForTitleIn per requests in bug 1934)\n";
2646 }
2647
2648 $DBversion = '3.01.00.056';
2649 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2650     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OPACPatronDetails','1','If OFF the patron details tab in the OPAC is disabled.','','YesNo');");
2651     SetVersion ($DBversion);
2652     print "Upgrade to $DBversion done (Bug 1172 : Add OPACPatronDetails syspref)\n";
2653 }
2654
2655 $DBversion = '3.01.00.057';
2656 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2657     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OPACFinesTab','1','If OFF the patron fines tab in the OPAC is disabled.','','YesNo');");
2658     SetVersion ($DBversion);
2659     print "Upgrade to $DBversion done (Bug 2576 : Add OPACFinesTab syspref)\n";
2660 }
2661
2662 $DBversion = '3.01.00.058';
2663 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2664     $dbh->do("ALTER TABLE `language_subtag_registry` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2665     $dbh->do("ALTER TABLE `language_rfc4646_to_iso639` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2666     $dbh->do("ALTER TABLE `language_descriptions` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2667     SetVersion ($DBversion);
2668     print "Upgrade to $DBversion done (Added primary keys to language tables)\n";
2669 }
2670
2671 $DBversion = '3.01.00.059';
2672 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2673     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type)VALUES('DisplayOPACiconsXSLT', '1', '', 'If ON, displays the format, audience, type icons in XSLT MARC21 results and display pages.', 'YesNo')");
2674     SetVersion ($DBversion);
2675     print "Upgrade to $DBversion done (added DisplayOPACiconsXSLT sysprefs)\n";
2676 }
2677
2678 $DBversion = '3.01.00.060';
2679 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2680     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowAllMessageDeletion','0','Allow any Library to delete any message','','YesNo');");
2681     $dbh->do('DROP TABLE IF EXISTS messages');
2682     $dbh->do("CREATE TABLE messages ( `message_id` int(11) NOT NULL auto_increment,
2683         `borrowernumber` int(11) NOT NULL,
2684         `branchcode` varchar(4) default NULL,
2685         `message_type` varchar(1) NOT NULL,
2686         `message` text NOT NULL,
2687         `message_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
2688         PRIMARY KEY (`message_id`)
2689         ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
2690
2691         print "Upgrade to $DBversion done ( Added AllowAllMessageDeletion syspref and messages table )\n";
2692     SetVersion ($DBversion);
2693 }
2694
2695 $DBversion = '3.01.00.061';
2696 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2697     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('ShowPatronImageInWebBasedSelfCheck', '0', 'If ON, displays patron image when a patron uses web-based self-checkout', '', 'YesNo')");
2698         print "Upgrade to $DBversion done ( Added ShowPatronImageInWebBasedSelfCheck system preference )\n";
2699     SetVersion ($DBversion);
2700 }
2701
2702 $DBversion = "3.01.00.062";
2703 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2704     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'manage_csv_profiles', 'Manage CSV export profiles')");
2705     $dbh->do(q/
2706         CREATE TABLE `export_format` (
2707           `export_format_id` int(11) NOT NULL auto_increment,
2708           `profile` varchar(255) NOT NULL,
2709           `description` mediumtext NOT NULL,
2710           `marcfields` mediumtext NOT NULL,
2711           PRIMARY KEY  (`export_format_id`)
2712         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Used for CSV export';
2713     /);
2714     print "Upgrade to $DBversion done (added csv export profiles)\n";
2715 }
2716
2717 $DBversion = "3.01.00.063";
2718 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2719     $dbh->do("
2720         CREATE TABLE `fieldmapping` (
2721           `id` int(11) NOT NULL auto_increment,
2722           `field` varchar(255) NOT NULL,
2723           `frameworkcode` char(4) NOT NULL default '',
2724           `fieldcode` char(3) NOT NULL,
2725           `subfieldcode` char(1) NOT NULL,
2726           PRIMARY KEY  (`id`)
2727         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2728              ");
2729     SetVersion ($DBversion);print "Upgrade to $DBversion done (Created table fieldmapping)\n";print "Upgrade to 3.01.00.064 done (Version number skipped: nothing done)\n";
2730 }
2731
2732 $DBversion = '3.01.00.065';
2733 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2734     $dbh->do('ALTER TABLE issuingrules ADD COLUMN `renewalsallowed` smallint(6) NOT NULL default "0" AFTER `issuelength`;');
2735     $sth = $dbh->prepare("SELECT itemtype, renewalsallowed FROM itemtypes");
2736     $sth->execute();
2737
2738     my $sthupd = $dbh->prepare("UPDATE issuingrules SET renewalsallowed = ? WHERE itemtype = ?");
2739
2740     while(my $row = $sth->fetchrow_hashref){
2741         $sthupd->execute($row->{renewalsallowed}, $row->{itemtype});
2742     }
2743
2744     $dbh->do('ALTER TABLE itemtypes DROP COLUMN `renewalsallowed`;');
2745
2746     SetVersion ($DBversion);
2747     print "Upgrade to $DBversion done (Moving allowed renewals from itemtypes to issuingrule)\n";
2748 }
2749
2750 $DBversion = '3.01.00.066';
2751 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2752     $dbh->do('ALTER TABLE issuingrules ADD COLUMN `reservesallowed` smallint(6) NOT NULL default "0" AFTER `renewalsallowed`;');
2753
2754     my $maxreserves = C4::Context->preference('maxreserves');
2755     $sth = $dbh->prepare('UPDATE issuingrules SET reservesallowed = ?;');
2756     $sth->execute($maxreserves);
2757
2758     $dbh->do('DELETE FROM systempreferences WHERE variable = "maxreserves";');
2759
2760     $dbh->do("INSERT INTO systempreferences (variable,value, options, explanation, type) VALUES('ReservesControlBranch','PatronLibrary','ItemHomeLibrary|PatronLibrary','Branch checked for members reservations rights','Choice')");
2761
2762     SetVersion ($DBversion);
2763     print "Upgrade to $DBversion done (Moving max allowed reserves from system preference to issuingrule)\n";
2764 }
2765
2766 $DBversion = "3.01.00.067";
2767 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2768     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'batchmod', 'Perform batch modification of items')");
2769     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'batchdel', 'Perform batch deletion of items')");
2770     print "Upgrade to $DBversion done (added permissions for batch modification and deletion)\n";
2771     SetVersion ($DBversion);
2772 }
2773
2774 $DBversion = "3.01.00.068";
2775 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2776         $dbh->do("ALTER TABLE issuingrules ADD COLUMN `finedays` int(11) default NULL AFTER `fine` ");
2777         print "Upgrade to $DBversion done (Adding finedays in issuingrules table)\n";
2778     SetVersion ($DBversion);
2779 }
2780
2781
2782 $DBversion = "3.01.00.069";
2783 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2784         $dbh->do("INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('EnableOpacSearchHistory', '1', '', 'Enable or disable opac search history', 'YesNo')");
2785
2786         my $create = <<SEARCHHIST;
2787 CREATE TABLE IF NOT EXISTS `search_history` (
2788   `userid` int(11) NOT NULL,
2789   `sessionid` varchar(32) NOT NULL,
2790   `query_desc` varchar(255) NOT NULL,
2791   `query_cgi` varchar(255) NOT NULL,
2792   `total` int(11) NOT NULL,
2793   `time` timestamp NOT NULL default CURRENT_TIMESTAMP,
2794   KEY `userid` (`userid`),
2795   KEY `sessionid` (`sessionid`)
2796 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Opac search history results';
2797 SEARCHHIST
2798         $dbh->do($create);
2799
2800         print "Upgrade to $DBversion done (added OPAC search history preference and table)\n";
2801 }
2802
2803 $DBversion = "3.01.00.070";
2804 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2805         $dbh->do("ALTER TABLE authorised_values ADD COLUMN `lib_opac` VARCHAR(80) default NULL AFTER `lib`");
2806         print "Upgrade to $DBversion done (Added a lib_opac field in authorised_values table)\n";
2807 }
2808
2809 $DBversion = "3.01.00.071";
2810 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2811         $dbh->do("ALTER TABLE `subscription` ADD `enddate` date default NULL");
2812         $dbh->do("ALTER TABLE subscriptionhistory CHANGE enddate histenddate DATE default NULL");
2813         print "Upgrade to $DBversion done ( Adding enddate to subscription)\n";
2814 }
2815
2816 # Acquisitions update
2817
2818 $DBversion = "3.01.00.072";
2819 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2820     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacPrivacy', '0', 'if ON, allows patrons to define their privacy rules (reading history)',NULL,'YesNo')");
2821     # create a new syspref for the 'Mr anonymous' patron
2822     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AnonymousPatron', '0', \"Set the identifier (borrowernumber) of the 'Mister anonymous' patron. Used for Suggestion and reading history privacy\",NULL,'')");
2823     # fill AnonymousPatron with AnonymousSuggestion value (copy)
2824     my $sth=$dbh->prepare("SELECT value FROM systempreferences WHERE variable='AnonSuggestions'");
2825     $sth->execute;
2826     my ($value) = $sth->fetchrow() || 0;
2827     $dbh->do("UPDATE systempreferences SET value='$value' WHERE variable='AnonymousPatron'");
2828     # set AnonymousSuggestion do YesNo
2829     # 1st, set the value (1/True if it had a borrowernumber)
2830     $dbh->do("UPDATE systempreferences SET value=1 WHERE variable='AnonSuggestions' AND value>0");
2831     # 2nd, change the type to Choice
2832     $dbh->do("UPDATE systempreferences SET type='YesNo' WHERE variable='AnonSuggestions'");
2833         # borrower reading record privacy : 0 : forever, 1 : laws, 2 : don't keep at all
2834     $dbh->do("ALTER TABLE `borrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
2835     print "Upgrade to $DBversion done (add new syspref and column in borrowers)\n";
2836     SetVersion ($DBversion);
2837 }
2838
2839 $DBversion = '3.01.00.073';
2840 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2841     $dbh->do('SET FOREIGN_KEY_CHECKS=0 ');
2842     $dbh->do(<<'END_SQL');
2843 CREATE TABLE IF NOT EXISTS `aqcontract` (
2844   `contractnumber` int(11) NOT NULL auto_increment,
2845   `contractstartdate` date default NULL,
2846   `contractenddate` date default NULL,
2847   `contractname` varchar(50) default NULL,
2848   `contractdescription` mediumtext,
2849   `booksellerid` int(11) not NULL,
2850     PRIMARY KEY  (`contractnumber`),
2851         CONSTRAINT `booksellerid_fk1` FOREIGN KEY (`booksellerid`)
2852         REFERENCES `aqbooksellers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
2853 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
2854 END_SQL
2855     $dbh->do('SET FOREIGN_KEY_CHECKS=1 ');
2856     print "Upgrade to $DBversion done (adding aqcontract table)\n";
2857     SetVersion ($DBversion);
2858 }
2859
2860 $DBversion = '3.01.00.074';
2861 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2862     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `basketname` varchar(50) default NULL AFTER `basketno`");
2863     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `note` mediumtext AFTER `basketname`");
2864     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `booksellernote` mediumtext AFTER `note`");
2865     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `contractnumber` int(11) AFTER `booksellernote`");
2866     $dbh->do("ALTER TABLE `aqbasket` ADD FOREIGN KEY (`contractnumber`) REFERENCES `aqcontract` (`contractnumber`)");
2867     print "Upgrade to $DBversion done (edit aqbasket table done)\n";
2868     SetVersion ($DBversion);
2869 }
2870
2871 $DBversion = '3.01.00.075';
2872 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2873     $dbh->do("ALTER TABLE `aqorders` ADD COLUMN `uncertainprice` tinyint(1)");
2874
2875     print "Upgrade to $DBversion done (adding uncertainprices)\n";
2876     SetVersion ($DBversion);
2877 }
2878
2879 $DBversion = '3.01.00.076';
2880 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2881     $dbh->do('SET FOREIGN_KEY_CHECKS=0 ');
2882     $dbh->do("CREATE TABLE IF NOT EXISTS `aqbasketgroups` (
2883                          `id` int(11) NOT NULL auto_increment,
2884                          `name` varchar(50) default NULL,
2885                          `closed` tinyint(1) default NULL,
2886                          `booksellerid` int(11) NOT NULL,
2887                          PRIMARY KEY (`id`),
2888                          KEY `booksellerid` (`booksellerid`),
2889                          CONSTRAINT `aqbasketgroups_ibfk_1` FOREIGN KEY (`booksellerid`) REFERENCES `aqbooksellers` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
2890                          ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
2891     $dbh->do("ALTER TABLE aqbasket ADD COLUMN `basketgroupid` int(11)");
2892     $dbh->do("ALTER TABLE aqbasket ADD FOREIGN KEY (`basketgroupid`) REFERENCES `aqbasketgroups` (`id`) ON UPDATE CASCADE ON DELETE SET NULL");
2893     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('pdfformat','pdfformat::layout2pages','Controls what script is used for printing (basketgroups)','','free')");
2894     $dbh->do('SET FOREIGN_KEY_CHECKS=1 ');
2895     print "Upgrade to $DBversion done (adding basketgroups)\n";
2896     SetVersion ($DBversion);
2897 }
2898 $DBversion = '3.01.00.077';
2899 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2900
2901     $dbh->do("SET FOREIGN_KEY_CHECKS=0 ");
2902     # create a mapping table holding the info we need to match orders to budgets
2903     $dbh->do('DROP TABLE IF EXISTS fundmapping');
2904     $dbh->do(
2905         q|CREATE TABLE fundmapping AS
2906         SELECT aqorderbreakdown.ordernumber, branchcode, bookfundid, budgetdate, entrydate
2907         FROM aqorderbreakdown JOIN aqorders ON aqorderbreakdown.ordernumber = aqorders.ordernumber|);
2908     # match the new type of the corresponding field
2909     $dbh->do('ALTER TABLE fundmapping modify column bookfundid varchar(30)');
2910     # System did not ensure budgetdate was valid historically
2911     $dbh->do(q|UPDATE fundmapping SET budgetdate = entrydate WHERE budgetdate = '0000-00-00' OR budgetdate IS NULL|);
2912     # We save the map in fundmapping in case you need later processing
2913     $dbh->do(q|ALTER TABLE fundmapping add column aqbudgetid integer|);
2914     # these can speed processing up
2915     $dbh->do(q|CREATE INDEX fundmaporder ON fundmapping (ordernumber)|);
2916     $dbh->do(q|CREATE INDEX fundmapid ON fundmapping (bookfundid)|);
2917
2918     $dbh->do("DROP TABLE IF EXISTS `aqbudgetperiods` ");
2919
2920     $dbh->do(qq|
2921                     CREATE TABLE `aqbudgetperiods` (
2922                     `budget_period_id` int(11) NOT NULL auto_increment,
2923                     `budget_period_startdate` date NOT NULL,
2924                     `budget_period_enddate` date NOT NULL,
2925                     `budget_period_active` tinyint(1) default '0',
2926                     `budget_period_description` mediumtext,
2927                     `budget_period_locked` tinyint(1) default NULL,
2928                     `sort1_authcat` varchar(10) default NULL,
2929                     `sort2_authcat` varchar(10) default NULL,
2930                     PRIMARY KEY  (`budget_period_id`)
2931                     ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 |);
2932
2933    $dbh->do(<<ADDPERIODS);
2934 INSERT INTO aqbudgetperiods (budget_period_startdate,budget_period_enddate,budget_period_active,budget_period_description,budget_period_locked)
2935 SELECT DISTINCT startdate, enddate, NOW() BETWEEN startdate and enddate, concat(startdate," ",enddate),NOT NOW() BETWEEN startdate AND enddate from aqbudget
2936 ADDPERIODS
2937 # SORRY , NO AQBUDGET/AQBOOKFUND -> AQBUDGETS IMPORT JUST YET,
2938 # BUT A NEW CLEAN AQBUDGETS TABLE CREATE FOR NOW..
2939 # DROP TABLE IF EXISTS `aqbudget`;
2940 #CREATE TABLE `aqbudget` (
2941 #  `bookfundid` varchar(10) NOT NULL default ',
2942 #    `startdate` date NOT NULL default 0,
2943 #         `enddate` date default NULL,
2944 #           `budgetamount` decimal(13,2) default NULL,
2945 #                 `aqbudgetid` tinyint(4) NOT NULL auto_increment,
2946 #                   `branchcode` varchar(10) default NULL,
2947     DropAllForeignKeys('aqbudget');
2948   #$dbh->do("drop table aqbudget;");
2949
2950
2951     my $maxbudgetid = $dbh->selectcol_arrayref(<<IDsBUDGET);
2952 SELECT MAX(aqbudgetid) from aqbudget
2953 IDsBUDGET
2954
2955 $$maxbudgetid[0] = 0 if !$$maxbudgetid[0];
2956
2957     $dbh->do(<<BUDGETAUTOINCREMENT);
2958 ALTER TABLE aqbudget AUTO_INCREMENT=$$maxbudgetid[0]
2959 BUDGETAUTOINCREMENT
2960
2961     $dbh->do(<<BUDGETNAME);
2962 ALTER TABLE aqbudget RENAME `aqbudgets`
2963 BUDGETNAME
2964
2965     $dbh->do(<<BUDGETS);
2966 ALTER TABLE `aqbudgets`
2967    CHANGE  COLUMN aqbudgetid `budget_id` int(11) NOT NULL AUTO_INCREMENT,
2968    CHANGE  COLUMN branchcode `budget_branchcode` varchar(10) default NULL,
2969    CHANGE  COLUMN budgetamount `budget_amount` decimal(28,6) NOT NULL default '0.00',
2970    CHANGE  COLUMN bookfundid   `budget_code` varchar(30) default NULL,
2971    ADD     COLUMN `budget_parent_id` int(11) default NULL,
2972    ADD     COLUMN `budget_name` varchar(80) default NULL,
2973    ADD     COLUMN `budget_encumb` decimal(28,6) default '0.00',
2974    ADD     COLUMN `budget_expend` decimal(28,6) default '0.00',
2975    ADD     COLUMN `budget_notes` mediumtext,
2976    ADD     COLUMN `budget_description` mediumtext,
2977    ADD     COLUMN `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
2978    ADD     COLUMN `budget_amount_sublevel`  decimal(28,6) AFTER `budget_amount`,
2979    ADD     COLUMN `budget_period_id` int(11) default NULL,
2980    ADD     COLUMN `sort1_authcat` varchar(80) default NULL,
2981    ADD     COLUMN `sort2_authcat` varchar(80) default NULL,
2982    ADD     COLUMN `budget_owner_id` int(11) default NULL,
2983    ADD     COLUMN `budget_permission` int(1) default '0';
2984 BUDGETS
2985
2986     $dbh->do(<<BUDGETCONSTRAINTS);
2987 ALTER TABLE `aqbudgets`
2988    ADD CONSTRAINT `aqbudgets_ifbk_1` FOREIGN KEY (`budget_period_id`) REFERENCES `aqbudgetperiods` (`budget_period_id`) ON DELETE CASCADE ON UPDATE CASCADE
2989 BUDGETCONSTRAINTS
2990 #    $dbh->do(<<BUDGETPKDROP);
2991 #ALTER TABLE `aqbudgets`
2992 #   DROP PRIMARY KEY
2993 #BUDGETPKDROP
2994 #    $dbh->do(<<BUDGETPKADD);
2995 #ALTER TABLE `aqbudgets`
2996 #   ADD PRIMARY KEY budget_id
2997 #BUDGETPKADD
2998
2999
3000         my $query_period= $dbh->prepare(qq|SELECT budget_period_id from aqbudgetperiods where budget_period_startdate=? and budget_period_enddate=?|);
3001         my $query_bookfund= $dbh->prepare(qq|SELECT * from aqbookfund where bookfundid=?|);
3002         my $selectbudgets=$dbh->prepare(qq|SELECT * from aqbudgets|);
3003         my $updatebudgets=$dbh->prepare(qq|UPDATE aqbudgets SET budget_period_id= ? , budget_name=?, budget_branchcode=? where budget_id=?|);
3004         $selectbudgets->execute;
3005         while (my $databudget=$selectbudgets->fetchrow_hashref){
3006                 $query_period->execute ($$databudget{startdate},$$databudget{enddate});
3007                 my ($budgetperiodid)=$query_period->fetchrow;
3008                 $query_bookfund->execute ($$databudget{budget_code});
3009                 my $databf=$query_bookfund->fetchrow_hashref;
3010                 my $branchcode=$$databudget{budget_branchcode}||$$databf{branchcode};
3011                 $updatebudgets->execute($budgetperiodid,$$databf{bookfundname},$branchcode,$$databudget{budget_id});
3012         }
3013     $dbh->do(<<BUDGETDROPDATES);
3014 ALTER TABLE `aqbudgets`
3015    DROP startdate,
3016    DROP enddate
3017 BUDGETDROPDATES
3018
3019
3020     $dbh->do("DROP TABLE IF EXISTS `aqbudgets_planning` ");
3021     $dbh->do("CREATE TABLE  `aqbudgets_planning` (
3022                     `plan_id` int(11) NOT NULL auto_increment,
3023                     `budget_id` int(11) NOT NULL,
3024                     `budget_period_id` int(11) NOT NULL,
3025                     `estimated_amount` decimal(28,6) default NULL,
3026                     `authcat` varchar(30) NOT NULL,
3027                     `authvalue` varchar(30) NOT NULL,
3028                                         `display` tinyint(1) DEFAULT 1,
3029                         PRIMARY KEY  (`plan_id`),
3030                         CONSTRAINT `aqbudgets_planning_ifbk_1` FOREIGN KEY (`budget_id`) REFERENCES `aqbudgets` (`budget_id`) ON DELETE CASCADE ON UPDATE CASCADE
3031                         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
3032
3033     $dbh->do("ALTER TABLE `aqorders`
3034                     ADD COLUMN `budget_id` tinyint(4) NOT NULL,
3035                     ADD COLUMN `budgetgroup_id` int(11) NOT NULL,
3036                     ADD COLUMN  `sort1_authcat` varchar(10) default NULL,
3037                     ADD COLUMN  `sort2_authcat` varchar(10) default NULL" );
3038                 # We need to map the orders to the budgets
3039                 # For Historic reasons this is more complex than it should be on occasions
3040                 my $budg_arr = $dbh->selectall_arrayref(
3041                     q|SELECT aqbudgets.budget_id, aqbudgets.budget_code, aqbudgetperiods.budget_period_startdate,
3042                     aqbudgetperiods.budget_period_enddate
3043                     FROM aqbudgets JOIN aqbudgetperiods ON aqbudgets.budget_period_id = aqbudgetperiods.budget_period_id
3044                     ORDER BY budget_code, budget_period_startdate|, { Slice => {} });
3045                 # We arbitarily order on start date, this means if you have overlapping periods the order will be
3046                 # linked to the latest matching budget YMMV
3047                 my $b_sth = $dbh->prepare(
3048                     'UPDATE fundmapping set aqbudgetid = ? where bookfundid =? AND budgetdate >= ? AND budgetdate <= ?');
3049                 for my $b ( @{$budg_arr}) {
3050                     $b_sth->execute($b->{budget_id}, $b->{budget_code}, $b->{budget_period_startdate}, $b->{budget_period_enddate});
3051                 }
3052                 # move the budgetids to aqorders
3053                 $dbh->do(q|UPDATE aqorders, fundmapping SET aqorders.budget_id = fundmapping.aqbudgetid
3054                     WHERE aqorders.ordernumber = fundmapping.ordernumber AND fundmapping.aqbudgetid IS NOT NULL|);
3055                 # NB fundmapping is left as an accontants trail also if you have budgetids that werent set
3056                 # you can decide what to do with them
3057
3058      $dbh->do(
3059          q|UPDATE aqorders, aqbudgets SET aqorders.budgetgroup_id = aqbudgets.budget_period_id
3060          WHERE aqorders.budget_id = aqbudgets.budget_id|);
3061                 # cannot do until aqorderbreakdown removed
3062 #    $dbh->do("DROP TABLE aqbookfund ");
3063 #    $dbh->do("ALTER TABLE aqorders  ADD FOREIGN KEY (`budget_id`) REFERENCES `aqbudgets` (`budget_id`) ON UPDATE CASCADE  " ); ????
3064     $dbh->do("SET FOREIGN_KEY_CHECKS=1 ");
3065
3066     print "Upgrade to $DBversion done (Adding new aqbudgetperiods, aqbudgets and aqbudget_planning tables  )\n";
3067     SetVersion ($DBversion);
3068 }
3069
3070
3071
3072 $DBversion = '3.01.00.078';
3073 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3074     $dbh->do("ALTER TABLE aqbudgetperiods ADD COLUMN budget_period_total decimal(28,6)");
3075     print "Upgrade to $DBversion done (adds 'budget_period_total' column to aqbudgetperiods table)\n";
3076     SetVersion($DBversion);
3077 }
3078
3079
3080 $DBversion = '3.01.00.079';
3081 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3082     $dbh->do("ALTER TABLE currency ADD COLUMN active  tinyint(1)");
3083
3084     print "Upgrade to $DBversion done (adds 'active' column to currencies table)\n";
3085     SetVersion($DBversion);
3086 }
3087
3088 $DBversion = '3.01.00.080';
3089 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3090     $dbh->do(<<BUDG_PERM );
3091 INSERT INTO permissions (module_bit, code, description) VALUES
3092             (11, 'vendors_manage', 'Manage vendors'),
3093             (11, 'contracts_manage', 'Manage contracts'),
3094             (11, 'period_manage', 'Manage periods'),
3095             (11, 'budget_manage', 'Manage budgets'),
3096             (11, 'budget_modify', "Modify budget (can't create lines but can modify existing ones)"),
3097             (11, 'planning_manage', 'Manage budget plannings'),
3098             (11, 'order_manage', 'Manage orders & basket'),
3099             (11, 'group_manage', 'Manage orders & basketgroups'),
3100             (11, 'order_receive', 'Manage orders & basket'),
3101             (11, 'budget_add_del', "Add and delete budgets (but can't modify budgets)");
3102 BUDG_PERM
3103
3104     print "Upgrade to $DBversion done (adds permissions for the acquisitions module)\n";
3105     SetVersion($DBversion);
3106 }
3107
3108
3109 $DBversion = '3.01.00.081';
3110 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3111     $dbh->do("ALTER TABLE aqbooksellers ADD COLUMN `gstrate` decimal(6,4) default NULL");
3112     if (my $gist=C4::Context->preference("gist")){
3113                 my $sql=$dbh->prepare("UPDATE aqbooksellers set `gstrate`=? ");
3114         $sql->execute($gist) ;
3115         }
3116     print "Upgrade to $DBversion done (added per-supplier gstrate setting)\n";
3117     SetVersion($DBversion);
3118 }
3119
3120 $DBversion = "3.01.00.082";
3121 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3122     if (C4::Context->preference("opaclanguages") eq "fr") {
3123         $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')#);
3124     } else {
3125         $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')");
3126     }
3127     print "Upgrade to $DBversion done (adding ReservesNeedReturns systempref, in circulation)\n";
3128     SetVersion ($DBversion);
3129 }
3130
3131 $DBversion = "3.01.00.083";
3132 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3133     $dbh->do(qq|
3134  CREATE TABLE `aqorders_items` (
3135   `ordernumber` int(11) NOT NULL,
3136   `itemnumber` int(11) NOT NULL,
3137   `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
3138   PRIMARY KEY  (`itemnumber`),
3139   KEY `ordernumber` (`ordernumber`)
3140 ) ENGINE=InnoDB DEFAULT CHARSET=utf8   |
3141     );
3142
3143     $dbh->do(qq| DROP TABLE aqorderbreakdown |);
3144     $dbh->do('DROP TABLE aqbookfund');
3145     print "Upgrade to $DBversion done (New aqorders_items table for acqui)\n";
3146     SetVersion ($DBversion);
3147 }
3148
3149 $DBversion = "3.01.00.084";
3150 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3151     $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')  #);
3152
3153     print "Upgrade to $DBversion done (CurrencyFormat syspref added)\n";
3154     SetVersion ($DBversion);
3155 }
3156
3157 $DBversion = "3.01.00.085";
3158 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3159     $dbh->do("ALTER table aqorders drop column title");
3160     $dbh->do("ALTER TABLE `aqorders` CHANGE `budget_id` `budget_id` INT( 11 ) NOT NULL");
3161     print "Upgrade to $DBversion done update budget_id size that should not be a tinyint\n";
3162     SetVersion ($DBversion);
3163 }
3164
3165 $DBversion = "3.01.00.086";
3166 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3167     $dbh->do(<<SUGGESTIONS);
3168 ALTER table suggestions
3169     ADD budgetid INT(11),
3170     ADD branchcode VARCHAR(10) default NULL,
3171     ADD acceptedby INT(11) default NULL,
3172     ADD accepteddate date default NULL,
3173     ADD suggesteddate date default NULL,
3174     ADD manageddate date default NULL,
3175     ADD rejectedby INT(11) default NULL,
3176     ADD rejecteddate date default NULL,
3177     ADD collectiontitle text default NULL,
3178     ADD itemtype VARCHAR(30) default NULL
3179     ;
3180 SUGGESTIONS
3181     print "Upgrade to $DBversion done (Suggestions)\n";
3182     SetVersion ($DBversion);
3183 }
3184
3185 $DBversion = "3.01.00.087";
3186 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3187     $dbh->do("ALTER table aqbudgets drop column budget_amount_sublevel;");
3188     print "Upgrade to $DBversion done (Drop column budget_amount_sublevel from aqbudgets)\n";
3189     SetVersion ($DBversion);
3190 }
3191
3192 $DBversion = "3.01.00.088";
3193 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3194     $dbh->do(  qq# INSERT INTO `systempreferences` VALUES ('intranetbookbag','1','','If ON, enables display of Cart feature in the intranet','YesNo')  #);
3195
3196     print "Upgrade to $DBversion done (intranetbookbag syspref added)\n";
3197     SetVersion ($DBversion);
3198 }
3199
3200 $DBversion = "3.01.00.090";
3201 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3202 $dbh->do("
3203        INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3204                 (16, 'execute_reports', 'Execute SQL reports'),
3205                 (16, 'create_reports', 'Create SQL Reports')
3206         ");
3207
3208     print "Upgrade to $DBversion done (granular permissions for guided reports added)\n";
3209     SetVersion ($DBversion);
3210 }
3211
3212 $DBversion = "3.01.00.091";
3213 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3214 $dbh->do("
3215         UPDATE `systempreferences` SET `options` = 'holdings|serialcollection|subscriptions'
3216         WHERE `systempreferences`.`variable` = 'opacSerialDefaultTab' LIMIT 1
3217         ");
3218
3219     print "Upgrade to $DBversion done (opac-detail default tag updated)\n";
3220     SetVersion ($DBversion);
3221 }
3222
3223 $DBversion = "3.01.00.092";
3224 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3225     if (C4::Context->preference("opaclanguages") =~ /fr/) {
3226         $dbh->do(qq{
3227 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');
3228         });
3229         }else{
3230         $dbh->do(qq{
3231 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');
3232         });
3233         }
3234     print "Upgrade to $DBversion done (Added RoutingListAddReserves syspref)\n";
3235     SetVersion ($DBversion);
3236 }
3237
3238 $DBversion = "3.01.00.093";
3239 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3240         $dbh->do(qq{
3241         ALTER TABLE biblioitems ADD INDEX issn_idx (issn);
3242         });
3243     print "Upgrade to $DBversion done (added index to ISSN)\n";
3244     SetVersion ($DBversion);
3245 }
3246
3247 $DBversion = "3.01.00.094";
3248 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3249         $dbh->do(qq{
3250         ALTER TABLE aqbasketgroups ADD deliveryplace VARCHAR(10) default NULL, ADD deliverycomment VARCHAR(255) default NULL;
3251         });
3252
3253     print "Upgrade to $DBversion done (adding deliveryplace deliverycomment to basketgroups)\n";
3254     SetVersion ($DBversion);
3255 }
3256
3257 $DBversion = "3.01.00.095";
3258 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3259         $dbh->do(qq{
3260         ALTER TABLE items ADD stocknumber VARCHAR(32) DEFAULT NULL COMMENT "stores the inventory number";
3261         });
3262         $dbh->do(qq{
3263         ALTER TABLE items ADD UNIQUE INDEX itemsstocknumberidx (stocknumber);
3264         });
3265         $dbh->do(qq{
3266         ALTER TABLE deleteditems ADD stocknumber VARCHAR(32) DEFAULT NULL COMMENT "stores the inventory number of deleted items";
3267         });
3268         $dbh->do(qq{
3269         ALTER TABLE deleteditems ADD UNIQUE INDEX deleteditemsstocknumberidx (stocknumber);
3270         });
3271         if (C4::Context->preference('marcflavour') eq 'UNIMARC'){
3272                 $dbh->do(qq{
3273         INSERT IGNORE INTO marc_subfield_structure (frameworkcode,tagfield, tagsubfield, tab, repeatable, mandatory,kohafield)
3274         SELECT DISTINCT (frameworkcode),995,"j",10,0,0,"items.stocknumber" from biblio_framework ;
3275                 });
3276                 #Previously, copynumber was used as stocknumber
3277                 $dbh->do(qq{
3278         UPDATE items set stocknumber=copynumber;
3279                 });
3280                 $dbh->do(qq{
3281         UPDATE items set copynumber=NULL;
3282                 });
3283         }
3284     print "Upgrade to $DBversion done (stocknumber field added)\n";
3285     SetVersion ($DBversion);
3286 }
3287
3288 $DBversion = "3.01.00.096";
3289 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3290     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OrderPdfTemplate','','Uploads a PDF template to use for printing baskets','NULL','Upload')");
3291     $dbh->do("UPDATE systempreferences SET variable='OrderPdfFormat' WHERE variable='pdfformat'");
3292     print "Upgrade to $DBversion done (PDF orders system preferences added and updated)\n";
3293     SetVersion ($DBversion);
3294 }
3295
3296 $DBversion = "3.01.00.097";
3297 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3298         $dbh->do(qq{
3299         ALTER TABLE aqbasketgroups ADD billingplace VARCHAR(10) NOT NULL AFTER deliverycomment;
3300         });
3301
3302     print "Upgrade to $DBversion done (Adding billingplace to aqbasketgroups)\n";
3303     SetVersion ($DBversion);
3304 }
3305
3306 $DBversion = "3.01.00.098";
3307 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3308         $dbh->do(qq{
3309         ALTER TABLE auth_subfield_structure MODIFY frameworkcode VARCHAR(10) NULL;
3310         });
3311
3312     print "Upgrade to $DBversion done (changing frameworkcode length in auth_subfield_structure)\n";
3313     SetVersion ($DBversion);
3314 }
3315
3316 $DBversion = "3.01.00.099";
3317 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3318         $dbh->do(qq{
3319                 INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3320                 (9, 'edit_catalogue', 'Edit catalogue'),
3321                 (9, 'fast_cataloging', 'Fast cataloging')
3322         });
3323
3324     print "Upgrade to $DBversion done (granular permissions for cataloging added)\n";
3325     SetVersion ($DBversion);
3326 }
3327
3328 $DBversion = "3.01.00.100";
3329 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3330         $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')");
3331         print "Upgrade to $DBversion done (added CAS authentication system preferences)\n";
3332     SetVersion ($DBversion);
3333 }
3334
3335 $DBversion = "3.01.00.101";
3336 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3337         $dbh->do(
3338         "INSERT INTO systempreferences
3339            (variable, value, options, explanation, type)
3340          VALUES (
3341             'OverdueNoticeBcc', '', '',
3342             'Email address to Bcc outgoing notices sent by email',
3343             'free')
3344          ");
3345         print "Upgrade to $DBversion done (added OverdueNoticeBcc system preferences)\n";
3346     SetVersion ($DBversion);
3347 }
3348 $DBversion = "3.01.00.102";
3349 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3350     $dbh->do(
3351     "UPDATE permissions set description = 'Edit catalog (Modify bibliographic/holdings data)' where module_bit = 9 and code = 'edit_catalogue'"
3352     );
3353         print "Upgrade to $DBversion done (fixed spelling error in edit_catalogue permission)\n";
3354     SetVersion ($DBversion);
3355 }
3356
3357 $DBversion = "3.01.00.103";
3358 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3359         $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES (13, 'moderate_tags', 'Moderate patron tags')");
3360         print "Upgrade to $DBversion done (adding patron permissions for tags tool)\n";
3361     SetVersion ($DBversion);
3362 }
3363
3364 $DBversion = "3.01.00.104";
3365 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3366
3367     my ($maninv_count, $borrnotes_count);
3368     eval { $maninv_count = $dbh->do("SELECT 1 FROM authorised_values WHERE category='MANUAL_INV'"); };
3369     if ($maninv_count == 0) {
3370         $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('MANUAL_INV','Copier Fees','.25')");
3371     }
3372     eval { $borrnotes_count = $dbh->do("SELECT 1 FROM authorised_values WHERE category='BOR_NOTES'"); };
3373     if ($borrnotes_count == 0) {
3374         $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('BOR_NOTES','ADDR','Address Notes')");
3375     }
3376
3377     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('LOC','CART','Book Cart')");
3378     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('LOC','PROC','Processing Center')");
3379
3380         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";
3381         SetVersion ($DBversion);
3382 }
3383
3384
3385 $DBversion = "3.01.00.105";
3386 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3387     $dbh->do("
3388       CREATE TABLE `collections` (
3389         `colId` int(11) NOT NULL auto_increment,
3390         `colTitle` varchar(100) NOT NULL default '',
3391         `colDesc` text NOT NULL,
3392         `colBranchcode` varchar(4) default NULL COMMENT 'branchcode for branch where item should be held.',
3393         PRIMARY KEY  (`colId`)
3394       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3395     ");
3396
3397     $dbh->do("
3398       CREATE TABLE `collections_tracking` (
3399         `ctId` int(11) NOT NULL auto_increment,
3400         `colId` int(11) NOT NULL default '0' COMMENT 'collections.colId',
3401         `itemnumber` int(11) NOT NULL default '0' COMMENT 'items.itemnumber',
3402         PRIMARY KEY  (`ctId`)
3403       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3404     ");
3405     $dbh->do("
3406         INSERT INTO permissions (module_bit, code, description)
3407         VALUES ( 13, 'rotating_collections', 'Manage Rotating collections')" );
3408         print "Upgrade to $DBversion done (added collection and collection_tracking tables for rotating collections functionality)\n";
3409     SetVersion ($DBversion);
3410 }
3411 $DBversion = "3.01.00.106";
3412 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3413         $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' )");
3414         print "Upgrade to $DBversion done (added OpacAddMastheadLibraryPulldown system preferences)\n";
3415     SetVersion ($DBversion);
3416 }
3417
3418 $DBversion = '3.01.00.107';
3419 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3420     my $upgrade_script = C4::Context->config("intranetdir") . "/installer/data/mysql/patroncards_upgrade.pl";
3421     system("perl $upgrade_script");
3422     print "Upgrade to $DBversion done (Migrated labels and patroncards tables and data to new schema.)\n";
3423     SetVersion ($DBversion);
3424 }
3425
3426 $DBversion = '3.01.00.108';
3427 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3428         $dbh->do(qq{
3429     ALTER TABLE `export_format` ADD `csv_separator` VARCHAR( 2 ) NOT NULL AFTER `marcfields` ,
3430     ADD `field_separator` VARCHAR( 2 ) NOT NULL AFTER `csv_separator` ,
3431     ADD `subfield_separator` VARCHAR( 2 ) NOT NULL AFTER `field_separator`
3432     });
3433         print "Upgrade to $DBversion done (added separators for csv export)\n";
3434     SetVersion ($DBversion);
3435 }
3436
3437 $DBversion = "3.01.00.109";
3438 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3439         $dbh->do(qq{
3440         ALTER TABLE `export_format` ADD `encoding` VARCHAR(255) NOT NULL AFTER `subfield_separator`
3441         });
3442         print "Upgrade to $DBversion done (added encoding for csv export)\n";
3443     SetVersion ($DBversion);
3444 }
3445
3446 $DBversion = '3.01.00.110';
3447 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3448     $dbh->do('ALTER TABLE `categories` ADD COLUMN `enrolmentperioddate` DATE NULL DEFAULT NULL AFTER `enrolmentperiod`');
3449     print "Upgrade to $DBversion done (Add enrolment period date support)\n";
3450     SetVersion ($DBversion);
3451 }
3452
3453 $DBversion = '3.01.00.111';
3454 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3455     print "Upgrade to $DBversion done (mark DBrev for 3.2-alpha release)\n";
3456     SetVersion ($DBversion);
3457 }
3458
3459 $DBversion = '3.01.00.112';
3460 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3461         $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');");
3462         print "Upgrade to $DBversion done ( added Show Spine Label Printer on Bib Items Details preferences )\n";
3463     SetVersion ($DBversion);
3464 }
3465
3466 $DBversion = '3.01.00.113';
3467 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3468     my $value = C4::Context->preference("XSLTResultsDisplay");
3469     $dbh->do(
3470         "INSERT INTO systempreferences (variable,value,type)
3471          VALUES('OPACXSLTResultsDisplay',?,'YesNo')", {}, $value ? 1 : 0);
3472     $value = C4::Context->preference("XSLTDetailsDisplay");
3473     $dbh->do(
3474         "INSERT INTO systempreferences (variable,value,type)
3475          VALUES('OPACXSLTDetailsDisplay',?,'YesNo')", {}, $value ? 1 : 0);
3476     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";
3477     SetVersion ($DBversion);
3478 }
3479
3480 $DBversion = '3.01.00.114';
3481 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3482     $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')");
3483     $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')");
3484     $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')");
3485         print "Upgrade to $DBversion done ( Added AutoSelfCheckAllowed, AutoSelfCheckID, and AutoShelfCheckPass system preference )\n";
3486     SetVersion ($DBversion);
3487 }
3488
3489 $DBversion = '3.01.00.115';
3490 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3491     $dbh->do('UPDATE aqorders SET quantityreceived = 0 WHERE quantityreceived IS NULL');
3492     $dbh->do('ALTER TABLE aqorders MODIFY COLUMN quantityreceived smallint(6) NOT NULL DEFAULT 0');
3493         print "Upgrade to $DBversion done ( Default aqorders.quantityreceived to 0 )\n";
3494     SetVersion ($DBversion);
3495 }
3496
3497 $DBversion = '3.01.00.116';
3498 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3499         if (C4::Context->preference('OrderPdfFormat') eq 'pdfformat::example'){
3500                 $dbh->do("UPDATE `systempreferences` set value='pdfformat::layout2pages' WHERE variable='OrderPdfFormat'");
3501         }
3502         print "Upgrade to $DBversion done (corrected default OrderPdfFormat value if still set wrong )\n";
3503     SetVersion ($DBversion);
3504 }
3505
3506 $DBversion = '3.01.00.117';
3507 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3508     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'por' WHERE rfc4646_subtag='pt' ");
3509     print "Upgrade to $DBversion done (corrected ISO 639-2 language code for Portuguese)\n";
3510     SetVersion ($DBversion);
3511 }
3512
3513 $DBversion = '3.01.00.118';
3514 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3515     my ($count) = $dbh->selectrow_array("SELECT count(*) FROM information_schema.columns
3516                                          WHERE table_name = 'aqbudgets_planning'
3517                                          AND column_name = 'display'");
3518     if ($count < 1) {
3519         $dbh->do("ALTER TABLE aqbudgets_planning ADD COLUMN display tinyint(1) DEFAULT 1");
3520     }
3521     print "Upgrade to $DBversion done (bug 4203: add display column to aqbudgets_planning if missing)\n";
3522     SetVersion ($DBversion);
3523 }
3524
3525 $DBversion = '3.01.00.119';
3526 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3527     eval{require Locale::Currency::Format};
3528     if (!$@) {
3529         print "Upgrade to $DBversion done (Locale::Currency::Format installed.)\n";
3530         SetVersion ($DBversion);
3531     }
3532     else {
3533         print "Upgrade to $DBversion done.\n";
3534         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";
3535         SetVersion ($DBversion);
3536     }
3537 }
3538
3539 $DBversion = '3.01.00.120';
3540 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3541     $dbh->do(q{
3542 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');
3543 });
3544     print "Upgrade to $DBversion done (bug 1080: add soundon system preference for circulation sounds)\n";
3545     SetVersion ($DBversion);
3546 }
3547
3548 $DBversion = '3.01.00.121';
3549 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3550     $dbh->do("ALTER TABLE `reserves` ADD `expirationdate` DATE DEFAULT NULL");
3551     $dbh->do("ALTER TABLE `reserves` ADD `lowestPriority` tinyint(1) NOT NULL");
3552     $dbh->do("ALTER TABLE `old_reserves` ADD `expirationdate` DATE DEFAULT NULL");
3553     $dbh->do("ALTER TABLE `old_reserves` ADD `lowestPriority` tinyint(1) NOT NULL");
3554     print "Upgrade to $DBversion done ( Added Additional Fields to Reserves tables )\n";
3555     SetVersion ($DBversion);
3556 }
3557
3558 $DBversion = '3.01.00.122';
3559 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3560     $dbh->do(q{
3561       INSERT INTO systempreferences (variable,value,explanation,options,type)
3562       VALUES ('OAI-PMH:ConfFile', '', 'If empty, Koha OAI Server operates in normal mode, otherwise it operates in extended mode.','','File');
3563 });
3564     print "Upgrade to $DBversion done. — Add a new system preference OAI-PMF:ConfFile\n";
3565     SetVersion ($DBversion);
3566 }
3567
3568 $DBversion = "3.01.00.123";
3569 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3570     $dbh->do("INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3571         (6, 'place_holds', 'Place holds for patrons')");
3572     $dbh->do("INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3573         (6, 'modify_holds_priority', 'Modify holds priority')");
3574     $dbh->do("UPDATE `userflags` SET `flagdesc` = 'Place and modify holds for patrons' WHERE `flag` = 'reserveforothers'");
3575     print "Upgrade to $DBversion done (Add granular permission for holds modification and update description of reserveforothers permission)\n";
3576     SetVersion ($DBversion);
3577 }
3578
3579 $DBversion = '3.01.00.124';
3580 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3581     $dbh->do("
3582         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>>).');
3583     ");
3584     print "Upgrade to $DBversion done (bug 3242: add HOLDPLACED letter template, which is used when emailLibrarianWhenHoldIsPlaced is enabled)\n";
3585     SetVersion ($DBversion);
3586 }
3587
3588 $DBversion = '3.01.00.125';
3589 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3590     $dbh->do("
3591         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' );
3592     ");
3593     $dbh->do("
3594         INSERT INTO message_transport_types (message_transport_type) values ('print');
3595     ");
3596     print "Upgrade to $DBversion done (bug 3482: Printable hold and overdue notices)\n";
3597     SetVersion ($DBversion);
3598 }
3599
3600 $DBversion = "3.01.00.126";
3601 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3602         $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')");
3603         $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')");
3604
3605     print "Upgrade to $DBversion done (Adding ILS-DI updates and ILS-DI:AuthorizedIPs)\n";
3606     SetVersion ($DBversion);
3607 }
3608
3609 $DBversion = '3.01.00.127';
3610 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3611     $dbh->do("ALTER TABLE messages CHANGE branchcode branchcode varchar(10);");
3612     print "Upgrade to $DBversion done (bug 4190: messages in patron account did not work with branchcodes > 4)\n";
3613     SetVersion ($DBversion);
3614 }
3615
3616 $DBversion = '3.01.00.128';
3617 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3618     $dbh->do('CREATE INDEX budget_id ON aqorders (budget_id );');
3619     print "Upgrade to $DBversion done (bug 4331: index orders by budget_id)\n";
3620     SetVersion ($DBversion);
3621 }
3622
3623 $DBversion = "3.01.00.129";
3624 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3625         $dbh->do("UPDATE `permissions` SET `code` = 'items_batchdel' WHERE `permissions`.`module_bit` =13 AND `permissions`.`code` = 'batchdel' LIMIT 1 ;");
3626         $dbh->do("UPDATE `permissions` SET `code` = 'items_batchmod' WHERE `permissions`.`module_bit` =13 AND `permissions`.`code` = 'batchmod' LIMIT 1 ;");
3627         print "Upgrade to $DBversion done (Change permissions names for item batch modification / deletion)\n";
3628
3629     SetVersion ($DBversion);
3630 }
3631
3632 $DBversion = "3.01.00.130";
3633 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3634     $dbh->do("UPDATE reserves SET expirationdate = NULL WHERE expirationdate = '0000-00-00'");
3635     print "Upgrade to $DBversion done (change reserves.expirationdate values of 0000-00-00 to NULL (bug 1532)\n";
3636     SetVersion ($DBversion);
3637 }
3638
3639 $DBversion = "3.01.00.131";
3640 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3641         $dbh->do(q{
3642 INSERT IGNORE INTO message_transport_types (message_transport_type) VALUES ('print'),('feed');
3643     });
3644     print "Upgrade to $DBversion done (adding print and feed message transport types)\n";
3645     SetVersion ($DBversion);
3646 }
3647
3648 $DBversion = "3.01.00.132";
3649 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3650         $dbh->do(q{
3651     ALTER TABLE language_descriptions ADD INDEX subtag_type_lang (subtag, type, lang);
3652     });
3653     print "Upgrade to $DBversion done (Adding index to language_descriptions table)\n";
3654     SetVersion ($DBversion);
3655 }
3656
3657 $DBversion = '3.01.00.133';
3658 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3659     $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')");
3660     print "Upgrade to $DBversion done (bug 4405: added OverduesBlockCirc syspref to control whether circulation is blocked if a borrower has overdues)\n";
3661     SetVersion ($DBversion);
3662 }
3663
3664 $DBversion = '3.01.00.134';
3665 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3666     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('DisplayMultiPlaceHold','1','Display the ability to place multiple holds or not','','YesNo')");
3667     print "Upgrade to $DBversion done (adding syspref DisplayMultiPlaceHold to control whether multiple holds can be placed from the search results page)\n";
3668     SetVersion ($DBversion);
3669 }
3670
3671 $DBversion = '3.01.00.135';
3672 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3673     $dbh->do("
3674         INSERT INTO `letter` (module, code, name, title, content) VALUES
3675 ('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')
3676 ");
3677     print "Upgrade to $DBversion done (bug 4377: added HOLD_PRINT message template)\n";
3678     SetVersion ($DBversion);
3679 }
3680
3681 $DBversion = '3.01.00.136';
3682 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3683     $dbh->do(qq{
3684 INSERT INTO permissions (module_bit, code, description) VALUES
3685    ( 9, 'edit_items', 'Edit Items');});
3686     print "Upgrade to $DBversion done (Adding a new permission to edit items)\n";
3687     SetVersion ($DBversion);
3688 }
3689
3690 $DBversion = "3.01.00.137";
3691 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3692         $dbh->do("
3693           INSERT INTO permissions (module_bit, code, description) VALUES
3694           (15, 'check_expiration', 'Check the expiration of a serial'),
3695           (15, 'claim_serials', 'Claim missing serials'),
3696           (15, 'create_subscription', 'Create a new subscription'),
3697           (15, 'delete_subscription', 'Delete an existing subscription'),
3698           (15, 'edit_subscription', 'Edit an existing subscription'),
3699           (15, 'receive_serials', 'Serials receiving'),
3700           (15, 'renew_subscription', 'Renew a subscription'),
3701           (15, 'routing', 'Routing');
3702                  ");
3703     print "Upgrade to $DBversion done (adding granular permissions for serials)\n";
3704     SetVersion ($DBversion);
3705 }
3706
3707 $DBversion = "3.01.00.138";
3708 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3709     $dbh->do("DELETE FROM systempreferences WHERE variable = 'GranularPermissions'");
3710     print "Upgrade to $DBversion done (bug 4896: removing GranularPermissions syspref; use of granular permissions is now the default)\n";
3711     SetVersion ($DBversion);
3712 }
3713
3714 $DBversion = '3.01.00.139';
3715 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3716     $dbh->do("ALTER TABLE message_attributes CHANGE message_name message_name varchar(40);");
3717     print "Upgrade to $DBversion done (bug 3682: change message_name from varchar(20) to varchar(40))\n";
3718     SetVersion ($DBversion);
3719 }
3720
3721 $DBversion = '3.01.00.140';
3722 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3723     $dbh->do("UPDATE systempreferences SET value = '0' WHERE variable = 'TagsModeration' AND value is NULL");
3724     print "Upgrade to $DBversion done (bug 4312 TagsModeration changed from NULL to 0)\n";
3725     SetVersion ($DBversion);
3726 }
3727
3728 $DBversion = '3.01.00.141';
3729 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3730     $dbh->do(qq{DELETE FROM message_attributes WHERE message_attribute_id=3;});
3731     $dbh->do(qq{DELETE FROM letter WHERE code='EVENT' AND title='Upcoming Library Event';});
3732     print "Upgrade to $DBversion done Remove upcoming events messaging option (bug 2434)\n";
3733     SetVersion ($DBversion);
3734 }
3735
3736 $DBversion = '3.01.00.142';
3737 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3738     $dbh->do(qq{DELETE FROM message_transports WHERE message_attribute_id=3;});
3739     print "Upgrade to $DBversion done (Remove upcoming events messaging option part 2 (bug 2434))\n";
3740     SetVersion ($DBversion);
3741 }
3742
3743 $DBversion = '3.01.00.143';
3744 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3745     $dbh->do(qq{CREATE INDEX auth_value_idx ON authorised_values (authorised_value)});
3746     $dbh->do(qq{CREATE INDEX auth_val_cat_idx ON borrower_attribute_types (authorised_value_category)});
3747     print "Upgrade to $DBversion done (Create index on authorised_values and borrower_attribute_types (bug 4139))\n";
3748     SetVersion ($DBversion);
3749 }
3750
3751 $DBversion = '3.01.00.144';
3752 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3753     $dbh->do(qq{UPDATE systempreferences SET value='normal' where value='default' and variable='IntranetBiblioDefaultView'});
3754     print "Upgrade to $DBversion done (Update the 'default' to 'normal' for the IntranetBiblioDefaultView syspref (bug 5007))\n";
3755     SetVersion ($DBversion);
3756 }
3757
3758 $DBversion = "3.01.00.145";
3759 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3760     $dbh->do("ALTER TABLE borrowers ADD KEY `guarantorid` (guarantorid);");
3761     print "Upgrade to $DBversion done (Add index on guarantorid)\n";
3762     SetVersion ($DBversion);
3763 }
3764
3765 $DBversion = '3.01.00.999';
3766 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3767     print "Upgrade to $DBversion done (3.2.0 release candidate)\n";
3768     SetVersion ($DBversion);
3769 }
3770
3771 $DBversion = "3.02.00.000";
3772 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3773     my $value = $dbh->selectrow_array("SELECT value FROM systempreferences WHERE variable = 'HomeOrHoldingBranch'");
3774     $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');");
3775     print "Upgrade to $DBversion done (Add HomeOrHoldingBranchReturn system preference)\n";
3776     SetVersion ($DBversion);
3777 }
3778
3779 $DBversion = "3.02.00.001";
3780 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3781     $dbh->do(q{DELETE FROM systempreferences WHERE variable IN (
3782                 'holdCancelLength',
3783                 'PINESISBN',
3784                 'sortbynonfiling',
3785                 'TemplateEncoding',
3786                 'OPACSubscriptionDisplay',
3787                 'OPACDisplayExtendedSubInfo',
3788                 'OAI-PMH:Set',
3789                 'OAI-PMH:Subset',
3790                 'libraryAddress',
3791                 'kohaspsuggest',
3792                 'OrderPdfTemplate',
3793                 'marc',
3794                 'acquisitions',
3795                 'MIME')
3796                }
3797     );
3798     print "Upgrade to $DBversion done (bug 3756: remove disused system preferences)\n";
3799     SetVersion ($DBversion);
3800 }
3801
3802 $DBversion = "3.02.00.002";
3803 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3804     $dbh->do(q{DELETE FROM systempreferences WHERE variable = 'OpacPrivacy'});
3805     print "Upgrade to $DBversion done (bug 3881: remove unused OpacPrivacy system preference)\n";
3806     SetVersion ($DBversion);
3807 }
3808
3809 $DBversion = "3.02.00.003";
3810 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3811     $dbh->do(q{UPDATE systempreferences SET variable = 'ILS-DI:AuthorizedIPs' WHERE variable = 'ILS-DI:Authorized_IPs'});
3812     print "Upgrade to $DBversion done (correct ILS-DI:AuthorizedIPs)\n";
3813     SetVersion ($DBversion);
3814 }
3815
3816 $DBversion = "3.02.00.004";
3817 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3818     print "Upgrade to $DBversion done (3.2.0 general release)\n";
3819     SetVersion ($DBversion);
3820 }
3821 # This is the point where 3.2.x and master diverged, we can use $original_version to make sure we don't
3822
3823 # apply updates that have already been done
3824
3825 $DBversion = "3.03.00.001";
3826 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.005")) {
3827     $dbh->do("DELETE FROM subscriptionroutinglist WHERE borrowernumber IS NULL;");
3828     $dbh->do("ALTER TABLE subscriptionroutinglist MODIFY COLUMN `borrowernumber` int(11) NOT NULL;");
3829     $dbh->do("DELETE FROM subscriptionroutinglist WHERE subscriptionid IS NULL;");
3830     $dbh->do("ALTER TABLE subscriptionroutinglist MODIFY COLUMN `subscriptionid` int(11) NOT NULL;");
3831     $dbh->do("CREATE TEMPORARY TABLE del_subscriptionroutinglist
3832               SELECT s1.routingid FROM subscriptionroutinglist s1
3833               WHERE EXISTS (SELECT * FROM subscriptionroutinglist s2
3834                             WHERE s2.borrowernumber = s1.borrowernumber
3835                             AND   s2.subscriptionid = s1.subscriptionid
3836                             AND   s2.routingid < s1.routingid);");
3837     $dbh->do("DELETE FROM subscriptionroutinglist
3838               WHERE routingid IN (SELECT routingid FROM del_subscriptionroutinglist);");
3839     $dbh->do("ALTER TABLE subscriptionroutinglist ADD UNIQUE (subscriptionid, borrowernumber);");
3840     $dbh->do("ALTER TABLE subscriptionroutinglist
3841                 ADD CONSTRAINT `subscriptionroutinglist_ibfk_1` FOREIGN KEY (`borrowernumber`)
3842                 REFERENCES `borrowers` (`borrowernumber`)
3843                 ON DELETE CASCADE ON UPDATE CASCADE");
3844     $dbh->do("ALTER TABLE subscriptionroutinglist
3845                 ADD CONSTRAINT `subscriptionroutinglist_ibfk_2` FOREIGN KEY (`subscriptionid`)
3846                 REFERENCES `subscription` (`subscriptionid`)
3847                 ON DELETE CASCADE ON UPDATE CASCADE");
3848     print "Upgrade to $DBversion done (Make subscriptionroutinglist more strict)\n";
3849     SetVersion ($DBversion);
3850 }
3851
3852 $DBversion = '3.03.00.002';
3853 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.006")) {
3854     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='arm' WHERE rfc4646_subtag='hy';");
3855     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='eng' WHERE rfc4646_subtag='en';");
3856     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'fi','fin');");
3857     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='fre' WHERE rfc4646_subtag='fr';");
3858     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'lo','lao');");
3859     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='ita' WHERE rfc4646_subtag='it';");
3860     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'sr','srp');");
3861     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'tet','tet');");
3862     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'ur','urd');");
3863
3864     print "Upgrade to $DBversion done (Correct language mappings)\n";
3865     SetVersion ($DBversion);
3866 }
3867
3868 $DBversion = '3.03.00.003';
3869 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.007")) {
3870     $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');");
3871     print "Upgrade to $DBversion done (Add UseTablesortForCirc syspref)\n";
3872     SetVersion ($DBversion);
3873 }
3874
3875 $DBversion = '3.03.00.004';
3876 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.001")) {
3877     my $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'ACCEPTED');
3878     $dbh->do(q/
3879 INSERT INTO `letter`
3880 (module, code, name, title, content)
3881 VALUES
3882 ('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>>')
3883 /) unless $count > 0;
3884     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'AVAILABLE');
3885     $dbh->do(q/
3886 INSERT INTO `letter`
3887 (module, code, name, title, content)
3888 VALUES
3889 ('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>>')
3890 /) unless $count > 0;
3891     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'ORDERED');
3892     $dbh->do(q/
3893 INSERT INTO `letter`
3894 (module, code, name, title, content)
3895 VALUES
3896 ('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>>')
3897 /) unless $count > 0;
3898     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'REJECTED');
3899     $dbh->do(q/
3900 INSERT INTO `letter`
3901 (module, code, name, title, content)
3902 VALUES
3903 ('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>>')
3904 /) unless $count > 0;
3905     print "Upgrade to $DBversion done (bug 5127: add default templates for suggestion status change notifications)\n";
3906     SetVersion ($DBversion);
3907 };
3908
3909 $DBversion = '3.03.00.005';
3910 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3911     $dbh->do("update `systempreferences` set options='whitespace|T-prefix|cuecat|libsuite8' where variable='itemBarcodeInputFilter'");
3912     print "Upgrade to $DBversion done (Add itemBarcodeInputFilter choice libsuite8)\n";
3913 }
3914
3915 $DBversion = '3.03.00.006';
3916 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.002")) {
3917     $dbh->do("ALTER TABLE deletedborrowers ADD `privacy` int(11) AFTER smsalertnumber;");
3918     $dbh->do("ALTER TABLE deletedborrowers CHANGE `cardnumber` `cardnumber` varchar(16);");
3919     print "Upgrade to $DBversion done (Fix differences between borrowers and deletedborrowers)\n";
3920     SetVersion ($DBversion);
3921 }
3922
3923 $DBversion = '3.03.00.007';
3924 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3925     $dbh->do("ALTER table suggestions ADD quantity SMALLINT(6) default NULL,
3926                 ADD currency VARCHAR(3) default NULL,
3927                 ADD price DECIMAL(28,6) default NULL,
3928                 ADD total DECIMAL(28,6) default NULL;
3929                 ");
3930     print "Upgrade to $DBversion done (Added acq related columns to suggestions)\n";
3931     SetVersion ($DBversion);
3932 }
3933
3934 $DBversion = '3.03.00.008';
3935 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3936     $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')");
3937     print "Upgrade to $DBversion done (adding syspref OPACNoResultsFound to control what displays when no results are found for a search in the OPAC.)\n";
3938     SetVersion ($DBversion);
3939 }
3940
3941 $DBversion = '3.03.00.009';
3942 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.003")) {
3943     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('IntranetUserCSS','','Add CSS to be included in the Intranet',NULL,'free')");
3944     print "Upgrade to $DBversion done (Add IntranetUserCSS syspref)\n";
3945     SetVersion ($DBversion);
3946 }
3947
3948 $DBversion = "3.03.00.010";
3949 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.02.001")) {
3950     $dbh->do("UPDATE `marc_subfield_structure` SET liblibrarian = 'Distance from earth' WHERE liblibrarian = 'Distrance from earth' AND tagfield = '034' AND tagsubfield = 'r';");
3951     $dbh->do("UPDATE `marc_subfield_structure` SET libopac = 'Distance from earth' WHERE libopac = 'Distrance from earth' AND tagfield = '034' AND tagsubfield = 'r';");
3952     print "Upgrade to $DBversion done (Fix misspelled 034r subfield in MARC21 Frameworks)\n";
3953     SetVersion ($DBversion);
3954 }
3955
3956 $DBversion = "3.03.00.011";
3957 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3958     $dbh->do("UPDATE aqbooksellers SET gstrate=NULL WHERE gstrate=0.0");
3959     print "Upgrade to $DBversion done (Bug 5186: allow GST rate to be set to 0)\n";
3960     SetVersion ($DBversion);
3961 }
3962
3963 $DBversion = "3.03.00.012";
3964 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3965    $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')");
3966    print "Upgrade to $DBversion done (Bug 2142: maxItemsInSearchResults syspref resurrected)\n";
3967    SetVersion ($DBversion);
3968 }
3969
3970 $DBversion = "3.03.00.013";
3971 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3972     $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')");
3973     print "Upgrade to $DBversion done (added 'OpacPublic' syspref)\n";
3974    SetVersion ($DBversion);
3975 }
3976
3977 $DBversion = "3.03.00.014";
3978 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3979     $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')");
3980     $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')");
3981     $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')");
3982     print "Upgrade to $DBversion done (Add flexible shelf browser constraints)\n";
3983     SetVersion ($DBversion);
3984 }
3985
3986 $DBversion = "3.03.00.015";
3987 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3988     if ( C4::Context->preference("marcflavour") eq "MARC21" ) {
3989         my $sth = $dbh->prepare(
3990 "INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`,
3991                              `tab`, `authorised_value`, `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`)
3992                              VALUES ( ?, '9', '9 (RLIN)', '9 (RLIN)', 0, 0, '', 6, '', '', '', 0, -5, '', '', '', NULL)"
3993         );
3994         $sth->execute('648');
3995         $sth->execute('654');
3996         $sth->execute('655');
3997         $sth->execute('656');
3998         $sth->execute('657');
3999         $sth->execute('658');
4000         $sth->execute('662');
4001         $sth->finish;
4002         print
4003 "Upgrade to $DBversion done (Bug 5619: Add subfield 9 to marc21 648,654,655,656,657,658,662)\n";
4004     }
4005     SetVersion($DBversion);
4006 }
4007
4008 $DBversion = '3.03.00.016';
4009 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4010     # reimplement OpacPrivacy system preference
4011     $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')");
4012     $dbh->do("ALTER TABLE `borrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
4013     $dbh->do("ALTER TABLE `deletedborrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
4014     print "Upgrade to $DBversion done (OpacPrivacy reimplementation)\n";
4015     SetVersion($DBversion);
4016 };
4017
4018 $DBversion = '3.03.00.017';
4019 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.001")) {
4020     $dbh->do("ALTER TABLE  `currency` CHANGE `rate` `rate` FLOAT( 15, 5 ) NULL DEFAULT NULL;");
4021     print "Upgrade to $DBversion done (Enable currency rates >= 100)\n";
4022     SetVersion ($DBversion);
4023 }
4024
4025 $DBversion = '3.03.00.018';
4026 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.002")) {
4027     $dbh->do( q|update language_descriptions set description = 'Nederlands' where lang = 'nl' and subtag = 'nl'|);
4028     $dbh->do( q|update language_descriptions set description = 'Dansk' where lang = 'da' and subtag = 'da'|);
4029     print "Upgrade to $DBversion done (Correct language descriptions)\n";
4030     SetVersion ($DBversion);
4031 }
4032
4033 $DBversion = '3.03.00.019';
4034 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.003")) {
4035     # Fix bokmål
4036     $dbh->do("UPDATE language_subtag_registry SET description = 'Norwegian bokm&#229;l' WHERE subtag = 'nb';");
4037     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'nb','nob');");
4038     $dbh->do("UPDATE language_descriptions SET description = 'Norsk bokm&#229;l' WHERE subtag = 'nb' AND lang = 'nb';");
4039     $dbh->do("UPDATE language_descriptions SET description = 'Norwegian bokm&#229;l' WHERE subtag = 'nb' AND lang = 'en';");
4040     $dbh->do("UPDATE language_descriptions SET description = 'Norvégien bokm&#229;l' WHERE subtag = 'nb' AND lang = 'fr';");
4041     # Add nynorsk
4042     $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'nn', 'language', 'Norwegian nynorsk','2011-02-14' )");
4043     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'nn','nno')");
4044     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'nb', 'Norsk nynorsk')");
4045     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'nn', 'Norsk nynorsk')");
4046     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'en', 'Norwegian nynorsk')");
4047     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'fr', 'Norvégien nynorsk')");
4048     print "Upgrade to $DBversion done (Correct language descriptions for Norwegian)\n";
4049     SetVersion ($DBversion);
4050 }
4051
4052 $DBversion = '3.03.00.020';
4053 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4054     $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')");
4055     $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')");
4056     print "Upgrade to $DBversion done (Bug 5811: Add sysprefs controlling overriding fines)\n";
4057     SetVersion($DBversion);
4058 };
4059
4060 $DBversion = '3.03.00.021';
4061 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.001")) {
4062     $dbh->do("ALTER TABLE items MODIFY enumchron TEXT");
4063     $dbh->do("ALTER TABLE deleteditems MODIFY enumchron TEXT");
4064     print "Upgrade to $DBversion done (bug 5642: longer serial enumeration)\n";
4065     SetVersion ($DBversion);
4066 }
4067
4068 $DBversion = '3.03.00.022';
4069 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4070     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('AuthoritiesLog','0','If ON, log edit/create/delete actions on authorities.','','YesNo');");
4071     print "Upgrade to $DBversion done (Add AuthoritiesLog syspref)\n";
4072     SetVersion ($DBversion);
4073 }
4074
4075 # due to a mismatch in kohastructure.sql some koha will have missing columns in aqbasketgroup
4076 # this attempts to fix that
4077 $DBversion = '3.03.00.023';
4078 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.002")) {
4079     my $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'billingplace'");
4080     $sth->execute;
4081     $dbh->do("ALTER TABLE aqbasketgroups ADD billingplace VARCHAR(10)") if ! $sth->fetchrow_hashref;
4082     $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'deliveryplace'");
4083     $sth->execute;
4084     $dbh->do("ALTER TABLE aqbasketgroups ADD deliveryplace VARCHAR(10)") if ! $sth->fetchrow_hashref;
4085     $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'deliverycomment'");
4086     $sth->execute;
4087     $dbh->do("ALTER TABLE aqbasketgroups ADD deliverycomment VARCHAR(255)") if ! $sth->fetchrow_hashref;
4088     print "Upgrade to $DBversion done (Reconcile aqbasketgroups)\n";
4089     SetVersion ($DBversion);
4090 }
4091
4092 $DBversion = '3.03.00.024';
4093 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4094     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('TraceCompleteSubfields','0','Force subject tracings to only match complete subfields.','0','YesNo')");
4095     $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')");
4096     print "Upgrade to $DBversion done (Add syspref to force whole-subfield matching on subject tracings)\n";
4097     SetVersion($DBversion);
4098 };
4099
4100 $DBversion = "3.03.00.025";
4101 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4102     $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')");
4103     print "Upgrade to $DBversion done (Add syspref to control if user can choose pickup branch for holds)\n";
4104     SetVersion ($DBversion);
4105 }
4106
4107 $DBversion = '3.03.00.026';
4108 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.003")) {
4109     $dbh->do("UPDATE `message_attributes` SET message_name='Item Due' WHERE message_attribute_id=1 AND message_name LIKE 'Item DUE'");
4110         print "Upgrade to $DBversion done ( fix capitalization in message type )\n";
4111     SetVersion ($DBversion);
4112 }
4113
4114 $DBversion = '3.03.00.027';
4115 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4116     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('displayFacetCount', '0', NULL, NULL, 'YesNo')");
4117     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('maxRecordsForFacets', '20', NULL, NULL, 'Integer')");
4118     print "Upgrade to $DBversion done (Preferences for facet count)\n";
4119     SetVersion ($DBversion);
4120 }
4121
4122 $DBversion = "3.03.00.028";
4123 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4124     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('FacetLabelTruncationLength', 20, 'Truncate facets length to','','free')");
4125     print "Upgrade to $DBversion done (Add FacetLabelTruncationLength syspref to control facets displayed length)\n";
4126     SetVersion ($DBversion);
4127 }
4128
4129 $DBversion = "3.03.00.029";
4130 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4131     $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')");
4132     print "Upgrade to $DBversion done (Add syspref to control if user can choose branch when making purchase suggestion)\n";
4133     SetVersion ($DBversion);
4134 }
4135
4136 $DBversion = "3.03.00.030";
4137 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4138     $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')");
4139     $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')");
4140     print "Upgrade to $DBversion done (Add sysprefs to control custom favicons)\n";
4141     SetVersion ($DBversion);
4142 }
4143
4144 $DBversion = "3.03.00.031";
4145 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4146     $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');");
4147     print "Upgrade to $DBversion done (Add syspref FineNotifyAtCheckin)\n";
4148     SetVersion ($DBversion);
4149 }
4150
4151 $DBversion = '3.03.00.032';
4152 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4153     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('TraceSubjectSubdivisions', 1, 'Create searches on all subdivisions for subject tracings.','1','YesNo')");
4154     print "Upgrade to $DBversion done ( include subdivisions when generating subject tracing searches )\n";
4155 }
4156
4157
4158 $DBversion = '3.03.00.033';
4159 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4160     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('StaffAuthorisedValueImages', '1', '', NULL, 'YesNo')");
4161     print "Upgrade to $DBversion done (System pref StaffAuthorisedValueImages)\n";
4162     SetVersion ($DBversion);
4163 }
4164
4165 $DBversion = '3.03.00.034';
4166 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4167     $dbh->do("ALTER TABLE `categories` ADD `hidelostitems` tinyint(1) NOT NULL default '0' AFTER `reservefee`");
4168     print "Upgrade to $DBversion done (Add hidelostitems preference to borrower categories)\n";
4169     SetVersion ($DBversion);
4170 }
4171
4172 $DBversion = '3.03.00.035';
4173 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4174     $dbh->do("ALTER TABLE `issuingrules` ADD hardduedate date default NULL AFTER issuelength");
4175     $dbh->do("ALTER TABLE `issuingrules` ADD hardduedatecompare tinyint NOT NULL default 0 AFTER hardduedate");
4176     my $duedate;
4177     if (C4::Context->preference("globalDueDate")) {
4178       $duedate = eval { output_pref( { dt => dt_from_string( C4::Context->preference("globalDueDate") ), dateonly => 1, dateformat => 'iso' } ); };
4179       $dbh->do("UPDATE `issuingrules` SET hardduedate = '$duedate', hardduedatecompare = 0");
4180     } elsif (C4::Context->preference("ceilingDueDate")) {
4181       $duedate = eval { output_pref( { dt => dt_from_string( C4::Context->preference("ceilingDueDate") ), dateonly => 1, dateformat => 'iso' } ); };
4182       $dbh->do("UPDATE `issuingrules` SET hardduedate = '$duedate', hardduedatecompare = -1");
4183     }
4184     $dbh->do("DELETE FROM `systempreferences` WHERE variable = 'globalDueDate' OR variable = 'ceilingDueDate'");
4185     print "Upgrade to $DBversion done (Move global and ceiling due dates to Circ Rules level)\n";
4186     SetVersion ($DBversion);
4187 }
4188
4189 $DBversion = '3.03.00.036';
4190 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4191     $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')");
4192     print "Upgrade to $DBversion done ( Make COinS optional in OPAC search results )\n";
4193     SetVersion ($DBversion);
4194 }
4195
4196 $DBversion = '3.03.00.037';
4197 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4198     $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')");
4199     $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')");
4200     print "Upgrade to $DBversion done (Add 'Display856uAsImage' and 'OPACDisplay856uAsImage' syspref)\n";
4201     SetVersion ($DBversion);
4202 }
4203
4204 $DBversion = '3.03.00.038';
4205 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4206     $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')");
4207     $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')");
4208     $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')");
4209     print "Upgrade to $DBversion done ( Add Self-checkout by Login system preferences )\n";
4210 }
4211
4212 $DBversion = "3.03.00.039";
4213 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4214     $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');");
4215     print "Upgrade to $DBversion done (Add syspref ShowReviewer)\n";
4216 }
4217
4218 $DBversion = "3.03.00.040";
4219 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4220     $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');");
4221     print "Upgrade to $DBversion done (Add syspref UseControlNumber)\n";
4222 }
4223
4224 $DBversion = "3.03.00.041";
4225 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4226     $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')");
4227     $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')");
4228     print "Upgrade to $DBversion done (Add sysprefs to control alternate holdings information display)\n";
4229     SetVersion ($DBversion);
4230 }
4231
4232 $DBversion = '3.03.00.042';
4233 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4234     stocknumber_checker();
4235     print "Upgrade to $DBversion done (5860 Index itemstocknumber)\n";
4236     SetVersion ($DBversion);
4237 }
4238
4239 sub stocknumber_checker { #code reused later on
4240   my @row;
4241   #drop the obsolete itemSStocknumber idx if it exists
4242   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemsstocknumberidx'");
4243   $dbh->do("ALTER TABLE `items` DROP INDEX `itemsstocknumberidx`;") if @row;
4244
4245   #check itemstocknumber idx; remove it if it is unique
4246   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemstocknumberidx' AND non_unique=0");
4247   $dbh->do("ALTER TABLE `items` DROP INDEX `itemstocknumberidx`;") if @row;
4248
4249   #add itemstocknumber index non-unique IF it still not exists
4250   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemstocknumberidx'");
4251   $dbh->do("ALTER TABLE items ADD INDEX itemstocknumberidx (stocknumber);") unless @row;
4252 }
4253
4254 $DBversion = "3.03.00.043";
4255 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4256
4257     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib,lib_opac) VALUES ('YES_NO','0','No','No')");
4258     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib,lib_opac) VALUES ('YES_NO','1','Yes','Yes')");
4259
4260         print "Upgrade to $DBversion done ( add generic boolean YES_NO authorised_values pair )\n";
4261         SetVersion ($DBversion);
4262 }
4263
4264 $DBversion = '3.03.00.044';
4265 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4266     $dbh->do("ALTER TABLE `aqbasketgroups` ADD `freedeliveryplace` TEXT NULL AFTER `deliveryplace`;");
4267     print "Upgrade to $DBversion done (adding freedeliveryplace to basketgroups)\n";
4268 }
4269
4270 $DBversion = '3.03.00.045';
4271 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4272     #Remove obsolete columns from aqbooksellers if needed
4273     my $a = $dbh->selectall_hashref('SHOW columns from aqbooksellers','Field');
4274     my $sqldrop="ALTER TABLE aqbooksellers DROP COLUMN ";
4275     foreach(qw/deliverydays followupdays followupscancel invoicedisc nocalc specialty/) {
4276       $dbh->do($sqldrop.$_) if exists $a->{$_};
4277     }
4278     #Remove obsolete column from aqbudgets if needed
4279     #The correct column is budget_notes
4280     $a = $dbh->selectall_hashref('SHOW columns from aqbudgets','Field');
4281     if(exists $a->{budget_description}) {
4282       $dbh->do("ALTER TABLE aqbudgets DROP COLUMN budget_description");
4283     }
4284     print "Upgrade to $DBversion done (Remove obsolete columns from aqbooksellers and aqbudgets if needed)\n";
4285     SetVersion ($DBversion);
4286 }
4287
4288 $DBversion = "3.03.00.046";
4289 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4290     $dbh->do("ALTER TABLE overduerules ALTER delay1 SET DEFAULT NULL, ALTER delay2 SET DEFAULT NULL, ALTER delay3 SET DEFAULT NULL");
4291     print "Upgrade to $DBversion done (Setting NULL default value for delayn columns in table overduerules)\n";
4292     SetVersion($DBversion);
4293 }
4294
4295 $DBversion = '3.03.00.047';
4296 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4297     $dbh->do("ALTER TABLE borrowers ADD `state` mediumtext AFTER city;");
4298     $dbh->do("ALTER TABLE borrowers ADD `B_state` mediumtext AFTER B_city;");
4299     $dbh->do("ALTER TABLE borrowers ADD `altcontactstate` mediumtext AFTER altcontactaddress3;");
4300     $dbh->do("ALTER TABLE deletedborrowers ADD `state` mediumtext AFTER city;");
4301     $dbh->do("ALTER TABLE deletedborrowers ADD `B_state` mediumtext AFTER B_city;");
4302     $dbh->do("ALTER TABLE deletedborrowers ADD `altcontactstate` mediumtext AFTER altcontactaddress3;");
4303     print "Upgrade to $DBversion done (Add state field to patron's addresses)\n";
4304 }
4305
4306 $DBversion = '3.03.00.048';
4307 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4308     $dbh->do("ALTER TABLE branches ADD `branchstate` mediumtext AFTER `branchcity`;");
4309     print "Upgrade to $DBversion done (Add state to branch address)\n";
4310     SetVersion ($DBversion);
4311 }
4312
4313 $DBversion = '3.03.00.049';
4314 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4315     $dbh->do("ALTER TABLE `accountlines` ADD `note` text NULL default NULL");
4316     $dbh->do("ALTER TABLE `accountlines` ADD `manager_id` int( 11 ) NULL ");
4317     print "Upgrade to $DBversion done (adding note and manager_id fields in accountlines table)\n";
4318     SetVersion($DBversion);
4319 }
4320
4321 $DBversion = "3.03.00.050";
4322 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4323     $dbh->do("
4324         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');
4325         ");
4326     print "Upgrade to $DBversion done (Adding OpacHiddenItems syspref)\n";
4327     SetVersion($DBversion);
4328 }
4329
4330 $DBversion = "3.03.00.051";
4331 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4332     print "Upgrade to $DBversion done (Remove spaces and dashes from message_attribute names)\n";
4333     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Due' WHERE message_name='Item Due'");
4334     $dbh->do("UPDATE message_attributes SET message_name = 'Advance_Notice' WHERE message_name='Advance Notice'");
4335     $dbh->do("UPDATE message_attributes SET message_name = 'Hold_Filled' WHERE message_name='Hold Filled'");
4336     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Check_in' WHERE message_name='Item Check-in'");
4337     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Checkout' WHERE message_name='Item Checkout'");
4338     SetVersion ($DBversion);
4339 }
4340
4341 $DBversion = "3.03.00.052";
4342 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4343     $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');");
4344     print "Upgrade to $DBversion done (Add syspref WaitingNotifyAtCheckin)\n";
4345     SetVersion ($DBversion);
4346 }
4347
4348 $DBversion = "3.04.00.000";
4349 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4350     print "Upgrade to $DBversion done Koha 3.4.0 release \n";
4351     SetVersion ($DBversion);
4352 }
4353
4354 $DBversion = "3.05.00.001";
4355 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4356     $dbh->do(qq{
4357     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');
4358     });
4359     print "Upgrade to $DBversion done (Adds New System preference numSearchRSSResults)\n";
4360     SetVersion($DBversion);
4361 }
4362
4363 $DBversion = '3.05.00.002';
4364 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4365     #follow up fix 5860: some installs already past 3.3.0.42
4366     stocknumber_checker();
4367     print "Upgrade to $DBversion done (Fix for stocknumber index)\n";
4368     SetVersion ($DBversion);
4369 }
4370
4371 $DBversion = "3.05.00.003";
4372 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4373     $dbh->do(qq{
4374     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');
4375     });
4376     print "Upgrade to $DBversion done (Adds New System preference OpacRenewalBranch)\n";
4377     SetVersion($DBversion);
4378 }
4379
4380 $DBversion = "3.05.00.004";
4381 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4382     $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');");
4383     print "Upgrade to $DBversion done (Add syspref ShowReviewerPhoto)\n";
4384     SetVersion($DBversion);
4385 }
4386
4387 $DBversion = "3.05.00.005";
4388 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4389     $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');");
4390     print "Upgrade to $DBversion done (Adds pref BasketConfirmations)\n";
4391     SetVersion($DBversion);
4392 }
4393
4394 $DBversion = "3.05.00.006";
4395 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4396     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('MARCAuthorityControlField008', '|| aca||aabn           | a|a     d', NULL, NULL, 'Textarea')");
4397     print "Upgrade to $DBversion done (Add syspref MARCAuthorityControlField008)\n";
4398     SetVersion ($DBversion);
4399 }
4400
4401 $DBversion = "3.05.00.007";
4402 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4403     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpenLibraryCovers',0,'If ON Openlibrary book covers will be show',NULL,'YesNo');");
4404     print "Upgrade to $DBversion done (Add syspref OpenLibraryCovers)\n";
4405     SetVersion($DBversion);
4406 }
4407
4408 $DBversion = "3.05.00.008";
4409 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4410     $dbh->do("ALTER TABLE `cities` ADD `city_state` VARCHAR( 100 ) NULL DEFAULT NULL AFTER  `city_name`;");
4411     $dbh->do("ALTER TABLE `cities` ADD `city_country` VARCHAR( 100 ) NULL DEFAULT NULL AFTER  `city_zipcode`;");
4412     print "Add state and country to cities table corresponding to new columns in borrowers\n";
4413     SetVersion($DBversion);
4414 }
4415
4416 $DBversion = "3.05.00.009";
4417 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4418     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4419               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE borrowernumber IS NULL");
4420     $dbh->do("DELETE FROM issues WHERE borrowernumber IS NULL");
4421
4422     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4423               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE itemnumber IS NULL");
4424     $dbh->do("DELETE FROM issues WHERE itemnumber IS NULL");
4425
4426     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4427               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowernumber = issues.borrowernumber)");
4428     $dbh->do("DELETE FROM issues WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowernumber = issues.borrowernumber)");
4429
4430     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4431               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)");
4432     $dbh->do("DELETE FROM issues WHERE NOT EXISTS (SELECT * FROM items WHERE itemnumber = issues.itemnumber)");
4433
4434     $dbh->do("ALTER TABLE issues DROP FOREIGN KEY `issues_ibfk_1`");
4435     $dbh->do("ALTER TABLE issues DROP FOREIGN KEY `issues_ibfk_2`");
4436     $dbh->do("ALTER TABLE issues ALTER COLUMN borrowernumber DROP DEFAULT");
4437     $dbh->do("ALTER TABLE issues ALTER COLUMN itemnumber DROP DEFAULT");
4438     $dbh->do("ALTER TABLE issues MODIFY COLUMN borrowernumber int(11) NOT NULL");
4439     $dbh->do("ALTER TABLE issues MODIFY COLUMN itemnumber int(11) NOT NULL");
4440     $dbh->do("ALTER TABLE issues DROP KEY `issuesitemidx`");
4441     $dbh->do("ALTER TABLE issues ADD PRIMARY KEY (`itemnumber`)");
4442     $dbh->do("ALTER TABLE issues ADD CONSTRAINT `issues_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE RESTRICT ON UPDATE CASCADE");
4443     $dbh->do("ALTER TABLE issues ADD CONSTRAINT `issues_ibfk_2` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE RESTRICT ON UPDATE CASCADE");
4444
4445     print "Upgrade to $DBversion done (issues referential integrity)\n";
4446     SetVersion ($DBversion);
4447 }
4448
4449 $DBversion = "3.05.00.010";
4450 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4451     $dbh->do("CREATE INDEX priorityfoundidx ON reserves (priority,found)");
4452     print "Create an index on reserves to speed up holds awaiting pickup report bug 5866\n";
4453     SetVersion($DBversion);
4454 }
4455
4456
4457 $DBversion = "3.05.00.011";
4458 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4459     $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')");
4460     print "Upgrade to $DBversion done (add OPACResultsSidebar syspref (enh 6165))\n";
4461     SetVersion($DBversion);
4462 }
4463
4464 $DBversion = "3.05.00.012";
4465 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4466     $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')");
4467     print "Upgrade to $DBversion done (add RecordLocalUseOnReturn syspref (enh 6403))\n";
4468     SetVersion($DBversion);
4469 }
4470
4471 $DBversion = "3.05.00.013";
4472 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4473     $dbh->do(qq|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OpacKohaUrl','0',"Show 'Powered by Koha' text on OPAC footer.",NULL,NULL)|);
4474     print "Upgrade to $DBversion done (Add syspref 'OpacKohaUrl')\n";
4475     SetVersion($DBversion);
4476 }
4477
4478 $DBversion = "3.05.00.014";
4479 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4480     $dbh->do("ALTER TABLE `borrowers` MODIFY `userid` VARCHAR(75)");
4481     print "Modified userid column length into 75 in borrowers\n";
4482     SetVersion($DBversion);
4483 }
4484
4485 $DBversion = "3.05.00.015";
4486 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4487     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectEnabled',0,'Enable Novelist Select content.  Requires Novelist Profile and Password',NULL,'YesNo')");
4488     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectProfile',NULL,'Novelist Select user Password',NULL,'free')");
4489     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectPassword',NULL,'Enable Novelist user Profile',NULL,'free')");
4490     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectView','tab','Where to display Novelist Select content','tab|above|below|right','Choice')");
4491     print "Upgrade to $DBversion done (Add support for EBSCO's NoveList Select (enh 6902))\n";
4492     SetVersion($DBversion);
4493 }
4494
4495 $DBversion = '3.05.00.016';
4496 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4497     $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');");
4498     print "Upgrade to $DBversion done (Add EasyAnalyticalRecords syspref)\n";
4499     SetVersion ($DBversion);
4500 }
4501
4502 $DBversion = '3.05.00.017';
4503 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4504     if (C4::Context->preference("marcflavour") eq 'MARC21' ||
4505         C4::Context->preference("marcflavour") eq 'NORMARC'){
4506         $dbh->do("INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`, `tab`, `authorised_value` , `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`) VALUES ('773', '0', 'Host Biblionumber', 'Host Biblionumber', 0, 0, NULL, 7, NULL, NULL, '', NULL, -6, '', '', '', NULL)");
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', '9', 'Host Itemnumber', 'Host Itemnumber', 0, 0, NULL, 7, NULL, NULL, '', NULL, -6, '', '', '', NULL)");
4508         print "Upgrade to $DBversion done (Add 773 subfield 9 and 0 to default framework)\n";
4509         SetVersion ($DBversion);
4510     } elsif (C4::Context->preference("marcflavour") eq 'UNIMARC'){
4511         $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)");
4512         print "Upgrade to $DBversion done (Add 461 subfield 9 to default framework)\n";
4513         SetVersion ($DBversion);
4514     }
4515 }
4516
4517 $DBversion = "3.05.00.018";
4518 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4519     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacNavBottom','','Links after OpacNav links','70|10','Textarea')");
4520     print "Upgrade to $DBversion done (add OpacNavBottom syspref (enh 6825): if appropriate, you can split OpacNav into OpacNav and OpacNavBottom)\n";
4521     SetVersion($DBversion);
4522 }
4523
4524 $DBversion = "3.05.00.019";
4525 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4526     $dbh->do("UPDATE itemtypes SET imageurl = 'vokal/Book.png' WHERE imageurl = 'vokal/BOOK.png'");
4527     $dbh->do("UPDATE itemtypes SET imageurl = 'vokal/Book-32px.png' WHERE imageurl = 'vokal/BOOK-32px.png'");
4528     $dbh->do("UPDATE authorised_values SET imageurl = 'vokal/Book.png' WHERE imageurl = 'vokal/BOOK.png'");
4529     $dbh->do("UPDATE authorised_values SET imageurl = 'vokal/Book-32px.png' WHERE imageurl = 'vokal/BOOK-32px.png'");
4530     print "Upgrade to $DBversion done (remove duplicate VOKAL Book icons, bug 6862)\n";
4531     SetVersion($DBversion);
4532 }
4533
4534 $DBversion = "3.05.00.020";
4535 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4536     $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')");
4537     print "Upgrade to $DBversion done (Add syspref AcqViewBaskets)\n";
4538     SetVersion($DBversion);
4539 }
4540
4541 $DBversion = "3.05.00.021";
4542 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4543     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN display_checkout TINYINT(1) NOT NULL DEFAULT '0';");
4544     print "Upgrade to $DBversion done (Added a display_checkout field in borrower_attribute_types table)\n";
4545     SetVersion($DBversion);
4546 }
4547
4548 $DBversion = "3.05.00.022";
4549 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4550     $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");
4551     print "Upgrade to $DBversion done (6094: Fixing ModAuthority problems, add a need_merge_authorities table)\n";
4552     SetVersion($DBversion);
4553 }
4554
4555 $DBversion = "3.05.00.023";
4556 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4557     $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');");
4558     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";
4559     SetVersion($DBversion);
4560 }
4561
4562 $DBversion = "3.06.00.000";
4563 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4564     print "Upgrade to $DBversion done Koha 3.6.0 release \n";
4565     SetVersion ($DBversion);
4566 }
4567
4568 $DBversion = "3.07.00.001";
4569 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4570     my $borrowers = $dbh->selectcol_arrayref( "SELECT borrowernumber from borrowers where debarred =1;", { Columns => [1] } );
4571     $dbh->do("ALTER TABLE borrowers MODIFY debarred DATE DEFAULT NULL;");
4572     $dbh->do( "UPDATE borrowers set debarred='9999-12-31' where borrowernumber IN (" . join( ",", @$borrowers ) . ");" ) if ($borrowers and scalar(@$borrowers)>0);
4573     $dbh->do("ALTER TABLE borrowers ADD COLUMN debarredcomment VARCHAR(255) DEFAULT NULL AFTER debarred;");
4574     $dbh->do("ALTER TABLE deletedborrowers MODIFY debarred DATE DEFAULT NULL;");
4575     $dbh->do("ALTER TABLE deletedborrowers ADD COLUMN debarredcomment VARCHAR(255) DEFAULT NULL AFTER debarred;");
4576     print "Upgrade done (Change borrowers.debarred into Date )\n";
4577     SetVersion($DBversion);
4578 }
4579
4580 $DBversion = "3.07.00.002";
4581 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4582     $dbh->do("UPDATE borrowers SET debarred=NULL WHERE debarred='0000-00-00';");
4583     print "Setting NULL to debarred where 0000-00-00 is stored (bug 7272)\n";
4584     SetVersion($DBversion);
4585 }
4586
4587 $DBversion = "3.07.00.003";
4588 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4589     $dbh->do(" UPDATE `message_attributes` SET message_name='Item_Due' WHERE message_name='Item_DUE'");
4590     print "Updating message_name in message_attributes\n";
4591     SetVersion($DBversion);
4592 }
4593
4594 $DBversion = "3.07.00.004";
4595 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4596     $dbh->do("ALTER TABLE  `suggestions` ADD  `patronreason` TEXT NULL AFTER  `reason`");
4597     print "Upgrade to $DBversion done (Add column to suggestions table to store patrons' reasons for submitting a suggestion. )\n";
4598     SetVersion($DBversion);
4599 }
4600
4601 $DBversion = "3.07.00.005";
4602 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4603     $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')");
4604     print "Upgrade to $DBversion done (BorrowerUnwantedField syspref)\n";
4605     SetVersion ($DBversion);
4606 }
4607
4608 $DBversion = "3.07.00.006";
4609 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4610     $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');");
4611     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";
4612     SetVersion($DBversion);
4613 }
4614
4615 $DBversion = "3.07.00.007";
4616 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4617     $dbh->do("ALTER TABLE items MODIFY materials text;");
4618     print "Upgrade to $DBversion done alter items.material from varchar(10) to text \n";
4619     SetVersion($DBversion);
4620 }
4621
4622 $DBversion = '3.07.00.008';
4623 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4624     if (C4::Context->preference("marcflavour") eq 'MARC21') {
4625         if (C4::Context->preference("opaclanguages") eq "de") {
4626             $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, '');");
4627         } else {
4628             $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, '');");
4629         }
4630     }
4631     print "Upgrade to $DBversion done (add MARC21 field 545 to framework)\n";
4632     SetVersion ($DBversion);
4633 }
4634
4635 $DBversion = "3.07.00.009";
4636 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4637     $dbh->do("ALTER TABLE `aqorders` ADD COLUMN `claims_count` INT(11)  DEFAULT 0, ADD COLUMN `claimed_date` DATE  DEFAULT NULL AFTER `claims_count`");
4638     print "Upgrade to $DBversion done (Add claims_count and claimed_date fields in aqorders table)\n";
4639     SetVersion($DBversion);
4640 }
4641
4642 $DBversion = "3.07.00.010";
4643 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4644     $dbh->do(
4645         q|CREATE TABLE `biblioimages` (
4646           `imagenumber` int(11) NOT NULL AUTO_INCREMENT,
4647           `biblionumber` int(11) NOT NULL,
4648           `mimetype` varchar(15) NOT NULL,
4649           `imagefile` mediumblob NOT NULL,
4650           `thumbnail` mediumblob NOT NULL,
4651           PRIMARY KEY (`imagenumber`),
4652           CONSTRAINT `bibliocoverimage_fk1` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
4653           ) ENGINE=InnoDB DEFAULT CHARSET=utf8|
4654     );
4655     $dbh->do(
4656         q|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OPACLocalCoverImages','0','Display local cover images on OPAC search and details pages.','1','YesNo')|
4657         );
4658     $dbh->do(
4659         q|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('LocalCoverImages','0','Display local cover images on intranet search and details pages.','1','YesNo')|
4660         );
4661     $dbh->do(
4662         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')|
4663     );
4664     $dbh->do(
4665         q|INSERT INTO permissions (module_bit, code, description) VALUES (13, 'upload_local_cover_images', 'Upload local cover images')|
4666     );
4667     print "Upgrade to $DBversion done (Added support for local cover images)\n";
4668     SetVersion($DBversion);
4669 }
4670
4671 $DBversion = "3.07.00.011";
4672 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4673     $dbh->do(<<ENDOFRENEWAL);
4674     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');
4675 ENDOFRENEWAL
4676     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";
4677     SetVersion($DBversion);
4678 }
4679
4680 $DBversion = "3.07.00.012";
4681 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4682     $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')");
4683     print "Upgrade to $DBversion add 'AllowItemsOnHoldCheckout' syspref \n";
4684     SetVersion ($DBversion);
4685 }
4686
4687 $DBversion = "3.07.00.013";
4688 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4689     $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');");
4690     print "Upgrade to $DBversion done (Bug 7345: Add system preference OpacExportOptions.)\n";
4691     SetVersion ($DBversion);
4692 }
4693
4694 $DBversion = "3.07.00.014";
4695 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4696     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";
4697     SetVersion($DBversion);
4698 }
4699
4700 $DBversion = "3.07.00.015";
4701 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4702     my $sth = $dbh->prepare(q|
4703         SELECT COUNT(*) FROM marc_subfield_structure where kohafield="biblioitems.editionstatement"
4704         |);
4705     $sth->execute;
4706     my $already_exists = $sth->fetchrow;
4707     if ( not $already_exists ) {
4708         my $field = C4::Context->preference("marcflavour") eq "UNIMARC" ? "205" : "250";
4709         my $subfield = "a";
4710         my $sth = $dbh->prepare( q|
4711             UPDATE marc_subfield_structure SET kohafield = "biblioitems.editionstatement"
4712             WHERE tagfield = ? AND tagsubfield = ?
4713         |);
4714         $sth->execute( $field, $subfield );
4715         print "Upgrade to $DBversion done (Added a mapping for biblioitems.editionstatement.)\n";
4716     } else {
4717         print "Upgrade to $DBversion done (Added a mapping for biblioitems.editionstatement (already exists, nothing to do).)\n";
4718     }
4719     SetVersion($DBversion);
4720 }
4721
4722 $DBversion = "3.07.00.016";
4723 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4724     $dbh->do("ALTER TABLE items ADD KEY `itemcallnumber` (itemcallnumber)");
4725     print "Upgrade to $DBversion done (Added index on items.itemcallnumber)\n";
4726     SetVersion($DBversion);
4727 }
4728
4729 $DBversion = "3.07.00.017";
4730 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4731     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('TransferWhenCancelAllWaitingHolds','0','Transfer items when cancelling all waiting holds',NULL,'YesNo')");
4732     print "Upgrade to $DBversion done (Add sysprefs to control transfer when cancel all waiting holds)\n";
4733     SetVersion ($DBversion);
4734 }
4735
4736 $DBversion = "3.07.00.018";
4737 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4738     $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;");
4739     print "Upgrade to $DBversion done ( adding offline operations table )\n";
4740     SetVersion($DBversion);
4741 }
4742
4743 $DBversion = "3.07.00.019";
4744 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4745     $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");
4746     $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");
4747     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";
4748     SetVersion($DBversion);
4749 }
4750
4751 $DBversion = "3.07.00.020";
4752 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4753     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OPACpatronimages',0,'Enable patron images in the OPAC',NULL,'YesNo');");
4754     print "Upgrade to $DBversion done (Bug 3516: Add the option to show patron images in the OPAC.)\n";
4755     SetVersion($DBversion);
4756 }
4757
4758 $DBversion = "3.07.00.021";
4759 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4760     $dbh->do(
4761     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('LinkerModule','Default','Chooses which linker module to use (see documentation).','Default|FirstMatchLastMatch','Choice');"
4762     );
4763     $dbh->do(
4764     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('LinkerOptions','','A pipe-separated list of options for the linker.','','free');"
4765     );
4766     $dbh->do(
4767     "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');"
4768     );
4769     $dbh->do(
4770     "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');"
4771     );
4772     $dbh->do(
4773     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AutoCreateAuthorities',0,'Automatically create authorities that do not exist when cataloging records.',NULL,'YesNo');"
4774     );
4775     $dbh->do(
4776     "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');"
4777     );
4778     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";
4779     SetVersion($DBversion);
4780 }
4781
4782 $DBversion = "3.07.00.022";
4783 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4784     $dbh->do("DELETE FROM reviews WHERE biblionumber NOT IN (SELECT biblionumber from biblio)");
4785     $dbh->do("UPDATE reviews SET borrowernumber = NULL WHERE borrowernumber NOT IN (SELECT borrowernumber FROM borrowers)");
4786     $dbh->do("ALTER TABLE reviews ADD CONSTRAINT reviews_ibfk_2 FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE");
4787     $dbh->do("ALTER TABLE reviews ADD CONSTRAINT reviews_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber ) ON UPDATE CASCADE ON DELETE SET NULL");
4788     print "Upgrade to $DBversion done (Bug 7493 - Add constraint linking OPAC comment biblionumber to biblio, OPAC comment borrowernumber to borrowers.)\n";
4789     SetVersion($DBversion);
4790 }
4791
4792 $DBversion = "3.07.00.023";
4793 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4794     $dbh->do("ALTER TABLE `message_transports` DROP FOREIGN KEY `message_transports_ibfk_3`");
4795     $dbh->do("ALTER TABLE `letter` DROP PRIMARY KEY");
4796     $dbh->do("ALTER TABLE `letter` ADD `branchcode` varchar(10) default NULL AFTER `code`");
4797     $dbh->do("ALTER TABLE `letter` ADD PRIMARY KEY  (`module`,`code`, `branchcode`)");
4798     $dbh->do("ALTER TABLE `message_transports` ADD `branchcode` varchar(10) NOT NULL default ''");
4799     $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");
4800     $dbh->do("ALTER TABLE `letter` ADD `is_html` tinyint(1) default 0 AFTER `name`");
4801
4802     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4803               VALUES ('circulation','ISSUESLIP','Issue Slip','Issue Slip', '<h3><<branches.branchname>></h3>
4804 Checked out to <<borrowers.title>> <<borrowers.firstname>> <<borrowers.initials>> <<borrowers.surname>> <br />
4805 (<<borrowers.cardnumber>>) <br />
4806
4807 <<today>><br />
4808
4809 <h4>Checked Out</h4>
4810 <checkedout>
4811 <p>
4812 <<biblio.title>> <br />
4813 Barcode: <<items.barcode>><br />
4814 Date due: <<issues.date_due>><br />
4815 </p>
4816 </checkedout>
4817
4818 <h4>Overdues</h4>
4819 <overdue>
4820 <p>
4821 <<biblio.title>> <br />
4822 Barcode: <<items.barcode>><br />
4823 Date due: <<issues.date_due>><br />
4824 </p>
4825 </overdue>
4826
4827 <hr>
4828
4829 <h4 style=\"text-align: center; font-style:italic;\">News</h4>
4830 <news>
4831 <div class=\"newsitem\">
4832 <h5 style=\"margin-bottom: 1px; margin-top: 1px\"><b><<opac_news.title>></b></h5>
4833 <p style=\"margin-bottom: 1px; margin-top: 1px\"><<opac_news.new>></p>
4834 <p class=\"newsfooter\" style=\"font-size: 8pt; font-style:italic; margin-bottom: 1px; margin-top: 1px\">Posted on <<opac_news.timestamp>></p>
4835 <hr />
4836 </div>
4837 </news>', 1)");
4838     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4839               VALUES ('circulation','ISSUEQSLIP','Issue Quick Slip','Issue Quick Slip', '<h3><<branches.branchname>></h3>
4840 Checked out to <<borrowers.title>> <<borrowers.firstname>> <<borrowers.initials>> <<borrowers.surname>> <br />
4841 (<<borrowers.cardnumber>>) <br />
4842
4843 <<today>><br />
4844
4845 <h4>Checked Out Today</h4>
4846 <checkedout>
4847 <p>
4848 <<biblio.title>> <br />
4849 Barcode: <<items.barcode>><br />
4850 Date due: <<issues.date_due>><br />
4851 </p>
4852 </checkedout>', 1)");
4853     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4854               VALUES ('circulation','RESERVESLIP','Reserve Slip','Reserve Slip', '<h5>Date: <<today>></h5>
4855
4856 <h3> Transfer to/Hold in <<branches.branchname>></h3>
4857
4858 <h3><<borrowers.surname>>, <<borrowers.firstname>></h3>
4859
4860 <ul>
4861     <li><<borrowers.cardnumber>></li>
4862     <li><<borrowers.phone>></li>
4863     <li> <<borrowers.address>><br />
4864          <<borrowers.address2>><br />
4865          <<borrowers.city >>  <<borrowers.zipcode>>
4866     </li>
4867     <li><<borrowers.email>></li>
4868 </ul>
4869 <br />
4870 <h3>ITEM ON HOLD</h3>
4871 <h4><<biblio.title>></h4>
4872 <h5><<biblio.author>></h5>
4873 <ul>
4874    <li><<items.barcode>></li>
4875    <li><<items.itemcallnumber>></li>
4876    <li><<reserves.waitingdate>></li>
4877 </ul>
4878 <p>Notes:
4879 <pre><<reserves.reservenotes>></pre>
4880 </p>', 1)");
4881     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4882               VALUES ('circulation','TRANSFERSLIP','Transfer Slip','Transfer Slip', '<h5>Date: <<today>></h5>
4883 <h3>Transfer to <<branches.branchname>></h3>
4884
4885 <h3>ITEM</h3>
4886 <h4><<biblio.title>></h4>
4887 <h5><<biblio.author>></h5>
4888 <ul>
4889    <li><<items.barcode>></li>
4890    <li><<items.itemcallnumber>></li>
4891 </ul>', 1)");
4892
4893     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('NoticeCSS','','Notices CSS url.',NULL,'free')");
4894     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('SlipCSS','','Slips CSS url.',NULL,'free')");
4895
4896     $dbh->do("UPDATE `letter` SET content = replace(content, '<<title>>', '<<biblio.title>>') WHERE code = 'HOLDPLACED'");
4897
4898     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";
4899     SetVersion($DBversion);
4900 }
4901
4902 $DBversion = "3.07.00.024";
4903 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4904     $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')");
4905     $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')");
4906     print "Upgrade to $DBversion done (Added system preference ExpireReservesMaxPickUpDelay, system preference ExpireReservesMaxPickUpDelayCharge, add reseves.charge_if_expired)\n";
4907 }
4908
4909 $DBversion = "3.07.00.025";
4910 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4911     if (TableExists('bibliocoverimage')) {
4912         $dbh->do( q|DROP TABLE bibliocoverimage;| );
4913         $dbh->do(
4914             q|CREATE TABLE biblioimages (
4915               imagenumber int(11) NOT NULL AUTO_INCREMENT,
4916               biblionumber int(11) NOT NULL,
4917               mimetype varchar(15) NOT NULL,
4918               imagefile mediumblob NOT NULL,
4919               thumbnail mediumblob NOT NULL,
4920               PRIMARY KEY (imagenumber),
4921               CONSTRAINT bibliocoverimage_fk1 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
4922               ) ENGINE=InnoDB DEFAULT CHARSET=utf8;|
4923         );
4924     }
4925     print "Upgrade to $DBversion done (Correct table name for local cover images if needed. )\n";
4926     SetVersion($DBversion);
4927 }
4928
4929 $DBversion = "3.07.00.026";
4930 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4931     $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');");
4932     print "Upgrade to $DBversion done (Add syspref CalendarFirstDayOfWeek used to select the first day of week to use in the calendar. )\n";
4933     SetVersion($DBversion);
4934 }
4935
4936 $DBversion = "3.07.00.027";
4937 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4938     $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');});
4939     print "Upgrade to $DBversion done (Added system preference RoutingListNote for adding a general note to all routing lists.)\n";
4940     SetVersion($DBversion);
4941 }
4942
4943 $DBversion = "3.07.00.028";
4944 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4945     $dbh->do(qq{
4946     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');
4947     });
4948     print "Upgrade to $DBversion done (Bug 6296 New System preference AllowPKIAuth)\n";
4949 }
4950
4951 $DBversion = "3.07.00.029";
4952 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4953     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_descriptions`;});
4954     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_mappings`;});
4955     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_biblios`;});
4956     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets`;});
4957
4958     $dbh->do(q{
4959         CREATE TABLE `oai_sets` (
4960           `id` int(11) NOT NULL auto_increment,
4961           `spec` varchar(80) NOT NULL UNIQUE,
4962           `name` varchar(80) NOT NULL,
4963           PRIMARY KEY (`id`)
4964         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4965     });
4966
4967     $dbh->do(q{
4968         CREATE TABLE `oai_sets_descriptions` (
4969           `set_id` int(11) NOT NULL,
4970           `description` varchar(255) NOT NULL,
4971           CONSTRAINT `oai_sets_descriptions_ibfk_1` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4972         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4973     });
4974
4975     $dbh->do(q{
4976         CREATE TABLE `oai_sets_mappings` (
4977           `set_id` int(11) NOT NULL,
4978           `marcfield` char(3) NOT NULL,
4979           `marcsubfield` char(1) NOT NULL,
4980           `marcvalue` varchar(80) NOT NULL,
4981           CONSTRAINT `oai_sets_mappings_ibfk_1` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4982         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4983     });
4984
4985     $dbh->do(q{
4986         CREATE TABLE `oai_sets_biblios` (
4987           `biblionumber` int(11) NOT NULL,
4988           `set_id` int(11) NOT NULL,
4989           PRIMARY KEY (`biblionumber`, `set_id`),
4990           CONSTRAINT `oai_sets_biblios_ibfk_1` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
4991           CONSTRAINT `oai_sets_biblios_ibfk_2` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4992         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4993     });
4994
4995     $dbh->do(q{
4996         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');
4997     });
4998
4999     print "Upgrade to $DBversion done (Atomic update for OAI-PMH sets management)\n";
5000     SetVersion($DBversion);
5001 }
5002
5003 $DBversion = "3.07.00.030";
5004 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5005     $dbh->do("ALTER TABLE default_circ_rules ADD
5006             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5007     $dbh->do("ALTER TABLE branch_item_rules ADD
5008             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5009     $dbh->do("ALTER TABLE default_branch_circ_rules ADD
5010             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5011     $dbh->do("ALTER TABLE default_branch_item_rules ADD
5012             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5013     # set the default rule to the current value of HomeOrHoldingBranchReturn (default to 'homebranch' if need be)
5014     my $homeorholdingbranchreturn = C4::Context->preference('HomeOrHoldingBranchReturn') || 'homebranch';
5015     $dbh->do("UPDATE default_circ_rules SET returnbranch = '$homeorholdingbranchreturn'");
5016     print "Upgrade to $DBversion done (Atomic update for OAI-PMH sets management)\n";
5017     SetVersion($DBversion);
5018 }
5019
5020 $DBversion = "3.07.00.031";
5021 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5022     $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')");
5023     print "Upgrade to $DBversion done (Add syspref to tell Koha if ICU indexing is in use for Zebra or not.)\n";
5024     SetVersion ($DBversion);
5025 }
5026
5027 $DBversion = "3.07.00.032";
5028 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5029     $dbh->do("ALTER TABLE virtualshelves MODIFY COLUMN owner int"); #should have been int already (fk to borrowers)
5030     $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
5031     $dbh->do("DELETE FROM virtualshelves WHERE owner IS NULL and category=1"); #delete private lists without owner (cascades to shelfcontents)
5032     $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");
5033     $dbh->do("UPDATE virtualshelves SET allow_add=0, allow_delete_own=1, allow_delete_other=0 WHERE category=1");
5034     $dbh->do("UPDATE virtualshelves SET allow_add=0, allow_delete_own=1, allow_delete_other=0 WHERE category=2");
5035     $dbh->do("UPDATE virtualshelves SET allow_add=1, allow_delete_own=1, allow_delete_other=1 WHERE category=3");
5036     $dbh->do("UPDATE virtualshelves SET category=2 WHERE category=3");
5037
5038     $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");
5039     $dbh->do("UPDATE virtualshelfcontents co LEFT JOIN virtualshelves sh USING (shelfnumber) SET co.borrowernumber=sh.owner");
5040
5041     $dbh->do("CREATE TABLE virtualshelfshares
5042     (id int AUTO_INCREMENT PRIMARY KEY, shelfnumber int NOT NULL,
5043     borrowernumber int, invitekey varchar(10), sharedate datetime,
5044     CONSTRAINT `virtualshelfshares_ibfk_1` FOREIGN KEY (`shelfnumber`) REFERENCES `virtualshelves` (`shelfnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
5045         CONSTRAINT `virtualshelfshares_ibfk_2` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE SET NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8");
5046
5047     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacAllowPublicListCreation',1,'If set, allows opac users to create public lists',NULL,'YesNo');");
5048     $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');");
5049
5050     print "Upgrade to $DBversion done (BZ7310: Improving list permissions)\n";
5051     SetVersion($DBversion);
5052 }
5053
5054 $DBversion = "3.07.00.033";
5055 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5056     $dbh->do("ALTER TABLE branches ADD opac_info text;");
5057     print "Upgrade to $DBversion done add opac_info to branches \n";
5058     SetVersion($DBversion);
5059 }
5060
5061 $DBversion = "3.07.00.034";
5062 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5063     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN category_code VARCHAR(10) NULL DEFAULT NULL AFTER `display_checkout`");
5064     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN class VARCHAR(255)  NOT NULL DEFAULT '' AFTER `category_code`");
5065     $dbh->do("ALTER TABLE borrower_attribute_types ADD CONSTRAINT category_code_fk FOREIGN KEY (category_code) REFERENCES categories(categorycode)");
5066     print "Upgrade to $DBversion done (New fields category_code and class in borrower_attribute_types table)\n";
5067     SetVersion($DBversion);
5068 }
5069
5070 $DBversion = "3.07.00.035";
5071 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5072     $dbh->do("ALTER TABLE issues CHANGE date_due date_due datetime");
5073     $dbh->do("UPDATE issues SET date_due = CONCAT(SUBSTR(date_due,1,11),'23:59:00')");
5074     $dbh->do("ALTER TABLE issues CHANGE returndate returndate datetime");
5075     $dbh->do("ALTER TABLE issues CHANGE lastreneweddate lastreneweddate datetime");
5076     $dbh->do("ALTER TABLE issues CHANGE issuedate issuedate datetime");
5077     $dbh->do("ALTER TABLE old_issues CHANGE date_due date_due datetime");
5078     $dbh->do("ALTER TABLE old_issues CHANGE returndate returndate datetime");
5079     $dbh->do("ALTER TABLE old_issues CHANGE lastreneweddate lastreneweddate datetime");
5080     $dbh->do("ALTER TABLE old_issues CHANGE issuedate issuedate datetime");
5081     $dbh->do("UPDATE accountlines SET description = CONCAT(description,' 23:59') WHERE accounttype='F' OR accounttype='FU'"); #BUG-8253
5082     print "Upgrade to $DBversion done (Setting up issues and accountlines tables for hourly loans)\n";
5083     SetVersion($DBversion);
5084 }
5085
5086 $DBversion = "3.07.00.036";
5087 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5088     $dbh->do(qq{
5089        ALTER TABLE z3950servers ADD timeout INT( 11 ) NOT NULL DEFAULT '0' AFTER syntax;
5090     });
5091     print "Upgrade to $DBversion done (New timeout field in z3950servers)\n";
5092 }
5093
5094 $DBversion = "3.07.00.037";
5095 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5096     $dbh->do("
5097        ALTER TABLE  `marc_subfield_structure` ADD  `maxlength` INT( 4 ) NOT NULL DEFAULT  '9999';
5098        ");
5099        $dbh->do("
5100        UPDATE `marc_subfield_structure` SET maxlength=24 WHERE tagfield='000';
5101        ");
5102        $dbh->do("
5103        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='MARC21','40','9999') WHERE tagfield='008';
5104        ");
5105        $dbh->do("
5106        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='NORMARC','40','9999') WHERE tagfield='008';
5107        ");
5108        $dbh->do("
5109        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='UNIMARC','36','9999') WHERE tagfield='100';
5110        ");
5111     print "Upgrade to $DBversion done (Add new field maxlength to marc_subfield_structure)\n";
5112     SetVersion($DBversion);
5113 }
5114
5115 $DBversion = "3.07.00.038";
5116 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5117     $dbh->do(qq{
5118         INSERT INTO systempreferences(variable,value,explanation,options,type)
5119         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')
5120     });
5121     print "Upgrade to $DBversion done (Added system preference 'UniqueItemFields')\n";
5122     SetVersion($DBversion);
5123 }
5124
5125 $DBversion = "3.07.00.039";
5126 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5127     $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')} );
5128     $dbh->do( qq{CREATE TABLE IF NOT EXISTS social_data
5129       ( isbn VARCHAR(30),
5130         num_critics INT,
5131         num_critics_pro INT,
5132         num_quotations INT,
5133         num_videos INT,
5134         score_avg DECIMAL(5,2),
5135         num_scores INT,
5136         PRIMARY KEY  (isbn)
5137       ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5138     } );
5139     $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')} );
5140     print "Upgrade to $DBversion done (added syspref and table for babeltheque (Babeltheque_url_js, babeltheque))\n";
5141     SetVersion($DBversion);
5142 }
5143
5144 $DBversion = "3.07.00.040";
5145 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5146     $dbh->do( qq{INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('SocialNetworks','0','Enable/Disable social networks links in opac detail','','YesNo')} );
5147     print "Upgrade to $DBversion done (added syspref SocialNetworks, to display facebook/ggl+ and other buttons)\n";
5148     SetVersion($DBversion);
5149 }
5150
5151
5152
5153 $DBversion = "3.07.00.041";
5154 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5155     $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')");
5156     print "Upgrade to $DBversion done (Add system preference SubscriptionDuplicateDroppedInput)\n";
5157     SetVersion($DBversion);
5158 }
5159
5160 $DBversion = "3.07.00.042";
5161 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5162     $dbh->do("ALTER TABLE reserves ADD suspend BOOLEAN NOT NULL DEFAULT 0");
5163     $dbh->do("ALTER TABLE old_reserves ADD suspend BOOLEAN NOT NULL DEFAULT 0");
5164
5165     $dbh->do("ALTER TABLE reserves ADD suspend_until DATETIME NULL DEFAULT NULL");
5166     $dbh->do("ALTER TABLE old_reserves ADD suspend_until DATETIME NULL DEFAULT NULL");
5167
5168     $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')");
5169
5170     print "Upgrade to $DBversion done (Add suspend fields to reserves table, add syspref AutoResumeSuspendedHolds)\n";
5171     SetVersion ($DBversion);
5172 }
5173
5174 $DBversion = "3.07.00.043";
5175 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5176     my $countXSLTDetailsDisplay = 0;
5177     my $valueXSLTDetailsDisplay = "";
5178     my $valueXSLTResultsDisplay = "";
5179     my $valueOPACXSLTDetailsDisplay = "";
5180     my $valueOPACXSLTResultsDisplay = "";
5181     #the line below test if database comes from a BibLibre's branch
5182     $countXSLTDetailsDisplay = $dbh->do('SELECT 1 FROM systempreferences WHERE variable="IntranetXSLTDetailsDisplay"');
5183     if ($countXSLTDetailsDisplay > 0)
5184     {
5185         #the two lines below will only be used to update the databases from the BibLibre's branch. They will not affect the others
5186         $dbh->do(q|UPDATE systempreferences SET variable="XSLTDetailsDisplay" WHERE variable="IntranetXSLTDetailsDisplay"|);
5187         $dbh->do(q|UPDATE systempreferences SET variable="XSLTResultsDisplay" WHERE variable="IntranetXSLTResultsDisplay"|);
5188     }
5189     else
5190     {
5191         $valueXSLTDetailsDisplay = "default" if (C4::Context->preference("XSLTDetailsDisplay"));
5192         $valueXSLTResultsDisplay = "default" if (C4::Context->preference("XSLTResultsDisplay"));
5193         $valueOPACXSLTDetailsDisplay = "default" if (C4::Context->preference("OPACXSLTDetailsDisplay"));
5194         $valueOPACXSLTResultsDisplay = "default" if (C4::Context->preference("OPACXSLTResultsDisplay"));
5195         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueXSLTDetailsDisplay\" WHERE variable='XSLTDetailsDisplay'");
5196         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueXSLTResultsDisplay\" WHERE variable='XSLTResultsDisplay'");
5197         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueOPACXSLTDetailsDisplay\" WHERE variable='OPACXSLTDetailsDisplay'");
5198         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueOPACXSLTResultsDisplay\" WHERE variable='OPACXSLTResultsDisplay'");
5199     }
5200     print "Upgrade to $DBversion done (XSLT systempreference takes a path to file rather than YesNo)\n";
5201     SetVersion($DBversion);
5202 }
5203
5204 $DBversion = "3.07.00.044";
5205 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5206     $dbh->do("ALTER TABLE aqbooksellers ADD deliverytime INT DEFAULT NULL");
5207     print "Upgrade to $DBversion done (Add deliverytime field in aqbooksellers table)";
5208     SetVersion($DBversion);
5209 }
5210
5211 $DBversion = "3.07.00.045";
5212 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5213     $dbh->do("ALTER TABLE import_batches MODIFY COLUMN batch_type ENUM('batch','z3950','webservice') NOT NULL default 'batch'");
5214     print "Upgrade to $DBversion done (Add 'webservice' to batch_type enum)\n";
5215     SetVersion ($DBversion);
5216 }
5217
5218 $DBversion = "3.07.00.046";
5219 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5220     $dbh->do("ALTER TABLE issuingrules ADD COLUMN lengthunit varchar(10) DEFAULT 'days' AFTER issuelength");
5221     print "Upgrade to $DBversion done (Setting up issues tables for hourly loans (lengthunit fix))\n";
5222     SetVersion($DBversion);
5223 }
5224
5225 $DBversion = "3.07.00.047";
5226 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5227     $dbh->do("CREATE INDEX items_location ON items(location)");
5228     $dbh->do("CREATE INDEX items_ccode ON items(ccode)");
5229     print "Upgrade to $DBversion done (items_location and items_ccode indexes added for ShelfBrowser)\n";
5230     SetVersion($DBversion);
5231 }
5232
5233 $DBversion = "3.07.00.048";
5234 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5235     $dbh->do(
5236         q | CREATE TABLE ratings (
5237   borrowernumber int(11) NOT NULL,
5238   biblionumber int(11) NOT NULL,
5239   rating_value tinyint(1) NOT NULL,
5240   timestamp timestamp NOT NULL default CURRENT_TIMESTAMP,
5241   PRIMARY KEY  (borrowernumber,biblionumber),
5242   CONSTRAINT ratings_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE,
5243   CONSTRAINT ratings_ibfk_2 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
5244 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
5245     );
5246
5247     $dbh->do(
5248 q /INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OpacStarRatings','disable',NULL,'disable|all|details','Choice') /
5249     );
5250
5251     print
5252 "Upgrade to $DBversion done (Add 'ratings' table and 'OpacStarRatings' syspref)\n";
5253     SetVersion($DBversion);
5254 }
5255
5256 $DBversion = "3.07.00.049";
5257 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5258     $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')");
5259     print "Upgrade to $DBversion done (Add system preference OpacBrowseResults ))\n";
5260     SetVersion($DBversion);
5261 }
5262
5263 $DBversion = "3.08.00.000";
5264 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5265     print "Upgrade to $DBversion done\n";
5266     SetVersion($DBversion);
5267 }
5268
5269 $DBversion = "3.09.00.001";
5270 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5271     $dbh->do("ALTER TABLE borrower_attribute_types MODIFY category_code VARCHAR( 1 ) NULL DEFAULT NULL");
5272     print "Upgrade to $DBversion done. (Bug 8002: Update patron attribute types table to allow NULL category_code)\n";
5273     SetVersion($DBversion);
5274 }
5275
5276 $DBversion = "3.09.00.002";
5277 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5278     $dbh->do("ALTER TABLE saved_sql
5279         ADD (
5280             cache_expiry INT NOT NULL DEFAULT 300,
5281             public BOOLEAN NOT NULL DEFAULT FALSE
5282         );
5283     ");
5284     print "Upgrade to $DBversion done (Added cache_expiry and public fields in
5285 saved_reports table.)\n";
5286     SetVersion($DBversion);
5287 }
5288
5289 $DBversion = "3.09.00.003";
5290 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5291     $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');");
5292     print "Upgrade to $DBversion done (Added SvcMaxReportRows syspref)\n";
5293     SetVersion($DBversion);
5294 }
5295
5296 $DBversion = "3.09.00.004";
5297 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5298     $dbh->do("INSERT IGNORE INTO permissions (module_bit, code, description) VALUES('13', 'edit_patrons', 'Perform batch modifivation of patrons')");
5299     print "Upgrade to $DBversion done (Adds permissions flag for access to the patron modifications tool)\n";
5300     SetVersion($DBversion);
5301 }
5302
5303 $DBversion = "3.09.00.005";
5304 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5305     unless (TableExists('quotes')) {
5306         $dbh->do( qq{
5307             CREATE TABLE `quotes` (
5308               `id` int(11) NOT NULL AUTO_INCREMENT,
5309               `source` text DEFAULT NULL,
5310               `text` mediumtext NOT NULL,
5311               `timestamp` datetime NOT NULL,
5312               PRIMARY KEY (`id`)
5313             ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5314         });
5315     }
5316     $dbh->do( qq{
5317         INSERT IGNORE INTO permissions VALUES (13, "edit_quotes","Edit quotes for quote-of-the-day feature");
5318     });
5319     $dbh->do( qq{
5320         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');
5321     });
5322     print "Upgrade to $DBversion done (Adding Quote of the Day Option.)\n";
5323     SetVersion($DBversion);
5324 }
5325
5326 $DBversion = "3.09.00.006";
5327 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5328     $dbh->do("UPDATE systempreferences SET
5329                 variable = 'OPACShowHoldQueueDetails',
5330                 value = CASE value WHEN '1' THEN 'priority' ELSE 'none' END,
5331                 options = 'none|priority|holds|holds_priority',
5332                 explanation = 'Show holds details in OPAC',
5333                 type = 'Choice'
5334               WHERE variable = 'OPACDisplayRequestPriority'");
5335     print "Upgrade to $DBversion done (Changed system preference OPACDisplayRequestPriority -> OPACShowHoldQueueDetails)\n";
5336     SetVersion($DBversion);
5337 }
5338
5339 $DBversion = "3.09.00.007";
5340 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5341     unless(C4::Context->preference('ReservesControlBranch')){
5342         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('ReservesControlBranch','PatronLibrary','ItemHomeLibrary|PatronLibrary','Branch checked for members reservations rights.','Choice')");
5343     }
5344     print "Upgrade to $DBversion done (Insert ReservesControlBranch systempreference into systempreferences table )\n";
5345     SetVersion($DBversion);
5346 }
5347
5348 $DBversion = "3.09.00.008";
5349 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5350     $dbh->do("ALTER TABLE sessions ADD PRIMARY KEY (id);");
5351     $dbh->do("ALTER TABLE sessions DROP INDEX `id`;");
5352     print "Upgrade to $DBversion done (redefine the field id as PRIMARY KEY of sessions)\n";
5353     SetVersion($DBversion);
5354 }
5355
5356 $DBversion = "3.09.00.009";
5357 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5358     $dbh->do("ALTER TABLE branches ADD PRIMARY KEY (branchcode);");
5359     $dbh->do("ALTER TABLE branches DROP INDEX branchcode;");
5360     print "Upgrade to $DBversion done (redefine the field branchcode as PRIMARY KEY of branches)\n";
5361     SetVersion ($DBversion);
5362 }
5363
5364 $DBversion = "3.09.00.010";
5365 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5366     $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')");
5367     print "Upgrade to $DBversion done (Add system preference issuelostitem ))\n";
5368     SetVersion($DBversion);
5369 }
5370
5371 $DBversion = "3.09.00.011";
5372 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5373     $dbh->do("ALTER TABLE `biblioitems` ADD `ean` VARCHAR( 13 ) NULL AFTER issn");
5374     $dbh->do("CREATE INDEX `ean` ON biblioitems (`ean`) ");
5375     $dbh->do("ALTER TABLE `deletedbiblioitems` ADD `ean` VARCHAR( 13 ) NULL AFTER issn");
5376     if (C4::Context->preference("marcflavour") eq 'UNIMARC') {
5377          $dbh->do("UPDATE marc_subfield_structure SET kohafield='biblioitems.ean' WHERE tagfield='073' and tagsubfield='a'");
5378     }
5379     print "Upgrade to $DBversion done (Adding ean in biblioitems and deletedbiblioitems)\n";
5380     print "If you have records with ean, please run misc/batchRebuildBiblioTables.pl to populate bibliotems.ean\n" if (C4::Context->preference("marcflavour") eq 'UNIMARC');
5381     SetVersion($DBversion);
5382 }
5383
5384 $DBversion = "3.09.00.012";
5385 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5386     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('SuspendHoldsIntranet', '1', NULL , 'Allow holds to be suspended from the intranet.', 'YesNo')");
5387     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('SuspendHoldsOpac', '1', NULL , 'Allow holds to be suspended from the OPAC.', 'YesNo')");
5388     print "Upgrade to $DBversion done (Add system preference OpacBrowseResults ))\n";
5389     SetVersion($DBversion);
5390 }
5391
5392 $DBversion ="3.09.00.013";
5393 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5394     $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');");
5395     print "Upgrade to $DBversion done (Add system preference DefaultLanguageField008))\n";
5396     SetVersion($DBversion);
5397 }
5398
5399 $DBversion ="3.09.00.014";
5400 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5401     # add phone message transport type
5402     $dbh->do("INSERT INTO message_transport_types (message_transport_type) VALUES ('phone')");
5403
5404     # adds HOLD_PHONE and PREDUE_PHONE letters (as placeholders)
5405     $dbh->do("INSERT INTO letter (module, code, name, title, content) VALUES
5406               ('reserves', 'HOLD_PHONE', 'Item Available for Pick-up (phone notice)', 'Item Available for Pick-up (phone notice)', 'Your item is available for pickup'),
5407               ('circulation', 'PREDUE_PHONE', 'Advance Notice of Item Due (phone notice)', 'Advance Notice of Item Due (phone notice)', 'Your item is due soon'),
5408               ('circulation', 'OVERDUE_PHONE', 'Overdue Notice (phone notice)', 'Overdue Notice (phone notice)', 'Your item is overdue')
5409               ");
5410
5411     # add phone notifications to patron message preferences options
5412     $dbh->do("INSERT INTO message_transports
5413              (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) VALUES
5414              (4, 'phone', 0, 'reserves', 'HOLD_PHONE'),
5415              (2, 'phone', 0, 'circulation', 'PREDUE_PHONE')
5416              ");
5417
5418     # add TalkingTechItivaPhoneNotification syspref
5419     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('TalkingTechItivaPhoneNotification',0,'If ON, enables Talking Tech I-tiva phone notifications',NULL,'YesNo');");
5420
5421     print "Upgrade done (Support for Talking Tech i-tiva phone notification system)\n";
5422     SetVersion($DBversion);
5423 }
5424
5425 $DBversion = "3.09.00.015";
5426 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5427     $dbh->do(qq{
5428         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')
5429     });
5430     print "Upgrade to $DBversion done (Add System preference StatisticsFields)\n";
5431     SetVersion($DBversion);
5432 }
5433
5434 $DBversion = "3.09.00.016";
5435 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5436     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACShowBarcode','0','Show items barcode in holding tab','','YesNo')");
5437     print "Upgrade to $DBversion done (Add syspref OPACShowBarcode)\n";
5438     SetVersion ($DBversion);
5439 }
5440
5441 $DBversion = "3.09.00.017";
5442 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5443     $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');");
5444     print "Upgrade to $DBversion done (Add customizable OpacNavRight region to the OPAC main page)\n";
5445     SetVersion ($DBversion);
5446 }
5447
5448 $DBversion = "3.09.00.018";
5449 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5450     $dbh->do("DROP TABLE IF EXISTS aqbudgetborrowers");
5451     $dbh->do("
5452         CREATE TABLE aqbudgetborrowers (
5453           budget_id int(11) NOT NULL,
5454           borrowernumber int(11) NOT NULL,
5455           PRIMARY KEY (budget_id, borrowernumber),
5456           CONSTRAINT aqbudgetborrowers_ibfk_1 FOREIGN KEY (budget_id)
5457             REFERENCES aqbudgets (budget_id)
5458             ON DELETE CASCADE ON UPDATE CASCADE,
5459           CONSTRAINT aqbudgetborrowers_ibfk_2 FOREIGN KEY (borrowernumber)
5460             REFERENCES borrowers (borrowernumber)
5461             ON DELETE CASCADE ON UPDATE CASCADE
5462         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
5463     ");
5464     $dbh->do("
5465         INSERT INTO permissions (module_bit, code, description)
5466         VALUES (11, 'budget_manage_all', 'Manage all budgets')
5467     ");
5468     print "Upgrade to $DBversion done (Add aqbudgetborrowers table)\n";
5469     SetVersion($DBversion);
5470 }
5471
5472 $DBversion = "3.09.00.019";
5473 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5474     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('OPACShowUnusedAuthorities','1','','Show authorities that are not being used in the OPAC.','YesNo')");
5475     print "Upgrade to $DBversion done (Add OPACShowUnusedAuthorities system preference)\n";
5476     SetVersion ($DBversion);
5477 }
5478
5479 $DBversion = "3.09.00.020";
5480 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5481     $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')");
5482     $dbh->do("
5483 CREATE TABLE IF NOT EXISTS borrower_files (
5484   file_id int(11) NOT NULL AUTO_INCREMENT,
5485   borrowernumber int(11) NOT NULL,
5486   file_name varchar(255) NOT NULL,
5487   file_type varchar(255) NOT NULL,
5488   file_description varchar(255) DEFAULT NULL,
5489   file_content longblob NOT NULL,
5490   date_uploaded timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
5491   PRIMARY KEY (file_id),
5492   KEY borrowernumber (borrowernumber)
5493 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
5494     ");
5495     $dbh->do("ALTER TABLE borrower_files ADD CONSTRAINT borrower_files_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE");
5496
5497     print "Upgrade to $DBversion done (Added borrow_files table, EnableBorrowerFiles syspref)\n";
5498     SetVersion($DBversion);
5499 }
5500
5501 $DBversion = "3.09.00.021";
5502 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5503     $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');");
5504     print "Upgrade to $DBversion done (Add syspref UpdateTotalIssuesOnCirc)\n";
5505     SetVersion($DBversion);
5506 }
5507
5508 $DBversion = "3.09.00.022";
5509 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5510     $dbh->do("ALTER TABLE search_history MODIFY COLUMN query_cgi text NOT NULL");
5511     print "Upgrade to $DBversion done (Change search_history.query_cgi type to text. bug 5981)\n";
5512     SetVersion($DBversion);
5513 }
5514
5515 $DBversion = "3.09.00.023";
5516 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5517     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('SearchEngine','Zebra','Solr|Zebra','Search Engine','Choice')");
5518     print "Upgrade to $DBversion done (Add system preference SearchEngine )\n";
5519     SetVersion($DBversion);
5520 }
5521
5522 $DBversion ="3.09.00.024";
5523 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5524     $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')");
5525     print "Upgrade to $DBversion done (Add system preference IntranetSlipPrinterJS))\n";
5526     SetVersion($DBversion);
5527 }
5528
5529 $DBversion = "3.09.00.025";
5530 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5531     $dbh->do('START TRANSACTION');
5532     $dbh->do('CREATE TABLE tmp_reserves AS SELECT * FROM old_reserves LIMIT 0');
5533     $dbh->do('ALTER TABLE tmp_reserves ADD reserve_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
5534     $dbh->do("
5535         INSERT INTO tmp_reserves (
5536           borrowernumber, reservedate, biblionumber,
5537           constrainttype, branchcode, notificationdate,
5538           reminderdate, cancellationdate, reservenotes,
5539           priority, found, timestamp, itemnumber,
5540           waitingdate, expirationdate, lowestPriority,
5541           suspend, suspend_until
5542         ) SELECT
5543           borrowernumber, reservedate, biblionumber,
5544           constrainttype, branchcode, notificationdate,
5545           reminderdate, cancellationdate, reservenotes,
5546           priority, found, timestamp, itemnumber,
5547           waitingdate, expirationdate, lowestPriority,
5548           suspend, suspend_until
5549         FROM old_reserves ORDER BY reservedate
5550     ");
5551     $dbh->do('SET @ai = ( SELECT MAX( reserve_id ) FROM tmp_reserves )');
5552     $dbh->do('TRUNCATE old_reserves');
5553     $dbh->do('ALTER TABLE old_reserves ADD reserve_id INT( 11 ) NOT NULL PRIMARY KEY FIRST');
5554     $dbh->do('INSERT INTO old_reserves SELECT * FROM tmp_reserves WHERE reserve_id <= @ai');
5555     $dbh->do("
5556         INSERT INTO tmp_reserves (
5557           borrowernumber, reservedate, biblionumber,
5558           constrainttype, branchcode, notificationdate,
5559           reminderdate, cancellationdate, reservenotes,
5560           priority, found, timestamp, itemnumber,
5561           waitingdate, expirationdate, lowestPriority,
5562           suspend, suspend_until
5563         ) SELECT
5564           borrowernumber, reservedate, biblionumber,
5565           constrainttype, branchcode, notificationdate,
5566           reminderdate, cancellationdate, reservenotes,
5567           priority, found, timestamp, itemnumber,
5568           waitingdate, expirationdate, lowestPriority,
5569           suspend, suspend_until
5570         FROM reserves ORDER BY reservedate
5571     ");
5572     $dbh->do('TRUNCATE reserves');
5573     $dbh->do('ALTER TABLE reserves ADD reserve_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
5574     $dbh->do('INSERT INTO reserves SELECT * FROM tmp_reserves WHERE reserve_id > COALESCE(@ai, 0)');
5575     $dbh->do('DROP TABLE tmp_reserves');
5576     $dbh->do('COMMIT');
5577
5578     my $sth = $dbh->prepare("
5579         SELECT COUNT( * ) AS count
5580         FROM information_schema.COLUMNS
5581         WHERE COLUMN_NAME =  'reserve_id'
5582         AND (
5583           TABLE_NAME LIKE  'reserves'
5584           OR
5585           TABLE_NAME LIKE  'old_reserves'
5586         )
5587     ");
5588     $sth->execute();
5589     my $row = $sth->fetchrow_hashref();
5590     die("Failed to add reserve_id to reserves tables, please refresh the page to try again.") unless ( $row->{'count'} );
5591
5592     print "Upgrade to $DBversion done (add reserve_id to reserves & old_reserves tables)\n";
5593     SetVersion($DBversion);
5594 }
5595
5596 $DBversion = "3.09.00.026";
5597 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5598     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
5599         ( 3, 'parameters_remaining_permissions', 'Remaining system parameters permissions'),
5600         ( 3, 'manage_circ_rules', 'manage circulation rules')");
5601     $dbh->do("INSERT INTO user_permissions (borrowernumber, module_bit, code)
5602         SELECT borrowernumber, 3, 'parameters_remaining_permissions'
5603         FROM borrowers WHERE flags & (1 << 3)");
5604     # Give new subpermissions to all users that have 'parameters' permission flag (bit 3) set
5605     # see userflags table
5606     $dbh->do("INSERT INTO user_permissions (borrowernumber, module_bit, code)
5607         SELECT borrowernumber, 3, 'manage_circ_rules'
5608         FROM borrowers WHERE flags & (1 << 3)");
5609     print "Upgrade to $DBversion done (Added parameters subpermissions)\n";
5610     SetVersion($DBversion);
5611 }
5612
5613 $DBversion = '3.09.00.027';
5614 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5615     $dbh->do("ALTER TABLE issuingrules ADD overduefinescap decimal(28,6) DEFAULT NULL");
5616     my $maxfine = C4::Context->preference('MaxFine');
5617     if ($maxfine && $maxfine < 900) { # an arbitrary value that tells us it's not "some huge value"
5618       $dbh->do("UPDATE issuingrules SET overduefinescap=?",undef,$maxfine);
5619       $dbh->do("UPDATE systempreferences SET value = NULL WHERE variable = 'MaxFine'");
5620     }
5621     $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'");
5622     print "Upgrade to $DBversion done (Bug 7420 add overduefinescap to circulation matrix)\n";
5623     SetVersion ($DBversion);
5624 }
5625
5626 $DBversion = "3.09.00.028";
5627 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5628     unless ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) {
5629         my %referencetypes = (  '00' => 'PERSO_NAME',
5630                                 '10' => 'CORPO_NAME',
5631                                 '11' => 'MEETI_NAME',
5632                                 '30' => 'UNIF_TITLE',
5633                                 '48' => 'CHRON_TERM',
5634                                 '50' => 'TOPIC_TERM',
5635                                 '51' => 'GEOGR_NAME',
5636                                 '55' => 'GENRE/FORM'
5637                 );
5638         my $query = q{SELECT DISTINCT authtypecode, tagfield
5639                     FROM auth_subfield_structure
5640                     WHERE (tagfield BETWEEN '400' AND '455' OR
5641                     tagfield BETWEEN '500' and '555') AND tagsubfield='a' AND
5642                     frameworkcode = '' AND ROW(authtypecode, tagfield) NOT IN
5643                     (SELECT authtypecode, tagfield FROM auth_subfield_structure
5644                     WHERE tagsubfield ='9' )};
5645         $sth = $dbh->prepare($query);
5646         $sth->execute;
5647         my $sth2 = $dbh->prepare(q{INSERT INTO auth_subfield_structure
5648                 (authtypecode, tagfield, tagsubfield, liblibrarian, libopac,
5649                  repeatable, mandatory, tab, authorised_value, value_builder,
5650                  seealso, isurl, hidden, linkid, kohafield, frameworkcode)
5651                 VALUES (?, ?, '9', '9 (RLIN)', '9 (RLIN)', 0, 0, ?, NULL, NULL,
5652                     NULL, 0, 1, '', '', '')});
5653         my $sth3 = $dbh->prepare(q{UPDATE auth_subfield_structure SET
5654                                     frameworkcode = ? WHERE authtypecode = ? AND
5655                                     tagfield = ? AND tagsubfield = 'a'});
5656         while (my $row = $sth->fetchrow_arrayref()) {
5657             my ($authtypecode, $field) = @$row;
5658             $sth2->execute($authtypecode, $field, substr($field, 0, 1));
5659             my $authtypemarker = substr $field, 1, 2;
5660             if ($authtypemarker && $referencetypes{$authtypemarker}) {
5661                 $sth3->execute($referencetypes{$authtypemarker}, $authtypecode, $field);
5662             }
5663         }
5664     }
5665
5666     print "Upgrade to $DBversion done (Add thesaurus links for MARC21/NORMARC)\n";
5667     SetVersion($DBversion);
5668 }
5669
5670 $DBversion = "3.09.00.029"; # FIXME
5671 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5672     $dbh->do("UPDATE systempreferences SET options=concat(options,'|EAN13') WHERE variable='itemBarcodeInputFilter' AND options NOT LIKE '%EAN13%'");
5673     print "Upgrade to $DBversion done (Add itemBarcodeInputFilter choice EAN13)\n";
5674
5675     $dbh->do("UPDATE systempreferences SET options = concat(options,'|EAN13'), explanation = concat(explanation,'; EAN13 - incremental') WHERE variable = 'autoBarcode' AND options NOT LIKE '%EAN13%'");
5676     print "Upgrade to $DBversion done ( Added EAN13 barcode autogeneration sequence )\n";
5677     SetVersion($DBversion);
5678 }
5679
5680 $DBversion ="3.09.00.030";
5681 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5682     my $query = "SELECT value FROM systempreferences WHERE variable='opacstylesheet'";
5683     my $remote= $dbh->selectrow_arrayref($query);
5684     $dbh->do("DELETE from systempreferences WHERE variable='opacstylesheet'");
5685     if($remote && $remote->[0]) {
5686         $query="UPDATE systempreferences SET value=? WHERE variable='opaclayoutstylesheet'";
5687         $dbh->do($query,undef,$remote->[0]);
5688         print "NOTE: The URL of your remote opac css file has been moved to preference opaclayoutstylesheet.\n";
5689     }
5690     print "Upgrade to $DBversion done (BZ 8263: Make OPAC stylesheet preferences more consistent)\n";
5691     SetVersion($DBversion);
5692 }
5693
5694 $DBversion = "3.09.00.031";
5695 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5696     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonReviews'");
5697     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonSimilarItems'");
5698     $dbh->do("DELETE FROM systempreferences WHERE variable='AWSAccessKeyID'");
5699     $dbh->do("DELETE FROM systempreferences WHERE variable='AWSPrivateKey'");
5700     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonReviews'");
5701     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonSimilarItems'");
5702     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonEnabled'");
5703     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonEnabled'");
5704     print "Upgrade to $DBversion done ('Remove preferences controlling broken Amazon features (Bug 8679')\n";
5705     SetVersion ($DBversion);
5706 }
5707
5708 $DBversion = "3.09.00.032";
5709 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5710     $dbh->do("UPDATE systempreferences SET value = 'call_number' WHERE variable = 'defaultSortField' AND value = 'callnumber'");
5711     $dbh->do("UPDATE systempreferences SET value = 'call_number' WHERE variable = 'OPACdefaultSortField' AND value = 'callnumber'");
5712     print "Upgrade to $DBversion done (Bug 8657 - Default sort by call number does not work. Correcting system preference value.)\n";
5713     SetVersion ($DBversion);
5714 }
5715
5716
5717 $DBversion = '3.09.00.033';
5718 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5719    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacSuppressionByIPRange','','Restrict the suppression to IP adresses outside of the IP range','','free');");
5720    print "Upgrade to $DBversion done (Add OpacSuppressionByIPRange syspref)\n";
5721    SetVersion ($DBversion);
5722 }
5723
5724 $DBversion ="3.09.00.034";
5725 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5726     $dbh->do("UPDATE auth_subfield_structure SET frameworkcode = 'PERSO_NAME' WHERE frameworkcode = 'PERSO_CODE'");
5727     $dbh->do("UPDATE auth_subfield_structure SET frameworkcode = 'CORPO_NAME' WHERE frameworkcode = 'ORGO_CODE'");
5728     print "Upgrade to $DBversion done (Bug 8207: correct typo in authority types)\n";
5729     SetVersion ($DBversion);
5730 }
5731
5732 $DBversion = "3.09.00.035";
5733 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5734     $dbh->do("
5735     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');
5736     ");
5737     $dbh->do(
5738     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SubfieldsToUseWhenPrefill','','Define a list of subfields to use when prefilling items (separated by space)','','Free');
5739     ");
5740     print "Upgrade to $DBversion done (Adding PrefillItem and SubfieldsToUseWhenPrefill sysprefs)\n";
5741     SetVersion ($DBversion);
5742 }
5743
5744 $DBversion = "3.09.00.036";
5745 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5746     # biblioitems changes
5747     $dbh->do("ALTER TABLE biblioitems ADD COLUMN agerestriction VARCHAR(255) DEFAULT NULL AFTER cn_sort");
5748     $dbh->do("ALTER TABLE deletedbiblioitems ADD COLUMN agerestriction VARCHAR(255) DEFAULT NULL AFTER cn_sort");
5749     # preferences changes
5750     $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')");
5751     $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')");
5752
5753     print "Upgrade to $DBversion done (Add colum agerestriction to biblioitems and deletedbiblioitems, add system preferences AgeRestrictionMarker and AgeRestrictionOverride)\n";
5754    SetVersion ($DBversion);
5755 }
5756
5757 $DBversion = "3.09.00.037";
5758 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5759     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('UseTransportCostMatrix',0,'Use Transport Cost Matrix when filling holds','','YesNo')");
5760
5761  $dbh->do("CREATE TABLE `transport_cost` (
5762               `frombranch` varchar(10) NOT NULL,
5763               `tobranch` varchar(10) NOT NULL,
5764               `cost` decimal(6,2) NOT NULL,
5765               `disable_transfer` tinyint(1) NOT NULL DEFAULT 0,
5766               CHECK ( `frombranch` <> `tobranch` ), -- a dud check, mysql does not support that
5767               PRIMARY KEY (`frombranch`, `tobranch`),
5768               CONSTRAINT `transport_cost_ibfk_1` FOREIGN KEY (`frombranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
5769               CONSTRAINT `transport_cost_ibfk_2` FOREIGN KEY (`tobranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
5770           ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
5771
5772     print "Upgrade to $DBversion done (creating `transport_cost` table; adding UseTransportCostMatrix systempref, in circulation)\n";
5773     SetVersion($DBversion);
5774 }
5775
5776 $DBversion ="3.09.00.038";
5777 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5778     $dbh->do("ALTER TABLE borrower_attributes CHANGE  attribute  attribute VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
5779     print "Upgrade to $DBversion done (Increase the maximum size of a borrower attribute value)\n";
5780     SetVersion($DBversion);
5781 }
5782
5783 $DBversion ="3.09.00.039";
5784 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5785     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,type) VALUES('DidYouMeanFromAuthorities','0','Suggest searches based on authority file.','YesNo');");
5786     print "Upgrade to $DBversion done (Add system preference DidYouMeanFromAuthorities)\n";
5787     SetVersion($DBversion);
5788 }
5789
5790 $DBversion = "3.09.00.040";
5791 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5792     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('IncludeSeeFromInSearches','0','','Include see-from references in searches.','YesNo');");
5793     print "Upgrade to $DBversion done (Add IncludeSeeFromInSearches system preference)\n";
5794     SetVersion ($DBversion);
5795 }
5796
5797 $DBversion = "3.09.00.041";
5798 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5799     $dbh->do(qq{
5800         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ExportRemoveFields','','List of fields for non export in circulation.pl (separated by a space)','','');
5801     });
5802     print "Upgrade to $DBversion done (Add system preference ExportRemoveFields)\n";
5803     SetVersion($DBversion);
5804 }
5805
5806 $DBversion = "3.09.00.042";
5807 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5808     $dbh->do(qq{
5809         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ExportWithCsvProfile','','Set a profile name for CSV export','','');
5810     });
5811     print "Upgrade to $DBversion done (Adds New System preference ExportWithCsvProfile)\n";
5812     SetVersion($DBversion)
5813 }
5814
5815 $DBversion = "3.09.00.043";
5816 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5817     $dbh->do("
5818         ALTER TABLE aqorders
5819         ADD parent_ordernumber int(11) DEFAULT NULL
5820     ");
5821     $dbh->do("
5822         UPDATE aqorders
5823         SET parent_ordernumber = ordernumber;
5824     ");
5825     print "Upgrade to $DBversion done (Adding parent_ordernumber in aqorders)\n";
5826     SetVersion($DBversion);
5827 }
5828
5829 $DBversion = '3.09.00.044';
5830 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5831     $dbh->do("ALTER TABLE statistics ADD COLUMN ccode VARCHAR ( 10 ) NULL AFTER associatedborrower");
5832     $dbh->do("UPDATE statistics SET statistics.ccode = ( SELECT items.ccode FROM items WHERE statistics.itemnumber = items.itemnumber )");
5833     $dbh->do("UPDATE statistics SET statistics.ccode = (
5834               SELECT deleteditems.ccode FROM deleteditems
5835                   WHERE statistics.itemnumber = deleteditems.itemnumber
5836               ) WHERE statistics.ccode IS NULL");
5837     print "Upgrade done ( Added Collection Code to Statistics table. )\n";
5838     SetVersion ($DBversion);
5839 }
5840
5841 $DBversion = "3.09.00.045";
5842 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5843     $dbh->do("ALTER TABLE borrower_attribute_types MODIFY category_code VARCHAR( 10 ) NULL DEFAULT NULL");
5844     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.";
5845     SetVersion($DBversion);
5846 }
5847
5848 $DBversion = "3.09.00.046";
5849 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5850     $dbh->do("ALTER TABLE `accountlines` ADD `accountlines_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;");
5851     print "Upgrade to $DBversion done (adding accountlines_id field in accountlines table)\n";
5852     SetVersion($DBversion);
5853 }
5854
5855 $DBversion = "3.09.00.047";
5856 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5857     # to preserve default behaviour as best as possible, set this new preference differently depending on whether IndependantBranches is set or not
5858     my $prefvalue = 'anywhere';
5859     if (C4::Context->preference("IndependantBranches")) { $prefvalue = 'homeorholdingbranch';}
5860     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowReturnToBranch', '$prefvalue', 'Where an item may be returned', 'anywhere|homebranch|holdingbranch|homeorholdingbranch', 'Choice');");
5861
5862     print "Upgrade to $DBversion done: adding AllowReturnToBranch syspref (bug 6151)";
5863     SetVersion($DBversion);
5864 }
5865
5866 $DBversion = "3.09.00.048";
5867 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5868     $dbh->do("ALTER TABLE authorised_values MODIFY lib varchar(200)");
5869     $dbh->do("ALTER TABLE authorised_values MODIFY lib_opac varchar(200)");
5870
5871     print "Upgrade to $DBversion done (Raise the length of Authorised Values descriptions)\n";
5872     SetVersion($DBversion);
5873 }
5874
5875 $DBversion ="3.09.00.049";
5876 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5877     $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');");
5878     $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');");
5879     $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');");
5880     $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');");
5881     print "Upgrade to $DBversion done (Add OPACMobileUserCSS, OpacMainUserBlockMobile, OpacShowLibrariesPulldownMobile and OpacShowFiltersPulldownMobile sysprefs)\n";
5882     SetVersion($DBversion);
5883 }
5884
5885 $DBversion = "3.09.00.050";
5886 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5887     $dbh->do("ALTER TABLE authorised_values MODIFY category varchar(16) NOT NULL DEFAULT '';");
5888     $dbh->do("INSERT INTO authorised_values (category, authorised_value, lib) VALUES
5889               ('REPORT_GROUP', 'CIRC', 'Circulation'),
5890               ('REPORT_GROUP', 'CAT', 'Catalog'),
5891               ('REPORT_GROUP', 'PAT', 'Patrons'),
5892               ('REPORT_GROUP', 'ACQ', 'Acquisitions'),
5893               ('REPORT_GROUP', 'ACC', 'Accounts');");
5894
5895     $dbh->do("ALTER TABLE reports_dictionary ADD report_area varchar(6) DEFAULT NULL;");
5896     $dbh->do("UPDATE reports_dictionary SET report_area = CASE area
5897                   WHEN 1 THEN 'CIRC'
5898                   WHEN 2 THEN 'CAT'
5899                   WHEN 3 THEN 'PAT'
5900                   WHEN 4 THEN 'ACQ'
5901                   WHEN 5 THEN 'ACC'
5902                   END;");
5903     $dbh->do("ALTER TABLE reports_dictionary DROP area;");
5904     $dbh->do("ALTER TABLE reports_dictionary ADD KEY dictionary_area_idx (report_area);");
5905
5906     $dbh->do("ALTER TABLE saved_sql ADD report_area varchar(6) DEFAULT NULL;");
5907     $dbh->do("ALTER TABLE saved_sql ADD report_group varchar(80) DEFAULT NULL;");
5908     $dbh->do("ALTER TABLE saved_sql ADD report_subgroup varchar(80) DEFAULT NULL;");
5909     $dbh->do("ALTER TABLE saved_sql ADD KEY sql_area_group_idx (report_group, report_subgroup);");
5910
5911     print "Upgrade to $DBversion done saved_sql new fields report_group and report_area; authorised_values.category 16 char \n";
5912     SetVersion($DBversion);
5913 }
5914
5915 $DBversion = "3.09.00.051";
5916 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5917     $dbh->do("
5918         CREATE TABLE aqinvoices (
5919           invoiceid int(11) NOT NULL AUTO_INCREMENT,
5920           invoicenumber mediumtext NOT NULL,
5921           booksellerid int(11) NOT NULL,
5922           shipmentdate date default NULL,
5923           billingdate date default NULL,
5924           closedate date default NULL,
5925           shipmentcost decimal(28,6) default NULL,
5926           shipmentcost_budgetid int(11) default NULL,
5927           PRIMARY KEY (invoiceid),
5928           CONSTRAINT aqinvoices_fk_aqbooksellerid FOREIGN KEY (booksellerid) REFERENCES aqbooksellers (id) ON DELETE CASCADE ON UPDATE CASCADE,
5929           CONSTRAINT aqinvoices_fk_shipmentcost_budgetid FOREIGN KEY (shipmentcost_budgetid) REFERENCES aqbudgets (budget_id) ON DELETE SET NULL ON UPDATE CASCADE
5930         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5931     ");
5932
5933     # Fill this new table with existing invoices
5934     my $sth = $dbh->prepare("
5935         SELECT aqorders.booksellerinvoicenumber AS invoicenumber, aqbasket.booksellerid, aqorders.datereceived
5936         FROM aqorders
5937           LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
5938         WHERE aqorders.booksellerinvoicenumber IS NOT NULL
5939           AND aqorders.booksellerinvoicenumber != ''
5940         GROUP BY aqorders.booksellerinvoicenumber
5941     ");
5942     $sth->execute;
5943     my $results = $sth->fetchall_arrayref({});
5944     $sth = $dbh->prepare("
5945         INSERT INTO aqinvoices (invoicenumber, booksellerid, shipmentdate) VALUES (?,?,?)
5946     ");
5947     foreach(@$results) {
5948         $sth->execute($_->{invoicenumber}, $_->{booksellerid}, $_->{datereceived});
5949     }
5950
5951     # Add the column in aqorders, fill it with correct value
5952     # and then drop booksellerinvoicenumber column
5953     $dbh->do("
5954         ALTER TABLE aqorders
5955         ADD COLUMN invoiceid int(11) default NULL AFTER booksellerinvoicenumber,
5956         ADD CONSTRAINT aqorders_ibfk_3 FOREIGN KEY (invoiceid) REFERENCES aqinvoices (invoiceid) ON DELETE SET NULL ON UPDATE CASCADE
5957     ");
5958
5959     $dbh->do("
5960         UPDATE aqorders, aqinvoices
5961         SET aqorders.invoiceid = aqinvoices.invoiceid
5962         WHERE aqorders.booksellerinvoicenumber = aqinvoices.invoicenumber
5963     ");
5964
5965     $dbh->do("
5966         ALTER TABLE aqorders
5967         DROP COLUMN booksellerinvoicenumber
5968     ");
5969
5970     print "Upgrade to $DBversion done (Add aqinvoices table) \n";
5971     SetVersion ($DBversion);
5972 }
5973
5974 $DBversion = "3.09.00.052";
5975 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5976     $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');");
5977     $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');");
5978     $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');");
5979     print "Upgrade to $DBversion done (Add systempreferences to decrease loan length on high demand items decreaseLoanHighHolds, decreaseLoanHighHoldsValue and decreaseLoanHighHoldsDuration) \n";
5980     SetVersion ($DBversion);
5981 }
5982
5983 $DBversion = "3.09.00.053";
5984 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5985     $dbh->do(
5986     q|CREATE TABLE `import_auths` (
5987         import_record_id int(11) NOT NULL,
5988         matched_authid int(11) default NULL,
5989         control_number varchar(25) default NULL,
5990         authorized_heading varchar(128) default NULL,
5991         original_source varchar(25) default NULL,
5992         CONSTRAINT import_auths_ibfk_1 FOREIGN KEY (import_record_id)
5993         REFERENCES import_records (import_record_id) ON DELETE CASCADE ON UPDATE CASCADE,
5994         KEY matched_authid (matched_authid)
5995         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;|
5996     );
5997     $dbh->do("ALTER TABLE import_batches
5998                 CHANGE COLUMN num_biblios num_records int(11) NOT NULL default 0,
5999                 ADD COLUMN record_type enum('biblio', 'auth', 'holdings') NOT NULL default 'biblio'");
6000     $dbh->do("UPDATE import_batches SET record_type='auth' WHERE import_batch_id IN
6001                 (SELECT import_batch_id FROM import_records WHERE record_type='auth')");
6002
6003     print "Upgrade to $DBversion done (Added support for staging authorities)\n";
6004     SetVersion ($DBversion);
6005 }
6006
6007 $DBversion = "3.09.00.054";
6008 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6009     $dbh->do("ALTER TABLE aqorders CHANGE COLUMN gst gstrate DECIMAL(6,4)  DEFAULT NULL");
6010     print "Upgrade to $DBversion done (Change column name in aqorders gst --> gstrate)\n";
6011     SetVersion($DBversion);
6012 }
6013
6014 $DBversion = "3.09.00.055";
6015 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6016     $dbh->do("ALTER TABLE aqorders ADD discount float(6,4) DEFAULT NULL AFTER gstrate");
6017     print "Upgrade to $DBversion done (Add discount field in aqorders table)\n";
6018     SetVersion($DBversion);
6019 }
6020
6021 $DBversion ="3.09.00.056";
6022 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6023     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('AuthDisplayHierarchy','0','Display authority hierarchies','','YesNo')");
6024     print "Upgrade to $DBversion done (Add system preference AuthDisplayHierarchy)\n";
6025     SetVersion($DBversion);
6026 }
6027
6028 $DBversion = "3.09.00.057";
6029 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6030     $dbh->do("ALTER TABLE aqbasket ADD deliveryplace VARCHAR(10) default NULL AFTER basketgroupid;");
6031     $dbh->do("ALTER TABLE aqbasket ADD billingplace VARCHAR(10) default NULL AFTER deliveryplace;");
6032     print "Upgrade to $DBversion done (Bug 5356: Added billingplace, deliveryplace to the aqbasket table)\n";
6033     SetVersion($DBversion);
6034 }
6035
6036 $DBversion ="3.09.00.058";
6037 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6038     $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');");
6039     $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');");
6040     print "Upgrade to $DBversion done (Add Did You Mean? configuration)\n";
6041     SetVersion($DBversion);
6042 }
6043
6044 $DBversion ="3.09.00.059";
6045 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6046     $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');");
6047     print "Upgrade to $DBversion done (Add system preference BlockReturnOfWithdrawnItems)\n";
6048     SetVersion($DBversion);
6049 }
6050
6051 $DBversion = "3.09.00.060";
6052 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6053     $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')");
6054     print "Upgrade to $DBversion done (Added HoldsToPullStartDate syspref)\n";
6055     SetVersion($DBversion);
6056 }
6057
6058 $DBversion = "3.09.00.061";
6059 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6060     $dbh->do("UPDATE systempreferences set value=0 WHERE variable='OPACItemsResultsDisplay' AND value='statuses'");
6061     $dbh->do("UPDATE systempreferences set value=1 WHERE variable='OPACItemsResultsDisplay' AND value='itemdetails'");
6062     $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'");
6063     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";
6064     SetVersion ($DBversion);
6065 }
6066
6067 $DBversion = "3.09.00.062";
6068 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6069    $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='NoZebra'");
6070    $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='QueryRemoveStopwords'");
6071    print "Upgrade to $DBversion done (Disable obsolete NoZebra and QueryRemoveStopwords sysprefs)\n";
6072    SetVersion ($DBversion);
6073 }
6074
6075 $DBversion = "3.09.00.063";
6076 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6077     my $gst_booksellers = $dbh->selectcol_arrayref("SELECT DISTINCT(gstrate) FROM aqbooksellers");
6078     my $gist_syspref = C4::Context->preference("gist");
6079     # remove the undef values and construct and array with the syspref and the supplier values
6080     my @gstrates = map { defined $_ ? $_ : () } @$gst_booksellers;
6081     push @gstrates, split ('\|', $gist_syspref);
6082     # we want to compare integer (or float)
6083     $_ = $_ + 0 for @gstrates;
6084     use List::MoreUtils qw/uniq/;
6085     # remove duplicate values
6086     @gstrates = uniq sort @gstrates;
6087     my $new_syspref_value = join '|', @gstrates;
6088     # update the syspref with the new values
6089     my $sth = $dbh->prepare("UPDATE systempreferences set value=? WHERE variable='gist'");
6090     $sth->execute( $new_syspref_value );
6091
6092     print "Upgrade to $DBversion done (Bug 8832, Set the syspref gist with the existing values)\n";
6093     SetVersion ($DBversion);
6094 }
6095
6096 $DBversion = "3.09.00.064";
6097 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6098    $dbh->do('ALTER TABLE items ADD coded_location_qualifier varchar(10) default NULL AFTER itemcallnumber');
6099    print "Upgrade to $DBversion done (Bug 6428: Added coded_location_qualifier to the items table)\n";
6100    SetVersion ($DBversion);
6101 }
6102
6103 $DBversion = "3.09.00.065";
6104 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6105    $dbh->do('ALTER TABLE deleteditems ADD coded_location_qualifier varchar(10) default NULL AFTER itemcallnumber');
6106    print "Upgrade to $DBversion done (Bug 6428: Added coded_location_qualifier to the deleteditems table)\n";
6107    SetVersion ($DBversion);
6108 }
6109
6110 $DBversion = "3.09.00.066";
6111 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6112    $dbh->do("DELETE FROM systempreferences WHERE variable='DidYouMeanFromAuthorities'");
6113    print "Upgrade to $DBversion done (Bug 9107: remove DidYouMeanFromAuthorities syspref)\n";
6114    SetVersion ($DBversion);
6115 }
6116
6117 $DBversion = "3.09.00.067";
6118 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6119    $dbh->do("ALTER TABLE statistics CHANGE COLUMN ccode ccode varchar(10) NULL");
6120    print "Upgrade to $DBversion done (Bug 9064: statistics.ccode potentially wrongly defined)\n";
6121    SetVersion ($DBversion);
6122 }
6123
6124 $DBversion = "3.10.00.00";
6125 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6126    print "Upgrade to $DBversion done (release tag)\n";
6127    SetVersion ($DBversion);
6128 }
6129
6130 $DBversion = "3.11.00.001";
6131 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6132     $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')");
6133     print "Upgrade to $DBversion done (Bug 2832 - Add alphabet syspref)\n";
6134 }
6135
6136 $DBversion = "3.11.00.002";
6137 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6138     $dbh->do(q{
6139         DELETE from aqorders_items where ordernumber NOT IN (SELECT ordernumber FROM aqorders);
6140     });
6141     $dbh->do(q{
6142         ALTER TABLE aqorders_items
6143         ADD CONSTRAINT aqorders_items_ibfk_1 FOREIGN KEY (ordernumber) REFERENCES aqorders (ordernumber)
6144         ON DELETE CASCADE ON UPDATE CASCADE;
6145     });
6146     print "Upgrade to $DBversion done (Bug 9030: Add constraint on aqorders_items.ordernumber)\n";
6147     SetVersion ($DBversion);
6148 }
6149
6150 $DBversion = "3.11.00.003";
6151 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6152     $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')");
6153     print "Upgrade to $DBversion done (Bug 7189: Add system preference RefundLostItemFeeOnReturn)\n";
6154     SetVersion($DBversion);
6155 }
6156
6157 $DBversion = "3.11.00.004";
6158 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6159     $dbh->do(qq{
6160         ALTER TABLE subscription ADD COLUMN closed INT(1) NOT NULL DEFAULT 0 AFTER enddate;
6161     });
6162
6163     print "Upgrade to $DBversion done (Bug 8782: Add field subscription.closed)\n";
6164     SetVersion($DBversion);
6165 }
6166
6167 $DBversion = "3.11.00.005";
6168 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6169     $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;});
6170
6171     $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;});
6172
6173     $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;});
6174
6175     print "Upgrade to $DBversion done (Bug 7919: Display of values depending on the connexion library)\n";
6176     SetVersion($DBversion);
6177 }
6178
6179 $DBversion = "3.11.00.006";
6180 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6181     $dbh->do(q{
6182         UPDATE virtualshelves SET sortfield="copyrightdate" where sortfield="year";
6183     });
6184     print "Upgrade to $DBversion done (Bug 9167: Update the virtualshelves.sortfield column with 'copyrightdate' if needed)\n";
6185     SetVersion($DBversion);
6186 }
6187
6188 $DBversion = "3.11.00.007";
6189 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6190     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ar', 'language', 'de', 'Arabisch')");
6191     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hy', 'language', 'de', 'Armenisch')");
6192     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'bg', 'language', 'de', 'Bulgarisch')");
6193     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'zh', 'language', 'de', 'Chinesisch')");
6194     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'cs', 'language', 'de', 'Tschechisch')");
6195     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'da', 'language', 'de', 'Dänisch')");
6196     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nl', 'language', 'de', 'Niederländisch')");
6197     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'en', 'language', 'de', 'Englisch')");
6198     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fi', 'language', 'de', 'Finnisch')");
6199     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fr', 'language', 'de', 'Französisch')");
6200     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'lo', 'language', 'fr', 'Laotien')");
6201     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'lo', 'language', 'de', 'Laotisch')");
6202     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'el', 'language', 'de', 'Griechisch (Nach 1453)')");
6203     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'he', 'language', 'de', 'Hebräisch')");
6204     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hi', 'language', 'de', 'Hindi')");
6205     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hu', 'language', 'de', 'Ungarisch')");
6206     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'id', 'language', 'de', 'Indonesisch')");
6207     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'it', 'language', 'de', 'Italienisch')");
6208     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ja', 'language', 'de', 'Japanisch')");
6209     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ko', 'language', 'de', 'Koreanisch')");
6210     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'la', 'language', 'de', 'Latein')");
6211     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'gl', 'language', 'fr', 'Galicien')");
6212     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'gl', 'language', 'de', 'Galizisch')");
6213     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nb', 'language', 'de', 'Norwegisch bokm&#229;l')");
6214     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nn', 'language', 'de', 'Norwegisch nynorsk')");
6215     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fa', 'language', 'de', 'Persisch')");
6216     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'pl', 'language', 'de', 'Polnisch')");
6217     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'pt', 'language', 'de', 'Portugiesisch')");
6218     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ro', 'language', 'de', 'Rumänisch')");
6219     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ru', 'language', 'de', 'Russisch')");
6220     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sr', 'language', 'fr', 'Serbe')");
6221     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sr', 'language', 'de', 'Serbisch')");
6222     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'es', 'language', 'de', 'Spanisch')");
6223     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sv', 'language', 'de', 'Schwedisch')");
6224     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tet', 'language', 'fr', 'Tétoum')");
6225     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tet', 'language', 'de', 'Tetum')");
6226     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'th', 'language', 'de', 'Thailändisch')");
6227     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tr', 'language', 'de', 'Türkisch')");
6228     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'uk', 'language', 'de', 'Ukrainisch')");
6229     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ur', 'language', 'fr', 'Ourdou')");
6230     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ur', 'language', 'de', 'Urdu')");
6231     print "Upgrade to $DBversion done (Bug 9056: add German and a couple of French translations to language_descriptions)\n";
6232     SetVersion ($DBversion);
6233 }
6234
6235 $DBversion = "3.11.00.008";
6236 if (CheckVersion($DBversion)) {
6237     $dbh->do("
6238         CREATE TABLE IF NOT EXISTS `borrower_modifications` (
6239           `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6240           `verification_token` varchar(255) NOT NULL DEFAULT '',
6241           `borrowernumber` int(11) NOT NULL DEFAULT '0',
6242           `cardnumber` varchar(16) DEFAULT NULL,
6243           `surname` mediumtext,
6244           `firstname` text,
6245           `title` mediumtext,
6246           `othernames` mediumtext,
6247           `initials` text,
6248           `streetnumber` varchar(10) DEFAULT NULL,
6249           `streettype` varchar(50) DEFAULT NULL,
6250           `address` mediumtext,
6251           `address2` text,
6252           `city` mediumtext,
6253           `state` text,
6254           `zipcode` varchar(25) DEFAULT NULL,
6255           `country` text,
6256           `email` mediumtext,
6257           `phone` text,
6258           `mobile` varchar(50) DEFAULT NULL,
6259           `fax` mediumtext,
6260           `emailpro` text,
6261           `phonepro` text,
6262           `B_streetnumber` varchar(10) DEFAULT NULL,
6263           `B_streettype` varchar(50) DEFAULT NULL,
6264           `B_address` varchar(100) DEFAULT NULL,
6265           `B_address2` text,
6266           `B_city` mediumtext,
6267           `B_state` text,
6268           `B_zipcode` varchar(25) DEFAULT NULL,
6269           `B_country` text,
6270           `B_email` text,
6271           `B_phone` mediumtext,
6272           `dateofbirth` date DEFAULT NULL,
6273           `branchcode` varchar(10) DEFAULT NULL,
6274           `categorycode` varchar(10) DEFAULT NULL,
6275           `dateenrolled` date DEFAULT NULL,
6276           `dateexpiry` date DEFAULT NULL,
6277           `gonenoaddress` tinyint(1) DEFAULT NULL,
6278           `lost` tinyint(1) DEFAULT NULL,
6279           `debarred` date DEFAULT NULL,
6280           `debarredcomment` varchar(255) DEFAULT NULL,
6281           `contactname` mediumtext,
6282           `contactfirstname` text,
6283           `contacttitle` text,
6284           `guarantorid` int(11) DEFAULT NULL,
6285           `borrowernotes` mediumtext,
6286           `relationship` varchar(100) DEFAULT NULL,
6287           `ethnicity` varchar(50) DEFAULT NULL,
6288           `ethnotes` varchar(255) DEFAULT NULL,
6289           `sex` varchar(1) DEFAULT NULL,
6290           `password` varchar(30) DEFAULT NULL,
6291           `flags` int(11) DEFAULT NULL,
6292           `userid` varchar(75) DEFAULT NULL,
6293           `opacnote` mediumtext,
6294           `contactnote` varchar(255) DEFAULT NULL,
6295           `sort1` varchar(80) DEFAULT NULL,
6296           `sort2` varchar(80) DEFAULT NULL,
6297           `altcontactfirstname` varchar(255) DEFAULT NULL,
6298           `altcontactsurname` varchar(255) DEFAULT NULL,
6299           `altcontactaddress1` varchar(255) DEFAULT NULL,
6300           `altcontactaddress2` varchar(255) DEFAULT NULL,
6301           `altcontactaddress3` varchar(255) DEFAULT NULL,
6302           `altcontactstate` text,
6303           `altcontactzipcode` varchar(50) DEFAULT NULL,
6304           `altcontactcountry` text,
6305           `altcontactphone` varchar(50) DEFAULT NULL,
6306           `smsalertnumber` varchar(50) DEFAULT NULL,
6307           `privacy` int(11) DEFAULT NULL,
6308           PRIMARY KEY (`verification_token`,`borrowernumber`),
6309           KEY `verification_token` (`verification_token`),
6310           KEY `borrowernumber` (`borrowernumber`)
6311         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6312 ");
6313
6314     $dbh->do("
6315         INSERT INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES
6316         ('PatronSelfRegistration', '0', NULL, 'If enabled, patrons will be able to register themselves via the OPAC.', 'YesNo'),
6317         ('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'),
6318         ('PatronSelfRegistrationDefaultCategory', '', '', 'A patron registered via the OPAC will receive a borrower category code set in this system preference.', 'free'),
6319         ('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'),
6320         ('PatronSelfRegistrationBorrowerMandatoryField',  'surname|firstname', NULL ,  'Choose the mandatory fields for a patron''s account, when registering via the OPAC.',  'free'),
6321         ('PatronSelfRegistrationBorrowerUnwantedField',  '', NULL ,  'Name the fields you don''t want to display when registering a new patron via the OPAC.',  'free');
6322     ");
6323
6324     $dbh->do("
6325     INSERT INTO  letter ( `module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content` )
6326     VALUES ( 'members', 'OPAC_REG_VERIFY', '', 'Opac Self-Registration Verification Email', '1', 'Verify Your Account', 'Hello!
6327
6328     Your library account has been created. Please verify your email address by clicking this link to complete the signup process:
6329
6330     http://<<OPACBaseURL>>/cgi-bin/koha/opac-registration-verify.pl?token=<<borrower_modifications.verification_token>>
6331
6332     If you did not initiate this request, you may safely ignore this one-time message. The request will expire shortly.'
6333     )");
6334
6335     print "Upgrade to $DBversion done (Bug 7067: Add Patron Self Registration)\n";
6336     SetVersion ($DBversion);
6337 }
6338
6339 $DBversion = "3.11.00.009";
6340 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6341     $dbh->do("
6342         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
6343         ('SeparateHoldings', '0', 'Separate current branch holdings from other holdings', NULL, 'YesNo'),
6344         ('SeparateHoldingsBranch', 'homebranch', 'Branch used to separate holdings', 'homebranch|holdingbranch', 'Choice'),
6345         ('OpacSeparateHoldings', '0', 'Separate current branch holdings from other holdings (OPAC)', NULL, 'YesNo'),
6346         ('OpacSeparateHoldingsBranch', 'homebranch', 'Branch used to separate holdings (OPAC)', 'homebranch|holdingbranch', 'Choice')
6347     ");
6348
6349     print "Upgrade to $DBversion done (Bug 7674: Add systempreferences SeparateHoldings, SeparateHoldingsBranch, OpacSeparateHoldings and OpacSeparateHoldingsBranch) \n";
6350     SetVersion ($DBversion);
6351 }
6352
6353 $DBversion = "3.11.00.010";
6354 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6355     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('RenewalSendNotice', '0', '', NULL, 'YesNo')");
6356     $dbh->do(q{
6357         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
6358         ('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>>.');
6359     });
6360     print "Upgrade to $DBversion done (Bug 9151 - Renewal notice according to patron alert preferences)\n";
6361     SetVersion($DBversion);
6362 }
6363
6364 $DBversion = "3.11.00.011";
6365 if ( CheckVersion($DBversion) ) {
6366    $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');");
6367    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('HTML5MediaExtensions','webm|ogg|ogv|oga|vtt','Media file extensions','','free');");
6368    print "Upgrade to $DBversion done (Bug 8377: Add HTML5MediaEnabled and HTML5MediaExtensions sysprefs)\n";
6369    SetVersion ($DBversion);
6370 }
6371
6372 $DBversion = "3.11.00.012";
6373 if ( CheckVersion($DBversion) ) {
6374     $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')");
6375     print "Upgrade to $DBversion done (Bug 9206: Only allow place holds in records that the patron don't have in his possession)\n";
6376     SetVersion($DBversion);
6377 }
6378
6379 $DBversion = "3.11.00.013";
6380 if ( CheckVersion($DBversion) ) {
6381     $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')");
6382     print "Upgrade to $DBversion done (Bug 9162 - Add a system preference to set which notes fields appears on title notes/description separator)\n";
6383     SetVersion($DBversion);
6384 }
6385
6386 $DBversion = "3.11.00.014";
6387 if ( CheckVersion($DBversion) ) {
6388    $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' )");
6389    $dbh->do("INSERT INTO systempreferences ( variable, value, explanation, type ) VALUES ( 'SCOUserJS', '', 'Define custom javascript for inclusion in the SCO module', 'free' )");
6390    print "Upgrade to $DBversion done (Bug 9009: Add SCOUserCSS and SCOUserJS sysprefs)\n";
6391 }
6392
6393 $DBversion = "3.11.00.015";
6394 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6395     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('RentalsInNoissuesCharge', '1', 'Rental charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
6396     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('ManInvInNoissuesCharge', '1', 'MANUAL_INV charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
6397     print "Upgrade to $DBversion done (Add sysprefs RentalsInNoissuesCharge and ManInvInNoissuesCharge.)\n";
6398     SetVersion($DBversion);
6399 }
6400
6401 $DBversion = "3.11.00.016";
6402 if ( CheckVersion($DBversion) ) {
6403    $dbh->do(q{
6404         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";
6405         });
6406    $dbh->do(q{
6407         UPDATE userflags SET flagdesc="Edit Authorities" where flagdesc="Allow to edit authorities";
6408         });
6409    $dbh->do(q{
6410         UPDATE userflags SET flagdesc="Allow access to the reports module" where flagdesc="Allow to access to the reports module";
6411         });
6412    $dbh->do(q{
6413         UPDATE userflags SET flagdesc="Set library management parameters (deprecated)" where flagdesc="Set library management parameters";
6414         });
6415    $dbh->do(q{
6416         UPDATE userflags SET flagdesc="Manage serial subscriptions" where flagdesc="Allow to manage serials subscriptions";
6417         });
6418    $dbh->do(q{
6419         UPDATE userflags SET flagdesc="Manage patrons fines and fees" where flagdesc="Update borrower charges";
6420         });
6421    $dbh->do(q{
6422         UPDATE userflags SET flagdesc="Check out and check in items" where flagdesc="Circulate books";
6423         });
6424    $dbh->do(q{
6425         UPDATE userflags SET flagdesc="Manage Koha system settings (Administration panel)" where flagdesc="Set Koha system parameters";
6426         });
6427    $dbh->do(q{
6428         UPDATE userflags SET flagdesc="Add or modify patrons" where flagdesc="Add or modify borrowers";
6429         });
6430    $dbh->do(q{
6431         UPDATE userflags SET flagdesc="Use all tools (expand for granular tools permissions)" where flagdesc="Use tools (export, import, barcodes)";
6432         });
6433    $dbh->do(q{
6434         UPDATE userflags SET flagdesc="Allow staff members to modify permissions for other staff members" where flagdesc="Set user permissions";
6435         });
6436    $dbh->do(q{
6437         UPDATE permissions SET description="Perform batch modification of patrons" where description="Perform batch modifivation of patrons";
6438         });
6439
6440    print "Upgrade to $DBversion done (Bug 9382 (updated with bug 9745) - refresh permission descriptions to make more sense)\n";
6441    SetVersion ($DBversion);
6442 }
6443
6444 $DBversion ="3.11.00.017";
6445 if ( CheckVersion($DBversion) ) {
6446     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksReviews','0','Display book review snippets from IDreamBooks.com','','YesNo');");
6447     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksReadometer','0','Display Readometer from IDreamBooks.com','','YesNo');");
6448     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksResults','0','Display IDreamBooks.com rating in search results','','YesNo');");
6449     print "Upgrade to $DBversion done (Add IDreamBooks enhanced content)\n";
6450     SetVersion($DBversion);
6451 }
6452
6453 $DBversion = "3.11.00.018";
6454 if ( CheckVersion($DBversion) ) {
6455    $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')");
6456    $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')");
6457    print "Upgrade to $DBversion done (Bug 9395: Problem with callnumber and standard number search in OPAC and Staff Client)\n";
6458    SetVersion ($DBversion);
6459 }
6460
6461 $DBversion = "3.11.00.019";
6462 if ( CheckVersion($DBversion) ) {
6463     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('UNIMARCAuthorityField100', 'afrey50      ba0', NULL, NULL, 'Textarea')");
6464     print "Upgrade to $DBversion done (Bug 9145 - Add syspref UNIMARCAuthorityField100)\n";
6465     SetVersion ($DBversion);
6466 }
6467
6468 $DBversion = "3.11.00.020";
6469 if ( CheckVersion($DBversion) ) {
6470     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UNIMARCField100Language', 'fre','UNIMARC field 100 default language',NULL,'short')");
6471     print "Upgrade to $DBversion done (Bug 8347 - Koha forces UNIMARC 100 field code language to 'fre')\n";
6472     SetVersion($DBversion);
6473 }
6474
6475 $DBversion ="3.11.00.021";
6476 if ( CheckVersion($DBversion) ) {
6477     $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');");
6478     print "Upgrade to $DBversion done (Bug 5888 - Subject search pop-up for the OPAC)\n";
6479     SetVersion($DBversion);
6480 }
6481
6482 $DBversion = "3.11.00.022";
6483 if ( CheckVersion($DBversion) ) {
6484     $dbh->do(
6485 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('Persona',0,'Use Mozilla Persona for login','','YesNo')"
6486     );
6487     print "Upgrade to $DBversion done (Bug 9587 - Allow login via Persona)\n";
6488     SetVersion($DBversion);
6489 }
6490
6491 $DBversion = "3.11.00.023";
6492 if ( CheckVersion($DBversion) ) {
6493     $dbh->do("UPDATE z3950servers SET host = 'lx2.loc.gov', port = 210, db = 'LCDB', syntax = 'USMARC', encoding = 'utf8' WHERE name = 'LIBRARY OF CONGRESS'");
6494     print "Upgrade to $DBversion done (Bug 9520 - Update default LOC Z39.50 target)\n";
6495     SetVersion($DBversion);
6496 }
6497
6498 $DBversion = "3.11.00.024";
6499 if ( CheckVersion($DBversion) ) {
6500     $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');");
6501     print "Upgrade to $DBversion done (Bug 5079: Add OpacItemLocation syspref)\n";
6502     SetVersion ($DBversion);
6503 }
6504
6505 $DBversion = "3.11.00.025";
6506 if ( CheckVersion($DBversion) ) {
6507     $dbh->do(
6508         "CREATE TABLE linktracker (
6509   id int(11) NOT NULL AUTO_INCREMENT,
6510   biblionumber int(11) DEFAULT NULL,
6511   itemnumber int(11) DEFAULT NULL,
6512   borrowernumber int(11) DEFAULT NULL,
6513   url text,
6514   timeclicked datetime DEFAULT NULL,
6515   PRIMARY KEY (id),
6516   KEY bibidx (biblionumber),
6517   KEY itemidx (itemnumber),
6518   KEY borridx (borrowernumber),
6519   KEY dateidx (timeclicked)
6520     ) ENGINE=InnoDB DEFAULT CHARSET=utf8;"
6521     );
6522     $dbh->do( "
6523   INSERT INTO systempreferences (variable,value,explanation,options,type)
6524   VALUES('TrackClicks','0','Track links clicked',NULL,'Integer')" );
6525     print
6526 "Upgrade to $DBversion done (Adds feature Bug 8917, the ability to track links clicked)\n";
6527     SetVersion($DBversion);
6528 }
6529
6530 $DBversion = "3.11.00.026";
6531 if ( CheckVersion($DBversion) ) {
6532     $dbh->do(qq{
6533         ALTER TABLE import_records ADD INDEX batch_id_record_type ( import_batch_id, record_type );
6534     });
6535     print "Upgrade to $DBversion done (Bug 9207: Add new index batch_id_record_type to import_records)\n";
6536     SetVersion($DBversion);
6537 }
6538
6539 $DBversion = "3.11.00.027";
6540 if ( CheckVersion($DBversion) ) {
6541     $dbh->do(q{
6542         INSERT INTO permissions ( module_bit, code, description )
6543         VALUES  ( '1', 'overdues_report', 'Execute overdue items report' )
6544     });
6545     # add new permission for users with all report permissions and circulation remaining permission
6546     $dbh->do(q{
6547         INSERT INTO user_permissions (borrowernumber, module_bit, code)
6548         SELECT user_permissions.borrowernumber, 1, 'overdues_report'
6549         FROM user_permissions
6550         LEFT JOIN borrowers USING(borrowernumber)
6551         WHERE borrowers.flags & (1 << 16)
6552         AND user_permissions.code = 'circulate_remaining_permissions'
6553     });
6554     print "Upgrade to $DBversion done ( Add circ permission overdues_report )\n";
6555     SetVersion($DBversion);
6556 }
6557
6558 $DBversion = "3.11.00.028";
6559 if ( CheckVersion($DBversion) ) {
6560     $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'    );");
6561     print "Upgrade to $DBversion done (Bug 9756 - Patron self registration missing the system preference PatronSelfRegistrationAdditionalInstructions)\n";
6562     SetVersion($DBversion);
6563 }
6564
6565 $DBversion = "3.11.00.029";
6566 if (CheckVersion($DBversion)) {
6567     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UseQueryParser', '0', 'If enabled, try to use QueryParser for queries.', NULL, 'YesNo')");
6568     print "Upgrade to $DBversion done (Bug 9239: Make it possible for Koha to use QueryParser)\n";
6569     SetVersion ($DBversion);
6570 }
6571
6572 $DBversion = "3.11.00.030";
6573 if ( CheckVersion($DBversion) ) {
6574     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('FinesIncludeGracePeriod','1','If enabled, fines calculations will include the grace period.',NULL,'YesNo');");
6575     print "Upgrade to $DBversion done (Add system preference FinesIncludeGracePeriod)\n";
6576     SetVersion($DBversion);
6577 }
6578
6579 $DBversion = "3.11.00.100";
6580 if ( CheckVersion($DBversion) ) {
6581     print "Upgrade to $DBversion done (3.12-alpha release)\n";
6582     SetVersion ($DBversion);
6583 }
6584
6585 $DBversion = "3.11.00.101";
6586 if ( CheckVersion($DBversion) ) {
6587    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('UNIMARCAuthorsFacetsSeparator',', ', 'UNIMARC authors facets separator', NULL, 'short')");
6588    print "Upgrade to $DBversion done (Bug 9341: Problem with UNIMARC authors facets)\n";
6589    SetVersion ($DBversion);
6590 }
6591
6592 $DBversion = "3.11.00.102";
6593 if ( CheckVersion($DBversion) ) {
6594     $dbh->do(q{
6595         DELETE FROM systempreferences WHERE variable='NoZebra'
6596     });
6597     $dbh->do(q{
6598         DELETE FROM systempreferences WHERE variable='QueryRemoveStopwords'
6599     });
6600     print "Upgrade to $DBversion done (Remove deprecated NoZebra and QueryRemoveStopwords sysprefs)\n";
6601     SetVersion($DBversion);
6602 }
6603
6604 $DBversion = "3.11.00.103";
6605 if ( CheckVersion($DBversion) ) {
6606     $dbh->do("DELETE FROM systempreferences WHERE variable = 'insecure';");
6607     print "Upgrade to $DBversion done (Bug 9827 - Remove 'insecure' system preference)\n";
6608     SetVersion($DBversion);
6609 }
6610
6611 $DBversion = "3.11.00.104";
6612 if ( CheckVersion($DBversion) ) {
6613     print "Upgrade to $DBversion done (3.12-alpha2 release)\n";
6614     SetVersion ($DBversion);
6615 }
6616
6617 $DBversion = "3.11.00.105";
6618 if ( CheckVersion($DBversion) ) {
6619     if ( C4::Context->preference("marcflavour") eq 'MARC21' ) {
6620         $sth = $dbh->prepare(
6621 "SELECT frameworkcode FROM marc_tag_structure WHERE tagfield = '029'"
6622         );
6623         $sth->execute;
6624         my $frameworkcodes = $sth->fetchall_hashref('frameworkcode');
6625
6626         for my $frameworkcode ( keys %$frameworkcodes ) {
6627             $dbh->do( "
6628     INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian,
6629     libopac, repeatable, mandatory, kohafield, tab, authorised_value, authtypecode,
6630     value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
6631     ('029', 'a', 'OCLC library identifier', 'OCLC library identifier', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6632     ('029', 'b', 'System control number', 'System control number', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6633     ('029', 'c', 'OAI set name', 'OAI set name', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6634     ('029', 't', 'Content type identifier', 'Content type identifier', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL)
6635    " );
6636         }
6637
6638         for my $tag ( '863', '864', '865' ) {
6639             $sth = $dbh->prepare(
6640 "SELECT frameworkcode FROM marc_tag_structure WHERE tagfield = '$tag'"
6641             );
6642             $sth->execute;
6643             my $frameworkcodes = $sth->fetchall_hashref('frameworkcode');
6644
6645             for my $frameworkcode ( keys %$frameworkcodes ) {
6646                 $dbh->do( "
6647      INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian,
6648      libopac, repeatable, mandatory, kohafield, tab, authorised_value, authtypecode,
6649      value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
6650      ('$tag', '6', 'Linkage', 'Linkage', 0, 0, '', 8, '', '', '', NULL, 5, '$frameworkcode', '', '', NULL),
6651      ('$tag', '8', 'Field link and sequence number', 'Field link and sequence number', 0, 0, '', 8, '', '', '', NULL, 5, '$frameworkcode', '', '', NULL),
6652      ('$tag', 'a', 'First level of enumeration', 'First level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6653      ('$tag', 'b', 'Second level of enumeration', 'Second level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6654      ('$tag', 'c', 'Third level of enumeration', 'Third level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6655      ('$tag', 'd', 'Fourth level of enumeration', 'Fourth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6656      ('$tag', 'e', 'Fifth level of enumeration', 'Fifth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6657      ('$tag', 'f', 'Sixth level of enumeration', 'Sixth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6658      ('$tag', 'g', 'Alternative numbering scheme, first level of enumeration', 'Alternative numbering scheme, first level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6659      ('$tag', 'h', 'Alternative numbering scheme, second level of enumeration', 'Alternative numbering scheme, second level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6660      ('$tag', 'i', 'First level of chronology', 'First level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6661      ('$tag', 'j', 'Second level of chronology', 'Second level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6662      ('$tag', 'k', 'Third level of chronology', 'Third level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6663      ('$tag', 'l', 'Fourth level of chronology', 'Fourth level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6664      ('$tag', 'm', 'Alternative numbering scheme, chronology', 'Alternative numbering scheme, chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6665      ('$tag', 'n', 'Converted Gregorian year', 'Converted Gregorian year', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6666      ('$tag', 'o', 'Type of unit', 'Type of unit', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6667      ('$tag', 'p', 'Piece designation', 'Piece designation', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6668      ('$tag', 'q', 'Piece physical condition', 'Piece physical condition', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6669      ('$tag', 's', 'Copyright article-fee code', 'Copyright article-fee code', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6670      ('$tag', 't', 'Copy number', 'Copy number', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6671      ('$tag', 'v', 'Issuing date', 'Issuing date', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6672      ('$tag', 'w', 'Break indicator', 'Break indicator', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6673      ('$tag', 'x', 'Nonpublic note', 'Nonpublic note', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6674      ('$tag', 'z', 'Public note', 'Public note', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL)
6675     " );
6676             }
6677         }
6678     }
6679     print "Upgrade to $DBversion done (Bug 9353: Missing subfields on MARC21 frameworks)\n";
6680     SetVersion($DBversion);
6681 }
6682
6683
6684 $DBversion = "3.11.00.106";
6685 if ( CheckVersion($DBversion) ) {
6686     $dbh->do("INSERT INTO userflags (bit, flag, flagdesc, defaulton) VALUES ('19', 'plugins', 'Koha plugins', '0')");
6687     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
6688               ('19', 'manage', 'Manage plugins ( install / uninstall )'),
6689               ('19', 'tool', 'Use tool plugins'),
6690               ('19', 'report', 'Use report plugins'),
6691               ('19', 'configure', 'Configure plugins')
6692             ");
6693     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UseKohaPlugins','0','Enable or disable the ability to use Koha Plugins.','','YesNo')");
6694
6695     $dbh->do("
6696         CREATE TABLE IF NOT EXISTS plugin_data (
6697             plugin_class varchar(255) NOT NULL,
6698             plugin_key varchar(255) NOT NULL,
6699             plugin_value text,
6700             PRIMARY KEY (plugin_class,plugin_key)
6701         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6702     ");
6703
6704     print "Upgrade to $DBversion done (Bug 7804: Added plugin system.)\n";
6705     SetVersion($DBversion);
6706 }
6707
6708 $DBversion = "3.11.00.107";
6709 if ( CheckVersion($DBversion) ) {
6710    $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('TimeFormat','24hr','12hr|24hr','Defines the global time format for visual output.','Choice')");
6711    print "Upgrade to $DBversion done (Bug 9014: Add syspref TimeFormat)\n";
6712    SetVersion ($DBversion);
6713 }
6714
6715 $DBversion = "3.11.00.108";
6716 if ( CheckVersion($DBversion) ) {
6717     $dbh->do("ALTER TABLE action_logs CHANGE timestamp timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;");
6718     $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');");
6719     $dbh->do("ALTER TABLE action_logs CHANGE timestamp timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;");
6720     print "Upgrade to $DBversion done (Bug 7241: Fix on circulation logs)\n";
6721     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";
6722     SetVersion($DBversion);
6723 }
6724
6725 $DBversion = "3.11.00.109";
6726 if ( CheckVersion($DBversion) ) {
6727    $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');");
6728    print "Upgrade to $DBversion done (Bug 9403: Add DisplayIconsXSLT)\n";
6729    SetVersion ($DBversion);
6730 }
6731
6732 $DBversion = "3.11.00.110";
6733 if ( CheckVersion($DBversion) ) {
6734     $dbh->do("ALTER TABLE pending_offline_operations CHANGE barcode barcode VARCHAR( 20 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
6735     $dbh->do("ALTER TABLE pending_offline_operations ADD amount DECIMAL( 28, 6 ) NULL DEFAULT NULL");
6736     print "Upgrade to $DBversion done (Bug 8220 - Allow koc uploads to go to process queue)\n";
6737     SetVersion ($DBversion);
6738 }
6739
6740 $DBversion = "3.11.00.111";
6741 if ( CheckVersion($DBversion) ) {
6742     my $sth = $dbh->prepare("
6743         SELECT module, code, branchcode, content
6744         FROM letter
6745         WHERE content LIKE '%<fine>%'
6746     ");
6747     $sth->execute;
6748     my $sth_update = $dbh->prepare("UPDATE letter SET content = ? WHERE module = ? AND code = ? AND branchcode = ?");
6749     while(my $row = $sth->fetchrow_hashref){
6750         $row->{content} =~ s/<fine>\w+<\/fine>/<<items.fine>>/;
6751         $sth_update->execute($row->{content}, $row->{module}, $row->{code}, $row->{branchcode});
6752     }
6753     print "Upgrade to $DBversion done (use new <<items.fine>> syntax in notices)\n";
6754     SetVersion($DBversion);
6755 }
6756
6757 $DBversion = "3.11.00.112";
6758 if ( CheckVersion($DBversion) ) {
6759     $dbh->do(qq{
6760         ALTER TABLE issuingrules ADD COLUMN renewalperiod int(4) DEFAULT NULL AFTER renewalsallowed
6761     });
6762     $dbh->do(qq{
6763         UPDATE issuingrules SET renewalperiod = issuelength
6764     });
6765     print "Upgrade to $DBversion done (Bug 8365: Add colum issuingrules.renewalperiod)\n";
6766     SetVersion ($DBversion);
6767 }
6768
6769 $DBversion = "3.11.00.113";
6770 if ( CheckVersion($DBversion) ) {
6771     $dbh->do(q{
6772         ALTER TABLE branchcategories ADD show_in_pulldown BOOLEAN NOT NULL DEFAULT '0',
6773         ADD INDEX ( show_in_pulldown )
6774     });
6775     print "Upgrade to $DBversion done (Bug 9257 - Add groups to normal search pulldown)\n";
6776     SetVersion ($DBversion);
6777 }
6778
6779 $DBversion = "3.11.00.115";
6780 if ( CheckVersion($DBversion) ) {
6781     $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')");
6782     $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')");
6783     print "Upgrade to $DBversion done (Bug 7740: Add syspref HighlightOwnItemsOnOPAC)\n";
6784     SetVersion ($DBversion);
6785 }
6786
6787 $DBversion = "3.11.00.116";
6788 if ( CheckVersion($DBversion) ) {
6789     $dbh->do(q{ALTER TABLE aqorders DROP COLUMN serialid;});
6790     $dbh->do(q{ALTER TABLE aqorders DROP COLUMN subscription;});
6791     $dbh->do(q{ALTER TABLE aqorders ADD COLUMN subscriptionid INT(11) DEFAULT NULL;});
6792     $dbh->do(q{ALTER TABLE aqorders ADD CONSTRAINT aqorders_subscriptionid FOREIGN KEY (subscriptionid) REFERENCES subscription (subscriptionid) ON DELETE CASCADE ON UPDATE CASCADE;});
6793     $dbh->do(q{ALTER TABLE subscription ADD COLUMN reneweddate DATE DEFAULT NULL;});
6794     print "Upgrade to $DBversion done (Bug 5343: table aqorders: DROP serialid and subscription fields and ADD subscriptionid, table subscription: ADD reneweddate)\n";
6795     SetVersion ($DBversion);
6796 }
6797
6798 $DBversion = "3.11.00.200";
6799 if ( CheckVersion($DBversion) ) {
6800     print "Upgrade to $DBversion done (3.12-beta1 release)\n";
6801     SetVersion ($DBversion);
6802 }
6803
6804 $DBversion = "3.11.00.201";
6805 if ( CheckVersion($DBversion) ) {
6806     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'BIBSYS' AND host LIKE 'z3950.bibsys.no'");
6807     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'NORBOK' AND host LIKE 'z3950.nb.no'");
6808     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'SAMBOK' AND host LIKE 'z3950.nb.no'");
6809     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'DEICHMAN' AND host like 'z3950.deich.folkebibl.no'");
6810     print "Upgrade to $DBversion done (Bug 9498 - Update encoding for Norwegian sample Z39.50 servers)\n";
6811     SetVersion($DBversion);
6812 }
6813
6814 $DBversion = "3.11.00.202";
6815 if ( CheckVersion($DBversion) ) {
6816    $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ca', 'language', 'Catalan','2013-01-12' )");
6817    $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'ca','cat')");
6818    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'es', 'Catalán')");
6819    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'en', 'Catalan')");
6820    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'fr', 'Catalan')");
6821    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'ca', 'Català')");
6822    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'de', 'Katalanisch')");
6823    print "Upgrade to $DBversion done (Bug 9381: Add Catalan laguage)\n";
6824    SetVersion ($DBversion);
6825 }
6826
6827 $DBversion = "3.11.00.203";
6828 if ( CheckVersion($DBversion) ) {
6829     $dbh->do(q{ALTER TABLE suggestions CHANGE COLUMN title title VARCHAR(255) DEFAULT NULL;});
6830     print "Upgrade to $DBversion done (Bug 2046 - increasing title column length for suggestions)\n";
6831     SetVersion ($DBversion);
6832 }
6833
6834 $DBversion = "3.11.00.300";
6835 if ( CheckVersion($DBversion) ) {
6836     print "Upgrade to $DBversion done (3.12-beta3 release)\n";
6837     SetVersion ($DBversion);
6838 }
6839
6840 $DBversion = "3.11.00.301";
6841 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6842     #issues
6843     $dbh->do(q{
6844         ALTER TABLE `issues`
6845             ADD KEY `itemnumber_idx` (`itemnumber`),
6846             ADD KEY `branchcode_idx` (`branchcode`),
6847             ADD KEY `issuingbranch_idx` (`issuingbranch`)
6848     });
6849     $dbh->do(q{
6850         ALTER TABLE `old_issues`
6851             ADD KEY `branchcode_idx` (`branchcode`),
6852             ADD KEY `issuingbranch_idx` (`issuingbranch`)
6853     });
6854     #items
6855     $dbh->do(q{
6856         ALTER TABLE `items` ADD KEY `itype_idx` (`itype`)
6857     });
6858     $dbh->do(q{
6859         ALTER TABLE `deleteditems` ADD KEY `itype_idx` (`itype`)
6860     });
6861     # biblioitems
6862     $dbh->do(q{
6863         ALTER TABLE `biblioitems` ADD KEY `itemtype_idx` (`itemtype`)
6864     });
6865     $dbh->do(q{
6866         ALTER TABLE `deletedbiblioitems` ADD KEY `itemtype_idx` (`itemtype`)
6867     });
6868     # statistics
6869     $dbh->do(q{
6870         ALTER TABLE `statistics`
6871             ADD KEY `branch_idx` (`branch`),
6872             ADD KEY `proccode_idx` (`proccode`),
6873             ADD KEY `type_idx` (`type`),
6874             ADD KEY `usercode_idx` (`usercode`),
6875             ADD KEY `itemnumber_idx` (`itemnumber`),
6876             ADD KEY `itemtype_idx` (`itemtype`),
6877             ADD KEY `borrowernumber_idx` (`borrowernumber`),
6878             ADD KEY `associatedborrower_idx` (`associatedborrower`),
6879             ADD KEY `ccode_idx` (`ccode`)
6880     });
6881
6882     print "Upgrade to $DBversion done (Bug 9681: Add some database indexes)\n";
6883     SetVersion($DBversion);
6884 }
6885
6886 $DBversion = "3.12.00.000";
6887 if ( CheckVersion($DBversion) ) {
6888     print "Upgrade to $DBversion done (3.12.0 release)\n";
6889     SetVersion ($DBversion);
6890 }
6891
6892 $DBversion = '3.13.00.000';
6893 if ( CheckVersion($DBversion) ) {
6894     print "Upgrade to $DBversion done (start the journey to Koha Pi)\n";
6895     SetVersion ($DBversion);
6896 }
6897
6898 $DBversion = "3.13.00.001";
6899 if ( CheckVersion($DBversion) ) {
6900     $dbh->do("INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('UseCourseReserves', '0', NULL, 'Enable the course reserves feature.', 'YesNo')");
6901     $dbh->do("INSERT INTO userflags (bit,flag,flagdesc,defaulton) VALUES ('18','coursereserves','Course Reserves','0')");
6902     $dbh->do("
6903 CREATE TABLE `courses` (
6904   `course_id` int(11) NOT NULL AUTO_INCREMENT,
6905   `department` varchar(20) DEFAULT NULL,
6906   `course_number` varchar(255) DEFAULT NULL,
6907   `section` varchar(255) DEFAULT NULL,
6908   `course_name` varchar(255) DEFAULT NULL,
6909   `term` varchar(20) DEFAULT NULL,
6910   `staff_note` mediumtext,
6911   `public_note` mediumtext,
6912   `students_count` varchar(20) DEFAULT NULL,
6913   `enabled` enum('yes','no') NOT NULL DEFAULT 'yes',
6914   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6915    PRIMARY KEY (`course_id`)
6916 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6917     ");
6918
6919     $dbh->do("
6920 CREATE TABLE `course_instructors` (
6921   `course_id` int(11) NOT NULL,
6922   `borrowernumber` int(11) NOT NULL,
6923   PRIMARY KEY (`course_id`,`borrowernumber`),
6924   KEY `borrowernumber` (`borrowernumber`)
6925 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6926     ");
6927
6928     $dbh->do("
6929 ALTER TABLE `course_instructors`
6930   ADD CONSTRAINT `course_instructors_ibfk_2` FOREIGN KEY (`course_id`) REFERENCES `courses` (`course_id`),
6931   ADD CONSTRAINT `course_instructors_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE;
6932     ");
6933
6934     $dbh->do("
6935 CREATE TABLE `course_items` (
6936   `ci_id` int(11) NOT NULL AUTO_INCREMENT,
6937   `itemnumber` int(11) NOT NULL,
6938   `itype` varchar(10) DEFAULT NULL,
6939   `ccode` varchar(10) DEFAULT NULL,
6940   `holdingbranch` varchar(10) DEFAULT NULL,
6941   `location` varchar(80) DEFAULT NULL,
6942   `enabled` enum('yes','no') NOT NULL DEFAULT 'no',
6943   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6944    PRIMARY KEY (`ci_id`),
6945    UNIQUE KEY `itemnumber` (`itemnumber`),
6946    KEY `holdingbranch` (`holdingbranch`)
6947 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6948     ");
6949
6950     $dbh->do("
6951 ALTER TABLE `course_items`
6952   ADD CONSTRAINT `course_items_ibfk_2` FOREIGN KEY (`holdingbranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
6953   ADD CONSTRAINT `course_items_ibfk_1` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE;
6954 ");
6955
6956     $dbh->do("
6957 CREATE TABLE `course_reserves` (
6958   `cr_id` int(11) NOT NULL AUTO_INCREMENT,
6959   `course_id` int(11) NOT NULL,
6960   `ci_id` int(11) NOT NULL,
6961   `staff_note` mediumtext,
6962   `public_note` mediumtext,
6963   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6964    PRIMARY KEY (`cr_id`),
6965    UNIQUE KEY `pseudo_key` (`course_id`,`ci_id`),
6966    KEY `course_id` (`course_id`)
6967 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6968 ");
6969
6970     $dbh->do("
6971 ALTER TABLE `course_reserves`
6972   ADD CONSTRAINT `course_reserves_ibfk_1` FOREIGN KEY (`course_id`) REFERENCES `courses` (`course_id`);
6973     ");
6974
6975     $dbh->do("
6976 INSERT INTO permissions (module_bit, code, description) VALUES
6977   (18, 'manage_courses', 'Add, edit and delete courses'),
6978   (18, 'add_reserves', 'Add course reserves'),
6979   (18, 'delete_reserves', 'Remove course reserves')
6980 ;
6981     ");
6982
6983
6984     print "Upgrade to $DBversion done (Add Course Reserves ( system preference UseCourseReserves ))\n";
6985     SetVersion($DBversion);
6986 }
6987
6988 $DBversion = "3.13.00.002";
6989 if ( CheckVersion($DBversion) ) {
6990    $dbh->do("UPDATE systempreferences SET variable = 'IndependentBranches' WHERE variable = 'IndependantBranches'");
6991    print "Upgrade to $DBversion done (Bug 10080 - Change system pref IndependantBranches to IndependentBranches)\n";
6992    SetVersion ($DBversion);
6993 }
6994
6995 $DBversion = '3.13.00.003';
6996 if ( CheckVersion($DBversion) ) {
6997     $dbh->do("ALTER TABLE serial DROP itemnumber");
6998     print "Upgrade to $DBversion done (Bug 7718 - Remove itemnumber column from serials table)\n";
6999     SetVersion($DBversion);
7000 }
7001
7002 $DBversion = "3.13.00.004";
7003 if(CheckVersion($DBversion)) {
7004     $dbh->do(
7005 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacShowHoldNotes',0,'Show hold notes on OPAC','','YesNo')"
7006     );
7007     print "Upgrade to $DBversion done (Bug 9722: Allow users to add notes when placing a hold in OPAC)\n";
7008     SetVersion($DBversion);
7009 }
7010
7011 $DBversion = "3.13.00.005";
7012 if(CheckVersion($DBversion)) {
7013     my $intra= C4::Context->preference("intranetstylesheet");
7014     #if this pref is not blank or starting with http, https or / [root], then
7015     #add an additional / to the front
7016     if($intra && $intra !~ /^(\/|https?)/) {
7017         $dbh->do("UPDATE systempreferences SET value=? WHERE variable=?",
7018             undef,('/'.$intra,"intranetstylesheet"));
7019         print "WARNING: Your system preference intranetstylesheet has been prefixed with a slash to make it an absolute path.\n";
7020     }
7021     print "Upgrade to $DBversion done (Bug 10052: Make intranetstylesheet and intranetcolorstylesheet behave exactly like their opac counterparts)\n";
7022     SetVersion ($DBversion);
7023 }
7024
7025 $DBversion = "3.13.00.006";
7026 if ( CheckVersion($DBversion) ) {
7027     $dbh->do(q{
7028         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
7029         VALUES ('CalculateFinesOnReturn','1','Switch to control if overdue fines are calculated on return or not', '', 'YesNo')
7030     });
7031     print "Upgrade to $DBversion done (Bug 10120: Fines on item return controlled by a systempreference)\n";
7032     SetVersion($DBversion);
7033 }
7034
7035 $DBversion = "3.13.00.007";
7036 if ( CheckVersion($DBversion) ) {
7037     $dbh->do("UPDATE systempreferences SET variable='OpacHoldNotes' WHERE variable='OpacShowHoldNotes'");
7038     print "Upgrade to $DBversion done (Bug 10343: Rename OpacShowHoldNotes to OpacHoldNotes)\n";
7039     SetVersion($DBversion);
7040 }
7041
7042 $DBversion = "3.13.00.008";
7043 if ( CheckVersion($DBversion) ) {
7044     $dbh->do("
7045 CREATE TABLE IF NOT EXISTS borrower_files (
7046   file_id int(11) NOT NULL AUTO_INCREMENT,
7047   borrowernumber int(11) NOT NULL,
7048   file_name varchar(255) NOT NULL,
7049   file_type varchar(255) NOT NULL,
7050   file_description varchar(255) DEFAULT NULL,
7051   file_content longblob NOT NULL,
7052   date_uploaded timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
7053   PRIMARY KEY (file_id),
7054   KEY borrowernumber (borrowernumber),
7055   CONSTRAINT borrower_files_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
7056 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7057     ");
7058     print "Upgrade to $DBversion done (Bug 10443: make sure borrower_files table exists)\n";
7059     SetVersion($DBversion);
7060 }
7061
7062 $DBversion = "3.13.00.009";
7063 if ( CheckVersion($DBversion) ) {
7064     $dbh->do("ALTER TABLE aqorders DROP COLUMN biblioitemnumber");
7065     print "Upgrade to $DBversion done (Bug 9987 - Drop column aqorders.biblioitemnumber)\n";
7066     SetVersion($DBversion);
7067 }
7068
7069 $DBversion = "3.13.00.010";
7070 if ( CheckVersion($DBversion) ) {
7071     $dbh->do(
7072         q{
7073 INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AcqWarnOnDuplicateInvoice','0','Warn librarians when they try to create a duplicate invoice', '', 'YesNo');
7074 }
7075     );
7076     print
7077 "Upgrade to $DBversion done (Bug 10366 - Add system preference to enabling warning librarian when invoice is duplicated)\n";
7078     SetVersion($DBversion);
7079 }
7080
7081 $DBversion = "3.13.00.011";
7082 if ( CheckVersion($DBversion) ) {
7083     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='ita' WHERE rfc4646_subtag='it'");
7084     print "Upgrade to $DBversion done (Bug 9519: Wrong language code for Italian in the advanced search language limitations)\n";
7085     SetVersion($DBversion);
7086 }
7087
7088 $DBversion = "3.13.00.012";
7089 if ( CheckVersion($DBversion) ) {
7090     $dbh->do("ALTER TABLE issuingrules MODIFY COLUMN overduefinescap decimal(28,6) DEFAULT NULL;");
7091     print "Upgrade to $DBversion done (Bug 10490: Correct datatype for overduefinescap in issuingrules)\n";
7092     SetVersion($DBversion);
7093 }
7094
7095 $DBversion ="3.13.00.013";
7096 if ( CheckVersion($DBversion) ) {
7097     $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');");
7098     print "Upgrade to $DBversion done (Bug 9576: add AllowTooManyOverride syspref to enable or disable issue limit confirmation)\n";
7099     SetVersion($DBversion);
7100 }
7101
7102 $DBversion = "3.13.00.014";
7103 if ( CheckVersion($DBversion) ) {
7104     $dbh->do("ALTER TABLE courses MODIFY COLUMN department varchar(80) DEFAULT NULL;");
7105     $dbh->do("ALTER TABLE courses MODIFY COLUMN term       varchar(80) DEFAULT NULL;");
7106     print "Upgrade to $DBversion done (Bug 10604: correct width of courses.department and courses.term)\n";
7107     SetVersion($DBversion);
7108 }
7109
7110 $DBversion = "3.13.00.015";
7111 if ( CheckVersion($DBversion) ) {
7112     $dbh->do(
7113 "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')"
7114     );
7115     print "Upgrade to $DBversion done (Bug 7494: Add itemBarcodeFallbackSearch syspref)\n";
7116     SetVersion($DBversion);
7117 }
7118
7119 $DBversion = "3.13.00.016";
7120 if ( CheckVersion($DBversion) ) {
7121     $dbh->do(q{
7122         ALTER TABLE items CHANGE wthdrawn withdrawn TINYINT( 1 ) NOT NULL DEFAULT  '0'
7123     });
7124
7125     $dbh->do(q{
7126         ALTER TABLE deleteditems CHANGE wthdrawn withdrawn TINYINT( 1 ) NOT NULL DEFAULT  '0'
7127     });
7128
7129     $dbh->do(q{
7130         UPDATE saved_sql SET savedsql = REPLACE(savedsql, 'wthdrawn', 'withdrawn')
7131     });
7132
7133     $dbh->do(q{
7134         UPDATE marc_subfield_structure SET kohafield = 'items.withdrawn' WHERE kohafield = 'items.wthdrawn'
7135     });
7136
7137     print "Upgrade to $DBversion done (Bug 10550 - Fix database typo wthdrawn)\n";
7138     SetVersion($DBversion);
7139 }
7140
7141 $DBversion = "3.13.00.017";
7142 if ( CheckVersion($DBversion) ) {
7143     $dbh->do(
7144 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveClientKey','','Client key for OverDrive integration','30','Free')"
7145     );
7146     $dbh->do(
7147 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveClientSecret','','Client key for OverDrive integration','30','YesNo')"
7148     );
7149     $dbh->do(
7150 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveLibraryID','','Library ID for OverDrive integration','','Integer')"
7151     );
7152     print "Upgrade to $DBversion done (Bug 10320 - Show results from library's OverDrive collection in OPAC search)\n";
7153     SetVersion($DBversion);
7154 }
7155
7156 $DBversion = "3.13.00.018";
7157 if ( CheckVersion($DBversion) ) {
7158     $dbh->do(qq{DROP TABLE IF EXISTS aqorders_transfers;});
7159     $dbh->do(qq{
7160         CREATE TABLE aqorders_transfers (
7161           ordernumber_from int(11) NULL,
7162           ordernumber_to int(11) NULL,
7163           timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
7164           UNIQUE KEY ordernumber_from (ordernumber_from),
7165           UNIQUE KEY ordernumber_to (ordernumber_to),
7166           CONSTRAINT aqorders_transfers_ordernumber_from FOREIGN KEY (ordernumber_from) REFERENCES aqorders (ordernumber) ON DELETE SET NULL ON UPDATE CASCADE,
7167           CONSTRAINT aqorders_transfers_ordernumber_to FOREIGN KEY (ordernumber_to) REFERENCES aqorders (ordernumber) ON DELETE SET NULL ON UPDATE CASCADE
7168         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7169     });
7170     print "Upgrade to $DBversion done (Bug 5349: Add aqorders_transfers table)\n";
7171     SetVersion($DBversion);
7172 }
7173
7174 $DBversion = "3.13.00.019";
7175 if ( CheckVersion($DBversion) ) {
7176     $dbh->do("ALTER TABLE itemtypes ADD COLUMN checkinmsg VARCHAR(255) AFTER summary;");
7177     $dbh->do("ALTER TABLE itemtypes ADD COLUMN checkinmsgtype CHAR(16) DEFAULT 'message' NOT NULL AFTER checkinmsg;");
7178     print "Upgrade to $DBversion done (Bug 10513 - Light up a warning/message when returning a chosen item type)\n";
7179     SetVersion($DBversion);
7180 }
7181
7182 $DBversion = "3.13.00.020";
7183 if ( CheckVersion($DBversion) ) {
7184     $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')");
7185     $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')");
7186     print "Upgrade to $DBversion done (Bug 7639: system preferences to forgive fines on lost items)\n";
7187     SetVersion($DBversion);
7188 }
7189
7190 $DBversion ="3.13.00.021";
7191 if ( CheckVersion($DBversion) ) {
7192     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ConfirmFutureHolds','0','Number of days for confirming future holds','','Integer');");
7193     print "Upgrade to $DBversion done (Bug 9761: Add ConfirmFutureHolds pref)\n";
7194     SetVersion($DBversion);
7195 }
7196
7197 $DBversion = "3.13.00.022";
7198 if ( CheckVersion($DBversion) ) {
7199     $dbh->do("DELETE from auth_tag_structure WHERE tagfield IN ('68a','68b')");
7200     $dbh->do("DELETE from auth_subfield_structure WHERE tagfield IN ('68a','68b')");
7201     print "Upgrade to $DBversion done (Bug 10687 - Delete erroneous tags 68a and 68b on default MARC21 auth framework)\n";
7202     SetVersion($DBversion);
7203 }
7204
7205 $DBversion = "3.13.00.023";
7206 if ( CheckVersion($DBversion) ) {
7207     $dbh->do("ALTER TABLE borrowers CHANGE password password VARCHAR(60);");
7208     print "Upgrade to $DBversion done (Bug 9611 upgrading password storage system)\n";
7209     SetVersion($DBversion);
7210 }
7211
7212 $DBversion = "3.13.00.024";
7213 if ( CheckVersion($DBversion) ) {
7214     $dbh->do(q{ALTER TABLE z3950servers ADD COLUMN recordtype VARCHAR(45) NOT NULL DEFAULT 'biblio' AFTER description;});
7215     print "Upgrade to $DBversion done (Bug 10096 - Add a Z39.50 interface for authority searching)\n";
7216 }
7217
7218 $DBversion = "3.13.00.025";
7219 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
7220    $dbh->do("ALTER TABLE oai_sets_mappings ADD COLUMN operator varchar(8) NOT NULL default 'equal' AFTER marcsubfield;");
7221    print "Upgrade to $DBversion done (Bug 9295: OAI notequal: add operator column to OAI mappings table)\n";
7222    SetVersion ($DBversion);
7223 }
7224
7225 $DBversion = "3.13.00.026";
7226 if ( CheckVersion($DBversion) ) {
7227     $dbh->do(q|
7228         ALTER TABLE auth_subfield_structure ADD COLUMN defaultvalue TEXT DEFAULT NULL AFTER frameworkcode
7229     |);
7230     print "Upgrade to $DBversion done (Bug 10602: Add the column auth_subfield_structure.defaultvalue)\n";
7231     SetVersion($DBversion);
7232 }
7233
7234 $DBversion = "3.13.00.027";
7235 if ( CheckVersion($DBversion) ) {
7236     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('AllowOfflineCirculation','0','','If on, enables HTML5 offline circulation functionality.','YesNo')");
7237     print "Upgrade to $DBversion done (Bug 10240: Add syspref AllowOfflineCirculation)\n";
7238     SetVersion ($DBversion);
7239 }
7240
7241 $DBversion = "3.13.00.028";
7242 if ( CheckVersion($DBversion) ) {
7243     $dbh->do(q{
7244         ALTER TABLE export_format ADD type VARCHAR(255) DEFAULT 'marc' AFTER encoding
7245     });
7246     $dbh->do(q{
7247         ALTER TABLE export_format CHANGE marcfields content mediumtext NOT NULL
7248     });
7249     print "Upgrade to $DBversion done (Bug 10853: Add new field export_format.type and rename export_format.marcfields with export_format.content)\n";
7250     SetVersion($DBversion);
7251 }
7252
7253 $DBversion = "3.13.00.029";
7254 if ( CheckVersion($DBversion) ) {
7255     $dbh->do(q{
7256         INSERT IGNORE INTO export_format( profile, description, content, csv_separator, type )
7257         VALUES ( "issues to claim", "Default CSV export for serial issue claims",
7258                 "SUPPLIER=aqbooksellers.name|TITLE=subscription.title|ISSUE NUMBER=serial.serialseq|LATE SINCE=serial.planneddate",
7259                 ",", "sql" )
7260     });
7261     print "Upgrade to $DBversion done (Bug 10854: Add the default CSV profile for claiming issues)\n";
7262     SetVersion($DBversion);
7263 }
7264
7265 $DBversion = "3.13.00.030";
7266 if ( CheckVersion($DBversion) ) {
7267     $dbh->do(qq{
7268         DELETE FROM patronimage WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowers.cardnumber = patronimage.cardnumber)
7269     });
7270
7271     $dbh->do(qq{
7272         ALTER TABLE patronimage ADD borrowernumber INT( 11 ) NULL FIRST
7273     });
7274
7275     $dbh->{AutoCommit} = 0;
7276     $dbh->{RaiseError} = 1;
7277
7278     eval {
7279         $dbh->do(qq{
7280             UPDATE patronimage LEFT JOIN borrowers USING ( cardnumber ) SET patronimage.borrowernumber = borrowers.borrowernumber
7281         });
7282         $dbh->commit();
7283     };
7284
7285     if ($@) {
7286         print "Upgrade to $DBversion done (Bug 10636 - patronimage should have borrowernumber as PK, not cardnumber) failed! Transaction aborted because $@\n";
7287         eval { $dbh->rollback };
7288     }
7289     else {
7290         $dbh->do(qq{
7291             ALTER TABLE patronimage DROP FOREIGN KEY patronimage_fk1
7292         });
7293         $dbh->do(qq{
7294             ALTER TABLE patronimage DROP PRIMARY KEY, ADD PRIMARY KEY( borrowernumber )
7295         });
7296         $dbh->do(qq{
7297             ALTER TABLE patronimage DROP cardnumber
7298         });
7299         $dbh->do(qq{
7300             ALTER TABLE patronimage ADD FOREIGN KEY ( borrowernumber ) REFERENCES borrowers ( borrowernumber ) ON DELETE CASCADE ON UPDATE CASCADE
7301         });
7302
7303         print "Upgrade to $DBversion done (Bug 10636 - patronimage should have borrowernumber as PK, not cardnumber)\n";
7304         SetVersion($DBversion);
7305     }
7306
7307     $dbh->{AutoCommit} = 1;
7308     $dbh->{RaiseError} = 0;
7309 }
7310
7311 $DBversion = "3.13.00.031";
7312 if ( CheckVersion($DBversion) ) {
7313
7314     $dbh->do(q{
7315         CREATE TABLE IF NOT EXISTS `patron_lists` (
7316           patron_list_id int(11) NOT NULL AUTO_INCREMENT,
7317           name varchar(255) CHARACTER SET utf8 NOT NULL,
7318           owner int(11) NOT NULL,
7319           PRIMARY KEY (patron_list_id),
7320           KEY owner (owner)
7321         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7322     });
7323
7324     $dbh->do(q{
7325         ALTER TABLE `patron_lists`
7326           ADD CONSTRAINT patron_lists_ibfk_1 FOREIGN KEY (`owner`) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE;
7327     });
7328
7329     $dbh->do(q{
7330         CREATE TABLE patron_list_patrons (
7331           patron_list_patron_id int(11) NOT NULL AUTO_INCREMENT,
7332           patron_list_id int(11) NOT NULL,
7333           borrowernumber int(11) NOT NULL,
7334           PRIMARY KEY (patron_list_patron_id),
7335           KEY patron_list_id (patron_list_id),
7336           KEY borrowernumber (borrowernumber)
7337         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7338     });
7339
7340     $dbh->do(q{
7341         ALTER TABLE `patron_list_patrons`
7342           ADD CONSTRAINT patron_list_patrons_ibfk_1 FOREIGN KEY (patron_list_id) REFERENCES patron_lists (patron_list_id) ON DELETE CASCADE ON UPDATE CASCADE,
7343           ADD CONSTRAINT patron_list_patrons_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE;
7344     });
7345
7346     $dbh->do(q{
7347         INSERT INTO permissions (module_bit, code, description) VALUES
7348         (13, 'manage_patron_lists', 'Add, edit and delete patron lists and their contents')
7349     });
7350
7351     print "Upgrade to $DBversion done (Bug 10565 - Add a 'Patron List' feature for storing and manipulating collections of patrons)\n";
7352     SetVersion($DBversion);
7353 }
7354
7355 $DBversion = "3.13.00.032";
7356 if ( CheckVersion($DBversion) ) {
7357     $dbh->do("ALTER TABLE aqorders ADD COLUMN orderstatus varchar(16) DEFAULT 'new' AFTER parent_ordernumber");
7358     $dbh->do("UPDATE aqorders SET orderstatus='ordered' WHERE basketno IN (SELECT basketno FROM aqbasket WHERE closedate IS NOT NULL)");
7359     $dbh->do(q{
7360         UPDATE aqorders SET orderstatus='partial'
7361         WHERE quantity > quantityreceived
7362         AND quantityreceived > 0
7363         AND ordernumber IN (
7364             SELECT parent_ordernumber
7365             FROM (
7366                 SELECT DISTINCT(parent_ordernumber)
7367                 FROM aqorders
7368                 WHERE ordernumber != parent_ordernumber
7369             ) AS aq
7370         )
7371         AND basketno IN (SELECT basketno FROM aqbasket WHERE closedate IS NOT NULL)
7372     });
7373     $dbh->do("UPDATE aqorders SET orderstatus='complete' WHERE quantity=quantityreceived");
7374     $dbh->do("UPDATE aqorders SET orderstatus='cancelled' WHERE datecancellationprinted IS NOT NULL");
7375     print "Upgrade to $DBversion done (Bug 5336: Add the new column aqorders.orderstatus)\n";
7376     SetVersion($DBversion);
7377 }
7378
7379 $DBversion = "3.13.00.033";
7380 if ( CheckVersion($DBversion) ) {
7381     $dbh->do(qq|
7382         DROP TABLE IF EXISTS subscription_frequencies
7383     |);
7384     $dbh->do(qq|
7385         CREATE TABLE subscription_frequencies (
7386             id INTEGER NOT NULL AUTO_INCREMENT,
7387             description TEXT NOT NULL,
7388             displayorder INT DEFAULT NULL,
7389             unit ENUM('day','week','month','year') DEFAULT NULL,
7390             unitsperissue INTEGER NOT NULL DEFAULT '1',
7391             issuesperunit INTEGER NOT NULL DEFAULT '1',
7392             PRIMARY KEY (id)
7393         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
7394     |);
7395
7396     $dbh->do(qq|
7397         DROP TABLE IF EXISTS subscription_numberpatterns
7398     |);
7399     $dbh->do(qq|
7400         CREATE TABLE subscription_numberpatterns (
7401             id INTEGER NOT NULL AUTO_INCREMENT,
7402             label VARCHAR(255) NOT NULL,
7403             displayorder INTEGER DEFAULT NULL,
7404             description TEXT NOT NULL,
7405             numberingmethod VARCHAR(255) NOT NULL,
7406             label1 VARCHAR(255) DEFAULT NULL,
7407             add1 INTEGER DEFAULT NULL,
7408             every1 INTEGER DEFAULT NULL,
7409             whenmorethan1 INTEGER DEFAULT NULL,
7410             setto1 INTEGER DEFAULT NULL,
7411             numbering1 VARCHAR(255) DEFAULT NULL,
7412             label2 VARCHAR(255) DEFAULT NULL,
7413             add2 INTEGER DEFAULT NULL,
7414             every2 INTEGER DEFAULT NULL,
7415             whenmorethan2 INTEGER DEFAULT NULL,
7416             setto2 INTEGER DEFAULT NULL,
7417             numbering2 VARCHAR(255) DEFAULT NULL,
7418             label3 VARCHAR(255) DEFAULT NULL,
7419             add3 INTEGER DEFAULT NULL,
7420             every3 INTEGER DEFAULT NULL,
7421             whenmorethan3 INTEGER DEFAULT NULL,
7422             setto3 INTEGER DEFAULT NULL,
7423             numbering3 VARCHAR(255) DEFAULT NULL,
7424             PRIMARY KEY (id)
7425         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
7426     |);
7427
7428     $dbh->do(qq|
7429         INSERT INTO subscription_frequencies (description, unit, unitsperissue, issuesperunit, displayorder)
7430         VALUES
7431             ('2/day', 'day', 1, 2, 1),
7432             ('1/day', 'day', 1, 1, 2),
7433             ('3/week', 'week', 1, 3, 3),
7434             ('1/week', 'week', 1, 1, 4),
7435             ('1/2 weeks', 'week', 2, 1, 5),
7436             ('1/3 weeks', 'week', 3, 1, 6),
7437             ('1/month', 'month', 1, 1, 7),
7438             ('1/2 months', 'month', 2, 1, 8),
7439             ('1/3 months', 'month', 3, 1, 9),
7440             ('2/year', 'month', 6, 1, 10),
7441             ('1/year', 'year', 1, 1, 11),
7442             ('1/2 year', 'year', 2, 1, 12),
7443             ('Irregular', NULL, 1, 1, 13)
7444     |);
7445
7446     # Used to link existing subscription to newly created frequencies
7447     my $frequencies_mapping = {     # keys are old frequency numbers, values are the new ones
7448         1 => 2,     # daily (n/week)
7449         2 => 4,     # 1/week
7450         3 => 5,     # 1/2 weeks
7451         4 => 6,     # 1/3 weeks
7452         5 => 7,     # 1/month
7453         6 => 8,     # 1/2 months (6/year)
7454         7 => 9,     # 1/3 months (1/quarter)
7455         8 => 9,    # 1/quarter (seasonal)
7456         9 => 10,    # 2/year
7457         10 => 11,   # 1/year
7458         11 => 12,   # 1/2 years
7459         12 => 1,    # 2/day
7460         16 => 13,   # Without periodicity
7461         32 => 13,   # Irregular
7462         48 => 13    # Unknown
7463     };
7464
7465     $dbh->do(qq|
7466         INSERT INTO subscription_numberpatterns
7467             (label, displayorder, description, numberingmethod,
7468             label1, add1, every1, whenmorethan1, setto1, numbering1,
7469             label2, add2, every2, whenmorethan2, setto2, numbering2,
7470             label3, add3, every3, whenmorethan3, setto3, numbering3)
7471         VALUES
7472             ('Number', 1, 'Simple Numbering method', 'No.{X}',
7473             'Number', 1, 1, 99999, 1, NULL,
7474             NULL, NULL, NULL, NULL, NULL, NULL,
7475             NULL, NULL, NULL, NULL, NULL, NULL),
7476
7477             ('Volume, Number, Issue', 2, 'Volume Number Issue 1', 'Vol.{X}, Number {Y}, Issue {Z}',
7478             'Volume', 1, 48, 99999, 1, NULL,
7479             'Number', 1, 4, 12, 1, NULL,
7480             'Issue', 1, 1, 4, 1, NULL),
7481
7482             ('Volume, Number', 3, 'Volume Number 1', 'Vol {X}, No {Y}',
7483             'Volume', 1, 12, 99999, 1, NULL,
7484             'Number', 1, 1, 12, 1, NULL,
7485             NULL, NULL, NULL, NULL, NULL, NULL),
7486
7487             ('Seasonal', 4, 'Season Year', '{X} {Y}',
7488             'Season', 1, 1, 3, 0, 'season',
7489             'Year', 1, 4, 99999, 1, NULL,
7490             NULL, NULL, NULL, NULL, NULL, NULL)
7491     |);
7492
7493     $dbh->do(qq|
7494         ALTER TABLE subscription
7495         MODIFY COLUMN numberpattern INTEGER DEFAULT NULL,
7496         MODIFY COLUMN periodicity INTEGER DEFAULT NULL
7497     |);
7498
7499     # Update existing subscriptions
7500
7501     my $query = qq|
7502         SELECT subscriptionid, periodicity, numberingmethod,
7503             add1, every1, whenmorethan1, setto1,
7504             add2, every2, whenmorethan2, setto2,
7505             add3, every3, whenmorethan3, setto3
7506         FROM subscription
7507         ORDER BY subscriptionid
7508     |;
7509     my $sth = $dbh->prepare($query);
7510     $sth->execute;
7511     my $insert_numberpatterns_sth = $dbh->prepare(qq|
7512         INSERT INTO subscription_numberpatterns
7513              (label, displayorder, description, numberingmethod,
7514             label1, add1, every1, whenmorethan1, setto1, numbering1,
7515             label2, add2, every2, whenmorethan2, setto2, numbering2,
7516             label3, add3, every3, whenmorethan3, setto3, numbering3)
7517         VALUES
7518             (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
7519     |);
7520     my $check_numberpatterns_sth = $dbh->prepare(qq|
7521         SELECT * FROM subscription_numberpatterns
7522         WHERE (add1 = ? OR (add1 IS NULL AND ? IS NULL)) AND (add2 = ? OR (add2 IS NULL AND ? IS NULL))
7523         AND (add3 = ? OR (add3 IS NULL AND ? IS NULL)) AND (every1 = ? OR (every1 IS NULL AND ? IS NULL))
7524         AND (every2 = ? OR (every2 IS NULL AND ? IS NULL)) AND (every3 = ? OR (every3 IS NULL AND ? IS NULL))
7525         AND (whenmorethan1 = ? OR (whenmorethan1 IS NULL AND ? IS NULL)) AND (whenmorethan2 = ? OR (whenmorethan2 IS NULL AND ? IS NULL))
7526         AND (whenmorethan3 = ? OR (whenmorethan3 IS NULL AND ? IS NULL)) AND (setto1 = ? OR (setto1 IS NULL AND ? IS NULL))
7527         AND (setto2 = ? OR (setto2 IS NULL AND ? IS NULL)) AND (setto3 = ? OR (setto3 IS NULL AND ? IS NULL))
7528         AND (numberingmethod = ? OR (numberingmethod IS NULL AND ? IS NULL))
7529         LIMIT 1
7530     |);
7531     my $update_subscription_sth = $dbh->prepare(qq|
7532         UPDATE subscription
7533         SET numberpattern = ?,
7534             periodicity = ?
7535         WHERE subscriptionid = ?
7536     |);
7537
7538     my $i = 1;
7539     while(my $sub = $sth->fetchrow_hashref) {
7540         $check_numberpatterns_sth->execute(
7541             $sub->{add1}, $sub->{add1}, $sub->{add2}, $sub->{add2}, $sub->{add3}, $sub->{add3},
7542             $sub->{every1}, $sub->{every1}, $sub->{every2}, $sub->{every2}, $sub->{every3}, $sub->{every3},
7543             $sub->{whenmorethan1}, $sub->{whenmorethan1}, $sub->{whenmorethan2}, $sub->{whenmorethan2},
7544             $sub->{whenmorethan3}, $sub->{whenmorethan3}, $sub->{setto1}, $sub->{setto1}, $sub->{setto2},
7545             $sub->{setto2}, $sub->{setto3}, $sub->{setto3}, $sub->{numberingmethod}, $sub->{numberingmethod}
7546         );
7547         my $p = $check_numberpatterns_sth->fetchrow_hashref;
7548         if (defined $p) {
7549             # Pattern already exists, link to it
7550             $update_subscription_sth->execute($p->{id},
7551                 $frequencies_mapping->{$sub->{periodicity}},
7552                 $sub->{subscriptionid});
7553         } else {
7554             # Create a new numbering pattern for this subscription
7555             my $ok = $insert_numberpatterns_sth->execute(
7556                 "Backup pattern $i", 4+$i, "Automatically created pattern by updatedatabase", $sub->{numberingmethod},
7557                 "X", $sub->{add1}, $sub->{every1}, $sub->{whenmorethan1}, $sub->{setto1}, undef,
7558                 "Y", $sub->{add2}, $sub->{every2}, $sub->{whenmorethan2}, $sub->{setto2}, undef,
7559                 "Z", $sub->{add3}, $sub->{every3}, $sub->{whenmorethan3}, $sub->{setto3}, undef
7560             );
7561             if($ok) {
7562                 my $id = $dbh->last_insert_id(undef, undef, 'subscription_numberpatterns', undef);
7563                 # Link to subscription_numberpatterns and subscription_frequencies
7564                 $update_subscription_sth->execute($id,
7565                     $frequencies_mapping->{$sub->{periodicity}},
7566                     $sub->{subscriptionid});
7567             }
7568             $i++;
7569         }
7570     }
7571
7572     # Remove now useless columns
7573     $dbh->do(qq|
7574         ALTER TABLE subscription
7575         DROP COLUMN numberingmethod,
7576         DROP COLUMN add1,
7577         DROP COLUMN every1,
7578         DROP COLUMN whenmorethan1,
7579         DROP COLUMN setto1,
7580         DROP COLUMN add2,
7581         DROP COLUMN every2,
7582         DROP COLUMN whenmorethan2,
7583         DROP COLUMN setto2,
7584         DROP COLUMN add3,
7585         DROP COLUMN every3,
7586         DROP COLUMN whenmorethan3,
7587         DROP COLUMN setto3,
7588         DROP COLUMN dow,
7589         DROP COLUMN issuesatonce,
7590         DROP COLUMN hemisphere,
7591         ADD COLUMN countissuesperunit INTEGER NOT NULL DEFAULT 1 AFTER periodicity,
7592         ADD COLUMN skip_serialseq BOOLEAN NOT NULL DEFAULT 0 AFTER irregularity,
7593         ADD COLUMN locale VARCHAR(80) DEFAULT NULL AFTER numberpattern,
7594         ADD CONSTRAINT subscription_ibfk_1 FOREIGN KEY (periodicity) REFERENCES subscription_frequencies (id) ON DELETE SET NULL ON UPDATE CASCADE,
7595         ADD CONSTRAINT subscription_ibfk_2 FOREIGN KEY (numberpattern) REFERENCES subscription_numberpatterns (id) ON DELETE SET NULL ON UPDATE CASCADE
7596     |);
7597
7598     # Set firstacquidate if not already set (firstacquidate is now mandatory)
7599     my $get_first_planneddate_sth = $dbh->prepare(qq|
7600         SELECT planneddate
7601         FROM serial
7602         WHERE subscriptionid = ?
7603         ORDER BY serialid
7604         LIMIT 1
7605     |);
7606     my $update_firstacquidate_sth = $dbh->prepare(qq|
7607         UPDATE subscription
7608         SET firstacquidate = ?
7609         WHERE subscriptionid = ?
7610     |);
7611     my $get_subscriptions_sth = $dbh->prepare(qq|
7612         SELECT subscriptionid, startdate
7613         FROM subscription
7614         WHERE firstacquidate IS NULL
7615           OR firstacquidate = '0000-00-00'
7616     |);
7617     $get_subscriptions_sth->execute;
7618     while ( my ($subscriptionid, $startdate) = $get_subscriptions_sth->fetchrow ) {
7619         # Try to get the planned date of the first serial
7620         $get_first_planneddate_sth->execute($subscriptionid);
7621         my ($first_planneddate) = $get_first_planneddate_sth->fetchrow;
7622         if ($first_planneddate and $first_planneddate =~ /^\d{4}-\d{2}-\d{2}$/) {
7623             $update_firstacquidate_sth->execute($first_planneddate, $subscriptionid);
7624         } else {
7625             # Defaults to subscription start date
7626             $update_firstacquidate_sth->execute($startdate, $subscriptionid);
7627         }
7628     }
7629
7630     print "Upgrade to $DBversion done (Bug 7688: add subscription_frequencies and subscription_numberpatterns tables)\n";
7631     SetVersion($DBversion);
7632 }
7633
7634 $DBversion = "3.13.00.034";
7635 if ( CheckVersion($DBversion) ) {
7636     $dbh->do("
7637         ALTER TABLE `import_batches`
7638         CHANGE `item_action` `item_action`
7639           ENUM( 'always_add', 'add_only_for_matches', 'add_only_for_new', 'ignore', 'replace' )
7640           NOT NULL DEFAULT 'always_add'
7641     ");
7642     print "Upgrade to $DBversion done (Bug 7131 - way to overlay items in in marc import)\n";
7643     SetVersion($DBversion);
7644 }
7645
7646 $DBversion ="3.13.00.035";
7647 if ( CheckVersion($DBversion) ) {
7648     $dbh->do(q{
7649 CREATE TABLE borrower_debarments (
7650   borrower_debarment_id int(11) NOT NULL AUTO_INCREMENT,
7651   borrowernumber int(11) NOT NULL,
7652   expiration date DEFAULT NULL,
7653   `type` enum('SUSPENSION','OVERDUES','MANUAL') NOT NULL DEFAULT 'MANUAL',
7654   `comment` text,
7655   manager_id int(11) DEFAULT NULL,
7656   created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
7657   updated timestamp NULL DEFAULT NULL,
7658   PRIMARY KEY (borrower_debarment_id),
7659   KEY borrowernumber (borrowernumber) ,
7660   CONSTRAINT `borrower_debarments_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
7661     ON DELETE CASCADE ON UPDATE CASCADE
7662 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7663     });
7664
7665     # debarments with end date
7666     $dbh->do(q{
7667 INSERT INTO borrower_debarments ( borrowernumber, expiration, comment ) SELECT borrowernumber, debarred, debarredcomment FROM borrowers WHERE debarred IS NOT NULL AND debarred <> '9999-12-31'
7668     });
7669     # debarments with no end date
7670     $dbh->do(q{
7671 INSERT INTO borrower_debarments ( borrowernumber, comment ) SELECT borrowernumber, debarredcomment FROM borrowers WHERE debarred = '9999-12-31'
7672     });
7673
7674     $dbh->do(q{
7675 INSERT IGNORE INTO systempreferences (variable,value,explanation,type) VALUES
7676 ('AutoRemoveOverduesRestrictions','0','Defines whether an OVERDUES debarment should be lifted automatically if all overdue items are returned by the patron.','YesNo')
7677     });
7678
7679     print "Upgrade to $DBversion done (Bug 2720 - Overdues which debar automatically should undebar automatically when returned)\n";
7680     SetVersion($DBversion);
7681 }
7682
7683 $DBversion = "3.13.00.036";
7684 if ( CheckVersion($DBversion) ) {
7685     $dbh->do(qq{
7686         INSERT INTO systempreferences (variable, value, explanation, options, type)
7687         VALUES ('StaffDetailItemSelection', '1', 'Enable item selection in record detail page', NULL, 'YesNo')
7688     });
7689     print "Upgrade to $DBversion done (Add system preference StaffDetailItemSelection)\n";
7690     SetVersion($DBversion);
7691 }
7692
7693 $DBversion = "3.13.00.037";
7694 if ( CheckVersion($DBversion) ) {
7695     #add phone if it is not there already (explains the ignore option)
7696     $dbh->do("
7697 INSERT IGNORE INTO message_transport_types (message_transport_type) values ('phone');
7698     ");
7699     print "Upgrade to $DBversion done (Bug 10572: Add phone to message_transport_types table for new installs)\n";
7700     SetVersion($DBversion);
7701 }
7702
7703 $DBversion = "3.13.00.038";
7704 if ( CheckVersion($DBversion) ) {
7705     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES(15, 'superserials', 'Manage subscriptions from any branch (only applies when IndependentBranches is used)')");
7706     print "Upgrade to $DBversion done (Bug 8435: Add superserials permission)\n";
7707     SetVersion($DBversion);
7708 }
7709
7710 $DBversion = "3.13.00.039";
7711 if ( CheckVersion($DBversion) ) {
7712     $dbh->do("
7713         ALTER TABLE aqbasket ADD branch varchar(10) default NULL
7714     ");
7715     $dbh->do("
7716         ALTER TABLE aqbasket
7717         ADD CONSTRAINT aqbasket_ibfk_4 FOREIGN KEY (branch)
7718             REFERENCES branches (branchcode)
7719             ON UPDATE CASCADE ON DELETE SET NULL
7720     ");
7721     $dbh->do("
7722         DROP TABLE IF EXISTS aqbasketusers
7723     ");
7724     $dbh->do("
7725         CREATE TABLE aqbasketusers (
7726             basketno int(11) NOT NULL,
7727             borrowernumber int(11) NOT NULL,
7728             PRIMARY KEY (basketno,borrowernumber),
7729             CONSTRAINT aqbasketusers_ibfk_1 FOREIGN KEY (basketno) REFERENCES aqbasket (basketno) ON DELETE CASCADE ON UPDATE CASCADE,
7730             CONSTRAINT aqbasketusers_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
7731         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7732     ");
7733     $dbh->do("
7734         INSERT INTO permissions (module_bit, code, description)
7735         VALUES (11, 'order_manage_all', 'Manage all orders and baskets, regardless of restrictions on them')
7736     ");
7737
7738     print "Upgrade to $DBversion done (Add branch and users list to baskets. "
7739         . "New permission order_manage_all)\n";
7740     SetVersion($DBversion);
7741 }
7742
7743 $DBversion = "3.13.00.040";
7744 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
7745     $dbh->do("CREATE TABLE IF NOT EXISTS marc_modification_templates (
7746               template_id int(11) NOT NULL auto_increment,
7747               name text NOT NULL,
7748               PRIMARY KEY  (template_id)
7749               ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;"
7750     );
7751
7752     $dbh->do("
7753       CREATE TABLE IF NOT EXISTS marc_modification_template_actions (
7754       mmta_id int(11) NOT NULL auto_increment,
7755       template_id int(11) NOT NULL,
7756       ordering int(3) NOT NULL,
7757       action enum('delete_field','update_field','move_field','copy_field') NOT NULL,
7758       field_number smallint(6) NOT NULL default '0',
7759       from_field varchar(3) NOT NULL,
7760       from_subfield varchar(1) NULL,
7761       field_value varchar(100) default NULL,
7762       to_field varchar(3) default NULL,
7763       to_subfield varchar(1) default NULL,
7764       to_regex_search text,
7765       to_regex_replace text,
7766       to_regex_modifiers varchar(8) default '',
7767       conditional enum('if','unless') default NULL,
7768       conditional_field varchar(3) default NULL,
7769       conditional_subfield varchar(1) default NULL,
7770       conditional_comparison enum('exists','not_exists','equals','not_equals') default NULL,
7771       conditional_value text,
7772       conditional_regex tinyint(1) NOT NULL default '0',
7773       description text,
7774       PRIMARY KEY  (mmta_id),
7775       CONSTRAINT `mmta_ibfk_1` FOREIGN KEY (`template_id`) REFERENCES `marc_modification_templates` (`template_id`) ON DELETE CASCADE ON UPDATE CASCADE
7776       ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7777     ");
7778
7779     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('13', 'marc_modification_templates', 'Manage marc modification templates')");
7780
7781     print "Upgrade to $DBversion done ( Bug 8015: Added tables for MARC Modification Framework )\n";
7782     SetVersion($DBversion);
7783 }
7784
7785 $DBversion = "3.13.00.041";
7786 if(CheckVersion($DBversion)) {
7787     $dbh->do(q{
7788         INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AcqItemSetSubfieldsWhenReceived','','Set subfields for item when items are created when receiving (e.g. o=5|a="foo bar")','','Free');
7789     });
7790     print "Upgrade to $DBversion done (Bug 10986: Added AcqItemSetSubfieldsWhenReceived syspref)\n";
7791     SetVersion($DBversion);
7792 }
7793
7794 $DBversion = "3.13.00.042";
7795 if(CheckVersion($DBversion)) {
7796     print "Upgrade to $DBversion done (Koha 3.14 beta)\n";
7797     SetVersion($DBversion);
7798 }
7799
7800 $DBversion = "3.13.00.043";
7801 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
7802     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('SearchEngine','Zebra','Solr|Zebra','Search Engine','Choice')");
7803     print "Upgrade to $DBversion done (Bug 11196: Add system preference SearchEngine if missing )\n";
7804     SetVersion($DBversion);
7805 }
7806
7807 $DBversion = "3.14.00.000";
7808 if ( CheckVersion($DBversion) ) {
7809     print "Upgrade to $DBversion done (3.14.0 release)\n";
7810     SetVersion ($DBversion);
7811 }
7812
7813 $DBversion = '3.15.00.000';
7814 if ( CheckVersion($DBversion) ) {
7815     print "Upgrade to $DBversion done (the road goes ever on)\n";
7816     SetVersion ($DBversion);
7817 }
7818
7819 $DBversion = "3.15.00.001";
7820 if ( CheckVersion($DBversion) ) {
7821     $dbh->do("UPDATE systempreferences SET value='clear' where variable = 'CircAutoPrintQuickSlip' and value = '0'");
7822     $dbh->do("UPDATE systempreferences SET value='qslip' where variable = 'CircAutoPrintQuickSlip' and value = '1'");
7823     $dbh->do("UPDATE systempreferences SET explanation = 'Choose what should happen when an empty barcode field is submitted in circulation: Display a print quick slip window, Display a print slip window or Clear the screen.', type = 'Choice' where variable = 'CircAutoPrintQuickSlip'");
7824     print "Upgrade to $DBversion done (Bug 11040: Add option to print full slip when checking out a null barcode)\n";
7825     SetVersion($DBversion);
7826 }
7827
7828 $DBversion = "3.15.00.002";
7829 if(CheckVersion($DBversion)) {
7830     $dbh->do("ALTER TABLE deleteditems MODIFY materials text;");
7831     print "Upgrade to $DBversion done (Bug 11275: alter deleteditems.materials from varchar(10) to text)\n";
7832     SetVersion($DBversion);
7833 }
7834
7835 $DBversion = "3.15.00.003";
7836 if ( CheckVersion($DBversion) ) {
7837     $dbh->do(q{
7838         UPDATE accountlines
7839         SET description = ''
7840         WHERE description IN (
7841             ' New Card',
7842             ' Fine',
7843             ' Sundry',
7844             'Writeoff',
7845             ' Account Management fee',
7846             'Payment,thanks', 'Payment,thanks - ',
7847             ' Lost Item'
7848         )
7849     });
7850     print "Upgrade to $DBversion done (Bug 2546: Update fine descriptions)\n";
7851     SetVersion($DBversion);
7852 }
7853
7854 $DBversion = "3.15.00.004";
7855 if ( CheckVersion($DBversion) ) {
7856     if ( C4::Context->preference("marcflavour") eq 'MARC21' ) {
7857         $dbh->do(qq{
7858             INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian, libopac, repeatable, mandatory,
7859             kohafield, tab, authorised_value, authtypecode, value_builder, isurl, hidden, frameworkcode, seealso, link,
7860             defaultvalue) VALUES
7861             ('015', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7862             ('020', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7863             ('024', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7864             ('027', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7865             ('800', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7866             ('810', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7867             ('811', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7868             ('830', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL);
7869         });
7870         $dbh->do(qq{
7871             INSERT IGNORE INTO auth_subfield_structure (authtypecode, tagfield, tagsubfield, liblibrarian, libopac, repeatable,
7872             mandatory, tab, authorised_value, value_builder, seealso, isurl, hidden, linkid, kohafield, frameworkcode) VALUES
7873             ('', '020', 'q', 'Qualifying information', 'Qualifying information', 1, 0, 0, NULL, NULL, NULL, 0, 0, '', '', ''),
7874             ('', '024', 'q', 'Qualifying information', 'Qualifying information', 1, 0, 0, NULL, NULL, NULL, 0, 0, '', '', '');
7875         });
7876     }
7877     print "Upgrade to $DBversion done (Bug 10970 - Update MARC21 frameworks to Update Nr. 17 - DB update)\n";
7878     SetVersion($DBversion);
7879 }
7880
7881 $DBversion = "3.15.00.005";
7882 if ( CheckVersion($DBversion) ) {
7883    $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('AcquisitionDetails', '1', '', 'Hide/Show acquisition details on the biblio detail page.', 'YesNo');");
7884    print "Upgrade to $DBversion done (Bug 8230: Add AcquisitionDetails system preference)\n";
7885    SetVersion ($DBversion);
7886 }
7887
7888 $DBversion = "3.15.00.006";
7889 if(CheckVersion($DBversion)) {
7890     $dbh->do(q{
7891         ALTER TABLE `borrowers`
7892         ADD KEY `surname_idx` (`surname`(255)),
7893         ADD KEY `firstname_idx` (`firstname`(255)),
7894         ADD KEY `othernames_idx` (`othernames`(255))
7895     });
7896     print "Upgrade to $DBversion done (Bug 11249 - Add DB indexes on borrower names)\n";
7897     SetVersion($DBversion);
7898 }
7899
7900 $DBversion = "3.15.00.007";
7901 if ( CheckVersion($DBversion) ) {
7902    $dbh->do("ALTER TABLE items ADD itemlost_on DATETIME NULL AFTER itemlost");
7903    $dbh->do("ALTER TABLE items ADD withdrawn_on DATETIME NULL AFTER withdrawn");
7904    $dbh->do("ALTER TABLE deleteditems ADD itemlost_on DATETIME NULL AFTER itemlost");
7905    $dbh->do("ALTER TABLE deleteditems ADD withdrawn_on DATETIME NULL AFTER withdrawn");
7906    print "Upgrade to $DBversion done (Bug 9673 - Track when items are marked as lost or withdrawn)\n";
7907    SetVersion ($DBversion);
7908 }
7909
7910 $DBversion = "3.15.00.008";
7911 if ( CheckVersion($DBversion) ) {
7912     $dbh->do(q{
7913         ALTER TABLE collections_tracking CHANGE ctId collections_tracking_id integer(11) NOT NULL auto_increment;
7914     });
7915     print "Upgrade to $DBversion done (Bug 11384) - change name of collections_tracker.ctId column)\n";
7916    SetVersion ($DBversion);
7917 }
7918
7919 $DBversion = "3.15.00.009";
7920 if ( CheckVersion($DBversion) ) {
7921     $dbh->do(q{
7922         ALTER TABLE suggestions MODIFY suggesteddate DATE NOT NULL
7923     });
7924     print "Upgrade to $DBversion done (Bug 11391) - drop default value on suggestions.suggesteddate column)\n";
7925    SetVersion ($DBversion);
7926 }
7927
7928 $DBversion = "3.15.00.010";
7929 if(CheckVersion($DBversion)) {
7930     $dbh->do("ALTER TABLE deleteditems DROP COLUMN marc");
7931     print "Upgrade to $DBversion done (Bug 6331: remove obsolete column in deleteditems.marc)\n";
7932     SetVersion ($DBversion);
7933 }
7934
7935 $DBversion = "3.15.00.011";
7936 if(CheckVersion($DBversion)) {
7937     $dbh->do("UPDATE marc_subfield_structure SET maxlength=9999 WHERE maxlength IS NULL OR maxlength=0;");
7938     print "Upgrade to $DBversion done (Bug 8018: set 9999 as default max length for subfields)\n";
7939     SetVersion ($DBversion);
7940 }
7941
7942 $DBversion = "3.15.00.012";
7943 if ( CheckVersion($DBversion) ) {
7944     $dbh->do(q{
7945         INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'force_checkout', 'Force checkout if a limitation exists')
7946     });
7947     $dbh->do(q{
7948         INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'manage_restrictions', 'Manage restrictions for accounts')
7949     });
7950     $dbh->do(q{
7951         INSERT INTO user_permissions (borrowernumber, module_bit, code)
7952             SELECT user_permissions.borrowernumber, 1, 'force_checkout'
7953             FROM user_permissions
7954             LEFT JOIN borrowers USING(borrowernumber)
7955             WHERE borrowers.flags & (1 << 1)
7956     });
7957     $dbh->do(q{
7958         INSERT INTO user_permissions (borrowernumber, module_bit, code)
7959             SELECT user_permissions.borrowernumber, 1, 'manage_restrictions'
7960             FROM user_permissions
7961             LEFT JOIN borrowers USING(borrowernumber)
7962             WHERE borrowers.flags & (1 << 1)
7963     });
7964
7965     print "Upgrade to $DBversion done (Bug 10863 - Add permissions force_checkout and manage_restrictions)\n";
7966     SetVersion($DBversion);
7967 }
7968
7969 $DBversion = "3.15.00.013";
7970 if(CheckVersion($DBversion)) {
7971     $dbh->do(q{
7972         UPDATE systempreferences
7973         SET explanation = 'Upon receiving items, update their subfields if they were created when placing an order (e.g. o=5|a="foo bar")'
7974         WHERE variable = "AcqItemSetSubfieldsWhenReceived"
7975     });
7976
7977     $dbh->do(q{
7978         UPDATE systempreferences
7979         SET value = ''
7980         WHERE variable = "AcqItemSetSubfieldsWhenReceived"
7981             AND value = "0"
7982     });
7983     print "Upgrade to $DBversion done (Bug 11237: Update explanation and default value for AcqItemSetSubfieldsWhenReceived syspref)\n";
7984     SetVersion($DBversion);
7985 }
7986
7987 $DBversion = "3.15.00.014";
7988 if (CheckVersion($DBversion)) {
7989     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('SelfCheckReceiptPrompt', '1', 'NULL', 'If ON, print receipt dialog pops up when self checkout is finished.', 'YesNo');");
7990     print "Upgrade to $DBversion done (Bug 11415: add system preference for automatic self checkout receipt printing)\n";
7991     SetVersion($DBversion);
7992 }
7993
7994 $DBversion = "3.15.00.015";
7995 if (CheckVersion($DBversion)) {
7996     $dbh->do("INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
7997         ('OpacSuggestionManagedBy',1,'','Show the name of the staff member who managed a suggestion in OPAC','YesNo');");
7998     print "Upgrade to $DBversion done (Bug 10907: Add OpacSuggestionManagedBy system preference)\n";
7999     SetVersion($DBversion);
8000 }
8001
8002 $DBversion = "3.15.00.016";
8003 if (CheckVersion($DBversion)) {
8004     $dbh->do("ALTER TABLE biblioitems CHANGE url url TEXT NULL DEFAULT NULL");
8005     $dbh->do("ALTER TABLE deletedbiblioitems CHANGE url url TEXT NULL DEFAULT NULL");
8006     print "Upgrade to $DBversion done (Bug 11268 - Biblioitems URL field is too small for some URLs)\n";
8007     SetVersion($DBversion);
8008 }
8009
8010 $DBversion = "3.15.00.017";
8011 if(CheckVersion($DBversion)) {
8012     $dbh->do(q{
8013         UPDATE systempreferences
8014         SET explanation = 'Define the contents of UNIMARC authority control field 100 position 08-35'
8015         WHERE variable = "UNIMARCAuthorityField100"
8016     });
8017     $dbh->do(q{
8018         UPDATE systempreferences
8019         SET explanation = 'Define the contents of MARC21 authority control field 008 position 06-39'
8020         WHERE variable = "MARCAuthorityControlField008"
8021     });
8022     $dbh->do(q{
8023         UPDATE systempreferences
8024         SET explanation = 'Define MARC Organization Code for MARC21 records - http://www.loc.gov/marc/organizations/orgshome.html'
8025         WHERE variable = "MARCOrgCode"
8026     });
8027     print "Upgrade to $DBversion done (Bug 11611 - fix possible confusion between UNIMARC and MARC21 in some sysprefs)\n";
8028     SetVersion($DBversion);
8029 }
8030
8031 $DBversion = "3.15.00.018";
8032 if ( CheckVersion($DBversion) ) {
8033     $dbh->{AutoCommit} = 0;
8034     $dbh->{RaiseError} = 1;
8035
8036     eval {
8037         $dbh->selectcol_arrayref(q|SELECT COUNT(*) FROM roadtype|);
8038     };
8039     unless ( $@ ) {
8040         my $av_added = $dbh->do(q|
8041             INSERT INTO authorised_values(category, authorised_value, lib, lib_opac)
8042                 SELECT 'ROADTYPE', roadtypeid, road_type, road_type
8043                 FROM roadtype;
8044         |);
8045
8046         my $rt_deleted = $dbh->do(q|
8047             DELETE FROM roadtype
8048         |);
8049
8050         if ( $av_added == $rt_deleted or $rt_deleted eq "0E0" ) {
8051             $dbh->do(q|
8052                 DROP TABLE roadtype;
8053             |);
8054             $dbh->commit;
8055             print "Upgrade to $DBversion done (Bug 7372: Move road types from the roadtype table to the ROADTYPE authorised values)\n";
8056             SetVersion($DBversion);
8057         } else {
8058             print "Upgrade to $DBversion failed (Bug 7372: Move road types from the roadtype table to the ROADTYPE authorised values.\nTransaction aborted because $@\n)";
8059             $dbh->rollback;
8060         }
8061     }
8062     $dbh->{AutoCommit} = 1;
8063     $dbh->{RaiseError} = 0;
8064 }
8065
8066 $DBversion = "3.15.00.019";
8067 if ( CheckVersion($DBversion) ) {
8068     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('OpacMaxItemsToDisplay','50','','Max items to display at the OPAC on a biblio detail','Integer')");
8069     print "Upgrade to $DBversion done (Bug 11256: Add system preference OpacMaxItemsToDisplay)\n";
8070     SetVersion($DBversion);
8071 }
8072
8073 $DBversion = "3.15.00.020";
8074 if ( CheckVersion($DBversion) ) {
8075     $dbh->do(q|
8076         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('MaxItemsForBatch','1000',NULL,'Max number of items record to process in a batch (modification or deletion)','Integer')
8077     |);
8078     print "Upgrade to $DBversion done (Bug 11343: Add system preference MaxItemsForBatch )\n";
8079     SetVersion($DBversion);
8080 }
8081
8082 $DBversion = "3.15.00.021";
8083 if(CheckVersion($DBversion)) {
8084     $dbh->do(q{
8085         ALTER TABLE `action_logs`
8086             DROP KEY timestamp,
8087             ADD KEY `timestamp_idx` (`timestamp`),
8088             ADD KEY `user_idx` (`user`),
8089             ADD KEY `module_idx` (`module`(255)),
8090             ADD KEY `action_idx` (`action`(255)),
8091             ADD KEY `object_idx` (`object`),
8092             ADD KEY `info_idx` (`info`(255))
8093     });
8094     print "Upgrade to $DBversion done (Bug 3445: Add indexes to action_logs table)\n";
8095     SetVersion($DBversion);
8096 }
8097
8098 $DBversion = "3.15.00.022";
8099 if (CheckVersion($DBversion)) {
8100     $dbh->do(q|
8101         DELETE FROM systempreferences WHERE variable= "memberofinstitution"
8102     |);
8103     print "Upgrade to $DBversion done (Bug 11751: Remove memberofinstitytion system preference)\n";
8104     SetVersion($DBversion);
8105 }
8106
8107 $DBversion = "3.15.00.023";
8108 if ( CheckVersion($DBversion) ) {
8109    $dbh->do("
8110        INSERT INTO systempreferences (variable,value,options,explanation,type)
8111        VALUES('CardnumberLength', '', '', 'Set a length for card numbers.', 'Free');
8112     ");
8113    print "Upgrade to $DBversion done (Bug 10861: Add CardnumberLength syspref)\n";
8114    SetVersion ($DBversion);
8115 }
8116
8117 $DBversion = "3.15.00.024";
8118 if ( CheckVersion($DBversion) ) {
8119     $dbh->do(q{
8120         DELETE FROM systempreferences WHERE variable = 'NoZebraIndexes'
8121     });
8122     print "Upgrade to $DBversion done (Bug 10012 - remove last vestiges of NoZebra)\n";
8123     SetVersion($DBversion);
8124 }
8125
8126 $DBversion = "3.15.00.025";
8127 if ( CheckVersion($DBversion) ) {
8128     $dbh->do(q{
8129         DROP TABLE aqorderdelivery;
8130     });
8131     print "Upgrade to $DBversion done (Bug 11928 - remove unused table)\n";
8132     SetVersion($DBversion);
8133 }
8134
8135 $DBversion = "3.15.00.026";
8136 if ( CheckVersion($DBversion) ) {
8137     $dbh->do(q{
8138         UPDATE language_descriptions SET description = 'Հայերեն' WHERE subtag = 'hy' AND lang = 'hy';
8139     });
8140     print "Upgrade to $DBversion done (Bug 11973 - Fix Armenian language description)\n";
8141     SetVersion($DBversion);
8142 }
8143
8144 $DBversion = "3.15.00.027";
8145 if (CheckVersion($DBversion)) {
8146     $dbh->do(q{
8147         ALTER TABLE opac_news ADD branchcode varchar(10) DEFAULT NULL
8148                                   AFTER idnew,
8149                               ADD CONSTRAINT opac_news_branchcode_ibfk
8150                                   FOREIGN KEY (branchcode)
8151                                   REFERENCES branches (branchcode)
8152                                   ON DELETE CASCADE ON UPDATE CASCADE;
8153     });
8154     print "Upgrade to $DBversion done (Bug 7567: Add branchcode to opac_news)\n";
8155     SetVersion($DBversion);
8156 }
8157
8158 $DBversion = "3.15.00.028";
8159 if(CheckVersion($DBversion)) {
8160     $dbh->do(q{
8161         ALTER TABLE issuingrules ADD norenewalbefore int(4) default NULL AFTER renewalperiod
8162     });
8163     print "Upgrade to $DBversion done (Bug 7413: Allow OPAC renewal x days before due date)\n";
8164     SetVersion($DBversion);
8165 }
8166
8167 $DBversion = "3.15.00.029";
8168 if ( CheckVersion($DBversion) ) {
8169     $dbh->do(q{
8170         UPDATE borrower_debarments SET expiration = NULL WHERE expiration = '9999-12-31'
8171     });
8172     print "Upgrade to $DBversion done (Bug 11846 - correct borrower_debarments with expiration 9999-12-31)\n";
8173     SetVersion($DBversion);
8174 }
8175
8176 $DBversion = "3.15.00.030";
8177 if(CheckVersion($DBversion)) {
8178     $dbh->do(q|
8179         INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OPACMySummaryNote','','','Note to display on the patron summary page. This note only appears if the patron is connected.','Free')
8180     |);
8181     print "Upgrade to $DBversion done (Bug 12052: Add OPACMySummaryNote syspref)\n";
8182     SetVersion($DBversion);
8183 }
8184
8185 $DBversion = "3.15.00.031";
8186 if ( CheckVersion($DBversion) ) {
8187    $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('10', 'writeoff', 'Write off fines and fees')");
8188    $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('10', 'remaining_permissions', 'Remaining permissions for managing fines and fees')");
8189    print "Upgrade to $DBversion done (Bug 9448 - Add separate permission for writing off fees)\n";
8190    SetVersion ($DBversion);
8191 }
8192
8193 $DBversion = "3.15.00.032";
8194 if ( CheckVersion($DBversion) ) {
8195     $dbh->do("ALTER TABLE aqorders CHANGE notes order_internalnote MEDIUMTEXT;");
8196     $dbh->do("ALTER TABLE aqorders ADD COLUMN order_vendornote MEDIUMTEXT AFTER order_internalnote;");
8197     print "Upgrade to $DBversion done (Bug 9416 - In each order, add a new note made for the vendor)\n";
8198    SetVersion ($DBversion);
8199 }
8200
8201 $DBversion = "3.15.00.033";
8202 if ( CheckVersion($DBversion) ) {
8203     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NoLoginInstructions', '', '60|10', 'Instructions to display on the OPAC login form when a patron is not logged in', 'Textarea')");
8204     print "Upgrade to $DBversion done (Bug 10951: Add NoLoginInstructions pref)\n";
8205     SetVersion($DBversion);
8206 }
8207
8208 $DBversion = "3.15.00.034";
8209 if ( CheckVersion($DBversion) ) {
8210     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('AdvancedSearchLanguages','','','ISO 639-2 codes of languages you wish to see appear as an advanced search option.  Example: eng|fra|ita','Textarea')");
8211     print "Upgrade to $DBversion done (Bug 10986: system preferences to limit languages in advanced search )\n";
8212     SetVersion ($DBversion);
8213 }
8214
8215 $DBversion = "3.15.00.035";
8216 if ( CheckVersion($DBversion) ) {
8217     #insert a notice for sharing a list and accepting a share
8218     $dbh->do("
8219 INSERT INTO letter (module, code, branchcode, name, is_html, title, content)
8220 VALUES ( 'members', 'SHARE_INVITE', '', 'Invitation for sharing a list', '0', 'Share list <<listname>>', 'Dear patron,
8221
8222 One of our patrons, <<borrowers.firstname>> <<borrowers.surname>>, invites you to share a list <<listname>> in our library catalog.
8223
8224 To access this shared list, please click on the following URL or copy-and-paste it into your browser address bar.
8225
8226 <<shareurl>>
8227
8228 In case you are not a patron in our library or do not want to accept this invitation, please ignore this mail. Note also that this invitation expires within two weeks.
8229
8230 Thank you.
8231
8232 Your library.'
8233     )");
8234     $dbh->do("
8235 INSERT INTO letter (module, code, branchcode, name, is_html, title, content)
8236 VALUES ( 'members', 'SHARE_ACCEPT', '', 'Notification about an accepted share', '0', 'Share on list <<listname>> accepted', 'Dear patron,
8237
8238 We want to inform you that <<borrowers.firstname>> <<borrowers.surname>> accepted your invitation to share your list <<listname>> in our library catalog.
8239
8240 Thank you.
8241
8242 Your library.'
8243     )");
8244     print "Upgrade to $DBversion done (Bug 9032: Share a list)\n";
8245     SetVersion($DBversion);
8246 }
8247
8248 $DBversion = "3.15.00.036";
8249 if ( CheckVersion($DBversion) ) {
8250     $dbh->do(q{
8251         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
8252         VALUES('AllowMultipleIssuesOnABiblio',1,'Allow/Don\'t allow patrons to check out multiple items from one biblio','','YesNo')
8253     });
8254
8255     print "Upgrade to $DBversion done (Bug 10859 - Add system preference AllowMultipleIssuesOnABiblio)\n";
8256     SetVersion($DBversion);
8257 }
8258
8259 $DBversion = "3.15.00.037";
8260 if(CheckVersion($DBversion)) {
8261     $dbh->do(q{
8262         ALTER TABLE itemtypes ADD sip_media_type VARCHAR( 3 ) DEFAULT NULL AFTER checkinmsgtype
8263     });
8264     $dbh->do(q{
8265         INSERT INTO authorised_values (category, authorised_value, lib) VALUES
8266          ('SIP_MEDIA_TYPE', '000', 'Other'),
8267          ('SIP_MEDIA_TYPE', '001', 'Book'),
8268          ('SIP_MEDIA_TYPE', '002', 'Magazine'),
8269          ('SIP_MEDIA_TYPE', '003', 'Bound journal'),
8270          ('SIP_MEDIA_TYPE', '004', 'Audio tape'),
8271          ('SIP_MEDIA_TYPE', '005', 'Video tape'),
8272          ('SIP_MEDIA_TYPE', '006', 'CD/CDROM'),
8273          ('SIP_MEDIA_TYPE', '007', 'Diskette'),
8274          ('SIP_MEDIA_TYPE', '008', 'Book with diskette'),
8275          ('SIP_MEDIA_TYPE', '009', 'Book with CD'),
8276          ('SIP_MEDIA_TYPE', '010', 'Book with audio tape')
8277     });
8278     print "Upgrade to $DBversion done (Bug 11351 - Add support for SIP2 media type)\n";
8279     SetVersion($DBversion);
8280 }
8281
8282 $DBversion = '3.15.00.038';
8283 if ( CheckVersion($DBversion) ) {
8284     $dbh->do(q{
8285         INSERT INTO  systempreferences (
8286             variable,
8287             value,
8288             options,
8289             explanation,
8290             type
8291             )
8292         VALUES (
8293             'DisplayLibraryFacets',  'holding',  'home|holding|both',  'Defines which library facets to display.',  'Choice'
8294         );
8295     });
8296     print "Upgrade to $DBversion done (Bug 11334 - Add facet for home library)\n";
8297     SetVersion ($DBversion);
8298 }
8299
8300 $DBversion = "3.15.00.039";
8301 if ( CheckVersion($DBversion) ) {
8302
8303     $dbh->do( q{
8304         ALTER TABLE letter ADD COLUMN message_transport_type VARCHAR(20) NOT NULL DEFAULT 'email' AFTER content
8305     } );
8306
8307     $dbh->do( q{
8308         ALTER TABLE letter ADD CONSTRAINT message_transport_type_fk FOREIGN KEY (message_transport_type) REFERENCES message_transport_types(message_transport_type);
8309     } );
8310
8311     $dbh->do( q{
8312         ALTER TABLE letter DROP PRIMARY KEY, ADD PRIMARY KEY (`module`,`code`,`branchcode`, message_transport_type);
8313     } );
8314
8315     $dbh->do( q{
8316         CREATE TABLE overduerules_transport_types(
8317             id INT(11) NOT NULL AUTO_INCREMENT,
8318             branchcode varchar(10) NOT NULL DEFAULT '',
8319             categorycode VARCHAR(10) NOT NULL DEFAULT '',
8320             letternumber INT(1) NOT NULL DEFAULT 1,
8321             message_transport_type VARCHAR(20) NOT NULL DEFAULT 'email',
8322             PRIMARY KEY (id),
8323             CONSTRAINT overduerules_fk FOREIGN KEY (branchcode, categorycode) REFERENCES overduerules (branchcode, categorycode) ON DELETE CASCADE ON UPDATE CASCADE,
8324             CONSTRAINT mtt_fk FOREIGN KEY (message_transport_type) REFERENCES message_transport_types (message_transport_type) ON DELETE CASCADE ON UPDATE CASCADE
8325         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
8326     } );
8327
8328     my $sth = $dbh->prepare( q{
8329         SELECT * FROM overduerules;
8330     } );
8331
8332     $sth->execute;
8333     my $sth_insert_mtt = $dbh->prepare( q{
8334         INSERT INTO overduerules_transport_types (branchcode, categorycode, letternumber, message_transport_type) VALUES ( ?, ?, ?, ? )
8335     } );
8336     while ( my $row = $sth->fetchrow_hashref ) {
8337         my $branchcode = $row->{branchcode};
8338         my $categorycode = $row->{categorycode};
8339         for my $letternumber ( 1 .. 3 ) {
8340             next unless $row->{"letter$letternumber"};
8341             $sth_insert_mtt->execute(
8342                 $branchcode, $categorycode, $letternumber, 'email'
8343             );
8344         }
8345     }
8346
8347     print "Upgrade done (Bug 9016: Adds multi transport types management for notices)\n";
8348     SetVersion($DBversion);
8349 }
8350
8351 $DBversion = "3.15.00.040";
8352 if ( CheckVersion($DBversion) ) {
8353     $dbh->do(q|
8354         UPDATE message_transports SET letter_code='HOLD' WHERE letter_code='HOLD_PHONE' OR letter_code='HOLD_PRINT'
8355     |);
8356     $dbh->do(q|
8357         UPDATE letter SET code='HOLD', message_transport_type='print' WHERE code='HOLD_PRINT'
8358     |);
8359     $dbh->do(q|
8360         UPDATE letter SET code='HOLD', message_transport_type='phone' WHERE code='HOLD_PHONE'
8361     |);
8362     print "Upgrade to $DBversion done (Bug 10845: Multi transport types for holds)\n";
8363     SetVersion($DBversion);
8364 }
8365
8366 $DBversion = "3.15.00.041";
8367 if ( CheckVersion($DBversion) ) {
8368     my ( $name ) = $dbh->selectrow_array(q|
8369         SELECT name FROM letter WHERE code="HOLD"
8370     |);
8371     $dbh->do(q|
8372         UPDATE letter
8373         SET code="HOLD",
8374             message_transport_type="phone",
8375             name= ?
8376         WHERE code="HOLD_PHONE"
8377     |, {}, $name);
8378
8379     ( $name ) = $dbh->selectrow_array(q|
8380         SELECT name FROM letter WHERE code="PREDUE"
8381     |);
8382     $dbh->do(q|
8383         UPDATE letter
8384         SET code="PREDUE",
8385             message_transport_type="phone",
8386             name= ?
8387         WHERE code="PREDUE_PHONE"
8388     |, {}, $name);
8389
8390     ( $name ) = $dbh->selectrow_array(q|
8391         SELECT name FROM letter WHERE code="OVERDUE"
8392     |);
8393     $dbh->do(q|
8394         UPDATE letter
8395         SET code="OVERDUE",
8396             message_transport_type="phone",
8397             name= ?
8398         WHERE code="OVERDUE_PHONE"
8399     |, {}, $name);
8400
8401     print "Upgrade to $DBversion done (Bug 11867: Update letters *_PHONE)\n";
8402     SetVersion($DBversion);
8403 }
8404
8405 $DBversion = "3.15.00.042";
8406 if ( CheckVersion($DBversion) ) {
8407     $dbh->do(q{
8408         INSERT INTO systempreferences
8409             (variable,value,explanation,options,type)
8410         VALUES
8411             ('SpecifyReturnDate',0,'Define whether to display \"Specify Return Date\" form in Circulation','','YesNo')
8412     });
8413     print "Upgrade to $DBversion done (Bug 10694 - Allow arbitrary backdating of returns)\n";
8414     SetVersion($DBversion);
8415 }
8416
8417 $DBversion = "3.15.00.043";
8418 if ( CheckVersion($DBversion) ) {
8419     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('MarcFieldsToOrder','','Set the mapping values for a new order line created from a MARC record in a staged file. In a YAML format.', NULL, 'textarea')");
8420    print "Upgrade to $DBversion done (Bug 7180: Added MarcFieldsToOrder syspref)\n";
8421    SetVersion ($DBversion);
8422 }
8423
8424 $DBversion = "3.15.00.044";
8425 if ( CheckVersion($DBversion) ) {
8426     $dbh->do("ALTER TABLE currency ADD isocode VARCHAR(5) default NULL AFTER symbol;");
8427     print "Upgrade to $DBversion done (Added isocode to the currency table)\n";
8428     SetVersion($DBversion);
8429 }
8430
8431 $DBversion = "3.15.00.045";
8432 if ( CheckVersion($DBversion) ) {
8433     $dbh->do("
8434         INSERT INTO systempreferences (variable,value,explanation,options,type)
8435         VALUES (
8436             'BlockExpiredPatronOpacActions',
8437             '0',
8438             'Set whether an expired patron can perform opac actions such as placing holds or renew books, can be overridden on a per patron-type basis',
8439             NULL,
8440             'YesNo'
8441         )
8442     ");
8443     $dbh->do("ALTER TABLE `categories` ADD COLUMN `BlockExpiredPatronOpacActions` TINYINT(1) DEFAULT -1 NOT NULL AFTER category_type");
8444     print "Upgraded to $DBversion done (Bug 6739 - expired patrons not blocked from opac actions)\n";
8445     SetVersion ($DBversion);
8446 }
8447
8448 $DBversion = "3.15.00.046";
8449 if ( CheckVersion($DBversion) ) {
8450     $dbh->do(q|
8451         ALTER TABLE search_history ADD COLUMN type VARCHAR(16) NOT NULL DEFAULT 'biblio' AFTER query_cgi
8452     |);
8453     print "Upgrade to $DBversion done (Bug 10807 - Add db field search_history.type)\n";
8454     SetVersion($DBversion);
8455 }
8456
8457 $DBversion = "3.15.00.047";
8458 if ( CheckVersion($DBversion) ) {
8459     $dbh->do(q|
8460         INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('EnableSearchHistory','0','','Enable or disable search history','YesNo')
8461     |);
8462     print "Upgrade to $DBversion done (Bug 10862: Add EnableSearchHistory syspref)\n";
8463     SetVersion($DBversion);
8464 }
8465
8466 $DBversion = "3.15.00.048";
8467 if ( CheckVersion($DBversion) ) {
8468     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OpacSuppressionRedirect','1','Redirect the opac detail page for suppressed records to an explanatory page (otherwise redirect to 404 error page)','','YesNo')");
8469     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OpacSuppressionMessage', '','Display this message on the redirect page for suppressed biblios','70|10','Textarea')");
8470     print "Upgrade to $DBversion done (Bug 10195: Records hidden with OpacSuppression can still be accessed)\n";
8471     SetVersion($DBversion);
8472 }
8473
8474 $DBversion = "3.15.00.049";
8475 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
8476     $dbh->do("ALTER TABLE biblioitems DROP INDEX isbn");
8477     $dbh->do("ALTER TABLE biblioitems DROP INDEX issn");
8478     $dbh->do("ALTER TABLE biblioitems DROP INDEX issn_idx");
8479     $dbh->do("ALTER TABLE biblioitems
8480               CHANGE isbn isbn MEDIUMTEXT NULL DEFAULT NULL,
8481               CHANGE issn issn MEDIUMTEXT NULL DEFAULT NULL
8482     ");
8483     $dbh->do("ALTER TABLE biblioitems
8484               ADD INDEX isbn ( isbn ( 255 ) ),
8485               ADD INDEX issn ( issn ( 255 ) )
8486     ");
8487
8488     $dbh->do("ALTER TABLE deletedbiblioitems DROP INDEX isbn");
8489     $dbh->do("ALTER TABLE deletedbiblioitems
8490               CHANGE isbn isbn MEDIUMTEXT NULL DEFAULT NULL,
8491               CHANGE issn issn MEDIUMTEXT NULL DEFAULT NULL
8492     ");
8493     $dbh->do("ALTER TABLE deletedbiblioitems
8494               ADD INDEX isbn ( isbn ( 255 ) )
8495     ");
8496
8497     print "Upgrade to $DBversion done (Bug 5377 - Biblioitems isbn and issn fields too small for multiple ISBN and ISSN)\n";
8498     SetVersion($DBversion);
8499 }
8500
8501 $DBversion = "3.15.00.050";
8502 if ( CheckVersion($DBversion) ) {
8503     $dbh->do("
8504         INSERT INTO systempreferences (
8505             variable,
8506             value,
8507             explanation,
8508             type
8509         ) VALUES (
8510             'AggressiveMatchOnISBN',
8511             '0',
8512             'If enabled, attempt to match aggressively by trying all variations of the ISBNs in the imported record as a phrase in the ISBN fields of already cataloged records when matching on ISBN with the record import tool',
8513             'YesNo'
8514         )
8515     ");
8516
8517     print "Upgrade to $DBversion done (Bug 10500 - Improve isbn matching when importing records)\n";
8518     SetVersion($DBversion);
8519 }
8520
8521 $DBversion = "3.15.00.051";
8522 if ( CheckVersion($DBversion) ) {
8523     print "Upgrade to $DBversion done (Koha 3.16 beta)\n";
8524     SetVersion($DBversion);
8525 }
8526
8527 $DBversion = "3.15.00.052";
8528 if ( CheckVersion($DBversion) ) {
8529     print "Upgrade to $DBversion done (Koha 3.16 RC)\n";
8530     SetVersion($DBversion);
8531 }
8532
8533 $DBversion = "3.16.00.000";
8534 if ( CheckVersion($DBversion) ) {
8535     print "Upgrade to $DBversion done (3.16.0 release)\n";
8536     SetVersion ($DBversion);
8537 }
8538
8539 $DBversion = '3.17.00.000';
8540 if ( CheckVersion($DBversion) ) {
8541     print "Upgrade to $DBversion done (there is no time to rest on our laurels)\n";
8542     SetVersion ($DBversion);
8543 }
8544
8545 $DBversion = '3.17.00.001';
8546 if ( CheckVersion($DBversion) ) {
8547    $dbh->do("UPDATE systempreferences SET variable = 'AuthoritySeparator' WHERE variable = 'authoritysep'");
8548    print "Upgrade to $DBversion done (Bug 10330 - Rename system preference authoritysep to AuthoritySeparator)\n";
8549    SetVersion ($DBversion);
8550 }
8551
8552 $DBversion = "3.17.00.002";
8553 if (CheckVersion($DBversion)) {
8554     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,type) VALUES('AcqEnableFiles','0','If enabled, allows librarians to upload and attach arbitrary files to invoice records.','YesNo')");
8555     $dbh->do("
8556 CREATE TABLE IF NOT EXISTS `misc_files` (
8557   `file_id` int(11) NOT NULL AUTO_INCREMENT,
8558   `table_tag` varchar(255) NOT NULL,
8559   `record_id` int(11) NOT NULL,
8560   `file_name` varchar(255) NOT NULL,
8561   `file_type` varchar(255) NOT NULL,
8562   `file_description` varchar(255) DEFAULT NULL,
8563   `file_content` longblob NOT NULL, -- file content
8564   `date_uploaded` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
8565   PRIMARY KEY (`file_id`),
8566   KEY `table_tag` (`table_tag`),
8567   KEY `record_id` (`record_id`)
8568 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
8569     ");
8570     print "Upgrade to $DBversion done (Bug 3050 - Add an option to upload scanned invoices)\n";
8571     SetVersion($DBversion);
8572 }
8573
8574 $DBversion = "3.17.00.003";
8575 if (CheckVersion($DBversion)) {
8576     $dbh->do("UPDATE systempreferences SET type = 'Choice', options = '0|1|force' WHERE variable = 'OPACItemHolds'");
8577     print "Upgrade to $DBversion done (Bug 7825 - Changed OPACItemHolds syspref to Choice)\n";
8578     SetVersion($DBversion);
8579 }
8580
8581 $DBversion = "3.17.00.004";
8582 if (CheckVersion($DBversion)) {
8583     $dbh->do("ALTER TABLE categories ADD default_privacy ENUM( 'default', 'never', 'forever' ) NOT NULL DEFAULT 'default' AFTER category_type");
8584     print "Upgrade to $DBversion done (Bug 6254 - can't set patron privacy by default)\n";
8585     SetVersion($DBversion);
8586 }
8587
8588 $DBversion = "3.17.00.005";
8589 if (CheckVersion($DBversion)) {
8590     $dbh->do(q|
8591         ALTER TABLE issuingrules
8592         ADD maxsuspensiondays INT(11) DEFAULT NULL AFTER finedays;
8593     |);
8594     print "Upgrade to $DBversion done (Bug 12230: Add new issuing rule maxsuspensiondays)\n";
8595     SetVersion($DBversion);
8596 }
8597
8598 $DBversion = "3.17.00.006";
8599 if ( CheckVersion($DBversion) ) {
8600     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('OpacLocationBranchToDisplay',  'holding',  'holding|home|both',  'In the OPAC, under location show which branch for Location in the record details.',  'Choice')");
8601     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('OpacLocationBranchToDisplayShelving',  'holding',  'holding|home|both',  'In the OPAC, display the shelving location under which which column',  'Choice')");
8602     print "Upgrade to $DBversion done (Bug 7720 - Ambiguity in OPAC Details location.)\n";
8603     SetVersion($DBversion);
8604 }
8605
8606 $DBversion = "3.17.00.007";
8607 if (CheckVersion($DBversion)) {
8608     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('UpdateNotForLoanStatusOnCheckin', '', 'NULL', 'This is a list of value pairs. When an item is checked in, if the not for loan value on the left matches the items not for loan value it will be updated to the right-hand value. E.g. ''-1: 0'' will cause an item that was set to ''Ordered'' to now be available for loan. Each pair of values should be on a separate line.', 'Free');");
8609     print "Upgrade to $DBversion done (Bug 11629 - Add ability to update not for loan status on checkin)\n";
8610     SetVersion($DBversion);
8611 }
8612
8613 $DBversion = "3.17.00.008";
8614 if ( CheckVersion($DBversion) ) {
8615     $dbh->do(q|
8616         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('OPACAcquisitionDetails','0', '','Show the acquisition details at the OPAC','YesNo')
8617     |);
8618     print "Upgrade to $DBversion done (Bug 11169 - Add OPACAcquisitionDetails syspref)\n";
8619     SetVersion($DBversion);
8620 }
8621
8622 $DBversion = "3.17.00.009";
8623 if ( CheckVersion($DBversion) ) {
8624     $dbh->do(q{
8625         DELETE FROM systempreferences WHERE variable = 'UseTablesortForCirc'
8626     });
8627
8628     print "Upgrade to $DBversion done (Bug 11703 - Remove UseTablesortForCirc syspref)\n";
8629     SetVersion($DBversion);
8630 }
8631
8632 $DBversion = "3.17.00.010";
8633 if ( CheckVersion($DBversion) ) {
8634     $dbh->do("DELETE FROM systempreferences WHERE variable='opacsmallimage'");
8635     print "Upgrade to $DBversion done (Bug 11347 - PROG/CCSR deprecation: Remove opacsmallimage system preference)\n";
8636     SetVersion($DBversion);
8637 }
8638
8639 $DBversion = "3.17.00.011";
8640 if ( CheckVersion($DBversion) ) {
8641     $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'hr', 'language', 'Croatian','2014-07-24' )");
8642     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'hr','hrv')");
8643     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'hr', 'Hrvatski')");
8644     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'en', 'Croatian')");
8645     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'fr', 'Croate')");
8646     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'de', 'Kroatisch')");
8647     print "Upgrade to $DBversion done (Bug 12649: Add Croatian language)\n";
8648     SetVersion ($DBversion);
8649 }
8650
8651 $DBversion = "3.17.00.012";
8652 if ( CheckVersion($DBversion) ) {
8653     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacShowFiltersPulldownMobile'");
8654     print "Upgrade to $DBversion done ( Bug 12512 - PROG/CCSR deprecation: Remove OpacShowFiltersPulldownMobile system preference )\n";
8655     SetVersion ($DBversion);
8656 }
8657
8658 $DBversion = "3.17.00.013";
8659 if ( CheckVersion($DBversion) ) {
8660     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('maxreserves',50,'System-wide maximum number of holds a patron can place','','Integer')");
8661     print "Upgrade to $DBversion done (Re-add system preference maxreserves)\n";
8662     SetVersion ($DBversion);
8663 }
8664
8665 $DBversion = '3.17.00.014';
8666 if ( CheckVersion($DBversion) ) {
8667     $dbh->do("
8668         INSERT INTO systempreferences (variable,value,explanation,type) VALUES
8669         ('OverdueNoticeCalendar',0,'Take calendar into consideration when working out sending overdue notices','YesNo')
8670     ");
8671     print "Upgrade to $DBversion done (Bug 12529 - Adding a syspref to allow the overdue notices to consider the calendar when generating notices)\n";
8672     SetVersion($DBversion);
8673 }
8674
8675 $DBversion = "3.17.00.015";
8676 if ( CheckVersion($DBversion) ) {
8677     $dbh->do(q{
8678         CREATE TABLE IF NOT EXISTS columns_settings (
8679             module varchar(255) NOT NULL,
8680             page varchar(255) NOT NULL,
8681             tablename varchar(255) NOT NULL,
8682             columnname varchar(255) NOT NULL,
8683             cannot_be_toggled int(1) NOT NULL DEFAULT 0,
8684             is_hidden int(1) NOT NULL DEFAULT 0,
8685             PRIMARY KEY(module, page, tablename, columnname)
8686         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
8687     });
8688     print "Upgrade to $DBversion done (Bug 10212 - Create new table columns_settings)\n";
8689     SetVersion ($DBversion);
8690 }
8691
8692 $DBversion = "3.17.00.016";
8693 if ( CheckVersion($DBversion) ) {
8694     $dbh->do("CREATE TABLE aqcontacts (
8695         id int(11) NOT NULL auto_increment,
8696         name varchar(100) default NULL,
8697         position varchar(100) default NULL,
8698         phone varchar(100) default NULL,
8699         altphone varchar(100) default NULL,
8700         fax varchar(100) default NULL,
8701         email varchar(100) default NULL,
8702         notes mediumtext,
8703         claimacquisition BOOLEAN NOT NULL DEFAULT 0,
8704         claimissues BOOLEAN NOT NULL DEFAULT 0,
8705         acqprimary BOOLEAN NOT NULL DEFAULT 0,
8706         serialsprimary BOOLEAN NOT NULL DEFAULT 0,
8707         booksellerid int(11) not NULL,
8708         PRIMARY KEY  (id),
8709         CONSTRAINT booksellerid_aqcontacts_fk FOREIGN KEY (booksellerid)
8710             REFERENCES aqbooksellers (id) ON DELETE CASCADE ON UPDATE CASCADE
8711         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;");
8712     $dbh->do("INSERT INTO aqcontacts (name, position, phone, altphone, fax,
8713             email, notes, booksellerid, claimacquisition, claimissues, acqprimary, serialsprimary)
8714         SELECT contact, contpos, contphone, contaltphone, contfax, contemail,
8715             contnotes, id, 1, 1, 1, 1 FROM aqbooksellers;");
8716     $dbh->do("ALTER TABLE aqbooksellers DROP COLUMN contact,
8717         DROP COLUMN contpos, DROP COLUMN contphone,
8718         DROP COLUMN contaltphone, DROP COLUMN contfax,
8719         DROP COLUMN contemail, DROP COLUMN contnotes;");
8720     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contact>>', '<<aqcontacts.name>>')");
8721     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contpos>>', '<<aqcontacts.position>>')");
8722     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contphone>>', '<<aqcontacts.phone>>')");
8723     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contaltphone>>', '<<aqcontacts.altphone>>')");
8724     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contfax>>', '<<aqcontacts.contfax>>')");
8725     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contemail>>', '<<aqcontacts.contemail>>')");
8726     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contnotes>>', '<<aqcontacts.contnotes>>')");
8727     print "Upgrade to $DBversion done (Bug 10402: Move bookseller contacts to separate table)\n";
8728     SetVersion($DBversion);
8729 }
8730
8731 $DBversion = "3.17.00.017";
8732 if ( CheckVersion($DBversion) ) {
8733     # Correct invalid recordtypes (should be very exceptional)
8734     $dbh->do(q{
8735         UPDATE z3950servers set recordtype='biblio' WHERE recordtype NOT IN ('authority','biblio')
8736     });
8737     # Correct invalid server types (should also be very exceptional)
8738     $dbh->do(q{
8739         UPDATE z3950servers set type='zed' WHERE type <> 'zed'
8740     });
8741     # Adjust table
8742     $dbh->do(q{
8743         ALTER TABLE z3950servers
8744         DROP COLUMN icon,
8745         DROP COLUMN description,
8746         DROP COLUMN position,
8747         MODIFY COLUMN id int NOT NULL AUTO_INCREMENT FIRST,
8748         MODIFY COLUMN recordtype enum('authority','biblio') NOT NULL DEFAULT 'biblio',
8749         CHANGE COLUMN name servername mediumtext NOT NULL,
8750         CHANGE COLUMN type servertype enum('zed','sru') NOT NULL DEFAULT 'zed',
8751         ADD COLUMN sru_options varchar(255) default NULL,
8752         ADD COLUMN sru_fields mediumtext default NULL,
8753         ADD COLUMN add_xslt mediumtext default NULL
8754     });
8755     print "Upgrade to $DBversion done (Bug 6536: Z3950 improvements)\n";
8756     SetVersion ($DBversion);
8757 }
8758
8759 $DBversion = "3.17.00.018";
8760 if ( CheckVersion($DBversion) ) {
8761     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('HoldsInNoissuesCharge', '0', 'Hold charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
8762     print "Upgrade to $DBversion done (Bug 12205: Add HoldsInNoissuesCharge systempreference)\n";
8763     SetVersion($DBversion);
8764 }
8765
8766 $DBversion = "3.17.00.019";
8767 if ( CheckVersion($DBversion) ) {
8768     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('NotHighlightedWords','and|or|not',NULL,'List of words to NOT highlight when OpacHighlightedWords is enabled','free')"
8769     );
8770     print "Upgrade to $DBversion done (Bug 6149: Operator highlighted in search results)\n";
8771     SetVersion($DBversion);
8772 }
8773
8774 $DBversion = "3.17.00.020";
8775 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
8776     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('ExpireReservesOnHolidays', '1', NULL, 'If false, reserves at a library will not be canceled on days the library is not open.', 'YesNo')");
8777     print "Upgrade to $DBversion done (Bug 8735 - Expire holds waiting only on days the library is open)\n";
8778     SetVersion ($DBversion);
8779 }
8780
8781 $DBversion = "3.17.00.021";
8782 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
8783     my $pref = C4::Context->preference('HomeOrHoldingBranch');
8784     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
8785        VALUES ('StaffSearchResultsDisplayBranch', ?,'homebranch|holdingbranch','Controls the display of the home or holding branch for staff search results','choice')", undef, $pref);
8786     print "Upgrade to $DBversion done (Bug 12582 - Control of branch displayed in search results linked to HomeOrHoldingBranch)\n";
8787     SetVersion ($DBversion);
8788 }
8789
8790 $DBversion = '3.17.00.022';
8791 if ( CheckVersion($DBversion) ) {
8792     my @temp= $dbh->selectrow_array(qq|
8793         SELECT count(*)
8794         FROM marc_subfield_structure
8795         WHERE kohafield='permanent_location' OR kohafield='items.permanent_location'
8796     |);
8797     print "Upgrade to $DBversion done (Bug 7817: Check for permanent_location)\n";
8798     if( $temp[0] ) {
8799         print "WARNING for Koha administrator: Your database contains one or more mappings for permanent_location to the MARC structure. This item field however is for internal use and should not be linked to a MARC (sub)field. Please correct it. See also Bugzilla reports 7817 and 12818.\n";
8800     }
8801     SetVersion($DBversion);
8802 }
8803
8804 $DBversion = "3.17.00.023";
8805 if ( CheckVersion($DBversion) ) {
8806     $dbh->do(q{
8807         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('AcqItemSetSubfieldsWhenReceiptIsCancelled','', '','Upon cancelling a receipt, update the items subfields if they were created when placing an order (e.g. o=5|a="bar foo")', 'Free')
8808     });
8809     print "Upgrade to $DBversion done (Bug 11169 - Add AcqItemSetSubfieldsWhenReceiptIsCancelled syspref)\n";
8810     SetVersion($DBversion);
8811 }
8812
8813 $DBversion = "3.17.00.024";
8814 if(CheckVersion($DBversion)) {
8815     $dbh->do(q{
8816         ALTER TABLE issues ADD auto_renew BOOLEAN default FALSE AFTER renewals
8817     });
8818     $dbh->do(q{
8819         ALTER TABLE old_issues ADD auto_renew BOOLEAN default FALSE AFTER renewals
8820     });
8821     $dbh->do(q{
8822         ALTER TABLE issuingrules ADD auto_renew BOOLEAN default FALSE AFTER norenewalbefore
8823     });
8824     print "Upgrade to $DBversion done (Bug 11577: [ENH] Automatic renewal feature)\n";
8825     SetVersion($DBversion);
8826 }
8827
8828 $DBversion = '3.17.00.025';
8829 if ( CheckVersion($DBversion) ) {
8830     $dbh->do(qq{
8831         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('StatisticsFields','location|itype|ccode','Define fields (from the items table) used for statistics members',NULL,'Free')
8832     });
8833     print "Upgrade to $DBversion done (Bug 12728: Checked syspref StatisticsFields)\n";
8834 }
8835
8836 $DBversion = "3.17.00.026";
8837 if ( CheckVersion($DBversion) ) {
8838     if ( C4::Context->preference('marcflavour') eq 'MARC21' ) {
8839         $dbh->do("UPDATE marc_subfield_structure SET liblibrarian = 'Encoded bitrate', libopac = 'Encoded bitrate' WHERE tagfield = '347' AND tagsubfield = 'f'");
8840         $dbh->do("UPDATE marc_subfield_structure SET repeatable = 1 WHERE tagfield IN ('110','111','610','611','710','711','810','811') AND tagsubfield = 'c'");
8841         $dbh->do("UPDATE auth_subfield_structure SET repeatable = 1 WHERE tagfield IN ('110','111','410','411','510','511','710','711') AND tagsubfield = 'c'");
8842         print "Upgrade to $DBversion done (Bug 12435 - Update MARC21 frameworks to Update No. 18 (April 2014))\n";
8843     }
8844     SetVersion($DBversion);
8845 }
8846
8847 $DBversion = "3.17.00.027";
8848 if ( CheckVersion($DBversion) ) {
8849     $dbh->do(q{
8850         DELETE FROM systempreferences WHERE variable = 'SearchEngine'
8851     });
8852     print "Upgrade to $DBversion done (Bug 12538 - Remove SearchEngine syspref)\n";
8853     SetVersion($DBversion);
8854 }
8855
8856 $DBversion = "3.17.00.028";
8857 if ( CheckVersion($DBversion) ) {
8858     $dbh->do(q{
8859         INSERT INTO systempreferences (variable,value) VALUES('OpacCustomSearch','');
8860     });
8861     print "Upgrade to $DBversion done (Bug 12296 - search box replaceable with a system preference)\n";
8862     SetVersion($DBversion);
8863 }
8864
8865 $DBversion = "3.17.00.029";
8866 if ( CheckVersion($DBversion) ) {
8867     $dbh->do("ALTER TABLE  `items` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8868     $dbh->do("ALTER TABLE  `deleteditems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8869     $dbh->do("ALTER TABLE  `biblioitems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8870     $dbh->do("ALTER TABLE  `deletedbiblioitems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8871     print "Upgrade to $DBversion done (Bug 12424 - ddc sorting of call numbers truncates long Cutter parts)\n";
8872     SetVersion ($DBversion);
8873 }
8874
8875 $DBversion = "3.17.00.030";
8876 if ( CheckVersion($DBversion) ) {
8877     $dbh->do(
8878         q{
8879        INSERT INTO systempreferences (variable, value, options, explanation, type )
8880        VALUES
8881         ('UsageStatsCountry', '', NULL, 'The country where your library is located, to be shown on the Hea Koha community website', 'YesNo'),
8882         ('UsageStatsID', '', NULL, 'This preference is part of Koha but it should not be deleted or updated manually.',  'Free'),
8883         ('UsageStatsLastUpdateTime', '', NULL, 'This preference is part of Koha but it should not be deleted or updated manually.', 'Free'),
8884         ('UsageStatsLibraryName', '', NULL, 'The library name to be shown on Hea Koha community website', 'Free'),
8885         ('UsageStatsLibraryType', 'public', 'public|university', 'The library type to be shown on the Hea Koha community website', 'Choice'),
8886         ('UsageStatsLibraryUrl', '', NULL, 'The library URL to be shown on Hea Koha community website', 'Free'),
8887         ('UsageStats', 0, NULL, 'Share anonymous usage data on the Hea Koha community website.', 'YesNo')
8888     });
8889     print "Upgrade to $DBversion done (Bug 11926: Add UsageStats systempreferences (HEA))\n";
8890     SetVersion ($DBversion);
8891 }
8892
8893 $DBversion = "3.17.00.031";
8894 if ( CheckVersion($DBversion) ) {
8895    $dbh->do("ALTER TABLE saved_sql CHANGE report_name report_name VARCHAR( 255 ) NOT NULL DEFAULT '' ");
8896    print "Upgrade to $DBversion done (Bug 2969: Report Name should be mandatory for saved reports)\n";
8897    SetVersion ($DBversion);
8898 }
8899
8900 $DBversion = "3.17.00.032";
8901 if ( CheckVersion($DBversion) ) {
8902     $dbh->do(
8903 "INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('ReplytoDefault',  '',  NULL,  'The default email address to be set as replyto.',  'Free')"
8904     );
8905     $dbh->do(
8906 "INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('ReturnpathDefault',  '',  NULL,  'The default email address to be set as return-path',  'Free')"
8907     );
8908     $dbh->do("ALTER TABLE branches ADD branchreplyto mediumtext AFTER branchemail");
8909     $dbh->do("ALTER TABLE branches ADD branchreturnpath mediumtext AFTER branchreplyto");
8910     print "Upgrade to $DBversion done (Bug 9530: Adding replyto and returnpath addresses.)\n";
8911     SetVersion($DBversion);
8912 }
8913
8914 $DBversion = "3.17.00.033";
8915 if ( CheckVersion($DBversion) ) {
8916     $dbh->do(q{
8917         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
8918         VALUES('FacetMaxCount', '20','Specify the max facet count for each category',NULL,'Integer')
8919     });
8920     print "Upgrade to $DBversion done (Bug 13088 - Allow the user to specify a max amount of facets to show)\n";
8921     SetVersion($DBversion);
8922 }
8923
8924 $DBversion = "3.17.00.034";
8925 if ( CheckVersion($DBversion) ) {
8926     $dbh->do(q|
8927         ALTER TABLE aqorders DROP COLUMN cancelledby;
8928     |);
8929
8930     print "Upgrade to $DBversion done (Bug 11007 - DROP column aqorders.cancelledby)\n";
8931     SetVersion($DBversion);
8932 }
8933
8934 $DBversion = "3.17.00.035";
8935 if ( CheckVersion($DBversion) ) {
8936     $dbh->do(q|
8937         ALTER TABLE serial ADD COLUMN claims_count INT(11) DEFAULT 0 after claimdate
8938     |);
8939     $dbh->do(q|
8940         UPDATE serial
8941         SET claims_count = 1
8942         WHERE claimdate IS NOT NULL
8943     |);
8944     print "Upgrade to $DBversion done (Bug 5342: Add claims_count field in serial table)\n";
8945     SetVersion($DBversion);
8946 }
8947
8948 $DBversion = "3.17.00.036";
8949 if ( CheckVersion($DBversion) ) {
8950     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacShowLibrariesPulldownMobile'");
8951     print "Upgrade to $DBversion done ( Bug 12513 - PROG/CCSR deprecation: Remove OpacShowLibrariesPulldownMobile system preference )\n";
8952     SetVersion ($DBversion);
8953 }
8954
8955 $DBversion = "3.17.00.037";
8956 if ( CheckVersion($DBversion) ) {
8957     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacMainUserBlockMobile'");
8958     print "Upgrade to $DBversion done ( Bug 12246 - PROG/CCSR deprecation: Remove OpacMainUserBlockMobile system preference )\n";
8959     SetVersion ($DBversion);
8960 }
8961
8962 $DBversion = "3.17.00.038";
8963 if ( CheckVersion($DBversion) ) {
8964     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACMobileUserCSS'");
8965     print "Upgrade to $DBversion done ( Bug 12245 - PROG/CCSR deprecation: Remove OPACMobileUserCSS system preference )\n";
8966     SetVersion ($DBversion);
8967 }
8968
8969 $DBversion = "3.17.00.039";
8970 if ( CheckVersion($DBversion) ) {
8971     $dbh->do("INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES
8972     ('OPACFallback', 'prog', 'bootstrap|prog', 'Define the fallback theme for the OPAC interface.', 'Themes')");
8973     print "Upgrade to $DBversion done (Bug 12539 - PROG/CCSR deprecation: Remove hardcoded theme from C4/Templates.pm)\n";
8974     SetVersion ($DBversion);
8975 }
8976
8977 $DBversion = "3.17.00.040";
8978 if ( CheckVersion($DBversion) ) {
8979     my $opac_theme = C4::Context->preference( 'opacthemes' );
8980     if ( !defined $opac_theme || $opac_theme eq 'prog' || $opac_theme eq 'ccsr' ) {
8981         $dbh->do("UPDATE systempreferences SET value='bootstrap' WHERE variable='opacthemes'");
8982     }
8983     print "Upgrade to $DBversion done (Bug 12223: 'prog' and 'ccsr' themes removed)\n";
8984     SetVersion($DBversion);
8985 }
8986
8987 $DBversion = "3.17.00.041";
8988 if ( CheckVersion($DBversion) ) {
8989     print "Upgrade to $DBversion done (Bug 11346: Deprecate the 'prog' and 'CCSR' themes)\n";
8990     SetVersion($DBversion);
8991 }
8992
8993 $DBversion = "3.17.00.042";
8994 if ( CheckVersion($DBversion) ) {
8995     $dbh->do("DELETE FROM systempreferences WHERE variable='yuipath'");
8996     print "Upgrade to $DBversion done (Bug 12494: Remove yuipath system preference)\n";
8997     SetVersion ($DBversion);
8998 }
8999
9000 $DBversion = "3.17.00.043";
9001 if ( CheckVersion($DBversion) ) {
9002     $dbh->do("
9003         ALTER TABLE aqorders
9004         ADD COLUMN cancellationreason TEXT DEFAULT NULL AFTER datecancellationprinted
9005     ");
9006     print "Upgrade to $DBversion done (Bug 7162: Add aqorders.cancellationreason)\n";
9007     SetVersion ($DBversion);
9008 }
9009
9010 $DBversion = "3.17.00.044";
9011 if ( CheckVersion($DBversion) ) {
9012     $dbh->do(q{
9013         INSERT IGNORE INTO systempreferences
9014             (variable,value,explanation,options,type)
9015             VALUES('OnSiteCheckouts','0','Enable/Disable the on-site checkouts feature','','YesNo');
9016     });
9017     $dbh->do(q{
9018         INSERT IGNORE INTO systempreferences
9019             (variable,value,explanation,options,type)
9020             VALUES('OnSiteCheckoutsForce','0','Enable/Disable the on-site for all cases (Even if a user is debarred, etc.)','','YesNo');
9021     });
9022     $dbh->do(q{
9023         ALTER TABLE issues ADD COLUMN onsite_checkout INT(1) NOT NULL DEFAULT 0 AFTER issuedate;
9024     });
9025     $dbh->do(q{
9026         ALTER TABLE old_issues ADD COLUMN onsite_checkout INT(1) NOT NULL DEFAULT 0 AFTER issuedate;
9027     });
9028     print "Upgrade to $DBversion done (Bug 10860: Add new system preference OnSiteCheckouts + fields [old_]issues.onsite_checkout)\n";
9029     SetVersion($DBversion);
9030 }
9031
9032 $DBversion = "3.17.00.045";
9033 if ( CheckVersion($DBversion) ) {
9034     $dbh->do(q{
9035         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
9036         ('LocalHoldsPriority',  '0', NULL,  'Enables the LocalHoldsPriority feature',  'YesNo'),
9037         ('LocalHoldsPriorityItemControl',  'holdingbranch',  'holdingbranch|homebranch',  'decides if the feature operates using the item''s home or holding library.',  'Choice'),
9038         ('LocalHoldsPriorityPatronControl',  'PickupLibrary',  'HomeLibrary|PickupLibrary',  'decides if the feature operates using the library set as the patron''s home library, or the library set as the pickup library for the given hold.',  'Choice')
9039     });
9040     print "Upgrade to $DBversion done (Bug 11126 - Make the holds system optionally give precedence to local holds)\n";
9041     SetVersion($DBversion);
9042 }
9043
9044 $DBversion = "3.17.00.046";
9045 if ( CheckVersion($DBversion) ) {
9046     $dbh->do(q{
9047         CREATE TABLE IF NOT EXISTS items_search_fields (
9048           name VARCHAR(255) NOT NULL,
9049           label VARCHAR(255) NOT NULL,
9050           tagfield CHAR(3) NOT NULL,
9051           tagsubfield CHAR(1) NULL DEFAULT NULL,
9052           authorised_values_category VARCHAR(16) NULL DEFAULT NULL,
9053           PRIMARY KEY(name),
9054           CONSTRAINT items_search_fields_authorised_values_category
9055             FOREIGN KEY (authorised_values_category) REFERENCES authorised_values (category)
9056             ON DELETE SET NULL ON UPDATE CASCADE
9057         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
9058     });
9059     print "Upgrade to $DBversion done (Bug 11425: Add items_search_fields table)\n";
9060     SetVersion($DBversion);
9061 }
9062
9063 $DBversion = "3.17.00.047";
9064 if ( CheckVersion($DBversion) ) {
9065     $dbh->do(q{
9066         ALTER TABLE collections
9067             CHANGE colBranchcode colBranchcode VARCHAR( 10 ) NULL DEFAULT NULL,
9068             ADD INDEX ( colBranchcode ),
9069             ADD CONSTRAINT collections_ibfk_1 FOREIGN KEY (colBranchcode) REFERENCES branches (branchcode) ON DELETE CASCADE ON UPDATE CASCADE
9070     });
9071     print "Upgrade to $DBversion done (Bug 8836 - Resurrect Rotating Collections)\n";
9072     SetVersion($DBversion);
9073 }
9074
9075 $DBversion = "3.17.00.048";
9076 if ( CheckVersion($DBversion) ) {
9077     $dbh->do(q|
9078         INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('RentalFeesCheckoutConfirmation', '0', NULL , 'Allow user to confirm when checking out an item with rental fees.', 'YesNo')
9079     |);
9080     print "Upgrade to $DBversion done (Bug 12448 - Add RentalFeesCheckoutConfirmation syspref)\n";
9081     SetVersion($DBversion);
9082 }
9083
9084 $DBversion = "3.17.00.049";
9085 if ( CheckVersion($DBversion) ) {
9086     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'am', 'language', 'Amharic','2014-10-29')");
9087     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'am','amh')");
9088     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'am', 'language', 'am', 'አማርኛ')");
9089     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'am', 'language', 'en', 'Amharic')");
9090
9091     $dbh->do("UPDATE language_descriptions SET description = 'لعربية' WHERE subtag = 'ar' AND type = 'language' AND lang = 'ar'");
9092
9093     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'az', 'language', 'Azerbaijani','2014-10-30')");
9094     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'az','aze')");
9095     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'az', 'language', 'az', 'Azərbaycan dili')");
9096     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'az', 'language', 'en', 'Azerbaijani')");
9097
9098     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'be', 'language', 'Byelorussian','2014-10-30')");
9099     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'be','bel')");
9100     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'be', 'language', 'be', 'Беларуская мова')");
9101     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'be', 'language', 'en', 'Byelorussian')");
9102
9103     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'bn', 'language', 'Bengali','2014-10-30')");
9104     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'bn','ben')");
9105     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'bn', 'language', 'bn', 'বাংলা')");
9106     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'bn', 'language', 'en', 'Bengali')");
9107
9108     $dbh->do("UPDATE language_descriptions SET description = 'Български' WHERE subtag = 'bg' AND type = 'language' AND lang = 'bg'");
9109     $dbh->do("UPDATE language_descriptions SET description = 'Ceština' WHERE subtag = 'cs' AND type = 'language' AND lang = 'cs'");
9110     $dbh->do("UPDATE language_descriptions SET description = 'Ελληνικά' WHERE subtag = 'el' AND type = 'language' AND lang = 'el'");
9111     $dbh->do("UPDATE language_descriptions SET description = 'Español' WHERE subtag = 'es' AND type = 'language' AND lang = 'es'");
9112
9113     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'eu', 'language', 'Basque','2014-10-30')");
9114     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'eu','eus')");
9115     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'eu', 'language', 'eu', 'Euskera')");
9116     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'eu', 'language', 'en', 'Basque')");
9117
9118     $dbh->do("UPDATE language_descriptions SET description = 'فارسى' WHERE subtag = 'fa' AND type = 'language' AND lang = 'fa'");
9119     $dbh->do("UPDATE language_descriptions SET description = 'Suomi' WHERE subtag = 'fi' AND type = 'language' AND lang = 'fi'");
9120
9121     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'fo', 'language', 'Faroese','2014-10-30')");
9122     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'fo','fao')");
9123     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'fo', 'language', 'fo', 'Føroyskt')");
9124     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'fo', 'language', 'en', 'Faroese')");
9125
9126     $dbh->do("UPDATE language_descriptions SET description = 'Français' WHERE subtag = 'fr' AND type = 'language' AND lang = 'fr'");
9127     $dbh->do("UPDATE language_descriptions SET description = 'עִבְרִית' WHERE subtag = 'he' AND type = 'language' AND lang = 'he'");
9128     $dbh->do("UPDATE language_descriptions SET description = 'हिन्दी' WHERE subtag = 'hi' AND type = 'language' AND lang = 'hi'");
9129
9130     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'is', 'language', 'Icelandic','2014-10-30')");
9131     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'is','ice')");
9132     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'is', 'language', 'is', 'Íslenska')");
9133     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'is', 'language', 'en', 'Icelandic')");
9134
9135     $dbh->do("UPDATE language_descriptions SET description = '日本語' WHERE subtag = 'ja' AND type = 'language' AND lang = 'ja'");
9136
9137     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ka', 'language', 'Kannada','2014-10-30')");
9138     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ka','kan')");
9139     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'ka', 'ಕನ್ನಡ')");
9140     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'en', 'Kannada')");
9141
9142     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'km', 'language', 'Khmer','2014-10-30')");
9143     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'km','khm')");
9144     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'km', 'language', 'km', 'ភាសាខ្មែរ')");
9145     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'km', 'language', 'en', 'Khmer')");
9146
9147     $dbh->do("UPDATE language_descriptions SET description = '한국어' WHERE subtag = 'ko' AND type = 'language' AND lang = 'ko'");
9148
9149     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ku', 'language', 'Kurdish','2014-05-13')");
9150     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ku','kur')");
9151     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'ku', 'کوردی')");
9152     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'en', 'Kurdish')");
9153     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'fr', 'Kurde')");
9154     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'de', 'Kurdisch')");
9155     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'es', 'Kurdo')");
9156
9157     $dbh->do("UPDATE language_descriptions SET description = 'ພາສາລາວ' WHERE subtag = 'lo' AND type = 'language' AND lang = 'lo'");
9158
9159     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mi', 'language', 'Maori','2014-10-30')");
9160     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mi','mri')");
9161     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mi', 'language', 'mi', 'Te Reo Māori')");
9162     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mi', 'language', 'en', 'Maori')");
9163
9164     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mn', 'language', 'Mongolian','2014-10-30')");
9165     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mn','mon')");
9166     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mn', 'language', 'mn', 'Mонгол')");
9167     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mn', 'language', 'en', 'Mongolian')");
9168
9169     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mr', 'language', 'Marathi','2014-10-30')");
9170     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mr','mar')");
9171     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mr', 'language', 'mr', 'मराठी')");
9172     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mr', 'language', 'en', 'Marathi')");
9173
9174     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ms', 'language', 'Malay','2014-10-30')");
9175     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ms','may')");
9176     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ms', 'language', 'ms', 'Bahasa melayu')");
9177     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ms', 'language', 'en', 'Malay')");
9178
9179     $dbh->do("UPDATE language_descriptions SET description = 'Norsk bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'nb'");
9180     $dbh->do("UPDATE language_descriptions SET description = 'Norwegian bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'en'");
9181     $dbh->do("UPDATE language_descriptions SET description = 'Norvégien bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'fr'");
9182     $dbh->do("UPDATE language_descriptions SET description = 'Norwegisch bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'de'");
9183
9184     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ne', 'language', 'Nepali','2014-10-30')");
9185     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ne','nep')");
9186     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)VALUES ( 'ne', 'language', 'ne', 'नेपाली')");
9187     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ne', 'language', 'en', 'Nepali')");
9188
9189     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'pbr', 'language', 'Pangwa','2014-10-30')");
9190     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'pbr','pbr')");
9191     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'pbr', 'language', 'pbr', 'Ekipangwa')");
9192     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'pbr', 'language', 'en', 'Pangwa')");
9193
9194     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'prs', 'language', 'Dari','2014-10-30')");
9195     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'prs','prs')");
9196     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'prs', 'language', 'prs', 'درى')");
9197     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'prs', 'language', 'en', 'Dari')");
9198
9199     $dbh->do("UPDATE language_descriptions SET description = 'Português' WHERE subtag = 'pt' AND type = 'language' AND lang = 'pt'");
9200     $dbh->do("UPDATE language_descriptions SET description = 'Român' WHERE subtag = 'ro' AND type = 'language' AND lang = 'ro'");
9201     $dbh->do("UPDATE language_descriptions SET description = 'Русский' WHERE subtag = 'ru' AND type = 'language' AND lang = 'ru'");
9202
9203     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'rw', 'language', 'Kinyarwanda','2014-10-30')");
9204     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'rw','kin')");
9205     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'rw', 'language', 'rw', 'Ikinyarwanda')");
9206     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'rw', 'language', 'en', 'Kinyarwanda')");
9207
9208     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sd', 'language', 'Sindhi','2014-10-30')");
9209     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sd','snd')");
9210     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sd', 'language', 'sd', 'سنڌي')");
9211     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sd', 'language', 'en', 'Sindhi')");
9212
9213     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sk', 'language', 'Slovak','2014-10-30')");
9214     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sk','slk')");
9215     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sk', 'language', 'sk', 'Slovenčina')");
9216     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sk', 'language', 'en', 'Slovak')");
9217
9218     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sl', 'language', 'Slovene','2014-10-30')");
9219     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sl','slv')");
9220     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sl', 'language', 'sl', 'Slovenščina')");
9221     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sl', 'language', 'en', 'Slovene')");
9222
9223     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sq', 'language', 'Albanian','2014-10-30')");
9224     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sq','sqi')");
9225     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sq', 'language', 'sq', 'Shqip')");
9226     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sq', 'language', 'en', 'Albanian')");
9227
9228     $dbh->do("UPDATE language_descriptions SET description = 'Cрпски' WHERE subtag = 'sr' AND type = 'language' AND lang = 'sr'");
9229
9230     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sw', 'language', 'Swahili','2014-10-30')");
9231     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sw','swa')");
9232     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sw', 'language', 'sw', 'Kiswahili')");
9233     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sw', 'language', 'en', 'Swahili')");
9234
9235     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ta', 'language', 'Tamil','2014-10-30')");
9236     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ta','tam')");
9237     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ta', 'language', 'ta', 'தமிழ்')");
9238     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ta', 'language', 'en', 'Tamil')");
9239
9240     $dbh->do("UPDATE language_descriptions SET description = 'Tetun' WHERE subtag = 'tet' AND type = 'language' AND lang = 'tet'");
9241     $dbh->do("UPDATE language_descriptions SET description = 'ภาษาไทย' WHERE subtag = 'th' AND type = 'language' AND lang = 'th'");
9242
9243     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'tl', 'language', 'Tagalog','2014-10-30')");
9244     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'tl','tgl')");
9245     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'tl', 'language', 'tl', 'Tagalog')");
9246     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'tl', 'language', 'en', 'Tagalog')");
9247
9248     $dbh->do("UPDATE language_descriptions SET description = 'Türkçe' WHERE subtag = 'tr' AND type = 'language' AND lang = 'tr'");
9249     $dbh->do("UPDATE language_descriptions SET description = 'Українська' WHERE subtag = 'uk' AND type = 'language' AND lang = 'uk'");
9250     $dbh->do("UPDATE language_descriptions SET description = 'اردو' WHERE subtag = 'ur' AND type = 'language' AND lang = 'ur'");
9251
9252     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'vi', 'language', 'Vietnamese','2014-10-30')");
9253     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'vi','vie')");
9254     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'vi', 'language', 'vi', '㗂越')");
9255     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'vi', 'language', 'en', 'Vietnamese')");
9256
9257     $dbh->do("UPDATE language_descriptions SET description = '中文' WHERE subtag = 'zh' AND type = 'language' AND lang = 'zh'");
9258     $dbh->do("UPDATE language_descriptions SET description = '' WHERE subtag = 'Arab,script' AND type = 'Arab' AND lang = 'العربية'");
9259
9260     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Armn', 'script', 'Armenian','2014-10-30')");
9261     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Armn', 'script', 'Armn', 'Հայոց այբուբեն')");
9262     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Armn', 'script', 'en', 'Armenian')");
9263
9264     $dbh->do("UPDATE language_descriptions SET description = 'Кирилица' WHERE subtag = 'Cyrl' AND type = 'script' AND lang = 'Cyrl'");
9265
9266     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Ethi', 'script', 'Ethiopic','2014-10-30')");
9267     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Ethi', 'script', 'Ethi', 'ግዕዝ')");
9268     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Ethi', 'script', 'en', 'Ethiopic')");
9269
9270     $dbh->do("UPDATE language_descriptions SET description = 'Ελληνικό αλφάβητο' WHERE subtag = 'Grek' AND type = 'script' AND lang = 'Grek'");
9271     $dbh->do("UPDATE language_descriptions SET description = '简体字' WHERE subtag = 'Hans' AND type = 'script' AND lang = 'Hans'");
9272     $dbh->do("UPDATE language_descriptions SET description = '繁體字' WHERE subtag = 'Hant' AND type = 'script' AND lang = 'Hant'");
9273     $dbh->do("UPDATE language_descriptions SET description = 'אָלֶף־בֵּית עִבְרִי' WHERE subtag = 'Hebr' AND type = 'script' AND lang = 'Hebr'");
9274
9275     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Jpan', 'script', 'Japanese','2014-10-30')");
9276     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Jpan', 'script', 'Jpan', '漢字')");
9277     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Jpan', 'script', 'en', 'Japanese')");
9278
9279     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Knda', 'script', 'Kannada','2014-10-30')");
9280     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Knda', 'script', 'Knda', 'ಕನ್ನಡ ಲಿಪಿ')");
9281     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Knda', 'script', 'en', 'Kannada')");
9282
9283     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Kore', 'script', 'Korean','2014-10-30')");
9284     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Kore', 'script', 'Kore', '한글')");
9285     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Kore', 'script', 'en', 'Korean')");
9286
9287     $dbh->do("UPDATE language_descriptions SET description = 'ອັກສອນລາວ' WHERE subtag = 'Laoo' AND type = 'script' AND lang = 'Laoo'");
9288
9289     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'AL', 'region', 'Albania','2014-10-30')");
9290     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AL', 'region', 'en', 'Albania')");
9291     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AL', 'region', 'sq', 'Shqipërisë')");
9292
9293     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'AZ', 'region', 'Azerbaijan','2014-10-30')");
9294     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AZ', 'region', 'en', 'Azerbaijan')");
9295     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AZ', 'region', 'az', 'Azərbaycan')");
9296
9297     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BE', 'region', 'Belgium','2014-10-30')");
9298     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BE', 'region', 'en', 'Belgium')");
9299     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BE', 'region', 'nl', 'België')");
9300
9301     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BR', 'region', 'Brazil','2014-10-30')");
9302     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BR', 'region', 'en', 'Brazil')");
9303     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BR', 'region', 'pt', 'Brasil')");
9304
9305     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BY', 'region', 'Belarus','2014-10-30')");
9306     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BY', 'region', 'en', 'Belarus')");
9307     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BY', 'region', 'be', 'Беларусь')");
9308
9309     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CA', 'region', 'fr', 'Canada')");
9310
9311     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CH', 'region', 'Switzerland','2014-10-30')");
9312     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CH', 'region', 'en', 'Switzerland')");
9313     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CH', 'region', 'de', 'Schweiz')");
9314
9315     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CN', 'region', 'China','2014-10-30')");
9316     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CN', 'region', 'en', 'China')");
9317     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CN', 'region', 'zh', '中国')");
9318
9319     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CZ', 'region', 'Czech Republic','2014-10-30')");
9320     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CZ', 'region', 'en', 'Czech Republic')");
9321     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CZ', 'region', 'cs', 'Česká republika')");
9322
9323     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'DE', 'region', 'Germany','2014-10-30')");
9324     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DE', 'region', 'en', 'Germany')");
9325     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DE', 'region', 'de', 'Deutschland')");
9326
9327     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DK', 'region', 'en', 'Denmark')");
9328
9329     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ES', 'region', 'Spain','2014-10-30')");
9330     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ES', 'region', 'en', 'Spain')");
9331     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ES', 'region', 'es', 'España')");
9332
9333     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'FI', 'region', 'Finland','2014-10-30')");
9334     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FI', 'region', 'en', 'Finland')");
9335     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FI', 'region', 'fi', 'Suomi')");
9336
9337     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'FO', 'region', 'Faroe Islands','2014-10-30')");
9338     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FO', 'region', 'en', 'Faroe Islands')");
9339     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FO', 'region', 'fo', 'Føroyar')");
9340
9341     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'GR', 'region', 'Greece','2014-10-30')");
9342     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'GR', 'region', 'en', 'Greece')");
9343     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'GR', 'region', 'el', 'Ελλάδα')");
9344
9345     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'HR', 'region', 'Croatia','2014-10-30')");
9346     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HR', 'region', 'en', 'Croatia')");
9347     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HR', 'region', 'hr', 'Hrvatska')");
9348
9349     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'HU', 'region', 'Hungary','2014-10-30')");
9350     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HU', 'region', 'en', 'Hungary')");
9351     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HU', 'region', 'hu', 'Magyarország')");
9352
9353     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ID', 'region', 'Indonesia','2014-10-30')");
9354     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ID', 'region', 'en', 'Indonesia')");
9355     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ID', 'region', 'id', 'Indonesia')");
9356
9357     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'IS', 'region', 'Iceland','2014-10-30')");
9358     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IS', 'region', 'en', 'Iceland')");
9359     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IS', 'region', 'is', 'Ísland')");
9360
9361     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'IT', 'region', 'Italy','2014-10-30')");
9362     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IT', 'region', 'en', 'Italy')");
9363     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IT', 'region', 'it', 'Italia')");
9364
9365     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'JP', 'region', 'Japan','2014-10-30')");
9366     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'JP', 'region', 'en', 'Japan')");
9367     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'JP', 'region', 'ja', '日本')");
9368
9369     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KE', 'region', 'Kenya','2014-10-30')");
9370     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KE', 'region', 'en', 'Kenya')");
9371     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KE', 'region', 'rw', 'Kenya')");
9372
9373     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KH', 'region', 'Cambodia','2014-10-30')");
9374     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KH', 'region', 'en', 'Cambodia')");
9375     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KH', 'region', 'km', 'កម្ពុជា')");
9376
9377     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KP', 'region', 'North Korea','2014-10-30')");
9378     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KP', 'region', 'en', 'North Korea')");
9379     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KP', 'region', 'ko', '조선민주주의인민공화국')");
9380
9381     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'LK', 'region', 'Sri Lanka','2014-10-30')");
9382     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'LK', 'region', 'en', 'Sri Lanka')");
9383     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'LK', 'region', 'ta', 'இலங்கை')");
9384
9385     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'MY', 'region', 'Malaysia','2014-10-30')");
9386     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'MY', 'region', 'en', 'Malaysia')");
9387     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'MY', 'region', 'ms', 'Malaysia')");
9388
9389     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NE', 'region', 'Niger','2014-10-30')");
9390     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NE', 'region', 'en', 'Niger')");
9391     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NE', 'region', 'ne', 'Niger')");
9392
9393     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NL', 'region', 'Netherlands','2014-10-30')");
9394     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NL', 'region', 'en', 'Netherlands')");
9395     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NL', 'region', 'nl', 'Nederland')");
9396
9397     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NO', 'region', 'Norway','2014-10-30')");
9398     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'en', 'Norway')");
9399     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'ne', 'Noreg')");
9400     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'nn', 'Noreg')");
9401
9402     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PH', 'region', 'Philippines','2014-10-30')");
9403     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PH', 'region', 'en', 'Philippines')");
9404     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PH', 'region', 'tl', 'Pilipinas')");
9405
9406     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PK', 'region', 'Pakistan','2014-10-30')");
9407     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PK', 'region', 'en', 'Pakistan')");
9408     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PK', 'region', 'sd', 'پاكستان')");
9409
9410     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PL', 'region', 'Poland','2014-10-30')");
9411     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PL', 'region', 'en', 'Poland')");
9412     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PL', 'region', 'pl', 'Polska')");
9413
9414     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PT', 'region', 'Portugal','2014-10-30')");
9415     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PT', 'region', 'en', 'Portugal')");
9416     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PT', 'region', 'pt', 'Portugal')");
9417
9418     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RO', 'region', 'Romania','2014-10-30')");
9419     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RO', 'region', 'en', 'Romania')");
9420     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RO', 'region', 'ro', 'România')");
9421
9422     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RU', 'region', 'Russia','2014-10-30')");
9423     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RU', 'region', 'en', 'Russia')");
9424     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RU', 'region', 'ru', 'Россия')");
9425
9426     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RW', 'region', 'Rwanda','2014-10-30')");
9427     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RW', 'region', 'en', 'Rwanda')");
9428     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RW', 'region', 'rw', 'Rwanda')");
9429
9430     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SE', 'region', 'Sweden','2014-10-30')");
9431     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SE', 'region', 'en', 'Sweden')");
9432     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SE', 'region', 'sv', 'Sverige')");
9433
9434     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SI', 'region', 'Slovenia','2014-10-30')");
9435     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SI', 'region', 'en', 'Slovenia')");
9436     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SI', 'region', 'sl', 'Slovenija')");
9437
9438     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SK', 'region', 'Slovakia','2014-10-30')");
9439     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SK', 'region', 'en', 'Slovakia')");
9440     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SK', 'region', 'sk', 'Slovensko')");
9441
9442     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TH', 'region', 'Thailand','2014-10-30')");
9443     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TH', 'region', 'en', 'Thailand')");
9444     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TH', 'region', 'th', 'ประเทศไทย')");
9445
9446     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TR', 'region', 'Turkey','2014-10-30')");
9447     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TR', 'region', 'en', 'Turkey')");
9448     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TR', 'region', 'tr', 'Türkiye')");
9449
9450     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TW', 'region', 'Taiwan','2014-10-30')");
9451     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TW', 'region', 'en', 'Taiwan')");
9452     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TW', 'region', 'zh', '台灣')");
9453
9454     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'UA', 'region', 'Ukraine','2014-10-30')");
9455     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'UA', 'region', 'en', 'Ukraine')");
9456     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'UA', 'region', 'uk', 'Україна')");
9457
9458     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'VN', 'region', 'Vietnam','2014-10-30')");
9459     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'VN', 'region', 'en', 'Vietnam')");
9460     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'VN', 'region', 'vi', 'Việt Nam')");
9461
9462     print "Upgrade to $DBversion done (Bug 12250: Update descriptions for languages, scripts and regions)\n";
9463     SetVersion($DBversion);
9464 }
9465
9466 $DBversion = "3.17.00.050";
9467 if ( CheckVersion($DBversion) ) {
9468     $dbh->do(q|
9469         INSERT INTO permissions (module_bit, code, description) VALUES
9470           (13, 'records_batchdel', 'Perform batch deletion of records (bibliographic or authority)')
9471     |);
9472     print "Upgrade to $DBversion done (Bug 12403: Add permission tools_records_batchdelitem)\n";
9473     SetVersion($DBversion);
9474 }
9475
9476 $DBversion = "3.17.00.051";
9477 if ( CheckVersion($DBversion) ) {
9478     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('GoogleIndicTransliteration','0','','GoogleIndicTransliteration on the OPAC.','YesNo')");
9479     print "Upgrade to $DBversion done (Bug 13211: Added system preferences GoogleIndicTransliteration on the OPAC)\n";
9480     SetVersion($DBversion);
9481 }
9482
9483 $DBversion = "3.17.00.052";
9484 if ( CheckVersion($DBversion) ) {
9485     $dbh->do(q{
9486         INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacAdvSearchOptions','pubdate|itemtype|language|sorting|location','Show search options','pubdate|itemtype|language|subtype|sorting|location','multiple');
9487     });
9488
9489     $dbh->do(q{
9490         INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacAdvSearchMoreOptions','pubdate|itemtype|language|subtype|sorting|location','Show search options for the expanded view (More options)','pubdate|itemtype|language|subtype|sorting|location','multiple');
9491    });
9492    print "Upgrade to $DBversion done (Bug 9043: Add system preference OpacAdvSearchOptions and OpacAdvSearchMoreOptions)\n";
9493    SetVersion ($DBversion);
9494 }
9495
9496 $DBversion = "3.17.00.053";
9497 if ( CheckVersion($DBversion) ) {
9498     $dbh->do(q{
9499         INSERT INTO permissions (module_bit, code, description) VALUES ('9', 'edit_items_restricted', 'Limit item modification to subfields defined in the SubfieldsToAllowForRestrictedEditing preference (please note that edit_item is still required)');
9500     });
9501
9502     $dbh->do(q{
9503         INSERT INTO permissions (module_bit, code, description) VALUES ('9', 'delete_all_items', 'Delete all items at once');
9504     });
9505
9506     $dbh->do(q{
9507         INSERT INTO permissions (module_bit, code, description) VALUES ('13', 'items_batchmod_restricted', 'Limit batch item modification to subfields defined in the SubfieldsToAllowForRestrictedBatchmod preference (please note that items_batchmod is still required)');
9508     });
9509
9510     # The delete_all_items permission should be added to users having the edit_items permission.
9511     $dbh->do(q{
9512         INSERT INTO user_permissions (borrowernumber, module_bit, code) SELECT borrowernumber, module_bit, "delete_all_items" FROM user_permissions WHERE code="edit_items";
9513     });
9514
9515     # Add 2 new prefs
9516     $dbh->do(q{
9517         INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SubfieldsToAllowForRestrictedEditing','','Define a list of subfields for which edition is authorized when edit_items_restricted permission is enabled, separated by spaces. Example: 995\$f 995\$h 995\$j','','Free');
9518     });
9519
9520     $dbh->do(q{
9521         INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SubfieldsToAllowForRestrictedBatchmod','','Define a list of subfields for which edition is authorized when items_batchmod_restricted permission is enabled, separated by spaces. Example: 995\$f 995\$h 995\$j','','Free');
9522     });
9523
9524     print "Upgrade to $DBversion done (Bug 7673: Adds 2 new prefs (SubfieldsToAllowForRestrictedEditing and SubfieldsToAllowForRestrictedBatchmod) and 3 new permissions (edit_items_restricted and delete_all_items and items_batchmod_restricted))\n";
9525     SetVersion($DBversion);
9526 }
9527
9528 $DBversion = "3.17.00.054";
9529 if (CheckVersion($DBversion)) {
9530     $dbh->do(q{
9531         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
9532         ('AllowRenewalIfOtherItemsAvailable','0',NULL,'If enabled, allow a patron to renew an item with unfilled holds if other available items can fill that hold.','YesNo')
9533     });
9534     print "Upgrade to $DBversion done (Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds)\n";
9535     SetVersion($DBversion);
9536 }
9537
9538 $DBversion = "3.17.00.055";
9539 if ( CheckVersion($DBversion) ) {
9540     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBEnable', '0', NULL, 'Enable communication with the Norwegian national patron database.', 'YesNo')");
9541     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBEndpoint', '', NULL, 'Which NL endpoint to use.', 'Free')");
9542     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBUsername', '', NULL, 'Username for communication with the Norwegian national patron database.', 'Free')");
9543     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBPassword', '', NULL, 'Password for communication with the Norwegian national patron database.', 'Free')");
9544     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBSearchNLAfterLocalHit','0',NULL,'Search NL if a search has already given one or more local hits?.','YesNo')");
9545     $dbh->do("
9546 CREATE TABLE borrower_sync (
9547     borrowersyncid int(11) NOT NULL AUTO_INCREMENT,
9548     borrowernumber int(11) NOT NULL,
9549     synctype varchar(32) NOT NULL,
9550     sync tinyint(1) NOT NULL DEFAULT '0',
9551     syncstatus varchar(10) DEFAULT NULL,
9552     lastsync varchar(50) DEFAULT NULL,
9553     hashed_pin varchar(64) DEFAULT NULL,
9554     PRIMARY KEY (borrowersyncid),
9555     KEY borrowernumber (borrowernumber),
9556     CONSTRAINT borrower_sync_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
9557 ) ENGINE=InnoDB DEFAULT CHARSET=utf8"
9558 );
9559     print "Upgrade to $DBversion done (Bug 11401 - Add support for Norwegian national library card)\n";
9560     SetVersion($DBversion);
9561 }
9562
9563 $DBversion = "3.17.00.056";
9564 if ( CheckVersion($DBversion) ) {
9565     $dbh->do(q{
9566         UPDATE systempreferences SET value = 'pubdate,itemtype,language,sorting,location' WHERE variable='OpacAdvSearchOptions'
9567     });
9568
9569     $dbh->do(q{
9570         UPDATE systempreferences SET value = 'pubdate,itemtype,language,subtype,sorting,location' WHERE variable='OpacAdvSearchMoreOptions'
9571     });
9572
9573     print "Upgrade to $DBversion done (Bug 9043 - Update the values for OpacAdvSearchOptions and OpacAdvSearchOptions)\n";
9574     SetVersion($DBversion);
9575 }
9576
9577 $DBversion = "3.17.00.057";
9578 if ( CheckVersion($DBversion) ) {
9579     print "Upgrade to $DBversion done (Koha 3.18 beta)\n";
9580     SetVersion ($DBversion);
9581 }
9582
9583 $DBversion = "3.17.00.058";
9584 if( CheckVersion($DBversion) ){
9585     $dbh->do("INSERT INTO systempreferences (variable, explanation, type) VALUES('DefaultLongOverdueChargeValue','Charge a lost item to the borrower account when the LOST value of the item changes to n',  'integer')");
9586     $dbh->do("INSERT INTO systempreferences (variable, explanation, type) VALUES('DefaultLongOverdueLostValue', 'Set the LOST value of an item to n when the item has been overdue for more than defaultlongoverduedays days.', 'integer')");
9587     $dbh->do("INSERT INTO systempreferences (variable, explanation, type) VALUES('DefaultLongOverdueDays', 'Set the LOST value of an item when the item has been overdue for more than n days.',  'integer')");
9588     print "Upgrade to $DBversion done (Bug 8337: System preferences for longoverdue cron)\n";
9589     SetVersion($DBversion);
9590 }
9591
9592 $DBversion = "3.17.00.059";
9593 if ( CheckVersion($DBversion) ) {
9594     $dbh->do(q{
9595         UPDATE permissions SET description = "Add and delete budgets (but can't modifiy budgets)" WHERE description = "Add and delete budgets (but cant modify budgets)";
9596     });
9597     print "Upgrade to $DBversion done (Bug 10749: Fix typo in budget_add_del permission description)\n";
9598     SetVersion ($DBversion);
9599 }
9600
9601 $DBversion = "3.17.00.060";
9602 if ( CheckVersion($DBversion) ) {
9603     my $count_l = $dbh->selectcol_arrayref(q|
9604         SELECT COUNT(*) FROM letter WHERE message_transport_type='feed'
9605     |);
9606     my $count_mq = $dbh->selectcol_arrayref(q|
9607         SELECT COUNT(*) FROM message_queue WHERE message_transport_type='feed'
9608     |);
9609     my $count_ott = $dbh->selectcol_arrayref(q|
9610         SELECT COUNT(*) FROM overduerules_transport_types WHERE message_transport_type='feed'
9611     |);
9612     my $count_mt = $dbh->selectcol_arrayref(q|
9613         SELECT COUNT(*) FROM message_transports WHERE message_transport_type='feed'
9614     |);
9615     my $count_bmtp = $dbh->selectcol_arrayref(q|
9616         SELECT COUNT(*) FROM borrower_message_transport_preferences WHERE message_transport_type='feed'
9617     |);
9618
9619     my $deleted = 0;
9620     if ( $count_l->[0] == 0 and $count_mq->[0] == 0 and $count_ott->[0] == 0 and $count_mt->[0] == 0 and $count_bmtp->[0] == 0 ) {
9621         $deleted = $dbh->do(q|
9622             DELETE FROM message_transport_types where message_transport_type='feed'
9623         |);
9624         $deleted = $deleted ne '0E0' ? 1 : 0;
9625     }
9626
9627     print "Upgrade to $DBversion done (Bug 12298: Delete the 'feed' message transport type " . ($deleted ? '(deleted!)' : '(not deleted)') . ")\n";
9628     SetVersion($DBversion);
9629 }
9630
9631 $DBversion = "3.18.00.000";
9632 if ( CheckVersion($DBversion) ) {
9633     print "Upgrade to $DBversion done (3.18.0 release)\n";
9634     SetVersion($DBversion);
9635 }
9636
9637 $DBversion = "3.19.00.000";
9638 if ( CheckVersion($DBversion) ) {
9639     print "Upgrade to $DBversion done (there's life after 3.18)\n";
9640     SetVersion ($DBversion);
9641 }
9642
9643 $DBversion = "3.19.00.001";
9644 if ( CheckVersion($DBversion) ) {
9645     $dbh->do("
9646         UPDATE systempreferences
9647         SET options = 'public|school|academic|research|private|societyAssociation|corporate|government|religiousOrg|subscription'
9648         WHERE variable = 'UsageStatsLibraryType'
9649     ");
9650     if ( C4::Context->preference("UsageStatsLibraryType") eq "university" ) {
9651         C4::Context->set_preference("UsageStatsLibraryType", "academic")
9652     }
9653     print "Upgrade to $DBversion done (Bug 13436: Add more options to UsageStatsLibraryType)\n";
9654     SetVersion ($DBversion);
9655 }
9656
9657 $DBversion = "3.19.00.002";
9658 if ( CheckVersion($DBversion) ) {
9659     $dbh->do(q|
9660         UPDATE suggestions SET branchcode="" WHERE branchcode="__ANY__"
9661     |);
9662     print "upgrade to $DBversion done (Bug 10753: replace __ANY__ with empty string in suggestions.branchcode)\n";
9663     SetVersion ($DBversion);
9664 }
9665
9666 $DBversion = "3.19.00.003";
9667 if ( CheckVersion($DBversion) ) {
9668     my ($count) = $dbh->selectrow_array("SELECT COUNT(*) FROM borrowers GROUP BY userid HAVING COUNT(userid) > 1");
9669
9670     if ( $count ) {
9671         print "Upgrade to $DBversion done (Bug 1861 - Unique patrons logins not (totally) enforced) FAILED!\n";
9672         print "Your database has users with duplicate user logins. Please have your administrator deduplicate your user logins.\n";
9673         print "Afterward, your Koha administrator should execute the following database query: ALTER TABLE borrowers DROP INDEX userid, ADD UNIQUE userid (userid)";
9674     } else {
9675         $dbh->do(q{
9676             ALTER TABLE borrowers
9677                 DROP INDEX userid ,
9678                 ADD UNIQUE userid (userid)
9679         });
9680         print "Upgrade to $DBversion done (Bug 1861: Unique patrons logins not (totally) enforced)\n";
9681     }
9682     SetVersion ($DBversion);
9683 }
9684
9685 $DBversion = "3.19.00.004";
9686 if ( CheckVersion($DBversion) ) {
9687     my $pref_value = C4::Context->preference('OpacExportOptions');
9688     $pref_value =~ s/\|/,/g; # multiple is separated by ,
9689     $dbh->do(q{
9690         UPDATE systempreferences
9691             SET value = ?,
9692                 type = 'multiple'
9693         WHERE variable = 'OpacExportOptions'
9694     }, {}, $pref_value );
9695     print "Upgrade to $DBversion done (Bug 13346: OpacExportOptions is now multiple)\n";
9696     SetVersion ($DBversion);
9697 }
9698
9699 $DBversion = "3.19.00.005";
9700 if(CheckVersion($DBversion)) {
9701     $dbh->do(q{
9702         ALTER TABLE authorised_values MODIFY COLUMN category VARCHAR(32) NOT NULL DEFAULT ''
9703     });
9704
9705     $dbh->do(q{
9706         ALTER TABLE borrower_attribute_types MODIFY COLUMN authorised_value_category VARCHAR(32) DEFAULT NULL
9707     });
9708
9709     print "Upgrade to $DBversion done (Bug 13379: Modify authorised_values.category to varchar(32))\n";
9710     SetVersion($DBversion);
9711 }
9712
9713 $DBversion = "3.19.00.006";
9714 if ( CheckVersion($DBversion) ) {
9715     $dbh->do(q|SET foreign_key_checks = 0|);
9716     my $sth = $dbh->table_info( '','','','TABLE' );
9717     my ( $cat, $schema, $name, $type, $remarks );
9718     while ( ( $cat, $schema, $name, $type, $remarks ) = $sth->fetchrow_array ) {
9719         my $table_sth = $dbh->prepare(qq|SHOW CREATE TABLE $name|);
9720         $table_sth->execute;
9721         my @table = $table_sth->fetchrow_array;
9722         unless ( $table[1] =~ /COLLATE=utf8mb4_unicode_ci/ ) { #catches utf8mb4 collated tables
9723             if ( $name eq 'marc_subfield_structure' ) {
9724                 $dbh->do(q|
9725                     ALTER TABLE marc_subfield_structure
9726                     MODIFY COLUMN tagfield varchar(3) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9727                     MODIFY COLUMN tagsubfield varchar(1) COLLATE utf8_bin NOT NULL DEFAULT '',
9728                     MODIFY COLUMN liblibrarian varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9729                     MODIFY COLUMN libopac varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9730                     MODIFY COLUMN kohafield varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
9731                     MODIFY COLUMN authorised_value varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
9732                     MODIFY COLUMN authtypecode varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
9733                     MODIFY COLUMN value_builder varchar(80) COLLATE utf8_unicode_ci DEFAULT NULL,
9734                     MODIFY COLUMN frameworkcode varchar(4) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9735                     MODIFY COLUMN seealso varchar(1100) COLLATE utf8_unicode_ci DEFAULT NULL,
9736                     MODIFY COLUMN link varchar(80) COLLATE utf8_unicode_ci DEFAULT NULL
9737                 |);
9738                 $dbh->do(qq|ALTER TABLE $name CHARACTER SET utf8 COLLATE utf8_unicode_ci|);
9739             }
9740             else {
9741                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci|);
9742             }
9743         }
9744     }
9745     $dbh->do(q|SET foreign_key_checks = 1|);;
9746
9747     print "Upgrade to $DBversion done (Bug 11944: Convert DB tables to utf8_unicode_ci)\n";
9748     SetVersion($DBversion);
9749 }
9750
9751 $DBversion = "3.19.00.007";
9752 if ( CheckVersion($DBversion) ) {
9753     my $orphan_budgets = $dbh->selectall_arrayref(q|
9754         SELECT budget_id, budget_name, budget_code
9755         FROM aqbudgets
9756         WHERE   budget_parent_id IS NOT NULL
9757             AND budget_parent_id NOT IN (
9758                 SELECT DISTINCT budget_id FROM aqbudgets
9759             )
9760     |, { Slice => {} } );
9761
9762     if ( @$orphan_budgets ) {
9763         for my $b ( @$orphan_budgets ) {
9764             print "Fund $b->{budget_name} (code:$b->{budget_code}, id:$b->{budget_id}) does not have a parent, it may cause problem\n";
9765         }
9766         print "Upgrade to $DBversion done (Bug 12905: Check budget integrity: FAIL)\n";
9767     } else {
9768         print "Upgrade to $DBversion done (Bug 12905: Check budget integrity: OK)\n";
9769     }
9770     SetVersion ($DBversion);
9771 }
9772
9773 $DBversion = "3.19.00.008";
9774 if ( CheckVersion($DBversion) ) {
9775     my $number_of_orders_not_linked = $dbh->selectcol_arrayref(q|
9776         SELECT COUNT(*)
9777         FROM aqorders o
9778         WHERE NOT EXISTS (
9779             SELECT NULL
9780             FROM aqbudgets b
9781             WHERE b.budget_id = o.budget_id
9782         );
9783     |);
9784
9785     if ( $number_of_orders_not_linked->[0] > 0 ) {
9786         $dbh->do(q|
9787             INSERT INTO aqbudgetperiods(budget_period_startdate, budget_period_enddate, budget_period_active, budget_period_description, budget_period_total) VALUES ( CAST(NOW() AS date), CAST(NOW() AS date), 0, "WARNING: This budget has been automatically created by the updatedatabase script, please see bug 12601 for more information", 0)
9788         |);
9789         my $budget_period_id = $dbh->last_insert_id( undef, undef, 'aqbudgetperiods', undef );
9790         $dbh->do(qq|
9791             INSERT INTO aqbudgets(budget_code, budget_name, budget_amount, budget_period_id) VALUES ( "BACKUP_TMP", "WARNING: fund created by the updatedatabase script, please see bug 12601", 0, $budget_period_id );
9792         |);
9793         my $budget_id = $dbh->last_insert_id( undef, undef, 'aqbudgets', undef );
9794         $dbh->do(qq|
9795             UPDATE aqorders o
9796             SET budget_id = $budget_id
9797             WHERE NOT EXISTS (
9798                 SELECT NULL
9799                 FROM aqbudgets b
9800                 WHERE b.budget_id = o.budget_id
9801             )
9802         |);
9803     }
9804
9805     $dbh->do(q|
9806         ALTER TABLE aqorders
9807         ADD CONSTRAINT aqorders_budget_id_fk FOREIGN KEY (budget_id) REFERENCES aqbudgets(budget_id) ON DELETE CASCADE ON UPDATE CASCADE
9808     |);
9809
9810     print "Upgrade to $DBversion done (Bug 12601: Add new foreign key aqorders.budget_id" . ( ( $number_of_orders_not_linked->[0] > 0 )  ? ' WARNING: temporary budget and fund have been created (search for "BACKUP_TMP"). At least one of your order was not linked to a budget' : '' ) . ")\n";
9811     SetVersion($DBversion);
9812 }
9813
9814 $DBversion = "3.19.00.009";
9815 if ( CheckVersion($DBversion) ) {
9816     $dbh->do(q|
9817         UPDATE suggestions s SET s.budgetid = NULL
9818         WHERE NOT EXISTS (
9819             SELECT NULL
9820             FROM aqbudgets b
9821             WHERE b.budget_id = s.budgetid
9822         );
9823     |);
9824
9825     $dbh->do(q|
9826         ALTER TABLE suggestions
9827         ADD CONSTRAINT suggestions_budget_id_fk FOREIGN KEY (budgetid) REFERENCES aqbudgets(budget_id) ON DELETE SET NULL ON UPDATE CASCADE
9828     |);
9829
9830     print "Upgrade to $DBversion done (Bug 13007: Add new foreign key suggestions.budgetid)\n";
9831     SetVersion($DBversion);
9832 }
9833
9834 $DBversion = "3.19.00.010";
9835 if ( CheckVersion($DBversion) ) {
9836     $dbh->do(q|
9837         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
9838         VALUES('SessionRestrictionByIP','1','Check for Change in  Remote IP address for Session Security. Disable when remote ip address changes frequently.','','YesNo')
9839     |);
9840     print "Upgrade to $DBversion done (Bug 5511: SessionRestrictionByIP)\n";
9841     SetVersion ($DBversion);
9842 }
9843
9844 $DBversion = "3.19.00.011";
9845 if ( CheckVersion($DBversion) ) {
9846     $dbh->do(q|
9847         INSERT INTO userflags (bit, flag, flagdesc, defaulton) VALUES
9848         (20, 'lists', 'Lists', 0)
9849     |);
9850     $dbh->do(q|
9851         INSERT INTO permissions (module_bit, code, description) VALUES
9852         (20, 'delete_public_lists', 'Delete public lists')
9853     |);
9854     print "Upgrade to $DBversion done (Bug 13417: Add permission to delete public lists)\n";
9855     SetVersion ($DBversion);
9856 }
9857
9858 $DBversion = "3.19.00.012";
9859 if(CheckVersion($DBversion)) {
9860     $dbh->do(q{
9861         ALTER TABLE biblioitems MODIFY COLUMN marcxml longtext
9862     });
9863
9864     $dbh->do(q{
9865         ALTER TABLE deletedbiblioitems MODIFY COLUMN marcxml longtext
9866     });
9867
9868     print "Upgrade to $DBversion done (Bug 13523 Remove NOT NULL restriction on field marcxml due to mysql STRICT_TRANS_TABLES)\n";
9869     SetVersion ($DBversion);
9870 }
9871
9872 $DBversion = "3.19.00.013";
9873 if ( CheckVersion($DBversion) ) {
9874     $dbh->do(q|
9875         INSERT INTO permissions (module_bit, code, description) VALUES
9876           (13, 'records_batchmod', 'Perform batch modification of records (biblios or authorities)')
9877     |);
9878     print "Upgrade to $DBversion done (Bug 11395: Add permission tools_records_batchmod)\n";
9879     SetVersion($DBversion);
9880 }
9881
9882 $DBversion = "3.19.00.014";
9883 if ( CheckVersion($DBversion) ) {
9884     $dbh->do(q|
9885         CREATE TABLE aqorder_users (
9886             ordernumber int(11) NOT NULL,
9887             borrowernumber int(11) NOT NULL,
9888             PRIMARY KEY (ordernumber, borrowernumber),
9889             CONSTRAINT aqorder_users_ibfk_1 FOREIGN KEY (ordernumber) REFERENCES aqorders (ordernumber) ON DELETE CASCADE ON UPDATE CASCADE,
9890             CONSTRAINT aqorder_users_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
9891         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
9892     |);
9893
9894     $dbh->do(q|
9895         INSERT INTO letter(module, code, branchcode, name, title, content, message_transport_type)
9896         VALUES ('acquisition', 'ACQ_NOTIF_ON_RECEIV', '', 'Notification on receiving', 'Order received', 'Dear <<borrowers.firstname>> <<borrowers.surname>>,\n\n The order <<aqorders.ordernumber>> (<<biblio.title>>) has been received.\n\nYour library.', 'email')
9897     |);
9898     print "Upgrade to $DBversion done (Bug 12648: Add letter ACQ_NOTIF_ON_RECEIV )\n";
9899     SetVersion ($DBversion);
9900 }
9901
9902 $DBversion = "3.19.00.015";
9903 if ( CheckVersion($DBversion) ) {
9904     $dbh->do(q|
9905         ALTER TABLE search_history ADD COLUMN id INT(11) NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY(id);
9906     |);
9907     print "Upgrade to $DBversion done (Bug 11430: Add primary key for search_history)\n";
9908     SetVersion ($DBversion);
9909 }
9910
9911 $DBversion = "3.19.00.016";
9912 if(CheckVersion($DBversion)) {
9913     my @order_cancellation_reason = $dbh->selectrow_array("SELECT count(*) FROM authorised_values WHERE category='ORDER_CANCELLATION_REASON'");
9914     if ($order_cancellation_reason[0] == 0) {
9915         $dbh->do(q{
9916             INSERT INTO authorised_values (category, authorised_value, lib) VALUES
9917              ('ORDER_CANCELLATION_REASON', 0, 'No reason provided'),
9918              ('ORDER_CANCELLATION_REASON', 1, 'Out of stock'),
9919              ('ORDER_CANCELLATION_REASON', 2, 'Restocking')
9920         });
9921
9922         my $already_existing_reasons = $dbh->selectcol_arrayref(q{
9923             SELECT DISTINCT( cancellationreason )
9924             FROM aqorders;
9925         }, { Slice => {} });
9926
9927         my $update_orders_sth = $dbh->prepare(q{
9928             UPDATE aqorders
9929             SET cancellationreason = ?
9930             WHERE cancellationreason = ?
9931         });
9932
9933         my $insert_av_sth = $dbh->prepare(q{
9934             INSERT INTO authorised_values (category, authorised_value, lib) VALUES
9935              ('ORDER_CANCELLATION_REASON', ?, ?)
9936         });
9937         my $i = 3;
9938         for my $reason ( @$already_existing_reasons ) {
9939             next unless $reason;
9940             $insert_av_sth->execute( $i, $reason );
9941             $update_orders_sth->execute( $i, $reason );
9942             $i++;
9943         }
9944         print "Upgrade to $DBversion done (Bug 13380: Add the ORDER_CANCELLATION_REASON authorised value)\n";
9945     }
9946     else {
9947         print "Upgrade to $DBversion done (Bug 13380: ORDER_CANCELLATION_REASON authorised value already existed from earlier update!)\n";
9948     }
9949
9950     SetVersion($DBversion);
9951 }
9952
9953 $DBversion = '3.19.00.017';
9954 if ( CheckVersion($DBversion) ) {
9955     # First create the column
9956     $dbh->do("ALTER TABLE issuingrules ADD onshelfholds tinyint(1) default 0 NOT NULL");
9957     # Now update the column
9958     if (C4::Context->preference("AllowOnShelfHolds")){
9959         # Pref is on, set allow for all rules
9960         $dbh->do("UPDATE issuingrules SET onshelfholds=1");
9961     } else {
9962         # If the preference is not set, leave off
9963         $dbh->do("UPDATE issuingrules SET onshelfholds=0");
9964     }
9965     # Remove from the systempreferences table
9966     $dbh->do("DELETE FROM systempreferences WHERE variable = 'AllowOnShelfHolds'");
9967
9968     # First create the column
9969     $dbh->do("ALTER TABLE issuingrules ADD opacitemholds char(1) DEFAULT 'N' NOT NULL");
9970     # Now update the column
9971     my $opacitemholds = C4::Context->preference("OPACItemHolds") || '';
9972     if (lc ($opacitemholds) eq 'force') {
9973         $opacitemholds = 'F';
9974     }
9975     else {
9976         $opacitemholds = $opacitemholds ? 'Y' : 'N';
9977     }
9978     # Set allow for all rules
9979     $dbh->do("UPDATE issuingrules SET opacitemholds='$opacitemholds'");
9980
9981     # Remove from the systempreferences table
9982     $dbh->do("DELETE FROM systempreferences WHERE variable = 'OPACItemHolds'");
9983
9984     print "Upgrade to $DBversion done (Bug 5786: Move AllowOnShelfHolds to circulation matrix; Move OPACItemHolds system preference to circulation matrix)\n";
9985     SetVersion ($DBversion);
9986 }
9987
9988
9989 $DBversion = "3.19.00.018";
9990 if ( CheckVersion($DBversion) ) {
9991     $dbh->do(q|
9992         UPDATE systempreferences set variable="OpacAdditionalStylesheet" WHERE variable="opaccolorstylesheet"
9993     |);
9994     print "Upgrade to $DBversion done (Bug 10328: Rename opaccolorstylesheet to OpacAdditionalStylesheet\n";
9995     SetVersion ($DBversion);
9996 }
9997
9998 $DBversion = "3.19.00.019";
9999 if ( CheckVersion($DBversion) ) {
10000     $dbh->do(q{
10001         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
10002         VALUES('Coce','0', 'If on, enables cover retrieval from the configured Coce server', NULL, 'YesNo')
10003     });
10004     $dbh->do(q{
10005         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
10006         VALUES('CoceHost', NULL, 'Coce server URL', NULL,'Free')
10007     });
10008     $dbh->do(q{
10009         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
10010         VALUES('CoceProviders', NULL, 'Coce providers', 'aws,gb,ol', 'multiple')
10011     });
10012     print "Upgrade to $DBversion done (Bug 9580: Cover image from Coce, a remote image URL cache)\n";
10013     SetVersion($DBversion);
10014 }
10015
10016 $DBversion = "3.19.00.020";
10017 if ( CheckVersion($DBversion) ) {
10018     $dbh->do(q|
10019         ALTER TABLE aqorders DROP COLUMN supplierreference;
10020     |);
10021
10022     print "Upgrade to $DBversion done (Bug 11008: DROP column aqorders.supplierreference)\n";
10023     SetVersion($DBversion);
10024 }
10025
10026 $DBversion = "3.19.00.021";
10027 if ( CheckVersion($DBversion) ) {
10028     $dbh->do(q|
10029         ALTER TABLE issues DROP COLUMN issuingbranch
10030     |);
10031     $dbh->do(q|
10032         ALTER TABLE old_issues DROP COLUMN issuingbranch
10033     |);
10034     print "Upgrade to $DBversion done (Bug 2806: Remove issuingbranch columns)\n";
10035     SetVersion ($DBversion);
10036 }
10037
10038 $DBversion = '3.19.00.022';
10039 if ( CheckVersion($DBversion) ) {
10040     $dbh->do(q{
10041         ALTER TABLE suggestions DROP COLUMN mailoverseeing;
10042     });
10043     print "Upgrade to $DBversion done (Bug 13006: Drop column suggestion.mailoverseeing)\n";
10044     SetVersion($DBversion);
10045 }
10046
10047 $DBversion = "3.19.00.023";
10048 if ( CheckVersion($DBversion) ) {
10049     $dbh->do(q|
10050         DELETE FROM systempreferences where variable = 'AddPatronLists'
10051     |);
10052     print "Upgrade to $DBversion done (Bug 13497: Remove the AddPatronLists system preferences)\n";
10053     SetVersion ($DBversion);
10054 }
10055
10056 $DBversion = "3.19.00.024";
10057 if ( CheckVersion($DBversion) ) {
10058     $dbh->do(qq|DROP table patroncards;|);
10059     print "Upgrade to $DBversion done (Bug 13539: Remove table patroncards from database as it's no longer in use)\n";
10060     SetVersion ($DBversion);
10061 }
10062
10063 $DBversion = "3.19.00.025";
10064 if ( CheckVersion($DBversion) ) {
10065     $dbh->do(q|
10066         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
10067         ('SearchWithISBNVariations','0',NULL,'If enabled, search on all variations of the ISBN','YesNo')
10068     |);
10069     print "Upgrade to $DBversion done (Bug 13528: Add the SearchWithISBNVariations syspref)\n";
10070     SetVersion ($DBversion);
10071 }
10072
10073 $DBversion = "3.19.00.026";
10074 if( CheckVersion($DBversion) ) {
10075     if ( C4::Context->preference('marcflavour') eq 'MARC21' ) {
10076     $dbh->do(q{
10077         INSERT IGNORE INTO auth_tag_structure (authtypecode, tagfield, liblibrarian, libopac, repeatable, mandatory, authorised_value) VALUES
10078         ('', '388', 'TIME PERIOD OF CREATION', 'TIME PERIOD OF CREATION', 1, 0, NULL);
10079     });
10080
10081     $dbh->do(q{
10082         INSERT IGNORE INTO auth_subfield_structure (authtypecode, tagfield, tagsubfield, liblibrarian, libopac, repeatable,
10083         mandatory, tab, authorised_value, value_builder, seealso, isurl, hidden, linkid, kohafield, frameworkcode) VALUES
10084         ('', '388', '0', 'Authority record control number or standard number', 'Authority record control number or standard number', 1, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10085         ('', '388', '2', 'Source of term', 'Source of term', 0, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10086         ('', '388', '3', 'Materials specified', 'Materials specified', 0, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10087         ('', '388', '6', 'Linkage', 'Linkage', 0, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10088         ('', '388', '8', 'Field link and sequence number', 'Field link and sequence number', 1, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10089         ('', '388', 'a', 'Time period of creation term', 'Time period of creation term', 1, 0, 3, NULL, NULL, NULL, 0, 0, '', '', '');
10090     });
10091
10092     $dbh->do(q{
10093         UPDATE IGNORE auth_subfield_structure SET repeatable = 1 WHERE tagsubfield = 'g' AND tagfield IN
10094         ('100','110','111','130','400','410','411','430','500','510','511','530','700','710','730');
10095     });
10096
10097     $dbh->do(q{
10098         INSERT IGNORE INTO auth_subfield_structure (authtypecode, tagfield, tagsubfield, liblibrarian, libopac, repeatable,
10099         mandatory, tab, authorised_value, value_builder, seealso, isurl, hidden, linkid, kohafield, frameworkcode) VALUES
10100         ('', '150', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 1, NULL, NULL, NULL, 0, 0, '', '', ''),
10101         ('', '151', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 1, NULL, NULL, NULL, 0, 0, '', '', ''),
10102         ('', '450', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 4, NULL, NULL, NULL, 0, 0, '', '', ''),
10103         ('', '451', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 4, NULL, NULL, NULL, 0, 0, '', '', ''),
10104         ('', '550', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 5, NULL, NULL, NULL, 0, 0, '', '', ''),
10105         ('', '551', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 5, NULL, NULL, NULL, 0, 0, '', '', ''),
10106         ('', '750', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10107         ('', '751', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10108         ('', '748', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10109         ('', '755', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10110         ('', '780', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10111         ('', '781', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10112         ('', '782', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10113         ('', '785', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10114         ('', '710', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10115         ('', '730', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10116         ('', '748', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10117         ('', '750', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10118         ('', '751', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10119         ('', '755', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10120         ('', '762', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10121         ('', '780', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10122         ('', '781', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10123         ('', '782', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10124         ('', '785', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10125         ('', '788', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', '');
10126     });
10127
10128     $dbh->do(q{
10129         UPDATE IGNORE auth_subfield_structure SET liblibrarian = 'Relationship information', libopac = 'Relationship information'
10130         WHERE tagsubfield = 'i' AND tagfield IN ('700','710','730','750','751','762');
10131     });
10132
10133     $dbh->do(q{
10134         UPDATE IGNORE auth_subfield_structure SET liblibrarian = 'Relationship code', libopac = 'Relationship code'
10135         WHERE tagsubfield = '4' AND tagfield IN ('700','710');
10136     });
10137
10138     $dbh->do(q{
10139         INSERT IGNORE INTO marc_tag_structure (tagfield, liblibrarian, libopac, repeatable, mandatory, authorised_value, frameworkcode) VALUES
10140         ('370', 'ASSOCIATED PLACE', 'ASSOCIATED PLACE', 1, 0, NULL, ''),
10141         ('388', 'TIME PERIOD OF CREATION', 'TIME PERIOD OF CREATION', 1, 0, NULL, '');
10142     });
10143
10144     $dbh->do(q{
10145         INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian, libopac, repeatable, mandatory,
10146         kohafield, tab, authorised_value, authtypecode, value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
10147         ('370', '0', 'Authority record control number or standard number', 'Authority record control number or standard number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10148         ('370', '2', 'Source of term', 'Source of term', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10149         ('370', '6', 'Linkage', 'Linkage', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10150         ('370', '8', 'Field link and sequence number', 'Field link and sequence number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10151         ('370', 'c', 'Associated country', 'Associated country', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10152         ('370', 'f', 'Other associated place', 'Other associated place', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10153         ('370', 'g', 'Place of origin of work', 'Place of origin of work', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10154         ('370', 's', 'Start period', 'Start period', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10155         ('370', 't', 'End period', 'End period', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10156         ('370', 'u', 'Uniform Resource Identifier', 'Uniform Resource Identifier', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10157         ('370', 'v', 'Source of information', 'Source of information', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10158         ('377', 'l', 'Language term', 'Language term', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10159         ('382', 's', 'Total number of performers', 'Total number of performers', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10160         ('388', '0', 'Authority record control number or standard number', 'Authority record control number or standard number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10161         ('388', '2', 'Source of term', 'Source of term', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10162         ('388', '3', ' Materials specified', ' Materials specified', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10163         ('388', '6', ' Linkage', ' Linkage', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10164         ('388', '8', 'Field link and sequence number', 'Field link and sequence number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10165         ('388', 'a', 'Time period of creation term', 'Time period of creation term', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10166         ('650', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, '', 6, '', '', '', 0, -1, '', '', '', NULL),
10167         ('651', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, '', 6, '', '', '', 0, -1, '', '', '', NULL);
10168     });
10169
10170     $dbh->do(q{
10171         UPDATE IGNORE marc_subfield_structure SET repeatable = 1 WHERE tagsubfield = 'g' AND
10172         tagfield IN ('100','110','111','130','240','243','246','247','600','610','611','630','700','710','711','730','800','810','811','830');
10173     });
10174     }
10175
10176     print "Upgrade to $DBversion done (Bug 13322: Update MARC21 frameworks to Update No. 19 - October 2014)\n";
10177     SetVersion($DBversion);
10178 }
10179
10180 $DBversion = '3.19.00.027';
10181 if ( CheckVersion($DBversion) ) {
10182     $dbh->do("ALTER TABLE items ADD COLUMN itemnotes_nonpublic MEDIUMTEXT AFTER itemnotes");
10183     $dbh->do("ALTER TABLE deleteditems ADD COLUMN itemnotes_nonpublic MEDIUMTEXT AFTER itemnotes");
10184     print "Upgrade to $DBversion done (Bug 4222: Nonpublic note not appearing in the staff client) <b>Please check each of your frameworks to ensure your non-public item notes are mapped to items.itemnotes_nonpublic. After doing so please have your administrator run misc/batchRebuildItemsTables.pl </b>)\n";
10185     SetVersion($DBversion);
10186 }
10187
10188 $DBversion = "3.19.00.028";
10189 if( CheckVersion($DBversion) ) {
10190     eval {
10191         local $dbh->{PrintError} = 0;
10192         $dbh->do(q{
10193             ALTER TABLE issues DROP PRIMARY KEY
10194         });
10195     };
10196
10197     $dbh->do(q{
10198         ALTER TABLE old_issues ADD issue_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10199     });
10200
10201     $dbh->do(q{
10202         ALTER TABLE old_issues CHANGE issue_id issue_id INT( 11 ) NOT NULL
10203     });
10204
10205     $dbh->do(q{
10206         ALTER TABLE issues ADD issue_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10207     });
10208
10209     $dbh->do(q{
10210         UPDATE issues SET issue_id = issue_id + ( SELECT COUNT(*) FROM old_issues ) ORDER BY issue_id DESC
10211     });
10212
10213     my $max_issue_id = $schema->resultset('Issue')->get_column('issue_id')->max();
10214     if ($max_issue_id) {
10215         $max_issue_id++;
10216         $dbh->do(qq{
10217             ALTER TABLE issues AUTO_INCREMENT = $max_issue_id
10218         });
10219     }
10220
10221     print "Upgrade to $DBversion done (Bug 13790: Add unique id issue_id to issues and oldissues tables)\n";
10222     SetVersion($DBversion);
10223 }
10224
10225 $DBversion = "3.19.00.029";
10226 if ( CheckVersion($DBversion) ) {
10227     $dbh->do(q|
10228          ALTER TABLE sessions CHANGE COLUMN a_session a_session MEDIUMTEXT
10229     |);
10230     print "Upgrade to $DBversion done (Bug 13606: Upgrade sessions.a_session to MEDIUMTEXT)\n";
10231     SetVersion($DBversion);
10232 }
10233
10234 $DBversion = "3.19.00.030";
10235 if ( CheckVersion($DBversion) ) {
10236     $dbh->do(q|
10237 UPDATE language_subtag_registry SET subtag = 'kn' WHERE subtag = 'ka' AND description = 'Kannada';
10238     |);
10239     $dbh->do(q|
10240 UPDATE language_rfc4646_to_iso639 SET rfc4646_subtag = 'kn' WHERE rfc4646_subtag = 'ka' AND iso639_2_code = 'kan';
10241     |);
10242     $dbh->do(q|
10243 UPDATE language_descriptions SET subtag = 'kn', lang = 'kn' WHERE subtag = 'ka' AND lang = 'ka' AND description = 'ಕನ್ನಡ';
10244     |);
10245     $dbh->do(q|
10246 UPDATE language_descriptions SET subtag = 'kn' WHERE subtag = 'ka' AND description = 'Kannada';
10247     |);
10248     $dbh->do(q|
10249 INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ka', 'language', 'Georgian','2015-04-20');
10250     |);
10251     $dbh->do(q|
10252 DELETE FROM language_subtag_registry
10253        WHERE NOT id IN
10254          (SELECT id FROM
10255            (SELECT MIN(id) as id,subtag,type,description,added
10256             FROM language_subtag_registry
10257             GROUP BY subtag,type,description,added)
10258            AS subtable);
10259     |);
10260     $dbh->do(q|
10261 INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ka', 'geo');
10262     |);
10263     $dbh->do(q|
10264 DELETE FROM language_rfc4646_to_iso639
10265        WHERE NOT id IN
10266          (SELECT id FROM
10267            (SELECT MIN(id) as id,rfc4646_subtag,iso639_2_code
10268             FROM language_rfc4646_to_iso639
10269             GROUP BY rfc4646_subtag,iso639_2_code)
10270            AS subtable);
10271     |);
10272     $dbh->do(q|
10273 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'ka', 'ქართული');
10274     |);
10275     $dbh->do(q|
10276 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'en', 'Georgian');
10277     |);
10278     $dbh->do(q|
10279 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'fr', 'Géorgien');
10280     |);
10281     $dbh->do(q|
10282 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'de', 'Georgisch');
10283     |);
10284     $dbh->do(q|
10285 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'es', 'Georgiano');
10286     |);
10287     $dbh->do(q|
10288 DELETE FROM language_descriptions
10289        WHERE NOT id IN
10290          (SELECT id FROM
10291            (SELECT MIN(id) as id,subtag,type,lang,description
10292             FROM language_descriptions GROUP BY subtag,type,lang,description)
10293            AS subtable);
10294     |);
10295     print "Upgrade to $DBversion done (Bug 14030: Add Georgian language and fix Kannada language code)\n";
10296     SetVersion($DBversion);
10297 }
10298
10299 $DBversion = "3.19.00.031";
10300 if ( CheckVersion($DBversion) ) {
10301     $dbh->do(q{
10302         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10303         VALUES('IdRef','0','Disable/enable the IdRef webservice from the OPAC detail page.',NULL,'YesNo')
10304     });
10305     print "Upgrade to $DBversion done (Bug 8992: Add system preference IdRef))\n";
10306     SetVersion($DBversion);
10307 }
10308
10309 $DBversion = "3.19.00.032";
10310 if ( CheckVersion($DBversion) ) {
10311     $dbh->do(q|
10312         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10313         VALUES('AddressFormat','us','Choose format to display postal addresses','','Choice')
10314     |);
10315     print "Upgrade to $DBversion done (Bug 4041: Address Format as a I18N/L10N system preference\n";
10316     SetVersion ($DBversion);
10317 }
10318
10319 $DBversion = "3.19.00.033";
10320 if ( CheckVersion($DBversion) ) {
10321     $dbh->do(q|
10322         ALTER TABLE auth_header
10323         CHANGE COLUMN datemodified modification_time TIMESTAMP NOT NULL default CURRENT_TIMESTAMP
10324     |);
10325     $dbh->do(q|
10326         ALTER TABLE auth_header
10327         CHANGE COLUMN modification_time modification_time TIMESTAMP NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP
10328     |);
10329     print "Upgrade to $DBversion done (Bug 11165: Update auth_header.datemodified when updated)\n";
10330     SetVersion ($DBversion);
10331 }
10332
10333 $DBversion = "3.19.00.034";
10334 if ( CheckVersion($DBversion) ) {
10335     $dbh->do(q|
10336         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10337         VALUES('CardnumberLength', '', '', 'Set a length for card numbers.', 'Free')
10338     |);
10339     print "Upgrade to $DBversion done (Bug 13984: CardnumberLength syspref missing on some setups\n";
10340     SetVersion ($DBversion);
10341 }
10342
10343 $DBversion = "3.19.00.035";
10344 if ( CheckVersion($DBversion) ) {
10345     $dbh->do(q|
10346         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('useDischarge','','Allows librarians to discharge borrowers and borrowers to request a discharge','','YesNo')
10347     |);
10348     $dbh->do(q|
10349         INSERT IGNORE INTO letter (module, code, name, title, content) VALUES('members', 'DISCHARGE', 'Discharge', 'Discharge for <<borrowers.firstname>> <<borrowers.surname>>', '<h1>Discharge</h1>\r\n\r\nThe library <<borrowers.branchcode>> certifies that the following borrower :\r\n\r\n    <<borrowers.firstname>> <<borrowers.surname>>\r\n   Cardnumber : <<borrowers.cardnumber>>\r\n\r\nreturned all his documents.')
10350     |);
10351
10352     $dbh->do(q|
10353         ALTER TABLE borrower_debarments CHANGE type type ENUM('SUSPENSION','OVERDUES','MANUAL','DISCHARGE') NOT NULL DEFAULT 'MANUAL'
10354     |);
10355
10356     $dbh->do(q|
10357         CREATE TABLE discharges (
10358           borrower int(11) DEFAULT NULL,
10359           needed timestamp NULL DEFAULT NULL,
10360           validated timestamp NULL DEFAULT NULL,
10361           KEY borrower_discharges_ibfk1 (borrower),
10362           CONSTRAINT borrower_discharges_ibfk1 FOREIGN KEY (borrower) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
10363         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
10364     |);
10365
10366     print "Upgrade to $DBversion done (Bug 8007: Add System Preferences useDischarge, the discharge notice and the new table discharges)\n";
10367     SetVersion($DBversion);
10368 }
10369
10370 $DBversion = "3.19.00.036";
10371 if ( CheckVersion($DBversion) ) {
10372     $dbh->do(q|
10373         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10374         VALUES ('CronjobLog','0',NULL,'If ON, log information from cron jobs.','YesNo')
10375     |);
10376     print "Upgrade to $DBversion done (Bug 13889: Add cron jobs information to system log)\n";
10377     SetVersion ($DBversion);
10378 }
10379
10380 $DBversion = "3.19.00.037";
10381 if ( CheckVersion($DBversion) ) {
10382     $dbh->do(q|
10383         ALTER TABLE marc_subfield_structure
10384         MODIFY COLUMN tagsubfield varchar(1) COLLATE utf8_bin NOT NULL DEFAULT ''
10385     |);
10386     print "Upgrade to $DBversion done (Bug 13810: Change collate for tagsubfield (utf8_bin))\n";
10387     SetVersion ($DBversion);
10388 }
10389
10390 $DBversion = "3.19.00.038";
10391 if ( CheckVersion($DBversion) ) {
10392     $dbh->do(q|
10393         ALTER TABLE virtualshelves
10394         ADD COLUMN created_on DATETIME NOT NULL AFTER lastmodified
10395     |);
10396     # Set created_on = lastmodified
10397     # I would say it's better than 0000-00-00
10398     # Set modified to the existing value (do not get the current ts!)
10399     $dbh->do(q|
10400         UPDATE virtualshelves
10401         SET created_on = lastmodified, lastmodified = lastmodified
10402     |);
10403     print "Upgrade to $DBversion done (Bug 13421: Add DB field virtualshelves.created_on)\n";
10404     SetVersion ($DBversion);
10405 }
10406
10407 $DBversion = "3.19.00.039";
10408 if ( CheckVersion($DBversion) ) {
10409     print "Upgrade to $DBversion done (Koha 3.20 beta)\n";
10410     SetVersion ($DBversion);
10411 }
10412
10413 $DBversion = "3.19.00.040";
10414 if ( CheckVersion($DBversion) ) {
10415     $dbh->do(q|
10416         ALTER TABLE aqorders DROP COLUMN totalamount
10417     |);
10418     print "Upgrade to $DBversion done (Bug 11006: Drop column aqorders.totalamount)\n";
10419     SetVersion ($DBversion);
10420 }
10421
10422 $DBversion = "3.19.00.041";
10423 if ( CheckVersion($DBversion) ) {
10424     unless ( index_exists( 'suggestions', 'status' ) ) {
10425         $dbh->do(q|
10426             ALTER TABLE suggestions ADD KEY status (STATUS)
10427         |);
10428     }
10429     unless ( index_exists( 'suggestions', 'biblionumber' ) ) {
10430         $dbh->do(q|
10431             ALTER TABLE suggestions ADD KEY biblionumber (biblionumber)
10432         |);
10433     }
10434     unless ( index_exists( 'suggestions', 'branchcode' ) ) {
10435         $dbh->do(q|
10436             ALTER TABLE suggestions ADD KEY branchcode (branchcode)
10437         |);
10438     }
10439     print "Upgrade to $DBversion done (Bug 14132: suggestions table is missing indexes)\n";
10440     SetVersion ($DBversion);
10441 }
10442
10443 $DBversion = "3.19.00.042";
10444 if ( CheckVersion($DBversion) ) {
10445     $dbh->do(q{
10446         DELETE ass.*
10447         FROM auth_subfield_structure AS ass
10448         LEFT JOIN auth_types USING(authtypecode)
10449         WHERE auth_types.authtypecode IS NULL
10450     });
10451
10452     unless ( foreign_key_exists( 'auth_subfield_structure', 'auth_subfield_structure_ibfk_1' ) ) {
10453         $dbh->do(q{
10454             ALTER TABLE auth_subfield_structure
10455             ADD CONSTRAINT auth_subfield_structure_ibfk_1
10456             FOREIGN KEY (authtypecode) REFERENCES auth_types(authtypecode)
10457             ON DELETE CASCADE ON UPDATE CASCADE
10458         });
10459     }
10460
10461     print "Upgrade to $DBversion done (Bug 8480: Add foreign key on auth_subfield_structure.authtypecode)\n";
10462     SetVersion($DBversion);
10463 }
10464
10465 $DBversion = "3.19.00.043";
10466 if ( CheckVersion($DBversion) ) {
10467     $dbh->do(q|
10468         INSERT IGNORE INTO authorised_values (category, authorised_value, lib) VALUES
10469         ('REPORT_GROUP', 'SER', 'Serials')
10470     |);
10471
10472     print "Upgrade to $DBversion done (Bug 5338: Add Serial to the report groups if does not exist)\n";
10473     SetVersion ($DBversion);
10474 }
10475
10476 $DBversion = "3.20.00.000";
10477 if ( CheckVersion($DBversion) ) {
10478     print "Upgrade to $DBversion done (Koha 3.20)\n";
10479     SetVersion ($DBversion);
10480 }
10481
10482 $DBversion = "3.21.00.000";
10483 if ( CheckVersion($DBversion) ) {
10484     print "Upgrade to $DBversion done (El tiempo vuela, un nuevo ciclo comienza.)\n";
10485     SetVersion ($DBversion);
10486 }
10487
10488 $DBversion = "3.21.00.001";
10489 if ( CheckVersion($DBversion) ) {
10490     $dbh->do(q|
10491         UPDATE systempreferences SET variable='IntranetUserJS' where variable='intranetuserjs'
10492     |);
10493     print "Upgrade to $DBversion done (Bug 12160: Rename intranetuserjs to IntranetUserJS)\n";
10494     SetVersion ($DBversion);
10495 }
10496
10497 $DBversion = "3.21.00.002";
10498 if ( CheckVersion($DBversion) ) {
10499     $dbh->do(q|
10500         UPDATE systempreferences SET variable='OPACUserJS' where variable='opacuserjs'
10501     |);
10502     print "Upgrade to $DBversion done (Bug 12160: Rename opacuserjs to OPACUserJS)\n";
10503     SetVersion ($DBversion);
10504 }
10505
10506 $DBversion = "3.21.00.003";
10507 if ( CheckVersion($DBversion) ) {
10508     $dbh->do(q|
10509         INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added)
10510         VALUES ( 'IN', 'region', 'India','2015-05-28');
10511     |);
10512     $dbh->do(q|
10513         INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)
10514         VALUES ( 'IN', 'region', 'en', 'India');
10515     |);
10516     $dbh->do(q|
10517         INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)
10518         VALUES ( 'IN', 'region', 'bn', 'ভারত');
10519     |);
10520     print "Upgrade to $DBversion done (Bug 14285: Add new region India)\n";
10521     SetVersion ($DBversion);
10522 }
10523
10524 $DBversion = '3.21.00.004';
10525 if ( CheckVersion($DBversion) ) {
10526     my $OPACBaseURL = C4::Context->preference('OPACBaseURL');
10527     if (defined($OPACBaseURL) && substr($OPACBaseURL,0,4) ne "http") {
10528         my $explanation = q{Specify the Base URL of the OPAC, e.g., http://opac.mylibrary.com, including the protocol (http:// or https://). Otherwise, the http:// will be added automatically by Koha upon saving.};
10529         $OPACBaseURL = 'http://' . $OPACBaseURL;
10530         my $sth_OPACBaseURL = $dbh->prepare( q{
10531             UPDATE systempreferences SET value=?,explanation=?
10532             WHERE variable='OPACBaseURL'; } );
10533         $sth_OPACBaseURL->execute($OPACBaseURL,$explanation);
10534     }
10535     if (defined($OPACBaseURL)) {
10536         $dbh->do( q{ UPDATE letter
10537                      SET content=replace(content,
10538                                          'http://<<OPACBaseURL>>',
10539                                          '<<OPACBaseURL>>')
10540                      WHERE content LIKE "%http://<<OPACBaseURL>>%"; } );
10541     }
10542
10543     print "Upgrade to $DBversion done (Bug 5010: Fix OPACBaseURL to include protocol)\n";
10544     SetVersion($DBversion);
10545 }
10546
10547 $DBversion = "3.21.00.005";
10548 if ( CheckVersion($DBversion) ) {
10549     $dbh->do(q|
10550         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10551         VALUES ('ReportsLog','0',NULL,'If ON, log information about reports.','YesNo')
10552     |);
10553     print "Upgrade to $DBversion done (Bug 14024: Add reports to action logs)\n";
10554     SetVersion ($DBversion);
10555 }
10556
10557 $DBversion = "3.21.00.006";
10558 if ( CheckVersion($DBversion) ) {
10559     # Remove the borrow permission flag (bit 7)
10560     $dbh->do(q|
10561         UPDATE borrowers
10562         SET flags = flags - ( flags & (1<<7) )
10563         WHERE flags IS NOT NULL
10564             AND flags > 0
10565     |);
10566     $dbh->do(q|
10567         DELETE FROM userflags WHERE bit=7;
10568     |);
10569     print "Upgrade to $DBversion done (Bug 7976: Remove the 'borrow' permission)\n";
10570     SetVersion($DBversion);
10571 }
10572
10573 $DBversion = "3.21.00.007";
10574 if ( CheckVersion($DBversion) ) {
10575     unless ( index_exists( 'aqbasket', 'authorisedby' ) ) {
10576         $dbh->do(q|
10577             ALTER TABLE aqbasket
10578                 ADD KEY authorisedby (authorisedby)
10579         |);
10580     }
10581     unless ( index_exists( 'aqbooksellers', 'name' ) ) {
10582         $dbh->do(q|
10583             ALTER TABLE aqbooksellers
10584                 ADD KEY name (name(255))
10585         |);
10586     }
10587     unless ( index_exists( 'aqbudgets', 'budget_parent_id' ) ) {
10588         $dbh->do(q|
10589             ALTER TABLE aqbudgets
10590                 ADD KEY budget_parent_id (budget_parent_id)|);
10591         }
10592     unless ( index_exists( 'aqbudgets', 'budget_code' ) ) {
10593         $dbh->do(q|
10594             ALTER TABLE aqbudgets
10595                 ADD KEY budget_code (budget_code)|);
10596     }
10597     unless ( index_exists( 'aqbudgets', 'budget_branchcode' ) ) {
10598         $dbh->do(q|
10599             ALTER TABLE aqbudgets
10600                 ADD KEY budget_branchcode (budget_branchcode)|);
10601     }
10602     unless ( index_exists( 'aqbudgets', 'budget_period_id' ) ) {
10603         $dbh->do(q|
10604             ALTER TABLE aqbudgets
10605                 ADD KEY budget_period_id (budget_period_id)|);
10606     }
10607     unless ( index_exists( 'aqbudgets', 'budget_owner_id' ) ) {
10608         $dbh->do(q|
10609             ALTER TABLE aqbudgets
10610                 ADD KEY budget_owner_id (budget_owner_id)|);
10611     }
10612     unless ( index_exists( 'aqbudgets_planning', 'budget_period_id' ) ) {
10613         $dbh->do(q|
10614             ALTER TABLE aqbudgets_planning
10615                 ADD KEY budget_period_id (budget_period_id)|);
10616     }
10617     unless ( index_exists( 'aqorders', 'parent_ordernumber' ) ) {
10618         $dbh->do(q|
10619             ALTER TABLE aqorders
10620                 ADD KEY parent_ordernumber (parent_ordernumber)|);
10621     }
10622     unless ( index_exists( 'aqorders', 'orderstatus' ) ) {
10623         $dbh->do(q|
10624             ALTER TABLE aqorders
10625                 ADD KEY orderstatus (orderstatus)|);
10626     }
10627     print "Upgrade to $DBversion done (Bug 14053: Acquisition db tables are missing indexes)\n";
10628     SetVersion ($DBversion);
10629 }
10630
10631 $DBversion = "3.21.00.008";
10632 if ( CheckVersion($DBversion) ) {
10633     $dbh->do(q{
10634         DELETE IGNORE FROM systempreferences
10635         WHERE variable = 'HomeOrHoldingBranchReturn';
10636     });
10637     print "Upgrade to $DBversion done (Bug 7981: Transfer message on return. HomeOrHoldingBranchReturn syspref removed in favour of circulation rules.)\n";
10638     SetVersion($DBversion);
10639 }
10640
10641 $DBversion = "3.21.00.009";
10642 if ( CheckVersion($DBversion) ) {
10643     $dbh->do(q|
10644         UPDATE aqorders SET orderstatus='cancelled'
10645         WHERE (datecancellationprinted IS NOT NULL OR
10646                datecancellationprinted<>'0000-00-00');
10647     |);
10648     print "Upgrade to $DBversion done (Bug 13993: Correct orderstatus for transferred orders)\n";
10649     SetVersion($DBversion);
10650 }
10651
10652 $DBversion = "3.21.00.010";
10653 if ( CheckVersion($DBversion) ) {
10654     $dbh->do(q|
10655         ALTER TABLE message_queue
10656             DROP message_id
10657     |);
10658     $dbh->do(q|
10659         ALTER TABLE message_queue
10660             ADD message_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10661     |);
10662     print "Upgrade to $DBversion done (Bug 7793: redefine the field message_id as PRIMARY KEY of message_queue)\n";
10663     SetVersion ($DBversion);
10664 }
10665
10666 $DBversion = "3.21.00.011";
10667 if ( CheckVersion($DBversion) ) {
10668     $dbh->do(q{
10669         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10670         VALUES ('OpacLangSelectorMode','footer','top|both|footer','Select the location to display the language selector','Choice')
10671     });
10672     print "Upgrade to $DBversion done (Bug 14252: Make the OPAC language switcher available in the masthead navbar, footer, or both)\n";
10673     SetVersion ($DBversion);
10674 }
10675
10676 $DBversion = "3.21.00.012";
10677 if ( CheckVersion($DBversion) ) {
10678     $dbh->do(q|
10679         INSERT INTO letter (module, code, name, title, content, message_transport_type)
10680         VALUES
10681         ('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')
10682     |);
10683     print "Upgrade to $DBversion done (Bug 13014: Add the TO_PROCESS letter code)\n";
10684     SetVersion($DBversion);
10685 }
10686
10687 $DBversion = "3.21.00.013";
10688 if ( CheckVersion($DBversion) ) {
10689     my $msg;
10690     if ( C4::Context->preference('OPACPrivacy') ) {
10691         if ( my $anonymous_patron = C4::Context->preference('AnonymousPatron') ) {
10692             my $anonymous_patron_exists = $dbh->selectcol_arrayref(q|
10693                 SELECT COUNT(*)
10694                 FROM borrowers
10695                 WHERE borrowernumber=?
10696             |, {}, $anonymous_patron);
10697             unless ( $anonymous_patron_exists->[0] ) {
10698                 $msg = "Configuration WARNING: OPACPrivacy is set but AnonymousPatron is not linked to an existing patron";
10699             }
10700         }
10701         else {
10702             $msg = "Configuration WARNING: OPACPrivacy is set but AnonymousPatron is not";
10703         }
10704     }
10705     else {
10706         my $patrons_have_required_anonymity = $dbh->selectcol_arrayref(q|
10707             SELECT COUNT(*)
10708             FROM borrowers
10709             WHERE privacy = 2
10710         |, {} );
10711         if ( $patrons_have_required_anonymity->[0] ) {
10712             $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.";
10713         }
10714     }
10715
10716     $msg //= "Privacy is correctly set";
10717     print "Upgrade to $DBversion done (Bug 9942: $msg)\n";
10718     SetVersion ($DBversion);
10719 }
10720
10721 $DBversion = "3.21.00.014";
10722 if ( CheckVersion($DBversion) ) {
10723     $dbh->do(q{
10724         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10725         VALUES ('OAI-PMH:DeletedRecord','persistent','Koha\'s deletedbiblio table will never be deleted (persistent) or might be deleted (transient)','transient|persistent','Choice')
10726     });
10727
10728     if ( foreign_key_exists( 'oai_sets_biblios', 'oai_sets_biblios_ibfk_1' ) ) {
10729         $dbh->do(q|
10730             ALTER TABLE oai_sets_biblios DROP FOREIGN KEY oai_sets_biblios_ibfk_1
10731         |);
10732     }
10733     print "Upgrade to $DBversion done (Bug 3206: OAI repository deleted record support)\n";
10734     SetVersion ($DBversion);
10735 }
10736
10737 $DBversion = "3.21.00.015";
10738 if ( CheckVersion($DBversion) ) {
10739     $dbh->do(q{
10740         UPDATE systempreferences SET value='0' WHERE variable='CalendarFirstDayOfWeek' AND value='Sunday';
10741     });
10742     $dbh->do(q{
10743         UPDATE systempreferences SET value='1' WHERE variable='CalendarFirstDayOfWeek' AND value='Monday';
10744     });
10745     $dbh->do(q{
10746         UPDATE systempreferences SET options='0|1|2|3|4|5|6' WHERE variable='CalendarFirstDayOfWeek';
10747     });
10748
10749     print "Upgrade to $DBversion done (Bug 12137: Extend functionality of CalendarFirstDayOfWeek to be any day)\n";
10750     SetVersion($DBversion);
10751 }
10752
10753 $DBversion = "3.21.00.016";
10754 if ( CheckVersion($DBversion) ) {
10755     my $rs = $schema->resultset('Systempreference');
10756     $rs->find_or_create(
10757         {
10758             variable => 'DumpTemplateVarsIntranet',
10759             value    => 0,
10760             explanation => 'If enabled, dump all Template Toolkit variable to a comment in the html source for the staff intranet.',
10761             type => 'YesNo',
10762         }
10763     );
10764     $rs->find_or_create(
10765         {
10766             variable => 'DumpTemplateVarsOpac',
10767             value    => 0,
10768             explanation => 'If enabled, dump all Template Toolkit variable to a comment in the html source for the opac.',
10769             type => 'YesNo',
10770         }
10771     );
10772     print "Upgrade to $DBversion done (Bug 13948: Add ability to dump template toolkit variables to html comment)\n";
10773     SetVersion($DBversion);
10774 }
10775
10776 $DBversion = "3.21.00.017";
10777 if ( CheckVersion($DBversion) ) {
10778     $dbh->do("
10779         CREATE TABLE uploaded_files (
10780             id int(11) NOT NULL AUTO_INCREMENT,
10781             hashvalue CHAR(40) NOT NULL,
10782             filename TEXT NOT NULL,
10783             dir TEXT NOT NULL,
10784             filesize int(11),
10785             dtcreated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
10786             categorycode tinytext,
10787             owner int(11),
10788             PRIMARY KEY (id)
10789         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
10790     ");
10791
10792     print "Upgrade to $DBversion done (Bug 6874: New cataloging plugin upload.pl)\n";
10793     print "This plugin comes with a new config variable (upload_path) and a new table (uploaded_files)\n";
10794     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";
10795     SetVersion($DBversion);
10796 }
10797
10798 $DBversion = "3.21.00.018";
10799 if ( CheckVersion($DBversion) ) {
10800     $dbh->do(q{
10801         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10802         VALUES
10803             ('RestrictedPageLocalIPs','',NULL,'Beginning of IP addresses considered as local (comma separated ex: \"127.0.0,127.0.2\")','Free'),
10804             ('RestrictedPageContent','',NULL,'HTML content of the restricted page','TextArea'),
10805             ('RestrictedPageTitle','',NULL,'Title of the restricted page (breadcrumb and header)','Free')
10806     });
10807     print "Upgrade to $DBversion done (Bug 13485: Add a page to display links to restricted sites)\n";
10808     SetVersion ($DBversion);
10809 }
10810
10811 $DBversion = "3.21.00.019";
10812 if ( CheckVersion($DBversion) ) {
10813     if ( column_exists( 'reserves', 'constrainttype' ) ) {
10814         $dbh->do(q{
10815             ALTER TABLE reserves DROP constrainttype
10816         });
10817         $dbh->do(q{
10818             ALTER TABLE old_reserves DROP constrainttype
10819         });
10820     }
10821     $dbh->do(q{
10822         DROP TABLE IF EXISTS reserveconstraints
10823     });
10824     print "Upgrade to $DBversion done (Bug 9809: Get rid of reserveconstraints)\n";
10825     SetVersion ($DBversion);
10826 }
10827
10828 $DBversion = "3.21.00.020";
10829 if ( CheckVersion($DBversion) ) {
10830     $dbh->do(q{
10831         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`)
10832         VALUES ('FeeOnChangePatronCategory','1','','If set, when a patron changes to a category with enrolment fee, a fee is charged','YesNo')
10833     });
10834     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";
10835     SetVersion($DBversion);
10836 }
10837
10838 $DBversion = "3.21.00.021";
10839 if ( CheckVersion($DBversion) ) {
10840     $dbh->do(q{
10841         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10842         VALUES ('UseWYSIWYGinSystemPreferences','0','','Show WYSIWYG editor when editing certain HTML system preferences.','YesNo')
10843     });
10844     print "Upgrade to $DBversion done (Bug 11584: Add wysiwyg editor to system preferences dealing with HTML)\n";
10845     SetVersion($DBversion);
10846 }
10847
10848 $DBversion = "3.21.00.022";
10849 if ( CheckVersion($DBversion) ) {
10850     $dbh->do(q{
10851         DELETE cr.*
10852         FROM course_reserves AS cr
10853         LEFT JOIN course_items USING(ci_id)
10854         WHERE course_items.ci_id IS NULL
10855     });
10856
10857     my ($print_error) = $dbh->{PrintError};
10858     $dbh->{RaiseError} = 0;
10859     $dbh->{PrintError} = 0;
10860     if ( foreign_key_exists('course_reserves', 'course_reserves_ibfk_2') ) {
10861         $dbh->do(q{ALTER TABLE course_reserves DROP FOREIGN KEY course_reserves_ibfk_2});
10862         $dbh->do(q{ALTER TABLE course_reserves DROP INDEX course_reserves_ibfk_2});
10863     }
10864     $dbh->{PrintError} = $print_error;
10865
10866     $dbh->do(q{
10867         ALTER TABLE course_reserves
10868             ADD CONSTRAINT course_reserves_ibfk_2
10869                 FOREIGN KEY (ci_id) REFERENCES course_items (ci_id)
10870                 ON DELETE CASCADE ON UPDATE CASCADE
10871     });
10872     print "Upgrade to $DBversion done (Bug 14205: Deleting an Item/Record does not remove link to course reserve)\n";
10873     SetVersion($DBversion);
10874 }
10875
10876 $DBversion = "3.21.00.023";
10877 if ( CheckVersion($DBversion) ) {
10878     $dbh->do(q{
10879         UPDATE borrowers SET debarred=NULL WHERE debarred='0000-00-00'
10880     });
10881     $dbh->do(q{
10882         UPDATE borrowers SET dateexpiry=NULL where dateexpiry='0000-00-00'
10883     });
10884     $dbh->do(q{
10885         UPDATE borrowers SET dateofbirth=NULL where dateofbirth='0000-00-00'
10886     });
10887     $dbh->do(q{
10888         UPDATE borrowers SET dateenrolled=NULL where dateenrolled='0000-00-00'
10889     });
10890     print "Upgrade to $DBversion done (Bug 14717: Prevent 0000-00-00 dates in patron data)\n";
10891     SetVersion($DBversion);
10892 }
10893
10894 $DBversion = "3.21.00.024";
10895 if ( CheckVersion($DBversion) ) {
10896     $dbh->do(q{
10897         ALTER TABLE marc_modification_template_actions
10898         MODIFY COLUMN action
10899             ENUM('delete_field','update_field','move_field','copy_field','copy_and_replace_field')
10900             NOT NULL
10901     });
10902     print "Upgrade to $DBversion done (Bug 14098: Regression in Marc Modification Templates)\n";
10903     SetVersion($DBversion);
10904 }
10905
10906 $DBversion = "3.21.00.025";
10907 if ( CheckVersion($DBversion) ) {
10908     $dbh->do(q{
10909         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10910         VALUES ('RisExportAdditionalFields',  '', NULL ,  'Define additional RIS tags to export from MARC records in YAML format as an associative array with either a marc tag/subfield combination as the value, or a list of tag/subfield combinations.',  'textarea')
10911     });
10912     $dbh->do(q{
10913         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10914         VALUES ('BibtexExportAdditionalFields',  '', NULL ,  'Define additional BibTex tags to export from MARC records in YAML format as an associative array with either a marc tag/subfield combination as the value, or a list of tag/subfield combinations.',  'textarea')
10915     });
10916     print "Upgrade to $DBversion done (Bug 12357: Enhancements to RIS and BibTeX exporting)\n";
10917     SetVersion($DBversion);
10918 }
10919
10920 $DBversion = "3.21.00.026";
10921 if ( CheckVersion($DBversion) ) {
10922     $dbh->do(q{
10923         UPDATE matchpoints
10924         SET search_index='issn'
10925         WHERE matcher_id IN (SELECT matcher_id FROM marc_matchers WHERE code = 'ISSN')
10926     });
10927     print "Upgrade to $DBversion done (Bug 14472: Wrong ISSN search index in record matching rules)\n";
10928     SetVersion($DBversion);
10929 }
10930
10931 $DBversion = "3.21.00.027";
10932 if ( CheckVersion($DBversion) ) {
10933     $dbh->do(q|
10934         INSERT IGNORE INTO permissions (module_bit, code, description)
10935         VALUES (1, 'self_checkout', 'Perform self checkout at the OPAC. It should be used for the patron matching the AutoSelfCheckID')
10936     |);
10937
10938     my $AutoSelfCheckID = C4::Context->preference('AutoSelfCheckID');
10939
10940     $dbh->do(q|
10941         UPDATE borrowers
10942         SET flags=0
10943         WHERE userid=?
10944     |, undef, $AutoSelfCheckID);
10945
10946     $dbh->do(q|
10947         DELETE FROM user_permissions
10948         WHERE borrowernumber=(SELECT borrowernumber FROM borrowers WHERE userid=?)
10949     |, undef, $AutoSelfCheckID);
10950
10951     $dbh->do(q|
10952         INSERT INTO user_permissions(borrowernumber, module_bit, code)
10953         SELECT borrowernumber, 1, 'self_checkout' FROM borrowers WHERE userid=?
10954     |, undef, $AutoSelfCheckID);
10955     print "Upgrade to $DBversion done (Bug 14298: AutoSelfCheckID user should only be able to access SCO)\n";
10956     SetVersion($DBversion);
10957 }
10958
10959 $DBversion = "3.21.00.028";
10960 if ( CheckVersion($DBversion) ) {
10961     unless ( column_exists('uploaded_files', 'public') ) {
10962         $dbh->do(q{
10963             ALTER TABLE uploaded_files
10964                 ADD COLUMN public tinyint,
10965                 ADD COLUMN permanent tinyint
10966         });
10967         $dbh->do(q{
10968             UPDATE uploaded_files SET public=1, permanent=1
10969         });
10970         $dbh->do(q{
10971             ALTER TABLE uploaded_files
10972                 CHANGE COLUMN categorycode uploadcategorycode tinytext
10973         });
10974     }
10975     print "Upgrade to $DBversion done (Bug 14321: Merge UploadedFile and UploadedFiles into Koha::Upload)\n";
10976     SetVersion($DBversion);
10977 }
10978
10979 $DBversion = "3.21.00.029";
10980 if ( CheckVersion($DBversion) ) {
10981     unless ( column_exists('discharges', 'discharge_id') ) {
10982         $dbh->do(q{
10983             ALTER TABLE discharges
10984                 ADD COLUMN discharge_id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10985         });
10986     }
10987     print "Upgrade to $DBversion done (Bug 14368: Add discharges history)\n";
10988     SetVersion($DBversion);
10989 }
10990
10991 $DBversion = "3.21.00.030";
10992 if ( CheckVersion($DBversion) ) {
10993     $dbh->do(q{
10994         UPDATE marc_subfield_structure
10995         SET value_builder='marc21_leader.pl'
10996         WHERE value_builder='marc21_leader_book.pl'
10997     });
10998     $dbh->do(q{
10999         UPDATE marc_subfield_structure
11000         SET value_builder='marc21_leader.pl'
11001         WHERE value_builder='marc21_leader_computerfile.pl'
11002     });
11003     $dbh->do(q{
11004         UPDATE marc_subfield_structure
11005         SET value_builder='marc21_leader.pl'
11006         WHERE value_builder='marc21_leader_video.pl'
11007     });
11008     print "Upgrade to $DBversion done (Bug 14201: Remove unused code or template from some MARC21 leader plugins )\n";
11009     SetVersion($DBversion);
11010 }
11011
11012 $DBversion = "3.21.00.031";
11013 if ( CheckVersion($DBversion) ) {
11014     $dbh->do(q{
11015         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
11016         VALUES
11017             ('SMSSendPassword', '', '', 'Password used to send SMS messages', 'free'),
11018             ('SMSSendUsername', '', '', 'Username/Login used to send SMS messages', 'free')
11019     });
11020     print "Upgrade to $DBversion done (Bug 14820: SMSSendUsername and SMSSendPassword are not listed in the system preferences)\n";
11021     SetVersion($DBversion);
11022 }
11023
11024 $DBversion = "3.21.00.032";
11025 if ( CheckVersion($DBversion) ) {
11026     $dbh->do(q{
11027         CREATE TABLE additional_fields (
11028             id int(11) NOT NULL AUTO_INCREMENT,
11029             tablename varchar(255) NOT NULL DEFAULT '',
11030             name varchar(255) NOT NULL DEFAULT '',
11031             authorised_value_category varchar(16) NOT NULL DEFAULT '',
11032             marcfield varchar(16) NOT NULL DEFAULT '',
11033             searchable tinyint(1) NOT NULL DEFAULT '0',
11034             PRIMARY KEY (id),
11035             UNIQUE KEY fields_uniq (tablename,name)
11036         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
11037     });
11038     $dbh->do(q{
11039         CREATE TABLE additional_field_values (
11040             id int(11) NOT NULL AUTO_INCREMENT,
11041             field_id int(11) NOT NULL,
11042             record_id int(11) NOT NULL,
11043             value varchar(255) NOT NULL DEFAULT '',
11044             PRIMARY KEY (id),
11045             UNIQUE KEY field_record (field_id,record_id),
11046             CONSTRAINT afv_fk FOREIGN KEY (field_id) REFERENCES additional_fields (id) ON DELETE CASCADE ON UPDATE CASCADE
11047         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
11048     });
11049     print "Upgrade to $DBversion done (Bug 10855: Additional fields for subscriptions)\n";
11050     SetVersion($DBversion);
11051 }
11052
11053 $DBversion = "3.21.00.033";
11054 if ( CheckVersion($DBversion) ) {
11055
11056     my $done = 0;
11057     my $count_ethnicity = $dbh->selectrow_arrayref(q|
11058         SELECT COUNT(*) FROM ethnicity
11059     |);
11060     my $count_borrower_modifications = $dbh->selectrow_arrayref(q|
11061         SELECT COUNT(*)
11062         FROM borrower_modifications
11063         WHERE ethnicity IS NOT NULL
11064             OR ethnotes IS NOT NULL
11065     |);
11066     my $count_borrowers = $dbh->selectrow_arrayref(q|
11067         SELECT COUNT(*)
11068         FROM borrowers
11069         WHERE ethnicity IS NOT NULL
11070             OR ethnotes IS NOT NULL
11071     |);
11072     # We don't care about the ethnicity of the deleted borrowers, right?
11073     if ( $count_ethnicity->[0] == 0
11074             and $count_borrower_modifications->[0] == 0
11075             and $count_borrowers->[0] == 0
11076     ) {
11077         $dbh->do(q|
11078             DROP TABLE ethnicity
11079         |);
11080         $dbh->do(q|
11081             ALTER TABLE borrower_modifications
11082             DROP COLUMN ethnicity,
11083             DROP COLUMN ethnotes
11084         |);
11085         $dbh->do(q|
11086             ALTER TABLE borrowers
11087             DROP COLUMN ethnicity,
11088             DROP COLUMN ethnotes
11089         |);
11090         $dbh->do(q|
11091             ALTER TABLE deletedborrowers
11092             DROP COLUMN ethnicity,
11093             DROP COLUMN ethnotes
11094         |);
11095         $done = 1;
11096     }
11097     if ( $done ) {
11098         print "Upgrade to $DBversion done (Bug 10020: Drop table ethnicity and columns ethnicity and ethnotes)\n";
11099     }
11100     else {
11101         print "Upgrade to $DBversion done (Bug 10020: This database contains data related to 'ethnicity'. No change will be done on the DB structure but note that the Koha codebase does not use it)\n";
11102     }
11103
11104     SetVersion ($DBversion);
11105 }
11106
11107 $DBversion = "3.21.00.034";
11108 if ( CheckVersion($DBversion) ) {
11109     $dbh->do(q{
11110         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11111         VALUES('MembershipExpiryDaysNotice',NULL,'Send an account expiration notice that a patron''s card is about to expire after',NULL,'Integer')
11112     });
11113     $dbh->do(q{
11114         INSERT IGNORE INTO letter (module, code, branchcode, name, title, content, message_transport_type)
11115         VALUES('members','MEMBERSHIP_EXPIRY','','Account expiration','Account expiration','Dear <<borrowers.title>> <<borrowers.firstname>> <<borrowers.surname>>,\r\n\r\nYour library card will expire soon, on:\r\n\r\n<<borrowers.dateexpiry>>\r\n\r\nThank you,\r\n\r\nLibrarian\r\n\r\n<<branches.branchname>>', 'email')
11116     });
11117     print "Upgrade to $DBversion done (Bug 6810: Send membership expiry reminder notices)\n";
11118     SetVersion($DBversion);
11119 }
11120
11121 $DBversion = "3.21.00.035";
11122 if ( CheckVersion($DBversion) ) {
11123     $dbh->do(q|
11124         ALTER TABLE branch_borrower_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11125     |);
11126     $dbh->do(q|
11127         UPDATE branch_borrower_circ_rules SET maxonsiteissueqty = maxissueqty;
11128     |);
11129     $dbh->do(q|
11130         ALTER TABLE default_borrower_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11131     |);
11132     $dbh->do(q|
11133         UPDATE default_borrower_circ_rules SET maxonsiteissueqty = maxissueqty;
11134     |);
11135     $dbh->do(q|
11136         ALTER TABLE default_branch_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11137     |);
11138     $dbh->do(q|
11139         UPDATE default_branch_circ_rules SET maxonsiteissueqty = maxissueqty;
11140     |);
11141     $dbh->do(q|
11142         ALTER TABLE default_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11143     |);
11144     $dbh->do(q|
11145         UPDATE default_circ_rules SET maxonsiteissueqty = maxissueqty;
11146     |);
11147     $dbh->do(q|
11148         ALTER TABLE issuingrules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11149     |);
11150     $dbh->do(q|
11151         UPDATE issuingrules SET maxonsiteissueqty = maxissueqty;
11152     |);
11153     $dbh->do(q|
11154         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11155         VALUES ('ConsiderOnSiteCheckoutsAsNormalCheckouts','1',NULL,'Consider on-site checkouts as normal checkouts','YesNo');
11156     |);
11157
11158     print "Upgrade to $DBversion done (Bug 14045: Add DB fields maxonsiteissueqty and pref ConsiderOnSiteCheckoutsAsNormalCheckouts)\n";
11159     SetVersion ($DBversion);
11160 }
11161
11162 $DBversion = "3.21.00.036";
11163 if ( CheckVersion($DBversion) ) {
11164    $dbh->do(q{
11165         ALTER TABLE authorised_values_branches
11166         DROP FOREIGN KEY authorised_values_branches_ibfk_1,
11167         DROP FOREIGN KEY authorised_values_branches_ibfk_2
11168     });
11169     $dbh->do(q{
11170         ALTER TABLE authorised_values_branches
11171         MODIFY av_id INT( 11 ) NOT NULL,
11172         MODIFY branchcode VARCHAR( 10 ) NOT NULL,
11173         ADD FOREIGN KEY (`av_id`) REFERENCES `authorised_values` (`id`) ON DELETE CASCADE,
11174         ADD FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE
11175    });
11176    print "Upgrade to $DBversion done (Bug 10363: There is no package for authorised values)\n";
11177    SetVersion($DBversion);
11178 }
11179
11180 $DBversion = "3.21.00.037";
11181 if ( CheckVersion($DBversion) ) {
11182    $dbh->do(q{
11183        INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11184        VALUES ('OverduesBlockRenewing','allow','If any of a patron checked out documents is late, should renewal be allowed, blocked only on overdue items or blocked on whatever checked out document','allow|blockitem|block','Choice')
11185    });
11186    $dbh->do(q{
11187        INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11188        VALUES ('RestrictionBlockRenewing','0','If patron is restricted, should renewal be allowed or blocked',NULL,'YesNo')
11189     });
11190    print "Upgrade to $DBversion done (Bug 8236: Prevent renewing if overdue or restriction)\n";
11191    SetVersion($DBversion);
11192 }
11193
11194 $DBversion = "3.21.00.038";
11195 if ( CheckVersion($DBversion) ) {
11196     $dbh->do(q|
11197         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11198         VALUES ('BatchCheckouts','0','','Enable or disable batch checkouts','YesNo')
11199     |);
11200     $dbh->do(q|
11201         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11202         VALUES ('BatchCheckoutsValidCategories','',NULL,'Patron categories allowed to checkout in a batch','Free')
11203     |);
11204     print "Upgrade to $DBversion done (Bug 11759: Add the batch checkout feature)\n";
11205     SetVersion($DBversion);
11206 }
11207
11208 $DBversion = "3.21.00.039";
11209 if ( CheckVersion($DBversion) ) {
11210     $dbh->do(q|
11211         ALTER TABLE creator_layouts ADD COLUMN oblique_title INT(1) NULL DEFAULT 1 AFTER guidebox
11212     |);
11213     print "Upgrade to $DBversion done (Bug 12194: Add column oblique_title to layouts)\n";
11214     SetVersion($DBversion);
11215 }
11216
11217 $DBversion = "3.21.00.040";
11218 if ( CheckVersion($DBversion) ) {
11219     $dbh->do(q{
11220         ALTER TABLE itemtypes
11221             ADD hideinopac TINYINT(1) NOT NULL DEFAULT 0
11222               AFTER sip_media_type,
11223             ADD searchcategory VARCHAR(80) DEFAULT NULL
11224               AFTER hideinopac;
11225     });
11226     print "Upgrade to $DBversion done (Bug 10937: Option to hide and group itemtypes from advanced search)\n";
11227     SetVersion($DBversion);
11228 }
11229
11230 $DBversion = "3.21.00.041";
11231 if ( CheckVersion($DBversion) ) {
11232     $dbh->do(q|
11233         ALTER TABLE issuingrules
11234             ADD chargeperiod_charge_at BOOLEAN NOT NULL DEFAULT  '0' AFTER chargeperiod
11235     |);
11236     print "Upgrade to $DBversion done (Bug 13590: Add ability to charge fines at start of charge period)\n";
11237     SetVersion($DBversion);
11238 }
11239
11240 $DBversion = "3.21.00.042";
11241 if ( CheckVersion($DBversion) ) {
11242     $dbh->do(q|
11243         ALTER TABLE items_search_fields
11244             MODIFY COLUMN authorised_values_category VARCHAR(32) DEFAULT NULL
11245     |);
11246     print "Upgrade to $DBversion done (Bug 15069: items_search_fields.authorised_values_category is still a varchar(32))\n";
11247     SetVersion($DBversion);
11248 }
11249
11250 $DBversion = "3.21.00.043";
11251 if ( CheckVersion($DBversion) ) {
11252     $dbh->do(q|
11253         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11254         VALUES ('EnableAdvancedCatalogingEditor','0','','Enable the Rancor advanced cataloging editor','YesNo')
11255     |);
11256     print "Upgrade to $DBversion done (Bug 11559: Professional cataloger's interface)\n";
11257     SetVersion($DBversion);
11258 }
11259
11260 $DBversion = "3.21.00.044";
11261 if ( CheckVersion($DBversion) ) {
11262     $dbh->do(q|
11263         CREATE TABLE localization (
11264             localization_id int(11) NOT NULL AUTO_INCREMENT,
11265             entity varchar(16) COLLATE utf8_unicode_ci NOT NULL,
11266             code varchar(64) COLLATE utf8_unicode_ci NOT NULL,
11267             lang varchar(25) COLLATE utf8_unicode_ci NOT NULL,
11268             translation text COLLATE utf8_unicode_ci,
11269             PRIMARY KEY (localization_id),
11270             UNIQUE KEY entity_code_lang (entity,code,lang)
11271         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
11272     |);
11273     print "Upgrade to $DBversion done (Bug 14100: Generic solution for language overlay)\n";
11274     SetVersion($DBversion);
11275 }
11276
11277 $DBversion = "3.21.00.045";
11278 if ( CheckVersion($DBversion) ) {
11279     $dbh->do(q|
11280         ALTER TABLE opac_news
11281             ADD borrowernumber int(11) default NULL
11282                 AFTER number
11283     |);
11284     $dbh->do(q|
11285         ALTER TABLE opac_news
11286             ADD CONSTRAINT borrowernumber_fk
11287                 FOREIGN KEY (borrowernumber)
11288                 REFERENCES borrowers (borrowernumber)
11289                 ON DELETE SET NULL ON UPDATE CASCADE
11290     |);
11291     print "Upgrade to $DBversion done (Bug 14246: (newsauthor) Add borrowernumber to koha_news)\n";
11292     SetVersion($DBversion);
11293 }
11294
11295 $DBversion = "3.21.00.046";
11296 if ( CheckVersion($DBversion) ) {
11297     $dbh->do(q{
11298         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11299         VALUES ('NewsAuthorDisplay','none','none|opac|staff|both','Display the author name for news items.','Choice')
11300     });
11301     print "Upgrade to $DBversion done (Bug 14247: (newsauthor) System preference for news author display)\n";
11302     SetVersion($DBversion);
11303 }
11304
11305 $DBversion = "3.21.00.047";
11306 if(CheckVersion($DBversion)) {
11307     $dbh->do(q{
11308         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11309         VALUES ('IndependentBranchesPatronModifications','0','Show only modification request for the logged in branch','','YesNo')
11310     });
11311     print "Upgrade to $DBversion done (Bug 10904: Limit patron update request management by branch)\n";
11312     SetVersion($DBversion);
11313 }
11314
11315 $DBversion = '3.21.00.048';
11316 if ( CheckVersion($DBversion) ) {
11317     my $create_table_issues = @{ $dbh->selectall_arrayref(q|SHOW CREATE TABLE issues|) }[0]->[1];
11318     if ($create_table_issues !~ m|UNIQUE KEY.*itemnumber| ) {
11319         $dbh->do(q|ALTER TABLE issues ADD CONSTRAINT UNIQUE KEY (itemnumber)|);
11320     }
11321     print "Upgrade to $DBversion done (Bug 14978: Make sure issues.itemnumber is a unique key)\n";
11322     SetVersion($DBversion);
11323 }
11324
11325 $DBversion = "3.21.00.049";
11326 if ( CheckVersion($DBversion) ) {
11327     $dbh->do(q{UPDATE systempreferences SET variable = 'AudioAlerts' WHERE variable = 'soundon'});
11328
11329     $dbh->do(q{
11330         CREATE TABLE audio_alerts (
11331             id int(11) NOT NULL AUTO_INCREMENT,
11332             precedence smallint(5) unsigned NOT NULL,
11333             selector varchar(255) NOT NULL,
11334             sound varchar(255) NOT NULL,
11335             PRIMARY KEY (id),
11336             KEY precedence (precedence)
11337         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
11338     });
11339
11340     $dbh->do(q{
11341         INSERT IGNORE INTO audio_alerts VALUES
11342         (1, 1, '.audio-alert-action', 'opening.ogg'),
11343         (2, 2, '.audio-alert-warning', 'critical.ogg'),
11344         (3, 3, '.audio-alert-success', 'beep.ogg');
11345     });
11346
11347     print "Upgrade to $DBversion done (Bug 11431: Add additional sound options for warnings)\n";
11348     SetVersion($DBversion);
11349 }
11350
11351 $DBversion = "3.21.00.050";
11352 if(CheckVersion($DBversion)) {
11353     $dbh->do(q{
11354         INSERT INTO letter ( module, code, branchcode, name, is_html, title, content, message_transport_type )
11355         VALUES ( 'circulation', 'OVERDUES_SLIP', '', 'Overdues Slip', '0', 'OVERDUES_SLIP', 'The following item(s) is/are currently overdue:
11356
11357 <item>"<<biblio.title>>" by <<biblio.author>>, <<items.itemcallnumber>>, Barcode: <<items.barcode>> Fine: <<items.fine>></item>
11358 ', 'print' )
11359     });
11360     print "Upgrade to $DBversion done (Bug 12933: Add ability to print overdue slip from staff intranet)\n";
11361     SetVersion($DBversion);
11362 }
11363
11364 $DBversion = "3.21.00.051";
11365 if ( CheckVersion($DBversion) ) {
11366     $dbh->do(q{
11367         ALTER TABLE virtualshelves
11368             CHANGE COLUMN sortfield sortfield VARCHAR(16) DEFAULT 'title'
11369     });
11370     $dbh->do(q{
11371         UPDATE virtualshelves
11372         SET sortfield='title'
11373             WHERE sortfield IS NULL;
11374     });
11375     print "Upgrade to $DBversion done (Bug 14544: Move the list related code to Koha::Virtualshelves)\n";
11376     SetVersion($DBversion);
11377 }
11378
11379 $DBversion = "3.21.00.052";
11380 if ( CheckVersion($DBversion) ) {
11381     $dbh->do(q{
11382         ALTER TABLE serial
11383             ADD COLUMN publisheddatetext VARCHAR(100) DEFAULT NULL AFTER publisheddate
11384     });
11385     print "Upgrade to $DBversion done (Bug 8296: Add descriptive (text) published date field for serials)\n";
11386     SetVersion($DBversion);
11387 }
11388
11389 $DBversion = "3.21.00.053";
11390 if ( CheckVersion($DBversion) ) {
11391     my $query = q{ SELECT * FROM itemtypes ORDER BY description };
11392     my $sth   = C4::Context->dbh->prepare($query);
11393     $sth->execute;
11394     my $suggestion_formats = $sth->fetchall_arrayref( {} );
11395
11396     foreach my $format (@$suggestion_formats) {
11397         $dbh->do(
11398             q|
11399             INSERT IGNORE INTO authorised_values (category, authorised_value, lib, lib_opac, imageurl)
11400             VALUES (?, ?, ?, ?, ?)
11401         |, {},
11402             'SUGGEST_FORMAT', $format->{itemtype}, $format->{description}, $format->{description},
11403             $format->{imageurl}
11404         );
11405     }
11406     print "Upgrade to $DBversion done (Bug 9468: create new SUGGEST_FORMAT authorised_value list)\n";
11407     SetVersion($DBversion);
11408 }
11409
11410 $DBversion = "3.21.00.054";
11411 if(CheckVersion($DBversion)) {
11412     $dbh->do(q{
11413         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11414         VALUES('MergeReportFields','','Displayed fields for deleted MARC records after merge',NULL,'Free')
11415     });
11416     print "Upgrade to $DBversion done (Bug 8064: Merge several biblio records)\n";
11417     SetVersion($DBversion);
11418 }
11419
11420 $DBversion = "3.21.00.055";
11421 if ( CheckVersion($DBversion) ) {
11422     print "Upgrade to $DBversion done (Koha 3.22 beta)\n";
11423     SetVersion($DBversion);
11424 }
11425
11426 $DBversion = "3.21.00.056";
11427 if(CheckVersion($DBversion)) {
11428     $dbh->do(q{
11429         UPDATE systempreferences
11430         SET
11431             options='metric|us|iso|dmydot',
11432             explanation='Define global date format (us mm/dd/yyyy, metric dd/mm/yyy, ISO yyyy-mm-dd, DMY separated by dots dd.mm.yyyy)'
11433         WHERE variable='dateformat'
11434     });
11435     print "Upgrade to $DBversion done (Bug 12072: New dateformat dd.mm.yyyy)\n";
11436     SetVersion($DBversion);
11437 }
11438
11439 $DBversion = "3.22.00.000";
11440 if ( CheckVersion($DBversion) ) {
11441     print "Upgrade to $DBversion done (Koha 3.22)\n";
11442     SetVersion($DBversion);
11443 }
11444
11445 $DBversion = "3.23.00.000";
11446 if ( CheckVersion($DBversion) ) {
11447     print "Upgrade to $DBversion done (The year of the monkey will be here soon.)\n";
11448     SetVersion ($DBversion);
11449 }
11450
11451 $DBversion = "3.23.00.001";
11452 if(CheckVersion($DBversion)) {
11453     $dbh->do(q{
11454         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11455         VALUES (
11456             'DefaultToLoggedInLibraryCircRules',  '0', NULL ,  'If enabled, circ rules editor will default to the logged in library''s rules, rather than the ''all libraries'' rules.',  'YesNo'
11457         ), (
11458             'DefaultToLoggedInLibraryNoticesSlips',  '0', NULL ,  'If enabled,slips and notices editor will default to the logged in library''s rules, rather than the ''all libraries'' rules.',  'YesNo'
11459         )
11460     });
11461
11462     print "Upgrade to $DBversion done (Bug 11625 - Add pref DefaultToLoggedInLibraryCircRules and DefaultToLoggedInLibraryNoticesSlips)\n";
11463     SetVersion($DBversion);
11464 }
11465
11466 $DBversion = "3.23.00.002";
11467 if(CheckVersion($DBversion)) {
11468     $dbh->do(q{
11469         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11470         VALUES ('DefaultToLoggedInLibraryOverdueTriggers',  '0', NULL,  'If enabled, overdue status triggers editor will default to the logged in library''s rules, rather than the ''default'' rules.',  'YesNo')
11471     });
11472
11473     print "Upgrade to $DBversion done (Bug 11747 - add pref DefaultToLoggedInLibraryOverdueTriggers)\n";
11474     SetVersion($DBversion);
11475 }
11476
11477 $DBversion = "3.23.00.003";
11478 if(CheckVersion($DBversion)) {
11479     $dbh->do(q{
11480         UPDATE letter SET name = "Hold Slip" WHERE name = "Reserve Slip"
11481     });
11482     $dbh->do(q{
11483         UPDATE letter SET title = "Hold Slip" WHERE title = "Reserve Slip";
11484     });
11485
11486     print "Upgrade to $DBversion done (Bug 8085 - Rename 'Reserve slip' to 'Hold slip')\n";
11487     SetVersion($DBversion);
11488 }
11489
11490 $DBversion = "3.23.00.004";
11491 if ( CheckVersion($DBversion) ) {
11492     $dbh->do(q{
11493         DROP TABLE IF EXISTS `stopwords`;
11494     });
11495     print "Upgrade to $DBversion done (Bug 9819 - stopwords related code should be removed)\n";
11496     SetVersion($DBversion);
11497 }
11498
11499 $DBversion = "3.23.00.005";
11500 if ( CheckVersion($DBversion) ) {
11501     $dbh->do(q{
11502         UPDATE permissions SET description = 'Manage circulation rules' WHERE description = 'manage circulation rules'
11503     });
11504     $dbh->do(q{
11505         UPDATE permissions SET description = 'Manage staged MARC records, including completing and reversing imports' WHERE description = 'Managed staged MARC records, including completing and reversing imports'
11506     });
11507     print "Upgrade to $DBversion done (Bug 11569 - Typo in userpermissions.sql)\n";
11508     SetVersion($DBversion);
11509 }
11510 $DBversion = "3.23.00.006";
11511 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
11512    $dbh->do("
11513        ALTER TABLE serial
11514         ADD serialseq_x VARCHAR( 100 ) NULL DEFAULT NULL AFTER serialseq,
11515         ADD serialseq_y VARCHAR( 100 ) NULL DEFAULT NULL AFTER serialseq_x,
11516         ADD serialseq_z VARCHAR( 100 ) NULL DEFAULT NULL AFTER serialseq_y
11517    ");
11518
11519     my $sth = $dbh->prepare("SELECT * FROM subscription");
11520     $sth->execute();
11521
11522     my $sth2 = $dbh->prepare("SELECT * FROM subscription_numberpatterns WHERE id = ?");
11523
11524     my $sth3 = $dbh->prepare("UPDATE serial SET serialseq_x = ?, serialseq_y = ?, serialseq_z = ? WHERE serialid = ?");
11525
11526     foreach my $subscription ( $sth->fetchrow_hashref() ) {
11527         next if !defined($subscription);
11528         $sth2->execute( $subscription->{numberpattern} );
11529         my $number_pattern = $sth2->fetchrow_hashref();
11530
11531         my $numbering_method = $number_pattern->{numberingmethod};
11532         # Get all the data between the enumeration values, we need
11533         # to split each enumeration string based on these values.
11534         my @splits = split( /\{[XYZ]\}/, $numbering_method );
11535         # Get the order in which the X Y and Z values are used
11536         my %indexes;
11537         foreach my $i (qw(X Y Z)) {
11538             $indexes{$i} = index( $numbering_method, "{$i}" );
11539             delete $indexes{$i} if $indexes{$i} == -1;
11540         }
11541         my @indexes = sort { $indexes{$a} <=> $indexes{$b} } keys(%indexes);
11542
11543         my @serials = @{
11544             $dbh->selectall_arrayref(
11545                 "SELECT * FROM serial WHERE subscriptionid = $subscription->{subscriptionid}",
11546                 { Slice => {} }
11547             )
11548         };
11549
11550         foreach my $serial (@serials) {
11551             my $serialseq = $serial->{serialseq};
11552             my %enumeration_data;
11553
11554             ## We cannot split on multiple values at once,
11555             ## so let's replace each of those values with __SPLIT__
11556             if (@splits) {
11557                 for my $split_item (@splits) {
11558                     my $quoted_split = quotemeta($split_item);
11559                     $serialseq =~ s/$quoted_split/__SPLIT__/;
11560                 }
11561                 (
11562                     undef,
11563                     $enumeration_data{ $indexes[0] // q{} },
11564                     $enumeration_data{ $indexes[1] // q{} },
11565                     $enumeration_data{ $indexes[2] // q{} }
11566                 ) = split( /__SPLIT__/, $serialseq );
11567             }
11568             else
11569             {    ## Nothing to split on means the only thing in serialseq is a single placeholder e.g. {X}
11570                 $enumeration_data{ $indexes[0] } = $serialseq;
11571             }
11572
11573             $sth3->execute(
11574                     $enumeration_data{'X'},
11575                     $enumeration_data{'Y'},
11576                     $enumeration_data{'Z'},
11577                     $serial->{serialid},
11578             );
11579         }
11580     }
11581
11582     print "Upgrade to $DBversion done ( Bug 8956 - Split serials enumeration data into separate fields )\n";
11583     SetVersion($DBversion);
11584 }
11585
11586 $DBversion = "3.23.00.007";
11587 if ( CheckVersion($DBversion) ) {
11588     $dbh->do("SET FOREIGN_KEY_CHECKS=0");
11589     $dbh->do("ALTER TABLE overduerules RENAME old_overduerules");
11590     $dbh->do("CREATE TABLE overduerules (
11591         `overduerules_id` int(11) NOT NULL AUTO_INCREMENT,
11592         `branchcode` varchar(10) NOT NULL DEFAULT '',
11593         `categorycode` varchar(10) NOT NULL DEFAULT '',
11594         `delay1` int(4) DEFAULT NULL,
11595         `letter1` varchar(20) DEFAULT NULL,
11596         `debarred1` varchar(1) DEFAULT '0',
11597         `delay2` int(4) DEFAULT NULL,
11598         `debarred2` varchar(1) DEFAULT '0',
11599         `letter2` varchar(20) DEFAULT NULL,
11600         `delay3` int(4) DEFAULT NULL,
11601         `letter3` varchar(20) DEFAULT NULL,
11602         `debarred3` int(1) DEFAULT '0',
11603         PRIMARY KEY (`overduerules_id`),
11604         UNIQUE KEY `overduerules_branch_cat` (`branchcode`,`categorycode`)
11605         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
11606     $dbh->do("INSERT INTO overduerules(branchcode, categorycode, delay1, letter1, debarred1, delay2, debarred2, letter2, delay3, letter3, debarred3) SELECT * FROM old_overduerules");
11607     $dbh->do("DROP TABLE old_overduerules");
11608     $dbh->do("ALTER TABLE overduerules_transport_types
11609               ADD COLUMN overduerules_id int(11) NOT NULL");
11610     my $mtts = $dbh->selectall_arrayref("SELECT * FROM overduerules_transport_types", { Slice => {} });
11611     $dbh->do("DELETE FROM overduerules_transport_types");
11612     $dbh->do("ALTER TABLE overduerules_transport_types
11613               DROP FOREIGN KEY overduerules_fk,
11614               ADD FOREIGN KEY overduerules_transport_types_fk (overduerules_id) REFERENCES overduerules (overduerules_id) ON DELETE CASCADE ON UPDATE CASCADE,
11615               DROP COLUMN branchcode,
11616               DROP COLUMN categorycode");
11617     my $s = $dbh->prepare("INSERT INTO overduerules_transport_types (overduerules_id, id, letternumber, message_transport_type) "
11618                          ." VALUES((SELECT overduerules_id FROM overduerules WHERE branchcode = ? AND categorycode = ?),?,?,?)");
11619     foreach my $mtt(@$mtts){
11620         $s->execute($mtt->{branchcode}, $mtt->{categorycode}, $mtt->{id}, $mtt->{letternumber}, $mtt->{message_transport_type} );
11621     }
11622     $dbh->do("SET FOREIGN_KEY_CHECKS=1");
11623
11624     print "Upgrade to $DBversion done (Bug 13624 - Remove columns branchcode, categorytype from table overduerules_transport_types)\n";
11625     SetVersion($DBversion);
11626 }
11627
11628 $DBversion = "3.23.00.008";
11629 if ( CheckVersion($DBversion) ) {
11630
11631     $dbh->do(q{ALTER TABLE borrowers ADD privacy_guarantor_checkouts BOOLEAN NOT NULL DEFAULT '0' AFTER privacy});
11632
11633     $dbh->do(q{ALTER TABLE deletedborrowers ADD privacy_guarantor_checkouts BOOLEAN NOT NULL DEFAULT '0' AFTER privacy});
11634
11635     $dbh->do(q{
11636         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type )
11637         VALUES (
11638             'AllowStaffToSetCheckoutsVisibilityForGuarantor',  '0', NULL,
11639             'If enabled, library staff can set a patron''s checkouts to be visible to linked patrons from the opac.',  'YesNo'
11640         ), (
11641             'AllowPatronToSetCheckoutsVisibilityForGuarantor',  '0', NULL,
11642             'If enabled, the patron can set checkouts to be visible to  his or her guarantor',  'YesNo'
11643         )
11644     });
11645
11646     print "Upgrade to $DBversion done (Bug 9303 - relative's checkouts in the opac)\n";
11647     SetVersion($DBversion);
11648 }
11649
11650 $DBversion = "3.23.00.009";
11651 if ( CheckVersion($DBversion) ) {
11652     $dbh->do(q{
11653         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type ) VALUES
11654         ( 'EnablePayPalOpacPayments',  '0', NULL ,  'Enables the ability to pay fees and fines from  the OPAC via PayPal',  'YesNo' ),
11655         ( 'PayPalChargeDescription',  'Koha fee payment', NULL ,  'This preference defines what the user will see the charge listed as in PayPal',  'Free' ),
11656         ( 'PayPalPwd',  '', NULL ,  'Your PayPal API password',  'Free' ),
11657         ( 'PayPalSandboxMode',  '1', NULL ,  'If enabled, the system will use PayPal''s sandbox server for testing, rather than the production server.',  'YesNo' ),
11658         ( 'PayPalSignature',  '', NULL ,  'Your PayPal API signature',  'Free' ),
11659         ( 'PayPalUser',  '', NULL ,  'Your PayPal API username ( email address )',  'Free' )
11660     });
11661
11662     print "Upgrade to $DBversion done (Bug 11622 - Add ability to pay fees and fines from OPAC via PayPal)\n";
11663     SetVersion($DBversion);
11664 }
11665
11666 $DBversion = "3.23.00.010";
11667 if ( CheckVersion($DBversion) ) {
11668     $dbh->do(q{
11669         ALTER TABLE issuingrules ADD cap_fine_to_replacement_price BOOLEAN NOT NULL DEFAULT '0' AFTER overduefinescap
11670     });
11671
11672     print "Upgrade to $DBversion done (Bug 9129 - Add the ability to set the maximum fine for an item to its replacement price)\n";
11673     SetVersion($DBversion);
11674 }
11675
11676 $DBversion = "3.23.00.011";
11677 if ( CheckVersion($DBversion) ) {
11678     $dbh->do(q{
11679         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES ('HoldFeeMode','not_always','always|not_always','Set the hold fee mode','Choice')
11680     });
11681
11682     print "Upgrade to $DBversion done (Bug 13592 - Hold fee not being applied on placing a hold)\n";
11683     SetVersion($DBversion);
11684 }
11685
11686 $DBversion = "3.23.00.012";
11687 if ( CheckVersion($DBversion) ) {
11688     $dbh->do(q{
11689         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `explanation`, `options`, `type` ) VALUES('MaxSearchResultsItemsPerRecordStatusCheck','20','Max number of items per record for which to check transit and hold status','','Integer')
11690     });
11691
11692     print "Upgrade to $DBversion done (Bug 15380 - Move the authority types related code to Koha::Authority::Type[s] - part 1)\n";
11693     SetVersion($DBversion);
11694 }
11695
11696 $DBversion = "3.23.00.013";
11697 if ( CheckVersion($DBversion) ) {
11698     $dbh->do(q{
11699         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES ('StoreLastBorrower','0','','If ON, the last borrower to return an item will be stored in items.last_returned_by','YesNo')
11700     });
11701     $dbh->do(q{
11702         CREATE TABLE IF NOT EXISTS `items_last_borrower` (
11703   `id` int(11) NOT NULL AUTO_INCREMENT,
11704   `itemnumber` int(11) NOT NULL,
11705   `borrowernumber` int(11) NOT NULL,
11706   `created_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
11707   PRIMARY KEY (`id`),
11708   UNIQUE KEY `itemnumber` (`itemnumber`),
11709   KEY `borrowernumber` (`borrowernumber`),
11710   CONSTRAINT `items_last_borrower_ibfk_2` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
11711   CONSTRAINT `items_last_borrower_ibfk_1` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE
11712 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
11713     });
11714
11715     print "Upgrade to $DBversion done (Bug 14945 - Add the ability to store the last patron to return an item)\n";
11716     SetVersion($DBversion);
11717
11718 }
11719
11720 $DBversion = "3.23.00.014";
11721 if ( CheckVersion($DBversion) ) {
11722     $dbh->do(q{
11723         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
11724 VALUES ('ClaimsBccCopy','0','','Bcc the ClaimAcquisition and ClaimIssues alerts','YesNo')
11725     });
11726
11727     print "Upgrade to $DBversion done (Bug 10076 - Add Bcc syspref for claimacquisition and clamissues)\n";
11728     SetVersion($DBversion);
11729 }
11730
11731 $DBversion = "3.23.00.015";
11732 if ( CheckVersion($DBversion) ) {
11733     $dbh->do(q{
11734         UPDATE letter SET code = "HOLD_SLIP" WHERE code = "RESERVESLIP";
11735     });
11736
11737     print "Upgrade to $DBversion done (Bug 15443 - Re-code RESERVESLIP as HOLD_SLIP)\n";
11738     SetVersion($DBversion);
11739 }
11740
11741 $DBversion = "3.23.00.016";
11742 if ( CheckVersion($DBversion) ) {
11743     $dbh->do(q{
11744     INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
11745     VALUES ('OpacResetPassword',  '0','','Shows the ''Forgot your password?'' link in the OPAC','YesNo');
11746 });
11747     $dbh->do(q{
11748     CREATE TABLE IF NOT EXISTS borrower_password_recovery (
11749       borrowernumber int(11) NOT NULL,
11750       uuid varchar(128) NOT NULL,
11751       valid_until timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
11752       PRIMARY KEY (borrowernumber),
11753       KEY borrowernumber (borrowernumber)
11754     ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
11755 });
11756     $dbh->do(q{
11757     INSERT IGNORE INTO `letter` (module, code, branchcode, name, is_html, title, content, message_transport_type)
11758     VALUES ('members','PASSWORD_RESET','','Online password reset',1,'Koha password recovery','<html>\r\n<p>This email has been sent in response to your password recovery request for the account <strong><<user>></strong>.\r\n</p>\r\n<p>\r\nYou can now create your new password using the following link:\r\n<br/><a href=\"<<passwordreseturl>>\"><<passwordreseturl>></a>\r\n</p>\r\n<p>This link will be valid for 2 days from this email\'s reception, then you must reapply if you do not change your password.</p>\r\n<p>Thank you.</p>\r\n</html>\r\n','email');
11759
11760     });
11761
11762     print "Upgrade to $DBversion done (Bug 8753 - Add forgot password link to OPAC)\n";
11763     SetVersion($DBversion);
11764 }
11765
11766 $DBversion = "3.23.00.017";
11767 if ( CheckVersion($DBversion) ) {
11768
11769 $dbh->do(q{
11770     DELETE FROM uploaded_files
11771     WHERE COALESCE(permanent,0)=0 AND dir='koha_upload'
11772 });
11773
11774 my $tmp = C4::Context->temporary_directory . '/koha_upload';
11775 remove_tree( $tmp ) if -d $tmp;
11776
11777     print "Upgrade to $DBversion done (Bug 14893 - Separate temporary storage per instance in Upload.pm)\n";
11778     SetVersion($DBversion);
11779
11780 }
11781
11782 $DBversion = "3.23.00.018";
11783 if ( CheckVersion($DBversion) ) {
11784     $dbh->do(q{
11785         UPDATE systempreferences SET value="0" where type="YesNo" and value="";
11786     });
11787
11788     print "Upgrade to $DBversion done (Bug 15446 - Fix systempreferences rows where type=YesNo and value='')\n";
11789     SetVersion($DBversion);
11790 }
11791
11792 $DBversion = "3.23.00.019";
11793 if ( CheckVersion($DBversion) ) {
11794     $dbh->do(q{
11795         UPDATE `authorised_values` SET `lib`='Non-fiction' WHERE `lib`='Non Fiction';
11796     });
11797
11798     print "Upgrade to $DBversion done (Bug 15411 - Change Non Fiction to Non-fiction in authorised_values)\n";
11799     SetVersion($DBversion);
11800 }
11801
11802 $DBversion = "3.23.00.020";
11803 if ( CheckVersion($DBversion) ) {
11804     $dbh->do(q{
11805         CREATE TABLE  sms_providers (
11806            id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
11807            name VARCHAR( 255 ) NOT NULL ,
11808            domain VARCHAR( 255 ) NOT NULL ,
11809            UNIQUE (
11810                name
11811            )
11812         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
11813     });
11814
11815     $dbh->do(q{
11816         ALTER TABLE borrowers ADD sms_provider_id INT( 11 ) NULL DEFAULT NULL AFTER smsalertnumber;
11817     });
11818     $dbh->do(q{
11819         ALTER TABLE borrowers ADD FOREIGN KEY ( sms_provider_id ) REFERENCES sms_providers ( id ) ON UPDATE CASCADE ON DELETE SET NULL;
11820     });
11821     $dbh->do(q{
11822         ALTER TABLE deletedborrowers ADD sms_provider_id INT( 11 ) NULL DEFAULT NULL AFTER smsalertnumber;
11823     });
11824
11825     print "Upgrade to $DBversion done (Bug 9021 - Add SMS via email as an alternative to SMS services via SMS::Send drivers)\n";
11826     SetVersion($DBversion);
11827 }
11828
11829 $DBversion = "3.23.00.021";
11830 if ( CheckVersion($DBversion) ) {
11831     $dbh->do(q{
11832         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES ('ShowAllCheckins', '0', '', 'Show all checkins', 'YesNo');
11833     });
11834
11835     print "Upgrade to $DBversion done (Bug 15736 - Add a preference to control whether all items should be shown in checked-in items list)\n";
11836     SetVersion($DBversion);
11837 }
11838
11839 $DBversion = "3.23.00.022";
11840 if ( CheckVersion($DBversion) ) {
11841     $dbh->do(q{ ALTER TABLE tags_all MODIFY COLUMN borrowernumber INT(11) });
11842     $dbh->do(q{ ALTER TABLE tags_all drop FOREIGN KEY tags_borrowers_fk_1 });
11843     $dbh->do(q{ ALTER TABLE tags_all ADD CONSTRAINT `tags_borrowers_fk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE });
11844     $dbh->do(q{ ALTER TABLE tags_approval DROP FOREIGN KEY tags_approval_borrowers_fk_1 });
11845     $dbh->do(q{ ALTER TABLE tags_approval ADD CONSTRAINT `tags_approval_borrowers_fk_1` FOREIGN KEY (`approved_by`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE });
11846
11847     print "Upgrade to $DBversion done (Bug 13534 - Deleting staff patron will delete tags approved by this patron)\n";
11848     SetVersion($DBversion);
11849 }
11850
11851 $DBversion = "3.23.00.023";
11852 if ( CheckVersion($DBversion) ) {
11853     $dbh->do(q{
11854         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11855         VALUES('OpenLibrarySearch','0','If Yes Open Library search results will show in OPAC',NULL,'YesNo');
11856     });
11857
11858     print "Upgrade to $DBversion done (Bug 6624 - Allow Koha to use the new read API from OpenLibrary)\n";
11859     SetVersion($DBversion);
11860 }
11861
11862 $DBversion = "3.23.00.024";
11863 if ( CheckVersion($DBversion) ) {
11864     $dbh->do(q{
11865         ALTER TABLE deletedborrowers MODIFY COLUMN userid VARCHAR(75) DEFAULT NULL;
11866     });
11867
11868     $dbh->do(q{
11869         ALTER TABLE deletedborrowers MODIFY COLUMN password VARCHAR(60) DEFAULT NULL;
11870     });
11871
11872     print "Upgrade to $DBversion done (Bug 15517 - Tables borrowers and deletedborrowers differ again)\n";
11873     SetVersion($DBversion);
11874 }
11875
11876 $DBversion = "3.23.00.025";
11877 if ( CheckVersion($DBversion) ) {
11878     $dbh->do(q{
11879         DROP TABLE IF EXISTS nozebra;
11880     });
11881
11882     print "Upgrade to $DBversion done (Bug 15526 - Drop nozebra database table)\n";
11883     SetVersion($DBversion);
11884 }
11885
11886 $DBversion = "3.23.00.026";
11887 if ( CheckVersion($DBversion) ) {
11888     $dbh->do(q{
11889         UPDATE systempreferences SET value = CONCAT_WS('|', IF(value='', NULL, value), "password") WHERE variable="PatronSelfRegistrationBorrowerUnwantedField" AND value NOT LIKE "%password%";
11890     });
11891
11892     print "Upgrade to $DBversion done (Bug 15343 - Allow patrons to choose their own password on self registration)\n";
11893     SetVersion($DBversion);
11894 }
11895
11896 $DBversion = "3.23.00.027";
11897 if ( CheckVersion($DBversion) ) {
11898     my ( $db_value ) = $dbh->selectrow_array(q|SELECT count(*) FROM branches|);
11899     my $pref_value = C4::Context->preference("singleBranchMode") || 0;
11900     if ( $db_value > 1 and $pref_value == 1 ) {
11901         warn "WARNING: You have more than 1 libraries in your branches tables but the singleBranchMode system preference is on.\n";
11902         warn "This configuration does not make sense. The system preference is going to be deleted,\n";
11903         warn "and this parameter will be based on the number of libraries defined.\n";
11904     }
11905     $dbh->do(q|DELETE FROM systempreferences WHERE variable="singleBranchMode"|);
11906
11907     print "Upgrade to $DBversion done (Bug 4941 - Can't set branch in staff client when singleBranchMode is enabled)\n";
11908     SetVersion($DBversion);
11909 }
11910
11911 $DBversion = "3.23.00.028";
11912 if ( CheckVersion($DBversion) ) {
11913     $dbh->do(q{
11914         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) SELECT 'PatronSelfModificationBorrowerUnwantedField',value,NULL,'Name the fields you don\'t want to display when a patron is editing their information via the OPAC.','free' FROM systempreferences WHERE variable = 'PatronSelfRegistrationBorrowerUnwantedField';
11915     });
11916
11917     print "Upgrade to $DBversion done (Bug 14658 - Split PatronSelfRegistrationBorrowerUnwantedField into two preferences for creating and editing)\n";
11918     SetVersion($DBversion);
11919 }
11920
11921 $DBversion = "3.23.00.029";
11922 if ( CheckVersion($DBversion) ) {
11923
11924     # move marc21_field_003.pl 040c and 040d to marc21_orgcode.pl
11925     $dbh->do(q{
11926         update marc_subfield_structure set value_builder='marc21_orgcode.pl' where value_builder IN ( 'marc21_field_003.pl', 'marc21_field_040c.pl', 'marc21_field_040d.pl' );
11927     });
11928     $dbh->do(q{
11929         update auth_subfield_structure set value_builder='marc21_orgcode.pl' where value_builder IN ( 'marc21_field_003.pl', 'marc21_field_040c.pl', 'marc21_field_040d.pl' );
11930     });
11931
11932     print "Upgrade to $DBversion done (Bug 14199 - Unify all organization code plugins)\n";
11933     SetVersion($DBversion);
11934 }
11935
11936 $DBversion = "3.23.00.030";
11937 if(CheckVersion($DBversion)) {
11938     $dbh->do(q{
11939         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
11940         VALUES ('OpacMaintenanceNotice','','','A user-defined block of HTML to appear on screen when OpacMaintenace is enabled','Textarea')
11941     });
11942
11943     print "Upgrade to $DBversion done (Bug 15311: Let libraries set text to display when OpacMaintenance = on)\n";
11944     SetVersion($DBversion);
11945 }
11946
11947 $DBversion = "3.23.00.031";
11948 if(CheckVersion($DBversion)) {
11949     $dbh->do(q{
11950         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11951         VALUES ('NoRenewalBeforePrecision', 'date', 'Calculate "No renewal before" based on date or exact time. Only relevant for loans calculated in days, hourly loans are not affected.', 'date|exact_time', 'Choice')
11952     });
11953
11954     print "Upgrade to $DBversion done (Bug 14395 - Two different ways to calculate 'No renewal before')\n";
11955     SetVersion($DBversion);
11956 }
11957
11958 $DBversion = "3.23.00.032";
11959 if ( CheckVersion($DBversion) ) {
11960     $dbh->do(q{
11961    -- Add issue_id to accountlines table
11962     ALTER TABLE accountlines ADD issue_id INT(11) NULL DEFAULT NULL AFTER accountlines_id;
11963     });
11964
11965 ## Close out any accruing fines with no current issue
11966     $dbh->do(q{
11967     UPDATE accountlines LEFT JOIN issues USING ( itemnumber, borrowernumber ) SET accounttype = 'F' WHERE accounttype = 'FU' and issues.issue_id IS NULL;
11968     });
11969
11970 ## Close out any extra not really accruing fines, keep only the latest accring fine
11971     $dbh->do(q{
11972     UPDATE accountlines a1
11973     LEFT JOIN (SELECT MAX(accountlines_id) AS keeper,
11974                       borrowernumber,
11975                       itemnumber
11976                FROM   accountlines
11977                WHERE  accounttype = 'FU'
11978                GROUP BY borrowernumber, itemnumber
11979               ) a2 USING ( borrowernumber, itemnumber )
11980     SET    a1.accounttype = 'F'
11981     WHERE  a1.accounttype = 'FU'
11982     AND  a1.accountlines_id != a2.keeper;
11983     });
11984
11985 ## Update the unclosed fines to add the current issue_id to them
11986     $dbh->do(q{
11987     UPDATE accountlines LEFT JOIN issues USING ( itemnumber ) SET accountlines.issue_id = issues.issue_id WHERE accounttype = 'FU'; 
11988     });
11989
11990     print "Upgrade to $DBversion done (Bug 15675 - Add issue_id column to accountlines and use it for updating fines)\n";
11991     SetVersion($DBversion);
11992 }
11993
11994 $DBversion = "3.23.00.033";
11995 if ( CheckVersion($DBversion) ) {
11996     $dbh->do(q{
11997     UPDATE systempreferences SET value = CONCAT_WS('|', IF(value = '', NULL, value), 'cardnumber') WHERE variable = 'PatronSelfRegistrationBorrowerUnwantedField' AND value NOT LIKE '%cardnumber%';
11998     });
11999
12000     $dbh->do(q{
12001     UPDATE systempreferences SET value = CONCAT_WS('|', IF(value = '', NULL, value), 'categorycode') WHERE variable = 'PatronSelfRegistrationBorrowerUnwantedField' AND value NOT LIKE '%categorycode%';
12002     });
12003
12004     print "Upgrade to $DBversion done (Bug 14659 - Allow patrons to enter card number and patron category on OPAC registration page)\n";
12005     SetVersion($DBversion);
12006 }
12007
12008 $DBversion = "3.23.00.034";
12009 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12010     $dbh->do(q{
12011         ALTER TABLE `items` ADD `new` VARCHAR(32) NULL AFTER `stocknumber`;
12012     });
12013     $dbh->do(q{
12014         ALTER TABLE `deleteditems` ADD `new` VARCHAR(32) NULL AFTER `stocknumber`;
12015     });
12016     print "Upgrade to $DBversion done (Bug 11023: Adds field 'new' in items and deleteditems tables)\n";
12017     SetVersion($DBversion);
12018 }
12019
12020 $DBversion = "3.23.00.035";
12021 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12022     $dbh->do(q{
12023         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('HTML5MediaYouTube',0,'Embed|Don\'t embed','YouTube links as videos','YesNo');
12024     });
12025     print "Upgrade to $DBversion done (Bug 14168 - enhance streaming cataloging to include youtube)\n";
12026
12027     SetVersion($DBversion);
12028     }
12029
12030 $DBversion = "3.23.00.036";
12031 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12032     $dbh->do(q{
12033     INSERT IGNORE INTO systempreferences (variable,value,explanation,type) VALUES ('HoldsQueueSkipClosed', '0', 'If enabled, any libraries that are closed when the holds queue is built will be ignored for the purpose of filling holds.', 'YesNo');
12034     });
12035     print "Upgrade to $DBversion done (Bug 12803 - Add ability to skip closed libraries when generating the holds queue)\n";
12036     SetVersion($DBversion);
12037     }
12038
12039 $DBversion = "3.23.00.037";
12040 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12041 ## Add the new currency.archived column
12042     $dbh->do(q{
12043     ALTER TABLE currency ADD column archived tinyint(1) DEFAULT 0;
12044     });
12045 ## Set currency=NULL if empty (just in case)
12046     $dbh->do(q{
12047     UPDATE aqorders SET currency=NULL WHERE currency="";
12048     });
12049 ## Insert the missing currency and mark them as archived before adding the FK
12050     $dbh->do(q{
12051     INSERT INTO currency(currency, archived) SELECT distinct currency, 1 FROM aqorders WHERE currency NOT IN (SELECT currency FROM currency);
12052     });
12053 ## Correct the field length in aqorders before adding FK too
12054     $dbh->do(q{ ALTER TABLE aqorders MODIFY COLUMN currency varchar(10) default NULL; });
12055 ## And finally add the FK
12056     $dbh->do(q{
12057     ALTER TABLE aqorders ADD FOREIGN KEY (currency) REFERENCES currency(currency) ON DELETE SET NULL ON UPDATE SET null;
12058     });
12059
12060     print "Upgrade to $DBversion done (Bug 15084 - Move the currency related code to Koha::Acquisition::Currenc[y|ies])\n";
12061     SetVersion($DBversion);
12062 }
12063
12064 $DBversion = "3.23.00.038";
12065 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12066     $dbh->do(q{
12067     INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES ('decreaseLoanHighHoldsControl', 'static', 'static|dynamic', "Chooses between static and dynamic high holds checking", 'Choice'), ('decreaseLoanHighHoldsIgnoreStatuses', '', 'damaged|itemlost|notforloan|withdrawn', "Ignore items with these statuses for dynamic high holds checking", 'Choice');
12068     });
12069     print "Upgrade to $DBversion done (Bug 14694 - Make decreaseloanHighHolds more flexible)\n";
12070     SetVersion($DBversion);
12071 }
12072
12073 $DBversion = "3.23.00.039";
12074 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12075
12076     $dbh->do(q{
12077     ALTER TABLE suggestions
12078     MODIFY COLUMN currency varchar(10) default NULL;
12079     });
12080     $dbh->do(q{
12081     ALTER TABLE aqbooksellers
12082     MODIFY COLUMN currency varchar(10) default NULL;
12083     });
12084     print "Upgrade to $DBversion done (Bug 15084 - Move the currency related code to Koha::Acquisition::Currenc[y|ies])\n";
12085     SetVersion($DBversion);
12086 }
12087
12088
12089 $DBversion = "3.23.00.040";
12090 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12091
12092     my $c = $dbh->selectrow_array('SELECT COUNT(*) FROM systempreferences WHERE variable="intranetcolorstylesheet" AND value="blue.css"');
12093
12094     if ( $c ) {
12095         print "WARNING: You are using a stylesheeet which has been removed from the Koha codebase.\n";
12096         print "Update your intranetcolorstylesheet.\n";
12097     }
12098     print "Upgrade to $DBversion done (Bug 16019 - Check intranetcolorstylesheet for blue.css)\n";
12099     SetVersion($DBversion);
12100 }
12101
12102 $DBversion = "3.23.00.041";
12103 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12104
12105     my $dbh = C4::Context->dbh;
12106     my ($print_error) = $dbh->{PrintError};
12107     $dbh->{RaiseError} = 0;
12108     $dbh->{PrintError} = 0;
12109     $dbh->do("ALTER TABLE overduerules_transport_types ADD COLUMN letternumber INT(1) NOT NULL DEFAULT 1 AFTER id");
12110     $dbh->{PrintError} = $print_error;
12111
12112     print "Upgrade to $DBversion done (Bug 16007: Make sure overduerules_transport_types.letternumber exists)\n";
12113     SetVersion($DBversion);
12114 }
12115
12116 $DBversion = "3.23.00.042";
12117 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12118
12119     $dbh->do(q{
12120             ALTER TABLE items CHANGE new new_status VARCHAR(32) NULL;
12121             });
12122     $dbh->do(q{
12123             ALTER TABLE deleteditems CHANGE new new_status VARCHAR(32) NULL;
12124             });
12125     $dbh->do(q{
12126             UPDATE systempreferences SET value=REPLACE(value, '"items.new"', '"items.new_status"') WHERE variable="automatic_item_modification_by_age_configuration";
12127             });
12128
12129     print "Upgrade to $DBversion done (Bug 16004 - Replace items.new with items.new_status)\n";
12130     SetVersion($DBversion);
12131 }
12132
12133 $DBversion = "3.23.00.043";
12134 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12135     $dbh->do(q{
12136             UPDATE systempreferences SET value="" WHERE value IS NULL;
12137             });
12138
12139     print "Upgrade to $DBversion done (Bug 16070 - Empty (undef) system preferences may cause some issues in combination with memcache)\n";
12140     SetVersion($DBversion);
12141 }
12142
12143 $DBversion = "3.23.00.044";
12144 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12145     $dbh->do(q{
12146             INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
12147             ('GoogleOpenIDConnect', '0', NULL, 'if ON, allows the use of Google OpenID Connect for login', 'YesNo'),
12148             ('GoogleOAuth2ClientID', '', NULL, 'Client ID for the web app registered with Google', 'Free'),
12149             ('GoogleOAuth2ClientSecret', '', NULL, 'Client Secret for the web app registered with Google', 'Free'),
12150             ('GoogleOpenIDConnectDomain', '', NULL, 'Restrict OpenID Connect to this domain (or subdomains of this domain). Leave blank for all Google domains', 'Free');
12151             });
12152
12153     print "Upgrade to $DBversion done (Bug 10988 - Allow login via Google OAuth2 (OpenID Connect))\n";
12154     SetVersion($DBversion);
12155 }
12156
12157 $DBversion = "3.23.00.045";
12158 if ( CheckVersion($DBversion) ) {
12159 ## Holds details for vendors supplying goods by EDI
12160    $dbh->do(q{
12161            CREATE TABLE IF NOT EXISTS vendor_edi_accounts (
12162                    id INT(11) NOT NULL auto_increment,
12163                    description TEXT NOT NULL,
12164                    host VARCHAR(40),
12165                    username VARCHAR(40),
12166                    password VARCHAR(40),
12167                    last_activity DATE,
12168                    vendor_id INT(11) REFERENCES aqbooksellers( id ),
12169                    download_directory TEXT,
12170                    upload_directory TEXT,
12171                    san VARCHAR(20),
12172                    id_code_qualifier VARCHAR(3) default '14',
12173                    transport VARCHAR(6) default 'FTP',
12174                    quotes_enabled TINYINT(1) not null default 0,
12175                    invoices_enabled TINYINT(1) not null default 0,
12176                    orders_enabled TINYINT(1) not null default 0,
12177                    responses_enabled TINYINT(1) not null default 0,
12178                    auto_orders TINYINT(1) not null default 0,
12179                    shipment_budget INTEGER(11) REFERENCES aqbudgets( budget_id ),
12180                    PRIMARY KEY  (id),
12181                    KEY vendorid (vendor_id),
12182                    KEY shipmentbudget (shipment_budget),
12183                    CONSTRAINT vfk_vendor_id FOREIGN KEY ( vendor_id ) REFERENCES aqbooksellers ( id ),
12184                    CONSTRAINT vfk_shipment_budget FOREIGN KEY ( shipment_budget ) REFERENCES aqbudgets ( budget_id )
12185                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
12186    });
12187
12188 ## Hold the actual edifact messages with links to associated baskets
12189    $dbh->do(q{
12190            CREATE TABLE IF NOT EXISTS edifact_messages (
12191                    id INT(11) NOT NULL auto_increment,
12192                    message_type VARCHAR(10) NOT NULL,
12193                    transfer_date DATE,
12194                    vendor_id INT(11) REFERENCES aqbooksellers( id ),
12195                    edi_acct  INTEGER REFERENCES vendor_edi_accounts( id ),
12196                    status TEXT,
12197                    basketno INT(11) REFERENCES aqbasket( basketno),
12198                    raw_msg MEDIUMTEXT,
12199                    filename TEXT,
12200                    deleted BOOLEAN NOT NULL DEFAULT 0,
12201                    PRIMARY KEY  (id),
12202                    KEY vendorid ( vendor_id),
12203                    KEY ediacct (edi_acct),
12204                    KEY basketno ( basketno),
12205                    CONSTRAINT emfk_vendor FOREIGN KEY ( vendor_id ) REFERENCES aqbooksellers ( id ),
12206                    CONSTRAINT emfk_edi_acct FOREIGN KEY ( edi_acct ) REFERENCES vendor_edi_accounts ( id ),
12207                    CONSTRAINT emfk_basketno FOREIGN KEY ( basketno ) REFERENCES aqbasket ( basketno )
12208                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
12209             });
12210
12211 ## invoices link back to the edifact message it was generated from
12212    $dbh->do(q{
12213            ALTER TABLE aqinvoices ADD COLUMN message_id INT(11) REFERENCES edifact_messages( id );
12214            });
12215
12216 ## clean up link on deletes
12217    $dbh->do(q{
12218            ALTER TABLE aqinvoices ADD CONSTRAINT edifact_msg_fk FOREIGN KEY ( message_id ) REFERENCES edifact_messages ( id ) ON DELETE SET NULL;
12219            });
12220
12221 ## Hold the supplier ids from quotes for ordering
12222 ## although this is an EAN-13 article number the standard says 35 characters ???
12223    $dbh->do(q{
12224            ALTER TABLE aqorders ADD COLUMN line_item_id VARCHAR(35);
12225            });
12226
12227 ## The suppliers unique reference usually a quotation line number ('QLI')
12228 ## Otherwise Suppliers unique orderline reference ('SLI')
12229    $dbh->do(q{
12230            ALTER TABLE aqorders ADD COLUMN suppliers_reference_number VARCHAR(35);
12231            });
12232    $dbh->do(q{
12233            ALTER TABLE aqorders ADD COLUMN suppliers_reference_qualifier VARCHAR(3);
12234            });
12235    $dbh->do(q{
12236            ALTER TABLE aqorders ADD COLUMN suppliers_report text;
12237            });
12238
12239 ## hold the EAN/SAN used in ordering
12240    $dbh->do(q{
12241            CREATE TABLE IF NOT EXISTS edifact_ean (
12242                    ee_id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
12243                    description VARCHAR(128) NULL DEFAULT NULL,
12244                    branchcode VARCHAR(10) NOT NULL REFERENCES branches (branchcode),
12245                    ean VARCHAR(15) NOT NULL,
12246                    id_code_qualifier VARCHAR(3) NOT NULL DEFAULT '14',
12247                    CONSTRAINT efk_branchcode FOREIGN KEY ( branchcode ) REFERENCES branches ( branchcode )
12248                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
12249            });
12250
12251 ## Add a permission for managing EDI
12252    $dbh->do(q{
12253            INSERT INTO permissions (module_bit, code, description) values (11, 'edi_manage', 'Manage EDIFACT transmissions');
12254            });
12255
12256    print "Upgrade to $DBversion done (Bug 7736 - Edifact QUOTE and ORDER functionality))\n";
12257    SetVersion($DBversion);
12258 }
12259
12260 $DBversion = "3.23.00.046";
12261 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12262
12263     $dbh->do(q{
12264     ALTER TABLE vendor_edi_accounts ADD COLUMN plugin VARCHAR(256) NOT NULL DEFAULT "";
12265     });
12266
12267     print "Upgrade to $DBversion done (Bug 15630 - Make Edifact module pluggable))\n";
12268     SetVersion($DBversion);
12269 }
12270
12271 $DBversion = "3.23.00.047";
12272 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12273
12274     $dbh->do(q{
12275          INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('IntranetReportsHomeHTML', '', 'Show the following HTML in a div on the bottom of the reports home page', NULL, 'Free');
12276          });
12277     $dbh->do(q{
12278          INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('IntranetCirculationHomeHTML', '', 'Show the following HTML in a div on the bottom of the reports home page', NULL, 'Free');
12279          });
12280
12281     print "Upgrade to $DBversion done (Bug 15008 - Add custom HTML areas to circulation and reports home pages)\n";
12282     SetVersion($DBversion);
12283 }
12284
12285 $DBversion = "3.23.00.048";
12286 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12287     $dbh->do(q{
12288     INSERT IGNORE INTO `systempreferences` (variable,value,options,explanation,type)  SELECT 'OPACISBD', value, '70|10', 'Allows to define ISBD view in OPAC', 'Textarea' FROM `systempreferences` WHERE variable = 'ISBD';
12289     });
12290
12291     print "Upgrade to $DBversion done (Bug 5979 - Add separate OPACISBD system preference)\n";
12292     SetVersion($DBversion);
12293 }
12294
12295
12296
12297 $DBversion = "3.23.00.049";
12298 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12299 my $dbh = C4::Context->dbh;
12300 my ( $column_has_been_used ) = $dbh->selectrow_array(q|
12301             SELECT COUNT(*)
12302                 FROM borrower_attributes
12303                     WHERE password IS NOT NULL
12304                     |);
12305
12306 if ( $column_has_been_used ) {
12307         print q|WARNING: The columns borrower_attribute_types.password_allowed and borrower_attributes.password have been removed from the Koha codebase. They were not used. However your installation has at least one borrower_attributes.password defined. In order not to alter your data, the columns have been kept, please save the information elsewhere and remove these columns manually.|;
12308 } else {
12309         $dbh->do(q|
12310         ALTER TABLE borrower_attribute_types DROP column password_allowed
12311         |);
12312         $dbh->do(q|
12313         ALTER TABLE borrower_attributes DROP column password;
12314         |);
12315     }
12316     print "Upgrade to $DBversion done (Bug 12267 - Allow password option in Patron Attribute non functional)\n";
12317         SetVersion($DBversion);
12318 }
12319
12320
12321 $DBversion = "3.23.00.050";
12322 if ( CheckVersion($DBversion) ) {
12323     use Koha::SearchMarcMaps;
12324     use Koha::SearchFields;
12325     use Koha::SearchEngine::Elasticsearch;
12326
12327     $dbh->do(q|INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
12328                     VALUES('SearchEngine','Zebra','Choose Search Engine','','Choice')|);
12329
12330
12331     $dbh->do(q|DROP TABLE IF EXISTS search_marc_to_field|);
12332     $dbh->do(q|DROP TABLE IF EXISTS search_marc_map|);
12333     $dbh->do(q|DROP TABLE IF EXISTS search_field|);
12334
12335 # This specifies the fields that will be stored in the search engine.
12336  $dbh->do(q|
12337          CREATE TABLE `search_field` (
12338              `id` int(11) NOT NULL AUTO_INCREMENT, 
12339              `name` varchar(255) NOT NULL COMMENT 'the name of the field as it will be stored in the search engine',
12340              `label` varchar(255) NOT NULL COMMENT 'the human readable name of the field, for display', 
12341              `type` ENUM('', 'string', 'date', 'number', 'boolean', 'sum') NOT NULL COMMENT 'what type of data this holds, relevant when storing it in the search engine',
12342              PRIMARY KEY (`id`),
12343              UNIQUE KEY (`name`)
12344              ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
12345          |);
12346 # This contains a MARC field specifier for a given index, marc type, and marc
12347 # field.
12348 $dbh->do(q|
12349         CREATE TABLE `search_marc_map` (
12350             id int(11) NOT NULL AUTO_INCREMENT,
12351             index_name ENUM('biblios','authorities') NOT NULL COMMENT 'what storage index this map is for',
12352             marc_type ENUM('marc21', 'unimarc', 'normarc') NOT NULL COMMENT 'what MARC type this map is for',
12353             marc_field VARCHAR(255) NOT NULL COMMENT 'the MARC specifier for this field',
12354             PRIMARY KEY(`id`),
12355             unique key( index_name, marc_field, marc_type),
12356             INDEX (`index_name`)
12357             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
12358         |);
12359
12360 # This joins the two search tables together. We can have any combination:
12361 # one marc field could have many search fields (maybe you want one value
12362 # to go to 'author' and 'corporate-author) and many marc fields could go
12363 # to one search field (e.g. all the various author fields going into
12364 # 'author'.)
12365 #
12366 # a note about the sort field:
12367 # * if all the entries for a mapping are 'null', nothing special is done with that mapping.
12368 # * if any of the entries are not null, then a __sort field is created in ES for this mapping. In this case:
12369 #   * any mapping with sort == false WILL NOT get copied into a __sort field
12370 #   * any mapping with sort == true or is null WILL get copied into a __sort field
12371 #   * any sorts on the field name will be applied to $fieldname.'__sort' instead.
12372 # this means that we can have search for author that includes 1xx, 245$c, and 7xx, but the sort only applies to 1xx.
12373
12374 $dbh->do(q|
12375         CREATE TABLE `search_marc_to_field` (
12376             search_marc_map_id int(11) NOT NULL,
12377             search_field_id int(11) NOT NULL,
12378             facet boolean DEFAULT FALSE COMMENT 'true if a facet field should be generated for this',
12379             suggestible boolean DEFAULT FALSE COMMENT 'true if this field can be used to generate suggestions for browse',
12380             sort boolean DEFAULT NULL COMMENT 'true/false creates special sort handling, null doesn''t',
12381             PRIMARY KEY(search_marc_map_id, search_field_id),
12382             FOREIGN KEY(search_marc_map_id) REFERENCES search_marc_map(id) ON DELETE CASCADE ON UPDATE CASCADE,
12383             FOREIGN KEY(search_field_id) REFERENCES search_field(id) ON DELETE CASCADE ON UPDATE CASCADE
12384             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
12385         |);
12386
12387         # Insert default mappings
12388         Koha::SearchEngine::Elasticsearch->reset_elasticsearch_mappings;
12389
12390 print "Upgrade to $DBversion done (Bug 12478 - Elasticsearch support for Koha)\n";
12391     SetVersion($DBversion);
12392     }
12393
12394
12395 $DBversion = "3.23.00.051";
12396 if ( CheckVersion($DBversion) ) {
12397 $dbh->do(q{
12398         ALTER TABLE edifact_messages
12399         DROP FOREIGN KEY emfk_vendor,
12400         DROP FOREIGN KEY emfk_edi_acct,
12401         DROP FOREIGN KEY emfk_basketno;
12402         });
12403
12404 $dbh->do(q{
12405         ALTER TABLE edifact_messages
12406         ADD CONSTRAINT emfk_vendor FOREIGN KEY ( vendor_id ) REFERENCES aqbooksellers ( id ) ON DELETE CASCADE ON UPDATE CASCADE,
12407         ADD CONSTRAINT emfk_edi_acct FOREIGN KEY ( edi_acct ) REFERENCES vendor_edi_accounts ( id ) ON DELETE CASCADE ON UPDATE CASCADE,
12408         ADD CONSTRAINT emfk_basketno FOREIGN KEY ( basketno ) REFERENCES aqbasket ( basketno ) ON DELETE CASCADE ON UPDATE CASCADE;
12409         });
12410
12411     print "Upgrade to $DBversion done (Bug 16354 - Fix FK constraints for edifact_messages table)\n";
12412     SetVersion($DBversion);
12413 }
12414
12415
12416 $DBversion = "3.23.00.052";
12417 if ( CheckVersion($DBversion) ) {
12418 ## Insert permission
12419
12420     $dbh->do(q{
12421         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
12422         (13, 'upload_general_files', 'Upload any file'),
12423         (13, 'upload_manage', 'Manage uploaded files');
12424         });
12425 ## Update user_permissions for current users (check count in uploaded_files)
12426 ## Note 9 == edit_catalogue and 13 == tools
12427 ## We do not insert if someone is superlibrarian, does not have edit_catalogue,
12428 ## or already has all tools
12429
12430         $dbh->do(q{
12431                 INSERT IGNORE INTO user_permissions (borrowernumber, module_bit, code)
12432                 SELECT borrowernumber, 13, 'upload_general_files'
12433                 FROM borrowers bo
12434                 WHERE flags<>1 AND flags & POW(2,13) = 0 AND
12435                 ( flags & POW(2,9) > 0 OR 
12436                   (SELECT COUNT(*) FROM user_permissions
12437                    WHERE borrowernumber=bo.borrowernumber AND module_bit=9 ) > 0 )
12438                 AND ( SELECT COUNT(*) FROM uploaded_files ) > 0
12439                 });
12440
12441     print "Upgrade to $DBversion done (Bug 14686 - New menu option and permission for file uploading)\n";
12442     SetVersion($DBversion);
12443 }
12444
12445 $DBversion = "3.23.00.053";
12446 if ( CheckVersion($DBversion) ) {
12447     my $letters = $dbh->selectall_arrayref(
12448         q|
12449         SELECT code, name
12450         FROM letter
12451         WHERE message_transport_type="email"
12452         |, { Slice => {} }
12453     );
12454     for my $letter (@$letters) {
12455         $dbh->do(
12456             q|
12457                 UPDATE letter
12458                 SET name = ?
12459                 WHERE code = ?
12460                 AND message_transport_type <> "email"
12461                 |, undef, $letter->{name}, $letter->{code}
12462         );
12463     }
12464
12465     print "Upgrade to $DBversion done (Bug 16217 - Notice' names may have diverged)\n";
12466     SetVersion($DBversion);
12467 }
12468
12469 $DBversion = "3.23.00.054";
12470 if ( CheckVersion($DBversion) ) {
12471     $dbh->do(q{
12472         ALTER TABLE branch_item_rules ADD COLUMN hold_fulfillment_policy ENUM('any', 'homebranch', 'holdingbranch') NOT NULL DEFAULT 'any' AFTER holdallowed;
12473     });
12474     $dbh->do(q{
12475         ALTER TABLE default_branch_circ_rules ADD COLUMN hold_fulfillment_policy ENUM('any', 'homebranch', 'holdingbranch') NOT NULL DEFAULT 'any' AFTER holdallowed;
12476     });
12477     $dbh->do(q{
12478         ALTER TABLE default_branch_item_rules ADD COLUMN hold_fulfillment_policy ENUM('any', 'homebranch', 'holdingbranch') NOT NULL DEFAULT 'any' AFTER holdallowed;
12479     });
12480     $dbh->do(q{
12481         ALTER TABLE default_circ_rules ADD COLUMN hold_fulfillment_policy ENUM('any', 'homebranch', 'holdingbranch') NOT NULL DEFAULT 'any' AFTER holdallowed;
12482     });
12483
12484     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";
12485     SetVersion($DBversion);
12486 }
12487
12488 $DBversion = "3.23.00.055";
12489 if ( CheckVersion($DBversion) ) {
12490     $dbh->do(q{
12491         ALTER TABLE reserves ADD COLUMN itemtype VARCHAR(10) NULL DEFAULT NULL AFTER suspend_until;
12492     });
12493     $dbh->do(q{
12494         ALTER TABLE reserves ADD KEY `itemtype` (`itemtype`);
12495     });
12496     $dbh->do(q{
12497         ALTER TABLE reserves ADD CONSTRAINT `reserves_ibfk_5` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE;
12498     });
12499     $dbh->do(q{
12500         ALTER TABLE old_reserves ADD COLUMN itemtype VARCHAR(10) NULL DEFAULT NULL AFTER suspend_until;
12501     });
12502     $dbh->do(q{
12503         ALTER TABLE old_reserves ADD KEY `itemtype` (`itemtype`);
12504     });
12505     $dbh->do(q{
12506         ALTER TABLE old_reserves ADD CONSTRAINT `old_reserves_ibfk_4` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE;
12507     });
12508
12509     $dbh->do(q{
12510         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
12511         ('AllowHoldItemTypeSelection','0','','If enabled, patrons and staff will be able to select the itemtype when placing a hold','YesNo');
12512     });
12513
12514     print "Upgrade to $DBversion done (Bug 15533 - Allow patrons and librarians to select itemtype when placing hold)\n";
12515     SetVersion($DBversion);
12516 }
12517
12518 $DBversion = "3.23.00.056";
12519 if ( CheckVersion($DBversion) ) {
12520     $dbh->do(q{
12521         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
12522         ('NoIssuesChargeGuarantees','','','Define maximum amount withstanding before check outs are blocked','Integer');
12523     });
12524
12525     print "Upgrade to $DBversion done (Bug 14577 - Allow restriction of checkouts based on fines of guarantor/guarantee)\n";
12526     SetVersion($DBversion);
12527 }
12528
12529 $DBversion = "3.23.00.057";
12530 if ( CheckVersion($DBversion) ) {
12531     $dbh->do(q{
12532         ALTER TABLE aqbasket ADD COLUMN is_standing TINYINT(1) NOT NULL DEFAULT 0 AFTER branch;
12533     });
12534
12535     print "Upgrade to $DBversion done (Bug 15531 - Add support for standing orders)\n";
12536     SetVersion($DBversion);
12537 }
12538
12539 $DBversion = "3.23.00.058";
12540 if ( CheckVersion($DBversion) ) {
12541
12542     my ($count_imageurl) = $dbh->selectrow_array(q|
12543         SELECT COUNT(*)
12544         FROM authorised_values
12545         WHERE imageurl IS NOT NULL
12546             AND imageurl <> ""
12547     |);
12548
12549     unless ($count_imageurl) {
12550         if (   C4::Context->preference('AuthorisedValueImages')
12551             or C4::Context->preference('StaffAuthorisedValueImages') )
12552         {
12553             $dbh->do(q|
12554                 UPDATE systempreferences
12555                 SET value = 0
12556                 WHERE variable = "AuthorisedValueImages"
12557                    or variable = "StaffAuthorisedValueImages"
12558             |);
12559             warn "The system preferences AuthorisedValueImages and StaffAuthorisedValueImages have been turned off\n";
12560             warn "authorised_values.imageurl is not populated, that means you are not using this feature\n";
12561         }
12562     }
12563     else {
12564         warn "At least one authorised value has an icon defined (imageurl)\n";
12565         warn "The system preference AuthorisedValueImages or StaffAuthorisedValueImages could be turned off if you are not aware of this feature\n";
12566     }
12567
12568     print "Upgrade to $DBversion done (Bug 16041 - StaffAuthorisedValueImages & AuthorisedValueImages preferences - impact on search performance)\n";
12569     SetVersion($DBversion);
12570 }
12571
12572 $DBversion = "3.23.00.059";
12573 if ( CheckVersion($DBversion) ) {
12574     $dbh->do(q{
12575         DELETE FROM systempreferences WHERE variable="AuthorisedValueImages" OR variable="StaffAuthorisedValueImages";
12576     });
12577
12578     print "Upgrade to $DBversion done (Bug 16167 - Remove prefs to drive authorised value images)\n";
12579     SetVersion($DBversion);
12580 }
12581
12582 $DBversion = "3.23.00.060";
12583 if ( CheckVersion($DBversion) ) {
12584     $dbh->do(q{
12585         INSERT IGNORE INTO systempreferences ( value, variable, options, explanation,type )
12586         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';
12587     });
12588
12589     print "Upgrade to $DBversion done (Bug 12528 - Enable staff to deny message setting access to patrons on the OPAC)\n";
12590     SetVersion($DBversion);
12591 }
12592
12593 $DBversion = "3.23.00.061";
12594 if ( CheckVersion($DBversion) ) {
12595     my ( $cnt ) = $dbh->selectrow_array( q|
12596         SELECT COUNT(*) FROM items it
12597         LEFT JOIN biblio bi ON bi.biblionumber=it.biblionumber
12598         LEFT JOIN biblioitems bii USING (biblioitemnumber)
12599         WHERE bi.biblionumber IS NULL
12600     |);
12601     if( $cnt ) {
12602         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";
12603     } else {
12604         # now add FK
12605         $dbh->do( q|
12606             ALTER TABLE items
12607             ADD FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
12608         |);
12609         print "Upgrade to $DBversion done (Bug 16170 - Add FK for biblionumber in items)\n";
12610     }
12611     SetVersion($DBversion);
12612 }
12613
12614 $DBversion = "3.23.00.062";
12615 if ( CheckVersion($DBversion) ) {
12616     $dbh->do( q|
12617             ALTER TABLE aqorders DROP COLUMN budgetgroup_id;
12618             |);
12619     print "Upgrade to $DBversion done (Bug 16414 - aqorders.budgetgroup_id has never been used and can be removed)\n";
12620 SetVersion($DBversion);
12621 }
12622
12623 $DBversion = "3.23.00.063";
12624 if ( CheckVersion($DBversion) ) {
12625     $dbh->do(q{
12626         UPDATE letter SET branchcode='' WHERE branchcode IS NULL;
12627     });
12628     $dbh->do(q{
12629         ALTER TABLE letter MODIFY COLUMN branchcode varchar(10) NOT NULL DEFAULT ''
12630     });
12631     $dbh->do(q{
12632         ALTER TABLE permissions MODIFY COLUMN code varchar(64) NOT NULL DEFAULT '';
12633     });
12634     print "Upgrade to $DBversion done (Bug 16402: Fix DB structure to work on MySQL 5.7)\n";
12635     SetVersion($DBversion);
12636 }
12637
12638 $DBversion = "3.23.00.064";
12639 if ( CheckVersion($DBversion) ) {
12640     $dbh->do(q{
12641         ALTER TABLE creator_layouts MODIFY layout_name char(25) NOT NULL DEFAULT 'DEFAULT';
12642     });
12643     print "Upgrade to $DBversion done (Bug 15086 - Creators layout and template sql has warnings)\n";
12644     SetVersion($DBversion);
12645 }
12646
12647 $DBversion = "16.05.00.000";
12648 if ( CheckVersion($DBversion) ) {
12649     print "Upgrade to $DBversion done (Koha 16.05)\n";
12650     SetVersion($DBversion);
12651 }
12652
12653 $DBversion = "16.06.00.000";
12654 if ( CheckVersion($DBversion) ) {
12655     print "Upgrade to $DBversion done (Koha 16.06 - starting a new dev line at KohaCon16 in Thessaloniki, Greece! Koha is great!)\n";
12656     SetVersion($DBversion);
12657 }
12658
12659 $DBversion = "16.06.00.001";
12660 if ( CheckVersion($DBversion) ) {
12661     $dbh->do(q{
12662         UPDATE accountlines SET accounttype='HE', description=itemnumber WHERE (description REGEXP '^Hold waiting too long [0-9]+') AND accounttype='F';
12663     });
12664
12665     print "Upgrade to $DBversion done (Bug 16200 - 'Hold waiting too long' fee has a translation problem)\n";
12666     SetVersion($DBversion);
12667 }
12668
12669 $DBversion = "16.06.00.002";
12670 if ( CheckVersion($DBversion) ) {
12671     unless ( column_exists('borrowers', 'updated_on') ) {
12672         $dbh->do(q{
12673             ALTER TABLE borrowers
12674                 ADD COLUMN updated_on timestamp NULL DEFAULT CURRENT_TIMESTAMP
12675                 ON UPDATE CURRENT_TIMESTAMP
12676                 AFTER privacy_guarantor_checkouts;
12677         });
12678         $dbh->do(q{
12679             ALTER TABLE deletedborrowers
12680                 ADD COLUMN updated_on timestamp NULL DEFAULT CURRENT_TIMESTAMP
12681                 ON UPDATE CURRENT_TIMESTAMP
12682                 AFTER privacy_guarantor_checkouts;
12683         });
12684     }
12685
12686     print "Upgrade to $DBversion done (Bug 10459 - borrowers should have a timestamp)\n";
12687     SetVersion($DBversion);
12688 }
12689
12690 $DBversion = "16.06.00.003";
12691 if ( CheckVersion($DBversion) ) {
12692     $dbh->do(q{
12693         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
12694         SELECT 'MaxItemsToProcessForBatchMod', value, NULL, 'Process up to a given number of items in a single item modification batch.', 'Integer' FROM systempreferences WHERE variable='MaxItemsForBatch';
12695     });
12696     $dbh->do(q{
12697         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
12698         SELECT 'MaxItemsToDisplayForBatchDel', value, NULL, 'Display up to a given number of items in a single item deletionbatch.', 'Integer' FROM systempreferences WHERE variable='MaxItemsForBatch';
12699     });
12700     $dbh->do(q{
12701         DELETE FROM systempreferences WHERE variable="MaxItemsForBatch";
12702     });
12703
12704     print "Upgrade to $DBversion done (Bug 11490 - MaxItemsForBatch should be split into two new prefs)\n";
12705     SetVersion($DBversion);
12706 }
12707
12708 $DBversion = '16.06.00.004';
12709 if ( CheckVersion($DBversion) ) {
12710     $dbh->do(q{
12711         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
12712          SELECT 'OPACXSLTListsDisplay', COALESCE(value,''), '', 'Enable XSLT stylesheet control over lists pages display on OPAC', 'Free'
12713          FROM systempreferences WHERE variable='OPACXSLTResultsDisplay';
12714     });
12715
12716     $dbh->do(q{
12717         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
12718          SELECT 'XSLTListsDisplay', COALESCE(value,''), '', 'Enable XSLT stylesheet control over lists pages display on intranet', 'Free'
12719          FROM systempreferences WHERE variable='XSLTResultsDisplay';
12720     });
12721
12722     print "Upgrade to $DBversion done (Bug 15485: Allow choosing different XSLTs for lists)\n";
12723     SetVersion($DBversion);
12724 }
12725
12726 $DBversion = '16.06.00.005';
12727 if ( CheckVersion($DBversion) ) {
12728     $dbh->do(q{
12729         UPDATE `systempreferences` set options = 'US|FR|CH' where variable = 'CurrencyFormat';
12730     });
12731
12732     print "Upgrade to $DBversion done (Bug 16768 - Add official number format for Switzerland: 1'234'567.89)\n";
12733     SetVersion($DBversion);
12734 }
12735
12736 $DBversion = "16.06.00.006";
12737 if ( CheckVersion($DBversion) ) {
12738     $dbh->do(q{
12739         CREATE TABLE `refund_lost_item_fee_rules` (
12740           `branchcode` varchar(10) NOT NULL default '',
12741           `refund` tinyint(1) NOT NULL default 0,
12742           PRIMARY KEY  (`branchcode`)
12743         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
12744     });
12745     $dbh->do(q{
12746         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
12747         VALUES( 'RefundLostOnReturnControl',
12748                 'CheckinLibrary',
12749                 'If a lost item is returned, choose which branch to pick rules for refunding.',
12750                 'CheckinLibrary|PatronLibrary|ItemHomeBranch|ItemHoldingbranch',
12751                 'Choice')
12752     });
12753     # Pick the old syspref as the default rule
12754     $dbh->do(q{
12755         INSERT INTO refund_lost_item_fee_rules (branchcode,refund)
12756             SELECT '*', COALESCE(value,'1') FROM systempreferences WHERE variable='RefundLostItemFeeOnReturn'
12757     });
12758     # Delete the old syspref
12759     $dbh->do(q{
12760         DELETE IGNORE FROM systempreferences
12761         WHERE variable='RefundLostItemFeeOnReturn'
12762     });
12763
12764     print "Upgrade to $DBversion done (Bug 14048: Change RefundLostItemFeeOnReturn to be branch specific)\n";
12765     SetVersion($DBversion);
12766 }
12767
12768 $DBversion = '16.06.00.007';
12769 if ( CheckVersion($DBversion) ) {
12770     $dbh->do(q{
12771         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) 
12772         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');
12773     });
12774
12775     print "Upgrade to $DBversion done (Bug 3534 - Patron quick add form)\n";
12776     SetVersion($DBversion);
12777 }
12778
12779 $DBversion = '16.06.00.008';
12780 if ( CheckVersion($DBversion) ) {
12781     $dbh->do(q{
12782         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
12783         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');
12784     });
12785     $dbh->do(q{
12786         ALTER TABLE categories
12787         ADD COLUMN `checkprevcheckout` varchar(7) NOT NULL default 'inherit'
12788         AFTER `default_privacy`;
12789     });
12790     $dbh->do(q{
12791         ALTER TABLE borrowers
12792         ADD COLUMN `checkprevcheckout` varchar(7) NOT NULL default 'inherit'
12793         AFTER `privacy_guarantor_checkouts`;
12794     });
12795     $dbh->do(q{
12796         ALTER TABLE deletedborrowers
12797         ADD COLUMN `checkprevcheckout` varchar(7) NOT NULL default 'inherit'
12798         AFTER `privacy_guarantor_checkouts`;
12799     });
12800
12801     print "Upgrade to $DBversion done (Bug 6906 - show 'Borrower has previously issued \$ITEM' alert on checkout)\n";
12802     SetVersion($DBversion);
12803 }
12804
12805 $DBversion = '16.06.00.009';
12806 if ( CheckVersion($DBversion) ) {
12807     $dbh->do(q{
12808         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) 
12809         VALUES ('IntranetCatalogSearchPulldown','0',NULL,'Show a search field pulldown for \"Search the catalog\" boxes. ','YesNo');
12810     });
12811
12812     print "Upgrade to $DBversion done (Bug 14902 - Add qualifier menu to staff side 'Search the Catalog')\n";
12813     SetVersion($DBversion);
12814 }
12815
12816 $DBversion = '16.06.00.010';
12817 if ( CheckVersion($DBversion) ) {
12818     $dbh->do(q{
12819         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
12820         VALUES ('MaxOpenSuggestions','',NULL,'Limit the number of open suggestions a patron can have at once, unlimited if blank','Integer')
12821     });
12822
12823     print "Upgrade to $DBversion done (Bug 15128 - Add ability to limit the number of open purchase suggestions a patron can make)\n";
12824     SetVersion($DBversion);
12825 }
12826
12827 $DBversion = '16.06.00.011';
12828 if ( CheckVersion($DBversion) ) {
12829     $dbh->do(q{
12830         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
12831         ('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'),
12832         ('NovelistSelectStaffView','tab','tab|above|below','Where to display Novelist Select content','Choice');
12833     });
12834
12835     print "Upgrade to $DBversion done (Bug 11606 - Novelist Select in Staff Client)\n";
12836     SetVersion($DBversion);
12837 }
12838
12839 $DBversion = '16.06.00.012';
12840 if ( CheckVersion($DBversion) ) {
12841     $dbh->do(q{
12842         ALTER TABLE virtualshelves MODIFY COLUMN created_on DATETIME not NULL;
12843     });
12844
12845     print "Upgrade to $DBversion done (Bug 16573 - Web installer fails to load structure and sample data on MySQL 5.7)\n";
12846     SetVersion($DBversion);
12847 }
12848
12849 $DBversion = '16.06.00.013';
12850 if ( CheckVersion($DBversion) ) {
12851     $dbh->do(q{
12852         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES
12853         ('OPACResultsLibrary', 'homebranch', 'homebranch|holdingbranch', 'Defines whether the OPAC displays the holding or home branch in search results when using XSLT', 'Choice');
12854     });
12855
12856     print "Upgrade to $DBversion done (Bug 7441 - Search results showing wrong branch)\n";
12857     SetVersion($DBversion);
12858 }
12859
12860 $DBversion = "16.06.00.014";
12861 if ( CheckVersion($DBversion) ) {
12862     $dbh->do(q{
12863         ALTER TABLE `action_logs` ADD COLUMN `interface` VARCHAR(30) DEFAULT NULL AFTER `info`;
12864     });
12865
12866     $dbh->do(q{
12867         ALTER TABLE `action_logs` ADD KEY `interface` (`interface`);
12868     });
12869
12870     print "Upgrade to $DBversion done (Bug 16829: action_logs should have an 'interface' column)\n";
12871     SetVersion($DBversion);
12872 }
12873
12874 $DBversion = "16.06.00.015";
12875 if ( CheckVersion($DBversion) ) {
12876     $dbh->do(q{
12877         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type ) VALUES
12878         ('HoldsLog','0',NULL,'If ON, log create/cancel/suspend/resume actions on holds.','YesNo');
12879     });
12880
12881     print "Upgrade to $DBversion done (Bug 14642: Add logging of hold modifications)\n";
12882     SetVersion($DBversion);
12883 }
12884
12885 $DBversion = "16.06.00.016";
12886 if ( CheckVersion($DBversion) ) {
12887     $dbh->do(q{
12888         update marc_subfield_structure set defaultvalue=REPLACE(defaultvalue, 'YYYY', '<<YYYY>>') where defaultvalue like "%YYYY%" and defaultvalue not like "%<<YYYY>>%";
12889     });
12890     $dbh->do(q{
12891         update marc_subfield_structure set defaultvalue=REPLACE(defaultvalue, 'MM', '<<MM>>') where defaultvalue like "%MM%" and defaultvalue not like "%<<MM>>%";
12892     });
12893     $dbh->do(q{
12894         update marc_subfield_structure set defaultvalue=REPLACE(defaultvalue, 'DD', '<<DD>>') where defaultvalue like "%DD%" and defaultvalue not like "%<<DD>>%";
12895     });
12896     $dbh->do(q{
12897         update marc_subfield_structure set defaultvalue=REPLACE(defaultvalue, 'user', '<<USER>>') where defaultvalue like "%user%" and defaultvalue not like "%<<USER>>%";
12898     });
12899
12900     print "Upgrade to $DBversion done (Bug 7045 - Default-value substitution inconsistent)\n";
12901     SetVersion($DBversion);
12902 }
12903
12904 $DBversion = "16.06.00.017";
12905 if ( CheckVersion($DBversion) ) {
12906     $dbh->do(q{
12907         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');
12908     });
12909
12910     print "Upgrade to $DBversion done (Bug 10848 - Allow configuration of mandatory/required fields on the suggestion form in OPAC)\n";
12911     SetVersion($DBversion);
12912 }
12913
12914 $DBversion = "16.06.00.018";
12915 if ( CheckVersion($DBversion) ) {
12916     $dbh->do(q{
12917         ALTER TABLE issuingrules ADD COLUMN holds_per_record SMALLINT(6) NOT NULL DEFAULT 1 AFTER reservesallowed;
12918     });
12919
12920     print "Upgrade to $DBversion done (Bug 14695 - Add ability to place multiple item holds on a given record per patron)\n";
12921     SetVersion($DBversion);
12922 }
12923
12924 $DBversion = "16.06.00.019";
12925 if ( CheckVersion($DBversion) ) {
12926     $dbh->do(q{
12927         ALTER TABLE reviews CHANGE COLUMN approved approved tinyint(4) DEFAULT 0;
12928     });
12929     $dbh->do(q{
12930         UPDATE reviews SET approved=0 WHERE approved IS NULL;
12931     });
12932
12933     print "Upgrade to $DBversion done (Bug 15839 - Move the reviews related code to Koha::Reviews)\n";
12934     SetVersion($DBversion);
12935 }
12936
12937 $DBversion = "16.06.00.020";
12938 if ( CheckVersion($DBversion) ) {
12939     $dbh->do(q{
12940         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('SwitchOnSiteCheckouts', '0', 'Automatically switch an on-site checkout to a normal checkout', NULL, 'YesNo');
12941     });
12942
12943     print "Upgrade to $DBversion done (Bug 16272 - Transform checkout from on-site checkout to regular checkout)\n";
12944     SetVersion($DBversion);
12945 }
12946
12947 $DBversion = "16.06.00.021";
12948 if ( CheckVersion($DBversion) ) {
12949     $dbh->do(q{
12950         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');
12951     });
12952
12953     print "Upgrade to $DBversion done (Bug 16275 - Prevent patron self registration if the email already filled in borrowers.email)\n";
12954     SetVersion($DBversion);
12955 }
12956
12957 $DBversion = "16.06.00.022";
12958 if ( CheckVersion($DBversion) ) {
12959     $dbh->do(q{
12960         INSERT IGNORE INTO `permissions`
12961         (module_bit, code,             description) VALUES
12962         (16,         'delete_reports', 'Delete SQL reports');
12963     });
12964     $dbh->do(q{
12965         INSERT IGNORE INTO user_permissions
12966         (borrowernumber,      module_bit,code)
12967         SELECT borrowernumber,module_bit,'delete_reports'
12968             FROM user_permissions
12969             WHERE module_bit=16 AND code='create_reports';
12970     });
12971
12972     print "Upgrade to $DBversion done (Bug 16978 - Add delete reports user permission)\n";
12973     SetVersion($DBversion);
12974 }
12975
12976 $DBversion = "16.06.00.023";
12977 if ( CheckVersion($DBversion) ) {
12978     my $pref = C4::Context->preference('timeout');
12979     if( !$pref || $pref eq '12000000' ) {
12980         # update if pref is null or equals old default value
12981         $dbh->do(q|
12982             UPDATE systempreferences SET value = '1d', type = 'Free'
12983             WHERE variable = 'timeout'
12984         |);
12985         print "Upgrade to $DBversion done (Bug 17187)\nNote: Pref value for timeout has been adjusted.\n";
12986     } else {
12987         # only update pref type
12988         $dbh->do(q|
12989             UPDATE systempreferences SET type = 'Free'
12990             WHERE variable = 'timeout'
12991         |);
12992         print "Upgrade to $DBversion done (Bug 17187)\nNote: Pref value for timeout has not been adjusted.\n";
12993     }
12994     SetVersion($DBversion);
12995 }
12996
12997 $DBversion = "16.06.00.024";
12998 if ( CheckVersion($DBversion) ) {
12999     $dbh->do(q{
13000         UPDATE language_descriptions SET description = 'Română' WHERE subtag = 'ro' AND type = 'language' AND lang = 'ro';
13001     });
13002
13003     print "Upgrade to $DBversion done (Bug 16311 - Advanced search language limit typo for Romanian)\n";
13004     SetVersion($DBversion);
13005 }
13006
13007 $DBversion = "16.06.00.025";
13008 if ( CheckVersion($DBversion) ) {
13009     $dbh->do(q{
13010         ALTER TABLE `subscription` ADD `itemtype` VARCHAR( 10 ) NULL AFTER reneweddate, ADD `previousitemtype` VARCHAR( 10 ) NULL AFTER itemtype;
13011     });
13012     $dbh->do(q{
13013         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
13014         ('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');
13015     });
13016
13017     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";
13018     SetVersion($DBversion);
13019 }
13020
13021 $DBversion = "16.06.00.026";
13022 if ( CheckVersion($DBversion) ) {
13023     $dbh->do(q{
13024         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('PatronSelfRegistrationLibraryList', '', 'Only display libraries listed. If empty, all libraries are displayed.', NULL, 'Free');
13025     });
13026
13027     print "Upgrade to $DBversion done (Bug 16274 - Make the selfregistration branchcode selection configurable)\n";
13028     SetVersion($DBversion);
13029 }
13030
13031 $DBversion = "16.06.00.027";
13032 if ( CheckVersion($DBversion) ) {
13033     unless ( column_exists('borrowers', 'lastseen') ) {
13034         $dbh->do(q{
13035             ALTER TABLE borrowers ADD COLUMN lastseen datetime default NULL AFTER updated_on;
13036         });
13037         $dbh->do(q{
13038             ALTER TABLE deletedborrowers ADD COLUMN lastseen datetime default NULL AFTER updated_on;
13039         });
13040     }
13041     $dbh->do(q{
13042         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');
13043     });
13044
13045     print "Upgrade to $DBversion done (Bug 16274 - Make the selfregistration branchcode selection configurable)\n";
13046     SetVersion($DBversion);
13047 }
13048
13049 $DBversion = '16.06.00.028';
13050 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
13051     {
13052         print "Attempting upgrade to $DBversion (Bug 17135) ...\n";
13053         my $maintenance_script = C4::Context->config("intranetdir") . "/installer/data/mysql/fix_unclosed_nonaccruing_fines_bug17135.pl";
13054         system("perl $maintenance_script --confirm");
13055
13056         print "Upgrade to $DBversion done (Bug 17135 - Fine for the previous overdue may get overwritten by the next one)\n";
13057
13058         unless ($original_version < TransformToNum("3.23.00.032")) { ## Bug 15675
13059             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";
13060             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";
13061         }
13062         SetVersion ($DBversion);
13063     }
13064 }
13065
13066 $DBversion = "16.06.00.029";
13067 if ( CheckVersion($DBversion) ) {
13068     $dbh->do(q{
13069         UPDATE systempreferences SET type="Choice" WHERE variable="UsageStatsLibraryType";
13070     });
13071     $dbh->do(q{
13072         UPDATE systempreferences SET value="Canada" WHERE variable="UsageStatsCountry" AND value="CANADA";
13073     });
13074     $dbh->do(q{
13075         UPDATE systempreferences SET value="Czech Republic" WHERE variable="UsageStatsCountry" AND value="CZ";
13076     });
13077     $dbh->do(q{
13078         UPDATE systempreferences SET value="United Kingdom" WHERE variable="UsageStatsCountry" AND (value="England" OR value="UK");
13079     });
13080     $dbh->do(q{
13081         UPDATE systempreferences SET value="Spain" WHERE variable="UsageStatsCountry" AND value="España";
13082     });
13083     $dbh->do(q{
13084         UPDATE systempreferences SET value="Greece" WHERE variable="UsageStatsCountry" AND value="GR";
13085     });
13086     $dbh->do(q{
13087         UPDATE systempreferences SET value="Ireland" WHERE variable="UsageStatsCountry" AND value="Irelanbd";
13088     });
13089     $dbh->do(q{
13090         UPDATE systempreferences SET value="Mexico" WHERE variable="UsageStatsCountry" AND value="México";
13091     });
13092     $dbh->do(q{
13093         UPDATE systempreferences SET value="Peru" WHERE variable="UsageStatsCountry" AND value="Perú";
13094     });
13095     $dbh->do(q{
13096         UPDATE systempreferences SET value="Dominican Rep." WHERE variable="UsageStatsCountry" AND value="República Dominicana";
13097     });
13098     $dbh->do(q{
13099         UPDATE systempreferences SET value="Trinidad & Tob." WHERE variable="UsageStatsCountry" AND value="Trinidad";
13100     });
13101     $dbh->do(q{
13102         UPDATE systempreferences SET value="Turkey" WHERE variable="UsageStatsCountry" AND value="Türkiye";
13103     });
13104     $dbh->do(q{
13105         UPDATE systempreferences SET value="USA" WHERE variable="UsageStatsCountry" AND (value="United States" OR value="United States of America" OR value="US");
13106     });
13107     $dbh->do(q{
13108         UPDATE systempreferences SET value="Zimbabwe" WHERE variable="UsageStatsCountry" AND value="Zimbabbwe";
13109     });
13110
13111     print "Upgrade to $DBversion done (Bug 14707 - Change UsageStatsCountry from free text to a dropdown list)\n";
13112     SetVersion($DBversion);
13113 }
13114
13115 $DBversion = "16.06.00.030";
13116 if ( CheckVersion($DBversion) ) {
13117     $dbh->do(q{
13118         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
13119         ('OPACHoldingsDefaultSortField','first_column','first_column|homebranch|holdingbranch','Default sort field for the holdings table at the OPAC','choice');
13120     });
13121
13122     print "Upgrade to $DBversion done (Bug 16552 - Add the ability to change the default holdings sort)\n";
13123     SetVersion($DBversion);
13124 }
13125
13126 $DBversion = "16.06.00.031";
13127 if ( CheckVersion($DBversion) ) {
13128     $dbh->do(q{
13129         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');
13130     });
13131
13132     print "Upgrade to $DBversion done (Bug 16273 - Prevent selfregistration from printing the borrower password and filling the logging form)\n";
13133     SetVersion($DBversion);
13134 }
13135
13136 $DBversion = "16.06.00.032";
13137 if ( CheckVersion($DBversion) ) {
13138     $dbh->do(q{
13139         UPDATE marc_subfield_structure SET authorised_value="WITHDRAWN" WHERE authorised_value="WTHDRAWN";
13140     });
13141
13142     print "Upgrade to $DBversion done (Bug 17357 - WTHDRAWN is still used in installer files)\n";
13143     SetVersion($DBversion);
13144 }
13145
13146
13147 $DBversion = "16.06.00.033";
13148 if ( CheckVersion($DBversion) ) {
13149     $dbh->do(q{
13150         CREATE TABLE authorised_value_categories (
13151         category_name VARCHAR(32) NOT NULL,
13152         primary key (category_name)
13153         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13154         });
13155 ## Add authorised value categories
13156     $dbh->do(q{
13157     INSERT INTO authorised_value_categories (category_name )
13158     SELECT DISTINCT category FROM authorised_values;
13159     });
13160     
13161 ## Add special categories
13162     $dbh->do(q{
13163     INSERT IGNORE INTO authorised_value_categories( category_name )
13164     VALUES
13165     ('Asort1'),
13166     ('Asort2'),
13167     ('Bsort1'),
13168     ('Bsort2'),
13169     ('SUGGEST'),
13170     ('DAMAGED'),
13171     ('LOST'),
13172     ('REPORT_GROUP'),
13173     ('REPORT_SUBGROUP'),
13174     ('DEPARTMENT'),
13175     ('TERM'),
13176     ('SUGGEST_STATUS'),
13177     ('ITEMTYPECAT');
13178     });
13179
13180 ## Add very special categories
13181     $dbh->do(q{
13182     INSERT IGNORE INTO authorised_value_categories( category_name )
13183     VALUES
13184     ('branches'),
13185     ('itemtypes'),
13186     ('cn_source');
13187     });
13188
13189     $dbh->do(q{
13190     INSERT IGNORE INTO authorised_value_categories( category_name )
13191     VALUES
13192     ('WITHDRAWN'),
13193     ('RESTRICTED'),
13194     ('NOT_LOAN'),
13195     ('CCODE'),
13196     ('LOC'),
13197     ('STACK');
13198     });
13199
13200 ## Update the FK
13201     $dbh->do(q{
13202     ALTER TABLE items_search_fields
13203     DROP FOREIGN KEY items_search_fields_authorised_values_category;
13204     });
13205
13206     $dbh->do(q{
13207     ALTER TABLE items_search_fields
13208     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;
13209     });
13210
13211     $dbh->do(q{
13212     ALTER TABLE authorised_values
13213     ADD CONSTRAINT `authorised_values_authorised_values_category` FOREIGN KEY (`category`) REFERENCES `authorised_value_categories` (`category_name`) ON DELETE CASCADE ON UPDATE CASCADE;
13214     });
13215
13216     $dbh->do(q{
13217             INSERT IGNORE INTO authorised_value_categories( category_name ) SELECT DISTINCT(authorised_value) FROM marc_subfield_structure;
13218             });
13219
13220     $dbh->do(q{
13221             UPDATE marc_subfield_structure SET authorised_value = NULL WHERE authorised_value = '';
13222             });
13223
13224     # 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)
13225     my $table_sth = $dbh->prepare(qq|SHOW CREATE TABLE marc_subfield_structure|);
13226     $table_sth->execute;
13227     my @table = $table_sth->fetchrow_array;
13228     if ( $table[1] !~ /COLLATE=utf8_unicode_ci/ and $table[1] !~ /COLLATE=utf8mb4_unicode_ci/ ) { #catches utf8mb4 collated tables
13229         $dbh->do(qq|ALTER TABLE marc_subfield_structure CHARACTER SET utf8 COLLATE utf8_unicode_ci|);
13230     }
13231     $dbh->do(q{
13232             ALTER TABLE marc_subfield_structure
13233             MODIFY COLUMN authorised_value VARCHAR(32) DEFAULT NULL,
13234             ADD CONSTRAINT marc_subfield_structure_ibfk_1 FOREIGN KEY (authorised_value) REFERENCES authorised_value_categories (category_name) ON UPDATE CASCADE ON DELETE SET NULL;
13235             });
13236
13237       print "Upgrade to $DBversion done (Bug 17216 - Add a new table to store authorized value categories)\n";
13238       SetVersion($DBversion);
13239 }
13240
13241 $DBversion = "16.06.00.034";
13242 if ( CheckVersion($DBversion) ) {
13243     $dbh->do(q{
13244         ALTER TABLE biblioitems DROP COLUMN marc;
13245     });
13246     $dbh->do(q{
13247         ALTER TABLE deletedbiblioitems DROP COLUMN marc;
13248     });
13249
13250     print "Upgrade to $DBversion done (Bug 10455 - remove redundant 'biblioitems.marc' field)\n";
13251     SetVersion($DBversion);
13252 }
13253
13254 $DBversion = '16.06.00.035';
13255 if ( CheckVersion($DBversion) ) {
13256     $dbh->do(q{
13257         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
13258          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'
13259          FROM systempreferences WHERE variable='AllowItemsOnHoldCheckout';
13260     });
13261
13262     print "Upgrade to $DBversion done (Bug 15131: Give SCO separate control for AllowItemsOnHoldCheckout)\n";
13263     SetVersion($DBversion);
13264 }
13265
13266 $DBversion = '16.06.00.036';
13267 if ( CheckVersion($DBversion) ) {
13268     $dbh->do(q{
13269         CREATE TABLE IF NOT EXISTS `housebound_profile` (
13270           `borrowernumber` int(11) NOT NULL, -- Number of the borrower associated with this profile.
13271           `day` text NOT NULL,  -- The preferred day of the week for delivery.
13272           `frequency` text NOT NULL, -- The Authorised_Value definining the pattern for delivery.
13273           `fav_itemtypes` text default NULL, -- Free text describing preferred itemtypes.
13274           `fav_subjects` text default NULL, -- Free text describing preferred subjects.
13275           `fav_authors` text default NULL, -- Free text describing preferred authors.
13276           `referral` text default NULL, -- Free text indicating how the borrower was added to the service.
13277           `notes` text default NULL, -- Free text for additional notes.
13278           PRIMARY KEY  (`borrowernumber`),
13279           CONSTRAINT `housebound_profile_bnfk`
13280             FOREIGN KEY (`borrowernumber`)
13281             REFERENCES `borrowers` (`borrowernumber`)
13282             ON UPDATE CASCADE ON DELETE CASCADE
13283         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13284     });
13285     $dbh->do(q{
13286         CREATE TABLE IF NOT EXISTS `housebound_visit` (
13287           `id` int(11) NOT NULL auto_increment, -- ID of the visit.
13288           `borrowernumber` int(11) NOT NULL, -- Number of the borrower, & the profile, linked to this visit.
13289           `appointment_date` date default NULL, -- Date of visit.
13290           `day_segment` varchar(10),  -- Rough time frame: 'morning', 'afternoon' 'evening'
13291           `chooser_brwnumber` int(11) default NULL, -- Number of the borrower to choose items  for delivery.
13292           `deliverer_brwnumber` int(11) default NULL, -- Number of the borrower to deliver items.
13293           PRIMARY KEY  (`id`),
13294           CONSTRAINT `houseboundvisit_bnfk`
13295             FOREIGN KEY (`borrowernumber`)
13296             REFERENCES `housebound_profile` (`borrowernumber`)
13297             ON UPDATE CASCADE ON DELETE CASCADE,
13298           CONSTRAINT `houseboundvisit_bnfk_1`
13299             FOREIGN KEY (`chooser_brwnumber`)
13300             REFERENCES `borrowers` (`borrowernumber`)
13301             ON UPDATE CASCADE ON DELETE CASCADE,
13302           CONSTRAINT `houseboundvisit_bnfk_2`
13303             FOREIGN KEY (`deliverer_brwnumber`)
13304             REFERENCES `borrowers` (`borrowernumber`)
13305             ON UPDATE CASCADE ON DELETE CASCADE
13306         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13307     });
13308     $dbh->do(q{
13309         CREATE TABLE IF NOT EXISTS `housebound_role` (
13310           `borrowernumber_id` int(11) NOT NULL, -- borrowernumber link
13311           `housebound_chooser` tinyint(1) NOT NULL DEFAULT 0, -- set to 1 to indicate this patron is a housebound chooser volunteer
13312           `housebound_deliverer` tinyint(1) NOT NULL DEFAULT 0, -- set to 1 to indicate this patron is a housebound deliverer volunteer
13313           PRIMARY KEY (`borrowernumber_id`),
13314           CONSTRAINT `houseboundrole_bnfk`
13315             FOREIGN KEY (`borrowernumber_id`)
13316             REFERENCES `borrowers` (`borrowernumber`)
13317             ON UPDATE CASCADE ON DELETE CASCADE
13318         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13319     });
13320     $dbh->do(q{
13321         INSERT IGNORE INTO systempreferences
13322                (variable,value,options,explanation,type) VALUES
13323                ('HouseboundModule',0,'',
13324                'If ON, enable housebound module functionality.','YesNo');
13325     });
13326     $dbh->do(q{
13327         INSERT IGNORE INTO authorised_value_categories( category_name ) VALUES
13328             ('HSBND_FREQ');
13329     });
13330     $dbh->do(q{
13331         INSERT IGNORE INTO authorised_values (category, authorised_value, lib) VALUES
13332                ('HSBND_FREQ','EW','Every week');
13333     });
13334
13335     print "Upgrade to $DBversion done (Bug 5670 - Housebound Readers Module)\n";
13336     SetVersion($DBversion);
13337 }
13338
13339 $DBversion = "16.06.00.037";
13340 if ( CheckVersion($DBversion) ) {
13341     $dbh->do(q{
13342         ALTER TABLE `issuingrules` ADD `article_requests` ENUM( 'no', 'yes', 'bib_only', 'item_only' ) NOT NULL DEFAULT 'no' AFTER `opacitemholds`;
13343     });
13344     $dbh->do(q{
13345         INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES
13346             ('ArticleRequests', '0', NULL, 'Enables the article request feature', 'YesNo'),
13347             ('ArticleRequestsMandatoryFields', '', NULL, 'Comma delimited list of required fields for bibs where article requests rule = ''yes''', 'multiple'),
13348             ('ArticleRequestsMandatoryFieldsItemsOnly', '', NULL, 'Comma delimited list of required fields for bibs where article requests rule = ''item_only''', 'multiple'),
13349             ('ArticleRequestsMandatoryFieldsRecordOnly', '', NULL, 'Comma delimited list of required fields for bibs where article requests rule = ''bib_only''', 'multiple');
13350     });
13351     $dbh->do(q{
13352         CREATE TABLE IF NOT EXISTS `article_requests` (
13353           `id` int(11) NOT NULL AUTO_INCREMENT,
13354           `borrowernumber` int(11) NOT NULL,
13355           `biblionumber` int(11) NOT NULL,
13356           `itemnumber` int(11) DEFAULT NULL,
13357           `branchcode` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
13358           `title` text,
13359           `author` text,
13360           `volume` text,
13361           `issue` text,
13362           `date` text,
13363           `pages` text,
13364           `chapters` text,
13365           `patron_notes` text,
13366           `status` enum('PENDING','PROCESSING','COMPLETED','CANCELED') NOT NULL DEFAULT 'PENDING',
13367           `notes` text,
13368           `created_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
13369           `updated_on` timestamp NULL DEFAULT NULL,
13370           PRIMARY KEY (`id`),
13371           KEY `borrowernumber` (`borrowernumber`),
13372           KEY `biblionumber` (`biblionumber`),
13373           KEY `itemnumber` (`itemnumber`),
13374           KEY `branchcode` (`branchcode`),
13375           CONSTRAINT `article_requests_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
13376           CONSTRAINT `article_requests_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
13377           CONSTRAINT `article_requests_ibfk_3` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE SET NULL ON UPDATE CASCADE,
13378           CONSTRAINT `article_requests_ibfk_4` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE SET NULL ON UPDATE CASCADE
13379         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13380     });
13381     $dbh->do(q{
13382         INSERT INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`) VALUES
13383         ('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'),
13384         ('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'),
13385         ('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'),
13386         ('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'),
13387         ('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');
13388     });
13389
13390     print "Upgrade to $DBversion done (Bug 14610 - Add ability to place article requests in Koha)\n";
13391     SetVersion($DBversion);
13392 }
13393
13394 $DBversion = '16.06.00.038';
13395 if ( CheckVersion($DBversion) ) {
13396     $dbh->do(q{
13397         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');
13398     });
13399
13400     print "Upgrade to $DBversion done (Bug 14874 - Add ability to search for patrons by date of birth from checkout and patron quick searches)\n";
13401     SetVersion($DBversion);
13402 }
13403
13404 $DBversion = "16.06.00.039";
13405 if ( CheckVersion($DBversion) ) {
13406
13407     my $sth = $dbh->prepare(q{
13408         SELECT s.itemnumber, i.itype, b.itemtype
13409         FROM
13410          ( SELECT DISTINCT itemnumber
13411            FROM statistics
13412            WHERE ( type = "return" OR type = "localuse" ) AND
13413                  itemtype IS NULL
13414          ) s
13415         LEFT JOIN
13416          ( SELECT itemnumber,biblionumber, itype
13417              FROM items
13418            UNION
13419            SELECT itemnumber,biblionumber, itype
13420              FROM deleteditems
13421          ) i
13422         ON (s.itemnumber=i.itemnumber)
13423         LEFT JOIN
13424          ( SELECT biblionumber, itemtype
13425              FROM biblioitems
13426            UNION
13427            SELECT biblionumber, itemtype
13428              FROM deletedbiblioitems
13429          ) b
13430         ON (i.biblionumber=b.biblionumber);
13431     });
13432     $sth->execute();
13433
13434     my $update_sth = $dbh->prepare(q{
13435         UPDATE statistics
13436         SET itemtype=?
13437         WHERE itemnumber=? AND itemtype IS NULL
13438     });
13439     my $ilevel_itypes = C4::Context->preference('item-level_itypes');
13440
13441     while ( my ($itemnumber,$item_itype,$biblio_itype) = $sth->fetchrow_array ) {
13442
13443         my $effective_itemtype = $ilevel_itypes
13444                                     ? $item_itype // $biblio_itype
13445                                     : $biblio_itype;
13446         warn "item-level_itypes set but no itype defined for item ($itemnumber)"
13447             if $ilevel_itypes and !defined $item_itype;
13448         $update_sth->execute( $effective_itemtype, $itemnumber );
13449     }
13450
13451     print "Upgrade to $DBversion done (Bug 14598: itemtype is not set on statistics by C4::Circulation::AddReturn)\n";
13452     SetVersion($DBversion);
13453 }
13454
13455 $DBversion = '16.06.00.040';
13456 if ( CheckVersion($DBversion) ) {
13457     $dbh->do(q{
13458         ALTER TABLE `aqcontacts` ADD `orderacquisition` BOOLEAN NOT NULL DEFAULT 0 AFTER `notes`;
13459     });
13460     $dbh->do(q{
13461         INSERT IGNORE INTO `letter` (module, code, name, title, content, message_transport_type) VALUES
13462         ('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');
13463     });
13464
13465     print "Upgrade to $DBversion done (Bug 5260 - Add option to send an order by e-mail to the acquisition module)\n";
13466     SetVersion($DBversion);
13467 }
13468
13469 $DBversion = '16.06.00.041';
13470 if ( CheckVersion($DBversion) ) {
13471     $dbh->do(q{
13472         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')
13473     });
13474
13475     print "Upgrade to $DBversion done (Bug 14629 - Add aggressive ISSN matching feature equivalent to the aggressive ISBN matcher)\n";
13476     SetVersion($DBversion);
13477 }
13478
13479 $DBversion = '16.06.00.042';
13480 if ( CheckVersion($DBversion) ) {
13481     $dbh->do(q|
13482         ALTER TABLE aqorders
13483             ADD COLUMN unitprice_tax_excluded decimal(28,6) default NULL AFTER unitprice,
13484             ADD COLUMN unitprice_tax_included decimal(28,6) default NULL AFTER unitprice_tax_excluded,
13485             ADD COLUMN rrp_tax_excluded decimal(28,6) default NULL AFTER rrp,
13486             ADD COLUMN rrp_tax_included decimal(28,6) default NULL AFTER rrp_tax_excluded,
13487             ADD COLUMN ecost_tax_excluded decimal(28,6) default NULL AFTER ecost,
13488             ADD COLUMN ecost_tax_included decimal(28,6) default NULL AFTER ecost_tax_excluded,
13489             ADD COLUMN tax_value decimal(6,4) default NULL AFTER gstrate
13490     |);
13491
13492     # rename gstrate with tax_rate
13493     $dbh->do(q|ALTER TABLE aqorders CHANGE COLUMN gstrate tax_rate decimal(6,4) DEFAULT NULL|);
13494     $dbh->do(q|ALTER TABLE aqbooksellers CHANGE COLUMN gstrate tax_rate decimal(6,4) DEFAULT NULL|);
13495
13496     # Fill the new columns
13497     my $orders = $dbh->selectall_arrayref(q|
13498         SELECT * FROM aqorders
13499     |, { Slice => {} } );
13500
13501     my $sth_update_order = $dbh->prepare(q|
13502         UPDATE aqorders
13503         SET unitprice_tax_excluded = ?,
13504             unitprice_tax_included = ?,
13505             rrp_tax_excluded = ?,
13506             rrp_tax_included = ?,
13507             ecost_tax_excluded = ?,
13508             ecost_tax_included = ?,
13509             tax_value = ?
13510         WHERE ordernumber = ?
13511     |);
13512
13513     my $sth_get_bookseller = $dbh->prepare(q|
13514         SELECT aqbooksellers.*
13515         FROM aqbooksellers
13516         LEFT JOIN aqbasket ON aqbasket.booksellerid = aqbooksellers.id
13517         LEFT JOIN aqorders ON aqorders.basketno = aqbasket.basketno
13518         WHERE ordernumber = ?
13519     |);
13520
13521     require Number::Format;
13522     my $format = Number::Format->new;
13523     my $precision = 2;
13524     for my $order ( @$orders ) {
13525         $sth_get_bookseller->execute( $order->{ordernumber} );
13526         my ( $bookseller ) = $sth_get_bookseller->fetchrow_hashref;
13527         $order->{rrp}   = $format->round( $order->{rrp}, $precision );
13528         $order->{ecost} = $format->round( $order->{ecost}, $precision );
13529         $order->{tax_rate} ||= 0 ; # tax_rate can be NULL in DB
13530         # Ordering
13531         if ( $bookseller->{listincgst} ) {
13532             $order->{rrp_tax_included} = $order->{rrp};
13533             $order->{rrp_tax_excluded} = $format->round(
13534                 $order->{rrp_tax_included} / ( 1 + $order->{tax_rate} ), $precision );
13535             $order->{ecost_tax_included} = $order->{ecost};
13536             $order->{ecost_tax_excluded} = $format->round(
13537                 $order->{ecost} / ( 1 + $order->{tax_rate} ), $precision );
13538         }
13539         else {
13540             $order->{rrp_tax_excluded} = $order->{rrp};
13541             $order->{rrp_tax_included} = $format->round(
13542                 $order->{rrp} * ( 1 + $order->{tax_rate} ), $precision );
13543             $order->{ecost_tax_excluded} = $order->{ecost};
13544             $order->{ecost_tax_included} = $format->round(
13545                 $order->{ecost} * ( 1 + $order->{tax_rate} ), $precision );
13546         }
13547
13548         #receiving
13549         if ( $bookseller->{listincgst} ) {
13550             $order->{unitprice_tax_included} = $format->round( $order->{unitprice}, $precision );
13551             $order->{unitprice_tax_excluded} = $format->round(
13552               $order->{unitprice_tax_included} / ( 1 + $order->{tax_rate} ), $precision );
13553         }
13554         else {
13555             $order->{unitprice_tax_excluded} = $format->round( $order->{unitprice}, $precision );
13556             $order->{unitprice_tax_included} = $format->round(
13557               $order->{unitprice_tax_excluded} * ( 1 + $order->{tax_rate} ), $precision );
13558         }
13559
13560         # If the order is received, the tax is calculated from the unit price
13561         if ( $order->{orderstatus} eq 'complete' ) {
13562             $order->{tax_value} = $format->round(
13563               ( $order->{unitprice_tax_included} - $order->{unitprice_tax_excluded} )
13564               * $order->{quantity}, $precision );
13565         } else {
13566             # otherwise the ecost is used
13567             $order->{tax_value} = $format->round(
13568                 ( $order->{ecost_tax_included} - $order->{ecost_tax_excluded} ) *
13569                   $order->{quantity}, $precision );
13570         }
13571
13572         $sth_update_order->execute(
13573             $order->{unitprice_tax_excluded},
13574             $order->{unitprice_tax_included},
13575             $order->{rrp_tax_excluded},
13576             $order->{rrp_tax_included},
13577             $order->{ecost_tax_excluded},
13578             $order->{ecost_tax_included},
13579             $order->{tax_value},
13580             $order->{ordernumber},
13581         );
13582     }
13583
13584     print "Upgrade to $DBversion done (Bug 13321 - Tax and prices calculation need to be fixed)\n";
13585     SetVersion($DBversion);
13586 }
13587
13588 $DBversion = '16.06.00.043';
13589 if ( CheckVersion($DBversion) ) {
13590     # Add the new columns
13591     $dbh->do(q|
13592         ALTER TABLE aqorders
13593             ADD COLUMN tax_rate_on_ordering   decimal(6,4) default NULL AFTER tax_rate,
13594             ADD COLUMN tax_rate_on_receiving  decimal(6,4) default NULL AFTER tax_rate_on_ordering,
13595             ADD COLUMN tax_value_on_ordering  decimal(28,6) default NULL AFTER tax_value,
13596             ADD COLUMN tax_value_on_receiving decimal(28,6) default NULL AFTER tax_value_on_ordering
13597     |);
13598
13599     my $orders = $dbh->selectall_arrayref(q|
13600         SELECT * FROM aqorders
13601     |, { Slice => {} } );
13602
13603     my $sth_update_order = $dbh->prepare(q|
13604         UPDATE aqorders
13605         SET tax_rate_on_ordering = tax_rate,
13606             tax_rate_on_receiving = tax_rate,
13607             tax_value_on_ordering = ?,
13608             tax_value_on_receiving = ?
13609         WHERE ordernumber = ?
13610     |);
13611
13612     for my $order (@$orders) {
13613         my $tax_value_on_ordering =
13614           $order->{quantity} *
13615           $order->{ecost_tax_excluded} *
13616           $order->{tax_rate};
13617
13618         my $tax_value_on_receiving =
13619           ( defined $order->{unitprice_tax_excluded} )
13620           ? $order->{quantity} * $order->{unitprice_tax_excluded} * $order->{tax_rate}
13621           : undef;
13622
13623         $sth_update_order->execute( $tax_value_on_ordering,
13624             $tax_value_on_receiving, $order->{ordernumber} );
13625     }
13626
13627     # Remove the old columns
13628     $dbh->do(q|
13629         ALTER TABLE aqorders
13630             CHANGE COLUMN tax_value tax_value_bak  decimal(28,6) default NULL,
13631             CHANGE COLUMN tax_rate tax_rate_bak decimal(6,4) default NULL
13632     |);
13633
13634     print "Upgrade to $DBversion done (Bug 13323 - Change the tax rate on receiving)\n";
13635     SetVersion($DBversion);
13636 }
13637
13638 $DBversion = '16.06.00.044';
13639 if ( CheckVersion($DBversion) ) {
13640     $dbh->do(q{
13641         ALTER TABLE `messages`
13642         ADD `manager_id` int(11) NULL,
13643         ADD FOREIGN KEY (`manager_id`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL;
13644     });
13645
13646     print "Upgrade to $DBversion done (Bug 17397 - Show name of librarian who created circulation message)\n";
13647     SetVersion($DBversion);
13648 }
13649
13650 $DBversion = '16.06.00.045';
13651 if ( CheckVersion($DBversion) ) {
13652     $dbh->do(q{
13653         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";
13654     });
13655
13656     print "Upgrade to $DBversion done (Bug 17443 - Make possible to renew patron by later of expiry and current date)\n";
13657     SetVersion($DBversion);
13658 }
13659
13660 $DBversion = '16.06.00.046';
13661 if ( CheckVersion($DBversion) ) {
13662     $dbh->do(q{
13663         ALTER TABLE issuingrules ADD COLUMN no_auto_renewal_after INT(4) DEFAULT NULL AFTER auto_renew;
13664     });
13665
13666     print "Upgrade to $DBversion done (Bug 15581 - Add a circ rule to not allow auto-renewals after defined loan period)\n";
13667     SetVersion($DBversion);
13668 }
13669
13670 $DBversion = '16.06.00.047';
13671 if ( CheckVersion($DBversion) ) {
13672     $dbh->do(q{
13673         UPDATE language_descriptions SET description = 'Čeština' WHERE subtag = 'cs' AND type = 'language' AND lang = 'cs'
13674     });
13675
13676     print "Upgrade to $DBversion done (Bug 17518: Displayed language name for Czech is wrong)\n";
13677     SetVersion($DBversion);
13678 }
13679
13680 $DBversion = '16.06.00.048';
13681 if( CheckVersion( $DBversion ) ) {
13682     $dbh->do(q|
13683         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
13684         (13, 'upload_general_files', 'Upload any file'),
13685         (13, 'upload_manage', 'Manage uploaded files');
13686     |);
13687
13688     # Update user_permissions for current users (check count in uploaded_files)
13689     # Note 9 == edit_catalogue and 13 == tools
13690     # We do not insert if someone is superlibrarian, does not have edit_catalogue,
13691     # or already has all tools
13692     $dbh->do(q|
13693         INSERT IGNORE INTO user_permissions (borrowernumber, module_bit, code)
13694         SELECT borrowernumber, 13, 'upload_general_files'
13695         FROM borrowers bo
13696         WHERE flags<>1 AND flags & POW(2,13) = 0 AND
13697             ( flags & POW(2,9) > 0 OR (
13698                 SELECT COUNT(*) FROM user_permissions
13699                 WHERE borrowernumber=bo.borrowernumber AND module_bit=9 ) > 0 )
13700             AND ( SELECT COUNT(*) FROM uploaded_files ) > 0;
13701     |);
13702
13703     SetVersion( $DBversion );
13704     print "Upgrade to $DBversion done (Bug 17663 - Forgotten userpermissions)\n";
13705 }
13706
13707 $DBversion = '16.06.00.049';
13708 if( CheckVersion( $DBversion ) ) {
13709     $dbh->do(q|
13710         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) 
13711         VALUES ('ReplytoDefault',  '',  NULL,  'The default email address to be set as replyto.',  'Free');
13712     |);
13713
13714     $dbh->do(q|
13715         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
13716         VALUES ('ReturnpathDefault',  '',  NULL,  'The default email address to be set as return-path',  'Free');
13717     |);
13718
13719     SetVersion( $DBversion );
13720     print "Upgrade to $DBversion done (Bug 17391 - ReturnpathDefault and ReplyToDefault missing from syspref.sql)\n";
13721 }
13722
13723 $DBversion = "16.06.00.050";
13724 if ( CheckVersion($DBversion) ) {
13725
13726     # If index issn_idx still exists, we assume that dbrev 3.15.00.049 failed,
13727     # and we repeat it (partially).
13728     # Note: the db rev only pertains to biblioitems and is not needed for
13729     # deletedbiblioitems.
13730
13731     my $temp = $dbh->selectall_arrayref( "SHOW INDEXES FROM biblioitems WHERE key_name = 'issn_idx'" );
13732
13733     if( @$temp > 0 ) {
13734         $dbh->do( "ALTER TABLE biblioitems DROP INDEX isbn" );
13735         $dbh->do( "ALTER TABLE biblioitems DROP INDEX issn" );
13736         $dbh->do( "ALTER TABLE biblioitems DROP INDEX issn_idx" );
13737         $dbh->do( "ALTER TABLE biblioitems CHANGE isbn isbn MEDIUMTEXT NULL DEFAULT NULL, CHANGE issn issn MEDIUMTEXT NULL DEFAULT NULL" );
13738         $dbh->do( "ALTER TABLE biblioitems ADD INDEX isbn ( isbn ( 255 ) ), ADD INDEX issn ( issn ( 255 ) )" );
13739         print "Upgrade to $DBversion done (Bug 8835). Removed issn_idx.\n";
13740     } else {
13741         print "Upgrade to $DBversion done (Bug 8835). Everything is fine.\n";
13742     }
13743
13744     SetVersion($DBversion);
13745 }
13746
13747 $DBversion = "16.11.00.000";
13748 if ( CheckVersion($DBversion) ) {
13749     print "Upgrade to $DBversion done (Koha 16.11)\n";
13750     SetVersion($DBversion);
13751 }
13752
13753 $DBversion = "16.12.00.000";
13754 if ( CheckVersion($DBversion) ) {
13755     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";
13756     SetVersion($DBversion);
13757 }
13758
13759 $DBversion = "16.12.00.001";
13760 if ( CheckVersion($DBversion) ) {
13761     $dbh->do(q{
13762         ALTER TABLE borrower_modifications
13763         ADD COLUMN extended_attributes text DEFAULT NULL
13764         AFTER privacy
13765     });
13766
13767     print "Upgrade to $DBversion done (Bug 17767 - Let Koha::Patron::Modification handle extended attributes)\n";
13768     SetVersion($DBversion);
13769 }
13770
13771 $DBversion = '16.12.00.002';
13772 if ( CheckVersion($DBversion) ) {
13773     unless (column_exists( 'branchtransfers', 'branchtransfer_id' )
13774         and index_exists( 'branchtransfers', 'PRIMARY' ) )
13775     {
13776         $dbh->do(
13777             "ALTER TABLE branchtransfers
13778                  ADD COLUMN branchtransfer_id int(12) NOT NULL auto_increment FIRST, ADD CONSTRAINT PRIMARY KEY (branchtransfer_id);"
13779         );
13780     }
13781
13782     SetVersion($DBversion);
13783     print "Upgrade to $DBversion done (Bug 14187 - branchtransfer needs a primary key (id) for DBIx and common sense.)\n";
13784 }
13785
13786 $DBversion = '16.12.00.003';
13787 if ( CheckVersion($DBversion) ) {
13788     $dbh->do(q{DELETE FROM systempreferences WHERE variable="Persona"});
13789     SetVersion($DBversion);
13790     print "Upgrade to $DBversion done (Bug 17486 - Remove 'Mozilla Persona' as an authentication method)\n";
13791 }
13792
13793 $DBversion = '16.12.00.004';
13794 if ( CheckVersion($DBversion) ) {
13795     $dbh->do(q{
13796         CREATE TABLE biblio_metadata (
13797             `id` INT(11) NOT NULL AUTO_INCREMENT,
13798             `biblionumber` INT(11) NOT NULL,
13799             `format` VARCHAR(16) NOT NULL,
13800             `marcflavour` VARCHAR(16) NOT NULL,
13801             `metadata` LONGTEXT NOT NULL,
13802             PRIMARY KEY(id),
13803             UNIQUE KEY `biblio_metadata_uniq_key` (`biblionumber`,`format`,`marcflavour`),
13804             CONSTRAINT `biblio_metadata_fk_1` FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
13805         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13806     });
13807     $dbh->do(q{
13808         CREATE TABLE deletedbiblio_metadata (
13809             `id` INT(11) NOT NULL AUTO_INCREMENT,
13810             `biblionumber` INT(11) NOT NULL,
13811             `format` VARCHAR(16) NOT NULL,
13812             `marcflavour` VARCHAR(16) NOT NULL,
13813             `metadata` LONGTEXT NOT NULL,
13814             PRIMARY KEY(id),
13815             UNIQUE KEY `deletedbiblio_metadata_uniq_key` (`biblionumber`,`format`,`marcflavour`),
13816             CONSTRAINT `deletedbiblio_metadata_fk_1` FOREIGN KEY (biblionumber) REFERENCES deletedbiblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
13817         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13818     });
13819     $dbh->do(q{
13820         INSERT INTO biblio_metadata ( biblionumber, format, marcflavour, metadata ) SELECT biblionumber, 'marcxml', 'CHANGEME', marcxml FROM biblioitems;
13821     });
13822     $dbh->do(q{
13823         INSERT INTO deletedbiblio_metadata ( biblionumber, format, marcflavour, metadata ) SELECT biblionumber, 'marcxml', 'CHANGEME', marcxml FROM deletedbiblioitems;
13824     });
13825     $dbh->do(q{
13826         UPDATE biblio_metadata SET marcflavour = (SELECT value FROM systempreferences WHERE variable="marcflavour");
13827     });
13828     $dbh->do(q{
13829         UPDATE deletedbiblio_metadata SET marcflavour = (SELECT value FROM systempreferences WHERE variable="marcflavour");
13830     });
13831     $dbh->do(q{
13832         ALTER TABLE biblioitems DROP COLUMN marcxml;
13833     });
13834     $dbh->do(q{
13835         ALTER TABLE deletedbiblioitems DROP COLUMN marcxml;
13836     });
13837     SetVersion($DBversion);
13838     print "Upgrade to $DBversion done (Bug 17196 - Move marcxml out of the biblioitems table)\n";
13839 }
13840
13841 $DBversion = '16.12.00.005';
13842 if( CheckVersion( $DBversion ) ) {
13843     $dbh->do( "INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('AuthorityMergeMode','loose','loose|strict','Authority merge mode','Choice')");
13844
13845     SetVersion( $DBversion );
13846     print "Upgrade to $DBversion done (Bug 17913 - AuthorityMergeMode)\n";
13847 }
13848
13849 $DBversion = "16.12.00.006";
13850 if ( CheckVersion($DBversion) ) {
13851     unless (     column_exists( 'borrower_attributes', 'id' )
13852              and index_exists( 'borrower_attributes', 'PRIMARY' ) )
13853     {
13854         $dbh->do(q{
13855             ALTER TABLE `borrower_attributes`
13856                 ADD `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
13857         });
13858     }
13859
13860     print "Upgrade to $DBversion done (Bug 17813: Table borrower_attributes needs a primary key\n";
13861     SetVersion($DBversion);
13862 }
13863
13864 $DBversion = "16.12.00.007";
13865 if( CheckVersion( $DBversion ) ) {
13866
13867     if ( column_exists('opac_news', 'new' ) ) {
13868         $dbh->do(q|ALTER TABLE opac_news CHANGE COLUMN new content text NOT NULL|);
13869     }
13870
13871     $dbh->do(q|
13872         UPDATE letter SET content = REPLACE(content, "<<opac_news.new>>", "<<opac_news.content>>") WHERE content LIKE "%<<opac_news.new>>%"
13873     |);
13874
13875     SetVersion( $DBversion );
13876     print "Upgrade to $DBversion done (Bug 17960 - Rename opac_news with opac_news.content (template notices have been updated!))\n";
13877 }
13878
13879 $DBversion = "16.12.00.008";
13880 if( CheckVersion( $DBversion ) ) {
13881     $dbh->do(q{
13882         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
13883         ('MarcItemFieldsToOrder','','Set the mapping values for new item records created from a MARC record in a staged file. In a YAML format.', NULL, 'textarea');
13884     });
13885
13886     SetVersion( $DBversion );
13887     print "Upgrade to $DBversion done (Bug 15503 - Grab Item Information from Order Files)\n";
13888 }
13889
13890 $DBversion = "16.12.00.009";
13891 if( CheckVersion( $DBversion ) ) {
13892     $dbh->do(q{
13893         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
13894         ('OPACHoldsIfAvailableAtPickup','1','','Allow to pickup up holds at libraries where the item is available','YesNo');
13895     });
13896
13897     $dbh->do(q{
13898         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
13899         ('OPACHoldsIfAvailableAtPickupExceptions','','','List the patron categories not affected by OPACHoldsIfAvailableAtPickup if off','Free');
13900     });
13901
13902     SetVersion( $DBversion );
13903     print "Upgrade to $DBversion done (Bug 17453 - Inter-site holds improvement)\n";
13904 }
13905
13906 $DBversion = "16.12.00.010";
13907 if( CheckVersion( $DBversion ) ) {
13908     $dbh->do(q{
13909         ALTER TABLE borrowers ADD overdrive_auth_token text default NULL AFTER lastseen;
13910     });
13911
13912     $dbh->do(q{
13913         ALTER TABLE deletedborrowers ADD overdrive_auth_token text default NULL AFTER lastseen;
13914     });
13915
13916     $dbh->do(q{
13917         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
13918         VALUES ('OverDriveCirculation','0','Enable client to see their OverDrive account','','YesNo');
13919     });
13920
13921     SetVersion( $DBversion );
13922     print "Upgrade to $DBversion done (Bug 16034 - Integration with OverDrive Patron API)\n";
13923 }
13924
13925 $DBversion = "16.12.00.011";
13926 if( CheckVersion( $DBversion ) ) {
13927     $dbh->do(q{
13928         ALTER TABLE search_field CHANGE COLUMN type type ENUM('', 'string', 'date', 'number', 'boolean', 'sum') NOT NULL
13929         COMMENT 'what type of data this holds, relevant when storing it in the search engine';
13930     });
13931
13932     SetVersion( $DBversion );
13933     print "Upgrade to $DBversion done (Bug 17260 - updatedatabase.pl fails on invalid entries in ENUM and BOOLEAN columns)\n";
13934 }
13935
13936 $DBversion = "16.12.00.012";
13937 if( CheckVersion( $DBversion ) ) {
13938     $dbh->do(q{
13939         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`)
13940         VALUES ('OpacNewsLibrarySelect', '0', '', 'Show selector for branches on OPAC news page', 'YesNo');
13941     });
13942
13943     SetVersion( $DBversion );
13944     print "Upgrade to $DBversion done (Bug 14764 - Add OPAC News branch selector)\n";
13945 }
13946
13947 $DBversion = "16.12.00.013";
13948 if( CheckVersion( $DBversion ) ) {
13949     $dbh->do(q{
13950         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
13951         VALUES ('CircSidebar','0','','Activate or deactivate the navigation sidebar on all Circulation pages','YesNo');
13952     });
13953
13954     SetVersion( $DBversion );
13955     print "Upgrade to $DBversion done (Bug 16530 - Add a circ sidebar navigation menu)\n";
13956 }
13957
13958 $DBversion = "16.12.00.014";
13959 if( CheckVersion( $DBversion ) ) {
13960     $dbh->do(q{
13961             INSERT INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
13962             ('LoadSearchHistoryToTheFirstLoggedUser', '1', NULL, 'If ON, the next user will automatically get the last searches in his history', 'YesNo');
13963             });
13964             SetVersion( $DBversion );
13965             print "Upgrade to $DBversion done (Bug 8010 - Search history can be added to the wrong patron)\n";
13966             }
13967
13968 $DBversion = "16.12.00.015";
13969 if( CheckVersion( $DBversion ) ) {
13970     unless( column_exists( 'branches', 'geolocation' ) ) {
13971         $dbh->do(q|
13972                 ALTER TABLE branches ADD COLUMN geolocation VARCHAR(255) DEFAULT NULL after opac_info
13973                 |);
13974     }
13975
13976     $dbh->do(q|
13977             INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type ) VALUES ('UsageStatsGeolocation', '', NULL, 'Geolocation of the main library', 'Free');
13978             |);
13979     $dbh->do(q|
13980             INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type ) VALUES ('UsageStatsLibrariesInfo', '', NULL, 'Share libraries information', 'YesNo');
13981             |);
13982     $dbh->do(q|
13983             INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type ) VALUES ('UsageStatsPublicID', '', NULL, 'Public ID for Hea website', 'Free');
13984             |);
13985         
13986         SetVersion( $DBversion );
13987     print "Upgrade to $DBversion done (Bug 18066 - Hea version 2)\n";
13988 }
13989
13990 $DBversion = "16.12.00.016";
13991 if ( CheckVersion($DBversion) ) {
13992     unless ( column_exists( 'borrower_attribute_types', 'opac_editable' ) )
13993     {
13994         $dbh->do(q{
13995             ALTER TABLE borrower_attribute_types
13996                 ADD COLUMN `opac_editable` tinyint(1) NOT NULL default 0 AFTER `opac_display`
13997         });
13998     }
13999
14000     print "Upgrade to $DBversion done (Bug 13757: Make patron attributes editable in the opac if set to 'editable in OPAC)'\n";
14001     SetVersion($DBversion);
14002 }
14003
14004 $DBversion = "16.12.00.017";
14005 if ( CheckVersion($DBversion) ) {
14006     $dbh->do(q{
14007         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
14008         VALUES ('CumulativeRestrictionPeriods',  0,  NULL,  'Cumulate the restriction periods instead of keeping the highest',  'YesNo')
14009     });
14010
14011     print "Upgrade to $DBversion done (Bug 14146 - Additional days are not added to restriction period when checking-in several overdues for same patron)'\n";
14012     SetVersion($DBversion);
14013 }
14014
14015 $DBversion = "16.12.00.018";
14016 if ( CheckVersion($DBversion) ) {
14017     $dbh->do(q{
14018         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
14019             SELECT 'ExportCircHistory', COUNT(*), NULL, "Display the export circulation options",  'YesNo'
14020             FROM systempreferences
14021             WHERE ( variable = 'ExportRemoveFields' AND value != "" AND value IS NOT NULL )
14022                 OR ( variable = 'ExportWithCsvProfile' AND value != "" AND value IS NOT NULL );
14023     });
14024
14025     $dbh->do(q{
14026         DELETE FROM systempreferences WHERE variable="ExportWithCsvProfile";
14027     });
14028
14029     print "Upgrade to $DBversion done (Bug 15498 - Replace ExportWithCsvProfile with ExportCircHistory)'\n";
14030     SetVersion($DBversion);
14031 }
14032
14033 $DBversion = "16.12.00.019";
14034 if( CheckVersion( $DBversion ) ) {
14035     if ( column_exists( 'issues', 'return' ) ) {
14036         $dbh->do(q|ALTER TABLE issues DROP column `return`|);
14037     }
14038
14039     if ( column_exists( 'old_issues', 'return' ) ) {
14040         $dbh->do(q|ALTER TABLE old_issues DROP column `return`|);
14041     }
14042
14043     SetVersion( $DBversion );
14044     print "Upgrade to $DBversion done (Bug 18173 - Remove issues.return DB field)\n";
14045 }
14046
14047 $DBversion = "16.12.00.020";
14048 if( CheckVersion( $DBversion ) ) {
14049     $dbh->do(q{
14050         UPDATE systempreferences SET options="any_time_is_placed|not_always|any_time_is_collected" WHERE variable="HoldFeeMode";
14051     });
14052
14053     $dbh->do(q{
14054         UPDATE systempreferences SET value="any_time_is_placed" WHERE variable="HoldFeeMode" AND value="always";
14055     });
14056
14057     SetVersion( $DBversion );
14058     print "Upgrade to $DBversion done (Bug 17560 - Hold fee placement at point of checkout)\n";
14059 }
14060
14061 $DBversion = "16.12.00.021";
14062 if( CheckVersion( $DBversion ) ) {
14063     $dbh->do(q{
14064         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14065         ('RenewalLog','0','','If ON, log information about renewals','YesNo');
14066     });
14067
14068     SetVersion( $DBversion );
14069     print "Upgrade to $DBversion done (Bug 17708 - Renewal log seems empty)\n";
14070 }
14071
14072 $DBversion = "16.12.00.022";
14073 if( CheckVersion( $DBversion ) ) {
14074     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";
14075     SetVersion( $DBversion );
14076     print "Upgrade to $DBversion done (Bug 17866 - Change sender for serial claim notifications)\n";
14077 }
14078
14079 $DBversion = '16.12.00.023';
14080 if( CheckVersion( $DBversion ) ) {
14081     my $oldval = C4::Context->preference('dontmerge');
14082     my $newval = $oldval ? 0 : 50;
14083
14084     # Remove dontmerge, add AuthorityMergeLimit
14085     $dbh->do(q{
14086         DELETE FROM systempreferences WHERE variable = 'dontmerge';
14087     });
14088     $dbh->do(qq{
14089         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');
14090     });
14091
14092     $dbh->do(q{
14093         ALTER TABLE need_merge_authorities
14094             ADD COLUMN authid_new BIGINT AFTER authid,
14095             ADD COLUMN reportxml text AFTER authid_new,
14096             ADD COLUMN timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
14097     });
14098
14099     $dbh->do(q{
14100         UPDATE need_merge_authorities SET authid_new=authid WHERE done <> 1
14101     });
14102
14103     SetVersion( $DBversion );
14104     if( $newval == 0 ) {
14105         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";
14106     }
14107     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";
14108     print "Upgrade to $DBversion done (Bug 9988 - Add AuthorityMergeLimit)\n";
14109 }
14110
14111 $DBversion = '16.12.00.024';
14112 if( CheckVersion( $DBversion ) ) {
14113     $dbh->do(q{
14114         UPDATE systempreferences SET variable="NoticeBcc" WHERE variable="OverdueNoticeBcc";
14115     });
14116
14117     SetVersion( $DBversion );
14118     print "Upgrade to $DBversion done (Bug 14537 - The system preference 'OverdueNoticeBcc' is mis-named.)\n";
14119 }
14120
14121 $DBversion = '16.12.00.025';
14122 if( CheckVersion( $DBversion ) ) {
14123     $dbh->do(q|
14124         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
14125         VALUES ('UploadPurgeTemporaryFilesDays','',NULL,'If not empty, number of days used when automatically deleting temporary uploads','integer');
14126     |);
14127
14128     my ( $cnt ) = $dbh->selectrow_array( "SELECT COUNT(*) FROM uploaded_files WHERE permanent IS NULL or permanent=0" );
14129     if( $cnt ) {
14130         print "NOTE: You have $cnt temporary uploads. You could benefit from setting pref UploadPurgeTemporaryFilesDays now to automatically delete them.\n";
14131     }
14132
14133     SetVersion( $DBversion );
14134     print "Upgrade to $DBversion done (Bug 17669 - Introduce preference for deleting temporary uploads)\n";
14135 }
14136
14137 $DBversion = '16.12.00.026';
14138 if( CheckVersion( $DBversion ) ) {
14139
14140     # In order to be overcomplete, we check if the situation is what we expect
14141     if( !index_exists( 'serialitems', 'PRIMARY' ) ) {
14142         if( index_exists( 'serialitems', 'serialitemsidx' ) ) {
14143             $dbh->do(q|
14144                 ALTER TABLE serialitems ADD PRIMARY KEY (itemnumber), DROP INDEX serialitemsidx;
14145             |);
14146         } else {
14147             $dbh->do(q|ALTER TABLE serialitems ADD PRIMARY KEY (itemnumber)|);
14148         }
14149     }
14150
14151     SetVersion( $DBversion );
14152     print "Upgrade to $DBversion done (Bug 18427 - Add a primary key to serialitems)\n";
14153 }
14154
14155 $DBversion = '16.12.00.027';
14156 if( CheckVersion( $DBversion ) ) {
14157
14158     $dbh->do(q{
14159         CREATE TABLE IF NOT EXISTS club_templates (
14160           id int(11) NOT NULL AUTO_INCREMENT,
14161           `name` tinytext NOT NULL,
14162           description text,
14163           is_enrollable_from_opac tinyint(1) NOT NULL DEFAULT '0',
14164           is_email_required tinyint(1) NOT NULL DEFAULT '0',
14165           branchcode varchar(10) NULL DEFAULT NULL,
14166           date_created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
14167           date_updated timestamp NULL DEFAULT NULL,
14168           is_deletable tinyint(1) NOT NULL DEFAULT '1',
14169           PRIMARY KEY (id),
14170           KEY ct_branchcode (branchcode),
14171           CONSTRAINT `club_templates_ibfk_1` FOREIGN KEY (branchcode) REFERENCES `branches` (branchcode) ON DELETE CASCADE ON UPDATE CASCADE
14172         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14173     });
14174
14175     $dbh->do(q{
14176         CREATE TABLE IF NOT EXISTS clubs (
14177           id int(11) NOT NULL AUTO_INCREMENT,
14178           club_template_id int(11) NOT NULL,
14179           `name` tinytext NOT NULL,
14180           description text,
14181           date_start date DEFAULT NULL,
14182           date_end date DEFAULT NULL,
14183           branchcode varchar(10) NULL DEFAULT NULL,
14184           date_created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
14185           date_updated timestamp NULL DEFAULT NULL,
14186           PRIMARY KEY (id),
14187           KEY club_template_id (club_template_id),
14188           KEY branchcode (branchcode),
14189           CONSTRAINT clubs_ibfk_1 FOREIGN KEY (club_template_id) REFERENCES club_templates (id) ON DELETE CASCADE ON UPDATE CASCADE,
14190           CONSTRAINT clubs_ibfk_2 FOREIGN KEY (branchcode) REFERENCES branches (branchcode)
14191         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14192     });
14193
14194     $dbh->do(q{
14195         CREATE TABLE IF NOT EXISTS club_enrollments (
14196           id int(11) NOT NULL AUTO_INCREMENT,
14197           club_id int(11) NOT NULL,
14198           borrowernumber int(11) NOT NULL,
14199           date_enrolled timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
14200           date_canceled timestamp NULL DEFAULT NULL,
14201           date_created timestamp NULL DEFAULT NULL,
14202           date_updated timestamp NULL DEFAULT NULL,
14203           branchcode varchar(10) NULL DEFAULT NULL,
14204           PRIMARY KEY (id),
14205           KEY club_id (club_id),
14206           KEY borrowernumber (borrowernumber),
14207           KEY branchcode (branchcode),
14208           CONSTRAINT club_enrollments_ibfk_1 FOREIGN KEY (club_id) REFERENCES clubs (id) ON DELETE CASCADE ON UPDATE CASCADE,
14209           CONSTRAINT club_enrollments_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE,
14210           CONSTRAINT club_enrollments_ibfk_3 FOREIGN KEY (branchcode) REFERENCES branches (branchcode) ON DELETE SET NULL ON UPDATE CASCADE
14211         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14212     });
14213
14214     $dbh->do(q{
14215         CREATE TABLE IF NOT EXISTS club_template_enrollment_fields (
14216           id int(11) NOT NULL AUTO_INCREMENT,
14217           club_template_id int(11) NOT NULL,
14218           `name` tinytext NOT NULL,
14219           description text,
14220           authorised_value_category varchar(16) DEFAULT NULL,
14221           PRIMARY KEY (id),
14222           KEY club_template_id (club_template_id),
14223           CONSTRAINT club_template_enrollment_fields_ibfk_1 FOREIGN KEY (club_template_id) REFERENCES club_templates (id) ON DELETE CASCADE ON UPDATE CASCADE
14224         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14225     });
14226
14227     $dbh->do(q{
14228         CREATE TABLE IF NOT EXISTS club_enrollment_fields (
14229           id int(11) NOT NULL AUTO_INCREMENT,
14230           club_enrollment_id int(11) NOT NULL,
14231           club_template_enrollment_field_id int(11) NOT NULL,
14232           `value` text NOT NULL,
14233           PRIMARY KEY (id),
14234           KEY club_enrollment_id (club_enrollment_id),
14235           KEY club_template_enrollment_field_id (club_template_enrollment_field_id),
14236           CONSTRAINT club_enrollment_fields_ibfk_1 FOREIGN KEY (club_enrollment_id) REFERENCES club_enrollments (id) ON DELETE CASCADE ON UPDATE CASCADE,
14237           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
14238         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14239     });
14240
14241     $dbh->do(q{
14242         CREATE TABLE IF NOT EXISTS club_template_fields (
14243           id int(11) NOT NULL AUTO_INCREMENT,
14244           club_template_id int(11) NOT NULL,
14245           `name` tinytext NOT NULL,
14246           description text,
14247           authorised_value_category varchar(16) DEFAULT NULL,
14248           PRIMARY KEY (id),
14249           KEY club_template_id (club_template_id),
14250           CONSTRAINT club_template_fields_ibfk_1 FOREIGN KEY (club_template_id) REFERENCES club_templates (id) ON DELETE CASCADE ON UPDATE CASCADE
14251         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14252     });
14253
14254     $dbh->do(q{
14255         CREATE TABLE IF NOT EXISTS club_fields (
14256           id int(11) NOT NULL AUTO_INCREMENT,
14257           club_template_field_id int(11) NOT NULL,
14258           club_id int(11) NOT NULL,
14259           `value` text,
14260           PRIMARY KEY (id),
14261           KEY club_template_field_id (club_template_field_id),
14262           KEY club_id (club_id),
14263           CONSTRAINT club_fields_ibfk_3 FOREIGN KEY (club_template_field_id) REFERENCES club_template_fields (id) ON DELETE CASCADE ON UPDATE CASCADE,
14264           CONSTRAINT club_fields_ibfk_4 FOREIGN KEY (club_id) REFERENCES clubs (id) ON DELETE CASCADE ON UPDATE CASCADE
14265         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14266     });
14267
14268     $dbh->do(q{
14269         INSERT IGNORE INTO userflags (bit, flag, flagdesc, defaulton) VALUES (21, 'clubs', 'Patron clubs', '0');
14270     });
14271
14272     $dbh->do(q{
14273         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
14274            (21, 'edit_templates', 'Create and update club templates'),
14275            (21, 'edit_clubs', 'Create and update clubs'),
14276            (21, 'enroll', 'Enroll patrons in clubs')
14277         ;
14278     });
14279
14280     SetVersion( $DBversion );
14281     print "Upgrade to $DBversion done (Bug 12461 - Add patron clubs feature)\n";
14282 }
14283
14284 $DBversion = '16.12.00.028';
14285 if( CheckVersion( $DBversion ) ) {
14286     $dbh->do(q{
14287         UPDATE systempreferences  SET options = 'us|de|fr' WHERE variable = 'AddressFormat';
14288     });
14289
14290     SetVersion( $DBversion );
14291     print "Upgrade to $DBversion done (Bug 18110 - Adds FR to the syspref AddressFormat)\n";
14292 }
14293
14294 $DBversion = '16.12.00.029';
14295 if( CheckVersion( $DBversion ) ) {
14296     unless( column_exists( 'issues', 'note' ) ) {
14297         $dbh->do(q|ALTER TABLE issues ADD note mediumtext default NULL AFTER onsite_checkout|);
14298     }
14299     unless( column_exists( 'issues', 'notedate' ) ) {
14300         $dbh->do(q|ALTER TABLE issues ADD notedate datetime default NULL AFTER note|);
14301     }
14302     unless( column_exists( 'old_issues', 'note' ) ) {
14303         $dbh->do(q|ALTER TABLE old_issues ADD note mediumtext default NULL AFTER onsite_checkout|);
14304     }
14305     unless( column_exists( 'old_issues', 'notedate' ) ) {
14306         $dbh->do(q|ALTER TABLE old_issues ADD notedate datetime default NULL AFTER note|);
14307     }
14308
14309     $dbh->do(q|
14310         INSERT IGNORE INTO letter (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`)
14311         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');
14312     |);
14313
14314     $dbh->do(q|
14315         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`,`type`)
14316         VALUES ('AllowCheckoutNotes', '0', NULL, 'Allow patrons to submit notes about checked out items.','YesNo');
14317     |);
14318
14319     SetVersion( $DBversion );
14320     print "Upgrade to $DBversion done (Bug 14224: Add column issues.note and issues.notedate)\n";
14321 }
14322
14323 $DBversion = '16.12.00.030';
14324 if( CheckVersion( $DBversion ) ) {
14325     unless( column_exists( 'issuingrules', 'no_auto_renewal_after_hard_limit' ) ) {
14326         $dbh->do(q{
14327             ALTER TABLE issuingrules ADD COLUMN no_auto_renewal_after_hard_limit DATE DEFAULT NULL AFTER no_auto_renewal_after;
14328         });
14329     }
14330
14331     SetVersion( $DBversion );
14332     print "Upgrade to $DBversion done (Bug 16344 - Add a circ rule to limit the auto renewals given a specific date)\n";
14333 }
14334
14335 $DBversion = '16.12.00.031';
14336 if( CheckVersion( $DBversion ) ) {
14337     if ( !index_exists( 'biblioitems', 'timestamp' ) ) {
14338         $dbh->do("ALTER TABLE biblioitems ADD KEY `timestamp` (`timestamp`);");
14339     }
14340     if ( !index_exists( 'deletedbiblioitems', 'timestamp' ) ) {
14341         $dbh->do("ALTER TABLE deletedbiblioitems ADD KEY `timestamp` (`timestamp`);");
14342     }
14343     if ( !index_exists( 'items', 'timestamp' ) ) {
14344         $dbh->do("ALTER TABLE items ADD KEY `timestamp` (`timestamp`);");
14345     }
14346     if ( !index_exists( 'deleteditems', 'timestamp' ) ) {
14347         $dbh->do("ALTER TABLE deleteditems ADD KEY `timestamp` (`timestamp`);");
14348     }
14349
14350     SetVersion( $DBversion );
14351     print "Upgrade to $DBversion done (Bug 15108: OAI-PMH provider improvements)\n";
14352 }
14353
14354 $DBversion = '16.12.00.032';
14355 if( CheckVersion( $DBversion ) ) {
14356     require Koha::Calendar;
14357     require Koha::Holds;
14358
14359     $dbh->do(q{
14360         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) 
14361         VALUES ('ExcludeHolidaysFromMaxPickUpDelay', '0', 'If ON, reserves max pickup delay takes into account the closed days.', NULL, 'Integer');
14362     });
14363
14364     my $waiting_holds = Koha::Holds->search({ found => 'W', priority => 0 });
14365     my $max_pickup_delay = C4::Context->preference("ReservesMaxPickUpDelay");
14366     while ( my $hold = $waiting_holds->next ) {
14367
14368         my $requested_expiration;
14369         if ($hold->expirationdate) {
14370             $requested_expiration = dt_from_string($hold->expirationdate);
14371         }
14372
14373         my $expirationdate = dt_from_string($hold->waitingdate);
14374         if ( C4::Context->preference("ExcludeHolidaysFromMaxPickUpDelay") ) {
14375             my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
14376             $expirationdate = $calendar->days_forward( $expirationdate, $max_pickup_delay );
14377         } else {
14378             $expirationdate->add( days => $max_pickup_delay );
14379         }
14380
14381         my $cmp = $requested_expiration ? DateTime->compare($requested_expiration, $expirationdate) : 0;
14382         $hold->expirationdate($cmp == -1 ? $requested_expiration->ymd : $expirationdate->ymd)->store;
14383     }
14384
14385     SetVersion( $DBversion );
14386     print "Upgrade to $DBversion done (Bug 12063 - Update reserves.expirationdate)\n";
14387 }
14388
14389 $DBversion = '16.12.00.033';
14390 if( CheckVersion( $DBversion ) ) {
14391
14392     if( !column_exists( 'letter', 'lang' ) ) {
14393         $dbh->do( "ALTER TABLE letter ADD COLUMN lang VARCHAR(25) NOT NULL DEFAULT 'default' AFTER message_transport_type" );
14394     }
14395
14396     if( !column_exists( 'borrowers', 'lang' ) ) {
14397         $dbh->do( "ALTER TABLE borrowers ADD COLUMN lang VARCHAR(25) NOT NULL DEFAULT 'default' AFTER lastseen" );
14398         $dbh->do( "ALTER TABLE deletedborrowers ADD COLUMN lang VARCHAR(25) NOT NULL DEFAULT 'default' AFTER lastseen" );
14399     }
14400
14401     # Add test on existene of this key
14402     $dbh->do( "ALTER TABLE message_transports DROP FOREIGN KEY message_transports_ibfk_3 ");
14403     $dbh->do( "ALTER TABLE letter DROP PRIMARY KEY ");
14404     $dbh->do( "ALTER TABLE letter ADD PRIMARY KEY (`module`, `code`, `branchcode`, `message_transport_type`, `lang`) ");
14405
14406     $dbh->do( "INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
14407         VALUES ('TranslateNotices',  '0',  NULL,  'Allow notices to be translated',  'YesNo') ");
14408
14409     SetVersion( $DBversion );
14410     print "Upgrade to $DBversion done (Bug 17762 - Add columns letter.lang and borrowers.lang to allow translation of notices)\n";
14411 }
14412
14413 $DBversion = '16.12.00.034';
14414 if( CheckVersion( $DBversion ) ) {
14415     $dbh->do(q{
14416         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
14417         VALUES ('OPACFineNoRenewalsBlockAutoRenew','0','','Block/Allow auto renewals if the patron owe more than OPACFineNoRenewals','YesNo')
14418     });
14419
14420     SetVersion( $DBversion );
14421     print "Upgrade to $DBversion done (Bug 15582 - Ability to block auto renewals if the OPACFineNoRenewals amount is reached)\n";
14422 }
14423
14424 $DBversion = '16.12.00.035';
14425 if( CheckVersion( $DBversion ) ) {
14426     if( !column_exists( 'issues', 'auto_renew_error' ) ) {
14427         $dbh->do(q{
14428            ALTER TABLE issues ADD COLUMN auto_renew_error VARCHAR(32) DEFAULT NULL AFTER auto_renew;
14429         });
14430     }
14431
14432     if( !column_exists( 'old_issues', 'auto_renew_error' ) ) {
14433         $dbh->do(q{
14434             ALTER TABLE old_issues ADD COLUMN auto_renew_error VARCHAR(32) DEFAULT NULL AFTER auto_renew;
14435         });
14436     }
14437
14438     $dbh->do(q{
14439         INSERT INTO letter (module, code, name, title, content, message_transport_type) VALUES ('circulation', 'AUTO_RENEWALS', 'notification on auto renewing', 'Auto renewals',
14440 "Dear [% borrower.firstname %] [% borrower.surname %],
14441 [% IF checkout.auto_renew_error %]
14442 The following item [% biblio.title %] has not been correctly renewed
14443 [% IF checkout.auto_renew_error == 'too_many' %]
14444 You have reach the maximum of checkouts possible.
14445 [% ELSIF checkout.auto_renew_error == 'on_reserve' %]
14446 This item is on hold for another patron.
14447 [% ELSIF checkout.auto_renew_error == 'restriction' %]
14448 You are currently restricted.
14449 [% ELSIF checkout.auto_renew_error == 'overdue' %]
14450 You have overdues.
14451 [% ELSIF checkout.auto_renew_error == 'auto_too_late' %]
14452 It\'s too late to renew this checkout.
14453 [% ELSIF checkout.auto_renew_error == 'auto_too_much_oweing' %]
14454 You have too much unpaid fines.
14455 [% END %]
14456 [% ELSE %]
14457 The following item [% biblio.title %] has correctly been renewed and is now due [% checkout.date_due %]
14458 [% END %]", 'email');
14459     });
14460
14461     SetVersion( $DBversion );
14462     print "Upgrade to $DBversion done (Bug 15705 - Notify the user on auto renewing)\n";
14463 }
14464
14465 $DBversion = '16.12.00.036';
14466 if( CheckVersion( $DBversion ) ) {
14467     $dbh->do(q{
14468         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
14469         VALUES ('NumSavedReports', '20', NULL, 'By default, show this number of saved reports.', 'Integer');
14470     });
14471
14472     SetVersion( $DBversion );
14473     print "Upgrade to $DBversion done (Bug 17465 - Add a System Preference to control number of Saved Reports displayed)\n";
14474 }
14475
14476 $DBversion = '16.12.00.037';
14477 if( CheckVersion( $DBversion ) ) {
14478     $dbh->do( q|
14479         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
14480         VALUES ('FailedLoginAttempts','','','Number of login attempts before lockout the patron account','Integer');
14481     |);
14482
14483     unless( column_exists( 'borrowers', 'login_attempts' ) ) {
14484         $dbh->do(q|
14485             ALTER TABLE borrowers ADD COLUMN login_attempts INT(4) DEFAULT 0 AFTER lastseen
14486         |);
14487         $dbh->do(q|
14488             ALTER TABLE deletedborrowers ADD COLUMN login_attempts INT(4) DEFAULT 0 AFTER lastseen
14489         |);
14490     }
14491
14492     SetVersion( $DBversion );
14493     print "Upgrade to $DBversion done (Bug 18314 - Add FailedLoginAttempts and borrowers.login_attempts)\n";
14494 }
14495
14496 $DBversion = '16.12.00.038';
14497 if( CheckVersion( $DBversion ) ) {
14498     $dbh->do(q{
14499         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14500         ('ExportRemoveFields','',NULL,'List of fields for non export in circulation.pl (separated by a space)','Free');
14501     });
14502
14503     SetVersion( $DBversion );
14504     print "Upgrade to $DBversion done (Bug 18663 - Missing db update for ExportRemoveFields)\n";
14505 }
14506
14507 $DBversion = '16.12.00.039';
14508 if( CheckVersion( $DBversion ) ) {
14509     $dbh->do(q{
14510         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14511         ('TalkingTechItivaPhoneNotification','0',NULL,'If ON, enables Talking Tech I-tiva phone notifications','YesNo');
14512     });
14513
14514     SetVersion( $DBversion );
14515     print "Upgrade to $DBversion done (Bug 18600 - Missing db update for TalkingTechItivaPhoneNotification)\n";
14516 }
14517
14518 $DBversion = '17.05.00.000';
14519 if( CheckVersion( $DBversion ) ) {
14520
14521     SetVersion( $DBversion );
14522     print "Upgrade to $DBversion done (Koha 17.05)\n";
14523 }
14524
14525 $DBversion = '17.06.00.000';
14526 if( CheckVersion( $DBversion ) ) {
14527     SetVersion( $DBversion );
14528     print "Upgrade to $DBversion done (He pai ake te iti i te kore)\n";
14529 }
14530
14531 $DBversion = '17.06.00.001';
14532 if( CheckVersion( $DBversion ) ) {
14533
14534     unless ( column_exists( 'export_format', 'used_for' ) ) {
14535         $dbh->do(q|ALTER TABLE export_format ADD used_for varchar(255) DEFAULT 'export_records' AFTER type|);
14536
14537         $dbh->do(q|UPDATE export_format SET used_for = 'late_issues' WHERE type = 'sql'|);
14538         $dbh->do(q|UPDATE export_format SET used_for = 'export_records' WHERE type = 'marc'|);
14539     }
14540     SetVersion( $DBversion );
14541     print "Upgrade to $DBversion done (Bug 8612 - Add new column export_format.used_for)\n";
14542 }
14543
14544 $DBversion = '17.06.00.002';
14545 if ( CheckVersion($DBversion) ) {
14546
14547     unless ( column_exists('virtualshelves', 'allow_change_from_owner' ) ) {
14548         $dbh->do(q|
14549             ALTER TABLE virtualshelves
14550             ADD COLUMN allow_change_from_owner tinyint(1) default 1,
14551             ADD COLUMN allow_change_from_others tinyint(1) default 0
14552         |);
14553
14554         # Conversion:
14555         # Since we had no readonly lists, change_from_owner is set to true.
14556         # When adding or delete_other was granted, change_from_others is true.
14557         # Note: In my opinion the best choice; there is no exact match.
14558         $dbh->do(q|
14559             UPDATE virtualshelves
14560             SET allow_change_from_owner = 1,
14561                 allow_change_from_others = CASE WHEN allow_add=1 OR allow_delete_other=1 THEN 1 ELSE 0 END
14562         |);
14563
14564         # Remove the old columns
14565         $dbh->do(q|
14566             ALTER TABLE virtualshelves
14567             DROP COLUMN allow_add,
14568             DROP COLUMN allow_delete_own,
14569             DROP COLUMN allow_delete_other
14570         |);
14571     }
14572
14573     SetVersion($DBversion);
14574     print "Upgrade to $DBversion done (Bug 18228 - Alter table virtualshelves to simplify permissions)\n";
14575 }
14576
14577 $DBversion = '17.06.00.003';
14578 if ( CheckVersion($DBversion) ) {
14579
14580     # Fetch all auth types
14581     my $authtypes = $dbh->selectcol_arrayref(q|SELECT authtypecode FROM auth_types|);
14582
14583     if ( grep { $_ eq 'Default' } @$authtypes ) {
14584
14585         # If this exists as an authtypecode, we don't do anything
14586     }
14587     else {
14588         # Replace the incorrect Default by empty string
14589         $dbh->do(q|
14590             UPDATE auth_header SET authtypecode='' WHERE authtypecode='Default'
14591         |);
14592     }
14593
14594     SetVersion($DBversion);
14595     print "Upgrade to $DBversion done (Bug 18801 - Update incorrect Default auth type codes)\n";
14596 }
14597
14598 $DBversion = '17.06.00.004';
14599 if( CheckVersion( $DBversion ) ) {
14600     $dbh->do(q{
14601         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14602         ('GoogleOpenIDConnectAutoRegister',   '0',NULL,' Google OpenID Connect logins to auto-register patrons.','YesNo'),
14603         ('GoogleOpenIDConnectDefaultCategory','','','This category code will be used to create Google OpenID Connect patrons.','Textarea'),
14604         ('GoogleOpenIDConnectDefaultBranch',  '','','This branch code will be used to create Google OpenID Connect patrons.','Textarea');
14605     });
14606
14607     SetVersion( $DBversion );
14608     print "Upgrade to $DBversion done (Bug 16892: Add automatic patron registration via OAuth2 login)\n";
14609 }
14610
14611 $DBversion = '17.06.00.005';
14612 if( CheckVersion( $DBversion ) ) {
14613     $dbh->do(q{
14614         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES  ('StaffLangSelectorMode','footer','top|both|footer','Select the location to display the language selector in staff client','Choice')
14615         });
14616
14617     SetVersion( $DBversion );
14618     print "Upgrade to $DBversion done (Bug 18718 - Language selector in staff header menu similar to OPAC )\n";
14619 }
14620
14621 $DBversion = '17.06.00.006';
14622 if( CheckVersion( $DBversion ) ) {
14623     print q{WARNING: Bug 18811 fixed an inconsistency in the visibility settings for authority frameworks. It is recommended that you run script misc/maintenance/auth_show_hidden_data.pl to check if you have data in hidden fields and adjust your frameworks accordingly to prevent data loss when editing such records.};
14624     print "\n";
14625
14626     SetVersion( $DBversion );
14627     print "Upgrade to $DBversion done (Bug 18811 - Visibility settings inconsistent between framework and authority editor)\n";
14628 }
14629
14630 $DBversion = '17.06.00.007';
14631 if( CheckVersion( $DBversion ) ) {
14632     if( !column_exists( 'branches', 'marcorgcode' ) ) {
14633         $dbh->do( "ALTER TABLE branches ADD COLUMN marcorgcode VARCHAR(16) default NULL AFTER geolocation" );
14634     }
14635
14636     SetVersion( $DBversion );
14637     print "Upgrade to $DBversion done (Bug 10132 - MARCOrgCode on branch level (branches.marcorgcode))\n";
14638 }
14639
14640 $DBversion = '17.06.00.008';
14641 if( CheckVersion( $DBversion ) ) {
14642     unless ( column_exists( 'borrowers', 'date_renewed' ) ) {
14643         $dbh->do(q{
14644             ALTER TABLE borrowers ADD COLUMN date_renewed DATE NULL DEFAULT NULL AFTER dateexpiry;
14645         });
14646     }
14647
14648     unless ( column_exists( 'deletedborrowers', 'date_renewed' ) ) {
14649         $dbh->do(q{
14650             ALTER TABLE deletedborrowers ADD COLUMN date_renewed DATE NULL DEFAULT NULL AFTER dateexpiry;
14651         });
14652     }
14653
14654     unless ( column_exists( 'borrower_modifications', 'date_renewed' ) ) {
14655         $dbh->do(q{
14656             ALTER TABLE borrower_modifications ADD COLUMN date_renewed DATE NULL DEFAULT NULL AFTER dateexpiry;
14657         });
14658     }
14659
14660     SetVersion( $DBversion );
14661     print "Upgrade to $DBversion done (Bug 6758 - Capture membership renewal date for reporting purposes (borrowers.date_renewed))\n";
14662 }
14663
14664 $DBversion = '17.06.00.009';
14665 if( CheckVersion( $DBversion ) ) {
14666     $dbh->do(q{
14667         ALTER TABLE borrowers MODIFY COLUMN login_attempts int(4) AFTER lang;
14668     });
14669     $dbh->do(q{
14670         ALTER TABLE deletedborrowers MODIFY COLUMN login_attempts int(4) AFTER lang;
14671     });
14672
14673     SetVersion( $DBversion );
14674     print "Upgrade to $DBversion done (Bug 19344 -  Reorder lang and login_attempts in the [deleted]borrowers tables)\n";
14675 }
14676
14677 $DBversion = '17.06.00.010';
14678 if ( CheckVersion($DBversion) ) {
14679     $dbh->do(q{
14680         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
14681         VALUES (
14682             'DefaultCountryField008','','',
14683             'Fill in the default country code for field 008 Range 15-17 of MARC21 - Place of publication, production, or execution. See <a href=\"http://www.loc.gov/marc/countries/countries_code.html\">MARC Code List for Countries</a>','Free')
14684     });
14685     SetVersion($DBversion);
14686     print "Upgrade to $DBversion done (Bug 13912 - System preference for default place of publication (country code) for field 008, range 15-17)\n";
14687 }
14688
14689 $DBversion = '17.06.00.011';
14690 if ( CheckVersion($DBversion) ) {
14691     # Drop index that might exist because of bug 5337
14692     if( index_exists('biblioitems', 'ean')) {
14693         $dbh->do(q{ ALTER TABLE biblioitems DROP INDEX ean });
14694     }
14695     if( index_exists('deletedbiblioitems', 'ean')) {
14696         $dbh->do(q{ ALTER TABLE deletedbiblioitems DROP INDEX ean });
14697     }
14698
14699     # Change data type of column
14700     $dbh->do(q{ ALTER TABLE biblioitems MODIFY COLUMN ean MEDIUMTEXT default NULL });
14701     $dbh->do(q{ ALTER TABLE deletedbiblioitems MODIFY COLUMN ean MEDIUMTEXT default NULL });
14702
14703     # Add indexes
14704     $dbh->do(q{ ALTER TABLE biblioitems ADD INDEX ean ( ean(255) )});
14705     $dbh->do(q{ ALTER TABLE deletedbiblioitems ADD INDEX ean ( ean(255 ) )});
14706
14707     SetVersion($DBversion);
14708     print "Upgrade to $DBversion done (Bug 13766 - Make ean mediumtext and add ean indexes)\n";
14709 }
14710
14711 $DBversion = '17.06.00.012';
14712 if( CheckVersion( $DBversion ) ) {
14713     my $where = q|host='clio-db.cc.columbia.edu' AND port=7090|;
14714     my $sql = "SELECT COUNT(*) FROM z3950servers WHERE $where";
14715     my ( $cnt ) = $dbh->selectrow_array( $sql );
14716     if( $cnt ) {
14717         $dbh->do( "DELETE FROM z3950servers WHERE $where" );
14718         print "Removed $cnt Z39.50 target(s) for Columbia University\n";
14719     }
14720
14721     SetVersion( $DBversion );
14722     print "Upgrade to $DBversion done (Bug 19043 - Z39.50 target for Columbia University is no longer publicly available.)\n";
14723 }
14724
14725 $DBversion = '17.06.00.013';
14726 if( CheckVersion( $DBversion ) ) {
14727     $dbh->do( "UPDATE systempreferences SET value = CONCAT('http://', value) WHERE variable = 'staffClientBaseURL' AND value <> '' AND value NOT LIKE 'http%'" );
14728
14729     my ( $staffClientBaseURL_used_in_notices ) = $dbh->selectrow_array(q|
14730         SELECT COUNT(*) FROM letter where content like "%staffClientBaseURL%"
14731     |);
14732     if ( $staffClientBaseURL_used_in_notices ) {
14733         warn "\tYou may need to update one or more notice templates if they contain 'staffClientBaseURL'\n";
14734     }
14735
14736     SetVersion( $DBversion );
14737     print "Upgrade to $DBversion done (Bug 16401 - fix potentialy bad set staffClientBaseURL preference)\n";
14738 }
14739
14740 $DBversion = '17.06.00.014';
14741 if( CheckVersion( $DBversion ) ) {
14742     unless( column_exists('aqbasket','create_items') ){
14743         $dbh->do(q{
14744             ALTER TABLE aqbasket
14745                 ADD COLUMN create_items ENUM('ordering', 'receiving', 'cataloguing') default NULL AFTER is_standing
14746         });
14747     }
14748
14749     SetVersion( $DBversion );
14750     print "Upgrade to $DBversion done (Bug 15685 - Allow creation of items (AcqCreateItem) to be customizable per-basket)\n";
14751 }
14752
14753 $DBversion = '17.06.00.015';
14754 if( CheckVersion( $DBversion ) ) {
14755     $dbh->do(q{
14756         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES
14757         ('SelfCheckoutByLogin','0',NULL,'Have patrons login into the web-based self checkout system with their username/password or their cardnumber','YesNo')
14758     });
14759
14760     SetVersion( $DBversion );
14761     print "Upgrade to $DBversion done (Bug 19186 - Insert system preference SelfCheckoutByLogin if missing)\n";
14762 }
14763
14764 $DBversion = '17.06.00.016';
14765 if( CheckVersion( $DBversion ) ) {
14766     $dbh->do(q{
14767         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
14768         VALUES ('RequireStrongPassword','0','','Require a strong login password for staff and patrons','YesNo');
14769     });
14770
14771     SetVersion( $DBversion );
14772     print "Upgrade to $DBversion done (Bug 18298 - Allow enforcing password complexity (system preference RequireStrongPassword))\n";
14773 }
14774
14775 $DBversion = '17.06.00.017';
14776 if( CheckVersion( $DBversion ) ) {
14777     unless (TableExists('account_offsets')) {
14778         $dbh->do(q{
14779             DROP TABLE IF EXISTS `accountoffsets`;
14780         });
14781
14782         $dbh->do(q{
14783             CREATE TABLE IF NOT EXISTS `account_offset_types` (
14784               `type` varchar(16) NOT NULL, -- The type of offset this is
14785               PRIMARY KEY (`type`)
14786             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14787         });
14788
14789         $dbh->do(q{
14790             CREATE TABLE IF NOT EXISTS `account_offsets` (
14791               `id` int(11) NOT NULL auto_increment, -- unique identifier for each offset
14792               `credit_id` int(11) NULL DEFAULT NULL, -- The id of the accountline the increased the patron's balance
14793               `debit_id` int(11) NULL DEFAULT NULL, -- The id of the accountline that decreased the patron's balance
14794               `type` varchar(16) NOT NULL, -- The type of offset this is
14795               `amount` decimal(26,6) NOT NULL, -- The amount of the change
14796               `created_on` timestamp NOT NULL default CURRENT_TIMESTAMP,
14797               PRIMARY KEY (`id`),
14798               CONSTRAINT `account_offsets_ibfk_p` FOREIGN KEY (`credit_id`) REFERENCES `accountlines` (`accountlines_id`) ON DELETE CASCADE ON UPDATE CASCADE,
14799               CONSTRAINT `account_offsets_ibfk_f` FOREIGN KEY (`debit_id`) REFERENCES `accountlines` (`accountlines_id`) ON DELETE CASCADE ON UPDATE CASCADE,
14800               CONSTRAINT `account_offsets_ibfk_t` FOREIGN KEY (`type`) REFERENCES `account_offset_types` (`type`) ON DELETE CASCADE ON UPDATE CASCADE
14801             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14802         });
14803
14804         $dbh->do(q{
14805             INSERT IGNORE INTO account_offset_types ( type ) VALUES
14806             ('Writeoff'),
14807             ('Payment'),
14808             ('Lost Item'),
14809             ('Processing Fee'),
14810             ('Manual Debit'),
14811             ('Reverse Payment'),
14812             ('Forgiven'),
14813             ('Dropbox'),
14814             ('Rental Fee'),
14815             ('Fine Update'),
14816             ('Fine');
14817         });
14818     }
14819
14820     SetVersion( $DBversion );
14821     print "Upgrade to $DBversion done (Bug 14826 - Resurrect account offsets table (Add new tables account_offsets and account_offset_types))\n";
14822 }
14823
14824 $DBversion = '17.06.00.018';
14825 if( CheckVersion( $DBversion ) ) {
14826     $dbh->do(q{
14827         INSERT IGNORE INTO systempreferences (variable,value,explanation,type) VALUES ('useDefaultReplacementCost',0,'default replacement cost defined in item type','YesNo');
14828     });
14829     $dbh->do(q{
14830         INSERT IGNORE INTO systempreferences (variable,value,explanation,type) VALUES ('ProcessingFeeNote','','Set the text to be recorded in the column note, table accountlines when the processing fee (defined in item type) is applied','textarea');
14831     });
14832     $dbh->do(q{
14833         ALTER TABLE `itemtypes` MODIFY COLUMN `rentalcharge` DECIMAL(28,6) NULL DEFAULT NULL;
14834     });
14835     unless ( column_exists( 'itemtypes', 'defaultreplacecost' ) ) {
14836         $dbh->do(q{
14837             ALTER TABLE `itemtypes` ADD `defaultreplacecost` DECIMAL(28,6) NULL DEFAULT NULL AFTER `rentalcharge`;
14838         });
14839     }
14840     unless ( column_exists( 'itemtypes', 'processfee' ) ) {
14841         $dbh->do(q{
14842             ALTER TABLE `itemtypes` ADD `processfee` DECIMAL(28,6) NULL DEFAULT NULL AFTER `defaultreplacecost`;
14843         });
14844
14845     }
14846     SetVersion( $DBversion );
14847     print "Upgrade to $DBversion done (Bug 12768 - Insert system preferences useDefaultReplacementCost and ProcessingFeeNote + Add new columns defaultreplacecost and processfee to the itemtypes table)\n";
14848 }
14849
14850 $DBversion = '17.06.00.019';
14851 if( CheckVersion( $DBversion ) ) {
14852     $dbh->do(q{
14853         INSERT IGNORE INTO account_offset_types ( type ) VALUES ( 'Processing Fee' );
14854     });
14855
14856     SetVersion( $DBversion );
14857     print "Upgrade to $DBversion done (Bug 12768 - Add 'Processing Fee' to the account_offset_types table if missing)\n";
14858 }
14859
14860 $DBversion = '17.06.00.020';
14861 if( CheckVersion( $DBversion ) ) {
14862     $dbh->do(q{
14863         UPDATE systempreferences
14864         SET
14865             variable='OpacLocationOnDetail',
14866             options='holding|home|both|column',
14867             explanation='In the OPAC detail, display the shelving location on its own column or under a library columns.'
14868         WHERE
14869             variable='OpacLocationBranchToDisplayShelving'
14870     });
14871
14872     SetVersion( $DBversion );
14873     print "Upgrade to $DBversion done (Bug 19028: Add 'shelving location' to holdings table in detail page (Rename syspref OpacLocationBranchToDisplayShelving with OpacLocationOnDetail))\n";
14874 }
14875
14876 $DBversion = '17.06.00.021';
14877 if( CheckVersion( $DBversion ) ) {
14878     $dbh->do(q{
14879         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type` ) VALUES ('SCOMainUserBlock','','70|10','Add a block of HTML that will display on the self checkout screen','Textarea')
14880     });
14881
14882     SetVersion( $DBversion );
14883     print "Upgrade to $DBversion done (Bug 17381 - Add system preference SCOMainUserBlock)\n";
14884 }
14885
14886 $DBversion = '17.06.00.022';
14887 if( CheckVersion( $DBversion ) ) {
14888     my $hide_barcode = C4::Context->preference('OPACShowBarcode') ? 0 : 1;
14889     $dbh->do(q{
14890         DELETE FROM systempreferences
14891         WHERE
14892             variable='OPACShowBarcode'
14893     });
14894
14895     # Configure column visibility if it isn't
14896     $dbh->do(q{
14897         INSERT IGNORE INTO columns_settings
14898             (module,page,tablename,columnname,cannot_be_toggled,is_hidden)
14899         VALUES
14900             ('opac','biblio-detail','holdingst','item_barcode',0,?)
14901     }, undef, $hide_barcode);
14902
14903     SetVersion( $DBversion );
14904     print "Upgrade to $DBversion done (Bug 19038: Remove OPACShowBarcode syspref)\n";
14905 }
14906
14907 $DBversion = '17.06.00.023';
14908 if( CheckVersion( $DBversion ) ) {
14909     $dbh->do(q{
14910         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14911         ('MarkLostItemsAsReturned','1','','Mark items as returned when flagged as lost','YesNo');
14912     });
14913
14914     SetVersion( $DBversion );
14915     print "Upgrade to $DBversion done (Bug 12363 - Add system preference MarkLostItemsAsReturned)\n";
14916 }
14917
14918 $DBversion = '17.06.00.024';
14919 if( CheckVersion( $DBversion ) ) {
14920     $dbh->do(q{
14921         INSERT IGNORE INTO systempreferences (`variable`,`value`,`options`,`explanation`,`type`) VALUES
14922         ('OPACUserSummary', 1, NULL, "Show the summary of a logged in user's checkouts, overdues, holds and fines on the mainpage", 'YesNo');
14923     });
14924
14925     SetVersion( $DBversion );
14926     print "Upgrade to $DBversion done (Bug 2093 - Add system preference OPACUserSummary)\n";
14927 }
14928
14929 $DBversion = '17.06.00.025';
14930 if( CheckVersion( $DBversion ) ) {
14931     $dbh->do(q{
14932         ALTER TABLE borrowers MODIFY cardnumber varchar(32);
14933     });
14934     $dbh->do(q{
14935         ALTER TABLE borrower_modifications MODIFY cardnumber varchar(32);
14936     });
14937     $dbh->do(q{
14938         ALTER TABLE deletedborrowers MODIFY cardnumber varchar(32);
14939     });
14940     $dbh->do(q{
14941         ALTER TABLE pending_offline_operations MODIFY cardnumber varchar(32);
14942     });
14943     $dbh->do(q{
14944         ALTER TABLE tmp_holdsqueue MODIFY cardnumber varchar(32);
14945     });
14946
14947     SetVersion( $DBversion );
14948     print "Upgrade to $DBversion done (Bug 13178 - Increase cardnumber fields to VARCHAR(32))\n";
14949 }
14950
14951 $DBversion = '17.06.00.026';
14952 if( CheckVersion( $DBversion ) ) {
14953     $dbh->do(q{
14954         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14955         ('BlockReturnOfLostItems','0','0','If enabled, items that are marked as lost cannot be returned.','YesNo');
14956     });
14957
14958     SetVersion( $DBversion );
14959     print "Upgrade to $DBversion done (Bug 10748 - Add system preference BlockReturnOfLostItems)\n";
14960 }
14961
14962 $DBversion = '17.06.00.027';
14963 if( CheckVersion( $DBversion ) ) {
14964     if ( !column_exists( 'statistics', 'location' ) ) {
14965         $dbh->do('ALTER TABLE statistics ADD COLUMN location VARCHAR(80) default NULL AFTER itemtype');
14966     }
14967
14968     SetVersion($DBversion);
14969     print "Upgrade to $DBversion done (Bug 18882 - Add location code to statistics table for checkouts and renewals)\n";
14970 }
14971
14972 $DBversion = '17.06.00.028';
14973 if( CheckVersion( $DBversion ) ) {
14974     if ( !TableExists( 'illrequests' ) ) {
14975         $dbh->do(q{
14976             CREATE TABLE illrequests (
14977                illrequest_id serial PRIMARY KEY,           -- ILL request number
14978                borrowernumber integer DEFAULT NULL,        -- Patron associated with request
14979                biblio_id integer DEFAULT NULL,             -- Potential bib linked to request
14980                branchcode varchar(50) NOT NULL,            -- The branch associated with the request
14981                status varchar(50) DEFAULT NULL,            -- Current Koha status of request
14982                placed date DEFAULT NULL,                   -- Date the request was placed
14983                replied date DEFAULT NULL,                  -- Last API response
14984                updated timestamp DEFAULT CURRENT_TIMESTAMP -- Last modification to request
14985                  ON UPDATE CURRENT_TIMESTAMP,
14986                completed date DEFAULT NULL,                -- Date the request was completed
14987                medium varchar(30) DEFAULT NULL,            -- The Koha request type
14988                accessurl varchar(500) DEFAULT NULL,        -- Potential URL for accessing item
14989                cost varchar(20) DEFAULT NULL,              -- Cost of request
14990                notesopac text DEFAULT NULL,                -- Patron notes attached to request
14991                notesstaff text DEFAULT NULL,               -- Staff notes attached to request
14992                orderid varchar(50) DEFAULT NULL,           -- Backend id attached to request
14993                backend varchar(20) DEFAULT NULL,           -- The backend used to create request
14994                CONSTRAINT `illrequests_bnfk`
14995                  FOREIGN KEY (`borrowernumber`)
14996                  REFERENCES `borrowers` (`borrowernumber`)
14997                  ON UPDATE CASCADE ON DELETE CASCADE,
14998                CONSTRAINT `illrequests_bcfk_2`
14999                  FOREIGN KEY (`branchcode`)
15000                  REFERENCES `branches` (`branchcode`)
15001                  ON UPDATE CASCADE ON DELETE CASCADE
15002            ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
15003         });
15004     }
15005
15006     if ( !TableExists( 'illrequestattributes' ) ) {
15007         $dbh->do(q{
15008             CREATE TABLE illrequestattributes (
15009                 illrequest_id bigint(20) unsigned NOT NULL, -- ILL request number
15010                 type varchar(200) NOT NULL,                 -- API ILL property name
15011                 value text NOT NULL,                        -- API ILL property value
15012                 PRIMARY KEY  (`illrequest_id`,`type`),
15013                 CONSTRAINT `illrequestattributes_ifk`
15014                   FOREIGN KEY (illrequest_id)
15015                   REFERENCES `illrequests` (`illrequest_id`)
15016                   ON UPDATE CASCADE ON DELETE CASCADE
15017             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
15018         });
15019     }
15020
15021     # System preferences
15022     $dbh->do(q{
15023         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
15024             ('ILLModule','0','If ON, enables the interlibrary loans module.','','YesNo');
15025     });
15026
15027     $dbh->do(q{
15028         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
15029             ('ILLModuleCopyrightClearance','','70|10','Enter text to enable the copyright clearance stage of request creation. Text will be displayed','Textarea');
15030     });
15031     # userflags
15032     $dbh->do(q{
15033         INSERT IGNORE INTO userflags (bit,flag,flagdesc,defaulton) VALUES
15034             (22,'ill','The Interlibrary Loans Module',0);
15035     });
15036
15037     SetVersion( $DBversion );
15038     print "Upgrade to $DBversion done (Bug 7317 - Add an Interlibrary Loan Module to Circulation and OPAC)\n";
15039 }
15040
15041 $DBversion = '17.11.00.000';
15042 if( CheckVersion( $DBversion ) ) {
15043     SetVersion( $DBversion );
15044     print "Upgrade to $DBversion done (Koha 17.11)\n";
15045 }
15046
15047 $DBversion = '17.12.00.000';
15048 if( CheckVersion( $DBversion ) ) {
15049     SetVersion( $DBversion );
15050     print "Upgrade to $DBversion done (Tē tōia, tē haumatia)\n";
15051 }
15052
15053 $DBversion = '17.12.00.001';
15054 if( CheckVersion( $DBversion ) ) {
15055     foreach my $table (qw(biblio_metadata deletedbiblio_metadata)) {
15056         if (!column_exists($table, 'timestamp')) {
15057             $dbh->do(qq{
15058                 ALTER TABLE `$table`
15059                 ADD COLUMN `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER `metadata`,
15060                 ADD KEY `timestamp` (`timestamp`)
15061             });
15062             $dbh->do(qq{
15063                 UPDATE $table metadata
15064                     LEFT JOIN biblioitems ON (biblioitems.biblionumber = metadata.biblionumber)
15065                     LEFT JOIN biblio ON (biblio.biblionumber = metadata.biblionumber)
15066                 SET metadata.timestamp = GREATEST(biblioitems.timestamp, biblio.timestamp);
15067             });
15068         }
15069     }
15070
15071     SetVersion( $DBversion );
15072     print "Upgrade to $DBversion done (Bug 19724 - Add [deleted]biblio_metadata.timestamp)\n";
15073 }
15074
15075 $DBversion = '17.12.00.002';
15076 if( CheckVersion( $DBversion ) ) {
15077
15078     my $msss = $dbh->selectall_arrayref(q|
15079         SELECT kohafield, tagfield, tagsubfield, frameworkcode
15080         FROM marc_subfield_structure
15081         WHERE   frameworkcode != ''
15082     |, { Slice => {} });
15083
15084
15085     my $sth = $dbh->prepare(q|
15086         SELECT kohafield
15087         FROM marc_subfield_structure
15088         WHERE frameworkcode = ''
15089         AND tagfield = ?
15090         AND tagsubfield = ?
15091     |);
15092
15093     my @exceptions;
15094     for my $mss ( @$msss ) {
15095         $sth->execute($mss->{tagfield}, $mss->{tagsubfield} );
15096         my ( $default_kohafield ) = $sth->fetchrow_array();
15097         if( $mss->{kohafield} ) {
15098             push @exceptions, { frameworkcode => $mss->{frameworkcode}, tagfield => $mss->{tagfield}, tagsubfield => $mss->{tagsubfield}, kohafield => $mss->{kohafield} } if not $default_kohafield or $default_kohafield ne $mss->{kohafield};
15099         } else {
15100             push @exceptions, { frameworkcode => $mss->{frameworkcode}, tagfield => $mss->{tagfield}, tagsubfield => $mss->{tagsubfield}, kohafield => q{} } if $default_kohafield;
15101         }
15102     }
15103
15104     if (@exceptions) {
15105         print "WARNING: The Default framework is now considered as authoritative for Koha to MARC mappings. We have found that your additional frameworks contained "
15106           . scalar(@exceptions)
15107           . " mapping(s) that deviate from the standard mappings. Please look at the following list and consider if you need to add them again in Default (possibly as a second mapping).\n";
15108         for my $exception (@exceptions) {
15109             print "Field "
15110               . $exception->{tagfield} . '$'
15111               . $exception->{tagsubfield}
15112               . " in framework "
15113               . $exception->{frameworkcode} . ': ';
15114             if ( $exception->{kohafield} ) {
15115                 print "Mapping to "
15116                   . $exception->{kohafield}
15117                   . " has been adjusted.\n";
15118             }
15119             else {
15120                 print "Mapping has been reset.\n";
15121             }
15122         }
15123
15124         # Sync kohafield
15125
15126         # Clear the destination frameworks first
15127         $dbh->do(q|
15128             UPDATE marc_subfield_structure
15129             SET kohafield = NULL
15130             WHERE   frameworkcode > ''
15131                 AND     Kohafield > ''
15132         |);
15133
15134         # Now copy from Default
15135         my $msss = $dbh->selectall_arrayref(q|
15136             SELECT kohafield, tagfield, tagsubfield
15137             FROM marc_subfield_structure
15138             WHERE   frameworkcode = ''
15139                 AND     kohafield > ''
15140         |, { Slice => {} });
15141         my $sth = $dbh->prepare(q|
15142             UPDATE marc_subfield_structure
15143             SET kohafield = ?
15144             WHERE frameworkcode > ''
15145             AND tagfield = ?
15146             AND tagsubfield = ?
15147         |);
15148         for my $mss (@$msss) {
15149             $sth->execute( $mss->{kohafield}, $mss->{tagfield},
15150                 $mss->{tagsubfield} );
15151         }
15152
15153         # Clear the cache
15154         my @frameworkcodes = $dbh->selectall_arrayref(q|
15155             SELECT frameworkcode FROM biblio_framework WHERE frameworkcode > ''
15156         |);
15157         for my $frameworkcode (@frameworkcodes) {
15158             Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
15159         }
15160         Koha::Caches->get_instance->clear_from_cache("default_value_for_mod_marc-");
15161     }
15162
15163     SetVersion( $DBversion );
15164     print "Upgrade to $DBversion done (Bug 19096 - Make Default authoritative for Koha to MARC mappings)\n";
15165 }
15166
15167 $DBversion = '17.12.00.003';
15168 if( CheckVersion( $DBversion ) ) {
15169     $dbh->do(q|DROP TABLE IF EXISTS notifys|);
15170
15171     if( column_exists( 'accountlines', 'notify_id' ) ) {
15172         $dbh->do(q|ALTER TABLE accountlines DROP COLUMN notify_id|);
15173         $dbh->do(q|ALTER TABLE accountlines DROP COLUMN notify_level|);
15174     }
15175
15176     SetVersion( $DBversion );
15177     print "Upgrade to $DBversion done (Bug 10021 - Drop notifys-related table and columns)\n";
15178 }
15179
15180 $DBversion = '17.12.00.004';
15181 if( CheckVersion( $DBversion ) ) {
15182     $dbh->do(q{
15183         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
15184         VALUES
15185             ('RESTdefaultPageSize','20','','Set the default number of results returned by the REST API endpoints','Integer')
15186     });
15187
15188     SetVersion( $DBversion );
15189     print "Upgrade to $DBversion done (Bug 19278 - Add a configurable default page size for REST endpoints)\n";
15190 }
15191
15192 $DBversion = '17.12.00.005';
15193 if( CheckVersion( $DBversion ) ) {
15194     # For installations having the note already
15195     $dbh->do(q{
15196         UPDATE letter
15197         SET code    = 'CHECKOUT_NOTE',
15198             name    = 'Checkout note on item set by patron',
15199             title   = 'Checkout note',
15200             content = REPLACE(content, "<<biblio.item>>", "<<biblio.title>>")
15201         WHERE code = 'PATRON_NOTE'
15202     });
15203     # For installations coming from 17.11
15204     $dbh->do(q{
15205         INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`)
15206         VALUES ('circulation', 'CHECKOUT_NOTE', '', 'Checkout note on item set by patron', '0', 'Checkout note', '<<borrowers.firstname>> <<borrowers.surname>> has added a note to the item <<biblio.title>> - <<biblio.author>> (<<biblio.biblionumber>>).','email')
15207     });
15208
15209     SetVersion( $DBversion );
15210     print "Upgrade to $DBversion done (Bug 18915 - Correct CHECKOUT_NOTE notice template)\n";
15211 }
15212
15213 $DBversion = '17.12.00.006';
15214 if( CheckVersion( $DBversion ) ) {
15215     $dbh->do(q{
15216         UPDATE systempreferences SET value=replace(value, "http://www.scholar", "https://scholar") WHERE variable='OPACSearchForTitleIn';
15217     });
15218
15219     SetVersion( $DBversion );
15220     print "Upgrade to $DBversion done (Bug 17682 - Update URL for Google Scholar in OPACSearchForTitleIn)\n";
15221 }
15222
15223 $DBversion = '17.12.00.007';
15224 if( CheckVersion( $DBversion ) ) {
15225
15226     unless ( TableExists( 'library_groups' ) ) {
15227         $dbh->do(q{
15228             CREATE TABLE library_groups (
15229                 id INT(11) NOT NULL auto_increment,    -- unique id for each group
15230                 parent_id INT(11) NULL DEFAULT NULL,   -- if this is a child group, the id of the parent group
15231                 branchcode VARCHAR(10) NULL DEFAULT NULL, -- The branchcode of a branch belonging to the parent group
15232                 title VARCHAR(100) NULL DEFAULT NULL,     -- Short description of the goup
15233                 description TEXT NULL DEFAULT NULL,    -- Longer explanation of the group, if necessary
15234                 created_on TIMESTAMP NULL,             -- Date and time of creation
15235                 updated_on TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- Date and time of last
15236                 PRIMARY KEY id ( id ),
15237                 FOREIGN KEY (parent_id) REFERENCES library_groups(id) ON UPDATE CASCADE ON DELETE CASCADE,
15238                 FOREIGN KEY (branchcode) REFERENCES branches(branchcode) ON UPDATE CASCADE ON DELETE CASCADE,
15239                 UNIQUE KEY title ( title )
15240             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
15241         });
15242     }
15243
15244     SetVersion( $DBversion );
15245     print "Upgrade to $DBversion done (Bug 15707 - Add new table library_groups)\n";
15246 }
15247
15248 $DBversion = '17.12.00.008';
15249 if ( CheckVersion($DBversion) ) {
15250
15251     if ( TableExists( 'branchcategories' ) and TableExists('branchrelations' )) {
15252         $dbh->do(q{
15253             INSERT INTO library_groups ( title, description, created_on ) VALUES ( '__SEARCH_GROUPS__', 'Library search groups', NOW() )
15254         });
15255         my $search_groups_root_id = $dbh->last_insert_id(undef, undef, 'library_groups', undef);
15256
15257         my $sth = $dbh->prepare("SELECT * FROM branchcategories");
15258
15259         my $sth2 = $dbh->prepare("INSERT INTO library_groups ( parent_id, title, description, created_on ) VALUES ( ?, ?, ?, NOW() )");
15260
15261         my $sth3 = $dbh->prepare("SELECT * FROM branchrelations WHERE categorycode = ?");
15262
15263         my $sth4 = $dbh->prepare("INSERT INTO library_groups ( parent_id, branchcode, created_on ) VALUES ( ?, ?, NOW() )");
15264
15265         $sth->execute();
15266         while ( my $lc = $sth->fetchrow_hashref ) {
15267             my $description = $lc->{categorycode};
15268             $description .= " - " . $lc->{codedescription} if $lc->{codedescription};
15269
15270             $sth2->execute($search_groups_root_id, $lc->{categoryname}, $description);
15271
15272             my $subgroup_id = $dbh->last_insert_id(undef, undef, 'library_groups', undef);
15273
15274             $sth3->execute( $lc->{categorycode} );
15275
15276             while ( my $l = $sth3->fetchrow_hashref ) {
15277                 $sth4->execute( $subgroup_id, $l->{branchcode} );
15278             }
15279         }
15280
15281         $dbh->do("DROP TABLE branchrelations");
15282         $dbh->do("DROP TABLE branchcategories");
15283     }
15284
15285     print "Upgrade to $DBversion done (Bug 16735 - Migrate library search groups into the new hierarchical groups)\n";
15286     SetVersion($DBversion);
15287 }
15288
15289 $DBversion = '17.12.00.009';
15290 if ( CheckVersion($DBversion) ) {
15291     $dbh->do(q|
15292         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
15293         (4, 'edit_borrowers', 'Add, modify and view patron information'),
15294         (4, 'view_borrower_infos_from_any_libraries', 'View patron infos from any libraries');
15295     |);
15296
15297     # We are lucky here, there is nothing else to do: flags 4-borrowers did not contain sub permissions
15298
15299     SetVersion( $DBversion );
15300     print "Upgrade to $DBversion done (Bug 18403 - Add the view_borrower_infos_from_any_libraries permission )\n";
15301 }
15302
15303 $DBversion = '17.12.00.010';
15304 if( CheckVersion( $DBversion ) ) {
15305
15306     if( !column_exists( 'library_groups', 'ft_hide_patron_info' ) ) {
15307         $dbh->do( "ALTER TABLE library_groups ADD COLUMN ft_hide_patron_info tinyint(1) NOT NULL DEFAULT 0 AFTER description" );
15308     }
15309
15310     SetVersion( $DBversion );
15311     print "Upgrade to $DBversion done (Bug 20133 - Add library_groups.ft_hide_patron_info)\n";
15312 }
15313
15314 $DBversion = '17.12.00.011';
15315 if( CheckVersion( $DBversion ) ) {
15316
15317     if( !column_exists( 'library_groups', 'ft_search_groups_opac' ) ) {
15318         $dbh->do( "ALTER TABLE library_groups ADD COLUMN ft_search_groups_opac tinyint(1) NOT NULL DEFAULT 0 AFTER ft_hide_patron_info" );
15319         $dbh->do( "ALTER TABLE library_groups ADD COLUMN ft_search_groups_staff tinyint(1) NOT NULL DEFAULT 0 AFTER ft_search_groups_opac" );
15320         $dbh->do( "UPDATE library_groups SET ft_search_groups_staff = 1 AND ft_search_groups_opac = 1 WHERE title = '__SEARCH_GROUPS__'" );
15321     }
15322
15323     SetVersion( $DBversion );
15324     print "Upgrade to $DBversion done (Bug 20157 - Use group 'features' to decide which groups to use for group searching functionality)\n";
15325 }
15326
15327 $DBversion = '17.12.00.012';
15328 if( CheckVersion( $DBversion ) ) {
15329
15330     $dbh->do( q|
15331         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15332         VALUES ('AutoSwitchPatron', '0', '', 'Auto switch to patron', 'YesNo');
15333     |);
15334
15335     SetVersion( $DBversion );
15336     print "Upgrade to $DBversion done (Bug 15752 - Add system preference AutoSwitchPatron)\n";
15337 }
15338
15339 $DBversion = '17.12.00.013';
15340 if( CheckVersion( $DBversion ) ) {
15341
15342     $dbh->do(q|
15343         ALTER TABLE club_enrollments MODIFY date_created timestamp NULL DEFAULT NULL;
15344     |);
15345
15346     SetVersion( $DBversion );
15347     print "Upgrade to $DBversion done (Bug 20175 - Set DEFAULT NULL value for club_enrollments.date_created)\n";
15348 }
15349
15350 $DBversion = '17.12.00.014';
15351 if( CheckVersion( $DBversion ) ) {
15352     $dbh->do( "UPDATE marc_subfield_structure SET kohafield=NULL where kohafield='additionalauthors.author'" );
15353     SetVersion( $DBversion );
15354     print "Upgrade to $DBversion done (Bug 19790 - Remove additionalauthors.author from installer files)\n";
15355 }
15356
15357 $DBversion = '17.12.00.015';
15358 if( CheckVersion( $DBversion ) ) {
15359     $dbh->do(q|
15360         ALTER TABLE borrowers
15361         MODIFY surname MEDIUMTEXT,
15362         MODIFY address MEDIUMTEXT,
15363         MODIFY city MEDIUMTEXT
15364     |);
15365     $dbh->do(q|
15366         ALTER TABLE deletedborrowers
15367         MODIFY surname MEDIUMTEXT,
15368         MODIFY address MEDIUMTEXT,
15369         MODIFY city MEDIUMTEXT
15370     |);
15371
15372     $dbh->do(q|
15373         ALTER TABLE export_format
15374         MODIFY csv_separator VARCHAR(2) NOT NULL DEFAULT ',',
15375         MODIFY field_separator VARCHAR(2),
15376         MODIFY subfield_separator VARCHAR(2)
15377     |);
15378     $dbh->do(q|
15379         ALTER TABLE export_format MODIFY encoding VARCHAR(255) NOT NULL DEFAULT 'utf8'
15380     |);
15381
15382     $dbh->do(q|
15383         ALTER TABLE reserves MODIFY lowestPriority tinyint(1) NOT NULL DEFAULT 0
15384     |);
15385     $dbh->do(q|
15386         ALTER TABLE old_reserves MODIFY lowestPriority tinyint(1) NOT NULL DEFAULT 0
15387     |);
15388
15389     SetVersion( $DBversion );
15390     print "Upgrade to $DBversion done (Bug 20144 - Adapt DB structure to work with new SQL modes)\n";
15391 }
15392
15393 $DBversion = '17.12.00.016';
15394 if( CheckVersion( $DBversion ) ) {
15395     $dbh->do(q|SET foreign_key_checks = 0|);
15396     my $sth = $dbh->table_info( '','','','TABLE' );
15397
15398     while ( my ( $cat, $schema, $name, $type, $remarks ) = $sth->fetchrow_array ) {
15399         my $table_sth = $dbh->prepare(qq|SHOW CREATE TABLE $name|);
15400         $table_sth->execute;
15401         my @table = $table_sth->fetchrow_array;
15402         unless ( $table[1] =~ /COLLATE=utf8mb4_unicode_ci/ ) {
15403             # Some users might have done the upgrade to utf8mb4 on their own
15404             # to support supplemental chars (japanese, chinese, etc)
15405             if ( $name eq 'additional_fields' ) {
15406                 $dbh->do(qq|
15407                     ALTER TABLE $name
15408                         DROP KEY `fields_uniq`,
15409                         ADD UNIQUE KEY `fields_uniq` (`tablename` (191), `name` (191))
15410                 |);
15411                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15412             }
15413             elsif ( $name eq 'authorised_values' ) {
15414                 $dbh->do(qq|
15415                     ALTER TABLE $name
15416                         DROP KEY `lib`,
15417                         ADD KEY `lib` (`lib` (191))
15418                 |);
15419                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15420             }
15421             elsif ( $name eq 'borrower_modifications' ) {
15422                 $dbh->do(qq|
15423                     ALTER TABLE $name
15424                         DROP PRIMARY KEY,
15425                         DROP KEY `verification_token`,
15426                         ADD PRIMARY KEY (`verification_token` (191),`borrowernumber`),
15427                         ADD KEY `verification_token` (`verification_token` (191))
15428                 |);
15429                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15430             }
15431             elsif ( $name eq 'columns_settings' ) {
15432                 $dbh->do(qq|
15433                     ALTER TABLE $name
15434                         DROP PRIMARY KEY,
15435                         ADD PRIMARY KEY (`module` (191), `page` (191), `tablename` (191), `columnname` (191))
15436                 |);
15437                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15438             }
15439             elsif ( $name eq 'illrequestattributes' ) {
15440                 $dbh->do(qq|
15441                     ALTER TABLE $name
15442                         DROP PRIMARY KEY,
15443                         ADD PRIMARY KEY  (`illrequest_id`, `type` (191))
15444                 |);
15445                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15446             }
15447             elsif ( $name eq 'items_search_fields' ) {
15448                 $dbh->do(qq|
15449                     ALTER TABLE $name
15450                         DROP PRIMARY KEY,
15451                         ADD PRIMARY KEY (`name` (191))
15452                 |);
15453                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15454             }
15455             elsif ( $name eq 'marc_subfield_structure' ) {
15456                 # In this case we convert each column explicitly
15457                 # to preserve 'tagsubield' collation (utf8mb4_bin)
15458                 $dbh->do(qq|
15459                     ALTER TABLE $name
15460                         MODIFY COLUMN tagfield
15461                             VARCHAR(3) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
15462                         MODIFY COLUMN tagsubfield
15463                             VARCHAR(1) COLLATE utf8mb4_bin NOT NULL DEFAULT '',
15464                         MODIFY COLUMN liblibrarian
15465                             VARCHAR(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
15466                         MODIFY COLUMN libopac
15467                             VARCHAR(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
15468                         MODIFY COLUMN kohafield
15469                             VARCHAR(40) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15470                         MODIFY COLUMN authorised_value
15471                             VARCHAR(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15472                         MODIFY COLUMN authtypecode
15473                             VARCHAR(20) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15474                         MODIFY COLUMN value_builder
15475                             VARCHAR(80) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15476                         MODIFY COLUMN frameworkcode
15477                             VARCHAR(4) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
15478                         MODIFY COLUMN seealso
15479                             VARCHAR(1100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15480                         MODIFY COLUMN link
15481                             VARCHAR(80) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15482                         MODIFY COLUMN defaultvalue
15483                             MEDIUMTEXT COLLATE utf8mb4_unicode_ci default NULL
15484                 |);
15485                 $dbh->do(qq|ALTER TABLE $name CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15486             }
15487             elsif ( $name eq 'plugin_data' ) {
15488                 $dbh->do(qq|
15489                     ALTER TABLE $name
15490                         DROP PRIMARY KEY,
15491                         ADD PRIMARY KEY (`plugin_class` (191), `plugin_key` (191))
15492                 |);
15493                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15494             }
15495             elsif ( $name eq 'search_field' ) {
15496                 $dbh->do(qq|
15497                     ALTER TABLE $name
15498                         DROP KEY `name`,
15499                         ADD UNIQUE KEY `name` (`name` (191))
15500                 |);
15501                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15502             }
15503             elsif ( $name eq 'search_marc_map' ) {
15504                 $dbh->do(qq|
15505                     ALTER TABLE $name
15506                         DROP KEY `index_name`,
15507                         ADD UNIQUE KEY `index_name` (`index_name`, `marc_field` (191), `marc_type`)
15508                 |);
15509                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15510             }
15511             elsif ( $name eq 'sms_providers' ) {
15512                 $dbh->do(qq|
15513                     ALTER TABLE $name
15514                         DROP KEY `name`,
15515                         ADD UNIQUE KEY `name` (`name` (191))
15516                 |);
15517                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15518             }
15519             elsif ( $name eq 'tags' ) {
15520                 $dbh->do(qq|
15521                     ALTER TABLE $name
15522                         DROP PRIMARY KEY,
15523                         ADD PRIMARY KEY (`entry` (191))
15524                 |);
15525                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15526             }
15527             elsif ( $name eq 'tags_approval' ) {
15528                 $dbh->do(qq|
15529                     ALTER TABLE $name
15530                         MODIFY COLUMN `term` VARCHAR(191) NOT NULL
15531                 |);
15532                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15533             }
15534             elsif ( $name eq 'tags_index' ) {
15535                 $dbh->do(qq|
15536                     ALTER TABLE $name
15537                         MODIFY COLUMN `term` VARCHAR(191) NOT NULL
15538                 |);
15539                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15540             }
15541             else {
15542                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15543             }
15544         }
15545     }
15546     $dbh->do(q|SET foreign_key_checks = 1|);
15547
15548     print "Upgrade to $DBversion done (Bug 18336 - Convert DB tables to utf8mb4 🎁)\n";
15549     SetVersion($DBversion);
15550 }
15551
15552
15553 $DBversion = '17.12.00.017';
15554 if( CheckVersion( $DBversion ) ) {
15555
15556     if( !column_exists( 'items', 'damaged_on' ) ) {
15557         $dbh->do( "ALTER TABLE items ADD COLUMN damaged_on DATETIME NULL AFTER damaged");
15558     }
15559     if( !column_exists( 'deleteditems', 'damaged_on' ) ) {
15560         $dbh->do( "ALTER TABLE deleteditems ADD COLUMN damaged_on DATETIME NULL AFTER damaged");
15561     }
15562
15563     SetVersion( $DBversion );
15564     print "Upgrade to $DBversion done (Bug 17672 - Add damaged_on to items and deleteditems tables)\n";
15565 }
15566
15567 $DBversion = '17.12.00.018';
15568 if( CheckVersion( $DBversion ) ) {
15569
15570     $dbh->do( q|
15571         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES  ('BrowseResultSelection','0',NULL,'Enable/Disable browsing search results fromt the bibliographic record detail page in staff client','YesNo')
15572     |);
15573
15574     SetVersion( $DBversion );
15575     print "Upgrade to $DBversion done (Bug 19290 - Add system preference BrowseResultSelection)\n";
15576 }
15577
15578 $DBversion = '17.12.00.019';
15579 if( CheckVersion( $DBversion ) ) {
15580
15581     $dbh->do(q|UPDATE auth_subfield_structure SET hidden=1 WHERE hidden<>0|);
15582
15583     SetVersion( $DBversion );
15584     print "Upgrade to $DBversion done (Bug 20074 - Auth_subfield_structure changes hidden attribute)\n";
15585 }
15586
15587 $DBversion = '17.12.00.020';
15588 if( CheckVersion( $DBversion ) ) {
15589
15590     $dbh->do(q|
15591         INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)
15592         VALUES ('vi', 'language', 'de', 'Vietnamesisch')
15593     |);
15594
15595     $dbh->do(q|
15596         UPDATE language_descriptions SET description = 'Tiếng Việt'
15597         WHERE subtag = 'vi' and type = 'language' and lang = 'vi'
15598     |);
15599
15600     SetVersion( $DBversion );
15601     print "Upgrade to $DBversion done (Bug 20082 - Update descriptions of Vietnamese language)\n";
15602 }
15603
15604 $DBversion = '17.12.00.021';
15605 if( CheckVersion( $DBversion ) ) {
15606
15607     $dbh->do(q|
15608         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
15609         ('PurgeSuggestionsOlderThan', '', NULL, 'Default value for cronjob purge_suggestions.pl', 'Integer');
15610     |);
15611
15612     SetVersion( $DBversion );
15613     print "Upgrade to $DBversion done (Bug 13287 - Add system preference PurgeSuggestionsOlderThan)\n";
15614 }
15615
15616 $DBversion = '17.12.00.022';
15617 if( CheckVersion( $DBversion ) ) {
15618
15619     if( !column_exists( 'currency', 'p_sep_by_space' ) ) {
15620         $dbh->do(q|
15621             ALTER TABLE currency ADD COLUMN p_sep_by_space tinyint(1) default 0 after archived
15622         |);
15623     }
15624
15625     SetVersion( $DBversion );
15626     print "Upgrade to $DBversion done (Bug 4078 - Add column currency.p_sep_by_space)\n";
15627 }
15628
15629 $DBversion = '17.12.00.023';
15630 if( CheckVersion( $DBversion ) ) {
15631     $dbh->do(q{
15632         DELETE FROM systempreferences
15633         WHERE variable='checkdigit'
15634     });
15635
15636     SetVersion( $DBversion );
15637     print "Upgrade to $DBversion done (Bug 20264 - Remove system preference 'checkdigit')\n";
15638 }
15639
15640 $DBversion = '17.12.00.024';
15641 if( CheckVersion( $DBversion ) ) {
15642
15643     $dbh->do(q{
15644         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15645         VALUES ('SelfCheckInMainUserBlock', '', '70|10', 'Add a block of HTML that will display on the self check-in screen.', 'Textarea');
15646     });
15647
15648     $dbh->do(q{
15649         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15650         VALUES ('SelfCheckInModule', 0, NULL, 'Enable the standalone self-checkin module.', 'YesNo');
15651     });
15652
15653     $dbh->do(q{
15654         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15655         VALUES ('SelfCheckInModuleUserID', NULL, NULL, 'Patron ID (borrowernumber) to be allowed on the self-checkin module.', 'Integer');
15656     });
15657
15658     $dbh->do(q{
15659         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15660         VALUES ('SelfCheckInTimeout', 120, NULL, 'Define the number of seconds before the self check-in module times out.', 'Integer');
15661     });
15662
15663     $dbh->do(q{
15664         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15665         VALUES ('SelfCheckInUserCSS', '', NULL, 'Add CSS to be included in the self check-in module in an embedded <style> tag.', 'free');
15666     });
15667
15668     $dbh->do(q{
15669         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15670         VALUES ('SelfCheckInUserJS', '', NULL, 'Define custom javascript for inclusion in the self check-in module.', 'free');
15671     });
15672
15673     # Add new userflag for self check
15674     $dbh->do(q{
15675         INSERT IGNORE INTO userflags (bit,flag,flagdesc,defaulton) VALUES
15676             (23,'self_check','Self check modules',0);
15677     });
15678
15679     # Add self check-in module subpermission
15680     $dbh->do(q{
15681         INSERT IGNORE INTO permissions (module_bit,code,description)
15682         VALUES (23, 'self_checkin_module', 'Log into the self check-in module');
15683     });
15684
15685     # Add self check-in module subpermission
15686     $dbh->do(q{
15687         INSERT IGNORE INTO permissions (module_bit,code,description)
15688         VALUES (23, 'self_checkout_module', 'Perform self checkout at the OPAC. It should be used for the patron matching the AutoSelfCheckID');
15689     });
15690
15691     # Update patrons with self_checkout permission
15692     # IMPORTANT: Needs to happen before removing the old subpermission
15693     $dbh->do(q{
15694         UPDATE user_permissions
15695         SET module_bit = 23,
15696                   code = 'self_checkout_module'
15697         WHERE module_bit = 1 AND code = 'self_checkout';
15698     });
15699
15700     # Remove old self_checkout permission
15701     $dbh->do(q{
15702         DELETE IGNORE FROM permissions
15703         WHERE  code='self_checkout';
15704     });
15705
15706     SetVersion( $DBversion );
15707     print "Upgrade to $DBversion done (Bug 15492 - Add a standalone self-checkin module)\n";
15708 }
15709
15710 $DBversion = '17.12.00.025';
15711 if( CheckVersion( $DBversion ) ) {
15712     $dbh->do(q|
15713         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
15714         VALUES ('StaffLoginInstructions','','HTML to go into the login box for the staff client',NULL,'Free')
15715     |);
15716     $dbh->do(q|
15717         UPDATE systempreferences
15718         SET variable = 'OpacLoginInstructions'
15719         WHERE variable = 'NoLoginInstructions'
15720     |);
15721
15722     SetVersion( $DBversion );
15723     print "Upgrade to $DBversion done (Bug 20291 - Add StaffLoginInstructions system preference and rename NoLoginInstructions with OpacLoginInstructions)\n";
15724 }
15725
15726 $DBversion = '17.12.00.026';
15727 if( CheckVersion( $DBversion ) ) {
15728     if( !column_exists( 'issuingrules', 'suspension_chargeperiod' ) ) {
15729         $dbh->do(q|
15730             ALTER TABLE issuingrules ADD COLUMN suspension_chargeperiod int(11) DEFAULT '1' AFTER maxsuspensiondays;
15731         |);
15732     }
15733
15734     SetVersion( $DBversion );
15735     print "Upgrade to $DBversion done (Bug 19804 - Add issuingrules.suspension_chargeperiod)\n";
15736 }
15737
15738 $DBversion = '17.12.00.027';
15739 if( CheckVersion( $DBversion ) ) {
15740     $dbh->do(q|
15741         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
15742         VALUES ('UseACQFrameworkForBiblioRecords','0','','Use the ACQ framework for the catalog details','YesNo')
15743     |);
15744
15745     SetVersion( $DBversion );
15746     print "Upgrade to $DBversion done (Bug 19289 - Add system preference UseACQFrameworkForBiblioRecords)\n";
15747 }
15748
15749 $DBversion = '17.12.00.028';
15750 if( CheckVersion( $DBversion ) ) {
15751     if( !column_exists( 'marc_tag_structure', 'ind1_defaultvalue' ) ) {
15752         $dbh->do(q|
15753             ALTER TABLE marc_tag_structure
15754             ADD COLUMN ind2_defaultvalue VARCHAR(1) NOT NULL DEFAULT '' AFTER authorised_value,
15755             ADD COLUMN ind1_defaultvalue VARCHAR(1) NOT NULL DEFAULT '' AFTER authorised_value;
15756         |);
15757     }
15758
15759     SetVersion( $DBversion );
15760     print "Upgrade to $DBversion done (Bug 9701 - Add default indicators (marc_tag_structure.indX_defaultvalue))\n";
15761 }
15762
15763 $DBversion = '17.12.00.029';
15764 if( CheckVersion( $DBversion ) ) {
15765     my $pref =
15766 q|# PERSO_NAME  100 600 696 700 796 800 896
15767 marc21, 100, ind1:auth1
15768 marc21, 600, ind1:auth1, ind2:thesaurus
15769 marc21, 696, ind1:auth1
15770 marc21, 700, ind1:auth1
15771 marc21, 796, ind1:auth1
15772 marc21, 800, ind1:auth1
15773 marc21, 896, ind1:auth1
15774 # CORPO_NAME  110 610 697 710 797 810 897
15775 marc21, 110, ind1:auth1
15776 marc21, 610, ind1:auth1, ind2:thesaurus
15777 marc21, 697, ind1:auth1
15778 marc21, 710, ind1:auth1
15779 marc21, 797, ind1:auth1
15780 marc21, 810, ind1:auth1
15781 marc21, 897, ind1:auth1
15782 # MEETI_NAME    111 611 698 711 798 811 898
15783 marc21, 111, ind1:auth1
15784 marc21, 611, ind1:auth1, ind2:thesaurus
15785 marc21, 698, ind1:auth1
15786 marc21, 711, ind1:auth1
15787 marc21, 798, ind1:auth1
15788 marc21, 811, ind1:auth1
15789 marc21, 898, ind1:auth1
15790 # UNIF_TITLE        130 440 630 699 730 799 830 899 / 240
15791 marc21, 130, ind1:auth2
15792 marc21, 240, , ind2:auth2
15793 marc21, 440, , ind2:auth2
15794 marc21, 630, ind1:auth2, ind2:thesaurus
15795 marc21, 699, ind1:auth2
15796 marc21, 730, ind1:auth2
15797 marc21, 799, ind1:auth2
15798 marc21, 830, , ind2:auth2
15799 marc21, 899, ind1:auth2
15800 # CHRON_TERM    648
15801 marc21, 648, , ind2:thesaurus
15802 # TOPIC_TERM      650 654 656 657 658 690
15803 marc21, 650, , ind2:thesaurus
15804 # GEOGR_NAME   651 662 691 / 751
15805 marc21, 651, , ind2:thesaurus
15806 # GENRE/FORM    655
15807 marc21, 655, , ind2:thesaurus
15808
15809 # UNIMARC: Always copy the indicators from the authority
15810 unimarc, *, ind1:auth1, ind2:auth2|;
15811
15812     $dbh->do( q|
15813         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
15814         VALUES ( 'AuthorityControlledIndicators', ?, 'Authority controlled indicators per biblio field', NULL, 'Free' );
15815     |, undef, $pref );
15816
15817     SetVersion( $DBversion );
15818     print "Upgrade to $DBversion done (Bug 14769 - Authorities merge: Set correct indicators in biblio field (new system preference AuthorityControlledIndicators))\n";
15819 }
15820
15821 $DBversion = '17.12.00.030';
15822 if( CheckVersion( $DBversion ) ) {
15823     $dbh->do(q|
15824         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
15825         VALUES ('NovelistSelectStaffProfile',NULL,'Novelist staff client user Profile',NULL,'free')
15826     |);
15827
15828     SetVersion( $DBversion );
15829     print "Upgrade to $DBversion done (Bug 19882 - Add system preference NovelistSelectStaffProfile)\n";
15830 }
15831
15832 $DBversion = '17.12.00.031';
15833 if( CheckVersion( $DBversion ) ) {
15834     $dbh->do(q|
15835         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
15836         VALUES ('MarcFieldDocURL', NULL, NULL, 'URL used for MARC field documentation. Following substitutions are available: {MARC} = marc flavour, eg. \"MARC21\" or \"UNIMARC\". {FIELD} = field number, eg. \"000\" or \"048\". {LANG} = user language, eg. \"en\" or \"fi-FI\"', 'free')
15837     |);
15838
15839     SetVersion( $DBversion );
15840     print "Upgrade to $DBversion done (Bug 11674 - Add system preference MarcFieldDocURL)\n";
15841 }
15842
15843 $DBversion = '17.12.00.032';
15844 if( CheckVersion( $DBversion ) ) {
15845     $dbh->do(q|
15846         UPDATE letter SET code = "SERIAL_ALERT" WHERE code = "RLIST";
15847     |);
15848     $dbh->do(q|
15849         UPDATE letter SET name = "New serial issue" WHERE name = "Routing List";
15850     |);
15851     $dbh->do(q|
15852         UPDATE subscription SET letter = "SERIAL_ALERT" WHERE letter = "RLIST";
15853     |);
15854
15855     SetVersion( $DBversion );
15856     print "Upgrade to $DBversion done (Bug 19794 - Rename RLIST notice to SERIAL_ALERT)\n";
15857 }
15858
15859 $DBversion = '17.12.00.033';
15860 if( CheckVersion( $DBversion ) ) {
15861     if ( !column_exists( 'accountlines', 'payment_type' ) ) {
15862         $dbh->do(q{
15863             ALTER TABLE accountlines ADD payment_type varchar(80) default NULL AFTER accounttype
15864         });
15865     }
15866
15867     $dbh->do(q{
15868         INSERT IGNORE INTO authorised_value_categories( category_name ) VALUES ('PAYMENT_TYPE')
15869     });
15870
15871     SetVersion( $DBversion );
15872     print "Upgrade to $DBversion done (Bug 18786 - Add ability to create custom payment types)\n";
15873 }
15874
15875 $DBversion = '17.12.00.034';
15876 if( CheckVersion( $DBversion ) ) {
15877
15878     $dbh->do( q{
15879         INSERT IGNORE INTO account_offset_types ( type ) VALUES ('Void Payment')
15880     } );
15881
15882     SetVersion( $DBversion );
15883     print "Upgrade to $DBversion done (Bug 18790 - Add ability to void payment)\n";
15884 }
15885
15886 $DBversion = '17.12.00.035';
15887 if( CheckVersion( $DBversion ) ) {
15888     my ( $original_value ) = $dbh->selectrow_array(q|
15889         SELECT value FROM systempreferences WHERE variable="MarkLostItemsAsReturned"
15890     |);
15891     if ( $original_value and $original_value eq '1' ) {
15892         $dbh->do(q{
15893             UPDATE systempreferences
15894             SET type="multiple",
15895                 options="batchmod|moredetail|cronjob|additem",
15896                 value="batchmod,moredetail,cronjob,additem"
15897             WHERE variable="MarkLostItemsAsReturned"
15898         });
15899     } else {
15900         $dbh->do(q{
15901             UPDATE systempreferences
15902             SET type="multiple",
15903                 options="batchmod|moredetail|cronjob|additem",
15904                 value=""
15905             WHERE variable="MarkLostItemsAsReturned"
15906         });
15907     }
15908
15909     SetVersion( $DBversion );
15910     print "Upgrade to $DBversion done (Bug 19974 - Make MarkLostItemsAsReturned multiple)\n";
15911 }
15912
15913 $DBversion = '17.12.00.036';
15914 if( CheckVersion( $DBversion ) ) {
15915
15916     $dbh->do( q{
15917         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES ('CanMarkHoldsToPullAsLost','do_not_allow','do_not_allow|allow|allow_and_notify','Add a button to the "Holds to pull" screen to mark an item as lost and notify the patron.','Choice');
15918     } );
15919     $dbh->do( q{
15920         INSERT IGNORE INTO letter(module, code, branchcode, name, is_html, title, content, message_transport_type, lang) VALUES ('reserves', 'CANCEL_HOLD_ON_LOST', '', 'Hold has been cancelled', 0, "Hold has been cancelled", "Dear [% borrower.firstname %] [% borrower.surname %],\n\nWe regret to inform you, that the following item can not be provided due to it being missing. Your hold was cancelled.\n\nTitle: [% biblio.title %]\nAuthor: [% biblio.author %]\nCopy: [% item.copynumber %]\nLocation: [% branch.branchname %]", 'email', 'default');
15921     } );
15922     $dbh->do( q{
15923         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES ('UpdateItemWhenLostFromHoldList','',NULL,'This is a list of values to update an item when it is marked as lost from the holds to pull screen','Free');
15924     } );
15925     $dbh->do( q{
15926         UPDATE systempreferences SET options="batchmod|moredetail|cronjob|additem|pendingreserves" WHERE variable="MarkLostItemsAsReturned";
15927     } );
15928
15929     SetVersion( $DBversion );
15930     print "Upgrade to $DBversion done (Bug 19287 - Add ability to mark an item 'Lost' from 'Holds to pull' list (CanMarkHoldsToPullAsLost, UpdateItemWhenLostFromHoldList and CANCEL_HOLD_ON_LOST))\n";
15931 }
15932
15933 $DBversion = '17.12.00.037';
15934 if( CheckVersion( $DBversion ) ) {
15935
15936     SetVersion( $DBversion );
15937     print "Upgrade to $DBversion done (This change has been reverted, nothing done!)\n";
15938 }
15939
15940 $DBversion = '17.12.00.038';
15941 if( CheckVersion( $DBversion ) ) {
15942
15943     $dbh->do( q{
15944         UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'slo' WHERE iso639_2_code = 'slk' AND rfc4646_subtag = 'sk';
15945     } );
15946
15947     SetVersion( $DBversion );
15948     print "Upgrade to $DBversion done (Bug 20245 - Use Bibliographic code value for Slovak language)\n";
15949 }
15950
15951 $DBversion = '17.12.00.039';
15952 if( CheckVersion( $DBversion ) ) {
15953
15954     $dbh->do( q{
15955         UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'baq' WHERE iso639_2_code = 'eus' AND rfc4646_subtag = 'eu';
15956     } );
15957     $dbh->do( q{
15958         UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'mao' WHERE iso639_2_code = 'mri' AND rfc4646_subtag = 'mi';
15959     } );
15960     $dbh->do( q{
15961         UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'alb' WHERE iso639_2_code = 'sqi' AND rfc4646_subtag = 'sq';
15962     } );
15963
15964     SetVersion( $DBversion );
15965     print "Upgrade to $DBversion done (Bug 20482 - Use Bibliographic code value for Basque, Maori and Albanian languages)\n";
15966 }
15967
15968 $DBversion = '17.12.00.040';
15969 if( CheckVersion( $DBversion ) ) {
15970
15971     $dbh->do( q{
15972         INSERT IGNORE INTO systempreferences ( value, variable, options, explanation, type )
15973         VALUES ( '0', 'ProtectSuperlibrarianPrivileges', NULL, 'If enabled, non-superlibrarians cannot set superlibrarian privileges', 'YesNo' )
15974     } );
15975
15976     SetVersion( $DBversion );
15977     print "Upgrade to $DBversion done (Bug 20100 - Add new system preference ProtectSuperlibrarianPrivileges)\n";
15978 }
15979
15980 $DBversion = '17.12.00.041';
15981 if( CheckVersion( $DBversion ) ) {
15982
15983     $dbh->do( q{
15984         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES (13, 'access_files', 'Access to the files stored on the server');
15985     } );
15986
15987     SetVersion( $DBversion );
15988     print "Upgrade to $DBversion done (Bug 11317 - Add a new permission to access files stored on the server)\n";
15989 }
15990
15991 $DBversion = '17.12.00.042';
15992 if( CheckVersion( $DBversion ) ) {
15993
15994     if (!TableExists('oauth_access_tokens')) {
15995         $dbh->do(q{
15996             CREATE TABLE oauth_access_tokens (
15997                 `access_token` VARCHAR(191) NOT NULL,
15998                 `client_id`    VARCHAR(191) NOT NULL,
15999                 `expires`      INT NOT NULL,
16000                 PRIMARY KEY (`access_token`)
16001             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
16002         });
16003     }
16004
16005     SetVersion( $DBversion );
16006     print "Upgrade to $DBversion done (Bug 20402 - Implement OAuth2 authentication for REST API)\n";
16007 }
16008
16009 $DBversion = '17.12.00.043';
16010 if(CheckVersion($DBversion)) {
16011
16012     if (!TableExists('api_keys')) {
16013         $dbh->do(q{
16014             CREATE TABLE `api_keys` (
16015                 `client_id`   VARCHAR(191) NOT NULL,
16016                 `secret`      VARCHAR(191) NOT NULL,
16017                 `description` VARCHAR(255) NOT NULL,
16018                 `patron_id`   INT(11) NOT NULL,
16019                 `active`      TINYINT(1) DEFAULT 1 NOT NULL,
16020                 PRIMARY KEY `client_id` (`client_id`),
16021                 UNIQUE KEY `secret` (`secret`),
16022                 KEY `patron_id` (`patron_id`),
16023                 CONSTRAINT `api_keys_fk_patron_id`
16024                   FOREIGN KEY (`patron_id`)
16025                   REFERENCES `borrowers` (`borrowernumber`)
16026                   ON DELETE CASCADE ON UPDATE CASCADE
16027             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16028         });
16029     }
16030
16031     print "Upgrade to $DBversion done (Bug 20568 - Add API key management interface for patrons)\n";
16032     SetVersion($DBversion);
16033 }
16034
16035 $DBversion = '17.12.00.044';
16036 if(CheckVersion($DBversion)) {
16037
16038     $dbh->do(q{
16039         INSERT IGNORE INTO systempreferences (`variable`,`value`,`options`,`explanation`,`type`)
16040         VALUES
16041             ('RESTOAuth2ClientCredentials','0',NULL,'If enabled, the OAuth2 client credentials flow is enabled for the REST API.','YesNo');
16042     });
16043
16044     print "Upgrade to $DBversion done (Bug 20624 - Disable OAuth2 client credentials grant by default)\n";
16045     SetVersion($DBversion);
16046 }
16047
16048 $DBversion = '18.05.00.000';
16049 if( CheckVersion( $DBversion ) ) {
16050     SetVersion( $DBversion );
16051     print "Upgrade to $DBversion done (Koha 18.05)\n";
16052 }
16053
16054 $DBversion = '18.06.00.000';
16055 if( CheckVersion( $DBversion ) ) {
16056     SetVersion( $DBversion );
16057     print "Upgrade to $DBversion done (Koha 18.06 - It's Adventure time!)\n";
16058 }
16059
16060 $DBversion = '18.06.00.001';
16061 if( CheckVersion( $DBversion ) ) {
16062     $dbh->do(q{UPDATE permissions SET description = 'Manage budgets' WHERE code = 'period_manage';});
16063     $dbh->do(q{UPDATE permissions SET description = 'Manage funds' WHERE code = 'budget_manage';});
16064     $dbh->do(q{UPDATE permissions SET description = 'Modify funds (can''t create lines, but can modify existing ones)' WHERE code = 'budget_modify';});
16065     $dbh->do(q{UPDATE permissions SET description = 'Manage baskets and order lines' WHERE code = 'order_manage';});
16066     $dbh->do(q{UPDATE permissions SET description = 'Manage all baskets and order lines, regardless of restrictions on them' WHERE code = 'order_manage_all';});
16067     $dbh->do(q{UPDATE permissions SET description = 'Manage basket groups' WHERE code = 'group_manage';});
16068     $dbh->do(q{UPDATE permissions SET description = 'Receive orders and manage shipments' WHERE code = 'order_receive';});
16069     $dbh->do(q{UPDATE permissions SET description = 'Add and delete funds (but can''t modify funds)' WHERE code = 'budget_add_del';});
16070     $dbh->do(q{UPDATE permissions SET description = 'Manage all funds' WHERE code = 'budget_manage_all';});
16071     SetVersion( $DBversion );
16072     print "Upgrade to $DBversion done (Bug 3849- Improve descriptions of granular acquisition permissions)\n";
16073 }
16074
16075 $DBversion = '18.06.00.002';
16076 if( CheckVersion( $DBversion ) ) {
16077     $dbh->do(q{DELETE FROM userflags WHERE bit = 12 AND flag = 'management';});
16078     $dbh->do(q{UPDATE borrowers SET flags = flags - ( flags & (1<<12) ) WHERE flags & (1 << 12);});
16079     SetVersion( $DBversion );
16080     print "Upgrade to $DBversion done (Bug 2426 - Remove deprecated management permission)\n";
16081 }
16082
16083 $DBversion = '18.06.00.003';
16084 if( CheckVersion( $DBversion ) ) {
16085     $dbh->do( "ALTER TABLE search_field CHANGE COLUMN type type ENUM('', 'string', 'date', 'number', 'boolean', 'sum', 'isbn', 'stdno') NOT NULL COMMENT 'what type of data this holds, relevant when storing it in the search engine'" );
16086     SetVersion( $DBversion );
16087     print "Upgrade to $DBversion done (Bug 20073 - Add new types for Elasticsearch fields)\n";
16088 }
16089
16090 $DBversion = '18.06.00.004';
16091 if( CheckVersion( $DBversion ) ) {
16092
16093     # Add 'Manual Credit' offset type
16094     $dbh->do(q{
16095         INSERT IGNORE INTO `account_offset_types` (`type`) VALUES ('Manual Credit');
16096     });
16097
16098     # Fix wrong account offsets / Manual credits
16099     $dbh->do(q{
16100         UPDATE account_offsets
16101         SET credit_id=debit_id,
16102             debit_id=NULL,
16103             type='Manual Credit'
16104         WHERE amount < 0 AND
16105               type='Manual Debit' AND
16106               debit_id IN
16107                 (SELECT accountlines_id AS debit_id
16108                  FROM accountlines
16109                  WHERE accounttype='C');
16110     });
16111
16112     # Fix wrong account offsets / Manually forgiven amounts
16113     $dbh->do(q{
16114         UPDATE account_offsets
16115         SET credit_id=debit_id,
16116             debit_id=NULL,
16117             type='Writeoff'
16118         WHERE amount < 0 AND
16119               type='Manual Debit' AND
16120               debit_id IN
16121                 (SELECT accountlines_id AS debit_id
16122                  FROM accountlines
16123                  WHERE accounttype='FOR');
16124     });
16125
16126     SetVersion( $DBversion );
16127     print "Upgrade to $DBversion done (Bug 20980 - Manual credit offsets are stored as debits)\n";
16128 }
16129
16130 $DBversion = '18.06.00.005';
16131 if( CheckVersion( $DBversion ) ) {
16132     unless ( column_exists('aqorders', 'created_by') ) {
16133         $dbh->do( "ALTER TABLE aqorders ADD COLUMN created_by int(11) NULL DEFAULT NULL AFTER quantityreceived;" );
16134         unless ( foreign_key_exists('aqorders', 'aqorders_created_by') ) {
16135             $dbh->do( "ALTER TABLE aqorders ADD CONSTRAINT aqorders_created_by FOREIGN KEY (created_by) REFERENCES borrowers (borrowernumber) ON DELETE SET NULL ON UPDATE CASCADE;" );
16136         }
16137         $dbh->do( "UPDATE aqorders, aqbasket SET aqorders.created_by = aqbasket.authorisedby  WHERE aqorders.basketno = aqbasket.basketno AND aqorders.created_by IS NULL;" );
16138     }
16139     SetVersion( $DBversion );
16140     print "Upgrade to $DBversion done (Bug 12395 - Save order line's creator)\n";
16141 }
16142
16143 $DBversion = '18.06.00.006';
16144 if( CheckVersion( $DBversion ) ) {
16145     unless ( column_exists('patron_lists', 'shared') ) {
16146         $dbh->do( "ALTER TABLE patron_lists ADD COLUMN shared tinyint(1) default 0 AFTER owner;" );
16147     }
16148     SetVersion( $DBversion );
16149     print "Upgrade to $DBversion done (Bug 19524 - Share patron lists between staff)\n";
16150 }
16151
16152 $DBversion = '18.06.00.007';
16153 if( CheckVersion( $DBversion ) ) {
16154     $dbh->do( "INSERT IGNORE INTO permissions (module_bit, code, description) VALUES (11, 'currencies_manage', 'Manage currencies and exchange rates');" );
16155     $dbh->do(q{
16156         INSERT IGNORE INTO user_permissions (borrowernumber, module_bit, code)
16157             SELECT borrowernumber, 11, 'currencies_manage' FROM borrowers WHERE flags & (1 << 3) OR borrowernumber IN
16158             (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16159     });
16160     SetVersion( $DBversion );
16161     print "Upgrade to $DBversion done (Bug 7651 - Add separate permission for managing currencies and exchange rates)\n";
16162 }
16163
16164 $DBversion = '18.06.00.008';
16165 if( CheckVersion( $DBversion ) ) {
16166     $dbh->do( "ALTER TABLE marc_modification_template_actions CHANGE action action ENUM('delete_field','add_field','update_field','move_field','copy_field','copy_and_replace_field')" );
16167     SetVersion( $DBversion );
16168     print "Upgrade to $DBversion done (Bug 13560 - need an add option in marc modification templates)\n";
16169 }
16170
16171 $DBversion = '18.06.00.009';
16172 if( CheckVersion( $DBversion ) ) {
16173     $dbh->do( "
16174         CREATE TABLE IF NOT EXISTS aqinvoice_adjustments (
16175             adjustment_id int(11) NOT NULL AUTO_INCREMENT,
16176             invoiceid int(11) NOT NULL,
16177             adjustment decimal(28,6),
16178             reason varchar(80) default NULL,
16179             note mediumtext default NULL,
16180             budget_id int(11) default NULL,
16181             encumber_open smallint(1) NOT NULL default 1,
16182             timestamp timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
16183             PRIMARY KEY (adjustment_id),
16184             CONSTRAINT aqinvoice_adjustments_fk_invoiceid FOREIGN KEY (invoiceid) REFERENCES aqinvoices (invoiceid) ON DELETE CASCADE ON UPDATE CASCADE,
16185             CONSTRAINT aqinvoice_adjustments_fk_budget_id FOREIGN KEY (budget_id) REFERENCES aqbudgets (budget_id) ON DELETE SET NULL ON UPDATE CASCADE
16186         ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
16187         " );
16188     $dbh->do("INSERT IGNORE INTO authorised_value_categories (category_name) VALUES ('ADJ_REASON')");
16189     SetVersion( $DBversion );
16190     print "Upgrade to $DBversion done (Bug 19166 - Add the ability to add adjustments to an invoice)\n";
16191 }
16192
16193 $DBversion = '18.06.00.010';
16194 if( CheckVersion( $DBversion ) ) {
16195     $dbh->do(q{
16196         INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`, `lang`)
16197         VALUES
16198             ('circulation', 'ACCOUNT_PAYMENT', '', 'Account payment', 0, 'Account payment', '[%- USE Price -%]\r\nA payment of [% credit.amount * -1 | $Price %] has been applied to your account.\r\n\r\nThis payment affected the following fees:\r\n[%- FOREACH o IN offsets %]\r\nDescription: [% o.debit.description %]\r\nAmount paid: [% o.amount * -1 | $Price %]\r\nAmount remaining: [% o.debit.amountoutstanding | $Price %]\r\n[% END %]', 'email', 'default'),
16199                 ('circulation', 'ACCOUNT_WRITEOFF', '', 'Account writeoff', 0, 'Account writeoff', '[%- USE Price -%]\r\nAn account writeoff of [% credit.amount * -1 | $Price %] has been applied to your account.\r\n\r\nThis writeoff affected the following fees:\r\n[%- FOREACH o IN offsets %]\r\nDescription: [% o.debit.description %]\r\nAmount paid: [% o.amount * -1 | $Price %]\r\nAmount remaining: [% o.debit.amountoutstanding | $Price %]\r\n[% END %]', 'email', 'default');
16200     });
16201     $dbh->do(q{
16202         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
16203         VALUES ('UseEmailReceipts','0','','Send email receipts for payments and write-offs','YesNo')
16204     });
16205     SetVersion( $DBversion );
16206     print "Upgrade to $DBversion done (Bug 19191 - Add ability to email receipts for account payments and write-offs)\n";
16207 }
16208
16209 $DBversion = '18.06.00.011';
16210 if( CheckVersion( $DBversion ) ) {
16211     unless( column_exists( 'issues', 'noteseen' ) ) {
16212         $dbh->do(q|ALTER TABLE issues ADD COLUMN noteseen int(1) default NULL AFTER notedate|);
16213     }
16214
16215     unless( column_exists( 'old_issues', 'noteseen' ) ) {
16216         $dbh->do(q|ALTER TABLE old_issues ADD COLUMN noteseen int(1) default NULL AFTER notedate|);
16217     }
16218     $dbh->do(q|INSERT IGNORE INTO permissions (module_bit, code, description) VALUES ( 1, 'manage_checkout_notes', 'Mark checkout notes as seen/not seen');|);
16219     SetVersion( $DBversion );
16220     print "Upgrade to $DBversion done (Bug 17698: Add column issues.noteseen and old_issues.noteseen)\n";
16221 }
16222
16223 $DBversion = '18.06.00.012';
16224 if( CheckVersion( $DBversion ) ) {
16225     $dbh->do(q|INSERT IGNORE INTO permissions (module_bit, code, description) VALUES (11, 'suggestions_manage', 'Manage purchase suggestions');|);
16226     $dbh->do(q|INSERT IGNORE INTO user_permissions (borrowernumber, module_bit, code) SELECT borrowernumber, 11, 'suggestions_manage' FROM borrowers WHERE flags & (1 << 2);|);
16227     SetVersion( $DBversion );
16228     print "Upgrade to $DBversion done (Bug 11911 - Add separate permission for managing suggestions)\n";
16229 }
16230
16231 $DBversion = '18.06.00.013';
16232 if( CheckVersion( $DBversion ) ) {
16233     $dbh->do(q{
16234         INSERT IGNORE INTO `account_offset_types` (`type`) VALUES ('Credit Applied');
16235     });
16236     SetVersion( $DBversion );
16237     print "Upgrade to $DBversion done (Bug 20997 - Add Koha::Account::Line::apply)\n";
16238 }
16239
16240 $DBversion = '18.06.00.014';
16241 if( CheckVersion( $DBversion ) ) {
16242     $dbh->do(q{
16243             INSERT IGNORE INTO  systempreferences (variable, value, options, explanation) VALUES ('HidePersonalPatronDetailOnCirculation', 0, 'YesNo', 'Hide patrons phone number, email address, street address and city in the circulation page');
16244     });
16245     SetVersion( $DBversion );
16246     print "Upgrade to $DBversion done (Bug 21121 - New syspref to allow hiding of private patron data in circulation page)\n";
16247 }
16248
16249 $DBversion = '18.06.00.015';
16250 if( CheckVersion( $DBversion ) ) {
16251     $dbh->do(q{DELETE FROM systempreferences where variable="OCLCAffiliateID";});
16252     $dbh->do(q{DELETE FROM systempreferences where variable="XISBN";});
16253     $dbh->do(q{DELETE FROM systempreferences where variable="XISBNDailyLimit";});
16254     SetVersion( $DBversion );
16255     print "Upgrade to $DBversion done (Bug 21226 - Remove prefs OCLCAffiliateID, XISBN and XISBNDailyLimit)\n";
16256 }
16257
16258 $DBversion = '18.06.00.016';
16259 if( CheckVersion( $DBversion ) ) {
16260     my $dtf  = Koha::Database->new->schema->storage->datetime_parser;
16261     my $days = C4::Context->preference('MaxPickupDelay') || 7;
16262     my $date = DateTime->now()->add( days => $days );
16263     my $sql  = q|UPDATE reserves SET expirationdate = ? WHERE expirationdate IS NULL AND waitingdate IS NOT NULL|;
16264     $dbh->do( $sql, undef, $dtf->format_datetime($date) );
16265     SetVersion( $DBversion );
16266     print "Upgrade to $DBversion done (Bug 20773 - expirationdate filled for waiting holds)\n";
16267 }
16268
16269 $DBversion = '18.06.00.017';
16270 if( CheckVersion( $DBversion ) ) {
16271     $dbh->do(q|INSERT IGNORE INTO authorised_value_categories (category_name) VALUES ('ROADTYPE');|);
16272     SetVersion( $DBversion );
16273     print "Upgrade to $DBversion done (Bug 21144: Add ROADTYPE to default authorised values categories)\n";
16274 }
16275
16276 $DBversion = '18.06.00.018';
16277 if( CheckVersion( $DBversion ) ) {
16278     $dbh->do( q|
16279 UPDATE items LEFT JOIN issues USING (itemnumber)
16280 SET items.onloan = NULL
16281 WHERE issues.itemnumber IS NULL
16282     |);
16283     SetVersion( $DBversion );
16284     print "Upgrade to $DBversion done (Bug 20487: Clear items.onloan for unissued items)\n";
16285 }
16286
16287 $DBversion = '18.06.00.019';
16288 if( CheckVersion( $DBversion ) ) {
16289     $dbh->do( q|
16290 INSERT IGNORE INTO columns_settings (module, page, tablename, columnname, cannot_be_toggled, is_hidden) VALUES
16291 ("circ", "circulation", "issues-table", "collection", 0, 1),
16292 ("members", "moremember", "issues-table", "collection", 0, 1);
16293     |);
16294     SetVersion( $DBversion );
16295     print "Upgrade to $DBversion done (Bug 19719: Default to hiding collection code column)\n";
16296 }
16297
16298 $DBversion = '18.06.00.020';
16299 if( CheckVersion( $DBversion ) ) {
16300     if( !column_exists( 'branch_borrower_circ_rules', 'max_holds' ) ) {
16301         $dbh->do(q{
16302             ALTER TABLE branch_borrower_circ_rules ADD COLUMN max_holds INT(4) NULL DEFAULT NULL AFTER maxonsiteissueqty
16303         });
16304     }
16305     if( !column_exists( 'default_borrower_circ_rules', 'max_holds' ) ) {
16306         $dbh->do(q{
16307             ALTER TABLE default_borrower_circ_rules ADD COLUMN max_holds INT(4) NULL DEFAULT NULL AFTER maxonsiteissueqty
16308         });
16309     }
16310     SetVersion( $DBversion );
16311     print "Upgrade to $DBversion done (Bug 15524 - Set limit on maximum possible holds per patron by category)\n";
16312 }
16313
16314 $DBversion = '18.06.00.021';
16315 if( CheckVersion( $DBversion ) ) {
16316     my $dbh = C4::Context->dbh;
16317     unless ( C4::Context->preference('NorwegianPatronDBEnable') ) {
16318         $dbh->do(q|
16319             DELETE FROM systempreferences
16320             WHERE variable IN ('NorwegianPatronDBEnable', 'NorwegianPatronDBEndpoint', 'NorwegianPatronDBUsername', 'NorwegianPatronDBPassword', 'NorwegianPatronDBSearchNLAfterLocalHit')
16321         |);
16322         if ( TableExists('borrower_sync') ) {
16323             $dbh->do(q|DROP TABLE borrower_sync|);
16324         }
16325     }
16326     SetVersion( $DBversion );
16327     print "Upgrade to $DBversion done (Bug 21068 - Remove system preferences NorwegianPatronDB*)\n";
16328 }
16329
16330 $DBversion = '18.06.00.022';
16331 if( CheckVersion( $DBversion ) ) {
16332     my $dbh = C4::Context->dbh;
16333     $dbh->do(q|
16334         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
16335         ('HoldsAutoFill','0',NULL,'If on, librarian will not be asked if hold should be filled, it will be filled automatically','YesNo'),
16336         ('HoldsAutoFillPrintSlip','0',NULL,'If on, hold slip print dialog will be displayed automatically','YesNo')
16337     |);
16338     SetVersion( $DBversion );
16339     print "Upgrade to $DBversion done (Bug 19383 - Add ability to print hold receipts automatically)\n";
16340 }
16341
16342 $DBversion = '18.06.00.023';
16343 if( CheckVersion( $DBversion ) ) {
16344     if( !column_exists( 'aqorders', 'replacementprice' ) ){
16345         $dbh->do( "ALTER TABLE aqorders ADD COLUMN replacementprice DECIMAL(28,6)" );
16346         $dbh->do( "UPDATE aqorders set replacementprice = rrp WHERE replacementprice IS NULL" );
16347     }
16348     SetVersion( $DBversion );
16349     print "Upgrade to $DBversion done (Bug 18639 - Add replacementprice field to aqorders table)\n";
16350 }
16351
16352 $DBversion = '18.06.00.024';
16353 if( CheckVersion( $DBversion ) ) {
16354     if( !column_exists( 'branches', 'pickup_location' ) ){
16355         $dbh->do( "ALTER TABLE branches ADD COLUMN pickup_location TINYINT(1) not null default 1" );
16356     }
16357     SetVersion( $DBversion );
16358     print "Upgrade to $DBversion done (Bug 7534 - Let libraries have configuration for pickup locations)\n";
16359 }
16360
16361 $DBversion = '18.06.00.025';
16362 if( CheckVersion( $DBversion ) ) {
16363     $dbh->do(q{
16364         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
16365         ('KohaManualBaseURL','https://koha-community.org/manual/','','Where is the Koha manual/documentation located?','Free'),
16366         ('KohaManualLanguage','en','en|ar|cs|es|de|fr|it|pt_BR|tr|zh_TW','What is the language of the online manual you want to use?','Choice')
16367     });
16368     SetVersion( $DBversion );
16369     print "Upgrade to $DBversion done (Bug 19817: Add pref KohaManualLanguage and KohaManualBaseURL)\n";
16370 }
16371
16372 $DBversion = '18.06.00.026';
16373 if( CheckVersion( $DBversion ) ) {
16374     $dbh->do(q|
16375 INSERT IGNORE INTO  systempreferences (variable, value, options, explanation, type) VALUES ('ArticleRequestsLinkControl', 'always', 'always\|calc', 'Control display of article request link on search results', 'Choice')
16376     |);
16377     SetVersion( $DBversion );
16378     print "Upgrade to $DBversion done (Bug 17530 - Add pref ArticleRequestsLinkControl)\n";
16379 }
16380
16381 $DBversion = '18.06.00.027';
16382 if( CheckVersion( $DBversion ) ) {
16383     $dbh->do( "DROP TABLE IF EXISTS services_throttle" );
16384     SetVersion( $DBversion );
16385     print "Upgrade to $DBversion done (Bug 21235: Remove table services_throttle)\n";
16386 }
16387
16388 $DBversion = '18.06.00.028';
16389 if( CheckVersion( $DBversion ) ) {
16390     $dbh->do(q{
16391 INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
16392 ('HoldsSplitQueue','nothing','nothing|branch|itemtype|branch_itemtype','In the staff client, split the holds view by the given criteria','Choice'),
16393 ('HoldsSplitQueueNumbering', 'actual', 'actual|virtual', 'If the holds queue is split, decide if the acual priorities should be displayed', 'Choice');
16394 });
16395     SetVersion( $DBversion );
16396     print "Upgrade to $DBversion done (Bug 19469 - Add ability to split view of holds view on record by pickup library and/or itemtype)\n";
16397 }
16398
16399 $DBversion = '18.06.00.029';
16400 if( CheckVersion( $DBversion ) ) {
16401     unless ( index_exists( 'subscription', 'by_biblionumber' ) ) {
16402         $dbh->do(q{
16403             CREATE INDEX `by_biblionumber` ON `subscription` (`biblionumber`)
16404         });
16405     }
16406     SetVersion( $DBversion );
16407     print "Upgrade to $DBversion done (Bug 21288: Slowness in acquisition caused by GetInvoices\n";
16408 }
16409
16410 $DBversion = '18.06.00.030';
16411 if( CheckVersion( $DBversion ) ) {
16412     if ( column_exists( 'accountlines', 'dispute' ) ) {
16413         $dbh->do(q{
16414             ALTER TABLE `accountlines`
16415                 DROP COLUMN `dispute`
16416         });
16417     }
16418     SetVersion( $DBversion );
16419     print "Upgrade to $DBversion done (Bug 20777 - Remove unused field accountlines.dispute)\n";
16420 }
16421
16422 $DBversion = '18.06.00.031';
16423 if( CheckVersion( $DBversion ) ) {
16424     # Add table and add column
16425     unless (TableExists('patron_consent')) {
16426         $dbh->do(q|
16427     CREATE TABLE patron_consent (id int AUTO_INCREMENT, borrowernumber int NOT NULL, type enum('GDPR_PROCESSING' ), given_on datetime, refused_on datetime, PRIMARY KEY (id), FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE )
16428         |);
16429     }
16430     unless ( column_exists( 'borrower_modifications', 'gdpr_proc_consent' ) ) {
16431         $dbh->do(q|
16432     ALTER TABLE borrower_modifications ADD COLUMN gdpr_proc_consent datetime
16433         |);
16434     }
16435     # Add two sysprefs too
16436     $dbh->do(q|
16437 INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type ) VALUES ('PrivacyPolicyURL','',NULL,'This URL is used in messages about GDPR consents.', 'Free')
16438     |);
16439     $dbh->do(q|
16440 INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type ) VALUES ('GDPR_Policy','','Enforced\|Permissive\|Disabled','General Data Protection Regulation - policy', 'Choice')
16441     |);
16442     SetVersion( $DBversion );
16443     print "Upgrade to $DBversion done (Bug 20819: Add patron_consent)\n";
16444 }
16445
16446 $DBversion = '18.06.00.032';
16447 if( CheckVersion( $DBversion ) ) {
16448     $dbh->do(q|ALTER TABLE items                   CHANGE COLUMN ccode ccode varchar(80) default NULL|);
16449     $dbh->do(q|ALTER TABLE deleteditems            CHANGE COLUMN ccode ccode varchar(80) default NULL|);
16450     $dbh->do(q|ALTER TABLE branch_transfer_limits  CHANGE COLUMN ccode ccode varchar(80) default NULL|);
16451     $dbh->do(q|ALTER TABLE course_items            CHANGE COLUMN ccode ccode varchar(80) default NULL|);
16452     SetVersion( $DBversion );
16453     print "Upgrade to $DBversion done (Bug 5458: length of items.ccode disagrees with authorised_values.authorised_value)\n";
16454 }
16455
16456 $DBversion = '18.06.00.033';
16457 if( CheckVersion( $DBversion ) ) {
16458     $dbh->do(q|
16459         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('AdditionalFieldsInZ3950ResultSearch', '', 'NULL', 'Determines which MARC field/subfields are displayed in -Additional field- column in the result of a search Z3950', 'Free')
16460     |);
16461     SetVersion( $DBversion );
16462     print "Upgrade to $DBversion done (Bug 12747 - Add AdditionalFieldsInZ3950ResultSearch system preference)\n";
16463 }
16464
16465 $DBversion = '18.06.00.034';
16466 if( CheckVersion( $DBversion ) ) {
16467     $dbh->do(q|
16468         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
16469         VALUES ('RecordedBooksClientSecret','','30','Client key for RecordedBooks integration','YesNo'),
16470                ('RecordedBooksLibraryID','','','Library ID for RecordedBooks integration','Integer'),
16471                ('RecordedBooksDomain','','','RecordedBooks domain','Free');
16472     |);
16473     SetVersion( $DBversion );
16474     print "Upgrade to $DBversion done (Bug 17602 - Integrate support for OneClickdigital/Recorded Books API)\n";
16475 }
16476
16477 $DBversion = '18.06.00.035';
16478 if( CheckVersion( $DBversion ) ) {
16479     $dbh->do(q{
16480         UPDATE `systempreferences` SET options = 'US|CA|DE|FR|IN|JP|UK' WHERE variable = 'AmazonLocale' AND options='US|CA|DE|FR|JP|UK';
16481     });
16482     SetVersion( $DBversion );
16483     print "Upgrade to $DBversion done (Bug 21403 - Add Indian Amazon Affiliate option to AmazonLocale setting)\n";
16484 }
16485
16486
16487 $DBversion = '18.06.00.036';
16488 if( CheckVersion( $DBversion ) ) {
16489     unless (TableExists('circulation_rules')){
16490         $dbh->do(q{
16491             CREATE TABLE `circulation_rules` (
16492               `id` int(11) NOT NULL auto_increment,
16493               `branchcode` varchar(10) NULL default NULL,
16494               `categorycode` varchar(10) NULL default NULL,
16495               `itemtype` varchar(10) NULL default NULL,
16496               `rule_name` varchar(32) NOT NULL,
16497               `rule_value` varchar(32) NOT NULL,
16498               PRIMARY KEY (`id`),
16499               CONSTRAINT `circ_rules_ibfk_1` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
16500               CONSTRAINT `circ_rules_ibfk_2` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`) ON DELETE CASCADE ON UPDATE CASCADE,
16501               CONSTRAINT `circ_rules_ibfk_3` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE,
16502               KEY `rule_name` (`rule_name`),
16503               UNIQUE (`branchcode`,`categorycode`,`itemtype`,`rule_name`)
16504             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16505         });
16506     }
16507     if (column_exists('branch_borrower_circ_rules', 'max_holds') ){
16508         $dbh->do(q{
16509             INSERT IGNORE INTO circulation_rules ( branchcode, categorycode, itemtype, rule_name, rule_value )
16510             SELECT branchcode, categorycode, NULL, 'max_holds', COALESCE( max_holds, '' ) FROM branch_borrower_circ_rules
16511         });
16512         $dbh->do(q{
16513             ALTER TABLE branch_borrower_circ_rules DROP COLUMN max_holds
16514         });
16515     }
16516     if (column_exists('default_borrower_circ_rules', 'max_holds') ){
16517         $dbh->do(q{
16518             INSERT IGNORE INTO circulation_rules ( branchcode, categorycode, itemtype, rule_name, rule_value )
16519             SELECT NULL, categorycode, NULL, 'max_holds', COALESCE( max_holds, '' ) FROM default_borrower_circ_rules
16520         });
16521         $dbh->do(q{
16522             ALTER TABLE default_borrower_circ_rules DROP COLUMN max_holds
16523         });
16524     }
16525     SetVersion( $DBversion );
16526     print "Upgrade to $DBversion done (Bug 18887 - Introduce new table 'circulation_rules', use for 'max_holds' rules)\n";
16527 }
16528
16529 $DBversion = '18.06.00.037';
16530 if( CheckVersion( $DBversion ) ) {
16531     unless (TableExists('branches_overdrive')){
16532         $dbh->do( q|
16533             CREATE TABLE IF NOT EXISTS branches_overdrive (
16534                 `branchcode` VARCHAR( 10 ) NOT NULL ,
16535                 `authname` VARCHAR( 255 ) NOT NULL ,
16536                 PRIMARY KEY (`branchcode`) ,
16537                 CONSTRAINT `branches_overdrive_ibfk_1` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
16538             ) ENGINE = INNODB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci |
16539         );
16540     }
16541     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('OverDriveAuthname', '', 'Authname for OverDrive Patron Authentication, will be used as fallback if individual branch authname not set', NULL, 'Free');");
16542     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('OverDriveWebsiteID','', 'WebsiteID provided by OverDrive', NULL, 'Free');");
16543     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('OverDrivePasswordRequired','', 'Does the library require passwords for OverDrive SIP authentication', NULL, 'YesNo');");
16544     SetVersion( $DBversion );
16545     print "Upgrade to $DBversion done (Bug 21082 - Add overdrive patron auth method)\n";
16546 }
16547
16548 $DBversion = '18.06.00.038';
16549 if( CheckVersion( $DBversion ) ) {
16550     $dbh->do( "ALTER TABLE edifact_ean MODIFY branchcode VARCHAR(10) NULL DEFAULT NULL" );
16551     SetVersion( $DBversion );
16552     print "Upgrade to $DBversion done (Bug 21417 - EDI ordering fails when basket and EAN libraries do not match)\n";
16553 }
16554
16555 $DBversion = '18.06.00.039';
16556 if( CheckVersion( $DBversion ) ) {
16557     $dbh->do(q{
16558         INSERT IGNORE INTO `permissions` (module_bit, code, description) VALUES(3, 'manage_circ_rules_from_any_libraries', 'Manage circ rules for any libraries');
16559     });
16560     SetVersion( $DBversion );
16561     print "Upgrade to $DBversion done (Bug 15520 - Add more granular permission for only editing own library's circ rules)\n";
16562 }
16563
16564 $DBversion = '18.06.00.040';
16565 if( CheckVersion( $DBversion ) ) {
16566     # Stock Rotation Rotas
16567     unless (TableExists('stockrotationrotas')){
16568         $dbh->do(q{
16569           CREATE TABLE `stockrotationrotas` (
16570             `rota_id` int(11) auto_increment,         -- Stockrotation rota ID
16571             `title` varchar(100) NOT NULL,            -- Title for this rota
16572             `description` text NOT NULL,              -- Description for this rota
16573             `cyclical` tinyint(1) NOT NULL default 0, -- Should items on this rota keep cycling?
16574             `active` tinyint(1) NOT NULL default 0,   -- Is this rota currently active?
16575             PRIMARY KEY (`rota_id`),
16576             CONSTRAINT `stockrotationrotas_title`
16577             UNIQUE (`title`)
16578           ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16579         });
16580     }
16581     # Stock Rotation Stages
16582     unless (TableExists('stockrotationstages')){
16583         $dbh->do(q{
16584           CREATE TABLE `stockrotationstages` (
16585               `stage_id` int(11) auto_increment,     -- Unique stage ID
16586               `position` int(11) NOT NULL,           -- The position of this stage within its rota
16587               `rota_id` int(11) NOT NULL,            -- The rota this stage belongs to
16588               `branchcode_id` varchar(10) NOT NULL,  -- Branch this stage relates to
16589               `duration` int(11) NOT NULL default 4, -- The number of days items shoud occupy this stage
16590               PRIMARY KEY (`stage_id`),
16591               CONSTRAINT `stockrotationstages_rifk`
16592                 FOREIGN KEY (`rota_id`)
16593                 REFERENCES `stockrotationrotas` (`rota_id`)
16594                 ON UPDATE CASCADE ON DELETE CASCADE,
16595               CONSTRAINT `stockrotationstages_bifk`
16596                 FOREIGN KEY (`branchcode_id`)
16597                 REFERENCES `branches` (`branchcode`)
16598                 ON UPDATE CASCADE ON DELETE CASCADE
16599           ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16600         });
16601     }
16602     # Stock Rotation Items
16603     unless (TableExists('stockrotationitems')){
16604         $dbh->do(q{
16605           CREATE TABLE `stockrotationitems` (
16606               `itemnumber_id` int(11) NOT NULL,         -- Itemnumber to link to a stage & rota
16607               `stage_id` int(11) NOT NULL,              -- stage ID to link the item to
16608               `indemand` tinyint(1) NOT NULL default 0, -- Should this item be skipped for rotation?
16609               `fresh` tinyint(1) NOT NULL default 0,    -- Flag showing item is only just added to rota
16610               PRIMARY KEY (itemnumber_id),
16611               CONSTRAINT `stockrotationitems_iifk`
16612                 FOREIGN KEY (`itemnumber_id`)
16613                 REFERENCES `items` (`itemnumber`)
16614                 ON UPDATE CASCADE ON DELETE CASCADE,
16615               CONSTRAINT `stockrotationitems_sifk`
16616                 FOREIGN KEY (`stage_id`)
16617                 REFERENCES `stockrotationstages` (`stage_id`)
16618                 ON UPDATE CASCADE ON DELETE CASCADE
16619           ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16620         });
16621     }
16622     # System preferences
16623     $dbh->do(q{
16624         INSERT IGNORE INTO `systempreferences` (`variable`,`value`,`explanation`,`options`,`type`)
16625         VALUES ('StockRotation','0','If ON, enables the stock rotation module','','YesNo'),
16626                ('RotationPreventTransfers','0','If ON, prevent any transfers for items on stock rotation rotas, except for stock rotation transfers','','YesNo');
16627     });
16628     # Permissions
16629     $dbh->do(q{
16630         INSERT IGNORE INTO `userflags` (`bit`, `flag`, `flagdesc`, `defaulton`)
16631         VALUES (24, 'stockrotation', 'Manage stockrotation operations', 0);
16632     });
16633     $dbh->do(q{
16634         INSERT IGNORE INTO `permissions` (`module_bit`, `code`, `description`)
16635         VALUES (24, 'manage_rotas', 'Create, edit and delete rotas'),
16636                (24, 'manage_rota_items', 'Add and remove items from rotas');
16637     });
16638     # Notices
16639     $dbh->do(q{
16640         INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`)
16641         VALUES ('circulation', 'SR_SLIP', '', 'Stock Rotation Slip', 0, 'Stockrotation Report', 'Stockrotation report for [% branch.name %]:\r\n\r\n[% IF branch.items.size %][% branch.items.size %] items to be processed for this branch.\r\n[% ELSE %]No items to be processed for this branch\r\n[% END %][% FOREACH item IN branch.items %][% IF item.reason ne \'in-demand\' %]Title: [% item.title %]\r\nAuthor: [% item.author %]\r\nCallnumber: [% item.callnumber %]\r\nLocation: [% item.location %]\r\nBarcode: [% item.barcode %]\r\nOn loan?: [% item.onloan %]\r\nStatus: [% item.reason %]\r\nCurrent Library: [% item.branch.branchname %] [% item.branch.branchcode %]\r\n\r\n[% END %][% END %]', 'email');
16642     });
16643     print "Upgrade to $DBversion done (Bug 11897 - Add Stock Rotation Feature)\n";
16644     SetVersion( $DBversion );
16645 }
16646
16647 $DBversion = '18.06.00.041';
16648 if( CheckVersion( $DBversion ) ) {
16649
16650      if( !column_exists( 'illrequests', 'price_paid' ) ) {
16651         $dbh->do(q{
16652             ALTER TABLE illrequests
16653                 ADD COLUMN price_paid varchar(20) DEFAULT NULL
16654                 AFTER cost
16655         });
16656      }
16657
16658      if( !column_exists( 'illrequestattributes', 'readonly' ) ) {
16659         $dbh->do(q{
16660             ALTER TABLE illrequestattributes
16661                 ADD COLUMN readonly tinyint(1) NOT NULL DEFAULT 1
16662                 AFTER value
16663         });
16664         $dbh->do(q{
16665             UPDATE illrequestattributes SET readonly = 1
16666         });
16667      }
16668
16669     SetVersion( $DBversion );
16670     print "Upgrade to $DBversion done (Bug 20772 - Add illrequestattributes.readonly and illrequest.price_paid columns)\n";
16671 }
16672
16673 $DBversion = '18.06.00.042';
16674 if( CheckVersion( $DBversion ) ) {
16675     $dbh->do( "alter table statistics change column ccode ccode varchar(80) default NULL" );
16676
16677     SetVersion( $DBversion );
16678     print "Upgrade to $DBversion done (Bug 21617: Make statistics.ccode longer)\n";
16679 }
16680
16681 $DBversion = "18.06.00.043";
16682 if ( CheckVersion($DBversion) ) {
16683     if ( !column_exists( 'issuingrules', 'holds_per_day' ) ) {
16684         $dbh->do(q{
16685             ALTER TABLE `issuingrules`
16686                 ADD COLUMN `holds_per_day` SMALLINT(6) DEFAULT NULL
16687                 AFTER `holds_per_record`
16688         });
16689     }
16690     print "Upgrade to $DBversion done (Bug 15486: Restrict number of holds placed by day)\n";
16691     SetVersion($DBversion);
16692 }
16693
16694 $DBversion = '18.06.00.044';
16695 if( CheckVersion( $DBversion ) ) {
16696     unless( column_exists( 'creator_batches', 'description' ) ) {
16697         $dbh->do(q|ALTER TABLE creator_batches ADD description mediumtext default NULL AFTER batch_id|);
16698     }
16699     SetVersion( $DBversion );
16700     print "Upgrade to $DBversion done (Bug 15766: Add column creator_batches.description)\n";
16701 }
16702
16703 $DBversion = '18.06.00.045';
16704 if( CheckVersion( $DBversion ) ) {
16705     $dbh->do(q(
16706         INSERT IGNORE INTO message_transports
16707         (message_attribute_id,message_transport_type,is_digest,letter_module,letter_code)
16708         VALUES
16709         (2, 'phone', 0, 'circulation', 'PREDUE'),
16710         (2, 'phone', 1, 'circulation', 'PREDUEDGST'),
16711         (4, 'phone', 0, 'reserves',    'HOLD')
16712         ));
16713     SetVersion( $DBversion );
16714     print "Upgrade to $DBversion done (Bug 21639 - Add phone transports by default)\n";
16715 }
16716
16717 $DBversion = '18.06.00.046';
16718 if( CheckVersion( $DBversion ) ) {
16719     unless (TableExists('illcomments')) {
16720         $dbh->do(q{
16721             CREATE TABLE illcomments (
16722                 illcomment_id int(11) NOT NULL AUTO_INCREMENT, -- Unique ID of the comment
16723                 illrequest_id bigint(20) unsigned NOT NULL,    -- ILL request number
16724                 borrowernumber integer DEFAULT NULL,           -- Link to the user who made the comment (could be librarian, patron or ILL partner library)
16725                 comment text DEFAULT NULL,                     -- The text of the comment
16726                 timestamp timestamp DEFAULT CURRENT_TIMESTAMP, -- Date and time when the comment was made
16727                 PRIMARY KEY  ( illcomment_id ),
16728                 CONSTRAINT illcomments_bnfk
16729                   FOREIGN KEY ( borrowernumber )
16730                   REFERENCES  borrowers  ( borrowernumber )
16731                   ON UPDATE CASCADE ON DELETE CASCADE,
16732                 CONSTRAINT illcomments_ifk
16733                   FOREIGN KEY (illrequest_id)
16734                   REFERENCES illrequests ( illrequest_id )
16735                   ON UPDATE CASCADE ON DELETE CASCADE
16736             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16737         });
16738     }
16739
16740     SetVersion( $DBversion );
16741     print "Upgrade to $DBversion done (Bug 18591 - Add comments to ILL requests)\n";
16742 }
16743
16744 $DBversion = '18.06.00.047';
16745 if( CheckVersion( $DBversion ) ) {
16746     # insert the authorized_value_category for CONTROL_NUM_SEQUENCE
16747     $dbh->do( "INSERT IGNORE INTO authorised_value_categories values ('CONTROL_NUM_SEQUENCE');" );
16748     SetVersion( $DBversion );
16749     print "Upgrade to $DBversion done (Bug 19263 - Advanced Editor - Rancor - Add auto control number (001) widget)\n";
16750 }
16751
16752 $DBversion = '18.06.00.048';
16753 if( CheckVersion( $DBversion ) ) {
16754     $dbh->do( "ALTER TABLE stockrotationrotas CHANGE COLUMN description description text" );
16755     SetVersion( $DBversion );
16756     print "Upgrade to $DBversion done (Bug 21682 - Remove default on stockrotationrotas.description)\n";
16757 }
16758
16759 $DBversion = '18.06.00.049';
16760 if( CheckVersion( $DBversion ) ) {
16761     $dbh->do(q{
16762         UPDATE letter SET content = REPLACE(content,"item.reason ne \'in-demand\'","item.reason != \'in-demand\'")
16763         WHERE code="SR_SLIP";
16764     });
16765     print "Upgrade to $DBversion done (Bug 21656 - Stock Rotation Notice, Template Toolkit Syntax Correction)\n";
16766     SetVersion( $DBversion );
16767 }
16768
16769 $DBversion = '18.06.00.050';
16770 if( CheckVersion( $DBversion ) ) {
16771     $dbh->do(q{
16772         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('OpacHiddenItemsExceptions','',NULL,'List of borrower categories, separated by |, that can see items otherwise hidden by OpacHiddenItems','Textarea');
16773     });
16774     print "Upgrade to $DBversion done (Bug 14385 - Add OpacHiddenItemExceptions)\n";
16775     SetVersion( $DBversion );
16776 }
16777
16778 $DBversion = '18.06.00.051';
16779 if( CheckVersion( $DBversion ) ) {
16780     $dbh->do(q{
16781         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES
16782         ('AdlibrisCoversEnabled', '0', NULL, 'Display cover images in OPAC results and detail listing from Swedish retailer Adlibris.','YesNo'),
16783         ('AdlibrisCoversURL', 'http://www.adlibris.com/se/organisationer/showimagesafe.aspx', NULL, 'Base URL for Adlibris cover image web service.', 'Free');
16784     });
16785     print "Upgrade to $DBversion done (Bug 8630 - Add covers from AdLibris to the OPAC and Intranet)\n";
16786     SetVersion( $DBversion );
16787 }
16788
16789 $DBversion = '18.06.00.052';
16790 if( CheckVersion( $DBversion ) ) {
16791     $dbh->do(q{
16792         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
16793            ( 3, 'manage_sysprefs', 'Manage global system preferences'),
16794            ( 3, 'manage_libraries', 'Manage libraries and library groups'),
16795            ( 3, 'manage_itemtypes', 'Manage item types'),
16796            ( 3, 'manage_auth_values', 'Manage authorized values'),
16797            ( 3, 'manage_patron_categories', 'Manage patron categories'),
16798            ( 3, 'manage_patron_attributes', 'Manage extended patron attributes'),
16799            ( 3, 'manage_transfers', 'Manage library transfer limits and transport cost matrix'),
16800            ( 3, 'manage_item_circ_alerts', 'Manage item circulation alerts'),
16801            ( 3, 'manage_cities', 'Manage cities and towns'),
16802            ( 3, 'manage_marc_frameworks', 'Manage MARC bibliographic and authority frameworks'),
16803            ( 3, 'manage_keywords2koha_mappings', 'Manage keywords to Koha mappings'),
16804            ( 3, 'manage_classifications', 'Manage classification sources'),
16805            ( 3, 'manage_matching_rules', 'Manage record matching rules'),
16806            ( 3, 'manage_oai_sets', 'Manage OAI sets'),
16807            ( 3, 'manage_item_search_fields', 'Manage item search fields'),
16808            ( 3, 'manage_search_engine_config', 'Manage search engine configuration'),
16809            ( 3, 'manage_search_targets', 'Manage Z39.50 and SRU server configuration'),
16810            ( 3, 'manage_didyoumean', 'Manage Did you mean? configuration'),
16811            ( 3, 'manage_column_config', 'Manage column configuration'),
16812            ( 3, 'manage_sms_providers', 'Manage SMS cellular providers'),
16813            ( 3, 'manage_audio_alerts', 'Manage audio alerts'),
16814            ( 3, 'manage_usage_stats', 'Manage usage statistics settings');
16815     });
16816     $dbh->do(q{
16817         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16818             SELECT borrowernumber, 3, 'manage_sysprefs' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16819     });
16820     $dbh->do(q{
16821         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16822             SELECT borrowernumber, 3, 'manage_libraries' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16823     });
16824     $dbh->do(q{
16825         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16826             SELECT borrowernumber, 3, 'manage_itemtypes' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16827     });
16828     $dbh->do(q{
16829         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16830             SELECT borrowernumber, 3, 'manage_auth_values' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16831     });
16832     $dbh->do(q{
16833         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16834             SELECT borrowernumber, 3, 'manage_patron_categories' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16835     });
16836     $dbh->do(q{
16837         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16838             SELECT borrowernumber, 3, 'manage_patron_attributes' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16839     });
16840     $dbh->do(q{
16841         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16842             SELECT borrowernumber, 3, 'manage_transfers' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16843     });
16844     $dbh->do(q{
16845         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16846             SELECT borrowernumber, 3, 'manage_item_circ_alerts' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16847     });
16848     $dbh->do(q{
16849         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16850             SELECT borrowernumber, 3, 'manage_cities' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16851     });
16852     $dbh->do(q{
16853         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16854             SELECT borrowernumber, 3, 'manage_marc_frameworks' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16855     });
16856     $dbh->do(q{
16857         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16858             SELECT borrowernumber, 3, 'manage_keywords2koha_mappings' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16859     });
16860     $dbh->do(q{
16861         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16862             SELECT borrowernumber, 3, 'manage_classifications' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16863     });
16864     $dbh->do(q{
16865         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16866             SELECT borrowernumber, 3, 'manage_matching_rules' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16867     });
16868     $dbh->do(q{
16869         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16870             SELECT borrowernumber, 3, 'manage_oai_sets' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16871     });
16872     $dbh->do(q{
16873         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16874             SELECT borrowernumber, 3, 'manage_item_search_fields' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16875     });
16876     $dbh->do(q{
16877         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16878             SELECT borrowernumber, 3, 'manage_search_engine_config' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16879     });
16880     $dbh->do(q{
16881         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16882             SELECT borrowernumber, 3, 'manage_search_targets' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16883     });
16884     $dbh->do(q{
16885         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16886             SELECT borrowernumber, 3, 'manage_didyoumean' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16887     });
16888     $dbh->do(q{
16889         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16890             SELECT borrowernumber, 3, 'manage_column_config' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16891     });
16892     $dbh->do(q{
16893         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16894             SELECT borrowernumber, 3, 'manage_sms_providers' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16895     });
16896     $dbh->do(q{
16897         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16898             SELECT borrowernumber, 3, 'manage_audio_alerts' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16899     });
16900     $dbh->do(q{
16901         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16902             SELECT borrowernumber, 3, 'manage_usage_stats' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16903     });
16904     $dbh->do(q{
16905         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16906             SELECT borrowernumber, 3, 'manage_item_search_fields' FROM borrowers WHERE flags & (1 << 2);
16907     });
16908     SetVersion( $DBversion );
16909     print "Upgrade to $DBversion done (Bug 14391: Add granular permissions to the administration module)\n";
16910 }
16911
16912 $DBversion = '18.06.00.053';
16913 if( CheckVersion( $DBversion ) ) {
16914     $dbh->do( "INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('ItemsDeniedRenewal','','','This syspref allows to define custom rules for denying renewal of specific items.','Textarea')" );
16915     SetVersion( $DBversion );
16916     print "Upgrade to $DBversion done (Bug 15494 - Block renewals by arbitrary item values)\n";
16917 }
16918
16919 $DBversion = '18.06.00.054';
16920 if( CheckVersion( $DBversion ) ) {
16921     if( !column_exists( 'search_field', 'weight' ) ) {
16922         $dbh->do( "ALTER TABLE `search_field` ADD COLUMN `weight` decimal(5,2) DEFAULT NULL AFTER `type`" );
16923     }
16924     SetVersion( $DBversion );
16925     print "Upgrade to $DBversion done (Bug 18316 - Add column search_field.weight)\n";
16926 }
16927
16928 $DBversion = '18.06.00.055';
16929 if( CheckVersion( $DBversion ) ) {
16930     unless( column_exists( 'issuingrules', 'note' ) ) {
16931         $dbh->do(q|ALTER TABLE `issuingrules` ADD `note` varchar(100) default NULL AFTER `article_requests`|);
16932     }
16933     SetVersion( $DBversion );
16934     print "Upgrade to $DBversion done (Bug 12365: Add column issuingrules.note)\n";
16935 }
16936
16937 $DBversion = '18.06.00.056';
16938 if( CheckVersion( $DBversion ) ) {
16939
16940     # All attributes we're potentially interested in
16941     my $ff_req = $dbh->selectall_arrayref(
16942         'SELECT a.illrequest_id, a.type, a.value '.
16943         'FROM illrequests r, illrequestattributes a '.
16944         'WHERE r.illrequest_id = a.illrequest_id '.
16945         'AND r.backend = "FreeForm"',
16946         { Slice => {} }
16947     );
16948
16949     # Before we go any further, identify whether we've done
16950     # this before, we test for the presence of "container_title"
16951     # We stop as soon as we find one
16952     foreach my $req(@{$ff_req}) {
16953         if ($req->{type} eq 'container_title') {
16954             warn "Upgrade already carried out";
16955         }
16956     }
16957
16958     # Transform into a hashref with the key of the request ID
16959     my $requests = {};
16960     foreach my $request(@{$ff_req}) {
16961         my $id = $request->{illrequest_id};
16962         if (!exists $requests->{$id}) {
16963             $requests->{$id} = {};
16964         }
16965         $requests->{$id}->{$request->{type}} = $request->{value};
16966     }
16967
16968     # Transform any article requests
16969     my $transformed = {};
16970     foreach my $id(keys %{$requests}) {
16971         if (lc($requests->{$id}->{type}) eq 'article') {
16972             $transformed->{$id} = $requests->{$id};
16973             $transformed->{$id}->{type} = 'article';
16974             $transformed->{$id}->{container_title} = $transformed->{$id}->{title}
16975                 if defined $transformed->{$id}->{title} &&
16976                     length $transformed->{$id}->{title} > 0;
16977             $transformed->{$id}->{title} = $transformed->{$id}->{article_title}
16978                 if defined $transformed->{$id}->{article_title} &&
16979                     length $transformed->{$id}->{article_title} > 0;
16980             $transformed->{$id}->{author} = $transformed->{$id}->{article_author}
16981                 if defined $transformed->{$id}->{article_author} &&
16982                     length $transformed->{$id}->{article_author} > 0;
16983             $transformed->{$id}->{pages} = $transformed->{$id}->{article_pages}
16984                 if defined $transformed->{$id}->{article_pages} &&
16985                     length $transformed->{$id}->{article_pages} > 0;
16986         }
16987     }
16988
16989     # Now write back the transformed data
16990     # Rather than selectively replace, we just remove all attributes we've
16991     # transformed and re-write them
16992     my @changed = keys %{$transformed};
16993     my $changed_str = join(',', @changed);
16994
16995     if (scalar @changed > 0) {
16996         my ($raise_error) = $dbh->{RaiseError};
16997         $dbh->{AutoCommit} = 0;
16998         $dbh->{RaiseError} = 1;
16999         eval {
17000             my $del = $dbh->do(
17001                 "DELETE FROM illrequestattributes ".
17002                 "WHERE illrequest_id IN ($changed_str)"
17003             );
17004             foreach my $reqid(keys %{$transformed}) {
17005                 my $attr = $transformed->{$reqid};
17006                 foreach my $key(keys %{$attr}) {
17007                     my $sth = $dbh->prepare(
17008                         'INSERT INTO illrequestattributes '.
17009                         '(illrequest_id, type, value) '.
17010                         'VALUES '.
17011                         '(?, ?, ?)'
17012                     );
17013                     $sth->execute(
17014                         $reqid,
17015                         $key,
17016                         $attr->{$key}
17017                     );
17018                 }
17019             }
17020             $dbh->commit;
17021         };
17022
17023         if ($@) {
17024             warn "Upgrade to $DBversion failed: $@\n";
17025             eval { $dbh->rollback };
17026         } else {
17027             SetVersion( $DBversion );
17028             print "Upgrade to $DBversion done (Bug 21079 - Unify metadata schema across backends)\n";
17029         }
17030
17031         $dbh->{AutoCommit} = 1;
17032         $dbh->{RaiseError} = $raise_error;
17033     }
17034
17035 }
17036
17037 $DBversion = '18.06.00.057';
17038 if( CheckVersion( $DBversion ) ) {
17039     # System preferences
17040     $dbh->do(q{
17041         INSERT IGNORE INTO `systempreferences` (`variable`,`value`,`explanation`,`options`,`type`)
17042         VALUES ('showLastPatron','0','','If ON, enables the last patron feature in the intranet','YesNo');
17043     });
17044     SetVersion( $DBversion );
17045     print "Upgrade to $DBversion done (Bug 20312 - Add showLastPatron systempreference)\n";
17046 }
17047
17048 $DBversion = '18.06.00.058';
17049 if( CheckVersion( $DBversion ) ) {
17050     $dbh->do(q{
17051         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES
17052         ('MarcFieldForCreatorId','',NULL,'Where to store the borrowernumber of the record''s creator','Free'),
17053         ('MarcFieldForCreatorName','',NULL,'Where to store the name of the record''s creator','Free'),
17054         ('MarcFieldForModifierId','',NULL,'Where to store the borrowernumber of the record''s last modifier','Free'),
17055         ('MarcFieldForModifierName','',NULL,'Where to store the name of the record''s last modifier','Free')
17056     });
17057
17058     SetVersion( $DBversion );
17059     print "Upgrade to $DBversion done (Bug 19349 - Add system preferences MarcFieldForCreatorId, MarcFieldForCreatorName, MarcFieldForModifierId, MarcFieldForModifierName)\n";
17060 }
17061
17062 $DBversion = '18.06.00.059';
17063 if( CheckVersion( $DBversion ) ) {
17064     $dbh->do(q{
17065         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type`) VALUES  ('EmailSMSSendDriverFromAddress', '', '', 'Email SMS send driver from address override', 'Free');
17066     });
17067     SetVersion( $DBversion );
17068     print "Upgrade to $DBversion done (Bug 20356 - Add EmailSMSSendDriverFromAddress system preference)\n";
17069 }
17070
17071 $DBversion = '18.06.00.060';
17072 if( CheckVersion( $DBversion ) ) {
17073     unless( TableExists( 'class_split_rules' ) ) {
17074         $dbh->do(q|
17075             CREATE TABLE class_split_rules (
17076               class_split_rule varchar(10) NOT NULL default '',
17077               description LONGTEXT,
17078               split_routine varchar(30) NOT NULL default '',
17079               split_regex varchar(255) NOT NULL default '',
17080               PRIMARY KEY (class_split_rule),
17081               UNIQUE KEY class_split_rule_idx (class_split_rule)
17082             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
17083         |);
17084
17085         $dbh->do(q|
17086             ALTER TABLE class_sources
17087             ADD COLUMN class_split_rule varchar(10) NOT NULL default ''
17088             AFTER class_sort_rule
17089         |);
17090         $dbh->do(q|
17091             UPDATE class_sources
17092             SET class_split_rule = class_sort_rule
17093         |);
17094
17095         $dbh->do(q|
17096             INSERT INTO class_split_rules(class_split_rule, description, split_routine)
17097             VALUES
17098             ('dewey', 'Default sorting rules for DDC', 'Dewey'),
17099             ('lcc', 'Default sorting rules for LCC', 'LCC'),
17100             ('generic', 'Generic call number sorting rules', 'Generic')
17101         |);
17102
17103         $dbh->do(q|
17104             ALTER TABLE class_sources
17105             ADD CONSTRAINT class_source_ibfk_2 FOREIGN KEY (class_split_rule)
17106             REFERENCES class_split_rules (class_split_rule)
17107         |);
17108     }
17109
17110     SetVersion( $DBversion );
17111     print "Upgrade to $DBversion done (Bug 15836 - Add class_sort_rules.split_routine and split_regex)\n";
17112 }
17113
17114 $DBversion = '18.06.00.061';
17115 if ( CheckVersion($DBversion) ) {
17116     $dbh->do(q{
17117         INSERT IGNORE INTO `systempreferences` (`variable`,`value`,`explanation`,`options`,`type`) VALUES
17118         ('ElasticsearchIndexStatus_biblios', '0', 'Biblios index status', NULL, NULL),
17119         ('ElasticsearchIndexStatus_authorities', '0', 'Authorities index status', NULL, NULL)
17120     });
17121     SetVersion($DBversion);
17122     print "Upgrade to $DBversion done (Bug 19893 - Add elasticsearch index status preferences)\n";
17123 }
17124
17125 $DBversion = '18.06.00.062';
17126 if( CheckVersion( $DBversion ) ) {
17127     $dbh->do( "INSERT IGNORE INTO authorised_value_categories (category_name) VALUES ('PA_CLASS');");
17128     SetVersion( $DBversion );
17129     print "Upgrade to $DBversion done (Bug 21730: Add new authorised value category PA_CLASS)\n";
17130 }
17131
17132 $DBversion = '18.11.00.000';
17133 if( CheckVersion( $DBversion ) ) {
17134     SetVersion( $DBversion );
17135     print "Upgrade to $DBversion done (18.11.00 release)\n";
17136 }
17137
17138 $DBversion = '18.12.00.000';
17139 if( CheckVersion( $DBversion ) ) {
17140     SetVersion( $DBversion );
17141     print "Upgrade to $DBversion done (...and Steven!)\n";
17142 }
17143
17144 $DBversion = '18.12.00.001';
17145 if( CheckVersion( $DBversion ) ) {
17146     $dbh->do(q{
17147         UPDATE permissions SET code = 'manage_didyoumean' WHERE code = 'manage_didyouean';
17148     });
17149     $dbh->do(q{
17150         UPDATE user_permissions SET code = 'manage_didyoumean' WHERE code = 'manage_didyouean';
17151     });
17152     SetVersion( $DBversion );
17153     print "Upgrade to $DBversion (Bug 21961 - Fix typo in manage_didyoumean permission)\n";
17154 }
17155
17156 # SEE bug 13068
17157 # if there is anything in the atomicupdate, read and execute it.
17158
17159 my $update_dir = C4::Context->config('intranetdir') . '/installer/data/mysql/atomicupdate/';
17160 opendir( my $dirh, $update_dir );
17161 foreach my $file ( sort readdir $dirh ) {
17162     next if $file !~ /\.(sql|perl)$/;  #skip other files
17163     next if $file eq 'skeleton.perl'; # skip the skeleton file
17164     print "DEV atomic update: $file\n";
17165     if ( $file =~ /\.sql$/ ) {
17166         my $installer = C4::Installer->new();
17167         my $rv = $installer->load_sql( $update_dir . $file ) ? 0 : 1;
17168     } elsif ( $file =~ /\.perl$/ ) {
17169         my $code = read_file( $update_dir . $file );
17170         eval $code;
17171         say "Atomic update generated errors: $@" if $@;
17172     }
17173 }
17174
17175 =head1 FUNCTIONS
17176
17177 =head2 TableExists($table)
17178
17179 =cut
17180
17181 sub TableExists {
17182     my $table = shift;
17183     eval {
17184                 local $dbh->{PrintError} = 0;
17185                 local $dbh->{RaiseError} = 1;
17186                 $dbh->do(qq{SELECT * FROM $table WHERE 1 = 0 });
17187             };
17188     return 1 unless $@;
17189     return 0;
17190 }
17191
17192 =head2 DropAllForeignKeys($table)
17193
17194 Drop all foreign keys of the table $table
17195
17196 =cut
17197
17198 sub DropAllForeignKeys {
17199     my ($table) = @_;
17200     # get the table description
17201     my $sth = $dbh->prepare("SHOW CREATE TABLE $table");
17202     $sth->execute;
17203     my $vsc_structure = $sth->fetchrow;
17204     # split on CONSTRAINT keyword
17205     my @fks = split /CONSTRAINT /,$vsc_structure;
17206     # parse each entry
17207     foreach (@fks) {
17208         # isolate what is before FOREIGN KEY, if there is something, it's a foreign key to drop
17209         $_ = /(.*) FOREIGN KEY.*/;
17210         my $id = $1;
17211         if ($id) {
17212             # we have found 1 foreign, drop it
17213             $dbh->do("ALTER TABLE $table DROP FOREIGN KEY $id");
17214             $id="";
17215         }
17216     }
17217 }
17218
17219
17220 =head2 TransformToNum
17221
17222 Transform the Koha version from a 4 parts string
17223 to a number, with just 1 .
17224
17225 =cut
17226
17227 sub TransformToNum {
17228     my $version = shift;
17229     # remove the 3 last . to have a Perl number
17230     $version =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
17231     # three X's at the end indicate that you are testing patch with dbrev
17232     # change it into 999
17233     # prevents error on a < comparison between strings (should be: lt)
17234     $version =~ s/XXX$/999/;
17235     return $version;
17236 }
17237
17238 =head2 SetVersion
17239
17240 set the DBversion in the systempreferences
17241
17242 =cut
17243
17244 sub SetVersion {
17245     return if $_[0]=~ /XXX$/;
17246       #you are testing a patch with a db revision; do not change version
17247     my $kohaversion = TransformToNum($_[0]);
17248     if (C4::Context->preference('Version')) {
17249       my $finish=$dbh->prepare("UPDATE systempreferences SET value=? WHERE variable='Version'");
17250       $finish->execute($kohaversion);
17251     } else {
17252       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')");
17253       $finish->execute($kohaversion);
17254     }
17255     C4::Context::clear_syspref_cache(); # invalidate cached preferences
17256 }
17257
17258 =head2 CheckVersion
17259
17260 Check whether a given update should be run when passed the proposed version
17261 number. The update will always be run if the proposed version is greater
17262 than the current database version and less than or equal to the version in
17263 kohaversion.pl. The update is also run if the version contains XXX, though
17264 this behavior will be changed following the adoption of non-linear updates
17265 as implemented in bug 7167.
17266
17267 =cut
17268
17269 sub CheckVersion {
17270     my ($proposed_version) = @_;
17271     my $version_number = TransformToNum($proposed_version);
17272
17273     # The following line should be deleted when bug 7167 is pushed
17274     return 1 if ( $proposed_version =~ m/XXX/ );
17275
17276     if ( C4::Context->preference("Version") < $version_number
17277         && $version_number <= TransformToNum( $Koha::VERSION ) )
17278     {
17279         return 1;
17280     }
17281     else {
17282         return 0;
17283     }
17284 }
17285
17286 exit;