Bug 8236: DBRev 3.21.00.037
[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 # CPAN modules
34 use DBI;
35 use Getopt::Long;
36 # Koha modules
37 use C4::Context;
38 use C4::Installer;
39 use C4::Dates;
40 use Koha::Database;
41 use Koha;
42
43 use MARC::Record;
44 use MARC::File::XML ( BinaryEncoding => 'utf8' );
45
46 # FIXME - The user might be installing a new database, so can't rely
47 # on /etc/koha.conf anyway.
48
49 my $debug = 0;
50
51 my (
52     $sth, $sti,
53     $query,
54     %existingtables,    # tables already in database
55     %types,
56     $table,
57     $column,
58     $type, $null, $key, $default, $extra,
59     $prefitem,          # preference item in systempreferences table
60 );
61
62 my $schema = Koha::Database->new()->schema();
63
64 my $silent;
65 GetOptions(
66     's' =>\$silent
67     );
68 my $dbh = C4::Context->dbh;
69 $|=1; # flushes output
70
71 local $dbh->{RaiseError} = 0;
72
73 # Record the version we are coming from
74
75 my $original_version = C4::Context->preference("Version");
76
77 # Deal with virtualshelves
78 my $DBversion = "3.00.00.001";
79 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
80     # update virtualshelves table to
81     #
82     $dbh->do("ALTER TABLE `bookshelf` RENAME `virtualshelves`");
83     $dbh->do("ALTER TABLE `shelfcontents` RENAME `virtualshelfcontents`");
84     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD `biblionumber` INT( 11 ) NOT NULL default '0' AFTER shelfnumber");
85     $dbh->do("UPDATE `virtualshelfcontents` SET biblionumber=(SELECT biblionumber FROM items WHERE items.itemnumber=virtualshelfcontents.itemnumber)");
86     # drop all foreign keys : otherwise, we can't drop itemnumber field.
87     DropAllForeignKeys('virtualshelfcontents');
88     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD KEY biblionumber (biblionumber)");
89     # create the new foreign keys (on biblionumber)
90     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD CONSTRAINT `virtualshelfcontents_ibfk_1` FOREIGN KEY (`shelfnumber`) REFERENCES `virtualshelves` (`shelfnumber`) ON DELETE CASCADE ON UPDATE CASCADE");
91     # re-create the foreign key on virtualshelf
92     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD CONSTRAINT `shelfcontents_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE");
93     $dbh->do("ALTER TABLE `virtualshelfcontents` DROP `itemnumber`");
94     print "Upgrade to $DBversion done (virtualshelves)\n";
95     SetVersion ($DBversion);
96 }
97
98
99 $DBversion = "3.00.00.002";
100 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
101     $dbh->do("DROP TABLE sessions");
102     $dbh->do("CREATE TABLE `sessions` (
103   `id` varchar(32) NOT NULL,
104   `a_session` text NOT NULL,
105   UNIQUE KEY `id` (`id`)
106 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
107     print "Upgrade to $DBversion done (sessions uses CGI::session, new table structure for sessions)\n";
108     SetVersion ($DBversion);
109 }
110
111
112 $DBversion = "3.00.00.003";
113 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
114     if (C4::Context->preference("opaclanguages") eq "fr") {
115         $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('ReservesNeedReturns','0','Si ce paramètre est mis à 1, une réservation posée sur un exemplaire présent sur le site devra être passée en retour pour être disponible. Sinon, elle sera automatiquement disponible, Koha considère que le bibliothécaire place la réservation en ayant le document en mains','','YesNo')");
116     } else {
117         $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('ReservesNeedReturns','0','If set, a reserve done on an item available in this branch need a check-in, otherwise, a reserve on a specific item, that is on the branch & available is considered as available','','YesNo')");
118     }
119     print "Upgrade to $DBversion done (adding ReservesNeedReturns systempref, in circulation)\n";
120     SetVersion ($DBversion);
121 }
122
123
124 $DBversion = "3.00.00.004";
125 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
126     $dbh->do("INSERT INTO `systempreferences` VALUES ('DebugLevel','2','set the level of error info sent to the browser. 0=none, 1=some, 2=most','0|1|2','Choice')");
127     print "Upgrade to $DBversion done (adding DebugLevel systempref, in 'Admin' tab)\n";
128     SetVersion ($DBversion);
129 }
130
131 $DBversion = "3.00.00.005";
132 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
133     $dbh->do("CREATE TABLE `tags` (
134                     `entry` varchar(255) NOT NULL default '',
135                     `weight` bigint(20) NOT NULL default 0,
136                     PRIMARY KEY  (`entry`)
137                     ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
138                 ");
139         $dbh->do("CREATE TABLE `nozebra` (
140                 `server` varchar(20)     NOT NULL,
141                 `indexname` varchar(40)  NOT NULL,
142                 `value` varchar(250)     NOT NULL,
143                 `biblionumbers` longtext NOT NULL,
144                 KEY `indexname` (`server`,`indexname`),
145                 KEY `value` (`server`,`value`))
146                 ENGINE=InnoDB DEFAULT CHARSET=utf8;
147                 ");
148     print "Upgrade to $DBversion done (adding tags and nozebra tables )\n";
149     SetVersion ($DBversion);
150 }
151
152 $DBversion = "3.00.00.006";
153 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
154     $dbh->do("UPDATE issues SET issuedate=timestamp WHERE issuedate='0000-00-00'");
155     print "Upgrade to $DBversion done (filled issues.issuedate with timestamp)\n";
156     SetVersion ($DBversion);
157 }
158
159 $DBversion = "3.00.00.007";
160 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
161     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SessionStorage','mysql','Use mysql or a temporary file for storing session data','mysql|tmp','Choice')");
162     print "Upgrade to $DBversion done (set SessionStorage variable)\n";
163     SetVersion ($DBversion);
164 }
165
166 $DBversion = "3.00.00.008";
167 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
168     $dbh->do("ALTER TABLE `biblio` ADD `datecreated` DATE NOT NULL AFTER `timestamp` ;");
169     $dbh->do("UPDATE biblio SET datecreated=timestamp");
170     print "Upgrade to $DBversion done (biblio creation date)\n";
171     SetVersion ($DBversion);
172 }
173
174 $DBversion = "3.00.00.009";
175 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
176
177     # Create backups of call number columns
178     # in case default migration needs to be customized
179     #
180     # UPGRADE NOTE: temp_upg_biblioitems_call_num should be dropped
181     #               after call numbers have been transformed to the new structure
182     #
183     # Not bothering to do the same with deletedbiblioitems -- assume
184     # default is good enough.
185     $dbh->do("CREATE TABLE `temp_upg_biblioitems_call_num` AS
186               SELECT `biblioitemnumber`, `biblionumber`,
187                      `classification`, `dewey`, `subclass`,
188                      `lcsort`, `ccode`
189               FROM `biblioitems`");
190
191     # biblioitems changes
192     $dbh->do("ALTER TABLE `biblioitems` CHANGE COLUMN `volumeddesc` `volumedesc` TEXT,
193                                     ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
194                                     ADD `cn_class` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
195                                     ADD `cn_item` VARCHAR(10) DEFAULT NULL AFTER `cn_class`,
196                                     ADD `cn_suffix` VARCHAR(10) DEFAULT NULL AFTER `cn_item`,
197                                     ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_suffix`,
198                                     ADD `totalissues` INT(10) AFTER `cn_sort`");
199
200     # default mapping of call number columns:
201     #   cn_class = concatentation of classification + dewey,
202     #              trimmed to fit -- assumes that most users do not
203     #              populate both classification and dewey in a single record
204     #   cn_item  = subclass
205     #   cn_source = left null
206     #   cn_sort = lcsort
207     #
208     # After upgrade, cn_sort will have to be set based on whatever
209     # default call number scheme user sets as a preference.  Misc
210     # script will be added at some point to do that.
211     #
212     $dbh->do("UPDATE `biblioitems`
213               SET cn_class = SUBSTR(TRIM(CONCAT_WS(' ', `classification`, `dewey`)), 1, 30),
214                     cn_item = subclass,
215                     `cn_sort` = `lcsort`
216             ");
217
218     # Now drop the old call number columns
219     $dbh->do("ALTER TABLE `biblioitems` DROP COLUMN `classification`,
220                                         DROP COLUMN `dewey`,
221                                         DROP COLUMN `subclass`,
222                                         DROP COLUMN `lcsort`,
223                                         DROP COLUMN `ccode`");
224
225     # deletedbiblio changes
226     $dbh->do("ALTER TABLE `deletedbiblio` ALTER COLUMN `frameworkcode` SET DEFAULT '',
227                                         DROP COLUMN `marc`,
228                                         ADD `datecreated` DATE NOT NULL AFTER `timestamp`");
229     $dbh->do("UPDATE deletedbiblio SET datecreated = timestamp");
230
231     # deletedbiblioitems changes
232     $dbh->do("ALTER TABLE `deletedbiblioitems`
233                         MODIFY `publicationyear` TEXT,
234                         CHANGE `volumeddesc` `volumedesc` TEXT,
235                         MODIFY `collectiontitle` MEDIUMTEXT DEFAULT NULL AFTER `volumedesc`,
236                         MODIFY `collectionissn` TEXT DEFAULT NULL AFTER `collectiontitle`,
237                         MODIFY `collectionvolume` MEDIUMTEXT DEFAULT NULL AFTER `collectionissn`,
238                         MODIFY `editionstatement` TEXT DEFAULT NULL AFTER `collectionvolume`,
239                         MODIFY `editionresponsibility` TEXT DEFAULT NULL AFTER `editionstatement`,
240                         MODIFY `place` VARCHAR(255) DEFAULT NULL AFTER `size`,
241                         MODIFY `marc` LONGBLOB,
242                         ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `url`,
243                         ADD `cn_class` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
244                         ADD `cn_item` VARCHAR(10) DEFAULT NULL AFTER `cn_class`,
245                         ADD `cn_suffix` VARCHAR(10) DEFAULT NULL AFTER `cn_item`,
246                         ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_suffix`,
247                         ADD `totalissues` INT(10) AFTER `cn_sort`,
248                         ADD `marcxml` LONGTEXT NOT NULL AFTER `totalissues`,
249                         ADD KEY `isbn` (`isbn`),
250                         ADD KEY `publishercode` (`publishercode`)
251                     ");
252
253     $dbh->do("UPDATE `deletedbiblioitems`
254                 SET `cn_class` = SUBSTR(TRIM(CONCAT_WS(' ', `classification`, `dewey`)), 1, 30),
255                `cn_item` = `subclass`,
256                 `cn_sort` = `lcsort`
257             ");
258     $dbh->do("ALTER TABLE `deletedbiblioitems`
259                         DROP COLUMN `classification`,
260                         DROP COLUMN `dewey`,
261                         DROP COLUMN `subclass`,
262                         DROP COLUMN `lcsort`,
263                         DROP COLUMN `ccode`
264             ");
265
266     # deleteditems changes
267     $dbh->do("ALTER TABLE `deleteditems`
268                         MODIFY `barcode` VARCHAR(20) DEFAULT NULL,
269                         MODIFY `price` DECIMAL(8,2) DEFAULT NULL,
270                         MODIFY `replacementprice` DECIMAL(8,2) DEFAULT NULL,
271                         DROP `bulk`,
272                         MODIFY `itemcallnumber` VARCHAR(30) DEFAULT NULL AFTER `wthdrawn`,
273                         MODIFY `holdingbranch` VARCHAR(10) DEFAULT NULL,
274                         DROP `interim`,
275                         MODIFY `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP AFTER `paidfor`,
276                         DROP `cutterextra`,
277                         ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `onloan`,
278                         ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
279                         ADD `ccode` VARCHAR(10) DEFAULT NULL AFTER `cn_sort`,
280                         ADD `materials` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
281                         ADD `uri` VARCHAR(255) DEFAULT NULL AFTER `materials`,
282                         MODIFY `marc` LONGBLOB AFTER `uri`,
283                         DROP KEY `barcode`,
284                         DROP KEY `itembarcodeidx`,
285                         DROP KEY `itembinoidx`,
286                         DROP KEY `itembibnoidx`,
287                         ADD UNIQUE KEY `delitembarcodeidx` (`barcode`),
288                         ADD KEY `delitembinoidx` (`biblioitemnumber`),
289                         ADD KEY `delitembibnoidx` (`biblionumber`),
290                         ADD KEY `delhomebranch` (`homebranch`),
291                         ADD KEY `delholdingbranch` (`holdingbranch`)");
292     $dbh->do("UPDATE deleteditems SET `ccode` = `itype`");
293     $dbh->do("ALTER TABLE deleteditems DROP `itype`");
294     $dbh->do("UPDATE `deleteditems` SET `cn_sort` = `itemcallnumber`");
295
296     # items changes
297     $dbh->do("ALTER TABLE `items` ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `onloan`,
298                                 ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
299                                 ADD `ccode` VARCHAR(10) DEFAULT NULL AFTER `cn_sort`,
300                                 ADD `materials` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
301                                 ADD `uri` VARCHAR(255) DEFAULT NULL AFTER `materials`
302             ");
303     $dbh->do("ALTER TABLE `items`
304                         DROP KEY `itembarcodeidx`,
305                         ADD UNIQUE KEY `itembarcodeidx` (`barcode`)");
306
307     # map items.itype to items.ccode and
308     # set cn_sort to itemcallnumber -- as with biblioitems.cn_sort,
309     # will have to be subsequently updated per user's default
310     # classification scheme
311     $dbh->do("UPDATE `items` SET `cn_sort` = `itemcallnumber`,
312                             `ccode` = `itype`");
313
314     $dbh->do("ALTER TABLE `items` DROP `cutterextra`,
315                                 DROP `itype`");
316
317     print "Upgrade to $DBversion done (major changes to biblio, biblioitems, items, and deleted* versions of same\n";
318     SetVersion ($DBversion);
319 }
320
321 $DBversion = "3.00.00.010";
322 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
323     $dbh->do("CREATE INDEX `userid` ON borrowers (`userid`) ");
324     print "Upgrade to $DBversion done (userid index added)\n";
325     SetVersion ($DBversion);
326 }
327
328 $DBversion = "3.00.00.011";
329 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
330     $dbh->do("ALTER TABLE `branchcategories` CHANGE `categorycode` `categorycode` varchar(10) ");
331     $dbh->do("ALTER TABLE `branchcategories` CHANGE `categoryname` `categoryname` varchar(32) ");
332     $dbh->do("ALTER TABLE `branchcategories` ADD COLUMN `categorytype` varchar(16) ");
333     $dbh->do("UPDATE `branchcategories` SET `categorytype` = 'properties'");
334     $dbh->do("ALTER TABLE `branchrelations` CHANGE `categorycode` `categorycode` varchar(10) ");
335     print "Upgrade to $DBversion done (added branchcategory type)\n";
336     SetVersion ($DBversion);
337 }
338
339 $DBversion = "3.00.00.012";
340 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
341     $dbh->do("CREATE TABLE `class_sort_rules` (
342                                `class_sort_rule` varchar(10) NOT NULL default '',
343                                `description` mediumtext,
344                                `sort_routine` varchar(30) NOT NULL default '',
345                                PRIMARY KEY (`class_sort_rule`),
346                                UNIQUE KEY `class_sort_rule_idx` (`class_sort_rule`)
347                              ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
348     $dbh->do("CREATE TABLE `class_sources` (
349                                `cn_source` varchar(10) NOT NULL default '',
350                                `description` mediumtext,
351                                `used` tinyint(4) NOT NULL default 0,
352                                `class_sort_rule` varchar(10) NOT NULL default '',
353                                PRIMARY KEY (`cn_source`),
354                                UNIQUE KEY `cn_source_idx` (`cn_source`),
355                                KEY `used_idx` (`used`),
356                                CONSTRAINT `class_source_ibfk_1` FOREIGN KEY (`class_sort_rule`)
357                                           REFERENCES `class_sort_rules` (`class_sort_rule`)
358                              ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
359     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type)
360               VALUES('DefaultClassificationSource','ddc',
361                      'Default classification scheme used by the collection. E.g., Dewey, LCC, etc.', NULL,'free')");
362     $dbh->do("INSERT INTO `class_sort_rules` (`class_sort_rule`, `description`, `sort_routine`) VALUES
363                                ('dewey', 'Default filing rules for DDC', 'Dewey'),
364                                ('lcc', 'Default filing rules for LCC', 'LCC'),
365                                ('generic', 'Generic call number filing rules', 'Generic')");
366     $dbh->do("INSERT INTO `class_sources` (`cn_source`, `description`, `used`, `class_sort_rule`) VALUES
367                             ('ddc', 'Dewey Decimal Classification', 1, 'dewey'),
368                             ('lcc', 'Library of Congress Classification', 1, 'lcc'),
369                             ('udc', 'Universal Decimal Classification', 0, 'generic'),
370                             ('sudocs', 'SuDoc Classification (U.S. GPO)', 0, 'generic'),
371                             ('z', 'Other/Generic Classification Scheme', 0, 'generic')");
372     print "Upgrade to $DBversion done (classification sources added)\n";
373     SetVersion ($DBversion);
374 }
375
376 $DBversion = "3.00.00.013";
377 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
378     $dbh->do("CREATE TABLE `import_batches` (
379               `import_batch_id` int(11) NOT NULL auto_increment,
380               `template_id` int(11) default NULL,
381               `branchcode` varchar(10) default NULL,
382               `num_biblios` int(11) NOT NULL default 0,
383               `num_items` int(11) NOT NULL default 0,
384               `upload_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
385               `overlay_action` enum('replace', 'create_new', 'use_template') NOT NULL default 'create_new',
386               `import_status` enum('staging', 'staged', 'importing', 'imported', 'reverting', 'reverted', 'cleaned') NOT NULL default 'staging',
387               `batch_type` enum('batch', 'z3950') NOT NULL default 'batch',
388               `file_name` varchar(100),
389               `comments` mediumtext,
390               PRIMARY KEY (`import_batch_id`),
391               KEY `branchcode` (`branchcode`)
392               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
393     $dbh->do("CREATE TABLE `import_records` (
394               `import_record_id` int(11) NOT NULL auto_increment,
395               `import_batch_id` int(11) NOT NULL,
396               `branchcode` varchar(10) default NULL,
397               `record_sequence` int(11) NOT NULL default 0,
398               `upload_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
399               `import_date` DATE default NULL,
400               `marc` longblob NOT NULL,
401               `marcxml` longtext NOT NULL,
402               `marcxml_old` longtext NOT NULL,
403               `record_type` enum('biblio', 'auth', 'holdings') NOT NULL default 'biblio',
404               `overlay_status` enum('no_match', 'auto_match', 'manual_match', 'match_applied') NOT NULL default 'no_match',
405               `status` enum('error', 'staged', 'imported', 'reverted', 'items_reverted') NOT NULL default 'staged',
406               `import_error` mediumtext,
407               `encoding` varchar(40) NOT NULL default '',
408               `z3950random` varchar(40) default NULL,
409               PRIMARY KEY (`import_record_id`),
410               CONSTRAINT `import_records_ifbk_1` FOREIGN KEY (`import_batch_id`)
411                           REFERENCES `import_batches` (`import_batch_id`) ON DELETE CASCADE ON UPDATE CASCADE,
412               KEY `branchcode` (`branchcode`),
413               KEY `batch_sequence` (`import_batch_id`, `record_sequence`)
414               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
415     $dbh->do("CREATE TABLE `import_record_matches` (
416               `import_record_id` int(11) NOT NULL,
417               `candidate_match_id` int(11) NOT NULL,
418               `score` int(11) NOT NULL default 0,
419               CONSTRAINT `import_record_matches_ibfk_1` FOREIGN KEY (`import_record_id`)
420                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
421               KEY `record_score` (`import_record_id`, `score`)
422               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
423     $dbh->do("CREATE TABLE `import_biblios` (
424               `import_record_id` int(11) NOT NULL,
425               `matched_biblionumber` int(11) default NULL,
426               `control_number` varchar(25) default NULL,
427               `original_source` varchar(25) default NULL,
428               `title` varchar(128) default NULL,
429               `author` varchar(80) default NULL,
430               `isbn` varchar(14) default NULL,
431               `issn` varchar(9) default NULL,
432               `has_items` tinyint(1) NOT NULL default 0,
433               CONSTRAINT `import_biblios_ibfk_1` FOREIGN KEY (`import_record_id`)
434                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
435               KEY `matched_biblionumber` (`matched_biblionumber`),
436               KEY `title` (`title`),
437               KEY `isbn` (`isbn`)
438               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
439     $dbh->do("CREATE TABLE `import_items` (
440               `import_items_id` int(11) NOT NULL auto_increment,
441               `import_record_id` int(11) NOT NULL,
442               `itemnumber` int(11) default NULL,
443               `branchcode` varchar(10) default NULL,
444               `status` enum('error', 'staged', 'imported', 'reverted') NOT NULL default 'staged',
445               `marcxml` longtext NOT NULL,
446               `import_error` mediumtext,
447               PRIMARY KEY (`import_items_id`),
448               CONSTRAINT `import_items_ibfk_1` FOREIGN KEY (`import_record_id`)
449                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
450               KEY `itemnumber` (`itemnumber`),
451               KEY `branchcode` (`branchcode`)
452               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
453
454     $dbh->do("INSERT INTO `import_batches`
455                 (`overlay_action`, `import_status`, `batch_type`, `file_name`)
456               SELECT distinct 'create_new', 'staged', 'z3950', `file`
457               FROM   `marc_breeding`");
458
459     $dbh->do("INSERT INTO `import_records`
460                 (`import_batch_id`, `import_record_id`, `record_sequence`, `marc`, `record_type`, `status`,
461                 `encoding`, `z3950random`, `marcxml`, `marcxml_old`)
462               SELECT `import_batch_id`, `id`, 1, `marc`, 'biblio', 'staged', `encoding`, `z3950random`, '', ''
463               FROM `marc_breeding`
464               JOIN `import_batches` ON (`file_name` = `file`)");
465
466     $dbh->do("INSERT INTO `import_biblios`
467                 (`import_record_id`, `title`, `author`, `isbn`)
468               SELECT `import_record_id`, `title`, `author`, `isbn`
469               FROM   `marc_breeding`
470               JOIN   `import_records` ON (`import_record_id` = `id`)");
471
472     $dbh->do("UPDATE `import_batches`
473               SET `num_biblios` = (
474               SELECT COUNT(*)
475               FROM `import_records`
476               WHERE `import_batch_id` = `import_batches`.`import_batch_id`
477               )");
478
479     $dbh->do("DROP TABLE `marc_breeding`");
480
481     print "Upgrade to $DBversion done (import_batches et al. added)\n";
482     SetVersion ($DBversion);
483 }
484
485 $DBversion = "3.00.00.014";
486 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
487     $dbh->do("ALTER TABLE subscription ADD lastbranch VARCHAR(4)");
488     print "Upgrade to $DBversion done (userid index added)\n";
489     SetVersion ($DBversion);
490 }
491
492 $DBversion = "3.00.00.015";
493 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
494     $dbh->do("CREATE TABLE `saved_sql` (
495            `id` int(11) NOT NULL auto_increment,
496            `borrowernumber` int(11) default NULL,
497            `date_created` datetime default NULL,
498            `last_modified` datetime default NULL,
499            `savedsql` text,
500            `last_run` datetime default NULL,
501            `report_name` varchar(255) default NULL,
502            `type` varchar(255) default NULL,
503            `notes` text,
504            PRIMARY KEY  (`id`),
505            KEY boridx (`borrowernumber`)
506         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
507     $dbh->do("CREATE TABLE `saved_reports` (
508            `id` int(11) NOT NULL auto_increment,
509            `report_id` int(11) default NULL,
510            `report` longtext,
511            `date_run` datetime default NULL,
512            PRIMARY KEY  (`id`)
513         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
514     print "Upgrade to $DBversion done (saved_sql and saved_reports added)\n";
515     SetVersion ($DBversion);
516 }
517
518 $DBversion = "3.00.00.016";
519 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
520     $dbh->do(" CREATE TABLE reports_dictionary (
521           id int(11) NOT NULL auto_increment,
522           name varchar(255) default NULL,
523           description text,
524           date_created datetime default NULL,
525           date_modified datetime default NULL,
526           saved_sql text,
527           area int(11) default NULL,
528           PRIMARY KEY  (id)
529         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
530     print "Upgrade to $DBversion done (reports_dictionary) added)\n";
531     SetVersion ($DBversion);
532 }
533
534 $DBversion = "3.00.00.017";
535 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
536     $dbh->do("ALTER TABLE action_logs DROP PRIMARY KEY");
537     $dbh->do("ALTER TABLE action_logs ADD KEY  timestamp (timestamp,user)");
538     $dbh->do("ALTER TABLE action_logs ADD action_id INT(11) NOT NULL FIRST");
539     $dbh->do("UPDATE action_logs SET action_id = if (\@a, \@a:=\@a+1, \@a:=1)");
540     $dbh->do("ALTER TABLE action_logs MODIFY action_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY");
541     print "Upgrade to $DBversion done (added column to action_logs)\n";
542     SetVersion ($DBversion);
543 }
544
545 $DBversion = "3.00.00.018";
546 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
547     $dbh->do("ALTER TABLE `zebraqueue`
548                     ADD `done` INT NOT NULL DEFAULT '0',
549                     ADD `time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ;
550             ");
551     print "Upgrade to $DBversion done (adding timestamp and done columns to zebraque table to improve problem tracking) added)\n";
552     SetVersion ($DBversion);
553 }
554
555 $DBversion = "3.00.00.019";
556 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
557     $dbh->do("ALTER TABLE biblio MODIFY biblionumber INT(11) NOT NULL AUTO_INCREMENT");
558     $dbh->do("ALTER TABLE biblioitems MODIFY biblioitemnumber INT(11) NOT NULL AUTO_INCREMENT");
559     $dbh->do("ALTER TABLE items MODIFY itemnumber INT(11) NOT NULL AUTO_INCREMENT");
560     print "Upgrade to $DBversion done (made bib/item PKs auto_increment)\n";
561     SetVersion ($DBversion);
562 }
563
564 $DBversion = "3.00.00.020";
565 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
566     $dbh->do("ALTER TABLE deleteditems
567               DROP KEY `delitembarcodeidx`,
568               ADD KEY `delitembarcodeidx` (`barcode`)");
569     print "Upgrade to $DBversion done (dropped uniqueness of key on deleteditems.barcode)\n";
570     SetVersion ($DBversion);
571 }
572
573 $DBversion = "3.00.00.021";
574 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
575     $dbh->do("ALTER TABLE items CHANGE homebranch homebranch VARCHAR(10)");
576     $dbh->do("ALTER TABLE deleteditems CHANGE homebranch homebranch VARCHAR(10)");
577     $dbh->do("ALTER TABLE statistics CHANGE branch branch VARCHAR(10)");
578     $dbh->do("ALTER TABLE subscription CHANGE lastbranch lastbranch VARCHAR(10)");
579     print "Upgrade to $DBversion done (extended missed branchcode columns to 10 chars)\n";
580     SetVersion ($DBversion);
581 }
582
583 $DBversion = "3.00.00.022";
584 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
585     $dbh->do("ALTER TABLE items
586                 ADD `damaged` tinyint(1) default NULL AFTER notforloan");
587     $dbh->do("ALTER TABLE deleteditems
588                 ADD `damaged` tinyint(1) default NULL AFTER notforloan");
589     print "Upgrade to $DBversion done (adding damaged column to items table)\n";
590     SetVersion ($DBversion);
591 }
592
593 $DBversion = "3.00.00.023";
594 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
595      $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
596          VALUES ('yuipath','http://yui.yahooapis.com/2.3.1/build','Insert the path to YUI libraries','','free')");
597     print "Upgrade to $DBversion done (adding new system preference for controlling YUI path)\n";
598     SetVersion ($DBversion);
599 }
600 $DBversion = "3.00.00.024";
601 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
602     $dbh->do("ALTER TABLE biblioitems CHANGE  itemtype itemtype VARCHAR(10)");
603     print "Upgrade to $DBversion done (changing itemtype to (10))\n";
604     SetVersion ($DBversion);
605 }
606
607 $DBversion = "3.00.00.025";
608 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
609     $dbh->do("ALTER TABLE items ADD COLUMN itype VARCHAR(10)");
610     $dbh->do("ALTER TABLE deleteditems ADD COLUMN itype VARCHAR(10) AFTER uri");
611     if(C4::Context->preference('item-level_itypes')){
612         $dbh->do('update items,biblioitems set items.itype=biblioitems.itemtype where items.biblionumber=biblioitems.biblionumber and itype is null');
613     }
614     print "Upgrade to $DBversion done (reintroduce items.itype - fill from itemtype)\n ";
615     SetVersion ($DBversion);
616 }
617
618 $DBversion = "3.00.00.026";
619 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
620     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
621        VALUES ('HomeOrHoldingBranch','homebranch','homebranch|holdingbranch','With independent branches turned on this decides whether to check the items holdingbranch or homebranch at circulatilon','choice')");
622     print "Upgrade to $DBversion done (adding new system preference for choosing whether homebranch or holdingbranch is checked in circulation)\n";
623     SetVersion ($DBversion);
624 }
625
626 $DBversion = "3.00.00.027";
627 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
628     $dbh->do("CREATE TABLE `marc_matchers` (
629                 `matcher_id` int(11) NOT NULL auto_increment,
630                 `code` varchar(10) NOT NULL default '',
631                 `description` varchar(255) NOT NULL default '',
632                 `record_type` varchar(10) NOT NULL default 'biblio',
633                 `threshold` int(11) NOT NULL default 0,
634                 PRIMARY KEY (`matcher_id`),
635                 KEY `code` (`code`),
636                 KEY `record_type` (`record_type`)
637               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
638     $dbh->do("CREATE TABLE `matchpoints` (
639                 `matcher_id` int(11) NOT NULL,
640                 `matchpoint_id` int(11) NOT NULL auto_increment,
641                 `search_index` varchar(30) NOT NULL default '',
642                 `score` int(11) NOT NULL default 0,
643                 PRIMARY KEY (`matchpoint_id`),
644                 CONSTRAINT `matchpoints_ifbk_1` FOREIGN KEY (`matcher_id`)
645                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE
646               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
647     $dbh->do("CREATE TABLE `matchpoint_components` (
648                 `matchpoint_id` int(11) NOT NULL,
649                 `matchpoint_component_id` int(11) NOT NULL auto_increment,
650                 sequence int(11) NOT NULL default 0,
651                 tag varchar(3) NOT NULL default '',
652                 subfields varchar(40) NOT NULL default '',
653                 offset int(4) NOT NULL default 0,
654                 length int(4) NOT NULL default 0,
655                 PRIMARY KEY (`matchpoint_component_id`),
656                 KEY `by_sequence` (`matchpoint_id`, `sequence`),
657                 CONSTRAINT `matchpoint_components_ifbk_1` FOREIGN KEY (`matchpoint_id`)
658                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
659               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
660     $dbh->do("CREATE TABLE `matchpoint_component_norms` (
661                 `matchpoint_component_id` int(11) NOT NULL,
662                 `sequence`  int(11) NOT NULL default 0,
663                 `norm_routine` varchar(50) NOT NULL default '',
664                 KEY `matchpoint_component_norms` (`matchpoint_component_id`, `sequence`),
665                 CONSTRAINT `matchpoint_component_norms_ifbk_1` FOREIGN KEY (`matchpoint_component_id`)
666                            REFERENCES `matchpoint_components` (`matchpoint_component_id`) ON DELETE CASCADE ON UPDATE CASCADE
667               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
668     $dbh->do("CREATE TABLE `matcher_matchpoints` (
669                 `matcher_id` int(11) NOT NULL,
670                 `matchpoint_id` int(11) NOT NULL,
671                 CONSTRAINT `matcher_matchpoints_ifbk_1` FOREIGN KEY (`matcher_id`)
672                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE,
673                 CONSTRAINT `matcher_matchpoints_ifbk_2` FOREIGN KEY (`matchpoint_id`)
674                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
675               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
676     $dbh->do("CREATE TABLE `matchchecks` (
677                 `matcher_id` int(11) NOT NULL,
678                 `matchcheck_id` int(11) NOT NULL auto_increment,
679                 `source_matchpoint_id` int(11) NOT NULL,
680                 `target_matchpoint_id` int(11) NOT NULL,
681                 PRIMARY KEY (`matchcheck_id`),
682                 CONSTRAINT `matcher_matchchecks_ifbk_1` FOREIGN KEY (`matcher_id`)
683                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE,
684                 CONSTRAINT `matcher_matchchecks_ifbk_2` FOREIGN KEY (`source_matchpoint_id`)
685                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE,
686                 CONSTRAINT `matcher_matchchecks_ifbk_3` FOREIGN KEY (`target_matchpoint_id`)
687                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
688               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
689     print "Upgrade to $DBversion done (added C4::Matcher serialization tables)\n ";
690     SetVersion ($DBversion);
691 }
692
693 $DBversion = "3.00.00.028";
694 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
695     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
696        VALUES ('canreservefromotherbranches','1','','With Independent branches on, can a user from one library reserve an item from another library','YesNo')");
697     print "Upgrade to $DBversion done (adding new system preference for changing reserve/holds behaviour with independent branches)\n";
698     SetVersion ($DBversion);
699 }
700
701
702 $DBversion = "3.00.00.029";
703 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
704     $dbh->do("ALTER TABLE `import_batches` ADD `matcher_id` int(11) NULL AFTER `import_batch_id`");
705     print "Upgrade to $DBversion done (adding matcher_id to import_batches)\n";
706     SetVersion ($DBversion);
707 }
708
709 $DBversion = "3.00.00.030";
710 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
711     $dbh->do("
712 CREATE TABLE services_throttle (
713   service_type varchar(10) NOT NULL default '',
714   service_count varchar(45) default NULL,
715   PRIMARY KEY  (service_type)
716 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
717 ");
718     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
719        VALUES ('FRBRizeEditions',0,'','If ON, Koha will query one or more ISBN web services for associated ISBNs and display an Editions tab on the details pages','YesNo')");
720  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
721        VALUES ('XISBN',0,'','Use with FRBRizeEditions. If ON, Koha will use the OCLC xISBN web service in the Editions tab on the detail pages. See: http://www.worldcat.org/affiliate/webservices/xisbn/app.jsp','YesNo')");
722  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
723        VALUES ('OCLCAffiliateID','','','Use with FRBRizeEditions and XISBN. You can sign up for an AffiliateID here: http://www.worldcat.org/wcpa/do/AffiliateUserServices?method=initSelfRegister','free')");
724  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
725        VALUES ('XISBNDailyLimit',499,'','The xISBN Web service is free for non-commercial use when usage does not exceed 500 requests per day','free')");
726  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
727        VALUES ('PINESISBN',0,'','Use with FRBRizeEditions. If ON, Koha will use PINES OISBN web service in the Editions tab on the detail pages.','YesNo')");
728  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
729        VALUES ('ThingISBN',0,'','Use with FRBRizeEditions. If ON, Koha will use the ThingISBN web service in the Editions tab on the detail pages.','YesNo')");
730     print "Upgrade to $DBversion done (adding services throttle table and sysprefs for xISBN)\n";
731     SetVersion ($DBversion);
732 }
733
734 $DBversion = "3.00.00.031";
735 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
736
737 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryStemming',1,'If ON, enables query stemming',NULL,'YesNo')");
738 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryFuzzy',1,'If ON, enables fuzzy option for searches',NULL,'YesNo')");
739 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryWeightFields',1,'If ON, enables field weighting',NULL,'YesNo')");
740 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('WebBasedSelfCheck',0,'If ON, enables the web-based self-check system',NULL,'YesNo')");
741 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('numSearchResults',20,'Specify the maximum number of results to display on a page of results',NULL,'free')");
742 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACnumSearchResults',20,'Specify the maximum number of results to display on a page of results',NULL,'free')");
743 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('maxItemsInSearchResults',20,'Specify the maximum number of items to display for each result on a page of results',NULL,'free')");
744 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('defaultSortField',NULL,'Specify the default field used for sorting','relevance|popularity|call_number|pubdate|acqdate|title|author','Choice')");
745 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('defaultSortOrder',NULL,'Specify the default sort order','asc|dsc|az|za','Choice')");
746 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACdefaultSortField',NULL,'Specify the default field used for sorting','relevance|popularity|call_number|pubdate|acqdate|title|author','Choice')");
747 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACdefaultSortOrder',NULL,'Specify the default sort order','asc|dsc|za|az','Choice')");
748 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('staffClientBaseURL','','Specify the base URL of the staff client',NULL,'free')");
749 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('minPasswordLength',3,'Specify the minimum length of a patron/staff password',NULL,'free')");
750 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('noItemTypeImages',0,'If ON, disables item-type images',NULL,'YesNo')");
751 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('emailLibrarianWhenHoldIsPlaced',0,'If ON, emails the librarian whenever a hold is placed',NULL,'YesNo')");
752 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('holdCancelLength','','Specify how many days before a hold is canceled',NULL,'free')");
753 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('libraryAddress','','The address to use for printing receipts, overdues, etc. if different than physical address',NULL,'free')");
754 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('finesMode','test','Choose the fines mode, test or production','test|production','Choice')");
755 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('globalDueDate','','If set, allows a global static due date for all checkouts',NULL,'free')");
756 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('itemBarcodeInputFilter','','If set, allows specification of a item barcode input filter','cuecat','Choice')");
757 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('singleBranchMode',0,'Operate in Single-branch mode, hide branch selection in the OPAC',NULL,'YesNo')");
758 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('URLLinkText','','Text to display as the link anchor in the OPAC',NULL,'free')");
759 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACSubscriptionDisplay','economical','Specify how to display subscription information in the OPAC','economical|off|full','Choice')");
760 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACDisplayExtendedSubInfo',1,'If ON, extended subscription information is displayed in the OPAC',NULL,'YesNo')");
761 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACViewOthersSuggestions',0,'If ON, allows all suggestions to be displayed in the OPAC',NULL,'YesNo')");
762 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACURLOpenInNewWindow',0,'If ON, URLs in the OPAC open in a new window',NULL,'YesNo')");
763 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACUserCSS',0,'Add CSS to be included in the OPAC',NULL,'free')");
764
765     print "Upgrade to $DBversion done (adding additional system preference)\n";
766     SetVersion ($DBversion);
767 }
768
769 $DBversion = "3.00.00.032";
770 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
771     $dbh->do("UPDATE `marc_subfield_structure` SET `kohafield` = 'items.wthdrawn' WHERE `kohafield` = 'items.withdrawn'");
772     print "Upgrade to $DBversion done (fixed MARC framework references to items.withdrawn)\n";
773     SetVersion ($DBversion);
774 }
775
776 $DBversion = "3.00.00.033";
777 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
778     $dbh->do("INSERT INTO `userflags` VALUES(17,'staffaccess','Modify login / permissions for staff users',0)");
779     print "Upgrade to $DBversion done (Adding permissions flag for staff member access modification.  )\n";
780     SetVersion ($DBversion);
781 }
782
783 $DBversion = "3.00.00.034";
784 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
785     $dbh->do("ALTER TABLE `virtualshelves` ADD COLUMN `sortfield` VARCHAR(16) ");
786     print "Upgrade to $DBversion done (Adding sortfield for Virtual Shelves.  )\n";
787     SetVersion ($DBversion);
788 }
789
790 $DBversion = "3.00.00.035";
791 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
792     $dbh->do("UPDATE marc_subfield_structure
793               SET authorised_value = 'cn_source'
794               WHERE kohafield IN ('items.cn_source', 'biblioitems.cn_source')
795               AND (authorised_value is NULL OR authorised_value = '')");
796     print "Upgrade to $DBversion done (MARC frameworks: make classification source a drop-down)\n";
797     SetVersion ($DBversion);
798 }
799
800 $DBversion = "3.00.00.036";
801 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
802     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACItemsResultsDisplay','statuses','statuses : show only the status of items in result list. itemdisplay : show full location of items (branch+location+callnumber) as in staff interface','statuses|itemdetails','Choice');");
803     print "Upgrade to $DBversion done (OPACItemsResultsDisplay systempreference added)\n";
804     SetVersion ($DBversion);
805 }
806
807 $DBversion = "3.00.00.037";
808 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
809     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactfirstname` varchar(255)");
810     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactsurname` varchar(255)");
811     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress1` varchar(255)");
812     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress2` varchar(255)");
813     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress3` varchar(255)");
814     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactzipcode` varchar(50)");
815     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactphone` varchar(50)");
816     print "Upgrade to $DBversion done (Adding Alternative Contact Person information to borrowers table)\n";
817     SetVersion ($DBversion);
818 }
819
820 $DBversion = "3.00.00.038";
821 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
822     $dbh->do("UPDATE `systempreferences` set explanation='Choose the fines mode, off, test (emails admin report) or production (accrue overdue fines).  Requires fines cron script' , options='off|test|production' where variable='finesMode'");
823     $dbh->do("DELETE FROM `systempreferences` WHERE variable='hideBiblioNumber'");
824     print "Upgrade to $DBversion done ('alter finesMode systempreference, remove superfluous syspref.')\n";
825     SetVersion ($DBversion);
826 }
827
828 $DBversion = "3.00.00.039";
829 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
830     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('uppercasesurnames',0,'If ON, surnames are converted to upper case in patron entry form',NULL,'YesNo')");
831     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('CircControl','ItemHomeLibrary','Specify the agency that controls the circulation and fines policy','PickupLibrary|PatronLibrary|ItemHomeLibrary','Choice')");
832     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('finesCalendar','noFinesWhenClosed','Specify whether to use the Calendar in calculating duedates and fines','ignoreCalendar|noFinesWhenClosed','Choice')");
833     # $dbh->do("DELETE FROM `systempreferences` WHERE variable='HomeOrHoldingBranch'"); # Bug #2752
834     print "Upgrade to $DBversion done ('add circ sysprefs CircControl, finesCalendar, and uppercasesurnames, and delete HomeOrHoldingBranch.')\n";
835     SetVersion ($DBversion);
836 }
837
838 $DBversion = "3.00.00.040";
839 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
840         $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('previousIssuesDefaultSortOrder','asc','Specify the sort order of Previous Issues on the circulation page','asc|desc','Choice')");
841         $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('todaysIssuesDefaultSortOrder','desc','Specify the sort order of Todays Issues on the circulation page','asc|desc','Choice')");
842         print "Upgrade to $DBversion done ('add circ sysprefs todaysIssuesDefaultSortOrder and previousIssuesDefaultSortOrder.')\n";
843     SetVersion ($DBversion);
844 }
845
846
847 $DBversion = "3.00.00.041";
848 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
849     # Strictly speaking it is not necessary to explicitly change
850     # NULL values to 0, because the ALTER TABLE statement will do that.
851     # However, setting them first avoids a warning.
852     $dbh->do("UPDATE items SET notforloan = 0 WHERE notforloan IS NULL");
853     $dbh->do("UPDATE items SET damaged = 0 WHERE damaged IS NULL");
854     $dbh->do("UPDATE items SET itemlost = 0 WHERE itemlost IS NULL");
855     $dbh->do("UPDATE items SET wthdrawn = 0 WHERE wthdrawn IS NULL");
856     $dbh->do("ALTER TABLE items
857                 MODIFY notforloan tinyint(1) NOT NULL default 0,
858                 MODIFY damaged    tinyint(1) NOT NULL default 0,
859                 MODIFY itemlost   tinyint(1) NOT NULL default 0,
860                 MODIFY wthdrawn   tinyint(1) NOT NULL default 0");
861     $dbh->do("UPDATE deleteditems SET notforloan = 0 WHERE notforloan IS NULL");
862     $dbh->do("UPDATE deleteditems SET damaged = 0 WHERE damaged IS NULL");
863     $dbh->do("UPDATE deleteditems SET itemlost = 0 WHERE itemlost IS NULL");
864     $dbh->do("UPDATE deleteditems SET wthdrawn = 0 WHERE wthdrawn IS NULL");
865     $dbh->do("ALTER TABLE deleteditems
866                 MODIFY notforloan tinyint(1) NOT NULL default 0,
867                 MODIFY damaged    tinyint(1) NOT NULL default 0,
868                 MODIFY itemlost   tinyint(1) NOT NULL default 0,
869                 MODIFY wthdrawn   tinyint(1) NOT NULL default 0");
870         print "Upgrade to $DBversion done (disallow NULL in several item status columns)\n";
871     SetVersion ($DBversion);
872 }
873
874 $DBversion = "3.00.00.04";
875 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
876     $dbh->do("ALTER TABLE aqbooksellers CHANGE name name mediumtext NOT NULL");
877         print "Upgrade to $DBversion done (disallow NULL in aqbooksellers.name; part of fix for bug 1251)\n";
878     SetVersion ($DBversion);
879 }
880
881 $DBversion = "3.00.00.043";
882 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
883     $dbh->do("ALTER TABLE `currency` ADD `symbol` varchar(5) default NULL AFTER currency, ADD `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP AFTER symbol");
884         print "Upgrade to $DBversion done (currency table: add symbol and timestamp columns)\n";
885     SetVersion ($DBversion);
886 }
887
888 $DBversion = "3.00.00.044";
889 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
890     $dbh->do("ALTER TABLE deletedborrowers
891   ADD `altcontactfirstname` varchar(255) default NULL,
892   ADD `altcontactsurname` varchar(255) default NULL,
893   ADD `altcontactaddress1` varchar(255) default NULL,
894   ADD `altcontactaddress2` varchar(255) default NULL,
895   ADD `altcontactaddress3` varchar(255) default NULL,
896   ADD `altcontactzipcode` varchar(50) default NULL,
897   ADD `altcontactphone` varchar(50) default NULL
898   ");
899   $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES
900 ('OPACBaseURL',NULL,'Specify the Base URL of the OPAC, e.g., opac.mylibrary.com, the http:// will be added automatically by Koha.',NULL,'Free'),
901 ('language','en','Set the default language in the staff client.',NULL,'Languages'),
902 ('QueryAutoTruncate',1,'If ON, query truncation is enabled by default',NULL,'YesNo'),
903 ('QueryRemoveStopwords',0,'If ON, stopwords listed in the Administration area will be removed from queries',NULL,'YesNo')
904   ");
905         print "Upgrade to $DBversion done (syncing deletedborrowers table with borrowers table)\n";
906     SetVersion ($DBversion);
907 }
908
909 #-- http://www.w3.org/International/articles/language-tags/
910
911 #-- RFC4646
912 $DBversion = "3.00.00.045";
913 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
914     $dbh->do("
915 CREATE TABLE language_subtag_registry (
916         subtag varchar(25),
917         type varchar(25), -- language-script-region-variant-extension-privateuse
918         description varchar(25), -- only one of the possible descriptions for ease of reference, see language_descriptions for the complete list
919         added date,
920         KEY `subtag` (`subtag`)
921 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
922
923 #-- TODO: add suppress_scripts
924 #-- this maps three letter codes defined in iso639.2 back to their
925 #-- two letter equivilents in rfc4646 (LOC maintains iso639+)
926  $dbh->do("CREATE TABLE language_rfc4646_to_iso639 (
927         rfc4646_subtag varchar(25),
928         iso639_2_code varchar(25),
929         KEY `rfc4646_subtag` (`rfc4646_subtag`)
930 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
931
932  $dbh->do("CREATE TABLE language_descriptions (
933         subtag varchar(25),
934         type varchar(25),
935         lang varchar(25),
936         description varchar(255),
937         KEY `lang` (`lang`)
938 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
939
940 #-- bi-directional support, keyed by script subcode
941  $dbh->do("CREATE TABLE language_script_bidi (
942         rfc4646_subtag varchar(25), -- script subtag, Arab, Hebr, etc.
943         bidi varchar(3), -- rtl ltr
944         KEY `rfc4646_subtag` (`rfc4646_subtag`)
945 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
946
947 #-- BIDI Stuff, Arabic and Hebrew
948  $dbh->do("INSERT INTO language_script_bidi(rfc4646_subtag,bidi)
949 VALUES( 'Arab', 'rtl')");
950  $dbh->do("INSERT INTO language_script_bidi(rfc4646_subtag,bidi)
951 VALUES( 'Hebr', 'rtl')");
952
953 #-- TODO: need to map language subtags to script subtags for detection
954 #-- of bidi when script is not specified (like ar, he)
955  $dbh->do("CREATE TABLE language_script_mapping (
956         language_subtag varchar(25),
957         script_subtag varchar(25),
958         KEY `language_subtag` (`language_subtag`)
959 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
960
961 #-- Default mappings between script and language subcodes
962  $dbh->do("INSERT INTO language_script_mapping(language_subtag,script_subtag)
963 VALUES( 'ar', 'Arab')");
964  $dbh->do("INSERT INTO language_script_mapping(language_subtag,script_subtag)
965 VALUES( 'he', 'Hebr')");
966
967         print "Upgrade to $DBversion done (adding language subtag registry and basic BiDi support NOTE: You should import the subtag registry SQL)\n";
968     SetVersion ($DBversion);
969 }
970
971 $DBversion = "3.00.00.046";
972 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
973     $dbh->do("ALTER TABLE `subscription` CHANGE `numberlength` `numberlength` int(11) default '0' ,
974                  CHANGE `weeklength` `weeklength` int(11) default '0'");
975     $dbh->do("CREATE TABLE `serialitems` (`serialid` int(11) NOT NULL, `itemnumber` int(11) NOT NULL, UNIQUE KEY `serialididx` (`serialid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
976     $dbh->do("INSERT INTO `serialitems` SELECT `serialid`,`itemnumber` from serial where NOT ISNULL(itemnumber) && itemnumber <> '' && itemnumber NOT LIKE '%,%'");
977         print "Upgrade to $DBversion done (Add serialitems table to link serial issues to items. )\n";
978     SetVersion ($DBversion);
979 }
980
981 $DBversion = "3.00.00.047";
982 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
983     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacRenewalAllowed',0,'If ON, users can renew their issues directly from their OPAC account',NULL,'YesNo');");
984         print "Upgrade to $DBversion done ( Added OpacRenewalAllowed syspref )\n";
985     SetVersion ($DBversion);
986 }
987
988 $DBversion = "3.00.00.048";
989 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
990     $dbh->do("ALTER TABLE `items` ADD `more_subfields_xml` longtext default NULL AFTER `itype`");
991         print "Upgrade to $DBversion done (added items.more_subfields_xml)\n";
992     SetVersion ($DBversion);
993 }
994
995 $DBversion = "3.00.00.049";
996 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
997         $dbh->do("ALTER TABLE `z3950servers` ADD `encoding` text default NULL AFTER type ");
998         print "Upgrade to $DBversion done ( Added encoding field to z3950servers table )\n";
999     SetVersion ($DBversion);
1000 }
1001
1002 $DBversion = "3.00.00.050";
1003 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1004     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacHighlightedWords','0','If Set, query matched terms are highlighted in OPAC',NULL,'YesNo');");
1005         print "Upgrade to $DBversion done ( Added OpacHighlightedWords syspref )\n";
1006     SetVersion ($DBversion);
1007 }
1008
1009 $DBversion = "3.00.00.051";
1010 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1011     $dbh->do("UPDATE systempreferences SET explanation = 'Define the current theme for the OPAC interface.' WHERE variable = 'opacthemes';");
1012         print "Upgrade to $DBversion done ( Corrected opacthemes explanation. )\n";
1013     SetVersion ($DBversion);
1014 }
1015
1016 $DBversion = "3.00.00.052";
1017 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1018     $dbh->do("ALTER TABLE `deleteditems` ADD `more_subfields_xml` LONGTEXT DEFAULT NULL AFTER `itype`");
1019         print "Upgrade to $DBversion done ( Adding missing column to deleteditems table. )\n";
1020     SetVersion ($DBversion);
1021 }
1022
1023 $DBversion = "3.00.00.053";
1024 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1025     $dbh->do("CREATE TABLE `printers_profile` (
1026             `prof_id` int(4) NOT NULL auto_increment,
1027             `printername` varchar(40) NOT NULL,
1028             `tmpl_id` int(4) NOT NULL,
1029             `paper_bin` varchar(20) NOT NULL,
1030             `offset_horz` float default NULL,
1031             `offset_vert` float default NULL,
1032             `creep_horz` float default NULL,
1033             `creep_vert` float default NULL,
1034             `unit` char(20) NOT NULL default 'POINT',
1035             PRIMARY KEY  (`prof_id`),
1036             UNIQUE KEY `printername` (`printername`,`tmpl_id`,`paper_bin`),
1037             CONSTRAINT `printers_profile_pnfk_1` FOREIGN KEY (`tmpl_id`) REFERENCES `labels_templates` (`tmpl_id`) ON DELETE CASCADE ON UPDATE CASCADE
1038             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1039     $dbh->do("CREATE TABLE `labels_profile` (
1040             `tmpl_id` int(4) NOT NULL,
1041             `prof_id` int(4) NOT NULL,
1042             UNIQUE KEY `tmpl_id` (`tmpl_id`),
1043             UNIQUE KEY `prof_id` (`prof_id`)
1044             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1045     print "Upgrade to $DBversion done ( Printer Profile tables added )\n";
1046     SetVersion ($DBversion);
1047 }
1048
1049 $DBversion = "3.00.00.054";
1050 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1051     $dbh->do("UPDATE systempreferences SET options = 'incremental|annual|hbyymmincr|OFF', explanation = 'Used to autogenerate a barcode: incremental will be of the form 1, 2, 3; annual of the form 2007-0001, 2007-0002; hbyymmincr of the form HB08010001 where HB = Home Branch' WHERE variable = 'autoBarcode';");
1052         print "Upgrade to $DBversion done ( Added another barcode autogeneration sequence to barcode.pl. )\n";
1053     SetVersion ($DBversion);
1054 }
1055
1056 $DBversion = "3.00.00.055";
1057 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1058     $dbh->do("ALTER TABLE `zebraqueue` ADD KEY `zebraqueue_lookup` (`server`, `biblio_auth_number`, `operation`, `done`)");
1059         print "Upgrade to $DBversion done ( Added index on zebraqueue. )\n";
1060     SetVersion ($DBversion);
1061 }
1062 $DBversion = "3.00.00.056";
1063 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1064     if (C4::Context->preference("marcflavour") eq 'UNIMARC') {
1065         $dbh->do("INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`, `tab`, `authorised_value` , `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`) VALUES ('995', 'v', 'Note sur le N° de périodique','Note sur le N° de périodique', 0, 0, 'items.enumchron', 10, '', '', '', 0, 0, '', '', '', NULL) ");
1066     } else {
1067         $dbh->do("INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`, `tab`, `authorised_value` , `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`) VALUES ('952', 'h', 'Serial Enumeration / chronology','Serial Enumeration / chronology', 0, 0, 'items.enumchron', 10, '', '', '', 0, 0, '', '', '', NULL) ");
1068     }
1069     $dbh->do("ALTER TABLE `items` ADD `enumchron` VARCHAR(80) DEFAULT NULL;");
1070     print "Upgrade to $DBversion done ( Added item.enumchron column, and framework map to 952h )\n";
1071     SetVersion ($DBversion);
1072 }
1073
1074 $DBversion = "3.00.00.057";
1075 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1076     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH','0','if ON, OAI-PMH server is enabled',NULL,'YesNo');");
1077     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH:archiveID','KOHA-OAI-TEST','OAI-PMH archive identification',NULL,'Free');");
1078     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH:MaxCount','50','OAI-PMH maximum number of records by answer to ListRecords and ListIdentifiers queries',NULL,'Integer');");
1079     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH:Set','SET,Experimental set\r\nSET:SUBSET,Experimental subset','OAI-PMH exported set, the set name is followed by a comma and a short description, one set by line',NULL,'Free');");
1080     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH:Subset',\"itemtype='BOOK'\",'Restrict answer to matching raws of the biblioitems table (experimental)',NULL,'Free');");
1081     SetVersion ($DBversion);
1082 }
1083
1084 $DBversion = "3.00.00.058";
1085 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1086     $dbh->do("ALTER TABLE `opac_news`
1087                 CHANGE `lang` `lang` VARCHAR( 25 )
1088                 CHARACTER SET utf8
1089                 COLLATE utf8_general_ci
1090                 NOT NULL default ''");
1091         print "Upgrade to $DBversion done ( lang field in opac_news made longer )\n";
1092     SetVersion ($DBversion);
1093 }
1094
1095 $DBversion = "3.00.00.059";
1096 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1097
1098     $dbh->do("CREATE TABLE IF NOT EXISTS `labels_templates` (
1099             `tmpl_id` int(4) NOT NULL auto_increment,
1100             `tmpl_code` char(100)  default '',
1101             `tmpl_desc` char(100) default '',
1102             `page_width` float default '0',
1103             `page_height` float default '0',
1104             `label_width` float default '0',
1105             `label_height` float default '0',
1106             `topmargin` float default '0',
1107             `leftmargin` float default '0',
1108             `cols` int(2) default '0',
1109             `rows` int(2) default '0',
1110             `colgap` float default '0',
1111             `rowgap` float default '0',
1112             `active` int(1) default NULL,
1113             `units` char(20)  default 'PX',
1114             `fontsize` int(4) NOT NULL default '3',
1115             PRIMARY KEY  (`tmpl_id`)
1116             ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1117     $dbh->do("CREATE TABLE  IF NOT EXISTS `printers_profile` (
1118             `prof_id` int(4) NOT NULL auto_increment,
1119             `printername` varchar(40) NOT NULL,
1120             `tmpl_id` int(4) NOT NULL,
1121             `paper_bin` varchar(20) NOT NULL,
1122             `offset_horz` float default NULL,
1123             `offset_vert` float default NULL,
1124             `creep_horz` float default NULL,
1125             `creep_vert` float default NULL,
1126             `unit` char(20) NOT NULL default 'POINT',
1127             PRIMARY KEY  (`prof_id`),
1128             UNIQUE KEY `printername` (`printername`,`tmpl_id`,`paper_bin`),
1129             CONSTRAINT `printers_profile_pnfk_1` FOREIGN KEY (`tmpl_id`) REFERENCES `labels_templates` (`tmpl_id`) ON DELETE CASCADE ON UPDATE CASCADE
1130             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1131     print "Upgrade to $DBversion done ( Added labels_templates table if it did not exist. )\n";
1132     SetVersion ($DBversion);
1133 }
1134
1135 $DBversion = "3.00.00.060";
1136 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1137     $dbh->do("CREATE TABLE IF NOT EXISTS `patronimage` (
1138             `cardnumber` varchar(16) NOT NULL,
1139             `mimetype` varchar(15) NOT NULL,
1140             `imagefile` mediumblob NOT NULL,
1141             PRIMARY KEY  (`cardnumber`),
1142             CONSTRAINT `patronimage_fk1` FOREIGN KEY (`cardnumber`) REFERENCES `borrowers` (`cardnumber`) ON DELETE CASCADE ON UPDATE CASCADE
1143             ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1144         print "Upgrade to $DBversion done ( Added patronimage table. )\n";
1145     SetVersion ($DBversion);
1146 }
1147
1148 $DBversion = "3.00.00.061";
1149 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1150     $dbh->do("ALTER TABLE labels_templates ADD COLUMN font char(10) NOT NULL DEFAULT 'TR';");
1151         print "Upgrade to $DBversion done ( Added font column to labels_templates )\n";
1152     SetVersion ($DBversion);
1153 }
1154
1155 $DBversion = "3.00.00.062";
1156 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1157     $dbh->do("CREATE TABLE `old_issues` (
1158                 `borrowernumber` int(11) default NULL,
1159                 `itemnumber` int(11) default NULL,
1160                 `date_due` date default NULL,
1161                 `branchcode` varchar(10) default NULL,
1162                 `issuingbranch` varchar(18) default NULL,
1163                 `returndate` date default NULL,
1164                 `lastreneweddate` date default NULL,
1165                 `return` varchar(4) default NULL,
1166                 `renewals` tinyint(4) default NULL,
1167                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1168                 `issuedate` date default NULL,
1169                 KEY `old_issuesborridx` (`borrowernumber`),
1170                 KEY `old_issuesitemidx` (`itemnumber`),
1171                 KEY `old_bordate` (`borrowernumber`,`timestamp`),
1172                 CONSTRAINT `old_issues_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1173                     ON DELETE SET NULL ON UPDATE SET NULL,
1174                 CONSTRAINT `old_issues_ibfk_2` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`)
1175                     ON DELETE SET NULL ON UPDATE SET NULL
1176                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1177     $dbh->do("CREATE TABLE `old_reserves` (
1178                 `borrowernumber` int(11) default NULL,
1179                 `reservedate` date default NULL,
1180                 `biblionumber` int(11) default NULL,
1181                 `constrainttype` varchar(1) default NULL,
1182                 `branchcode` varchar(10) default NULL,
1183                 `notificationdate` date default NULL,
1184                 `reminderdate` date default NULL,
1185                 `cancellationdate` date default NULL,
1186                 `reservenotes` mediumtext,
1187                 `priority` smallint(6) default NULL,
1188                 `found` varchar(1) default NULL,
1189                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1190                 `itemnumber` int(11) default NULL,
1191                 `waitingdate` date default NULL,
1192                 KEY `old_reserves_borrowernumber` (`borrowernumber`),
1193                 KEY `old_reserves_biblionumber` (`biblionumber`),
1194                 KEY `old_reserves_itemnumber` (`itemnumber`),
1195                 KEY `old_reserves_branchcode` (`branchcode`),
1196                 CONSTRAINT `old_reserves_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1197                     ON DELETE SET NULL ON UPDATE SET NULL,
1198                 CONSTRAINT `old_reserves_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`)
1199                     ON DELETE SET NULL ON UPDATE SET NULL,
1200                 CONSTRAINT `old_reserves_ibfk_3` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`)
1201                     ON DELETE SET NULL ON UPDATE SET NULL
1202                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1203
1204     # move closed transactions to old_* tables
1205     $dbh->do("INSERT INTO old_issues SELECT * FROM issues WHERE returndate IS NOT NULL");
1206     $dbh->do("DELETE FROM issues WHERE returndate IS NOT NULL");
1207     $dbh->do("INSERT INTO old_reserves SELECT * FROM reserves WHERE cancellationdate IS NOT NULL OR found = 'F'");
1208     $dbh->do("DELETE FROM reserves WHERE cancellationdate IS NOT NULL OR found = 'F'");
1209
1210         print "Upgrade to $DBversion done ( Added old_issues and old_reserves tables )\n";
1211     SetVersion ($DBversion);
1212 }
1213
1214 $DBversion = "3.00.00.063";
1215 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1216     $dbh->do("ALTER TABLE deleteditems
1217                 CHANGE COLUMN booksellerid booksellerid MEDIUMTEXT DEFAULT NULL,
1218                 ADD COLUMN enumchron VARCHAR(80) DEFAULT NULL AFTER more_subfields_xml,
1219                 ADD COLUMN copynumber SMALLINT(6) DEFAULT NULL AFTER enumchron;");
1220     $dbh->do("ALTER TABLE items
1221                 CHANGE COLUMN booksellerid booksellerid MEDIUMTEXT,
1222                 ADD COLUMN copynumber SMALLINT(6) DEFAULT NULL AFTER enumchron;");
1223         print "Upgrade to $DBversion done ( Changed items.booksellerid and deleteditems.booksellerid to MEDIUMTEXT and added missing items.copynumber and deleteditems.copynumber to fix Bug 1927)\n";
1224     SetVersion ($DBversion);
1225 }
1226
1227 $DBversion = "3.00.00.064";
1228 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1229     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AmazonLocale','US','Use to set the Locale of your Amazon.com Web Services','US|CA|DE|FR|JP|UK','Choice');");
1230     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AWSAccessKeyID','','See:  http://aws.amazon.com','','free');");
1231     $dbh->do("DELETE FROM `systempreferences` WHERE variable='AmazonDevKey';");
1232     $dbh->do("DELETE FROM `systempreferences` WHERE variable='XISBNAmazonSimilarItems';");
1233     $dbh->do("DELETE FROM `systempreferences` WHERE variable='OPACXISBNAmazonSimilarItems';");
1234     print "Upgrade to $DBversion done (IMPORTANT: Upgrading to Amazon.com Associates Web Service 4.0 ) \n";
1235     SetVersion ($DBversion);
1236 }
1237
1238 $DBversion = "3.00.00.065";
1239 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1240     $dbh->do("CREATE TABLE `patroncards` (
1241                 `cardid` int(11) NOT NULL auto_increment,
1242                 `batch_id` varchar(10) NOT NULL default '1',
1243                 `borrowernumber` int(11) NOT NULL,
1244                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1245                 PRIMARY KEY  (`cardid`),
1246                 KEY `patroncards_ibfk_1` (`borrowernumber`),
1247                 CONSTRAINT `patroncards_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE
1248                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1249     print "Upgrade to $DBversion done (Adding patroncards table for patroncards generation feature. ) \n";
1250     SetVersion ($DBversion);
1251 }
1252
1253 $DBversion = "3.00.00.066";
1254 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1255     $dbh->do("ALTER TABLE `virtualshelfcontents` MODIFY `dateadded` timestamp NOT NULL
1256 DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP;
1257 ");
1258     print "Upgrade to $DBversion done (fix for bug 1873: virtualshelfcontents dateadded column empty. ) \n";
1259     SetVersion ($DBversion);
1260 }
1261
1262 $DBversion = "3.00.00.067";
1263 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1264     $dbh->do("UPDATE systempreferences SET explanation = 'Enable patron images for the Staff Client', type = 'YesNo' WHERE variable = 'patronimages'");
1265     print "Upgrade to $DBversion done (Updating patronimages syspref to reflect current kohastructure.sql. ) \n";
1266     SetVersion ($DBversion);
1267 }
1268
1269 $DBversion = "3.00.00.068";
1270 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1271     $dbh->do("CREATE TABLE `permissions` (
1272                 `module_bit` int(11) NOT NULL DEFAULT 0,
1273                 `code` varchar(30) DEFAULT NULL,
1274                 `description` varchar(255) DEFAULT NULL,
1275                 PRIMARY KEY  (`module_bit`, `code`),
1276                 CONSTRAINT `permissions_ibfk_1` FOREIGN KEY (`module_bit`) REFERENCES `userflags` (`bit`)
1277                     ON DELETE CASCADE ON UPDATE CASCADE
1278               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1279     $dbh->do("CREATE TABLE `user_permissions` (
1280                 `borrowernumber` int(11) NOT NULL DEFAULT 0,
1281                 `module_bit` int(11) NOT NULL DEFAULT 0,
1282                 `code` varchar(30) DEFAULT NULL,
1283                 CONSTRAINT `user_permissions_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1284                     ON DELETE CASCADE ON UPDATE CASCADE,
1285                 CONSTRAINT `user_permissions_ibfk_2` FOREIGN KEY (`module_bit`, `code`)
1286                     REFERENCES `permissions` (`module_bit`, `code`)
1287                     ON DELETE CASCADE ON UPDATE CASCADE
1288               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1289
1290     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
1291     (13, 'edit_news', 'Write news for the OPAC and staff interfaces'),
1292     (13, 'label_creator', 'Create printable labels and barcodes from catalog and patron data'),
1293     (13, 'edit_calendar', 'Define days when the library is closed'),
1294     (13, 'moderate_comments', 'Moderate patron comments'),
1295     (13, 'edit_notices', 'Define notices'),
1296     (13, 'edit_notice_status_triggers', 'Set notice/status triggers for overdue items'),
1297     (13, 'view_system_logs', 'Browse the system logs'),
1298     (13, 'inventory', 'Perform inventory (stocktaking) of your catalogue'),
1299     (13, 'stage_marc_import', 'Stage MARC records into the reservoir'),
1300     (13, 'manage_staged_marc', 'Managed staged MARC records, including completing and reversing imports'),
1301     (13, 'export_catalog', 'Export bibliographic and holdings data'),
1302     (13, 'import_patrons', 'Import patron data'),
1303     (13, 'delete_anonymize_patrons', 'Delete old borrowers and anonymize circulation history (deletes borrower reading history)'),
1304     (13, 'batch_upload_patron_images', 'Upload patron images in batch or one at a time'),
1305     (13, 'schedule_tasks', 'Schedule tasks to run')");
1306
1307     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('GranularPermissions','0','Use detailed staff user permissions',NULL,'YesNo')");
1308
1309     print "Upgrade to $DBversion done (adding permissions and user_permissions tables and GranularPermissions syspref) \n";
1310     SetVersion ($DBversion);
1311 }
1312 $DBversion = "3.00.00.069";
1313 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1314     $dbh->do("ALTER TABLE labels_conf CHANGE COLUMN class classification int(1) DEFAULT NULL;");
1315         print "Upgrade to $DBversion done ( Correcting columname in labels_conf )\n";
1316     SetVersion ($DBversion);
1317 }
1318
1319 $DBversion = "3.00.00.070";
1320 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1321     $sth = $dbh->prepare("SELECT value FROM systempreferences WHERE variable='yuipath'");
1322     $sth->execute;
1323     my ($value) = $sth->fetchrow;
1324     $value =~ s/2.3.1/2.5.1/;
1325     $dbh->do("UPDATE systempreferences SET value='$value' WHERE variable='yuipath';");
1326         print "Update yuipath syspref to 2.5.1 if necessary\n";
1327     SetVersion ($DBversion);
1328 }
1329
1330 $DBversion = "3.00.00.071";
1331 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1332     $dbh->do(" ALTER TABLE `subscription` ADD `serialsadditems` TINYINT( 1 ) NOT NULL DEFAULT '0';");
1333     # fill the new field with the previous systempreference value, then drop the syspref
1334     my $sth = $dbh->prepare("SELECT value FROM systempreferences WHERE variable='serialsadditems'");
1335     $sth->execute;
1336     my ($serialsadditems) = $sth->fetchrow();
1337     $dbh->do("UPDATE subscription SET serialsadditems=$serialsadditems");
1338     $dbh->do("DELETE FROM systempreferences WHERE variable='serialsadditems'");
1339     print "Upgrade to $DBversion done ( moving serialsadditems from syspref to subscription )\n";
1340     SetVersion ($DBversion);
1341 }
1342
1343 $DBversion = "3.00.00.072";
1344 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1345     $dbh->do("ALTER TABLE labels_conf ADD COLUMN formatstring mediumtext DEFAULT NULL AFTER printingtype");
1346         print "Upgrade to $DBversion done ( Adding format string to labels generator. )\n";
1347     SetVersion ($DBversion);
1348 }
1349
1350 $DBversion = "3.00.00.073";
1351 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1352         $dbh->do("DROP TABLE IF EXISTS `tags_all`;");
1353         $dbh->do(q#
1354         CREATE TABLE `tags_all` (
1355           `tag_id`         int(11) NOT NULL auto_increment,
1356           `borrowernumber` int(11) NOT NULL,
1357           `biblionumber`   int(11) NOT NULL,
1358           `term`      varchar(255) NOT NULL,
1359           `language`       int(4) default NULL,
1360           `date_created` datetime  NOT NULL,
1361           PRIMARY KEY  (`tag_id`),
1362           KEY `tags_borrowers_fk_1` (`borrowernumber`),
1363           KEY `tags_biblionumber_fk_1` (`biblionumber`),
1364           CONSTRAINT `tags_borrowers_fk_1` FOREIGN KEY (`borrowernumber`)
1365                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1366           CONSTRAINT `tags_biblionumber_fk_1` FOREIGN KEY (`biblionumber`)
1367                 REFERENCES `biblio`     (`biblionumber`)  ON DELETE CASCADE ON UPDATE CASCADE
1368         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1369         #);
1370         $dbh->do("DROP TABLE IF EXISTS `tags_approval`;");
1371         $dbh->do(q#
1372         CREATE TABLE `tags_approval` (
1373           `term`   varchar(255) NOT NULL,
1374           `approved`     int(1) NOT NULL default '0',
1375           `date_approved` datetime       default NULL,
1376           `approved_by` int(11)          default NULL,
1377           `weight_total` int(9) NOT NULL default '1',
1378           PRIMARY KEY  (`term`),
1379           KEY `tags_approval_borrowers_fk_1` (`approved_by`),
1380           CONSTRAINT `tags_approval_borrowers_fk_1` FOREIGN KEY (`approved_by`)
1381                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE
1382         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1383         #);
1384         $dbh->do("DROP TABLE IF EXISTS `tags_index`;");
1385         $dbh->do(q#
1386         CREATE TABLE `tags_index` (
1387           `term`    varchar(255) NOT NULL,
1388           `biblionumber` int(11) NOT NULL,
1389           `weight`        int(9) NOT NULL default '1',
1390           PRIMARY KEY  (`term`,`biblionumber`),
1391           KEY `tags_index_biblionumber_fk_1` (`biblionumber`),
1392           CONSTRAINT `tags_index_term_fk_1` FOREIGN KEY (`term`)
1393                 REFERENCES `tags_approval` (`term`)  ON DELETE CASCADE ON UPDATE CASCADE,
1394           CONSTRAINT `tags_index_biblionumber_fk_1` FOREIGN KEY (`biblionumber`)
1395                 REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
1396         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1397         #);
1398         $dbh->do(q#
1399         INSERT INTO `systempreferences` VALUES
1400                 ('BakerTaylorBookstoreURL','','','URL template for \"My Libary Bookstore\" links, to which the \"key\" value is appended, and \"https://\" is prepended.  It should include your hostname and \"Parent Number\".  Make this variable empty to turn MLB links off.  Example: ocls.mylibrarybookstore.com/MLB/actions/searchHandler.do?nextPage=bookDetails&parentNum=10923&key=',''),
1401                 ('BakerTaylorEnabled','0','','Enable or disable all Baker & Taylor features.','YesNo'),
1402                 ('BakerTaylorPassword','','','Baker & Taylor Password for Content Cafe (external content)','Textarea'),
1403                 ('BakerTaylorUsername','','','Baker & Taylor Username for Content Cafe (external content)','Textarea'),
1404                 ('TagsEnabled','1','','Enables or disables all tagging features.  This is the main switch for tags.','YesNo'),
1405                 ('TagsExternalDictionary',NULL,'','Path on server to local ispell executable, used to set $Lingua::Ispell::path  This dictionary is used as a \"whitelist\" of pre-allowed tags.',''),
1406                 ('TagsInputOnDetail','1','','Allow users to input tags from the detail page.',         'YesNo'),
1407                 ('TagsInputOnList',  '0','','Allow users to input tags from the search results list.', 'YesNo'),
1408                 ('TagsModeration',  NULL,'','Require tags from patrons to be approved before becoming visible.','YesNo'),
1409                 ('TagsShowOnDetail','10','','Number of tags to display on detail page.  0 is off.',        'Integer'),
1410                 ('TagsShowOnList',   '6','','Number of tags to display on search results list.  0 is off.','Integer')
1411         #);
1412         print "Upgrade to $DBversion done (Baker/Taylor,Tags: sysprefs and tables (tags_all, tags_index, tags_approval)) \n";
1413         SetVersion ($DBversion);
1414 }
1415
1416 $DBversion = "3.00.00.074";
1417 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1418     $dbh->do( q(update itemtypes set imageurl = concat( 'npl/', imageurl )
1419                   where imageurl not like 'http%'
1420                     and imageurl is not NULL
1421                     and imageurl != '') );
1422     print "Upgrade to $DBversion done (updating imagetype.imageurls to reflect new icon locations.)\n";
1423     SetVersion ($DBversion);
1424 }
1425
1426 $DBversion = "3.00.00.075";
1427 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1428     $dbh->do( q(alter table authorised_values add imageurl varchar(200) default NULL) );
1429     print "Upgrade to $DBversion done (adding imageurl field to authorised_values table)\n";
1430     SetVersion ($DBversion);
1431 }
1432
1433 $DBversion = "3.00.00.076";
1434 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1435     $dbh->do("ALTER TABLE import_batches
1436               ADD COLUMN nomatch_action enum('create_new', 'ignore') NOT NULL default 'create_new' AFTER overlay_action");
1437     $dbh->do("ALTER TABLE import_batches
1438               ADD COLUMN item_action enum('always_add', 'add_only_for_matches', 'add_only_for_new', 'ignore')
1439                   NOT NULL default 'always_add' AFTER nomatch_action");
1440     $dbh->do("ALTER TABLE import_batches
1441               MODIFY overlay_action  enum('replace', 'create_new', 'use_template', 'ignore')
1442                   NOT NULL default 'create_new'");
1443     $dbh->do("ALTER TABLE import_records
1444               MODIFY status  enum('error', 'staged', 'imported', 'reverted', 'items_reverted',
1445                                   'ignored') NOT NULL default 'staged'");
1446     $dbh->do("ALTER TABLE import_items
1447               MODIFY status enum('error', 'staged', 'imported', 'reverted', 'ignored') NOT NULL default 'staged'");
1448
1449         print "Upgrade to $DBversion done (changes to import_batches and import_records)\n";
1450         SetVersion ($DBversion);
1451 }
1452
1453 $DBversion = "3.00.00.077";
1454 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1455     # drop these tables only if they exist and none of them are empty
1456     # these tables are not defined in the packaged 2.2.9, but since it is believed
1457     # that at least one library may be using them in a post-2.2.9 but pre-3.0 Koha,
1458     # some care is taken.
1459     my ($print_error) = $dbh->{PrintError};
1460     $dbh->{PrintError} = 0;
1461     my ($raise_error) = $dbh->{RaiseError};
1462     $dbh->{RaiseError} = 1;
1463
1464     my $count = 0;
1465     my $do_drop = 1;
1466     eval { $count = $dbh->do("SELECT 1 FROM categorytable"); };
1467     if ($count > 0) {
1468         $do_drop = 0;
1469     }
1470     eval { $count = $dbh->do("SELECT 1 FROM mediatypetable"); };
1471     if ($count > 0) {
1472         $do_drop = 0;
1473     }
1474     eval { $count = $dbh->do("SELECT 1 FROM subcategorytable"); };
1475     if ($count > 0) {
1476         $do_drop = 0;
1477     }
1478
1479     if ($do_drop) {
1480         $dbh->do("DROP TABLE IF EXISTS `categorytable`");
1481         $dbh->do("DROP TABLE IF EXISTS `mediatypetable`");
1482         $dbh->do("DROP TABLE IF EXISTS `subcategorytable`");
1483     }
1484
1485     $dbh->{PrintError} = $print_error;
1486     $dbh->{RaiseError} = $raise_error;
1487         print "Upgrade to $DBversion done (drop categorytable, subcategorytable, and mediatypetable)\n";
1488         SetVersion ($DBversion);
1489 }
1490
1491 $DBversion = "3.00.00.078";
1492 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1493     my ($print_error) = $dbh->{PrintError};
1494     $dbh->{PrintError} = 0;
1495
1496     unless ($dbh->do("SELECT 1 FROM browser")) {
1497         $dbh->{PrintError} = $print_error;
1498         $dbh->do("CREATE TABLE `browser` (
1499                     `level` int(11) NOT NULL,
1500                     `classification` varchar(20) NOT NULL,
1501                     `description` varchar(255) NOT NULL,
1502                     `number` bigint(20) NOT NULL,
1503                     `endnode` tinyint(4) NOT NULL
1504                   ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1505     }
1506     $dbh->{PrintError} = $print_error;
1507         print "Upgrade to $DBversion done (add browser table if not already present)\n";
1508         SetVersion ($DBversion);
1509 }
1510
1511 $DBversion = "3.00.00.079";
1512 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1513  my ($print_error) = $dbh->{PrintError};
1514     $dbh->{PrintError} = 0;
1515
1516     $dbh->do("INSERT INTO `systempreferences` (variable, value,options,type, explanation)VALUES
1517         ('AddPatronLists','categorycode','categorycode|category_type','Choice','Allow user to choose what list to pick up from when adding patrons')");
1518     print "Upgrade to $DBversion done (add browser table if not already present)\n";
1519         SetVersion ($DBversion);
1520 }
1521
1522 $DBversion = "3.00.00.080";
1523 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1524     $dbh->do("ALTER TABLE subscription CHANGE monthlength monthlength int(11) default '0'");
1525     $dbh->do("ALTER TABLE deleteditems MODIFY marc LONGBLOB AFTER copynumber");
1526     $dbh->do("ALTER TABLE aqbooksellers CHANGE name name mediumtext NOT NULL");
1527         print "Upgrade to $DBversion done (catch up on DB schema changes since alpha and beta)\n";
1528         SetVersion ($DBversion);
1529 }
1530
1531 $DBversion = "3.00.00.081";
1532 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1533     $dbh->do("CREATE TABLE `borrower_attribute_types` (
1534                 `code` varchar(10) NOT NULL,
1535                 `description` varchar(255) NOT NULL,
1536                 `repeatable` tinyint(1) NOT NULL default 0,
1537                 `unique_id` tinyint(1) NOT NULL default 0,
1538                 `opac_display` tinyint(1) NOT NULL default 0,
1539                 `password_allowed` tinyint(1) NOT NULL default 0,
1540                 `staff_searchable` tinyint(1) NOT NULL default 0,
1541                 `authorised_value_category` varchar(10) default NULL,
1542                 PRIMARY KEY  (`code`)
1543               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1544     $dbh->do("CREATE TABLE `borrower_attributes` (
1545                 `borrowernumber` int(11) NOT NULL,
1546                 `code` varchar(10) NOT NULL,
1547                 `attribute` varchar(30) default NULL,
1548                 `password` varchar(30) default NULL,
1549                 KEY `borrowernumber` (`borrowernumber`),
1550                 KEY `code_attribute` (`code`, `attribute`),
1551                 CONSTRAINT `borrower_attributes_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1552                     ON DELETE CASCADE ON UPDATE CASCADE,
1553                 CONSTRAINT `borrower_attributes_ibfk_2` FOREIGN KEY (`code`) REFERENCES `borrower_attribute_types` (`code`)
1554                     ON DELETE CASCADE ON UPDATE CASCADE
1555             ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1556     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('ExtendedPatronAttributes','0','Use extended patron IDs and attributes',NULL,'YesNo')");
1557     print "Upgrade to $DBversion done (added borrower_attributes and  borrower_attribute_types)\n";
1558  SetVersion ($DBversion);
1559 }
1560
1561 $DBversion = "3.00.00.082";
1562 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1563     $dbh->do( q(alter table accountlines add column lastincrement decimal(28,6) default NULL) );
1564     print "Upgrade to $DBversion done (adding lastincrement column to accountlines table)\n";
1565     SetVersion ($DBversion);
1566 }
1567
1568 $DBversion = "3.00.00.083";
1569 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1570     $dbh->do( qq(UPDATE systempreferences SET value='local' where variable='yuipath' and value like "%/intranet-tmpl/prog/%"));
1571     print "Upgrade to $DBversion done (Changing yuipath behaviour in managing a local value)\n";
1572     SetVersion ($DBversion);
1573 }
1574 $DBversion = "3.00.00.084";
1575     if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1576     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('RenewSerialAddsSuggestion','0','if ON, adds a new suggestion at serial subscription renewal',NULL,'YesNo')");
1577     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('GoogleJackets','0','if ON, displays jacket covers from Google Books API',NULL,'YesNo')");
1578     print "Upgrade to $DBversion done (add new sysprefs)\n";
1579     SetVersion ($DBversion);
1580 }
1581
1582 $DBversion = "3.00.00.085";
1583 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1584     if (C4::Context->preference("marcflavour") eq 'MARC21') {
1585         $dbh->do("UPDATE marc_subfield_structure SET tab = 0 WHERE tab =  9 AND tagfield = '037'");
1586         $dbh->do("UPDATE marc_subfield_structure SET tab = 1 WHERE tab =  6 AND tagfield in ('100', '110', '111', '130')");
1587         $dbh->do("UPDATE marc_subfield_structure SET tab = 2 WHERE tab =  6 AND tagfield in ('240', '243')");
1588         $dbh->do("UPDATE marc_subfield_structure SET tab = 4 WHERE tab =  6 AND tagfield in ('400', '410', '411', '440')");
1589         $dbh->do("UPDATE marc_subfield_structure SET tab = 5 WHERE tab =  9 AND tagfield = '584'");
1590         $dbh->do("UPDATE marc_subfield_structure SET tab = 7 WHERE tab = -6 AND tagfield = '760'");
1591     }
1592     print "Upgrade to $DBversion done (move editing tab of various MARC21 subfields)\n";
1593     SetVersion ($DBversion);
1594 }
1595
1596 $DBversion = "3.00.00.086";
1597 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1598         $dbh->do(
1599         "CREATE TABLE `tmp_holdsqueue` (
1600         `biblionumber` int(11) default NULL,
1601         `itemnumber` int(11) default NULL,
1602         `barcode` varchar(20) default NULL,
1603         `surname` mediumtext NOT NULL,
1604         `firstname` text,
1605         `phone` text,
1606         `borrowernumber` int(11) NOT NULL,
1607         `cardnumber` varchar(16) default NULL,
1608         `reservedate` date default NULL,
1609         `title` mediumtext,
1610         `itemcallnumber` varchar(30) default NULL,
1611         `holdingbranch` varchar(10) default NULL,
1612         `pickbranch` varchar(10) default NULL,
1613         `notes` text
1614         ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1615
1616         $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('RandomizeHoldsQueueWeight','0','if ON, the holds queue in circulation will be randomized, either based on all location codes, or by the location codes specified in StaticHoldsQueueWeight',NULL,'YesNo')");
1617         $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('StaticHoldsQueueWeight','0','Specify a list of library location codes separated by commas -- the list of codes will be traversed and weighted with first values given higher weight for holds fulfillment -- alternatively, if RandomizeHoldsQueueWeight is set, the list will be randomly selective',NULL,'TextArea')");
1618
1619         print "Upgrade to $DBversion done (Table structure for table `tmp_holdsqueue`)\n";
1620         SetVersion ($DBversion);
1621 }
1622
1623 $DBversion = "3.00.00.087";
1624 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1625     $dbh->do("INSERT INTO `systempreferences` VALUES ('AutoEmailOpacUser','0','','Sends notification emails containing new account details to patrons - when account is created.','YesNo')" );
1626     $dbh->do("INSERT INTO `systempreferences` VALUES ('AutoEmailPrimaryAddress','OFF','email|emailpro|B_email|cardnumber|OFF','Defines the default email address where Account Details emails are sent.','Choice')");
1627     print "Upgrade to $DBversion done (added 2 new 'AutoEmailOpacUser' sysprefs)\n";
1628     SetVersion ($DBversion);
1629 }
1630
1631 $DBversion = "3.00.00.088";
1632 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1633         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('OPACShelfBrowser','1','','Enable/disable Shelf Browser on item details page','YesNo')");
1634         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('OPACItemHolds','1','Allow OPAC users to place hold on specific items. If OFF, users can only request next available copy.','','YesNo')");
1635         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('XSLTDetailsDisplay','0','','Enable XSL stylesheet control over details page display on OPAC WARNING: MARC21 Only','YesNo')");
1636         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('XSLTResultsDisplay','0','','Enable XSL stylesheet control over results page display on OPAC WARNING: MARC21 Only','YesNo')");
1637         print "Upgrade to $DBversion done (added 2 new 'AutoEmailOpacUser' sysprefs)\n";
1638     SetVersion ($DBversion);
1639 }
1640
1641 $DBversion = "3.00.00.089";
1642 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1643         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES('AdvancedSearchTypes','itemtypes','itemtypes|ccode','Select which set of fields comprise the Type limit in the advanced search','Choice')");
1644         print "Upgrade to $DBversion done (added new AdvancedSearchTypes syspref)\n";
1645     SetVersion ($DBversion);
1646 }
1647
1648 $DBversion = "3.00.00.090";
1649 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1650     $dbh->do("
1651         CREATE TABLE `branch_borrower_circ_rules` (
1652           `branchcode` VARCHAR(10) NOT NULL,
1653           `categorycode` VARCHAR(10) NOT NULL,
1654           `maxissueqty` int(4) default NULL,
1655           PRIMARY KEY (`categorycode`, `branchcode`),
1656           CONSTRAINT `branch_borrower_circ_rules_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
1657             ON DELETE CASCADE ON UPDATE CASCADE,
1658           CONSTRAINT `branch_borrower_circ_rules_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`)
1659             ON DELETE CASCADE ON UPDATE CASCADE
1660         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1661     ");
1662     $dbh->do("
1663         CREATE TABLE `default_borrower_circ_rules` (
1664           `categorycode` VARCHAR(10) NOT NULL,
1665           `maxissueqty` int(4) default NULL,
1666           PRIMARY KEY (`categorycode`),
1667           CONSTRAINT `borrower_borrower_circ_rules_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
1668             ON DELETE CASCADE ON UPDATE CASCADE
1669         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1670     ");
1671     $dbh->do("
1672         CREATE TABLE `default_branch_circ_rules` (
1673           `branchcode` VARCHAR(10) NOT NULL,
1674           `maxissueqty` int(4) default NULL,
1675           PRIMARY KEY (`branchcode`),
1676           CONSTRAINT `default_branch_circ_rules_ibfk_1` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`)
1677             ON DELETE CASCADE ON UPDATE CASCADE
1678         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1679     ");
1680     $dbh->do("
1681         CREATE TABLE `default_circ_rules` (
1682             `singleton` enum('singleton') NOT NULL default 'singleton',
1683             `maxissueqty` int(4) default NULL,
1684             PRIMARY KEY (`singleton`)
1685         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1686     ");
1687     print "Upgrade to $DBversion done (added several circ rules tables)\n";
1688     SetVersion ($DBversion);
1689 }
1690
1691
1692 $DBversion = "3.00.00.091";
1693 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1694     $dbh->do(<<'END_SQL');
1695 ALTER TABLE borrowers
1696 ADD `smsalertnumber` varchar(50) default NULL
1697 END_SQL
1698
1699     $dbh->do(<<'END_SQL');
1700 CREATE TABLE `message_attributes` (
1701   `message_attribute_id` int(11) NOT NULL auto_increment,
1702   `message_name` varchar(20) NOT NULL default '',
1703   `takes_days` tinyint(1) NOT NULL default '0',
1704   PRIMARY KEY  (`message_attribute_id`),
1705   UNIQUE KEY `message_name` (`message_name`)
1706 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1707 END_SQL
1708
1709     $dbh->do(<<'END_SQL');
1710 CREATE TABLE `message_transport_types` (
1711   `message_transport_type` varchar(20) NOT NULL,
1712   PRIMARY KEY  (`message_transport_type`)
1713 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1714 END_SQL
1715
1716     $dbh->do(<<'END_SQL');
1717 CREATE TABLE `message_transports` (
1718   `message_attribute_id` int(11) NOT NULL,
1719   `message_transport_type` varchar(20) NOT NULL,
1720   `is_digest` tinyint(1) NOT NULL default '0',
1721   `letter_module` varchar(20) NOT NULL default '',
1722   `letter_code` varchar(20) NOT NULL default '',
1723   PRIMARY KEY  (`message_attribute_id`,`message_transport_type`,`is_digest`),
1724   KEY `message_transport_type` (`message_transport_type`),
1725   KEY `letter_module` (`letter_module`,`letter_code`),
1726   CONSTRAINT `message_transports_ibfk_1` FOREIGN KEY (`message_attribute_id`) REFERENCES `message_attributes` (`message_attribute_id`) ON DELETE CASCADE ON UPDATE CASCADE,
1727   CONSTRAINT `message_transports_ibfk_2` FOREIGN KEY (`message_transport_type`) REFERENCES `message_transport_types` (`message_transport_type`) ON DELETE CASCADE ON UPDATE CASCADE,
1728   CONSTRAINT `message_transports_ibfk_3` FOREIGN KEY (`letter_module`, `letter_code`) REFERENCES `letter` (`module`, `code`) ON DELETE CASCADE ON UPDATE CASCADE
1729 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1730 END_SQL
1731
1732     $dbh->do(<<'END_SQL');
1733 CREATE TABLE `borrower_message_preferences` (
1734   `borrower_message_preference_id` int(11) NOT NULL auto_increment,
1735   `borrowernumber` int(11) NOT NULL default '0',
1736   `message_attribute_id` int(11) default '0',
1737   `days_in_advance` int(11) default '0',
1738   `wants_digets` tinyint(1) NOT NULL default '0',
1739   PRIMARY KEY  (`borrower_message_preference_id`),
1740   KEY `borrowernumber` (`borrowernumber`),
1741   KEY `message_attribute_id` (`message_attribute_id`),
1742   CONSTRAINT `borrower_message_preferences_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1743   CONSTRAINT `borrower_message_preferences_ibfk_2` FOREIGN KEY (`message_attribute_id`) REFERENCES `message_attributes` (`message_attribute_id`) ON DELETE CASCADE ON UPDATE CASCADE
1744 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1745 END_SQL
1746
1747     $dbh->do(<<'END_SQL');
1748 CREATE TABLE `borrower_message_transport_preferences` (
1749   `borrower_message_preference_id` int(11) NOT NULL default '0',
1750   `message_transport_type` varchar(20) NOT NULL default '0',
1751   PRIMARY KEY  (`borrower_message_preference_id`,`message_transport_type`),
1752   KEY `message_transport_type` (`message_transport_type`),
1753   CONSTRAINT `borrower_message_transport_preferences_ibfk_1` FOREIGN KEY (`borrower_message_preference_id`) REFERENCES `borrower_message_preferences` (`borrower_message_preference_id`) ON DELETE CASCADE ON UPDATE CASCADE,
1754   CONSTRAINT `borrower_message_transport_preferences_ibfk_2` FOREIGN KEY (`message_transport_type`) REFERENCES `message_transport_types` (`message_transport_type`) ON DELETE CASCADE ON UPDATE CASCADE
1755 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1756 END_SQL
1757
1758     $dbh->do(<<'END_SQL');
1759 CREATE TABLE `message_queue` (
1760   `message_id` int(11) NOT NULL auto_increment,
1761   `borrowernumber` int(11) NOT NULL,
1762   `subject` text,
1763   `content` text,
1764   `message_transport_type` varchar(20) NOT NULL,
1765   `status` enum('sent','pending','failed','deleted') NOT NULL default 'pending',
1766   `time_queued` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1767   KEY `message_id` (`message_id`),
1768   KEY `borrowernumber` (`borrowernumber`),
1769   KEY `message_transport_type` (`message_transport_type`),
1770   CONSTRAINT `messageq_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1771   CONSTRAINT `messageq_ibfk_2` FOREIGN KEY (`message_transport_type`) REFERENCES `message_transport_types` (`message_transport_type`) ON DELETE RESTRICT ON UPDATE CASCADE
1772 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1773 END_SQL
1774
1775     $dbh->do(<<'END_SQL');
1776 INSERT INTO `systempreferences`
1777   (variable,value,explanation,options,type)
1778 VALUES
1779 ('EnhancedMessagingPreferences',0,'If ON, allows patrons to select to receive additional messages about items due or nearly due.','','YesNo')
1780 END_SQL
1781
1782     $dbh->do( <<'END_SQL');
1783 INSERT INTO `letter`
1784 (module, code, name, title, content)
1785 VALUES
1786 ('circulation','DUE','Item Due Reminder','Item Due Reminder','Dear <<borrowers.firstname>> <<borrowers.surname>>,\r\n\r\nThe following item is now due:\r\n\r\n<<biblio.title>> by <<biblio.author>>'),
1787 ('circulation','DUEDGST','Item Due Reminder (Digest)','Item Due Reminder','You have <<count>> items due'),
1788 ('circulation','PREDUE','Advance Notice of Item Due','Advance Notice of Item Due','Dear <<borrowers.firstname>> <<borrowers.surname>>,\r\n\r\nThe following item will be due soon:\r\n\r\n<<biblio.title>> by <<biblio.author>>'),
1789 ('circulation','PREDUEDGST','Advance Notice of Item Due (Digest)','Advance Notice of Item Due','You have <<count>> items due soon'),
1790 ('circulation','EVENT','Upcoming Library Event','Upcoming Library Event','Dear <<borrowers.firstname>> <<borrowers.surname>>,\r\n\r\nThis is a reminder of an upcoming library event in which you have expressed interest.');
1791 END_SQL
1792
1793     my @sql_scripts = (
1794         'installer/data/mysql/en/mandatory/message_transport_types.sql',
1795         'installer/data/mysql/en/optional/sample_notices_message_attributes.sql',
1796         'installer/data/mysql/en/optional/sample_notices_message_transports.sql',
1797     );
1798
1799     my $installer = C4::Installer->new();
1800     foreach my $script ( @sql_scripts ) {
1801         my $full_path = $installer->get_file_path_from_name($script);
1802         my $error = $installer->load_sql($full_path);
1803         warn $error if $error;
1804     }
1805
1806     print "Upgrade to $DBversion done (Table structure for table `message_queue`, `message_transport_types`, `message_attributes`, `message_transports`, `borrower_message_preferences`, and `borrower_message_transport_preferences`.  Alter `borrowers` table,\n";
1807     SetVersion ($DBversion);
1808 }
1809
1810 $DBversion = "3.00.00.092";
1811 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1812     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES('AllowOnShelfHolds', '0', '', 'Allow hold requests to be placed on items that are not on loan', 'YesNo')");
1813     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES('AllowHoldsOnDamagedItems', '1', '', 'Allow hold requests to be placed on damaged items', 'YesNo')");
1814         print "Upgrade to $DBversion done (added new AllowOnShelfHolds syspref)\n";
1815     SetVersion ($DBversion);
1816 }
1817
1818 $DBversion = "3.00.00.093";
1819 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1820     $dbh->do("ALTER TABLE `items` MODIFY COLUMN `copynumber` VARCHAR(32) DEFAULT NULL");
1821     $dbh->do("ALTER TABLE `deleteditems` MODIFY COLUMN `copynumber` VARCHAR(32) DEFAULT NULL");
1822         print "Upgrade to $DBversion done (Change data type of items.copynumber to allow free text)\n";
1823     SetVersion ($DBversion);
1824 }
1825
1826 $DBversion = "3.00.00.094";
1827 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1828     $dbh->do("ALTER TABLE `marc_subfield_structure` MODIFY `tagsubfield` VARCHAR(1) NOT NULL DEFAULT '' COLLATE utf8_bin");
1829         print "Upgrade to $DBversion done (Change Collation of marc_subfield_structure to allow mixed case in subfield labels.)\n";
1830     SetVersion ($DBversion);
1831 }
1832
1833 $DBversion = "3.00.00.095";
1834 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1835     if (C4::Context->preference("marcflavour") eq 'MARC21') {
1836         $dbh->do("UPDATE marc_subfield_structure SET authtypecode = 'MEETI_NAME' WHERE authtypecode = 'Meeting Name'");
1837         $dbh->do("UPDATE marc_subfield_structure SET authtypecode = 'CORPO_NAME' WHERE authtypecode = 'CORP0_NAME'");
1838     }
1839         print "Upgrade to $DBversion done (fix invalid authority types in MARC21 frameworks [bug 2254])\n";
1840     SetVersion ($DBversion);
1841 }
1842
1843 $DBversion = "3.00.00.096";
1844 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1845     $sth = $dbh->prepare("SHOW COLUMNS FROM borrower_message_preferences LIKE 'wants_digets'");
1846     $sth->execute();
1847     if (my $row = $sth->fetchrow_hashref) {
1848         $dbh->do("ALTER TABLE borrower_message_preferences CHANGE wants_digets wants_digest tinyint(1) NOT NULL default 0");
1849     }
1850         print "Upgrade to $DBversion done (fix name borrower_message_preferences.wants_digest)\n";
1851     SetVersion ($DBversion);
1852 }
1853
1854 $DBversion = '3.00.00.097';
1855 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1856
1857     $dbh->do('ALTER TABLE message_queue ADD to_address   mediumtext default NULL');
1858     $dbh->do('ALTER TABLE message_queue ADD from_address mediumtext default NULL');
1859     $dbh->do('ALTER TABLE message_queue ADD content_type text');
1860     $dbh->do('ALTER TABLE message_queue CHANGE borrowernumber borrowernumber int(11) default NULL');
1861
1862     print "Upgrade to $DBversion done (updating 4 fields in message_queue table)\n";
1863     SetVersion($DBversion);
1864 }
1865
1866 $DBversion = '3.00.00.098';
1867 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1868
1869     $dbh->do(q(DELETE FROM message_transport_types WHERE message_transport_type = 'rss'));
1870     $dbh->do(q(DELETE FROM message_transports WHERE message_transport_type = 'rss'));
1871
1872     print "Upgrade to $DBversion done (removing unused RSS message_transport_type)\n";
1873     SetVersion($DBversion);
1874 }
1875
1876 $DBversion = '3.00.00.099';
1877 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1878     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('OpacSuppression', '0', '', 'Turn ON the OPAC Suppression feature, requires further setup, ask your system administrator for details', 'YesNo')");
1879     print "Upgrade to $DBversion done (Adding OpacSuppression syspref)\n";
1880     SetVersion($DBversion);
1881 }
1882
1883 $DBversion = '3.00.00.100';
1884 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1885         $dbh->do('ALTER TABLE virtualshelves ADD COLUMN lastmodified timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP');
1886     print "Upgrade to $DBversion done (Adding lastmodified column to virtualshelves)\n";
1887     SetVersion($DBversion);
1888 }
1889
1890 $DBversion = '3.00.00.101';
1891 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1892         $dbh->do('ALTER TABLE `overduerules` CHANGE `categorycode` `categorycode` VARCHAR(10) NOT NULL');
1893         $dbh->do('ALTER TABLE `deletedborrowers` CHANGE `categorycode` `categorycode` VARCHAR(10) NOT NULL');
1894     print "Upgrade to $DBversion done (Updating columnd definitions for patron category codes in notice/statsu triggers and deletedborrowers tables.)\n";
1895     SetVersion($DBversion);
1896 }
1897
1898 $DBversion = '3.00.00.102';
1899 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1900         $dbh->do('ALTER TABLE serialitems MODIFY `serialid` int(11) NOT NULL AFTER itemnumber' );
1901         $dbh->do('ALTER TABLE serialitems DROP KEY serialididx' );
1902         $dbh->do('ALTER TABLE serialitems ADD CONSTRAINT UNIQUE KEY serialitemsidx (itemnumber)' );
1903         # before setting constraint, delete any unvalid data
1904         $dbh->do('DELETE from serialitems WHERE serialid not in (SELECT serial.serialid FROM serial)');
1905         $dbh->do('ALTER TABLE serialitems ADD CONSTRAINT serialitems_sfk_1 FOREIGN KEY (serialid) REFERENCES serial (serialid) ON DELETE CASCADE ON UPDATE CASCADE' );
1906     print "Upgrade to $DBversion done (Updating serialitems table to allow for multiple items per serial fixing kohabug 2380)\n";
1907     SetVersion($DBversion);
1908 }
1909
1910 $DBversion = "3.00.00.103";
1911 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1912     $dbh->do("DELETE FROM systempreferences WHERE variable='serialsadditems'");
1913     print "Upgrade to $DBversion done ( Verifying the removal of serialsadditems from syspref fixing kohabug 2219)\n";
1914     SetVersion ($DBversion);
1915 }
1916
1917 $DBversion = "3.00.00.104";
1918 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1919     $dbh->do("DELETE FROM systempreferences WHERE variable='noOPACHolds'");
1920     print "Upgrade to $DBversion done (remove superseded 'noOPACHolds' system preference per bug 2413)\n";
1921     SetVersion ($DBversion);
1922 }
1923
1924 $DBversion = '3.00.00.105';
1925 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
1926
1927     # it is possible that this syspref is already defined since the feature was added some time ago.
1928     unless ( $dbh->do(q(SELECT variable FROM systempreferences WHERE variable = 'SMSSendDriver')) ) {
1929         $dbh->do(<<'END_SQL');
1930 INSERT INTO `systempreferences`
1931   (variable,value,explanation,options,type)
1932 VALUES
1933 ('SMSSendDriver','','Sets which SMS::Send driver is used to send SMS messages.','','free')
1934 END_SQL
1935     }
1936     print "Upgrade to $DBversion done (added SMSSendDriver system preference)\n";
1937     SetVersion($DBversion);
1938 }
1939
1940 $DBversion = "3.00.00.106";
1941 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1942     $dbh->do("DELETE FROM systempreferences WHERE variable='noOPACHolds'");
1943
1944 # db revision 105 didn't apply correctly, so we're rolling this into 106
1945         $dbh->do("INSERT INTO `systempreferences`
1946    (variable,value,explanation,options,type)
1947         VALUES
1948         ('SMSSendDriver','','Sets which SMS::Send driver is used to send SMS messages.','','free')");
1949
1950     print "Upgrade to $DBversion done (remove default '0000-00-00' in subscriptionhistory.enddate field)\n";
1951     $dbh->do("ALTER TABLE `subscriptionhistory` CHANGE `enddate` `enddate` DATE NULL DEFAULT NULL ");
1952     $dbh->do("UPDATE subscriptionhistory SET enddate=NULL WHERE enddate='0000-00-00'");
1953     SetVersion ($DBversion);
1954 }
1955
1956 $DBversion = '3.00.00.107';
1957 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1958     $dbh->do(<<'END_SQL');
1959 UPDATE systempreferences
1960   SET explanation = CONCAT( explanation, '. WARNING: this feature is very resource consuming on collections with large numbers of items.' )
1961   WHERE variable = 'OPACShelfBrowser'
1962     AND explanation NOT LIKE '%WARNING%'
1963 END_SQL
1964     $dbh->do(<<'END_SQL');
1965 UPDATE systempreferences
1966   SET explanation = CONCAT( explanation, '. WARNING: this feature is very resource consuming.' )
1967   WHERE variable = 'CataloguingLog'
1968     AND explanation NOT LIKE '%WARNING%'
1969 END_SQL
1970     $dbh->do(<<'END_SQL');
1971 UPDATE systempreferences
1972   SET explanation = CONCAT( explanation, '. WARNING: using NoZebra on even modest sized collections is very slow.' )
1973   WHERE variable = 'NoZebra'
1974     AND explanation NOT LIKE '%WARNING%'
1975 END_SQL
1976     print "Upgrade to $DBversion done (warning added to OPACShelfBrowser system preference)\n";
1977     SetVersion ($DBversion);
1978 }
1979
1980 $DBversion = '3.01.00.000';
1981 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1982     print "Upgrade to $DBversion done (start of 3.1)\n";
1983     SetVersion ($DBversion);
1984 }
1985
1986 $DBversion = '3.01.00.001';
1987 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1988     $dbh->do("
1989         CREATE TABLE hold_fill_targets (
1990             `borrowernumber` int(11) NOT NULL,
1991             `biblionumber` int(11) NOT NULL,
1992             `itemnumber` int(11) NOT NULL,
1993             `source_branchcode`  varchar(10) default NULL,
1994             `item_level_request` tinyint(4) NOT NULL default 0,
1995             PRIMARY KEY `itemnumber` (`itemnumber`),
1996             KEY `bib_branch` (`biblionumber`, `source_branchcode`),
1997             CONSTRAINT `hold_fill_targets_ibfk_1` FOREIGN KEY (`borrowernumber`)
1998                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1999             CONSTRAINT `hold_fill_targets_ibfk_2` FOREIGN KEY (`biblionumber`)
2000                 REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
2001             CONSTRAINT `hold_fill_targets_ibfk_3` FOREIGN KEY (`itemnumber`)
2002                 REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
2003             CONSTRAINT `hold_fill_targets_ibfk_4` FOREIGN KEY (`source_branchcode`)
2004                 REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
2005         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2006     ");
2007     $dbh->do("
2008         ALTER TABLE tmp_holdsqueue
2009             ADD item_level_request tinyint(4) NOT NULL default 0
2010     ");
2011
2012     print "Upgrade to $DBversion done (add hold_fill_targets table and a column to tmp_holdsqueue)\n";
2013     SetVersion($DBversion);
2014 }
2015
2016 $DBversion = '3.01.00.002';
2017 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2018     # use statistics where available
2019     $dbh->do("
2020         ALTER TABLE statistics ADD KEY  tmp_stats (type, itemnumber, borrowernumber)
2021     ");
2022     $dbh->do("
2023         UPDATE issues iss
2024         SET issuedate = (
2025             SELECT max(datetime)
2026             FROM statistics
2027             WHERE type = 'issue'
2028             AND itemnumber = iss.itemnumber
2029             AND borrowernumber = iss.borrowernumber
2030         )
2031         WHERE issuedate IS NULL;
2032     ");
2033     $dbh->do("ALTER TABLE statistics DROP KEY tmp_stats");
2034
2035     # default to last renewal date
2036     $dbh->do("
2037         UPDATE issues
2038         SET issuedate = lastreneweddate
2039         WHERE issuedate IS NULL
2040         and lastreneweddate IS NOT NULL
2041     ");
2042
2043     my $num_bad_issuedates = $dbh->selectrow_array("SELECT COUNT(*) FROM issues WHERE issuedate IS NULL");
2044     if ($num_bad_issuedates > 0) {
2045         print STDERR "After the upgrade to $DBversion, there are still $num_bad_issuedates loan(s) with a NULL (blank) loan date. ",
2046                      "Please check the issues table in your database.";
2047     }
2048     print "Upgrade to $DBversion done (bug 2582: set null issues.issuedate to lastreneweddate)\n";
2049     SetVersion($DBversion);
2050 }
2051
2052 $DBversion = "3.01.00.003";
2053 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2054     $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')");
2055     print "Upgrade to $DBversion done (add new syspref)\n";
2056     SetVersion ($DBversion);
2057 }
2058
2059 $DBversion = '3.01.00.004';
2060 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2061     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACDisplayRequestPriority','0','Show patrons the priority level on holds in the OPAC','','YesNo')");
2062     print "Upgrade to $DBversion done (added OPACDisplayRequestPriority system preference)\n";
2063     SetVersion ($DBversion);
2064 }
2065
2066 $DBversion = '3.01.00.005';
2067 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2068     $dbh->do("
2069         INSERT INTO `letter` (module, code, name, title, content)
2070         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>>')
2071     ");
2072     $dbh->do("INSERT INTO `message_attributes` (message_attribute_id, message_name, takes_days) values(4, 'Hold Filled', 0)");
2073     $dbh->do("INSERT INTO `message_transports` (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) values(4, 'sms', 0, 'reserves', 'HOLD')");
2074     $dbh->do("INSERT INTO `message_transports` (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) values(4, 'email', 0, 'reserves', 'HOLD')");
2075     print "Upgrade to $DBversion done (Add letter for holds notifications)\n";
2076     SetVersion ($DBversion);
2077 }
2078
2079 $DBversion = '3.01.00.006';
2080 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2081     $dbh->do("ALTER TABLE `biblioitems` ADD KEY issn (issn)");
2082     print "Upgrade to $DBversion done (add index on biblioitems.issn)\n";
2083     SetVersion ($DBversion);
2084 }
2085
2086 $DBversion = "3.01.00.007";
2087 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2088     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='intranetmainUserblock'");
2089     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='intranetuserjs'");
2090     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='opacheader'");
2091     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='OpacMainUserBlock'");
2092     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='OpacNav'");
2093     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='opacuserjs'");
2094     $dbh->do("UPDATE `systempreferences` SET options='30|10', type='Textarea' WHERE variable='OAI-PMH:Set'");
2095     $dbh->do("UPDATE `systempreferences` SET options='50' WHERE variable='intranetstylesheet'");
2096     $dbh->do("UPDATE `systempreferences` SET options='50' WHERE variable='intranetcolorstylesheet'");
2097     $dbh->do("UPDATE `systempreferences` SET options='10' WHERE variable='globalDueDate'");
2098     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='numSearchResults'");
2099     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='OPACnumSearchResults'");
2100     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='ReservesMaxPickupDelay'");
2101     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='TransfersMaxDaysWarning'");
2102     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='StaticHoldsQueueWeight'");
2103     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='holdCancelLength'");
2104     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='XISBNDailyLimit'");
2105     $dbh->do("UPDATE `systempreferences` SET type='Float' WHERE variable='gist'");
2106     $dbh->do("UPDATE `systempreferences` SET type='Free' WHERE variable='BakerTaylorUsername'");
2107     $dbh->do("UPDATE `systempreferences` SET type='Free' WHERE variable='BakerTaylorPassword'");
2108     $dbh->do("UPDATE `systempreferences` SET type='Textarea', options='70|10' WHERE variable='ISBD'");
2109     $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'");
2110     print "Upgrade to $DBversion done (fix display of many sysprefs)\n";
2111     SetVersion ($DBversion);
2112 }
2113
2114 $DBversion = '3.01.00.008';
2115 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2116
2117     $dbh->do("CREATE TABLE branch_transfer_limits (
2118                           limitId int(8) NOT NULL auto_increment,
2119                           toBranch varchar(4) NOT NULL,
2120                           fromBranch varchar(4) NOT NULL,
2121                           itemtype varchar(4) NOT NULL,
2122                           PRIMARY KEY  (limitId)
2123                           ) ENGINE=InnoDB DEFAULT CHARSET=utf8"
2124                         );
2125
2126     $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')");
2127
2128     print "Upgrade to $DBversion done (added branch_transfer_limits table and UseBranchTransferLimits system preference)\n";
2129     SetVersion ($DBversion);
2130 }
2131
2132 $DBversion = "3.01.00.009";
2133 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2134     $dbh->do("ALTER TABLE permissions MODIFY `code` varchar(64) DEFAULT NULL");
2135     $dbh->do("ALTER TABLE user_permissions MODIFY `code` varchar(64) DEFAULT NULL");
2136     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'circulate_remaining_permissions', 'Remaining circulation permissions')");
2137     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'override_renewals', 'Override blocked renewals')");
2138     print "Upgrade to $DBversion done (added subpermissions for circulate permission)\n";
2139 }
2140
2141 $DBversion = '3.01.00.010';
2142 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2143     $dbh->do("ALTER TABLE `borrower_attributes` MODIFY COLUMN `attribute` VARCHAR(64) DEFAULT NULL");
2144     $dbh->do("ALTER TABLE `borrower_attributes` MODIFY COLUMN `password` VARCHAR(64) DEFAULT NULL");
2145     print "Upgrade to $DBversion done (bug 2687: increase length of borrower attribute fields)\n";
2146     SetVersion ($DBversion);
2147 }
2148
2149 $DBversion = '3.01.00.011';
2150 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2151
2152     # Yes, the old value was ^M terminated.
2153     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);";
2154
2155     my $intranetuserjs = C4::Context->preference('intranetuserjs');
2156     if ($intranetuserjs  and  $intranetuserjs eq $bad_value) {
2157         my $sql = <<'END_SQL';
2158 UPDATE systempreferences
2159 SET value = ''
2160 WHERE variable = 'intranetuserjs'
2161 END_SQL
2162         $dbh->do($sql);
2163     }
2164     print "Upgrade to $DBversion done (removed bogus intranetuserjs syspref)\n";
2165     SetVersion($DBversion);
2166 }
2167
2168 $DBversion = "3.01.00.012";
2169 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2170     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowHoldPolicyOverride', '0', 'Allow staff to override hold policies when placing holds',NULL,'YesNo')");
2171     $dbh->do("
2172         CREATE TABLE `branch_item_rules` (
2173           `branchcode` varchar(10) NOT NULL,
2174           `itemtype` varchar(10) NOT NULL,
2175           `holdallowed` tinyint(1) default NULL,
2176           PRIMARY KEY  (`itemtype`,`branchcode`),
2177           KEY `branch_item_rules_ibfk_2` (`branchcode`),
2178           CONSTRAINT `branch_item_rules_ibfk_1` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE,
2179           CONSTRAINT `branch_item_rules_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
2180         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2181     ");
2182     $dbh->do("
2183         CREATE TABLE `default_branch_item_rules` (
2184           `itemtype` varchar(10) NOT NULL,
2185           `holdallowed` tinyint(1) default NULL,
2186           PRIMARY KEY  (`itemtype`),
2187           CONSTRAINT `default_branch_item_rules_ibfk_1` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE
2188         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2189     ");
2190     $dbh->do("
2191         ALTER TABLE default_branch_circ_rules
2192             ADD COLUMN holdallowed tinyint(1) NULL
2193     ");
2194     $dbh->do("
2195         ALTER TABLE default_circ_rules
2196             ADD COLUMN holdallowed tinyint(1) NULL
2197     ");
2198     print "Upgrade to $DBversion done (Add tables and system preferences for holds policies)\n";
2199     SetVersion ($DBversion);
2200 }
2201
2202 $DBversion = '3.01.00.013';
2203 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2204     $dbh->do("
2205         CREATE TABLE item_circulation_alert_preferences (
2206             id           int(11) AUTO_INCREMENT,
2207             branchcode   varchar(10) NOT NULL,
2208             categorycode varchar(10) NOT NULL,
2209             item_type    varchar(10) NOT NULL,
2210             notification varchar(16) NOT NULL,
2211             PRIMARY KEY (id),
2212             KEY (branchcode, categorycode, item_type, notification)
2213         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2214     ");
2215
2216     $dbh->do(q{ ALTER TABLE `message_queue` ADD metadata text DEFAULT NULL           AFTER content;  });
2217     $dbh->do(q{ ALTER TABLE `message_queue` ADD letter_code varchar(64) DEFAULT NULL AFTER metadata; });
2218
2219     $dbh->do(q{
2220         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
2221         ('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.');
2222     });
2223     $dbh->do(q{
2224         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
2225         ('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>>.');
2226     });
2227
2228     $dbh->do(q{INSERT INTO message_attributes (message_attribute_id, message_name, takes_days) VALUES (5, 'Item Check-in', 0);});
2229     $dbh->do(q{INSERT INTO message_attributes (message_attribute_id, message_name, takes_days) VALUES (6, 'Item Checkout', 0);});
2230
2231     $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');});
2232     $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');});
2233     $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');});
2234     $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');});
2235
2236     print "Upgrade to $DBversion done (data for Email Checkout Slips project)\n";
2237          SetVersion ($DBversion);
2238 }
2239
2240 $DBversion = "3.01.00.014";
2241 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2242     $dbh->do("ALTER TABLE `branch_transfer_limits` CHANGE `itemtype` `itemtype` VARCHAR( 4 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL");
2243     $dbh->do("ALTER TABLE `branch_transfer_limits` ADD `ccode` VARCHAR( 10 ) NULL ;");
2244     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2245     VALUES (
2246     'BranchTransferLimitsType', 'ccode', 'itemtype|ccode', 'When using branch transfer limits, choose whether to limit by itemtype or collection code.', 'Choice'
2247     );");
2248
2249     print "Upgrade to $DBversion done ( Updated table for Branch Transfer Limits)\n";
2250     SetVersion ($DBversion);
2251 }
2252
2253 $DBversion = '3.01.00.015';
2254 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2255     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsClientCode', '0', 'Client Code for using Syndetics Solutions content','','free')");
2256
2257     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsEnabled', '0', 'Turn on Syndetics Enhanced Content','','YesNo')");
2258
2259     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsCoverImages', '0', 'Display Cover Images from Syndetics','','YesNo')");
2260
2261     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsTOC', '0', 'Display Table of Content information from Syndetics','','YesNo')");
2262
2263     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsSummary', '0', 'Display Summary Information from Syndetics','','YesNo')");
2264
2265     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsEditions', '0', 'Display Editions from Syndetics','','YesNo')");
2266
2267     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsExcerpt', '0', 'Display Excerpts and first chapters on OPAC from Syndetics','','YesNo')");
2268
2269     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsReviews', '0', 'Display Reviews on OPAC from Syndetics','','YesNo')");
2270
2271     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsAuthorNotes', '0', 'Display Notes about the Author on OPAC from Syndetics','','YesNo')");
2272
2273     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsAwards', '0', 'Display Awards on OPAC from Syndetics','','YesNo')");
2274
2275     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsSeries', '0', 'Display Series information on OPAC from Syndetics','','YesNo')");
2276
2277     $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')");
2278
2279     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAmazonCoverImages', '0', 'Display cover images on OPAC from Amazon Web Services','','YesNo')");
2280
2281     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AmazonCoverImages', '0', 'Display Cover Images in Staff Client from Amazon Web Services','','YesNo')");
2282
2283     $dbh->do("UPDATE systempreferences SET variable='AmazonEnabled' WHERE variable = 'AmazonContent'");
2284
2285     $dbh->do("UPDATE systempreferences SET variable='OPACAmazonEnabled' WHERE variable = 'OPACAmazonContent'");
2286
2287     print "Upgrade to $DBversion done (added Syndetics Enhanced Content system preferences)\n";
2288     SetVersion ($DBversion);
2289 }
2290
2291 $DBversion = "3.01.00.016";
2292 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2293     $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')");
2294     print "Upgrade to $DBversion done (Added Babeltheque syspref)\n";
2295     SetVersion ($DBversion);
2296 }
2297
2298 $DBversion = "3.01.00.017";
2299 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2300     $dbh->do("ALTER TABLE `subscription` ADD `staffdisplaycount` VARCHAR(10) NULL;");
2301     $dbh->do("ALTER TABLE `subscription` ADD `opacdisplaycount` VARCHAR(10) NULL;");
2302     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2303     VALUES (
2304     'StaffSerialIssueDisplayCount', '3', '', 'Number of serial issues to display per subscription in the Staff client', 'Integer'
2305     );");
2306         $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2307     VALUES (
2308     'OPACSerialIssueDisplayCount', '3', '', 'Number of serial issues to display per subscription in the OPAC', 'Integer'
2309     );");
2310
2311     print "Upgrade to $DBversion done ( Updated table for Serials Display)\n";
2312     SetVersion ($DBversion);
2313 }
2314
2315 $DBversion = "3.01.00.018";
2316 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2317     $dbh->do("ALTER TABLE deletedborrowers ADD `smsalertnumber` varchar(50) default NULL");
2318     print "Upgrade to $DBversion done (added deletedborrowers.smsalertnumber, missed in 3.00.00.091)\n";
2319     SetVersion ($DBversion);
2320 }
2321
2322 $DBversion = "3.01.00.019";
2323 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2324         $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')");
2325     print "Upgrade to $DBversion done (adding OPACShowCheckoutName systempref)\n";
2326     SetVersion ($DBversion);
2327 }
2328
2329 $DBversion = "3.01.00.020";
2330 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2331     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesID','','See:http://librarything.com/forlibraries/','','free')");
2332     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesEnabled','0','Enable or Disable Library Thing for Libraries Features','','YesNo')");
2333     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesTabbedView','0','Put LibraryThingForLibraries Content in Tabs.','','YesNo')");
2334     print "Upgrade to $DBversion done (adding LibraryThing for Libraries sysprefs)\n";
2335     SetVersion ($DBversion);
2336 }
2337
2338 $DBversion = "3.01.00.021";
2339 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2340     my $enable_reviews = C4::Context->preference('OPACAmazonEnabled') ? '1' : '0';
2341     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAmazonReviews', '$enable_reviews', 'Display Amazon readers reviews on OPAC','','YesNo')");
2342     print "Upgrade to $DBversion done (adding OPACAmazonReviews syspref)\n";
2343     SetVersion ($DBversion);
2344 }
2345
2346 $DBversion = '3.01.00.022';
2347 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2348     $dbh->do("ALTER TABLE `labels_conf` MODIFY COLUMN `formatstring` mediumtext DEFAULT NULL");
2349     print "Upgrade to $DBversion done (bug 2945: increase size of labels_conf.formatstring)\n";
2350     SetVersion ($DBversion);
2351 }
2352
2353 $DBversion = '3.01.00.023';
2354 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2355     $dbh->do("ALTER TABLE biblioitems        MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2356     $dbh->do("ALTER TABLE deletedbiblioitems MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2357     $dbh->do("ALTER TABLE import_biblios     MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2358     $dbh->do("ALTER TABLE suggestions        MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2359     print "Upgrade to $DBversion done (bug 2765: increase width of isbn column in several tables)\n";
2360     SetVersion ($DBversion);
2361 }
2362
2363 $DBversion = "3.01.00.024";
2364 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2365     $dbh->do("ALTER TABLE labels MODIFY COLUMN batch_id int(10) NOT NULL default 1;");
2366     print "Upgrade to $DBversion done (change labels.batch_id from varchar to int)\n";
2367     SetVersion ($DBversion);
2368 }
2369
2370 $DBversion = '3.01.00.025';
2371 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2372     $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')");
2373
2374     print "Upgrade to $DBversion done (added ceilingDueDate system preference)\n";
2375     SetVersion ($DBversion);
2376 }
2377
2378 $DBversion = '3.01.00.026';
2379 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2380     $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')");
2381
2382     print "Upgrade to $DBversion done (added numReturnedItemsToShow system preference)\n";
2383     SetVersion ($DBversion);
2384 }
2385
2386 $DBversion = '3.01.00.027';
2387 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2388     $dbh->do("ALTER TABLE zebraqueue CHANGE `biblio_auth_number` `biblio_auth_number` bigint(20) unsigned NOT NULL default 0");
2389     print "Upgrade to $DBversion done (Increased size of zebraqueue biblio_auth_number to address bug 3148.)\n";
2390     SetVersion ($DBversion);
2391 }
2392
2393 $DBversion = '3.01.00.028';
2394 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2395     my $enable_reviews = C4::Context->preference('AmazonEnabled') ? '1' : '0';
2396     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AmazonReviews', '$enable_reviews', 'Display Amazon reviews on staff interface','','YesNo')");
2397     print "Upgrade to $DBversion done (added AmazonReviews)\n";
2398     SetVersion ($DBversion);
2399 }
2400
2401 $DBversion = '3.01.00.029';
2402 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2403     $dbh->do(q( UPDATE language_rfc4646_to_iso639
2404                 SET iso639_2_code = 'spa'
2405                 WHERE rfc4646_subtag = 'es'
2406                 AND   iso639_2_code = 'rus' )
2407             );
2408     print "Upgrade to $DBversion done (fixed bug 2599: using Spanish search limit retrieves Russian results)\n";
2409     SetVersion ($DBversion);
2410 }
2411
2412 $DBversion = "3.01.00.030";
2413 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2414     $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')");
2415     print "Upgrade to $DBversion done (added AllowNotForLoanOverride system preference)\n";
2416     SetVersion ($DBversion);
2417 }
2418
2419 $DBversion = "3.01.00.031";
2420 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2421     $dbh->do("ALTER TABLE branch_transfer_limits
2422               MODIFY toBranch   varchar(10) NOT NULL,
2423               MODIFY fromBranch varchar(10) NOT NULL,
2424               MODIFY itemtype   varchar(10) NULL");
2425     print "Upgrade to $DBversion done (fix column widths in branch_transfer_limits)\n";
2426     SetVersion ($DBversion);
2427 }
2428
2429 $DBversion = "3.01.00.032";
2430 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2431     $dbh->do(<<ENDOFRENEWAL);
2432 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');
2433 ENDOFRENEWAL
2434     print "Upgrade to $DBversion done (Change the field)\n";
2435     SetVersion ($DBversion);
2436 }
2437
2438 $DBversion = "3.01.00.033";
2439 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2440     $dbh->do(q/
2441         ALTER TABLE borrower_message_preferences
2442         MODIFY borrowernumber int(11) default NULL,
2443         ADD    categorycode varchar(10) default NULL AFTER borrowernumber,
2444         ADD KEY `categorycode` (`categorycode`),
2445         ADD CONSTRAINT `borrower_message_preferences_ibfk_3`
2446                        FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
2447                        ON DELETE CASCADE ON UPDATE CASCADE
2448     /);
2449     print "Upgrade to $DBversion done (DB changes to allow patron category defaults for messaging preferences)\n";
2450     SetVersion ($DBversion);
2451 }
2452
2453 $DBversion = "3.01.00.034";
2454 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2455     $dbh->do("ALTER TABLE `subscription` ADD COLUMN `graceperiod` INT(11) NOT NULL default '0';");
2456     print "Upgrade to $DBversion done (Adding graceperiod column to subscription table)\n";
2457     SetVersion ($DBversion);
2458 }
2459
2460 $DBversion = '3.01.00.035';
2461 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2462     $dbh->do(q{ ALTER TABLE `subscription` ADD location varchar(80) NULL DEFAULT '' AFTER callnumber; });
2463    print "Upgrade to $DBversion done (Adding location to subscription table)\n";
2464     SetVersion ($DBversion);
2465 }
2466
2467 $DBversion = '3.01.00.036';
2468 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2469     $dbh->do("UPDATE systempreferences SET explanation = 'Choose the default detail view in the staff interface; choose between normal, labeled_marc, marc or isbd'
2470               WHERE variable = 'IntranetBiblioDefaultView'
2471               AND   explanation = 'IntranetBiblioDefaultView'");
2472     $dbh->do("UPDATE systempreferences SET type = 'Choice', options = 'normal|marc|isbd|labeled_marc'
2473               WHERE variable = 'IntranetBiblioDefaultView'");
2474     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewISBD','1','Allow display of ISBD view of bibiographic records','','YesNo')");
2475     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewLabeledMARC','0','Allow display of labeled MARC view of bibiographic records','','YesNo')");
2476     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewMARC','1','Allow display of MARC view of bibiographic records','','YesNo')");
2477     print "Upgrade to $DBversion done (new viewISBD, viewLabeledMARC, viewMARC sysprefs and tweak IntranetBiblioDefaultView)\n";
2478     SetVersion ($DBversion);
2479 }
2480
2481 $DBversion = '3.01.00.037';
2482 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2483     $dbh->do('ALTER TABLE authorised_values ADD KEY `lib` (`lib`)');
2484     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('FilterBeforeOverdueReport','0','Do not run overdue report until filter selected','','YesNo')");
2485     SetVersion ($DBversion);
2486     print "Upgrade to $DBversion done (added FilterBeforeOverdueReport syspref and new index on authorised_values)\n";
2487 }
2488
2489 $DBversion = "3.01.00.038";
2490 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2491     # update branches table
2492     #
2493     $dbh->do("ALTER TABLE branches ADD `branchzip` varchar(25) default NULL AFTER `branchaddress3`");
2494     $dbh->do("ALTER TABLE branches ADD `branchcity` mediumtext AFTER `branchzip`");
2495     $dbh->do("ALTER TABLE branches ADD `branchcountry` text AFTER `branchcity`");
2496     $dbh->do("ALTER TABLE branches ADD `branchurl` mediumtext AFTER `branchemail`");
2497     $dbh->do("ALTER TABLE branches ADD `branchnotes` mediumtext AFTER `branchprinter`");
2498     print "Upgrade to $DBversion done (add ZIP, city, country, URL, and notes column to branches)\n";
2499     SetVersion ($DBversion);
2500 }
2501
2502 $DBversion = '3.01.00.039';
2503 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2504     $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')");
2505     $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')");
2506     SetVersion ($DBversion);
2507     print "Upgrade to $DBversion done (added SpineLabelFormat and SpineLabelAutoPrint sysprefs)\n";
2508 }
2509
2510 $DBversion = '3.01.00.040';
2511 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2512     $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')");
2513     $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')");
2514     SetVersion ($DBversion);
2515     print "Upgrade to $DBversion done (AllowHoldDateInFuture and OPACAllowHoldDateInFuture sysprefs)\n";
2516 }
2517
2518 $DBversion = '3.01.00.041';
2519 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2520     $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')");
2521     SetVersion ($DBversion);
2522     print "Upgrade to $DBversion done (added AWSPrivateKey syspref - note that if you use enhanced content from Amazon, this should be set right away.)\n";
2523 }
2524
2525 $DBversion = '3.01.00.042';
2526 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2527     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACFineNoRenewals','99999','Fine Limit above which user canmot renew books via OPAC','','Integer')");
2528     SetVersion ($DBversion);
2529     print "Upgrade to $DBversion done (added OPACFineNoRenewals syspref)\n";
2530 }
2531
2532 $DBversion = '3.01.00.043';
2533 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2534     $dbh->do('ALTER TABLE items ADD COLUMN permanent_location VARCHAR(80) DEFAULT NULL AFTER location');
2535     $dbh->do('UPDATE items SET permanent_location = location');
2536     $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 )', '')");
2537     $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')");
2538     $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')");
2539     SetVersion ($DBversion);
2540     print "Upgrade to $DBversion done (amended Item added NewItemsDefaultLocation, InProcessingToShelvingCart, ReturnToShelvingCart sysprefs)\n";
2541 }
2542
2543 $DBversion = '3.01.00.044';
2544 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2545     $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')");
2546     SetVersion ($DBversion);
2547     print "Upgrade to $DBversion done (added DisplayClearScreenButton system preference)\n";
2548 }
2549
2550 $DBversion = '3.01.00.045';
2551 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2552     $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')");
2553     SetVersion ($DBversion);
2554     print "Upgrade to $DBversion done (added a preference to hide the patrons name in the staff catalog)\n";
2555 }
2556
2557 $DBversion = "3.01.00.046";
2558 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2559     # update borrowers table
2560     #
2561     $dbh->do("ALTER TABLE borrowers ADD `country` text AFTER zipcode");
2562     $dbh->do("ALTER TABLE borrowers ADD `B_country` text AFTER B_zipcode");
2563     $dbh->do("ALTER TABLE deletedborrowers ADD `country` text AFTER zipcode");
2564     $dbh->do("ALTER TABLE deletedborrowers ADD `B_country` text AFTER B_zipcode");
2565     print "Upgrade to $DBversion done (add country and B_country to borrowers)\n";
2566     SetVersion ($DBversion);
2567 }
2568
2569 $DBversion = '3.01.00.047';
2570 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2571     $dbh->do("ALTER TABLE items MODIFY itemcallnumber varchar(255);");
2572     $dbh->do("ALTER TABLE deleteditems MODIFY itemcallnumber varchar(255);");
2573     $dbh->do("ALTER TABLE tmp_holdsqueue MODIFY itemcallnumber varchar(255);");
2574     SetVersion ($DBversion);
2575     print " Upgrade to $DBversion done (bug 2761: change max length of itemcallnumber to 255 from 30)\n";
2576 }
2577
2578 $DBversion = '3.01.00.048';
2579 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2580     $dbh->do("UPDATE userflags SET flagdesc='View Catalog (Librarian Interface)' WHERE bit=2;");
2581     $dbh->do("UPDATE userflags SET flagdesc='Edit Catalog (Modify bibliographic/holdings data)' WHERE bit=9;");
2582     $dbh->do("UPDATE userflags SET flagdesc='Allow to edit authorities' WHERE bit=14;");
2583     $dbh->do("UPDATE userflags SET flagdesc='Allow to access to the reports module' WHERE bit=16;");
2584     $dbh->do("UPDATE userflags SET flagdesc='Allow to manage serials subscriptions' WHERE bit=15;");
2585     SetVersion ($DBversion);
2586     print " Upgrade to $DBversion done (bug 2611: fix spelling/capitalization in permission flag descriptions)\n";
2587 }
2588
2589 $DBversion = '3.01.00.049';
2590 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2591     $dbh->do("UPDATE permissions SET description = 'Perform inventory (stocktaking) of your catalog' WHERE code = 'inventory';");
2592      SetVersion ($DBversion);
2593     print "Upgrade to $DBversion done (bug 2611: changed catalogue to catalog per the standard)\n";
2594 }
2595
2596 $DBversion = '3.01.00.050';
2597 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2598     $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');");
2599     SetVersion ($DBversion);
2600     print "Upgrade to $DBversion done (bug 1934: Add OPACSearchForTitleIn syspref)\n";
2601 }
2602
2603 $DBversion = '3.01.00.051';
2604 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2605     $dbh->do("UPDATE systempreferences SET explanation='Fine limit above which user cannot renew books via OPAC' WHERE variable='OPACFineNoRenewals';");
2606     $dbh->do("UPDATE systempreferences SET explanation='If set to ON, a clear screen button will appear on the circulation page.' WHERE variable='DisplayClearScreenButton';");
2607     SetVersion ($DBversion);
2608     print "Upgrade to $DBversion done (fixed typos in new sysprefs)\n";
2609 }
2610
2611 $DBversion = '3.01.00.052';
2612 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2613     $dbh->do('ALTER TABLE deleteditems ADD COLUMN permanent_location VARCHAR(80) DEFAULT NULL AFTER location');
2614     SetVersion ($DBversion);
2615     print "Upgrade to $DBversion done (bug 3481: add permanent_location column to deleteditems)\n";
2616 }
2617
2618 $DBversion = '3.01.00.053';
2619 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2620     my $upgrade_script = C4::Context->config("intranetdir") . "/installer/data/mysql/labels_upgrade.pl";
2621     system("perl $upgrade_script");
2622     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";
2623     SetVersion ($DBversion);
2624 }
2625
2626 $DBversion = '3.01.00.054';
2627 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2628     $dbh->do("ALTER TABLE borrowers ADD `B_address2` text AFTER B_address");
2629     $dbh->do("ALTER TABLE borrowers ADD `altcontactcountry` text AFTER altcontactzipcode");
2630     $dbh->do("ALTER TABLE deletedborrowers ADD `B_address2` text AFTER B_address");
2631     $dbh->do("ALTER TABLE deletedborrowers ADD `altcontactcountry` text AFTER altcontactzipcode");
2632     SetVersion ($DBversion);
2633     print "Upgrade to $DBversion done (bug 1600, bug 3454: add altcontactcountry and B_address2 to borrowers and deletedborrowers)\n";
2634 }
2635
2636 $DBversion = '3.01.00.055';
2637 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2638     $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'|);
2639     SetVersion ($DBversion);
2640     print "Upgrade to $DBversion done (changed OPACSearchForTitleIn per requests in bug 1934)\n";
2641 }
2642
2643 $DBversion = '3.01.00.056';
2644 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2645     $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');");
2646     SetVersion ($DBversion);
2647     print "Upgrade to $DBversion done (Bug 1172 : Add OPACPatronDetails syspref)\n";
2648 }
2649
2650 $DBversion = '3.01.00.057';
2651 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2652     $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');");
2653     SetVersion ($DBversion);
2654     print "Upgrade to $DBversion done (Bug 2576 : Add OPACFinesTab syspref)\n";
2655 }
2656
2657 $DBversion = '3.01.00.058';
2658 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2659     $dbh->do("ALTER TABLE `language_subtag_registry` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2660     $dbh->do("ALTER TABLE `language_rfc4646_to_iso639` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2661     $dbh->do("ALTER TABLE `language_descriptions` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2662     SetVersion ($DBversion);
2663     print "Upgrade to $DBversion done (Added primary keys to language tables)\n";
2664 }
2665
2666 $DBversion = '3.01.00.059';
2667 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2668     $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')");
2669     SetVersion ($DBversion);
2670     print "Upgrade to $DBversion done (added DisplayOPACiconsXSLT sysprefs)\n";
2671 }
2672
2673 $DBversion = '3.01.00.060';
2674 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2675     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowAllMessageDeletion','0','Allow any Library to delete any message','','YesNo');");
2676     $dbh->do('DROP TABLE IF EXISTS messages');
2677     $dbh->do("CREATE TABLE messages ( `message_id` int(11) NOT NULL auto_increment,
2678         `borrowernumber` int(11) NOT NULL,
2679         `branchcode` varchar(4) default NULL,
2680         `message_type` varchar(1) NOT NULL,
2681         `message` text NOT NULL,
2682         `message_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
2683         PRIMARY KEY (`message_id`)
2684         ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
2685
2686         print "Upgrade to $DBversion done ( Added AllowAllMessageDeletion syspref and messages table )\n";
2687     SetVersion ($DBversion);
2688 }
2689
2690 $DBversion = '3.01.00.061';
2691 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2692     $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')");
2693         print "Upgrade to $DBversion done ( Added ShowPatronImageInWebBasedSelfCheck system preference )\n";
2694     SetVersion ($DBversion);
2695 }
2696
2697 $DBversion = "3.01.00.062";
2698 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2699     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'manage_csv_profiles', 'Manage CSV export profiles')");
2700     $dbh->do(q/
2701         CREATE TABLE `export_format` (
2702           `export_format_id` int(11) NOT NULL auto_increment,
2703           `profile` varchar(255) NOT NULL,
2704           `description` mediumtext NOT NULL,
2705           `marcfields` mediumtext NOT NULL,
2706           PRIMARY KEY  (`export_format_id`)
2707         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Used for CSV export';
2708     /);
2709     print "Upgrade to $DBversion done (added csv export profiles)\n";
2710 }
2711
2712 $DBversion = "3.01.00.063";
2713 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2714     $dbh->do("
2715         CREATE TABLE `fieldmapping` (
2716           `id` int(11) NOT NULL auto_increment,
2717           `field` varchar(255) NOT NULL,
2718           `frameworkcode` char(4) NOT NULL default '',
2719           `fieldcode` char(3) NOT NULL,
2720           `subfieldcode` char(1) NOT NULL,
2721           PRIMARY KEY  (`id`)
2722         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2723              ");
2724     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";
2725 }
2726
2727 $DBversion = '3.01.00.065';
2728 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2729     $dbh->do('ALTER TABLE issuingrules ADD COLUMN `renewalsallowed` smallint(6) NOT NULL default "0" AFTER `issuelength`;');
2730     $sth = $dbh->prepare("SELECT itemtype, renewalsallowed FROM itemtypes");
2731     $sth->execute();
2732
2733     my $sthupd = $dbh->prepare("UPDATE issuingrules SET renewalsallowed = ? WHERE itemtype = ?");
2734
2735     while(my $row = $sth->fetchrow_hashref){
2736         $sthupd->execute($row->{renewalsallowed}, $row->{itemtype});
2737     }
2738
2739     $dbh->do('ALTER TABLE itemtypes DROP COLUMN `renewalsallowed`;');
2740
2741     SetVersion ($DBversion);
2742     print "Upgrade to $DBversion done (Moving allowed renewals from itemtypes to issuingrule)\n";
2743 }
2744
2745 $DBversion = '3.01.00.066';
2746 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2747     $dbh->do('ALTER TABLE issuingrules ADD COLUMN `reservesallowed` smallint(6) NOT NULL default "0" AFTER `renewalsallowed`;');
2748
2749     my $maxreserves = C4::Context->preference('maxreserves');
2750     $sth = $dbh->prepare('UPDATE issuingrules SET reservesallowed = ?;');
2751     $sth->execute($maxreserves);
2752
2753     $dbh->do('DELETE FROM systempreferences WHERE variable = "maxreserves";');
2754
2755     $dbh->do("INSERT INTO systempreferences (variable,value, options, explanation, type) VALUES('ReservesControlBranch','PatronLibrary','ItemHomeLibrary|PatronLibrary','Branch checked for members reservations rights','Choice')");
2756
2757     SetVersion ($DBversion);
2758     print "Upgrade to $DBversion done (Moving max allowed reserves from system preference to issuingrule)\n";
2759 }
2760
2761 $DBversion = "3.01.00.067";
2762 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2763     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'batchmod', 'Perform batch modification of items')");
2764     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'batchdel', 'Perform batch deletion of items')");
2765     print "Upgrade to $DBversion done (added permissions for batch modification and deletion)\n";
2766     SetVersion ($DBversion);
2767 }
2768
2769 $DBversion = "3.01.00.068";
2770 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2771         $dbh->do("ALTER TABLE issuingrules ADD COLUMN `finedays` int(11) default NULL AFTER `fine` ");
2772         print "Upgrade to $DBversion done (Adding finedays in issuingrules table)\n";
2773     SetVersion ($DBversion);
2774 }
2775
2776
2777 $DBversion = "3.01.00.069";
2778 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2779         $dbh->do("INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('EnableOpacSearchHistory', '1', '', 'Enable or disable opac search history', 'YesNo')");
2780
2781         my $create = <<SEARCHHIST;
2782 CREATE TABLE IF NOT EXISTS `search_history` (
2783   `userid` int(11) NOT NULL,
2784   `sessionid` varchar(32) NOT NULL,
2785   `query_desc` varchar(255) NOT NULL,
2786   `query_cgi` varchar(255) NOT NULL,
2787   `total` int(11) NOT NULL,
2788   `time` timestamp NOT NULL default CURRENT_TIMESTAMP,
2789   KEY `userid` (`userid`),
2790   KEY `sessionid` (`sessionid`)
2791 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Opac search history results';
2792 SEARCHHIST
2793         $dbh->do($create);
2794
2795         print "Upgrade to $DBversion done (added OPAC search history preference and table)\n";
2796 }
2797
2798 $DBversion = "3.01.00.070";
2799 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2800         $dbh->do("ALTER TABLE authorised_values ADD COLUMN `lib_opac` VARCHAR(80) default NULL AFTER `lib`");
2801         print "Upgrade to $DBversion done (Added a lib_opac field in authorised_values table)\n";
2802 }
2803
2804 $DBversion = "3.01.00.071";
2805 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2806         $dbh->do("ALTER TABLE `subscription` ADD `enddate` date default NULL");
2807         $dbh->do("ALTER TABLE subscriptionhistory CHANGE enddate histenddate DATE default NULL");
2808         print "Upgrade to $DBversion done ( Adding enddate to subscription)\n";
2809 }
2810
2811 # Acquisitions update
2812
2813 $DBversion = "3.01.00.072";
2814 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2815     $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')");
2816     # create a new syspref for the 'Mr anonymous' patron
2817     $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,'')");
2818     # fill AnonymousPatron with AnonymousSuggestion value (copy)
2819     my $sth=$dbh->prepare("SELECT value FROM systempreferences WHERE variable='AnonSuggestions'");
2820     $sth->execute;
2821     my ($value) = $sth->fetchrow() || 0;
2822     $dbh->do("UPDATE systempreferences SET value='$value' WHERE variable='AnonymousPatron'");
2823     # set AnonymousSuggestion do YesNo
2824     # 1st, set the value (1/True if it had a borrowernumber)
2825     $dbh->do("UPDATE systempreferences SET value=1 WHERE variable='AnonSuggestions' AND value>0");
2826     # 2nd, change the type to Choice
2827     $dbh->do("UPDATE systempreferences SET type='YesNo' WHERE variable='AnonSuggestions'");
2828         # borrower reading record privacy : 0 : forever, 1 : laws, 2 : don't keep at all
2829     $dbh->do("ALTER TABLE `borrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
2830     print "Upgrade to $DBversion done (add new syspref and column in borrowers)\n";
2831     SetVersion ($DBversion);
2832 }
2833
2834 $DBversion = '3.01.00.073';
2835 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2836     $dbh->do('SET FOREIGN_KEY_CHECKS=0 ');
2837     $dbh->do(<<'END_SQL');
2838 CREATE TABLE IF NOT EXISTS `aqcontract` (
2839   `contractnumber` int(11) NOT NULL auto_increment,
2840   `contractstartdate` date default NULL,
2841   `contractenddate` date default NULL,
2842   `contractname` varchar(50) default NULL,
2843   `contractdescription` mediumtext,
2844   `booksellerid` int(11) not NULL,
2845     PRIMARY KEY  (`contractnumber`),
2846         CONSTRAINT `booksellerid_fk1` FOREIGN KEY (`booksellerid`)
2847         REFERENCES `aqbooksellers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
2848 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
2849 END_SQL
2850     $dbh->do('SET FOREIGN_KEY_CHECKS=1 ');
2851     print "Upgrade to $DBversion done (adding aqcontract table)\n";
2852     SetVersion ($DBversion);
2853 }
2854
2855 $DBversion = '3.01.00.074';
2856 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2857     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `basketname` varchar(50) default NULL AFTER `basketno`");
2858     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `note` mediumtext AFTER `basketname`");
2859     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `booksellernote` mediumtext AFTER `note`");
2860     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `contractnumber` int(11) AFTER `booksellernote`");
2861     $dbh->do("ALTER TABLE `aqbasket` ADD FOREIGN KEY (`contractnumber`) REFERENCES `aqcontract` (`contractnumber`)");
2862     print "Upgrade to $DBversion done (edit aqbasket table done)\n";
2863     SetVersion ($DBversion);
2864 }
2865
2866 $DBversion = '3.01.00.075';
2867 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2868     $dbh->do("ALTER TABLE `aqorders` ADD COLUMN `uncertainprice` tinyint(1)");
2869
2870     print "Upgrade to $DBversion done (adding uncertainprices)\n";
2871     SetVersion ($DBversion);
2872 }
2873
2874 $DBversion = '3.01.00.076';
2875 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2876     $dbh->do('SET FOREIGN_KEY_CHECKS=0 ');
2877     $dbh->do("CREATE TABLE IF NOT EXISTS `aqbasketgroups` (
2878                          `id` int(11) NOT NULL auto_increment,
2879                          `name` varchar(50) default NULL,
2880                          `closed` tinyint(1) default NULL,
2881                          `booksellerid` int(11) NOT NULL,
2882                          PRIMARY KEY (`id`),
2883                          KEY `booksellerid` (`booksellerid`),
2884                          CONSTRAINT `aqbasketgroups_ibfk_1` FOREIGN KEY (`booksellerid`) REFERENCES `aqbooksellers` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
2885                          ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
2886     $dbh->do("ALTER TABLE aqbasket ADD COLUMN `basketgroupid` int(11)");
2887     $dbh->do("ALTER TABLE aqbasket ADD FOREIGN KEY (`basketgroupid`) REFERENCES `aqbasketgroups` (`id`) ON UPDATE CASCADE ON DELETE SET NULL");
2888     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('pdfformat','pdfformat::layout2pages','Controls what script is used for printing (basketgroups)','','free')");
2889     $dbh->do('SET FOREIGN_KEY_CHECKS=1 ');
2890     print "Upgrade to $DBversion done (adding basketgroups)\n";
2891     SetVersion ($DBversion);
2892 }
2893 $DBversion = '3.01.00.077';
2894 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2895
2896     $dbh->do("SET FOREIGN_KEY_CHECKS=0 ");
2897     # create a mapping table holding the info we need to match orders to budgets
2898     $dbh->do('DROP TABLE IF EXISTS fundmapping');
2899     $dbh->do(
2900         q|CREATE TABLE fundmapping AS
2901         SELECT aqorderbreakdown.ordernumber, branchcode, bookfundid, budgetdate, entrydate
2902         FROM aqorderbreakdown JOIN aqorders ON aqorderbreakdown.ordernumber = aqorders.ordernumber|);
2903     # match the new type of the corresponding field
2904     $dbh->do('ALTER TABLE fundmapping modify column bookfundid varchar(30)');
2905     # System did not ensure budgetdate was valid historically
2906     $dbh->do(q|UPDATE fundmapping SET budgetdate = entrydate WHERE budgetdate = '0000-00-00' OR budgetdate IS NULL|);
2907     # We save the map in fundmapping in case you need later processing
2908     $dbh->do(q|ALTER TABLE fundmapping add column aqbudgetid integer|);
2909     # these can speed processing up
2910     $dbh->do(q|CREATE INDEX fundmaporder ON fundmapping (ordernumber)|);
2911     $dbh->do(q|CREATE INDEX fundmapid ON fundmapping (bookfundid)|);
2912
2913     $dbh->do("DROP TABLE IF EXISTS `aqbudgetperiods` ");
2914
2915     $dbh->do(qq|
2916                     CREATE TABLE `aqbudgetperiods` (
2917                     `budget_period_id` int(11) NOT NULL auto_increment,
2918                     `budget_period_startdate` date NOT NULL,
2919                     `budget_period_enddate` date NOT NULL,
2920                     `budget_period_active` tinyint(1) default '0',
2921                     `budget_period_description` mediumtext,
2922                     `budget_period_locked` tinyint(1) default NULL,
2923                     `sort1_authcat` varchar(10) default NULL,
2924                     `sort2_authcat` varchar(10) default NULL,
2925                     PRIMARY KEY  (`budget_period_id`)
2926                     ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 |);
2927
2928    $dbh->do(<<ADDPERIODS);
2929 INSERT INTO aqbudgetperiods (budget_period_startdate,budget_period_enddate,budget_period_active,budget_period_description,budget_period_locked)
2930 SELECT DISTINCT startdate, enddate, NOW() BETWEEN startdate and enddate, concat(startdate," ",enddate),NOT NOW() BETWEEN startdate AND enddate from aqbudget
2931 ADDPERIODS
2932 # SORRY , NO AQBUDGET/AQBOOKFUND -> AQBUDGETS IMPORT JUST YET,
2933 # BUT A NEW CLEAN AQBUDGETS TABLE CREATE FOR NOW..
2934 # DROP TABLE IF EXISTS `aqbudget`;
2935 #CREATE TABLE `aqbudget` (
2936 #  `bookfundid` varchar(10) NOT NULL default ',
2937 #    `startdate` date NOT NULL default 0,
2938 #         `enddate` date default NULL,
2939 #           `budgetamount` decimal(13,2) default NULL,
2940 #                 `aqbudgetid` tinyint(4) NOT NULL auto_increment,
2941 #                   `branchcode` varchar(10) default NULL,
2942     DropAllForeignKeys('aqbudget');
2943   #$dbh->do("drop table aqbudget;");
2944
2945
2946     my $maxbudgetid = $dbh->selectcol_arrayref(<<IDsBUDGET);
2947 SELECT MAX(aqbudgetid) from aqbudget
2948 IDsBUDGET
2949
2950 $$maxbudgetid[0] = 0 if !$$maxbudgetid[0];
2951
2952     $dbh->do(<<BUDGETAUTOINCREMENT);
2953 ALTER TABLE aqbudget AUTO_INCREMENT=$$maxbudgetid[0]
2954 BUDGETAUTOINCREMENT
2955
2956     $dbh->do(<<BUDGETNAME);
2957 ALTER TABLE aqbudget RENAME `aqbudgets`
2958 BUDGETNAME
2959
2960     $dbh->do(<<BUDGETS);
2961 ALTER TABLE `aqbudgets`
2962    CHANGE  COLUMN aqbudgetid `budget_id` int(11) NOT NULL AUTO_INCREMENT,
2963    CHANGE  COLUMN branchcode `budget_branchcode` varchar(10) default NULL,
2964    CHANGE  COLUMN budgetamount `budget_amount` decimal(28,6) NOT NULL default '0.00',
2965    CHANGE  COLUMN bookfundid   `budget_code` varchar(30) default NULL,
2966    ADD     COLUMN `budget_parent_id` int(11) default NULL,
2967    ADD     COLUMN `budget_name` varchar(80) default NULL,
2968    ADD     COLUMN `budget_encumb` decimal(28,6) default '0.00',
2969    ADD     COLUMN `budget_expend` decimal(28,6) default '0.00',
2970    ADD     COLUMN `budget_notes` mediumtext,
2971    ADD     COLUMN `budget_description` mediumtext,
2972    ADD     COLUMN `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
2973    ADD     COLUMN `budget_amount_sublevel`  decimal(28,6) AFTER `budget_amount`,
2974    ADD     COLUMN `budget_period_id` int(11) default NULL,
2975    ADD     COLUMN `sort1_authcat` varchar(80) default NULL,
2976    ADD     COLUMN `sort2_authcat` varchar(80) default NULL,
2977    ADD     COLUMN `budget_owner_id` int(11) default NULL,
2978    ADD     COLUMN `budget_permission` int(1) default '0';
2979 BUDGETS
2980
2981     $dbh->do(<<BUDGETCONSTRAINTS);
2982 ALTER TABLE `aqbudgets`
2983    ADD CONSTRAINT `aqbudgets_ifbk_1` FOREIGN KEY (`budget_period_id`) REFERENCES `aqbudgetperiods` (`budget_period_id`) ON DELETE CASCADE ON UPDATE CASCADE
2984 BUDGETCONSTRAINTS
2985 #    $dbh->do(<<BUDGETPKDROP);
2986 #ALTER TABLE `aqbudgets`
2987 #   DROP PRIMARY KEY
2988 #BUDGETPKDROP
2989 #    $dbh->do(<<BUDGETPKADD);
2990 #ALTER TABLE `aqbudgets`
2991 #   ADD PRIMARY KEY budget_id
2992 #BUDGETPKADD
2993
2994
2995         my $query_period= $dbh->prepare(qq|SELECT budget_period_id from aqbudgetperiods where budget_period_startdate=? and budget_period_enddate=?|);
2996         my $query_bookfund= $dbh->prepare(qq|SELECT * from aqbookfund where bookfundid=?|);
2997         my $selectbudgets=$dbh->prepare(qq|SELECT * from aqbudgets|);
2998         my $updatebudgets=$dbh->prepare(qq|UPDATE aqbudgets SET budget_period_id= ? , budget_name=?, budget_branchcode=? where budget_id=?|);
2999         $selectbudgets->execute;
3000         while (my $databudget=$selectbudgets->fetchrow_hashref){
3001                 $query_period->execute ($$databudget{startdate},$$databudget{enddate});
3002                 my ($budgetperiodid)=$query_period->fetchrow;
3003                 $query_bookfund->execute ($$databudget{budget_code});
3004                 my $databf=$query_bookfund->fetchrow_hashref;
3005                 my $branchcode=$$databudget{budget_branchcode}||$$databf{branchcode};
3006                 $updatebudgets->execute($budgetperiodid,$$databf{bookfundname},$branchcode,$$databudget{budget_id});
3007         }
3008     $dbh->do(<<BUDGETDROPDATES);
3009 ALTER TABLE `aqbudgets`
3010    DROP startdate,
3011    DROP enddate
3012 BUDGETDROPDATES
3013
3014
3015     $dbh->do("DROP TABLE IF EXISTS `aqbudgets_planning` ");
3016     $dbh->do("CREATE TABLE  `aqbudgets_planning` (
3017                     `plan_id` int(11) NOT NULL auto_increment,
3018                     `budget_id` int(11) NOT NULL,
3019                     `budget_period_id` int(11) NOT NULL,
3020                     `estimated_amount` decimal(28,6) default NULL,
3021                     `authcat` varchar(30) NOT NULL,
3022                     `authvalue` varchar(30) NOT NULL,
3023                                         `display` tinyint(1) DEFAULT 1,
3024                         PRIMARY KEY  (`plan_id`),
3025                         CONSTRAINT `aqbudgets_planning_ifbk_1` FOREIGN KEY (`budget_id`) REFERENCES `aqbudgets` (`budget_id`) ON DELETE CASCADE ON UPDATE CASCADE
3026                         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
3027
3028     $dbh->do("ALTER TABLE `aqorders`
3029                     ADD COLUMN `budget_id` tinyint(4) NOT NULL,
3030                     ADD COLUMN `budgetgroup_id` int(11) NOT NULL,
3031                     ADD COLUMN  `sort1_authcat` varchar(10) default NULL,
3032                     ADD COLUMN  `sort2_authcat` varchar(10) default NULL" );
3033                 # We need to map the orders to the budgets
3034                 # For Historic reasons this is more complex than it should be on occasions
3035                 my $budg_arr = $dbh->selectall_arrayref(
3036                     q|SELECT aqbudgets.budget_id, aqbudgets.budget_code, aqbudgetperiods.budget_period_startdate,
3037                     aqbudgetperiods.budget_period_enddate
3038                     FROM aqbudgets JOIN aqbudgetperiods ON aqbudgets.budget_period_id = aqbudgetperiods.budget_period_id
3039                     ORDER BY budget_code, budget_period_startdate|, { Slice => {} });
3040                 # We arbitarily order on start date, this means if you have overlapping periods the order will be
3041                 # linked to the latest matching budget YMMV
3042                 my $b_sth = $dbh->prepare(
3043                     'UPDATE fundmapping set aqbudgetid = ? where bookfundid =? AND budgetdate >= ? AND budgetdate <= ?');
3044                 for my $b ( @{$budg_arr}) {
3045                     $b_sth->execute($b->{budget_id}, $b->{budget_code}, $b->{budget_period_startdate}, $b->{budget_period_enddate});
3046                 }
3047                 # move the budgetids to aqorders
3048                 $dbh->do(q|UPDATE aqorders, fundmapping SET aqorders.budget_id = fundmapping.aqbudgetid
3049                     WHERE aqorders.ordernumber = fundmapping.ordernumber AND fundmapping.aqbudgetid IS NOT NULL|);
3050                 # NB fundmapping is left as an accontants trail also if you have budgetids that werent set
3051                 # you can decide what to do with them
3052
3053      $dbh->do(
3054          q|UPDATE aqorders, aqbudgets SET aqorders.budgetgroup_id = aqbudgets.budget_period_id
3055          WHERE aqorders.budget_id = aqbudgets.budget_id|);
3056                 # cannot do until aqorderbreakdown removed
3057 #    $dbh->do("DROP TABLE aqbookfund ");
3058 #    $dbh->do("ALTER TABLE aqorders  ADD FOREIGN KEY (`budget_id`) REFERENCES `aqbudgets` (`budget_id`) ON UPDATE CASCADE  " ); ????
3059     $dbh->do("SET FOREIGN_KEY_CHECKS=1 ");
3060
3061     print "Upgrade to $DBversion done (Adding new aqbudgetperiods, aqbudgets and aqbudget_planning tables  )\n";
3062     SetVersion ($DBversion);
3063 }
3064
3065
3066
3067 $DBversion = '3.01.00.078';
3068 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3069     $dbh->do("ALTER TABLE aqbudgetperiods ADD COLUMN budget_period_total decimal(28,6)");
3070     print "Upgrade to $DBversion done (adds 'budget_period_total' column to aqbudgetperiods table)\n";
3071     SetVersion($DBversion);
3072 }
3073
3074
3075 $DBversion = '3.01.00.079';
3076 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3077     $dbh->do("ALTER TABLE currency ADD COLUMN active  tinyint(1)");
3078
3079     print "Upgrade to $DBversion done (adds 'active' column to currencies table)\n";
3080     SetVersion($DBversion);
3081 }
3082
3083 $DBversion = '3.01.00.080';
3084 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3085     $dbh->do(<<BUDG_PERM );
3086 INSERT INTO permissions (module_bit, code, description) VALUES
3087             (11, 'vendors_manage', 'Manage vendors'),
3088             (11, 'contracts_manage', 'Manage contracts'),
3089             (11, 'period_manage', 'Manage periods'),
3090             (11, 'budget_manage', 'Manage budgets'),
3091             (11, 'budget_modify', "Modify budget (can't create lines but can modify existing ones)"),
3092             (11, 'planning_manage', 'Manage budget plannings'),
3093             (11, 'order_manage', 'Manage orders & basket'),
3094             (11, 'group_manage', 'Manage orders & basketgroups'),
3095             (11, 'order_receive', 'Manage orders & basket'),
3096             (11, 'budget_add_del', "Add and delete budgets (but can't modify budgets)");
3097 BUDG_PERM
3098
3099     print "Upgrade to $DBversion done (adds permissions for the acquisitions module)\n";
3100     SetVersion($DBversion);
3101 }
3102
3103
3104 $DBversion = '3.01.00.081';
3105 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3106     $dbh->do("ALTER TABLE aqbooksellers ADD COLUMN `gstrate` decimal(6,4) default NULL");
3107     if (my $gist=C4::Context->preference("gist")){
3108                 my $sql=$dbh->prepare("UPDATE aqbooksellers set `gstrate`=? ");
3109         $sql->execute($gist) ;
3110         }
3111     print "Upgrade to $DBversion done (added per-supplier gstrate setting)\n";
3112     SetVersion($DBversion);
3113 }
3114
3115 $DBversion = "3.01.00.082";
3116 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3117     if (C4::Context->preference("opaclanguages") eq "fr") {
3118         $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')#);
3119     } else {
3120         $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')");
3121     }
3122     print "Upgrade to $DBversion done (adding ReservesNeedReturns systempref, in circulation)\n";
3123     SetVersion ($DBversion);
3124 }
3125
3126 $DBversion = "3.01.00.083";
3127 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3128     $dbh->do(qq|
3129  CREATE TABLE `aqorders_items` (
3130   `ordernumber` int(11) NOT NULL,
3131   `itemnumber` int(11) NOT NULL,
3132   `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
3133   PRIMARY KEY  (`itemnumber`),
3134   KEY `ordernumber` (`ordernumber`)
3135 ) ENGINE=InnoDB DEFAULT CHARSET=utf8   |
3136     );
3137
3138     $dbh->do(qq| DROP TABLE aqorderbreakdown |);
3139     $dbh->do('DROP TABLE aqbookfund');
3140     print "Upgrade to $DBversion done (New aqorders_items table for acqui)\n";
3141     SetVersion ($DBversion);
3142 }
3143
3144 $DBversion = "3.01.00.084";
3145 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3146     $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')  #);
3147
3148     print "Upgrade to $DBversion done (CurrencyFormat syspref added)\n";
3149     SetVersion ($DBversion);
3150 }
3151
3152 $DBversion = "3.01.00.085";
3153 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3154     $dbh->do("ALTER table aqorders drop column title");
3155     $dbh->do("ALTER TABLE `aqorders` CHANGE `budget_id` `budget_id` INT( 11 ) NOT NULL");
3156     print "Upgrade to $DBversion done update budget_id size that should not be a tinyint\n";
3157     SetVersion ($DBversion);
3158 }
3159
3160 $DBversion = "3.01.00.086";
3161 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3162     $dbh->do(<<SUGGESTIONS);
3163 ALTER table suggestions
3164     ADD budgetid INT(11),
3165     ADD branchcode VARCHAR(10) default NULL,
3166     ADD acceptedby INT(11) default NULL,
3167     ADD accepteddate date default NULL,
3168     ADD suggesteddate date default NULL,
3169     ADD manageddate date default NULL,
3170     ADD rejectedby INT(11) default NULL,
3171     ADD rejecteddate date default NULL,
3172     ADD collectiontitle text default NULL,
3173     ADD itemtype VARCHAR(30) default NULL
3174     ;
3175 SUGGESTIONS
3176     print "Upgrade to $DBversion done (Suggestions)\n";
3177     SetVersion ($DBversion);
3178 }
3179
3180 $DBversion = "3.01.00.087";
3181 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3182     $dbh->do("ALTER table aqbudgets drop column budget_amount_sublevel;");
3183     print "Upgrade to $DBversion done (Drop column budget_amount_sublevel from aqbudgets)\n";
3184     SetVersion ($DBversion);
3185 }
3186
3187 $DBversion = "3.01.00.088";
3188 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3189     $dbh->do(  qq# INSERT INTO `systempreferences` VALUES ('intranetbookbag','1','','If ON, enables display of Cart feature in the intranet','YesNo')  #);
3190
3191     print "Upgrade to $DBversion done (intranetbookbag syspref added)\n";
3192     SetVersion ($DBversion);
3193 }
3194
3195 $DBversion = "3.01.00.090";
3196 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3197 $dbh->do("
3198        INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3199                 (16, 'execute_reports', 'Execute SQL reports'),
3200                 (16, 'create_reports', 'Create SQL Reports')
3201         ");
3202
3203     print "Upgrade to $DBversion done (granular permissions for guided reports added)\n";
3204     SetVersion ($DBversion);
3205 }
3206
3207 $DBversion = "3.01.00.091";
3208 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3209 $dbh->do("
3210         UPDATE `systempreferences` SET `options` = 'holdings|serialcollection|subscriptions'
3211         WHERE `systempreferences`.`variable` = 'opacSerialDefaultTab' LIMIT 1
3212         ");
3213
3214     print "Upgrade to $DBversion done (opac-detail default tag updated)\n";
3215     SetVersion ($DBversion);
3216 }
3217
3218 $DBversion = "3.01.00.092";
3219 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3220     if (C4::Context->preference("opaclanguages") =~ /fr/) {
3221         $dbh->do(qq{
3222 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');
3223         });
3224         }else{
3225         $dbh->do(qq{
3226 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');
3227         });
3228         }
3229     print "Upgrade to $DBversion done (Added RoutingListAddReserves syspref)\n";
3230     SetVersion ($DBversion);
3231 }
3232
3233 $DBversion = "3.01.00.093";
3234 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3235         $dbh->do(qq{
3236         ALTER TABLE biblioitems ADD INDEX issn_idx (issn);
3237         });
3238     print "Upgrade to $DBversion done (added index to ISSN)\n";
3239     SetVersion ($DBversion);
3240 }
3241
3242 $DBversion = "3.01.00.094";
3243 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3244         $dbh->do(qq{
3245         ALTER TABLE aqbasketgroups ADD deliveryplace VARCHAR(10) default NULL, ADD deliverycomment VARCHAR(255) default NULL;
3246         });
3247
3248     print "Upgrade to $DBversion done (adding deliveryplace deliverycomment to basketgroups)\n";
3249     SetVersion ($DBversion);
3250 }
3251
3252 $DBversion = "3.01.00.095";
3253 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3254         $dbh->do(qq{
3255         ALTER TABLE items ADD stocknumber VARCHAR(32) DEFAULT NULL COMMENT "stores the inventory number";
3256         });
3257         $dbh->do(qq{
3258         ALTER TABLE items ADD UNIQUE INDEX itemsstocknumberidx (stocknumber);
3259         });
3260         $dbh->do(qq{
3261         ALTER TABLE deleteditems ADD stocknumber VARCHAR(32) DEFAULT NULL COMMENT "stores the inventory number of deleted items";
3262         });
3263         $dbh->do(qq{
3264         ALTER TABLE deleteditems ADD UNIQUE INDEX deleteditemsstocknumberidx (stocknumber);
3265         });
3266         if (C4::Context->preference('marcflavour') eq 'UNIMARC'){
3267                 $dbh->do(qq{
3268         INSERT IGNORE INTO marc_subfield_structure (frameworkcode,tagfield, tagsubfield, tab, repeatable, mandatory,kohafield)
3269         SELECT DISTINCT (frameworkcode),995,"j",10,0,0,"items.stocknumber" from biblio_framework ;
3270                 });
3271                 #Previously, copynumber was used as stocknumber
3272                 $dbh->do(qq{
3273         UPDATE items set stocknumber=copynumber;
3274                 });
3275                 $dbh->do(qq{
3276         UPDATE items set copynumber=NULL;
3277                 });
3278         }
3279     print "Upgrade to $DBversion done (stocknumber field added)\n";
3280     SetVersion ($DBversion);
3281 }
3282
3283 $DBversion = "3.01.00.096";
3284 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3285     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OrderPdfTemplate','','Uploads a PDF template to use for printing baskets','NULL','Upload')");
3286     $dbh->do("UPDATE systempreferences SET variable='OrderPdfFormat' WHERE variable='pdfformat'");
3287     print "Upgrade to $DBversion done (PDF orders system preferences added and updated)\n";
3288     SetVersion ($DBversion);
3289 }
3290
3291 $DBversion = "3.01.00.097";
3292 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3293         $dbh->do(qq{
3294         ALTER TABLE aqbasketgroups ADD billingplace VARCHAR(10) NOT NULL AFTER deliverycomment;
3295         });
3296
3297     print "Upgrade to $DBversion done (Adding billingplace to aqbasketgroups)\n";
3298     SetVersion ($DBversion);
3299 }
3300
3301 $DBversion = "3.01.00.098";
3302 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3303         $dbh->do(qq{
3304         ALTER TABLE auth_subfield_structure MODIFY frameworkcode VARCHAR(10) NULL;
3305         });
3306
3307     print "Upgrade to $DBversion done (changing frameworkcode length in auth_subfield_structure)\n";
3308     SetVersion ($DBversion);
3309 }
3310
3311 $DBversion = "3.01.00.099";
3312 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3313         $dbh->do(qq{
3314                 INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3315                 (9, 'edit_catalogue', 'Edit catalogue'),
3316                 (9, 'fast_cataloging', 'Fast cataloging')
3317         });
3318
3319     print "Upgrade to $DBversion done (granular permissions for cataloging added)\n";
3320     SetVersion ($DBversion);
3321 }
3322
3323 $DBversion = "3.01.00.100";
3324 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3325         $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')");
3326         print "Upgrade to $DBversion done (added CAS authentication system preferences)\n";
3327     SetVersion ($DBversion);
3328 }
3329
3330 $DBversion = "3.01.00.101";
3331 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3332         $dbh->do(
3333         "INSERT INTO systempreferences
3334            (variable, value, options, explanation, type)
3335          VALUES (
3336             'OverdueNoticeBcc', '', '',
3337             'Email address to Bcc outgoing notices sent by email',
3338             'free')
3339          ");
3340         print "Upgrade to $DBversion done (added OverdueNoticeBcc system preferences)\n";
3341     SetVersion ($DBversion);
3342 }
3343 $DBversion = "3.01.00.102";
3344 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3345     $dbh->do(
3346     "UPDATE permissions set description = 'Edit catalog (Modify bibliographic/holdings data)' where module_bit = 9 and code = 'edit_catalogue'"
3347     );
3348         print "Upgrade to $DBversion done (fixed spelling error in edit_catalogue permission)\n";
3349     SetVersion ($DBversion);
3350 }
3351
3352 $DBversion = "3.01.00.103";
3353 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3354         $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES (13, 'moderate_tags', 'Moderate patron tags')");
3355         print "Upgrade to $DBversion done (adding patron permissions for tags tool)\n";
3356     SetVersion ($DBversion);
3357 }
3358
3359 $DBversion = "3.01.00.104";
3360 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3361
3362     my ($maninv_count, $borrnotes_count);
3363     eval { $maninv_count = $dbh->do("SELECT 1 FROM authorised_values WHERE category='MANUAL_INV'"); };
3364     if ($maninv_count == 0) {
3365         $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('MANUAL_INV','Copier Fees','.25')");
3366     }
3367     eval { $borrnotes_count = $dbh->do("SELECT 1 FROM authorised_values WHERE category='BOR_NOTES'"); };
3368     if ($borrnotes_count == 0) {
3369         $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('BOR_NOTES','ADDR','Address Notes')");
3370     }
3371
3372     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('LOC','CART','Book Cart')");
3373     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('LOC','PROC','Processing Center')");
3374
3375         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";
3376         SetVersion ($DBversion);
3377 }
3378
3379
3380 $DBversion = "3.01.00.105";
3381 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3382     $dbh->do("
3383       CREATE TABLE `collections` (
3384         `colId` int(11) NOT NULL auto_increment,
3385         `colTitle` varchar(100) NOT NULL default '',
3386         `colDesc` text NOT NULL,
3387         `colBranchcode` varchar(4) default NULL COMMENT 'branchcode for branch where item should be held.',
3388         PRIMARY KEY  (`colId`)
3389       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3390     ");
3391
3392     $dbh->do("
3393       CREATE TABLE `collections_tracking` (
3394         `ctId` int(11) NOT NULL auto_increment,
3395         `colId` int(11) NOT NULL default '0' COMMENT 'collections.colId',
3396         `itemnumber` int(11) NOT NULL default '0' COMMENT 'items.itemnumber',
3397         PRIMARY KEY  (`ctId`)
3398       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3399     ");
3400     $dbh->do("
3401         INSERT INTO permissions (module_bit, code, description)
3402         VALUES ( 13, 'rotating_collections', 'Manage Rotating collections')" );
3403         print "Upgrade to $DBversion done (added collection and collection_tracking tables for rotating collections functionality)\n";
3404     SetVersion ($DBversion);
3405 }
3406 $DBversion = "3.01.00.106";
3407 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3408         $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' )");
3409         print "Upgrade to $DBversion done (added OpacAddMastheadLibraryPulldown system preferences)\n";
3410     SetVersion ($DBversion);
3411 }
3412
3413 $DBversion = '3.01.00.107';
3414 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3415     my $upgrade_script = C4::Context->config("intranetdir") . "/installer/data/mysql/patroncards_upgrade.pl";
3416     system("perl $upgrade_script");
3417     print "Upgrade to $DBversion done (Migrated labels and patroncards tables and data to new schema.)\n";
3418     SetVersion ($DBversion);
3419 }
3420
3421 $DBversion = '3.01.00.108';
3422 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3423         $dbh->do(qq{
3424     ALTER TABLE `export_format` ADD `csv_separator` VARCHAR( 2 ) NOT NULL AFTER `marcfields` ,
3425     ADD `field_separator` VARCHAR( 2 ) NOT NULL AFTER `csv_separator` ,
3426     ADD `subfield_separator` VARCHAR( 2 ) NOT NULL AFTER `field_separator`
3427     });
3428         print "Upgrade to $DBversion done (added separators for csv export)\n";
3429     SetVersion ($DBversion);
3430 }
3431
3432 $DBversion = "3.01.00.109";
3433 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3434         $dbh->do(qq{
3435         ALTER TABLE `export_format` ADD `encoding` VARCHAR(255) NOT NULL AFTER `subfield_separator`
3436         });
3437         print "Upgrade to $DBversion done (added encoding for csv export)\n";
3438     SetVersion ($DBversion);
3439 }
3440
3441 $DBversion = '3.01.00.110';
3442 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3443     $dbh->do('ALTER TABLE `categories` ADD COLUMN `enrolmentperioddate` DATE NULL DEFAULT NULL AFTER `enrolmentperiod`');
3444     print "Upgrade to $DBversion done (Add enrolment period date support)\n";
3445     SetVersion ($DBversion);
3446 }
3447
3448 $DBversion = '3.01.00.111';
3449 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3450     print "Upgrade to $DBversion done (mark DBrev for 3.2-alpha release)\n";
3451     SetVersion ($DBversion);
3452 }
3453
3454 $DBversion = '3.01.00.112';
3455 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3456         $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');");
3457         print "Upgrade to $DBversion done ( added Show Spine Label Printer on Bib Items Details preferences )\n";
3458     SetVersion ($DBversion);
3459 }
3460
3461 $DBversion = '3.01.00.113';
3462 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3463     my $value = C4::Context->preference("XSLTResultsDisplay");
3464     $dbh->do(
3465         "INSERT INTO systempreferences (variable,value,type)
3466          VALUES('OPACXSLTResultsDisplay',?,'YesNo')", {}, $value ? 1 : 0);
3467     $value = C4::Context->preference("XSLTDetailsDisplay");
3468     $dbh->do(
3469         "INSERT INTO systempreferences (variable,value,type)
3470          VALUES('OPACXSLTDetailsDisplay',?,'YesNo')", {}, $value ? 1 : 0);
3471     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";
3472     SetVersion ($DBversion);
3473 }
3474
3475 $DBversion = '3.01.00.114';
3476 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3477     $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')");
3478     $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')");
3479     $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')");
3480         print "Upgrade to $DBversion done ( Added AutoSelfCheckAllowed, AutoSelfCheckID, and AutoShelfCheckPass system preference )\n";
3481     SetVersion ($DBversion);
3482 }
3483
3484 $DBversion = '3.01.00.115';
3485 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3486     $dbh->do('UPDATE aqorders SET quantityreceived = 0 WHERE quantityreceived IS NULL');
3487     $dbh->do('ALTER TABLE aqorders MODIFY COLUMN quantityreceived smallint(6) NOT NULL DEFAULT 0');
3488         print "Upgrade to $DBversion done ( Default aqorders.quantityreceived to 0 )\n";
3489     SetVersion ($DBversion);
3490 }
3491
3492 $DBversion = '3.01.00.116';
3493 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3494         if (C4::Context->preference('OrderPdfFormat') eq 'pdfformat::example'){
3495                 $dbh->do("UPDATE `systempreferences` set value='pdfformat::layout2pages' WHERE variable='OrderPdfFormat'");
3496         }
3497         print "Upgrade to $DBversion done (corrected default OrderPdfFormat value if still set wrong )\n";
3498     SetVersion ($DBversion);
3499 }
3500
3501 $DBversion = '3.01.00.117';
3502 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3503     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'por' WHERE rfc4646_subtag='pt' ");
3504     print "Upgrade to $DBversion done (corrected ISO 639-2 language code for Portuguese)\n";
3505     SetVersion ($DBversion);
3506 }
3507
3508 $DBversion = '3.01.00.118';
3509 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3510     my ($count) = $dbh->selectrow_array("SELECT count(*) FROM information_schema.columns
3511                                          WHERE table_name = 'aqbudgets_planning'
3512                                          AND column_name = 'display'");
3513     if ($count < 1) {
3514         $dbh->do("ALTER TABLE aqbudgets_planning ADD COLUMN display tinyint(1) DEFAULT 1");
3515     }
3516     print "Upgrade to $DBversion done (bug 4203: add display column to aqbudgets_planning if missing)\n";
3517     SetVersion ($DBversion);
3518 }
3519
3520 $DBversion = '3.01.00.119';
3521 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3522     eval{require Locale::Currency::Format};
3523     if (!$@) {
3524         print "Upgrade to $DBversion done (Locale::Currency::Format installed.)\n";
3525         SetVersion ($DBversion);
3526     }
3527     else {
3528         print "Upgrade to $DBversion done.\n";
3529         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";
3530         SetVersion ($DBversion);
3531     }
3532 }
3533
3534 $DBversion = '3.01.00.120';
3535 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3536     $dbh->do(q{
3537 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');
3538 });
3539     print "Upgrade to $DBversion done (bug 1080: add soundon system preference for circulation sounds)\n";
3540     SetVersion ($DBversion);
3541 }
3542
3543 $DBversion = '3.01.00.121';
3544 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3545     $dbh->do("ALTER TABLE `reserves` ADD `expirationdate` DATE DEFAULT NULL");
3546     $dbh->do("ALTER TABLE `reserves` ADD `lowestPriority` tinyint(1) NOT NULL");
3547     $dbh->do("ALTER TABLE `old_reserves` ADD `expirationdate` DATE DEFAULT NULL");
3548     $dbh->do("ALTER TABLE `old_reserves` ADD `lowestPriority` tinyint(1) NOT NULL");
3549     print "Upgrade to $DBversion done ( Added Additional Fields to Reserves tables )\n";
3550     SetVersion ($DBversion);
3551 }
3552
3553 $DBversion = '3.01.00.122';
3554 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3555     $dbh->do(q{
3556       INSERT INTO systempreferences (variable,value,explanation,options,type)
3557       VALUES ('OAI-PMH:ConfFile', '', 'If empty, Koha OAI Server operates in normal mode, otherwise it operates in extended mode.','','File');
3558 });
3559     print "Upgrade to $DBversion done. — Add a new system preference OAI-PMF:ConfFile\n";
3560     SetVersion ($DBversion);
3561 }
3562
3563 $DBversion = "3.01.00.123";
3564 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3565     $dbh->do("INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3566         (6, 'place_holds', 'Place holds for patrons')");
3567     $dbh->do("INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3568         (6, 'modify_holds_priority', 'Modify holds priority')");
3569     $dbh->do("UPDATE `userflags` SET `flagdesc` = 'Place and modify holds for patrons' WHERE `flag` = 'reserveforothers'");
3570     print "Upgrade to $DBversion done (Add granular permission for holds modification and update description of reserveforothers permission)\n";
3571     SetVersion ($DBversion);
3572 }
3573
3574 $DBversion = '3.01.00.124';
3575 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3576     $dbh->do("
3577         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>>).');
3578     ");
3579     print "Upgrade to $DBversion done (bug 3242: add HOLDPLACED letter template, which is used when emailLibrarianWhenHoldIsPlaced is enabled)\n";
3580     SetVersion ($DBversion);
3581 }
3582
3583 $DBversion = '3.01.00.125';
3584 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3585     $dbh->do("
3586         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' );
3587     ");
3588     $dbh->do("
3589         INSERT INTO message_transport_types (message_transport_type) values ('print');
3590     ");
3591     print "Upgrade to $DBversion done (bug 3482: Printable hold and overdue notices)\n";
3592     SetVersion ($DBversion);
3593 }
3594
3595 $DBversion = "3.01.00.126";
3596 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3597         $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')");
3598         $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')");
3599
3600     print "Upgrade to $DBversion done (Adding ILS-DI updates and ILS-DI:AuthorizedIPs)\n";
3601     SetVersion ($DBversion);
3602 }
3603
3604 $DBversion = '3.01.00.127';
3605 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3606     $dbh->do("ALTER TABLE messages CHANGE branchcode branchcode varchar(10);");
3607     print "Upgrade to $DBversion done (bug 4190: messages in patron account did not work with branchcodes > 4)\n";
3608     SetVersion ($DBversion);
3609 }
3610
3611 $DBversion = '3.01.00.128';
3612 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3613     $dbh->do('CREATE INDEX budget_id ON aqorders (budget_id );');
3614     print "Upgrade to $DBversion done (bug 4331: index orders by budget_id)\n";
3615     SetVersion ($DBversion);
3616 }
3617
3618 $DBversion = "3.01.00.129";
3619 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3620         $dbh->do("UPDATE `permissions` SET `code` = 'items_batchdel' WHERE `permissions`.`module_bit` =13 AND `permissions`.`code` = 'batchdel' LIMIT 1 ;");
3621         $dbh->do("UPDATE `permissions` SET `code` = 'items_batchmod' WHERE `permissions`.`module_bit` =13 AND `permissions`.`code` = 'batchmod' LIMIT 1 ;");
3622         print "Upgrade to $DBversion done (Change permissions names for item batch modification / deletion)\n";
3623
3624     SetVersion ($DBversion);
3625 }
3626
3627 $DBversion = "3.01.00.130";
3628 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3629     $dbh->do("UPDATE reserves SET expirationdate = NULL WHERE expirationdate = '0000-00-00'");
3630     print "Upgrade to $DBversion done (change reserves.expirationdate values of 0000-00-00 to NULL (bug 1532)\n";
3631     SetVersion ($DBversion);
3632 }
3633
3634 $DBversion = "3.01.00.131";
3635 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3636         $dbh->do(q{
3637 INSERT IGNORE INTO message_transport_types (message_transport_type) VALUES ('print'),('feed');
3638     });
3639     print "Upgrade to $DBversion done (adding print and feed message transport types)\n";
3640     SetVersion ($DBversion);
3641 }
3642
3643 $DBversion = "3.01.00.132";
3644 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3645         $dbh->do(q{
3646     ALTER TABLE language_descriptions ADD INDEX subtag_type_lang (subtag, type, lang);
3647     });
3648     print "Upgrade to $DBversion done (Adding index to language_descriptions table)\n";
3649     SetVersion ($DBversion);
3650 }
3651
3652 $DBversion = '3.01.00.133';
3653 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3654     $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')");
3655     print "Upgrade to $DBversion done (bug 4405: added OverduesBlockCirc syspref to control whether circulation is blocked if a borrower has overdues)\n";
3656     SetVersion ($DBversion);
3657 }
3658
3659 $DBversion = '3.01.00.134';
3660 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3661     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('DisplayMultiPlaceHold','1','Display the ability to place multiple holds or not','','YesNo')");
3662     print "Upgrade to $DBversion done (adding syspref DisplayMultiPlaceHold to control whether multiple holds can be placed from the search results page)\n";
3663     SetVersion ($DBversion);
3664 }
3665
3666 $DBversion = '3.01.00.135';
3667 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3668     $dbh->do("
3669         INSERT INTO `letter` (module, code, name, title, content) VALUES
3670 ('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')
3671 ");
3672     print "Upgrade to $DBversion done (bug 4377: added HOLD_PRINT message template)\n";
3673     SetVersion ($DBversion);
3674 }
3675
3676 $DBversion = '3.01.00.136';
3677 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3678     $dbh->do(qq{
3679 INSERT INTO permissions (module_bit, code, description) VALUES
3680    ( 9, 'edit_items', 'Edit Items');});
3681     print "Upgrade to $DBversion done (Adding a new permission to edit items)\n";
3682     SetVersion ($DBversion);
3683 }
3684
3685 $DBversion = "3.01.00.137";
3686 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3687         $dbh->do("
3688           INSERT INTO permissions (module_bit, code, description) VALUES
3689           (15, 'check_expiration', 'Check the expiration of a serial'),
3690           (15, 'claim_serials', 'Claim missing serials'),
3691           (15, 'create_subscription', 'Create a new subscription'),
3692           (15, 'delete_subscription', 'Delete an existing subscription'),
3693           (15, 'edit_subscription', 'Edit an existing subscription'),
3694           (15, 'receive_serials', 'Serials receiving'),
3695           (15, 'renew_subscription', 'Renew a subscription'),
3696           (15, 'routing', 'Routing');
3697                  ");
3698     print "Upgrade to $DBversion done (adding granular permissions for serials)\n";
3699     SetVersion ($DBversion);
3700 }
3701
3702 $DBversion = "3.01.00.138";
3703 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3704     $dbh->do("DELETE FROM systempreferences WHERE variable = 'GranularPermissions'");
3705     print "Upgrade to $DBversion done (bug 4896: removing GranularPermissions syspref; use of granular permissions is now the default)\n";
3706     SetVersion ($DBversion);
3707 }
3708
3709 $DBversion = '3.01.00.139';
3710 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3711     $dbh->do("ALTER TABLE message_attributes CHANGE message_name message_name varchar(40);");
3712     print "Upgrade to $DBversion done (bug 3682: change message_name from varchar(20) to varchar(40))\n";
3713     SetVersion ($DBversion);
3714 }
3715
3716 $DBversion = '3.01.00.140';
3717 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3718     $dbh->do("UPDATE systempreferences SET value = '0' WHERE variable = 'TagsModeration' AND value is NULL");
3719     print "Upgrade to $DBversion done (bug 4312 TagsModeration changed from NULL to 0)\n";
3720     SetVersion ($DBversion);
3721 }
3722
3723 $DBversion = '3.01.00.141';
3724 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3725     $dbh->do(qq{DELETE FROM message_attributes WHERE message_attribute_id=3;});
3726     $dbh->do(qq{DELETE FROM letter WHERE code='EVENT' AND title='Upcoming Library Event';});
3727     print "Upgrade to $DBversion done Remove upcoming events messaging option (bug 2434)\n";
3728     SetVersion ($DBversion);
3729 }
3730
3731 $DBversion = '3.01.00.142';
3732 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3733     $dbh->do(qq{DELETE FROM message_transports WHERE message_attribute_id=3;});
3734     print "Upgrade to $DBversion done (Remove upcoming events messaging option part 2 (bug 2434))\n";
3735     SetVersion ($DBversion);
3736 }
3737
3738 $DBversion = '3.01.00.143';
3739 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3740     $dbh->do(qq{CREATE INDEX auth_value_idx ON authorised_values (authorised_value)});
3741     $dbh->do(qq{CREATE INDEX auth_val_cat_idx ON borrower_attribute_types (authorised_value_category)});
3742     print "Upgrade to $DBversion done (Create index on authorised_values and borrower_attribute_types (bug 4139))\n";
3743     SetVersion ($DBversion);
3744 }
3745
3746 $DBversion = '3.01.00.144';
3747 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3748     $dbh->do(qq{UPDATE systempreferences SET value='normal' where value='default' and variable='IntranetBiblioDefaultView'});
3749     print "Upgrade to $DBversion done (Update the 'default' to 'normal' for the IntranetBiblioDefaultView syspref (bug 5007))\n";
3750     SetVersion ($DBversion);
3751 }
3752
3753 $DBversion = "3.01.00.145";
3754 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3755     $dbh->do("ALTER TABLE borrowers ADD KEY `guarantorid` (guarantorid);");
3756     print "Upgrade to $DBversion done (Add index on guarantorid)\n";
3757     SetVersion ($DBversion);
3758 }
3759
3760 $DBversion = '3.01.00.999';
3761 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3762     print "Upgrade to $DBversion done (3.2.0 release candidate)\n";
3763     SetVersion ($DBversion);
3764 }
3765
3766 $DBversion = "3.02.00.000";
3767 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3768     my $value = $dbh->selectrow_array("SELECT value FROM systempreferences WHERE variable = 'HomeOrHoldingBranch'");
3769     $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');");
3770     print "Upgrade to $DBversion done (Add HomeOrHoldingBranchReturn system preference)\n";
3771     SetVersion ($DBversion);
3772 }
3773
3774 $DBversion = "3.02.00.001";
3775 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3776     $dbh->do(q{DELETE FROM systempreferences WHERE variable IN (
3777                 'holdCancelLength',
3778                 'PINESISBN',
3779                 'sortbynonfiling',
3780                 'TemplateEncoding',
3781                 'OPACSubscriptionDisplay',
3782                 'OPACDisplayExtendedSubInfo',
3783                 'OAI-PMH:Set',
3784                 'OAI-PMH:Subset',
3785                 'libraryAddress',
3786                 'kohaspsuggest',
3787                 'OrderPdfTemplate',
3788                 'marc',
3789                 'acquisitions',
3790                 'MIME')
3791                }
3792     );
3793     print "Upgrade to $DBversion done (bug 3756: remove disused system preferences)\n";
3794     SetVersion ($DBversion);
3795 }
3796
3797 $DBversion = "3.02.00.002";
3798 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3799     $dbh->do(q{DELETE FROM systempreferences WHERE variable = 'OpacPrivacy'});
3800     print "Upgrade to $DBversion done (bug 3881: remove unused OpacPrivacy system preference)\n";
3801     SetVersion ($DBversion);
3802 }
3803
3804 $DBversion = "3.02.00.003";
3805 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3806     $dbh->do(q{UPDATE systempreferences SET variable = 'ILS-DI:AuthorizedIPs' WHERE variable = 'ILS-DI:Authorized_IPs'});
3807     print "Upgrade to $DBversion done (correct ILS-DI:AuthorizedIPs)\n";
3808     SetVersion ($DBversion);
3809 }
3810
3811 $DBversion = "3.02.00.004";
3812 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3813     print "Upgrade to $DBversion done (3.2.0 general release)\n";
3814     SetVersion ($DBversion);
3815 }
3816 # This is the point where 3.2.x and master diverged, we can use $original_version to make sure we don't
3817
3818 # apply updates that have already been done
3819
3820 $DBversion = "3.03.00.001";
3821 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.005")) {
3822     $dbh->do("DELETE FROM subscriptionroutinglist WHERE borrowernumber IS NULL;");
3823     $dbh->do("ALTER TABLE subscriptionroutinglist MODIFY COLUMN `borrowernumber` int(11) NOT NULL;");
3824     $dbh->do("DELETE FROM subscriptionroutinglist WHERE subscriptionid IS NULL;");
3825     $dbh->do("ALTER TABLE subscriptionroutinglist MODIFY COLUMN `subscriptionid` int(11) NOT NULL;");
3826     $dbh->do("CREATE TEMPORARY TABLE del_subscriptionroutinglist
3827               SELECT s1.routingid FROM subscriptionroutinglist s1
3828               WHERE EXISTS (SELECT * FROM subscriptionroutinglist s2
3829                             WHERE s2.borrowernumber = s1.borrowernumber
3830                             AND   s2.subscriptionid = s1.subscriptionid
3831                             AND   s2.routingid < s1.routingid);");
3832     $dbh->do("DELETE FROM subscriptionroutinglist
3833               WHERE routingid IN (SELECT routingid FROM del_subscriptionroutinglist);");
3834     $dbh->do("ALTER TABLE subscriptionroutinglist ADD UNIQUE (subscriptionid, borrowernumber);");
3835     $dbh->do("ALTER TABLE subscriptionroutinglist
3836                 ADD CONSTRAINT `subscriptionroutinglist_ibfk_1` FOREIGN KEY (`borrowernumber`)
3837                 REFERENCES `borrowers` (`borrowernumber`)
3838                 ON DELETE CASCADE ON UPDATE CASCADE");
3839     $dbh->do("ALTER TABLE subscriptionroutinglist
3840                 ADD CONSTRAINT `subscriptionroutinglist_ibfk_2` FOREIGN KEY (`subscriptionid`)
3841                 REFERENCES `subscription` (`subscriptionid`)
3842                 ON DELETE CASCADE ON UPDATE CASCADE");
3843     print "Upgrade to $DBversion done (Make subscriptionroutinglist more strict)\n";
3844     SetVersion ($DBversion);
3845 }
3846
3847 $DBversion = '3.03.00.002';
3848 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.006")) {
3849     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='arm' WHERE rfc4646_subtag='hy';");
3850     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='eng' WHERE rfc4646_subtag='en';");
3851     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'fi','fin');");
3852     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='fre' WHERE rfc4646_subtag='fr';");
3853     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'lo','lao');");
3854     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='ita' WHERE rfc4646_subtag='it';");
3855     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'sr','srp');");
3856     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'tet','tet');");
3857     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'ur','urd');");
3858
3859     print "Upgrade to $DBversion done (Correct language mappings)\n";
3860     SetVersion ($DBversion);
3861 }
3862
3863 $DBversion = '3.03.00.003';
3864 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.007")) {
3865     $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');");
3866     print "Upgrade to $DBversion done (Add UseTablesortForCirc syspref)\n";
3867     SetVersion ($DBversion);
3868 }
3869
3870 $DBversion = '3.03.00.004';
3871 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.001")) {
3872     my $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'ACCEPTED');
3873     $dbh->do(q/
3874 INSERT INTO `letter`
3875 (module, code, name, title, content)
3876 VALUES
3877 ('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>>')
3878 /) unless $count > 0;
3879     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'AVAILABLE');
3880     $dbh->do(q/
3881 INSERT INTO `letter`
3882 (module, code, name, title, content)
3883 VALUES
3884 ('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>>')
3885 /) unless $count > 0;
3886     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'ORDERED');
3887     $dbh->do(q/
3888 INSERT INTO `letter`
3889 (module, code, name, title, content)
3890 VALUES
3891 ('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>>')
3892 /) unless $count > 0;
3893     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'REJECTED');
3894     $dbh->do(q/
3895 INSERT INTO `letter`
3896 (module, code, name, title, content)
3897 VALUES
3898 ('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>>')
3899 /) unless $count > 0;
3900     print "Upgrade to $DBversion done (bug 5127: add default templates for suggestion status change notifications)\n";
3901     SetVersion ($DBversion);
3902 };
3903
3904 $DBversion = '3.03.00.005';
3905 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3906     $dbh->do("update `systempreferences` set options='whitespace|T-prefix|cuecat|libsuite8' where variable='itemBarcodeInputFilter'");
3907     print "Upgrade to $DBversion done (Add itemBarcodeInputFilter choice libsuite8)\n";
3908 }
3909
3910 $DBversion = '3.03.00.006';
3911 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.002")) {
3912     $dbh->do("ALTER TABLE deletedborrowers ADD `privacy` int(11) AFTER smsalertnumber;");
3913     $dbh->do("ALTER TABLE deletedborrowers CHANGE `cardnumber` `cardnumber` varchar(16);");
3914     print "Upgrade to $DBversion done (Fix differences between borrowers and deletedborrowers)\n";
3915     SetVersion ($DBversion);
3916 }
3917
3918 $DBversion = '3.03.00.007';
3919 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3920     $dbh->do("ALTER table suggestions ADD quantity SMALLINT(6) default NULL,
3921                 ADD currency VARCHAR(3) default NULL,
3922                 ADD price DECIMAL(28,6) default NULL,
3923                 ADD total DECIMAL(28,6) default NULL;
3924                 ");
3925     print "Upgrade to $DBversion done (Added acq related columns to suggestions)\n";
3926     SetVersion ($DBversion);
3927 }
3928
3929 $DBversion = '3.03.00.008';
3930 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3931     $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')");
3932     print "Upgrade to $DBversion done (adding syspref OPACNoResultsFound to control what displays when no results are found for a search in the OPAC.)\n";
3933     SetVersion ($DBversion);
3934 }
3935
3936 $DBversion = '3.03.00.009';
3937 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.003")) {
3938     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('IntranetUserCSS','','Add CSS to be included in the Intranet',NULL,'free')");
3939     print "Upgrade to $DBversion done (Add IntranetUserCSS syspref)\n";
3940     SetVersion ($DBversion);
3941 }
3942
3943 $DBversion = "3.03.00.010";
3944 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.02.001")) {
3945     $dbh->do("UPDATE `marc_subfield_structure` SET liblibrarian = 'Distance from earth' WHERE liblibrarian = 'Distrance from earth' AND tagfield = '034' AND tagsubfield = 'r';");
3946     $dbh->do("UPDATE `marc_subfield_structure` SET libopac = 'Distance from earth' WHERE libopac = 'Distrance from earth' AND tagfield = '034' AND tagsubfield = 'r';");
3947     print "Upgrade to $DBversion done (Fix misspelled 034r subfield in MARC21 Frameworks)\n";
3948     SetVersion ($DBversion);
3949 }
3950
3951 $DBversion = "3.03.00.011";
3952 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3953     $dbh->do("UPDATE aqbooksellers SET gstrate=NULL WHERE gstrate=0.0");
3954     print "Upgrade to $DBversion done (Bug 5186: allow GST rate to be set to 0)\n";
3955     SetVersion ($DBversion);
3956 }
3957
3958 $DBversion = "3.03.00.012";
3959 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3960    $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')");
3961    print "Upgrade to $DBversion done (Bug 2142: maxItemsInSearchResults syspref resurrected)\n";
3962    SetVersion ($DBversion);
3963 }
3964
3965 $DBversion = "3.03.00.013";
3966 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3967     $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')");
3968     print "Upgrade to $DBversion done (added 'OpacPublic' syspref)\n";
3969    SetVersion ($DBversion);
3970 }
3971
3972 $DBversion = "3.03.00.014";
3973 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3974     $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')");
3975     $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')");
3976     $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')");
3977     print "Upgrade to $DBversion done (Add flexible shelf browser constraints)\n";
3978     SetVersion ($DBversion);
3979 }
3980
3981 $DBversion = "3.03.00.015";
3982 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3983     if ( C4::Context->preference("marcflavour") eq "MARC21" ) {
3984         my $sth = $dbh->prepare(
3985 "INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`,
3986                              `tab`, `authorised_value`, `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`)
3987                              VALUES ( ?, '9', '9 (RLIN)', '9 (RLIN)', 0, 0, '', 6, '', '', '', 0, -5, '', '', '', NULL)"
3988         );
3989         $sth->execute('648');
3990         $sth->execute('654');
3991         $sth->execute('655');
3992         $sth->execute('656');
3993         $sth->execute('657');
3994         $sth->execute('658');
3995         $sth->execute('662');
3996         $sth->finish;
3997         print
3998 "Upgrade to $DBversion done (Bug 5619: Add subfield 9 to marc21 648,654,655,656,657,658,662)\n";
3999     }
4000     SetVersion($DBversion);
4001 }
4002
4003 $DBversion = '3.03.00.016';
4004 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4005     # reimplement OpacPrivacy system preference
4006     $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')");
4007     $dbh->do("ALTER TABLE `borrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
4008     $dbh->do("ALTER TABLE `deletedborrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
4009     print "Upgrade to $DBversion done (OpacPrivacy reimplementation)\n";
4010     SetVersion($DBversion);
4011 };
4012
4013 $DBversion = '3.03.00.017';
4014 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.001")) {
4015     $dbh->do("ALTER TABLE  `currency` CHANGE `rate` `rate` FLOAT( 15, 5 ) NULL DEFAULT NULL;");
4016     print "Upgrade to $DBversion done (Enable currency rates >= 100)\n";
4017     SetVersion ($DBversion);
4018 }
4019
4020 $DBversion = '3.03.00.018';
4021 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.002")) {
4022     $dbh->do( q|update language_descriptions set description = 'Nederlands' where lang = 'nl' and subtag = 'nl'|);
4023     $dbh->do( q|update language_descriptions set description = 'Dansk' where lang = 'da' and subtag = 'da'|);
4024     print "Upgrade to $DBversion done (Correct language descriptions)\n";
4025     SetVersion ($DBversion);
4026 }
4027
4028 $DBversion = '3.03.00.019';
4029 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.003")) {
4030     # Fix bokmål
4031     $dbh->do("UPDATE language_subtag_registry SET description = 'Norwegian bokm&#229;l' WHERE subtag = 'nb';");
4032     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'nb','nob');");
4033     $dbh->do("UPDATE language_descriptions SET description = 'Norsk bokm&#229;l' WHERE subtag = 'nb' AND lang = 'nb';");
4034     $dbh->do("UPDATE language_descriptions SET description = 'Norwegian bokm&#229;l' WHERE subtag = 'nb' AND lang = 'en';");
4035     $dbh->do("UPDATE language_descriptions SET description = 'Norvégien bokm&#229;l' WHERE subtag = 'nb' AND lang = 'fr';");
4036     # Add nynorsk
4037     $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'nn', 'language', 'Norwegian nynorsk','2011-02-14' )");
4038     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'nn','nno')");
4039     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'nb', 'Norsk nynorsk')");
4040     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'nn', 'Norsk nynorsk')");
4041     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'en', 'Norwegian nynorsk')");
4042     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'fr', 'Norvégien nynorsk')");
4043     print "Upgrade to $DBversion done (Correct language descriptions for Norwegian)\n";
4044     SetVersion ($DBversion);
4045 }
4046
4047 $DBversion = '3.03.00.020';
4048 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4049     $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')");
4050     $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')");
4051     print "Upgrade to $DBversion done (Bug 5811: Add sysprefs controlling overriding fines)\n";
4052     SetVersion($DBversion);
4053 };
4054
4055 $DBversion = '3.03.00.021';
4056 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.001")) {
4057     $dbh->do("ALTER TABLE items MODIFY enumchron TEXT");
4058     $dbh->do("ALTER TABLE deleteditems MODIFY enumchron TEXT");
4059     print "Upgrade to $DBversion done (bug 5642: longer serial enumeration)\n";
4060     SetVersion ($DBversion);
4061 }
4062
4063 $DBversion = '3.03.00.022';
4064 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4065     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('AuthoritiesLog','0','If ON, log edit/create/delete actions on authorities.','','YesNo');");
4066     print "Upgrade to $DBversion done (Add AuthoritiesLog syspref)\n";
4067     SetVersion ($DBversion);
4068 }
4069
4070 # due to a mismatch in kohastructure.sql some koha will have missing columns in aqbasketgroup
4071 # this attempts to fix that
4072 $DBversion = '3.03.00.023';
4073 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.002")) {
4074     my $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'billingplace'");
4075     $sth->execute;
4076     $dbh->do("ALTER TABLE aqbasketgroups ADD billingplace VARCHAR(10)") if ! $sth->fetchrow_hashref;
4077     $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'deliveryplace'");
4078     $sth->execute;
4079     $dbh->do("ALTER TABLE aqbasketgroups ADD deliveryplace VARCHAR(10)") if ! $sth->fetchrow_hashref;
4080     $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'deliverycomment'");
4081     $sth->execute;
4082     $dbh->do("ALTER TABLE aqbasketgroups ADD deliverycomment VARCHAR(255)") if ! $sth->fetchrow_hashref;
4083     print "Upgrade to $DBversion done (Reconcile aqbasketgroups)\n";
4084     SetVersion ($DBversion);
4085 }
4086
4087 $DBversion = '3.03.00.024';
4088 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4089     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('TraceCompleteSubfields','0','Force subject tracings to only match complete subfields.','0','YesNo')");
4090     $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')");
4091     print "Upgrade to $DBversion done (Add syspref to force whole-subfield matching on subject tracings)\n";
4092     SetVersion($DBversion);
4093 };
4094
4095 $DBversion = "3.03.00.025";
4096 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4097     $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')");
4098     print "Upgrade to $DBversion done (Add syspref to control if user can choose pickup branch for holds)\n";
4099     SetVersion ($DBversion);
4100 }
4101
4102 $DBversion = '3.03.00.026';
4103 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.003")) {
4104     $dbh->do("UPDATE `message_attributes` SET message_name='Item Due' WHERE message_attribute_id=1 AND message_name LIKE 'Item DUE'");
4105         print "Upgrade to $DBversion done ( fix capitalization in message type )\n";
4106     SetVersion ($DBversion);
4107 }
4108
4109 $DBversion = '3.03.00.027';
4110 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4111     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('displayFacetCount', '0', NULL, NULL, 'YesNo')");
4112     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('maxRecordsForFacets', '20', NULL, NULL, 'Integer')");
4113     print "Upgrade to $DBversion done (Preferences for facet count)\n";
4114     SetVersion ($DBversion);
4115 }
4116
4117 $DBversion = "3.03.00.028";
4118 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4119     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('FacetLabelTruncationLength', 20, 'Truncate facets length to','','free')");
4120     print "Upgrade to $DBversion done (Add FacetLabelTruncationLength syspref to control facets displayed length)\n";
4121     SetVersion ($DBversion);
4122 }
4123
4124 $DBversion = "3.03.00.029";
4125 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4126     $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')");
4127     print "Upgrade to $DBversion done (Add syspref to control if user can choose branch when making purchase suggestion)\n";
4128     SetVersion ($DBversion);
4129 }
4130
4131 $DBversion = "3.03.00.030";
4132 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4133     $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')");
4134     $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')");
4135     print "Upgrade to $DBversion done (Add sysprefs to control custom favicons)\n";
4136     SetVersion ($DBversion);
4137 }
4138
4139 $DBversion = "3.03.00.031";
4140 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4141     $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');");
4142     print "Upgrade to $DBversion done (Add syspref FineNotifyAtCheckin)\n";
4143     SetVersion ($DBversion);
4144 }
4145
4146 $DBversion = '3.03.00.032';
4147 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4148     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('TraceSubjectSubdivisions', 1, 'Create searches on all subdivisions for subject tracings.','1','YesNo')");
4149     print "Upgrade to $DBversion done ( include subdivisions when generating subject tracing searches )\n";
4150 }
4151
4152
4153 $DBversion = '3.03.00.033';
4154 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4155     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('StaffAuthorisedValueImages', '1', '', NULL, 'YesNo')");
4156     print "Upgrade to $DBversion done (System pref StaffAuthorisedValueImages)\n";
4157     SetVersion ($DBversion);
4158 }
4159
4160 $DBversion = '3.03.00.034';
4161 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4162     $dbh->do("ALTER TABLE `categories` ADD `hidelostitems` tinyint(1) NOT NULL default '0' AFTER `reservefee`");
4163     print "Upgrade to $DBversion done (Add hidelostitems preference to borrower categories)\n";
4164     SetVersion ($DBversion);
4165 }
4166
4167 $DBversion = '3.03.00.035';
4168 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4169     $dbh->do("ALTER TABLE `issuingrules` ADD hardduedate date default NULL AFTER issuelength");
4170     $dbh->do("ALTER TABLE `issuingrules` ADD hardduedatecompare tinyint NOT NULL default 0 AFTER hardduedate");
4171     my $duedate;
4172     if (C4::Context->preference("globalDueDate")) {
4173       $duedate = C4::Dates::format_date_in_iso(C4::Context->preference("globalDueDate"));
4174       $dbh->do("UPDATE `issuingrules` SET hardduedate = '$duedate', hardduedatecompare = 0");
4175     } elsif (C4::Context->preference("ceilingDueDate")) {
4176       $duedate = C4::Dates::format_date_in_iso(C4::Context->preference("ceilingDueDate"));
4177       $dbh->do("UPDATE `issuingrules` SET hardduedate = '$duedate', hardduedatecompare = -1");
4178     }
4179     $dbh->do("DELETE FROM `systempreferences` WHERE variable = 'globalDueDate' OR variable = 'ceilingDueDate'");
4180     print "Upgrade to $DBversion done (Move global and ceiling due dates to Circ Rules level)\n";
4181     SetVersion ($DBversion);
4182 }
4183
4184 $DBversion = '3.03.00.036';
4185 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4186     $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')");
4187     print "Upgrade to $DBversion done ( Make COinS optional in OPAC search results )\n";
4188     SetVersion ($DBversion);
4189 }
4190
4191 $DBversion = '3.03.00.037';
4192 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4193     $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')");
4194     $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')");
4195     print "Upgrade to $DBversion done (Add 'Display856uAsImage' and 'OPACDisplay856uAsImage' syspref)\n";
4196     SetVersion ($DBversion);
4197 }
4198
4199 $DBversion = '3.03.00.038';
4200 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4201     $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')");
4202     $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')");
4203     $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')");
4204     print "Upgrade to $DBversion done ( Add Self-checkout by Login system preferences )\n";
4205 }
4206
4207 $DBversion = "3.03.00.039";
4208 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4209     $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');");
4210     print "Upgrade to $DBversion done (Add syspref ShowReviewer)\n";
4211 }
4212
4213 $DBversion = "3.03.00.040";
4214 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4215     $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');");
4216     print "Upgrade to $DBversion done (Add syspref UseControlNumber)\n";
4217 }
4218
4219 $DBversion = "3.03.00.041";
4220 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4221     $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')");
4222     $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')");
4223     print "Upgrade to $DBversion done (Add sysprefs to control alternate holdings information display)\n";
4224     SetVersion ($DBversion);
4225 }
4226
4227 $DBversion = '3.03.00.042';
4228 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4229     stocknumber_checker();
4230     print "Upgrade to $DBversion done (5860 Index itemstocknumber)\n";
4231     SetVersion ($DBversion);
4232 }
4233
4234 sub stocknumber_checker { #code reused later on
4235   my @row;
4236   #drop the obsolete itemSStocknumber idx if it exists
4237   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemsstocknumberidx'");
4238   $dbh->do("ALTER TABLE `items` DROP INDEX `itemsstocknumberidx`;") if @row;
4239
4240   #check itemstocknumber idx; remove it if it is unique
4241   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemstocknumberidx' AND non_unique=0");
4242   $dbh->do("ALTER TABLE `items` DROP INDEX `itemstocknumberidx`;") if @row;
4243
4244   #add itemstocknumber index non-unique IF it still not exists
4245   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemstocknumberidx'");
4246   $dbh->do("ALTER TABLE items ADD INDEX itemstocknumberidx (stocknumber);") unless @row;
4247 }
4248
4249 $DBversion = "3.03.00.043";
4250 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4251
4252     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib,lib_opac) VALUES ('YES_NO','0','No','No')");
4253     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib,lib_opac) VALUES ('YES_NO','1','Yes','Yes')");
4254
4255         print "Upgrade to $DBversion done ( add generic boolean YES_NO authorised_values pair )\n";
4256         SetVersion ($DBversion);
4257 }
4258
4259 $DBversion = '3.03.00.044';
4260 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4261     $dbh->do("ALTER TABLE `aqbasketgroups` ADD `freedeliveryplace` TEXT NULL AFTER `deliveryplace`;");
4262     print "Upgrade to $DBversion done (adding freedeliveryplace to basketgroups)\n";
4263 }
4264
4265 $DBversion = '3.03.00.045';
4266 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4267     #Remove obsolete columns from aqbooksellers if needed
4268     my $a = $dbh->selectall_hashref('SHOW columns from aqbooksellers','Field');
4269     my $sqldrop="ALTER TABLE aqbooksellers DROP COLUMN ";
4270     foreach(qw/deliverydays followupdays followupscancel invoicedisc nocalc specialty/) {
4271       $dbh->do($sqldrop.$_) if exists $a->{$_};
4272     }
4273     #Remove obsolete column from aqbudgets if needed
4274     #The correct column is budget_notes
4275     $a = $dbh->selectall_hashref('SHOW columns from aqbudgets','Field');
4276     if(exists $a->{budget_description}) {
4277       $dbh->do("ALTER TABLE aqbudgets DROP COLUMN budget_description");
4278     }
4279     print "Upgrade to $DBversion done (Remove obsolete columns from aqbooksellers and aqbudgets if needed)\n";
4280     SetVersion ($DBversion);
4281 }
4282
4283 $DBversion = "3.03.00.046";
4284 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4285     $dbh->do("ALTER TABLE overduerules ALTER delay1 SET DEFAULT NULL, ALTER delay2 SET DEFAULT NULL, ALTER delay3 SET DEFAULT NULL");
4286     print "Upgrade to $DBversion done (Setting NULL default value for delayn columns in table overduerules)\n";
4287     SetVersion($DBversion);
4288 }
4289
4290 $DBversion = '3.03.00.047';
4291 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4292     $dbh->do("ALTER TABLE borrowers ADD `state` mediumtext AFTER city;");
4293     $dbh->do("ALTER TABLE borrowers ADD `B_state` mediumtext AFTER B_city;");
4294     $dbh->do("ALTER TABLE borrowers ADD `altcontactstate` mediumtext AFTER altcontactaddress3;");
4295     $dbh->do("ALTER TABLE deletedborrowers ADD `state` mediumtext AFTER city;");
4296     $dbh->do("ALTER TABLE deletedborrowers ADD `B_state` mediumtext AFTER B_city;");
4297     $dbh->do("ALTER TABLE deletedborrowers ADD `altcontactstate` mediumtext AFTER altcontactaddress3;");
4298     print "Upgrade to $DBversion done (Add state field to patron's addresses)\n";
4299 }
4300
4301 $DBversion = '3.03.00.048';
4302 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4303     $dbh->do("ALTER TABLE branches ADD `branchstate` mediumtext AFTER `branchcity`;");
4304     print "Upgrade to $DBversion done (Add state to branch address)\n";
4305     SetVersion ($DBversion);
4306 }
4307
4308 $DBversion = '3.03.00.049';
4309 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4310     $dbh->do("ALTER TABLE `accountlines` ADD `note` text NULL default NULL");
4311     $dbh->do("ALTER TABLE `accountlines` ADD `manager_id` int( 11 ) NULL ");
4312     print "Upgrade to $DBversion done (adding note and manager_id fields in accountlines table)\n";
4313     SetVersion($DBversion);
4314 }
4315
4316 $DBversion = "3.03.00.050";
4317 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4318     $dbh->do("
4319         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');
4320         ");
4321     print "Upgrade to $DBversion done (Adding OpacHiddenItems syspref)\n";
4322     SetVersion($DBversion);
4323 }
4324
4325 $DBversion = "3.03.00.051";
4326 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4327     print "Upgrade to $DBversion done (Remove spaces and dashes from message_attribute names)\n";
4328     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Due' WHERE message_name='Item Due'");
4329     $dbh->do("UPDATE message_attributes SET message_name = 'Advance_Notice' WHERE message_name='Advance Notice'");
4330     $dbh->do("UPDATE message_attributes SET message_name = 'Hold_Filled' WHERE message_name='Hold Filled'");
4331     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Check_in' WHERE message_name='Item Check-in'");
4332     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Checkout' WHERE message_name='Item Checkout'");
4333     SetVersion ($DBversion);
4334 }
4335
4336 $DBversion = "3.03.00.052";
4337 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4338     $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');");
4339     print "Upgrade to $DBversion done (Add syspref WaitingNotifyAtCheckin)\n";
4340     SetVersion ($DBversion);
4341 }
4342
4343 $DBversion = "3.04.00.000";
4344 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4345     print "Upgrade to $DBversion done Koha 3.4.0 release \n";
4346     SetVersion ($DBversion);
4347 }
4348
4349 $DBversion = "3.05.00.001";
4350 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4351     $dbh->do(qq{
4352     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');
4353     });
4354     print "Upgrade to $DBversion done (Adds New System preference numSearchRSSResults)\n";
4355     SetVersion($DBversion);
4356 }
4357
4358 $DBversion = '3.05.00.002';
4359 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4360     #follow up fix 5860: some installs already past 3.3.0.42
4361     stocknumber_checker();
4362     print "Upgrade to $DBversion done (Fix for stocknumber index)\n";
4363     SetVersion ($DBversion);
4364 }
4365
4366 $DBversion = "3.05.00.003";
4367 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4368     $dbh->do(qq{
4369     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');
4370     });
4371     print "Upgrade to $DBversion done (Adds New System preference OpacRenewalBranch)\n";
4372     SetVersion($DBversion);
4373 }
4374
4375 $DBversion = "3.05.00.004";
4376 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4377     $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');");
4378     print "Upgrade to $DBversion done (Add syspref ShowReviewerPhoto)\n";
4379     SetVersion($DBversion);
4380 }
4381
4382 $DBversion = "3.05.00.005";
4383 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4384     $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');");
4385     print "Upgrade to $DBversion done (Adds pref BasketConfirmations)\n";
4386     SetVersion($DBversion);
4387 }
4388
4389 $DBversion = "3.05.00.006";
4390 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4391     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('MARCAuthorityControlField008', '|| aca||aabn           | a|a     d', NULL, NULL, 'Textarea')");
4392     print "Upgrade to $DBversion done (Add syspref MARCAuthorityControlField008)\n";
4393     SetVersion ($DBversion);
4394 }
4395
4396 $DBversion = "3.05.00.007";
4397 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4398     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpenLibraryCovers',0,'If ON Openlibrary book covers will be show',NULL,'YesNo');");
4399     print "Upgrade to $DBversion done (Add syspref OpenLibraryCovers)\n";
4400     SetVersion($DBversion);
4401 }
4402
4403 $DBversion = "3.05.00.008";
4404 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4405     $dbh->do("ALTER TABLE `cities` ADD `city_state` VARCHAR( 100 ) NULL DEFAULT NULL AFTER  `city_name`;");
4406     $dbh->do("ALTER TABLE `cities` ADD `city_country` VARCHAR( 100 ) NULL DEFAULT NULL AFTER  `city_zipcode`;");
4407     print "Add state and country to cities table corresponding to new columns in borrowers\n";
4408     SetVersion($DBversion);
4409 }
4410
4411 $DBversion = "3.05.00.009";
4412 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4413     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4414               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE borrowernumber IS NULL");
4415     $dbh->do("DELETE FROM issues WHERE borrowernumber IS NULL");
4416
4417     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4418               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE itemnumber IS NULL");
4419     $dbh->do("DELETE FROM issues WHERE itemnumber IS NULL");
4420
4421     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4422               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowernumber = issues.borrowernumber)");
4423     $dbh->do("DELETE FROM issues WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowernumber = issues.borrowernumber)");
4424
4425     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4426               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE NOT EXISTS (SELECT * FROM items WHERE itemnumber = issues.itemnumber)");
4427     $dbh->do("DELETE FROM issues WHERE NOT EXISTS (SELECT * FROM items WHERE itemnumber = issues.itemnumber)");
4428
4429     $dbh->do("ALTER TABLE issues DROP FOREIGN KEY `issues_ibfk_1`");
4430     $dbh->do("ALTER TABLE issues DROP FOREIGN KEY `issues_ibfk_2`");
4431     $dbh->do("ALTER TABLE issues ALTER COLUMN borrowernumber DROP DEFAULT");
4432     $dbh->do("ALTER TABLE issues ALTER COLUMN itemnumber DROP DEFAULT");
4433     $dbh->do("ALTER TABLE issues MODIFY COLUMN borrowernumber int(11) NOT NULL");
4434     $dbh->do("ALTER TABLE issues MODIFY COLUMN itemnumber int(11) NOT NULL");
4435     $dbh->do("ALTER TABLE issues DROP KEY `issuesitemidx`");
4436     $dbh->do("ALTER TABLE issues ADD PRIMARY KEY (`itemnumber`)");
4437     $dbh->do("ALTER TABLE issues ADD CONSTRAINT `issues_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE RESTRICT ON UPDATE CASCADE");
4438     $dbh->do("ALTER TABLE issues ADD CONSTRAINT `issues_ibfk_2` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE RESTRICT ON UPDATE CASCADE");
4439
4440     print "Upgrade to $DBversion done (issues referential integrity)\n";
4441     SetVersion ($DBversion);
4442 }
4443
4444 $DBversion = "3.05.00.010";
4445 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4446     $dbh->do("CREATE INDEX priorityfoundidx ON reserves (priority,found)");
4447     print "Create an index on reserves to speed up holds awaiting pickup report bug 5866\n";
4448     SetVersion($DBversion);
4449 }
4450
4451
4452 $DBversion = "3.05.00.011";
4453 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4454     $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')");
4455     print "Upgrade to $DBversion done (add OPACResultsSidebar syspref (enh 6165))\n";
4456     SetVersion($DBversion);
4457 }
4458
4459 $DBversion = "3.05.00.012";
4460 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4461     $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')");
4462     print "Upgrade to $DBversion done (add RecordLocalUseOnReturn syspref (enh 6403))\n";
4463     SetVersion($DBversion);
4464 }
4465
4466 $DBversion = "3.05.00.013";
4467 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4468     $dbh->do(qq|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OpacKohaUrl','0',"Show 'Powered by Koha' text on OPAC footer.",NULL,NULL)|);
4469     print "Upgrade to $DBversion done (Add syspref 'OpacKohaUrl')\n";
4470     SetVersion($DBversion);
4471 }
4472
4473 $DBversion = "3.05.00.014";
4474 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4475     $dbh->do("ALTER TABLE `borrowers` MODIFY `userid` VARCHAR(75)");
4476     print "Modified userid column length into 75 in borrowers\n";
4477     SetVersion($DBversion);
4478 }
4479
4480 $DBversion = "3.05.00.015";
4481 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4482     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectEnabled',0,'Enable Novelist Select content.  Requires Novelist Profile and Password',NULL,'YesNo')");
4483     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectProfile',NULL,'Novelist Select user Password',NULL,'free')");
4484     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectPassword',NULL,'Enable Novelist user Profile',NULL,'free')");
4485     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectView','tab','Where to display Novelist Select content','tab|above|below|right','Choice')");
4486     print "Upgrade to $DBversion done (Add support for EBSCO's NoveList Select (enh 6902))\n";
4487     SetVersion($DBversion);
4488 }
4489
4490 $DBversion = '3.05.00.016';
4491 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4492     $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');");
4493     print "Upgrade to $DBversion done (Add EasyAnalyticalRecords syspref)\n";
4494     SetVersion ($DBversion);
4495 }
4496
4497 $DBversion = '3.05.00.017';
4498 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4499     if (C4::Context->preference("marcflavour") eq 'MARC21' ||
4500         C4::Context->preference("marcflavour") eq 'NORMARC'){
4501         $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)");
4502         $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)");
4503         print "Upgrade to $DBversion done (Add 773 subfield 9 and 0 to default framework)\n";
4504         SetVersion ($DBversion);
4505     } elsif (C4::Context->preference("marcflavour") eq 'UNIMARC'){
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 ('461', '9', 'Host Itemnumber', 'Host Itemnumber', 0, 0, NULL, 7, NULL, NULL, '', NULL, -6, '', '', '', NULL)");
4507         print "Upgrade to $DBversion done (Add 461 subfield 9 to default framework)\n";
4508         SetVersion ($DBversion);
4509     }
4510 }
4511
4512 $DBversion = "3.05.00.018";
4513 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4514     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacNavBottom','','Links after OpacNav links','70|10','Textarea')");
4515     print "Upgrade to $DBversion done (add OpacNavBottom syspref (enh 6825): if appropriate, you can split OpacNav into OpacNav and OpacNavBottom)\n";
4516     SetVersion($DBversion);
4517 }
4518
4519 $DBversion = "3.05.00.019";
4520 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4521     $dbh->do("UPDATE itemtypes SET imageurl = 'vokal/Book.png' WHERE imageurl = 'vokal/BOOK.png'");
4522     $dbh->do("UPDATE itemtypes SET imageurl = 'vokal/Book-32px.png' WHERE imageurl = 'vokal/BOOK-32px.png'");
4523     $dbh->do("UPDATE authorised_values SET imageurl = 'vokal/Book.png' WHERE imageurl = 'vokal/BOOK.png'");
4524     $dbh->do("UPDATE authorised_values SET imageurl = 'vokal/Book-32px.png' WHERE imageurl = 'vokal/BOOK-32px.png'");
4525     print "Upgrade to $DBversion done (remove duplicate VOKAL Book icons, bug 6862)\n";
4526     SetVersion($DBversion);
4527 }
4528
4529 $DBversion = "3.05.00.020";
4530 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4531     $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')");
4532     print "Upgrade to $DBversion done (Add syspref AcqViewBaskets)\n";
4533     SetVersion($DBversion);
4534 }
4535
4536 $DBversion = "3.05.00.021";
4537 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4538     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN display_checkout TINYINT(1) NOT NULL DEFAULT '0';");
4539     print "Upgrade to $DBversion done (Added a display_checkout field in borrower_attribute_types table)\n";
4540     SetVersion($DBversion);
4541 }
4542
4543 $DBversion = "3.05.00.022";
4544 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4545     $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");
4546     print "Upgrade to $DBversion done (6094: Fixing ModAuthority problems, add a need_merge_authorities table)\n";
4547     SetVersion($DBversion);
4548 }
4549
4550 $DBversion = "3.05.00.023";
4551 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4552     $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');");
4553     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";
4554     SetVersion($DBversion);
4555 }
4556
4557 $DBversion = "3.06.00.000";
4558 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4559     print "Upgrade to $DBversion done Koha 3.6.0 release \n";
4560     SetVersion ($DBversion);
4561 }
4562
4563 $DBversion = "3.07.00.001";
4564 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4565     my $borrowers = $dbh->selectcol_arrayref( "SELECT borrowernumber from borrowers where debarred =1;", { Columns => [1] } );
4566     $dbh->do("ALTER TABLE borrowers MODIFY debarred DATE DEFAULT NULL;");
4567     $dbh->do( "UPDATE borrowers set debarred='9999-12-31' where borrowernumber IN (" . join( ",", @$borrowers ) . ");" ) if ($borrowers and scalar(@$borrowers)>0);
4568     $dbh->do("ALTER TABLE borrowers ADD COLUMN debarredcomment VARCHAR(255) DEFAULT NULL AFTER debarred;");
4569     $dbh->do("ALTER TABLE deletedborrowers MODIFY debarred DATE DEFAULT NULL;");
4570     $dbh->do("ALTER TABLE deletedborrowers ADD COLUMN debarredcomment VARCHAR(255) DEFAULT NULL AFTER debarred;");
4571     print "Upgrade done (Change borrowers.debarred into Date )\n";
4572     SetVersion($DBversion);
4573 }
4574
4575 $DBversion = "3.07.00.002";
4576 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4577     $dbh->do("UPDATE borrowers SET debarred=NULL WHERE debarred='0000-00-00';");
4578     print "Setting NULL to debarred where 0000-00-00 is stored (bug 7272)\n";
4579     SetVersion($DBversion);
4580 }
4581
4582 $DBversion = "3.07.00.003";
4583 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4584     $dbh->do(" UPDATE `message_attributes` SET message_name='Item_Due' WHERE message_name='Item_DUE'");
4585     print "Updating message_name in message_attributes\n";
4586     SetVersion($DBversion);
4587 }
4588
4589 $DBversion = "3.07.00.004";
4590 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4591     $dbh->do("ALTER TABLE  `suggestions` ADD  `patronreason` TEXT NULL AFTER  `reason`");
4592     print "Upgrade to $DBversion done (Add column to suggestions table to store patrons' reasons for submitting a suggestion. )\n";
4593     SetVersion($DBversion);
4594 }
4595
4596 $DBversion = "3.07.00.005";
4597 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4598     $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')");
4599     print "Upgrade to $DBversion done (BorrowerUnwantedField syspref)\n";
4600     SetVersion ($DBversion);
4601 }
4602
4603 $DBversion = "3.07.00.006";
4604 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4605     $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');");
4606     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";
4607     SetVersion($DBversion);
4608 }
4609
4610 $DBversion = "3.07.00.007";
4611 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4612     $dbh->do("ALTER TABLE items MODIFY materials text;");
4613     print "Upgrade to $DBversion done alter items.material from varchar(10) to text \n";
4614     SetVersion($DBversion);
4615 }
4616
4617 $DBversion = '3.07.00.008';
4618 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4619     if (C4::Context->preference("marcflavour") eq 'MARC21') {
4620         if (C4::Context->preference("opaclanguages") eq "de") {
4621             $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, '');");
4622         } else {
4623             $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, '');");
4624         }
4625     }
4626     print "Upgrade to $DBversion done (add MARC21 field 545 to framework)\n";
4627     SetVersion ($DBversion);
4628 }
4629
4630 $DBversion = "3.07.00.009";
4631 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4632     $dbh->do("ALTER TABLE `aqorders` ADD COLUMN `claims_count` INT(11)  DEFAULT 0, ADD COLUMN `claimed_date` DATE  DEFAULT NULL AFTER `claims_count`");
4633     print "Upgrade to $DBversion done (Add claims_count and claimed_date fields in aqorders table)\n";
4634     SetVersion($DBversion);
4635 }
4636
4637 $DBversion = "3.07.00.010";
4638 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4639     $dbh->do(
4640         q|CREATE TABLE `biblioimages` (
4641           `imagenumber` int(11) NOT NULL AUTO_INCREMENT,
4642           `biblionumber` int(11) NOT NULL,
4643           `mimetype` varchar(15) NOT NULL,
4644           `imagefile` mediumblob NOT NULL,
4645           `thumbnail` mediumblob NOT NULL,
4646           PRIMARY KEY (`imagenumber`),
4647           CONSTRAINT `bibliocoverimage_fk1` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
4648           ) ENGINE=InnoDB DEFAULT CHARSET=utf8|
4649     );
4650     $dbh->do(
4651         q|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OPACLocalCoverImages','0','Display local cover images on OPAC search and details pages.','1','YesNo')|
4652         );
4653     $dbh->do(
4654         q|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('LocalCoverImages','0','Display local cover images on intranet search and details pages.','1','YesNo')|
4655         );
4656     $dbh->do(
4657         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')|
4658     );
4659     $dbh->do(
4660         q|INSERT INTO permissions (module_bit, code, description) VALUES (13, 'upload_local_cover_images', 'Upload local cover images')|
4661     );
4662     print "Upgrade to $DBversion done (Added support for local cover images)\n";
4663     SetVersion($DBversion);
4664 }
4665
4666 $DBversion = "3.07.00.011";
4667 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4668     $dbh->do(<<ENDOFRENEWAL);
4669     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');
4670 ENDOFRENEWAL
4671     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";
4672     SetVersion($DBversion);
4673 }
4674
4675 $DBversion = "3.07.00.012";
4676 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4677     $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')");
4678     print "Upgrade to $DBversion add 'AllowItemsOnHoldCheckout' syspref \n";
4679     SetVersion ($DBversion);
4680 }
4681
4682 $DBversion = "3.07.00.013";
4683 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4684     $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');");
4685     print "Upgrade to $DBversion done (Bug 7345: Add system preference OpacExportOptions.)\n";
4686     SetVersion ($DBversion);
4687 }
4688
4689 $DBversion = "3.07.00.014";
4690 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4691     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";
4692     SetVersion($DBversion);
4693 }
4694
4695 $DBversion = "3.07.00.015";
4696 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4697     my $sth = $dbh->prepare(q|
4698         SELECT COUNT(*) FROM marc_subfield_structure where kohafield="biblioitems.editionstatement"
4699         |);
4700     $sth->execute;
4701     my $already_exists = $sth->fetchrow;
4702     if ( not $already_exists ) {
4703         my $field = C4::Context->preference("marcflavour") eq "UNIMARC" ? "205" : "250";
4704         my $subfield = "a";
4705         my $sth = $dbh->prepare( q|
4706             UPDATE marc_subfield_structure SET kohafield = "biblioitems.editionstatement"
4707             WHERE tagfield = ? AND tagsubfield = ?
4708         |);
4709         $sth->execute( $field, $subfield );
4710         print "Upgrade to $DBversion done (Added a mapping for biblioitems.editionstatement.)\n";
4711     } else {
4712         print "Upgrade to $DBversion done (Added a mapping for biblioitems.editionstatement (already exists, nothing to do).)\n";
4713     }
4714     SetVersion($DBversion);
4715 }
4716
4717 $DBversion = "3.07.00.016";
4718 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4719     $dbh->do("ALTER TABLE items ADD KEY `itemcallnumber` (itemcallnumber)");
4720     print "Upgrade to $DBversion done (Added index on items.itemcallnumber)\n";
4721     SetVersion($DBversion);
4722 }
4723
4724 $DBversion = "3.07.00.017";
4725 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4726     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('TransferWhenCancelAllWaitingHolds','0','Transfer items when cancelling all waiting holds',NULL,'YesNo')");
4727     print "Upgrade to $DBversion done (Add sysprefs to control transfer when cancel all waiting holds)\n";
4728     SetVersion ($DBversion);
4729 }
4730
4731 $DBversion = "3.07.00.018";
4732 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4733     $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;");
4734     print "Upgrade to $DBversion done ( adding offline operations table )\n";
4735     SetVersion($DBversion);
4736 }
4737
4738 $DBversion = "3.07.00.019";
4739 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4740     $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");
4741     $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");
4742     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";
4743     SetVersion($DBversion);
4744 }
4745
4746 $DBversion = "3.07.00.020";
4747 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4748     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OPACpatronimages',0,'Enable patron images in the OPAC',NULL,'YesNo');");
4749     print "Upgrade to $DBversion done (Bug 3516: Add the option to show patron images in the OPAC.)\n";
4750     SetVersion($DBversion);
4751 }
4752
4753 $DBversion = "3.07.00.021";
4754 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4755     $dbh->do(
4756     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('LinkerModule','Default','Chooses which linker module to use (see documentation).','Default|FirstMatchLastMatch','Choice');"
4757     );
4758     $dbh->do(
4759     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('LinkerOptions','','A pipe-separated list of options for the linker.','','free');"
4760     );
4761     $dbh->do(
4762     "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');"
4763     );
4764     $dbh->do(
4765     "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');"
4766     );
4767     $dbh->do(
4768     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AutoCreateAuthorities',0,'Automatically create authorities that do not exist when cataloging records.',NULL,'YesNo');"
4769     );
4770     $dbh->do(
4771     "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');"
4772     );
4773     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";
4774     SetVersion($DBversion);
4775 }
4776
4777 $DBversion = "3.07.00.022";
4778 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4779     $dbh->do("DELETE FROM reviews WHERE biblionumber NOT IN (SELECT biblionumber from biblio)");
4780     $dbh->do("UPDATE reviews SET borrowernumber = NULL WHERE borrowernumber NOT IN (SELECT borrowernumber FROM borrowers)");
4781     $dbh->do("ALTER TABLE reviews ADD CONSTRAINT reviews_ibfk_2 FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE");
4782     $dbh->do("ALTER TABLE reviews ADD CONSTRAINT reviews_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber ) ON UPDATE CASCADE ON DELETE SET NULL");
4783     print "Upgrade to $DBversion done (Bug 7493 - Add constraint linking OPAC comment biblionumber to biblio, OPAC comment borrowernumber to borrowers.)\n";
4784     SetVersion($DBversion);
4785 }
4786
4787 $DBversion = "3.07.00.023";
4788 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4789     $dbh->do("ALTER TABLE `message_transports` DROP FOREIGN KEY `message_transports_ibfk_3`");
4790     $dbh->do("ALTER TABLE `letter` DROP PRIMARY KEY");
4791     $dbh->do("ALTER TABLE `letter` ADD `branchcode` varchar(10) default NULL AFTER `code`");
4792     $dbh->do("ALTER TABLE `letter` ADD PRIMARY KEY  (`module`,`code`, `branchcode`)");
4793     $dbh->do("ALTER TABLE `message_transports` ADD `branchcode` varchar(10) NOT NULL default ''");
4794     $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");
4795     $dbh->do("ALTER TABLE `letter` ADD `is_html` tinyint(1) default 0 AFTER `name`");
4796
4797     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4798               VALUES ('circulation','ISSUESLIP','Issue Slip','Issue Slip', '<h3><<branches.branchname>></h3>
4799 Checked out to <<borrowers.title>> <<borrowers.firstname>> <<borrowers.initials>> <<borrowers.surname>> <br />
4800 (<<borrowers.cardnumber>>) <br />
4801
4802 <<today>><br />
4803
4804 <h4>Checked Out</h4>
4805 <checkedout>
4806 <p>
4807 <<biblio.title>> <br />
4808 Barcode: <<items.barcode>><br />
4809 Date due: <<issues.date_due>><br />
4810 </p>
4811 </checkedout>
4812
4813 <h4>Overdues</h4>
4814 <overdue>
4815 <p>
4816 <<biblio.title>> <br />
4817 Barcode: <<items.barcode>><br />
4818 Date due: <<issues.date_due>><br />
4819 </p>
4820 </overdue>
4821
4822 <hr>
4823
4824 <h4 style=\"text-align: center; font-style:italic;\">News</h4>
4825 <news>
4826 <div class=\"newsitem\">
4827 <h5 style=\"margin-bottom: 1px; margin-top: 1px\"><b><<opac_news.title>></b></h5>
4828 <p style=\"margin-bottom: 1px; margin-top: 1px\"><<opac_news.new>></p>
4829 <p class=\"newsfooter\" style=\"font-size: 8pt; font-style:italic; margin-bottom: 1px; margin-top: 1px\">Posted on <<opac_news.timestamp>></p>
4830 <hr />
4831 </div>
4832 </news>', 1)");
4833     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4834               VALUES ('circulation','ISSUEQSLIP','Issue Quick Slip','Issue Quick Slip', '<h3><<branches.branchname>></h3>
4835 Checked out to <<borrowers.title>> <<borrowers.firstname>> <<borrowers.initials>> <<borrowers.surname>> <br />
4836 (<<borrowers.cardnumber>>) <br />
4837
4838 <<today>><br />
4839
4840 <h4>Checked Out Today</h4>
4841 <checkedout>
4842 <p>
4843 <<biblio.title>> <br />
4844 Barcode: <<items.barcode>><br />
4845 Date due: <<issues.date_due>><br />
4846 </p>
4847 </checkedout>', 1)");
4848     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4849               VALUES ('circulation','RESERVESLIP','Reserve Slip','Reserve Slip', '<h5>Date: <<today>></h5>
4850
4851 <h3> Transfer to/Hold in <<branches.branchname>></h3>
4852
4853 <h3><<borrowers.surname>>, <<borrowers.firstname>></h3>
4854
4855 <ul>
4856     <li><<borrowers.cardnumber>></li>
4857     <li><<borrowers.phone>></li>
4858     <li> <<borrowers.address>><br />
4859          <<borrowers.address2>><br />
4860          <<borrowers.city >>  <<borrowers.zipcode>>
4861     </li>
4862     <li><<borrowers.email>></li>
4863 </ul>
4864 <br />
4865 <h3>ITEM ON HOLD</h3>
4866 <h4><<biblio.title>></h4>
4867 <h5><<biblio.author>></h5>
4868 <ul>
4869    <li><<items.barcode>></li>
4870    <li><<items.itemcallnumber>></li>
4871    <li><<reserves.waitingdate>></li>
4872 </ul>
4873 <p>Notes:
4874 <pre><<reserves.reservenotes>></pre>
4875 </p>', 1)");
4876     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4877               VALUES ('circulation','TRANSFERSLIP','Transfer Slip','Transfer Slip', '<h5>Date: <<today>></h5>
4878 <h3>Transfer to <<branches.branchname>></h3>
4879
4880 <h3>ITEM</h3>
4881 <h4><<biblio.title>></h4>
4882 <h5><<biblio.author>></h5>
4883 <ul>
4884    <li><<items.barcode>></li>
4885    <li><<items.itemcallnumber>></li>
4886 </ul>', 1)");
4887
4888     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('NoticeCSS','','Notices CSS url.',NULL,'free')");
4889     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('SlipCSS','','Slips CSS url.',NULL,'free')");
4890
4891     $dbh->do("UPDATE `letter` SET content = replace(content, '<<title>>', '<<biblio.title>>') WHERE code = 'HOLDPLACED'");
4892
4893     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";
4894     SetVersion($DBversion);
4895 }
4896
4897 $DBversion = "3.07.00.024";
4898 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4899     $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')");
4900     $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')");
4901     print "Upgrade to $DBversion done (Added system preference ExpireReservesMaxPickUpDelay, system preference ExpireReservesMaxPickUpDelayCharge, add reseves.charge_if_expired)\n";
4902 }
4903
4904 $DBversion = "3.07.00.025";
4905 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4906     if (TableExists('bibliocoverimage')) {
4907         $dbh->do( q|DROP TABLE bibliocoverimage;| );
4908         $dbh->do(
4909             q|CREATE TABLE biblioimages (
4910               imagenumber int(11) NOT NULL AUTO_INCREMENT,
4911               biblionumber int(11) NOT NULL,
4912               mimetype varchar(15) NOT NULL,
4913               imagefile mediumblob NOT NULL,
4914               thumbnail mediumblob NOT NULL,
4915               PRIMARY KEY (imagenumber),
4916               CONSTRAINT bibliocoverimage_fk1 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
4917               ) ENGINE=InnoDB DEFAULT CHARSET=utf8;|
4918         );
4919     }
4920     print "Upgrade to $DBversion done (Correct table name for local cover images if needed. )\n";
4921     SetVersion($DBversion);
4922 }
4923
4924 $DBversion = "3.07.00.026";
4925 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4926     $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');");
4927     print "Upgrade to $DBversion done (Add syspref CalendarFirstDayOfWeek used to select the first day of week to use in the calendar. )\n";
4928     SetVersion($DBversion);
4929 }
4930
4931 $DBversion = "3.07.00.027";
4932 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4933     $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');});
4934     print "Upgrade to $DBversion done (Added system preference RoutingListNote for adding a general note to all routing lists.)\n";
4935     SetVersion($DBversion);
4936 }
4937
4938 $DBversion = "3.07.00.028";
4939 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4940     $dbh->do(qq{
4941     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');
4942     });
4943     print "Upgrade to $DBversion done (Bug 6296 New System preference AllowPKIAuth)\n";
4944 }
4945
4946 $DBversion = "3.07.00.029";
4947 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4948     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_descriptions`;});
4949     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_mappings`;});
4950     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_biblios`;});
4951     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets`;});
4952
4953     $dbh->do(q{
4954         CREATE TABLE `oai_sets` (
4955           `id` int(11) NOT NULL auto_increment,
4956           `spec` varchar(80) NOT NULL UNIQUE,
4957           `name` varchar(80) NOT NULL,
4958           PRIMARY KEY (`id`)
4959         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4960     });
4961
4962     $dbh->do(q{
4963         CREATE TABLE `oai_sets_descriptions` (
4964           `set_id` int(11) NOT NULL,
4965           `description` varchar(255) NOT NULL,
4966           CONSTRAINT `oai_sets_descriptions_ibfk_1` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4967         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4968     });
4969
4970     $dbh->do(q{
4971         CREATE TABLE `oai_sets_mappings` (
4972           `set_id` int(11) NOT NULL,
4973           `marcfield` char(3) NOT NULL,
4974           `marcsubfield` char(1) NOT NULL,
4975           `marcvalue` varchar(80) NOT NULL,
4976           CONSTRAINT `oai_sets_mappings_ibfk_1` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4977         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4978     });
4979
4980     $dbh->do(q{
4981         CREATE TABLE `oai_sets_biblios` (
4982           `biblionumber` int(11) NOT NULL,
4983           `set_id` int(11) NOT NULL,
4984           PRIMARY KEY (`biblionumber`, `set_id`),
4985           CONSTRAINT `oai_sets_biblios_ibfk_1` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
4986           CONSTRAINT `oai_sets_biblios_ibfk_2` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4987         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4988     });
4989
4990     $dbh->do(q{
4991         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');
4992     });
4993
4994     print "Upgrade to $DBversion done (Atomic update for OAI-PMH sets management)\n";
4995     SetVersion($DBversion);
4996 }
4997
4998 $DBversion = "3.07.00.030";
4999 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5000     $dbh->do("ALTER TABLE default_circ_rules ADD
5001             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5002     $dbh->do("ALTER TABLE branch_item_rules ADD
5003             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5004     $dbh->do("ALTER TABLE default_branch_circ_rules ADD
5005             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5006     $dbh->do("ALTER TABLE default_branch_item_rules ADD
5007             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5008     # set the default rule to the current value of HomeOrHoldingBranchReturn (default to 'homebranch' if need be)
5009     my $homeorholdingbranchreturn = C4::Context->preference('HomeOrHoldingBranchReturn') || 'homebranch';
5010     $dbh->do("UPDATE default_circ_rules SET returnbranch = '$homeorholdingbranchreturn'");
5011     print "Upgrade to $DBversion done (Atomic update for OAI-PMH sets management)\n";
5012     SetVersion($DBversion);
5013 }
5014
5015 $DBversion = "3.07.00.031";
5016 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5017     $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')");
5018     print "Upgrade to $DBversion done (Add syspref to tell Koha if ICU indexing is in use for Zebra or not.)\n";
5019     SetVersion ($DBversion);
5020 }
5021
5022 $DBversion = "3.07.00.032";
5023 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5024     $dbh->do("ALTER TABLE virtualshelves MODIFY COLUMN owner int"); #should have been int already (fk to borrowers)
5025     $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
5026     $dbh->do("DELETE FROM virtualshelves WHERE owner IS NULL and category=1"); #delete private lists without owner (cascades to shelfcontents)
5027     $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");
5028     $dbh->do("UPDATE virtualshelves SET allow_add=0, allow_delete_own=1, allow_delete_other=0 WHERE category=1");
5029     $dbh->do("UPDATE virtualshelves SET allow_add=0, allow_delete_own=1, allow_delete_other=0 WHERE category=2");
5030     $dbh->do("UPDATE virtualshelves SET allow_add=1, allow_delete_own=1, allow_delete_other=1 WHERE category=3");
5031     $dbh->do("UPDATE virtualshelves SET category=2 WHERE category=3");
5032
5033     $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");
5034     $dbh->do("UPDATE virtualshelfcontents co LEFT JOIN virtualshelves sh USING (shelfnumber) SET co.borrowernumber=sh.owner");
5035
5036     $dbh->do("CREATE TABLE virtualshelfshares
5037     (id int AUTO_INCREMENT PRIMARY KEY, shelfnumber int NOT NULL,
5038     borrowernumber int, invitekey varchar(10), sharedate datetime,
5039     CONSTRAINT `virtualshelfshares_ibfk_1` FOREIGN KEY (`shelfnumber`) REFERENCES `virtualshelves` (`shelfnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
5040         CONSTRAINT `virtualshelfshares_ibfk_2` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE SET NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8");
5041
5042     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacAllowPublicListCreation',1,'If set, allows opac users to create public lists',NULL,'YesNo');");
5043     $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');");
5044
5045     print "Upgrade to $DBversion done (BZ7310: Improving list permissions)\n";
5046     SetVersion($DBversion);
5047 }
5048
5049 $DBversion = "3.07.00.033";
5050 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5051     $dbh->do("ALTER TABLE branches ADD opac_info text;");
5052     print "Upgrade to $DBversion done add opac_info to branches \n";
5053     SetVersion($DBversion);
5054 }
5055
5056 $DBversion = "3.07.00.034";
5057 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5058     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN category_code VARCHAR(10) NULL DEFAULT NULL AFTER `display_checkout`");
5059     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN class VARCHAR(255)  NOT NULL DEFAULT '' AFTER `category_code`");
5060     $dbh->do("ALTER TABLE borrower_attribute_types ADD CONSTRAINT category_code_fk FOREIGN KEY (category_code) REFERENCES categories(categorycode)");
5061     print "Upgrade to $DBversion done (New fields category_code and class in borrower_attribute_types table)\n";
5062     SetVersion($DBversion);
5063 }
5064
5065 $DBversion = "3.07.00.035";
5066 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5067     $dbh->do("ALTER TABLE issues CHANGE date_due date_due datetime");
5068     $dbh->do("UPDATE issues SET date_due = CONCAT(SUBSTR(date_due,1,11),'23:59:00')");
5069     $dbh->do("ALTER TABLE issues CHANGE returndate returndate datetime");
5070     $dbh->do("ALTER TABLE issues CHANGE lastreneweddate lastreneweddate datetime");
5071     $dbh->do("ALTER TABLE issues CHANGE issuedate issuedate datetime");
5072     $dbh->do("ALTER TABLE old_issues CHANGE date_due date_due datetime");
5073     $dbh->do("ALTER TABLE old_issues CHANGE returndate returndate datetime");
5074     $dbh->do("ALTER TABLE old_issues CHANGE lastreneweddate lastreneweddate datetime");
5075     $dbh->do("ALTER TABLE old_issues CHANGE issuedate issuedate datetime");
5076     $dbh->do("UPDATE accountlines SET description = CONCAT(description,' 23:59') WHERE accounttype='F' OR accounttype='FU'"); #BUG-8253
5077     print "Upgrade to $DBversion done (Setting up issues and accountlines tables for hourly loans)\n";
5078     SetVersion($DBversion);
5079 }
5080
5081 $DBversion = "3.07.00.036";
5082 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5083     $dbh->do(qq{
5084        ALTER TABLE z3950servers ADD timeout INT( 11 ) NOT NULL DEFAULT '0' AFTER syntax;
5085     });
5086     print "Upgrade to $DBversion done (New timeout field in z3950servers)\n";
5087 }
5088
5089 $DBversion = "3.07.00.037";
5090 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5091     $dbh->do("
5092        ALTER TABLE  `marc_subfield_structure` ADD  `maxlength` INT( 4 ) NOT NULL DEFAULT  '9999';
5093        ");
5094        $dbh->do("
5095        UPDATE `marc_subfield_structure` SET maxlength=24 WHERE tagfield='000';
5096        ");
5097        $dbh->do("
5098        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='MARC21','40','9999') WHERE tagfield='008';
5099        ");
5100        $dbh->do("
5101        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='NORMARC','40','9999') WHERE tagfield='008';
5102        ");
5103        $dbh->do("
5104        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='UNIMARC','36','9999') WHERE tagfield='100';
5105        ");
5106     print "Upgrade to $DBversion done (Add new field maxlength to marc_subfield_structure)\n";
5107     SetVersion($DBversion);
5108 }
5109
5110 $DBversion = "3.07.00.038";
5111 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5112     $dbh->do(qq{
5113         INSERT INTO systempreferences(variable,value,explanation,options,type)
5114         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')
5115     });
5116     print "Upgrade to $DBversion done (Added system preference 'UniqueItemFields')\n";
5117     SetVersion($DBversion);
5118 }
5119
5120 $DBversion = "3.07.00.039";
5121 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5122     $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')} );
5123     $dbh->do( qq{CREATE TABLE IF NOT EXISTS social_data
5124       ( isbn VARCHAR(30),
5125         num_critics INT,
5126         num_critics_pro INT,
5127         num_quotations INT,
5128         num_videos INT,
5129         score_avg DECIMAL(5,2),
5130         num_scores INT,
5131         PRIMARY KEY  (isbn)
5132       ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5133     } );
5134     $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')} );
5135     print "Upgrade to $DBversion done (added syspref and table for babeltheque (Babeltheque_url_js, babeltheque))\n";
5136     SetVersion($DBversion);
5137 }
5138
5139 $DBversion = "3.07.00.040";
5140 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5141     $dbh->do( qq{INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('SocialNetworks','0','Enable/Disable social networks links in opac detail','','YesNo')} );
5142     print "Upgrade to $DBversion done (added syspref SocialNetworks, to display facebook/ggl+ and other buttons)\n";
5143     SetVersion($DBversion);
5144 }
5145
5146
5147
5148 $DBversion = "3.07.00.041";
5149 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5150     $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')");
5151     print "Upgrade to $DBversion done (Add system preference SubscriptionDuplicateDroppedInput)\n";
5152     SetVersion($DBversion);
5153 }
5154
5155 $DBversion = "3.07.00.042";
5156 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5157     $dbh->do("ALTER TABLE reserves ADD suspend BOOLEAN NOT NULL DEFAULT 0");
5158     $dbh->do("ALTER TABLE old_reserves ADD suspend BOOLEAN NOT NULL DEFAULT 0");
5159
5160     $dbh->do("ALTER TABLE reserves ADD suspend_until DATETIME NULL DEFAULT NULL");
5161     $dbh->do("ALTER TABLE old_reserves ADD suspend_until DATETIME NULL DEFAULT NULL");
5162
5163     $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')");
5164
5165     print "Upgrade to $DBversion done (Add suspend fields to reserves table, add syspref AutoResumeSuspendedHolds)\n";
5166     SetVersion ($DBversion);
5167 }
5168
5169 $DBversion = "3.07.00.043";
5170 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5171     my $countXSLTDetailsDisplay = 0;
5172     my $valueXSLTDetailsDisplay = "";
5173     my $valueXSLTResultsDisplay = "";
5174     my $valueOPACXSLTDetailsDisplay = "";
5175     my $valueOPACXSLTResultsDisplay = "";
5176     #the line below test if database comes from a BibLibre's branch
5177     $countXSLTDetailsDisplay = $dbh->do('SELECT 1 FROM systempreferences WHERE variable="IntranetXSLTDetailsDisplay"');
5178     if ($countXSLTDetailsDisplay > 0)
5179     {
5180         #the two lines below will only be used to update the databases from the BibLibre's branch. They will not affect the others
5181         $dbh->do(q|UPDATE systempreferences SET variable="XSLTDetailsDisplay" WHERE variable="IntranetXSLTDetailsDisplay"|);
5182         $dbh->do(q|UPDATE systempreferences SET variable="XSLTResultsDisplay" WHERE variable="IntranetXSLTResultsDisplay"|);
5183     }
5184     else
5185     {
5186         $valueXSLTDetailsDisplay = "default" if (C4::Context->preference("XSLTDetailsDisplay"));
5187         $valueXSLTResultsDisplay = "default" if (C4::Context->preference("XSLTResultsDisplay"));
5188         $valueOPACXSLTDetailsDisplay = "default" if (C4::Context->preference("OPACXSLTDetailsDisplay"));
5189         $valueOPACXSLTResultsDisplay = "default" if (C4::Context->preference("OPACXSLTResultsDisplay"));
5190         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueXSLTDetailsDisplay\" WHERE variable='XSLTDetailsDisplay'");
5191         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueXSLTResultsDisplay\" WHERE variable='XSLTResultsDisplay'");
5192         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueOPACXSLTDetailsDisplay\" WHERE variable='OPACXSLTDetailsDisplay'");
5193         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueOPACXSLTResultsDisplay\" WHERE variable='OPACXSLTResultsDisplay'");
5194     }
5195     print "Upgrade to $DBversion done (XSLT systempreference takes a path to file rather than YesNo)\n";
5196     SetVersion($DBversion);
5197 }
5198
5199 $DBversion = "3.07.00.044";
5200 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5201     $dbh->do("ALTER TABLE aqbooksellers ADD deliverytime INT DEFAULT NULL");
5202     print "Upgrade to $DBversion done (Add deliverytime field in aqbooksellers table)";
5203     SetVersion($DBversion);
5204 }
5205
5206 $DBversion = "3.07.00.045";
5207 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5208     $dbh->do("ALTER TABLE import_batches MODIFY COLUMN batch_type ENUM('batch','z3950','webservice') NOT NULL default 'batch'");
5209     print "Upgrade to $DBversion done (Add 'webservice' to batch_type enum)\n";
5210     SetVersion ($DBversion);
5211 }
5212
5213 $DBversion = "3.07.00.046";
5214 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5215     $dbh->do("ALTER TABLE issuingrules ADD COLUMN lengthunit varchar(10) DEFAULT 'days' AFTER issuelength");
5216     print "Upgrade to $DBversion done (Setting up issues tables for hourly loans (lengthunit fix))\n";
5217     SetVersion($DBversion);
5218 }
5219
5220 $DBversion = "3.07.00.047";
5221 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5222     $dbh->do("CREATE INDEX items_location ON items(location)");
5223     $dbh->do("CREATE INDEX items_ccode ON items(ccode)");
5224     print "Upgrade to $DBversion done (items_location and items_ccode indexes added for ShelfBrowser)\n";
5225     SetVersion($DBversion);
5226 }
5227
5228 $DBversion = "3.07.00.048";
5229 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5230     $dbh->do(
5231         q | CREATE TABLE ratings (
5232   borrowernumber int(11) NOT NULL,
5233   biblionumber int(11) NOT NULL,
5234   rating_value tinyint(1) NOT NULL,
5235   timestamp timestamp NOT NULL default CURRENT_TIMESTAMP,
5236   PRIMARY KEY  (borrowernumber,biblionumber),
5237   CONSTRAINT ratings_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE,
5238   CONSTRAINT ratings_ibfk_2 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
5239 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
5240     );
5241
5242     $dbh->do(
5243 q /INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OpacStarRatings','disable',NULL,'disable|all|details','Choice') /
5244     );
5245
5246     print
5247 "Upgrade to $DBversion done (Add 'ratings' table and 'OpacStarRatings' syspref)\n";
5248     SetVersion($DBversion);
5249 }
5250
5251 $DBversion = "3.07.00.049";
5252 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5253     $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')");
5254     print "Upgrade to $DBversion done (Add system preference OpacBrowseResults ))\n";
5255     SetVersion($DBversion);
5256 }
5257
5258 $DBversion = "3.08.00.000";
5259 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5260     print "Upgrade to $DBversion done\n";
5261     SetVersion($DBversion);
5262 }
5263
5264 $DBversion = "3.09.00.001";
5265 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5266     $dbh->do("ALTER TABLE borrower_attribute_types MODIFY category_code VARCHAR( 1 ) NULL DEFAULT NULL");
5267     print "Upgrade to $DBversion done. (Bug 8002: Update patron attribute types table to allow NULL category_code)\n";
5268     SetVersion($DBversion);
5269 }
5270
5271 $DBversion = "3.09.00.002";
5272 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5273     $dbh->do("ALTER TABLE saved_sql
5274         ADD (
5275             cache_expiry INT NOT NULL DEFAULT 300,
5276             public BOOLEAN NOT NULL DEFAULT FALSE
5277         );
5278     ");
5279     print "Upgrade to $DBversion done (Added cache_expiry and public fields in
5280 saved_reports table.)\n";
5281     SetVersion($DBversion);
5282 }
5283
5284 $DBversion = "3.09.00.003";
5285 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5286     $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');");
5287     print "Upgrade to $DBversion done (Added SvcMaxReportRows syspref)\n";
5288     SetVersion($DBversion);
5289 }
5290
5291 $DBversion = "3.09.00.004";
5292 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5293     $dbh->do("INSERT IGNORE INTO permissions (module_bit, code, description) VALUES('13', 'edit_patrons', 'Perform batch modifivation of patrons')");
5294     print "Upgrade to $DBversion done (Adds permissions flag for access to the patron modifications tool)\n";
5295     SetVersion($DBversion);
5296 }
5297
5298 $DBversion = "3.09.00.005";
5299 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5300     unless (TableExists('quotes')) {
5301         $dbh->do( qq{
5302             CREATE TABLE `quotes` (
5303               `id` int(11) NOT NULL AUTO_INCREMENT,
5304               `source` text DEFAULT NULL,
5305               `text` mediumtext NOT NULL,
5306               `timestamp` datetime NOT NULL,
5307               PRIMARY KEY (`id`)
5308             ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5309         });
5310     }
5311     $dbh->do( qq{
5312         INSERT IGNORE INTO permissions VALUES (13, "edit_quotes","Edit quotes for quote-of-the-day feature");
5313     });
5314     $dbh->do( qq{
5315         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');
5316     });
5317     print "Upgrade to $DBversion done (Adding Quote of the Day Option.)\n";
5318     SetVersion($DBversion);
5319 }
5320
5321 $DBversion = "3.09.00.006";
5322 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5323     $dbh->do("UPDATE systempreferences SET
5324                 variable = 'OPACShowHoldQueueDetails',
5325                 value = CASE value WHEN '1' THEN 'priority' ELSE 'none' END,
5326                 options = 'none|priority|holds|holds_priority',
5327                 explanation = 'Show holds details in OPAC',
5328                 type = 'Choice'
5329               WHERE variable = 'OPACDisplayRequestPriority'");
5330     print "Upgrade to $DBversion done (Changed system preference OPACDisplayRequestPriority -> OPACShowHoldQueueDetails)\n";
5331     SetVersion($DBversion);
5332 }
5333
5334 $DBversion = "3.09.00.007";
5335 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5336     unless(C4::Context->preference('ReservesControlBranch')){
5337         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('ReservesControlBranch','PatronLibrary','ItemHomeLibrary|PatronLibrary','Branch checked for members reservations rights.','Choice')");
5338     }
5339     print "Upgrade to $DBversion done (Insert ReservesControlBranch systempreference into systempreferences table )\n";
5340     SetVersion($DBversion);
5341 }
5342
5343 $DBversion = "3.09.00.008";
5344 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5345     $dbh->do("ALTER TABLE sessions ADD PRIMARY KEY (id);");
5346     $dbh->do("ALTER TABLE sessions DROP INDEX `id`;");
5347     print "Upgrade to $DBversion done (redefine the field id as PRIMARY KEY of sessions)\n";
5348     SetVersion($DBversion);
5349 }
5350
5351 $DBversion = "3.09.00.009";
5352 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5353     $dbh->do("ALTER TABLE branches ADD PRIMARY KEY (branchcode);");
5354     $dbh->do("ALTER TABLE branches DROP INDEX branchcode;");
5355     print "Upgrade to $DBversion done (redefine the field branchcode as PRIMARY KEY of branches)\n";
5356     SetVersion ($DBversion);
5357 }
5358
5359 $DBversion = "3.09.00.010";
5360 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5361     $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')");
5362     print "Upgrade to $DBversion done (Add system preference issuelostitem ))\n";
5363     SetVersion($DBversion);
5364 }
5365
5366 $DBversion = "3.09.00.011";
5367 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5368     $dbh->do("ALTER TABLE `biblioitems` ADD `ean` VARCHAR( 13 ) NULL AFTER issn");
5369     $dbh->do("CREATE INDEX `ean` ON biblioitems (`ean`) ");
5370     $dbh->do("ALTER TABLE `deletedbiblioitems` ADD `ean` VARCHAR( 13 ) NULL AFTER issn");
5371     if (C4::Context->preference("marcflavour") eq 'UNIMARC') {
5372          $dbh->do("UPDATE marc_subfield_structure SET kohafield='biblioitems.ean' WHERE tagfield='073' and tagsubfield='a'");
5373     }
5374     print "Upgrade to $DBversion done (Adding ean in biblioitems and deletedbiblioitems)\n";
5375     print "If you have records with ean, please run misc/batchRebuildBiblioTables.pl to populate bibliotems.ean\n" if (C4::Context->preference("marcflavour") eq 'UNIMARC');
5376     SetVersion($DBversion);
5377 }
5378
5379 $DBversion = "3.09.00.012";
5380 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5381     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('SuspendHoldsIntranet', '1', NULL , 'Allow holds to be suspended from the intranet.', 'YesNo')");
5382     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('SuspendHoldsOpac', '1', NULL , 'Allow holds to be suspended from the OPAC.', 'YesNo')");
5383     print "Upgrade to $DBversion done (Add system preference OpacBrowseResults ))\n";
5384     SetVersion($DBversion);
5385 }
5386
5387 $DBversion ="3.09.00.013";
5388 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5389     $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');");
5390     print "Upgrade to $DBversion done (Add system preference DefaultLanguageField008))\n";
5391     SetVersion($DBversion);
5392 }
5393
5394 $DBversion ="3.09.00.014";
5395 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5396     # add phone message transport type
5397     $dbh->do("INSERT INTO message_transport_types (message_transport_type) VALUES ('phone')");
5398
5399     # adds HOLD_PHONE and PREDUE_PHONE letters (as placeholders)
5400     $dbh->do("INSERT INTO letter (module, code, name, title, content) VALUES
5401               ('reserves', 'HOLD_PHONE', 'Item Available for Pick-up (phone notice)', 'Item Available for Pick-up (phone notice)', 'Your item is available for pickup'),
5402               ('circulation', 'PREDUE_PHONE', 'Advance Notice of Item Due (phone notice)', 'Advance Notice of Item Due (phone notice)', 'Your item is due soon'),
5403               ('circulation', 'OVERDUE_PHONE', 'Overdue Notice (phone notice)', 'Overdue Notice (phone notice)', 'Your item is overdue')
5404               ");
5405
5406     # add phone notifications to patron message preferences options
5407     $dbh->do("INSERT INTO message_transports
5408              (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) VALUES
5409              (4, 'phone', 0, 'reserves', 'HOLD_PHONE'),
5410              (2, 'phone', 0, 'circulation', 'PREDUE_PHONE')
5411              ");
5412
5413     # add TalkingTechItivaPhoneNotification syspref
5414     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('TalkingTechItivaPhoneNotification',0,'If ON, enables Talking Tech I-tiva phone notifications',NULL,'YesNo');");
5415
5416     print "Upgrade done (Support for Talking Tech i-tiva phone notification system)\n";
5417     SetVersion($DBversion);
5418 }
5419
5420 $DBversion = "3.09.00.015";
5421 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5422     $dbh->do(qq{
5423         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')
5424     });
5425     print "Upgrade to $DBversion done (Add System preference StatisticsFields)\n";
5426     SetVersion($DBversion);
5427 }
5428
5429 $DBversion = "3.09.00.016";
5430 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5431     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACShowBarcode','0','Show items barcode in holding tab','','YesNo')");
5432     print "Upgrade to $DBversion done (Add syspref OPACShowBarcode)\n";
5433     SetVersion ($DBversion);
5434 }
5435
5436 $DBversion = "3.09.00.017";
5437 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5438     $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');");
5439     print "Upgrade to $DBversion done (Add customizable OpacNavRight region to the OPAC main page)\n";
5440     SetVersion ($DBversion);
5441 }
5442
5443 $DBversion = "3.09.00.018";
5444 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5445     $dbh->do("DROP TABLE IF EXISTS aqbudgetborrowers");
5446     $dbh->do("
5447         CREATE TABLE aqbudgetborrowers (
5448           budget_id int(11) NOT NULL,
5449           borrowernumber int(11) NOT NULL,
5450           PRIMARY KEY (budget_id, borrowernumber),
5451           CONSTRAINT aqbudgetborrowers_ibfk_1 FOREIGN KEY (budget_id)
5452             REFERENCES aqbudgets (budget_id)
5453             ON DELETE CASCADE ON UPDATE CASCADE,
5454           CONSTRAINT aqbudgetborrowers_ibfk_2 FOREIGN KEY (borrowernumber)
5455             REFERENCES borrowers (borrowernumber)
5456             ON DELETE CASCADE ON UPDATE CASCADE
5457         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
5458     ");
5459     $dbh->do("
5460         INSERT INTO permissions (module_bit, code, description)
5461         VALUES (11, 'budget_manage_all', 'Manage all budgets')
5462     ");
5463     print "Upgrade to $DBversion done (Add aqbudgetborrowers table)\n";
5464     SetVersion($DBversion);
5465 }
5466
5467 $DBversion = "3.09.00.019";
5468 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5469     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('OPACShowUnusedAuthorities','1','','Show authorities that are not being used in the OPAC.','YesNo')");
5470     print "Upgrade to $DBversion done (Add OPACShowUnusedAuthorities system preference)\n";
5471     SetVersion ($DBversion);
5472 }
5473
5474 $DBversion = "3.09.00.020";
5475 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5476     $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')");
5477     $dbh->do("
5478 CREATE TABLE IF NOT EXISTS borrower_files (
5479   file_id int(11) NOT NULL AUTO_INCREMENT,
5480   borrowernumber int(11) NOT NULL,
5481   file_name varchar(255) NOT NULL,
5482   file_type varchar(255) NOT NULL,
5483   file_description varchar(255) DEFAULT NULL,
5484   file_content longblob NOT NULL,
5485   date_uploaded timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
5486   PRIMARY KEY (file_id),
5487   KEY borrowernumber (borrowernumber)
5488 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
5489     ");
5490     $dbh->do("ALTER TABLE borrower_files ADD CONSTRAINT borrower_files_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE");
5491
5492     print "Upgrade to $DBversion done (Added borrow_files table, EnableBorrowerFiles syspref)\n";
5493     SetVersion($DBversion);
5494 }
5495
5496 $DBversion = "3.09.00.021";
5497 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5498     $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');");
5499     print "Upgrade to $DBversion done (Add syspref UpdateTotalIssuesOnCirc)\n";
5500     SetVersion($DBversion);
5501 }
5502
5503 $DBversion = "3.09.00.022";
5504 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5505     $dbh->do("ALTER TABLE search_history MODIFY COLUMN query_cgi text NOT NULL");
5506     print "Upgrade to $DBversion done (Change search_history.query_cgi type to text. bug 5981)\n";
5507     SetVersion($DBversion);
5508 }
5509
5510 $DBversion = "3.09.00.023";
5511 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5512     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('SearchEngine','Zebra','Solr|Zebra','Search Engine','Choice')");
5513     print "Upgrade to $DBversion done (Add system preference SearchEngine )\n";
5514     SetVersion($DBversion);
5515 }
5516
5517 $DBversion ="3.09.00.024";
5518 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5519     $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')");
5520     print "Upgrade to $DBversion done (Add system preference IntranetSlipPrinterJS))\n";
5521     SetVersion($DBversion);
5522 }
5523
5524 $DBversion = "3.09.00.025";
5525 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5526     $dbh->do('START TRANSACTION');
5527     $dbh->do('CREATE TABLE tmp_reserves AS SELECT * FROM old_reserves LIMIT 0');
5528     $dbh->do('ALTER TABLE tmp_reserves ADD reserve_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
5529     $dbh->do("
5530         INSERT INTO tmp_reserves (
5531           borrowernumber, reservedate, biblionumber,
5532           constrainttype, branchcode, notificationdate,
5533           reminderdate, cancellationdate, reservenotes,
5534           priority, found, timestamp, itemnumber,
5535           waitingdate, expirationdate, lowestPriority,
5536           suspend, suspend_until
5537         ) SELECT
5538           borrowernumber, reservedate, biblionumber,
5539           constrainttype, branchcode, notificationdate,
5540           reminderdate, cancellationdate, reservenotes,
5541           priority, found, timestamp, itemnumber,
5542           waitingdate, expirationdate, lowestPriority,
5543           suspend, suspend_until
5544         FROM old_reserves ORDER BY reservedate
5545     ");
5546     $dbh->do('SET @ai = ( SELECT MAX( reserve_id ) FROM tmp_reserves )');
5547     $dbh->do('TRUNCATE old_reserves');
5548     $dbh->do('ALTER TABLE old_reserves ADD reserve_id INT( 11 ) NOT NULL PRIMARY KEY FIRST');
5549     $dbh->do('INSERT INTO old_reserves SELECT * FROM tmp_reserves WHERE reserve_id <= @ai');
5550     $dbh->do("
5551         INSERT INTO tmp_reserves (
5552           borrowernumber, reservedate, biblionumber,
5553           constrainttype, branchcode, notificationdate,
5554           reminderdate, cancellationdate, reservenotes,
5555           priority, found, timestamp, itemnumber,
5556           waitingdate, expirationdate, lowestPriority,
5557           suspend, suspend_until
5558         ) SELECT
5559           borrowernumber, reservedate, biblionumber,
5560           constrainttype, branchcode, notificationdate,
5561           reminderdate, cancellationdate, reservenotes,
5562           priority, found, timestamp, itemnumber,
5563           waitingdate, expirationdate, lowestPriority,
5564           suspend, suspend_until
5565         FROM reserves ORDER BY reservedate
5566     ");
5567     $dbh->do('TRUNCATE reserves');
5568     $dbh->do('ALTER TABLE reserves ADD reserve_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
5569     $dbh->do('INSERT INTO reserves SELECT * FROM tmp_reserves WHERE reserve_id > COALESCE(@ai, 0)');
5570     $dbh->do('DROP TABLE tmp_reserves');
5571     $dbh->do('COMMIT');
5572
5573     my $sth = $dbh->prepare("
5574         SELECT COUNT( * ) AS count
5575         FROM information_schema.COLUMNS
5576         WHERE COLUMN_NAME =  'reserve_id'
5577         AND (
5578           TABLE_NAME LIKE  'reserves'
5579           OR
5580           TABLE_NAME LIKE  'old_reserves'
5581         )
5582     ");
5583     $sth->execute();
5584     my $row = $sth->fetchrow_hashref();
5585     die("Failed to add reserve_id to reserves tables, please refresh the page to try again.") unless ( $row->{'count'} );
5586
5587     print "Upgrade to $DBversion done (add reserve_id to reserves & old_reserves tables)\n";
5588     SetVersion($DBversion);
5589 }
5590
5591 $DBversion = "3.09.00.026";
5592 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5593     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
5594         ( 3, 'parameters_remaining_permissions', 'Remaining system parameters permissions'),
5595         ( 3, 'manage_circ_rules', 'manage circulation rules')");
5596     $dbh->do("INSERT INTO user_permissions (borrowernumber, module_bit, code)
5597         SELECT borrowernumber, 3, 'parameters_remaining_permissions'
5598         FROM borrowers WHERE flags & (1 << 3)");
5599     # Give new subpermissions to all users that have 'parameters' permission flag (bit 3) set
5600     # see userflags table
5601     $dbh->do("INSERT INTO user_permissions (borrowernumber, module_bit, code)
5602         SELECT borrowernumber, 3, 'manage_circ_rules'
5603         FROM borrowers WHERE flags & (1 << 3)");
5604     print "Upgrade to $DBversion done (Added parameters subpermissions)\n";
5605     SetVersion($DBversion);
5606 }
5607
5608 $DBversion = '3.09.00.027';
5609 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5610     $dbh->do("ALTER TABLE issuingrules ADD overduefinescap decimal(28,6) DEFAULT NULL");
5611     my $maxfine = C4::Context->preference('MaxFine');
5612     if ($maxfine && $maxfine < 900) { # an arbitrary value that tells us it's not "some huge value"
5613       $dbh->do("UPDATE issuingrules SET overduefinescap=?",undef,$maxfine);
5614       $dbh->do("UPDATE systempreferences SET value = NULL WHERE variable = 'MaxFine'");
5615     }
5616     $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'");
5617     print "Upgrade to $DBversion done (Bug 7420 add overduefinescap to circulation matrix)\n";
5618     SetVersion ($DBversion);
5619 }
5620
5621 $DBversion = "3.09.00.028";
5622 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5623     unless ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) {
5624         my %referencetypes = (  '00' => 'PERSO_NAME',
5625                                 '10' => 'CORPO_NAME',
5626                                 '11' => 'MEETI_NAME',
5627                                 '30' => 'UNIF_TITLE',
5628                                 '48' => 'CHRON_TERM',
5629                                 '50' => 'TOPIC_TERM',
5630                                 '51' => 'GEOGR_NAME',
5631                                 '55' => 'GENRE/FORM'
5632                 );
5633         my $query = q{SELECT DISTINCT authtypecode, tagfield
5634                     FROM auth_subfield_structure
5635                     WHERE (tagfield BETWEEN '400' AND '455' OR
5636                     tagfield BETWEEN '500' and '555') AND tagsubfield='a' AND
5637                     frameworkcode = '' AND ROW(authtypecode, tagfield) NOT IN
5638                     (SELECT authtypecode, tagfield FROM auth_subfield_structure
5639                     WHERE tagsubfield ='9' )};
5640         $sth = $dbh->prepare($query);
5641         $sth->execute;
5642         my $sth2 = $dbh->prepare(q{INSERT INTO auth_subfield_structure
5643                 (authtypecode, tagfield, tagsubfield, liblibrarian, libopac,
5644                  repeatable, mandatory, tab, authorised_value, value_builder,
5645                  seealso, isurl, hidden, linkid, kohafield, frameworkcode)
5646                 VALUES (?, ?, '9', '9 (RLIN)', '9 (RLIN)', 0, 0, ?, NULL, NULL,
5647                     NULL, 0, 1, '', '', '')});
5648         my $sth3 = $dbh->prepare(q{UPDATE auth_subfield_structure SET
5649                                     frameworkcode = ? WHERE authtypecode = ? AND
5650                                     tagfield = ? AND tagsubfield = 'a'});
5651         while (my $row = $sth->fetchrow_arrayref()) {
5652             my ($authtypecode, $field) = @$row;
5653             $sth2->execute($authtypecode, $field, substr($field, 0, 1));
5654             my $authtypemarker = substr $field, 1, 2;
5655             if ($authtypemarker && $referencetypes{$authtypemarker}) {
5656                 $sth3->execute($referencetypes{$authtypemarker}, $authtypecode, $field);
5657             }
5658         }
5659     }
5660
5661     print "Upgrade to $DBversion done (Add thesaurus links for MARC21/NORMARC)\n";
5662     SetVersion($DBversion);
5663 }
5664
5665 $DBversion = "3.09.00.029"; # FIXME
5666 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5667     $dbh->do("UPDATE systempreferences SET options=concat(options,'|EAN13') WHERE variable='itemBarcodeInputFilter' AND options NOT LIKE '%EAN13%'");
5668     print "Upgrade to $DBversion done (Add itemBarcodeInputFilter choice EAN13)\n";
5669
5670     $dbh->do("UPDATE systempreferences SET options = concat(options,'|EAN13'), explanation = concat(explanation,'; EAN13 - incremental') WHERE variable = 'autoBarcode' AND options NOT LIKE '%EAN13%'");
5671     print "Upgrade to $DBversion done ( Added EAN13 barcode autogeneration sequence )\n";
5672     SetVersion($DBversion);
5673 }
5674
5675 $DBversion ="3.09.00.030";
5676 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5677     my $query = "SELECT value FROM systempreferences WHERE variable='opacstylesheet'";
5678     my $remote= $dbh->selectrow_arrayref($query);
5679     $dbh->do("DELETE from systempreferences WHERE variable='opacstylesheet'");
5680     if($remote && $remote->[0]) {
5681         $query="UPDATE systempreferences SET value=? WHERE variable='opaclayoutstylesheet'";
5682         $dbh->do($query,undef,$remote->[0]);
5683         print "NOTE: The URL of your remote opac css file has been moved to preference opaclayoutstylesheet.\n";
5684     }
5685     print "Upgrade to $DBversion done (BZ 8263: Make OPAC stylesheet preferences more consistent)\n";
5686     SetVersion($DBversion);
5687 }
5688
5689 $DBversion = "3.09.00.031";
5690 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5691     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonReviews'");
5692     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonSimilarItems'");
5693     $dbh->do("DELETE FROM systempreferences WHERE variable='AWSAccessKeyID'");
5694     $dbh->do("DELETE FROM systempreferences WHERE variable='AWSPrivateKey'");
5695     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonReviews'");
5696     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonSimilarItems'");
5697     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonEnabled'");
5698     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonEnabled'");
5699     print "Upgrade to $DBversion done ('Remove preferences controlling broken Amazon features (Bug 8679')\n";
5700     SetVersion ($DBversion);
5701 }
5702
5703 $DBversion = "3.09.00.032";
5704 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5705     $dbh->do("UPDATE systempreferences SET value = 'call_number' WHERE variable = 'defaultSortField' AND value = 'callnumber'");
5706     $dbh->do("UPDATE systempreferences SET value = 'call_number' WHERE variable = 'OPACdefaultSortField' AND value = 'callnumber'");
5707     print "Upgrade to $DBversion done (Bug 8657 - Default sort by call number does not work. Correcting system preference value.)\n";
5708     SetVersion ($DBversion);
5709 }
5710
5711
5712 $DBversion = '3.09.00.033';
5713 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5714    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacSuppressionByIPRange','','Restrict the suppression to IP adresses outside of the IP range','','free');");
5715    print "Upgrade to $DBversion done (Add OpacSuppressionByIPRange syspref)\n";
5716    SetVersion ($DBversion);
5717 }
5718
5719 $DBversion ="3.09.00.034";
5720 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5721     $dbh->do("UPDATE auth_subfield_structure SET frameworkcode = 'PERSO_NAME' WHERE frameworkcode = 'PERSO_CODE'");
5722     $dbh->do("UPDATE auth_subfield_structure SET frameworkcode = 'CORPO_NAME' WHERE frameworkcode = 'ORGO_CODE'");
5723     print "Upgrade to $DBversion done (Bug 8207: correct typo in authority types)\n";
5724     SetVersion ($DBversion);
5725 }
5726
5727 $DBversion = "3.09.00.035";
5728 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5729     $dbh->do("
5730     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');
5731     ");
5732     $dbh->do(
5733     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SubfieldsToUseWhenPrefill','','Define a list of subfields to use when prefilling items (separated by space)','','Free');
5734     ");
5735     print "Upgrade to $DBversion done (Adding PrefillItem and SubfieldsToUseWhenPrefill sysprefs)\n";
5736     SetVersion ($DBversion);
5737 }
5738
5739 $DBversion = "3.09.00.036";
5740 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5741     # biblioitems changes
5742     $dbh->do("ALTER TABLE biblioitems ADD COLUMN agerestriction VARCHAR(255) DEFAULT NULL AFTER cn_sort");
5743     $dbh->do("ALTER TABLE deletedbiblioitems ADD COLUMN agerestriction VARCHAR(255) DEFAULT NULL AFTER cn_sort");
5744     # preferences changes
5745     $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')");
5746     $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')");
5747
5748     print "Upgrade to $DBversion done (Add colum agerestriction to biblioitems and deletedbiblioitems, add system preferences AgeRestrictionMarker and AgeRestrictionOverride)\n";
5749    SetVersion ($DBversion);
5750 }
5751
5752 $DBversion = "3.09.00.037";
5753 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5754     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('UseTransportCostMatrix',0,'Use Transport Cost Matrix when filling holds','','YesNo')");
5755
5756  $dbh->do("CREATE TABLE `transport_cost` (
5757               `frombranch` varchar(10) NOT NULL,
5758               `tobranch` varchar(10) NOT NULL,
5759               `cost` decimal(6,2) NOT NULL,
5760               `disable_transfer` tinyint(1) NOT NULL DEFAULT 0,
5761               CHECK ( `frombranch` <> `tobranch` ), -- a dud check, mysql does not support that
5762               PRIMARY KEY (`frombranch`, `tobranch`),
5763               CONSTRAINT `transport_cost_ibfk_1` FOREIGN KEY (`frombranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
5764               CONSTRAINT `transport_cost_ibfk_2` FOREIGN KEY (`tobranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
5765           ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
5766
5767     print "Upgrade to $DBversion done (creating `transport_cost` table; adding UseTransportCostMatrix systempref, in circulation)\n";
5768     SetVersion($DBversion);
5769 }
5770
5771 $DBversion ="3.09.00.038";
5772 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5773     $dbh->do("ALTER TABLE borrower_attributes CHANGE  attribute  attribute VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
5774     print "Upgrade to $DBversion done (Increase the maximum size of a borrower attribute value)\n";
5775     SetVersion($DBversion);
5776 }
5777
5778 $DBversion ="3.09.00.039";
5779 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5780     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,type) VALUES('DidYouMeanFromAuthorities','0','Suggest searches based on authority file.','YesNo');");
5781     print "Upgrade to $DBversion done (Add system preference DidYouMeanFromAuthorities)\n";
5782     SetVersion($DBversion);
5783 }
5784
5785 $DBversion = "3.09.00.040";
5786 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5787     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('IncludeSeeFromInSearches','0','','Include see-from references in searches.','YesNo');");
5788     print "Upgrade to $DBversion done (Add IncludeSeeFromInSearches system preference)\n";
5789     SetVersion ($DBversion);
5790 }
5791
5792 $DBversion = "3.09.00.041";
5793 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5794     $dbh->do(qq{
5795         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ExportRemoveFields','','List of fields for non export in circulation.pl (separated by a space)','','');
5796     });
5797     print "Upgrade to $DBversion done (Add system preference ExportRemoveFields)\n";
5798     SetVersion($DBversion);
5799 }
5800
5801 $DBversion = "3.09.00.042";
5802 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5803     $dbh->do(qq{
5804         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ExportWithCsvProfile','','Set a profile name for CSV export','','');
5805     });
5806     print "Upgrade to $DBversion done (Adds New System preference ExportWithCsvProfile)\n";
5807     SetVersion($DBversion)
5808 }
5809
5810 $DBversion = "3.09.00.043";
5811 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5812     $dbh->do("
5813         ALTER TABLE aqorders
5814         ADD parent_ordernumber int(11) DEFAULT NULL
5815     ");
5816     $dbh->do("
5817         UPDATE aqorders
5818         SET parent_ordernumber = ordernumber;
5819     ");
5820     print "Upgrade to $DBversion done (Adding parent_ordernumber in aqorders)\n";
5821     SetVersion($DBversion);
5822 }
5823
5824 $DBversion = '3.09.00.044';
5825 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5826     $dbh->do("ALTER TABLE statistics ADD COLUMN ccode VARCHAR ( 10 ) NULL AFTER associatedborrower");
5827     $dbh->do("UPDATE statistics SET statistics.ccode = ( SELECT items.ccode FROM items WHERE statistics.itemnumber = items.itemnumber )");
5828     $dbh->do("UPDATE statistics SET statistics.ccode = (
5829               SELECT deleteditems.ccode FROM deleteditems
5830                   WHERE statistics.itemnumber = deleteditems.itemnumber
5831               ) WHERE statistics.ccode IS NULL");
5832     print "Upgrade done ( Added Collection Code to Statistics table. )\n";
5833     SetVersion ($DBversion);
5834 }
5835
5836 $DBversion = "3.09.00.045";
5837 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5838     $dbh->do("ALTER TABLE borrower_attribute_types MODIFY category_code VARCHAR( 10 ) NULL DEFAULT NULL");
5839     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.";
5840     SetVersion($DBversion);
5841 }
5842
5843 $DBversion = "3.09.00.046";
5844 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5845     $dbh->do("ALTER TABLE `accountlines` ADD `accountlines_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;");
5846     print "Upgrade to $DBversion done (adding accountlines_id field in accountlines table)\n";
5847     SetVersion($DBversion);
5848 }
5849
5850 $DBversion = "3.09.00.047";
5851 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5852     # to preserve default behaviour as best as possible, set this new preference differently depending on whether IndependantBranches is set or not
5853     my $prefvalue = 'anywhere';
5854     if (C4::Context->preference("IndependantBranches")) { $prefvalue = 'homeorholdingbranch';}
5855     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowReturnToBranch', '$prefvalue', 'Where an item may be returned', 'anywhere|homebranch|holdingbranch|homeorholdingbranch', 'Choice');");
5856
5857     print "Upgrade to $DBversion done: adding AllowReturnToBranch syspref (bug 6151)";
5858     SetVersion($DBversion);
5859 }
5860
5861 $DBversion = "3.09.00.048";
5862 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5863     $dbh->do("ALTER TABLE authorised_values MODIFY lib varchar(200)");
5864     $dbh->do("ALTER TABLE authorised_values MODIFY lib_opac varchar(200)");
5865
5866     print "Upgrade to $DBversion done (Raise the length of Authorised Values descriptions)\n";
5867     SetVersion($DBversion);
5868 }
5869
5870 $DBversion ="3.09.00.049";
5871 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5872     $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');");
5873     $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');");
5874     $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');");
5875     $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');");
5876     print "Upgrade to $DBversion done (Add OPACMobileUserCSS, OpacMainUserBlockMobile, OpacShowLibrariesPulldownMobile and OpacShowFiltersPulldownMobile sysprefs)\n";
5877     SetVersion($DBversion);
5878 }
5879
5880 $DBversion = "3.09.00.050";
5881 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5882     $dbh->do("ALTER TABLE authorised_values MODIFY category varchar(16) NOT NULL DEFAULT '';");
5883     $dbh->do("INSERT INTO authorised_values (category, authorised_value, lib) VALUES
5884               ('REPORT_GROUP', 'CIRC', 'Circulation'),
5885               ('REPORT_GROUP', 'CAT', 'Catalog'),
5886               ('REPORT_GROUP', 'PAT', 'Patrons'),
5887               ('REPORT_GROUP', 'ACQ', 'Acquisitions'),
5888               ('REPORT_GROUP', 'ACC', 'Accounts');");
5889
5890     $dbh->do("ALTER TABLE reports_dictionary ADD report_area varchar(6) DEFAULT NULL;");
5891     $dbh->do("UPDATE reports_dictionary SET report_area = CASE area
5892                   WHEN 1 THEN 'CIRC'
5893                   WHEN 2 THEN 'CAT'
5894                   WHEN 3 THEN 'PAT'
5895                   WHEN 4 THEN 'ACQ'
5896                   WHEN 5 THEN 'ACC'
5897                   END;");
5898     $dbh->do("ALTER TABLE reports_dictionary DROP area;");
5899     $dbh->do("ALTER TABLE reports_dictionary ADD KEY dictionary_area_idx (report_area);");
5900
5901     $dbh->do("ALTER TABLE saved_sql ADD report_area varchar(6) DEFAULT NULL;");
5902     $dbh->do("ALTER TABLE saved_sql ADD report_group varchar(80) DEFAULT NULL;");
5903     $dbh->do("ALTER TABLE saved_sql ADD report_subgroup varchar(80) DEFAULT NULL;");
5904     $dbh->do("ALTER TABLE saved_sql ADD KEY sql_area_group_idx (report_group, report_subgroup);");
5905
5906     print "Upgrade to $DBversion done saved_sql new fields report_group and report_area; authorised_values.category 16 char \n";
5907     SetVersion($DBversion);
5908 }
5909
5910 $DBversion = "3.09.00.051";
5911 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5912     $dbh->do("
5913         CREATE TABLE aqinvoices (
5914           invoiceid int(11) NOT NULL AUTO_INCREMENT,
5915           invoicenumber mediumtext NOT NULL,
5916           booksellerid int(11) NOT NULL,
5917           shipmentdate date default NULL,
5918           billingdate date default NULL,
5919           closedate date default NULL,
5920           shipmentcost decimal(28,6) default NULL,
5921           shipmentcost_budgetid int(11) default NULL,
5922           PRIMARY KEY (invoiceid),
5923           CONSTRAINT aqinvoices_fk_aqbooksellerid FOREIGN KEY (booksellerid) REFERENCES aqbooksellers (id) ON DELETE CASCADE ON UPDATE CASCADE,
5924           CONSTRAINT aqinvoices_fk_shipmentcost_budgetid FOREIGN KEY (shipmentcost_budgetid) REFERENCES aqbudgets (budget_id) ON DELETE SET NULL ON UPDATE CASCADE
5925         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5926     ");
5927
5928     # Fill this new table with existing invoices
5929     my $sth = $dbh->prepare("
5930         SELECT aqorders.booksellerinvoicenumber AS invoicenumber, aqbasket.booksellerid, aqorders.datereceived
5931         FROM aqorders
5932           LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
5933         WHERE aqorders.booksellerinvoicenumber IS NOT NULL
5934           AND aqorders.booksellerinvoicenumber != ''
5935         GROUP BY aqorders.booksellerinvoicenumber
5936     ");
5937     $sth->execute;
5938     my $results = $sth->fetchall_arrayref({});
5939     $sth = $dbh->prepare("
5940         INSERT INTO aqinvoices (invoicenumber, booksellerid, shipmentdate) VALUES (?,?,?)
5941     ");
5942     foreach(@$results) {
5943         $sth->execute($_->{invoicenumber}, $_->{booksellerid}, $_->{datereceived});
5944     }
5945
5946     # Add the column in aqorders, fill it with correct value
5947     # and then drop booksellerinvoicenumber column
5948     $dbh->do("
5949         ALTER TABLE aqorders
5950         ADD COLUMN invoiceid int(11) default NULL AFTER booksellerinvoicenumber,
5951         ADD CONSTRAINT aqorders_ibfk_3 FOREIGN KEY (invoiceid) REFERENCES aqinvoices (invoiceid) ON DELETE SET NULL ON UPDATE CASCADE
5952     ");
5953
5954     $dbh->do("
5955         UPDATE aqorders, aqinvoices
5956         SET aqorders.invoiceid = aqinvoices.invoiceid
5957         WHERE aqorders.booksellerinvoicenumber = aqinvoices.invoicenumber
5958     ");
5959
5960     $dbh->do("
5961         ALTER TABLE aqorders
5962         DROP COLUMN booksellerinvoicenumber
5963     ");
5964
5965     print "Upgrade to $DBversion done (Add aqinvoices table) \n";
5966     SetVersion ($DBversion);
5967 }
5968
5969 $DBversion = "3.09.00.052";
5970 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5971     $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');");
5972     $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');");
5973     $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');");
5974     print "Upgrade to $DBversion done (Add systempreferences to decrease loan length on high demand items decreaseLoanHighHolds, decreaseLoanHighHoldsValue and decreaseLoanHighHoldsDuration) \n";
5975     SetVersion ($DBversion);
5976 }
5977
5978 $DBversion = "3.09.00.053";
5979 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5980     $dbh->do(
5981     q|CREATE TABLE `import_auths` (
5982         import_record_id int(11) NOT NULL,
5983         matched_authid int(11) default NULL,
5984         control_number varchar(25) default NULL,
5985         authorized_heading varchar(128) default NULL,
5986         original_source varchar(25) default NULL,
5987         CONSTRAINT import_auths_ibfk_1 FOREIGN KEY (import_record_id)
5988         REFERENCES import_records (import_record_id) ON DELETE CASCADE ON UPDATE CASCADE,
5989         KEY matched_authid (matched_authid)
5990         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;|
5991     );
5992     $dbh->do("ALTER TABLE import_batches
5993                 CHANGE COLUMN num_biblios num_records int(11) NOT NULL default 0,
5994                 ADD COLUMN record_type enum('biblio', 'auth', 'holdings') NOT NULL default 'biblio'");
5995     $dbh->do("UPDATE import_batches SET record_type='auth' WHERE import_batch_id IN
5996                 (SELECT import_batch_id FROM import_records WHERE record_type='auth')");
5997
5998     print "Upgrade to $DBversion done (Added support for staging authorities)\n";
5999     SetVersion ($DBversion);
6000 }
6001
6002 $DBversion = "3.09.00.054";
6003 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6004     $dbh->do("ALTER TABLE aqorders CHANGE COLUMN gst gstrate DECIMAL(6,4)  DEFAULT NULL");
6005     print "Upgrade to $DBversion done (Change column name in aqorders gst --> gstrate)\n";
6006     SetVersion($DBversion);
6007 }
6008
6009 $DBversion = "3.09.00.055";
6010 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6011     $dbh->do("ALTER TABLE aqorders ADD discount float(6,4) DEFAULT NULL AFTER gstrate");
6012     print "Upgrade to $DBversion done (Add discount field in aqorders table)\n";
6013     SetVersion($DBversion);
6014 }
6015
6016 $DBversion ="3.09.00.056";
6017 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6018     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('AuthDisplayHierarchy','0','Display authority hierarchies','','YesNo')");
6019     print "Upgrade to $DBversion done (Add system preference AuthDisplayHierarchy)\n";
6020     SetVersion($DBversion);
6021 }
6022
6023 $DBversion = "3.09.00.057";
6024 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6025     $dbh->do("ALTER TABLE aqbasket ADD deliveryplace VARCHAR(10) default NULL AFTER basketgroupid;");
6026     $dbh->do("ALTER TABLE aqbasket ADD billingplace VARCHAR(10) default NULL AFTER deliveryplace;");
6027     print "Upgrade to $DBversion done (Bug 5356: Added billingplace, deliveryplace to the aqbasket table)\n";
6028     SetVersion($DBversion);
6029 }
6030
6031 $DBversion ="3.09.00.058";
6032 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6033     $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');");
6034     $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');");
6035     print "Upgrade to $DBversion done (Add Did You Mean? configuration)\n";
6036     SetVersion($DBversion);
6037 }
6038
6039 $DBversion ="3.09.00.059";
6040 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6041     $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');");
6042     print "Upgrade to $DBversion done (Add system preference BlockReturnOfWithdrawnItems)\n";
6043     SetVersion($DBversion);
6044 }
6045
6046 $DBversion = "3.09.00.060";
6047 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6048     $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')");
6049     print "Upgrade to $DBversion done (Added HoldsToPullStartDate syspref)\n";
6050     SetVersion($DBversion);
6051 }
6052
6053 $DBversion = "3.09.00.061";
6054 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6055     $dbh->do("UPDATE systempreferences set value=0 WHERE variable='OPACItemsResultsDisplay' AND value='statuses'");
6056     $dbh->do("UPDATE systempreferences set value=1 WHERE variable='OPACItemsResultsDisplay' AND value='itemdetails'");
6057     $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'");
6058     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";
6059     SetVersion ($DBversion);
6060 }
6061
6062 $DBversion = "3.09.00.062";
6063 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6064    $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='NoZebra'");
6065    $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='QueryRemoveStopwords'");
6066    print "Upgrade to $DBversion done (Disable obsolete NoZebra and QueryRemoveStopwords sysprefs)\n";
6067    SetVersion ($DBversion);
6068 }
6069
6070 $DBversion = "3.09.00.063";
6071 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6072     my $gst_booksellers = $dbh->selectcol_arrayref("SELECT DISTINCT(gstrate) FROM aqbooksellers");
6073     my $gist_syspref = C4::Context->preference("gist");
6074     # remove the undef values and construct and array with the syspref and the supplier values
6075     my @gstrates = map { defined $_ ? $_ : () } @$gst_booksellers;
6076     push @gstrates, split ('\|', $gist_syspref);
6077     # we want to compare integer (or float)
6078     $_ = $_ + 0 for @gstrates;
6079     use List::MoreUtils qw/uniq/;
6080     # remove duplicate values
6081     @gstrates = uniq sort @gstrates;
6082     my $new_syspref_value = join '|', @gstrates;
6083     # update the syspref with the new values
6084     my $sth = $dbh->prepare("UPDATE systempreferences set value=? WHERE variable='gist'");
6085     $sth->execute( $new_syspref_value );
6086
6087     print "Upgrade to $DBversion done (Bug 8832, Set the syspref gist with the existing values)\n";
6088     SetVersion ($DBversion);
6089 }
6090
6091 $DBversion = "3.09.00.064";
6092 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6093    $dbh->do('ALTER TABLE items ADD coded_location_qualifier varchar(10) default NULL AFTER itemcallnumber');
6094    print "Upgrade to $DBversion done (Bug 6428: Added coded_location_qualifier to the items table)\n";
6095    SetVersion ($DBversion);
6096 }
6097
6098 $DBversion = "3.09.00.065";
6099 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6100    $dbh->do('ALTER TABLE deleteditems ADD coded_location_qualifier varchar(10) default NULL AFTER itemcallnumber');
6101    print "Upgrade to $DBversion done (Bug 6428: Added coded_location_qualifier to the deleteditems table)\n";
6102    SetVersion ($DBversion);
6103 }
6104
6105 $DBversion = "3.09.00.066";
6106 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6107    $dbh->do("DELETE FROM systempreferences WHERE variable='DidYouMeanFromAuthorities'");
6108    print "Upgrade to $DBversion done (Bug 9107: remove DidYouMeanFromAuthorities syspref)\n";
6109    SetVersion ($DBversion);
6110 }
6111
6112 $DBversion = "3.09.00.067";
6113 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6114    $dbh->do("ALTER TABLE statistics CHANGE COLUMN ccode ccode varchar(10) NULL");
6115    print "Upgrade to $DBversion done (Bug 9064: statistics.ccode potentially wrongly defined)\n";
6116    SetVersion ($DBversion);
6117 }
6118
6119 $DBversion = "3.10.00.00";
6120 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6121    print "Upgrade to $DBversion done (release tag)\n";
6122    SetVersion ($DBversion);
6123 }
6124
6125 $DBversion = "3.11.00.001";
6126 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6127     $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')");
6128     print "Upgrade to $DBversion done (Bug 2832 - Add alphabet syspref)\n";
6129 }
6130
6131 $DBversion = "3.11.00.002";
6132 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6133     $dbh->do(q{
6134         DELETE from aqorders_items where ordernumber NOT IN (SELECT ordernumber FROM aqorders);
6135     });
6136     $dbh->do(q{
6137         ALTER TABLE aqorders_items
6138         ADD CONSTRAINT aqorders_items_ibfk_1 FOREIGN KEY (ordernumber) REFERENCES aqorders (ordernumber)
6139         ON DELETE CASCADE ON UPDATE CASCADE;
6140     });
6141     print "Upgrade to $DBversion done (Bug 9030: Add constraint on aqorders_items.ordernumber)\n";
6142     SetVersion ($DBversion);
6143 }
6144
6145 $DBversion = "3.11.00.003";
6146 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6147     $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')");
6148     print "Upgrade to $DBversion done (Bug 7189: Add system preference RefundLostItemFeeOnReturn)\n";
6149     SetVersion($DBversion);
6150 }
6151
6152 $DBversion = "3.11.00.004";
6153 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6154     $dbh->do(qq{
6155         ALTER TABLE subscription ADD COLUMN closed INT(1) NOT NULL DEFAULT 0 AFTER enddate;
6156     });
6157
6158     print "Upgrade to $DBversion done (Bug 8782: Add field subscription.closed)\n";
6159     SetVersion($DBversion);
6160 }
6161
6162 $DBversion = "3.11.00.005";
6163 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6164     $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;});
6165
6166     $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;});
6167
6168     $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;});
6169
6170     print "Upgrade to $DBversion done (Bug 7919: Display of values depending on the connexion library)\n";
6171     SetVersion($DBversion);
6172 }
6173
6174 $DBversion = "3.11.00.006";
6175 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6176     $dbh->do(q{
6177         UPDATE virtualshelves SET sortfield="copyrightdate" where sortfield="year";
6178     });
6179     print "Upgrade to $DBversion done (Bug 9167: Update the virtualshelves.sortfield column with 'copyrightdate' if needed)\n";
6180     SetVersion($DBversion);
6181 }
6182
6183 $DBversion = "3.11.00.007";
6184 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6185     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ar', 'language', 'de', 'Arabisch')");
6186     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hy', 'language', 'de', 'Armenisch')");
6187     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'bg', 'language', 'de', 'Bulgarisch')");
6188     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'zh', 'language', 'de', 'Chinesisch')");
6189     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'cs', 'language', 'de', 'Tschechisch')");
6190     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'da', 'language', 'de', 'Dänisch')");
6191     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nl', 'language', 'de', 'Niederländisch')");
6192     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'en', 'language', 'de', 'Englisch')");
6193     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fi', 'language', 'de', 'Finnisch')");
6194     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fr', 'language', 'de', 'Französisch')");
6195     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'lo', 'language', 'fr', 'Laotien')");
6196     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'lo', 'language', 'de', 'Laotisch')");
6197     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'el', 'language', 'de', 'Griechisch (Nach 1453)')");
6198     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'he', 'language', 'de', 'Hebräisch')");
6199     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hi', 'language', 'de', 'Hindi')");
6200     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hu', 'language', 'de', 'Ungarisch')");
6201     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'id', 'language', 'de', 'Indonesisch')");
6202     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'it', 'language', 'de', 'Italienisch')");
6203     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ja', 'language', 'de', 'Japanisch')");
6204     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ko', 'language', 'de', 'Koreanisch')");
6205     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'la', 'language', 'de', 'Latein')");
6206     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'gl', 'language', 'fr', 'Galicien')");
6207     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'gl', 'language', 'de', 'Galizisch')");
6208     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nb', 'language', 'de', 'Norwegisch bokm&#229;l')");
6209     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nn', 'language', 'de', 'Norwegisch nynorsk')");
6210     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fa', 'language', 'de', 'Persisch')");
6211     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'pl', 'language', 'de', 'Polnisch')");
6212     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'pt', 'language', 'de', 'Portugiesisch')");
6213     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ro', 'language', 'de', 'Rumänisch')");
6214     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ru', 'language', 'de', 'Russisch')");
6215     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sr', 'language', 'fr', 'Serbe')");
6216     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sr', 'language', 'de', 'Serbisch')");
6217     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'es', 'language', 'de', 'Spanisch')");
6218     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sv', 'language', 'de', 'Schwedisch')");
6219     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tet', 'language', 'fr', 'Tétoum')");
6220     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tet', 'language', 'de', 'Tetum')");
6221     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'th', 'language', 'de', 'Thailändisch')");
6222     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tr', 'language', 'de', 'Türkisch')");
6223     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'uk', 'language', 'de', 'Ukrainisch')");
6224     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ur', 'language', 'fr', 'Ourdou')");
6225     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ur', 'language', 'de', 'Urdu')");
6226     print "Upgrade to $DBversion done (Bug 9056: add German and a couple of French translations to language_descriptions)\n";
6227     SetVersion ($DBversion);
6228 }
6229
6230 $DBversion = "3.11.00.008";
6231 if (CheckVersion($DBversion)) {
6232     $dbh->do("
6233         CREATE TABLE IF NOT EXISTS `borrower_modifications` (
6234           `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6235           `verification_token` varchar(255) NOT NULL DEFAULT '',
6236           `borrowernumber` int(11) NOT NULL DEFAULT '0',
6237           `cardnumber` varchar(16) DEFAULT NULL,
6238           `surname` mediumtext,
6239           `firstname` text,
6240           `title` mediumtext,
6241           `othernames` mediumtext,
6242           `initials` text,
6243           `streetnumber` varchar(10) DEFAULT NULL,
6244           `streettype` varchar(50) DEFAULT NULL,
6245           `address` mediumtext,
6246           `address2` text,
6247           `city` mediumtext,
6248           `state` text,
6249           `zipcode` varchar(25) DEFAULT NULL,
6250           `country` text,
6251           `email` mediumtext,
6252           `phone` text,
6253           `mobile` varchar(50) DEFAULT NULL,
6254           `fax` mediumtext,
6255           `emailpro` text,
6256           `phonepro` text,
6257           `B_streetnumber` varchar(10) DEFAULT NULL,
6258           `B_streettype` varchar(50) DEFAULT NULL,
6259           `B_address` varchar(100) DEFAULT NULL,
6260           `B_address2` text,
6261           `B_city` mediumtext,
6262           `B_state` text,
6263           `B_zipcode` varchar(25) DEFAULT NULL,
6264           `B_country` text,
6265           `B_email` text,
6266           `B_phone` mediumtext,
6267           `dateofbirth` date DEFAULT NULL,
6268           `branchcode` varchar(10) DEFAULT NULL,
6269           `categorycode` varchar(10) DEFAULT NULL,
6270           `dateenrolled` date DEFAULT NULL,
6271           `dateexpiry` date DEFAULT NULL,
6272           `gonenoaddress` tinyint(1) DEFAULT NULL,
6273           `lost` tinyint(1) DEFAULT NULL,
6274           `debarred` date DEFAULT NULL,
6275           `debarredcomment` varchar(255) DEFAULT NULL,
6276           `contactname` mediumtext,
6277           `contactfirstname` text,
6278           `contacttitle` text,
6279           `guarantorid` int(11) DEFAULT NULL,
6280           `borrowernotes` mediumtext,
6281           `relationship` varchar(100) DEFAULT NULL,
6282           `ethnicity` varchar(50) DEFAULT NULL,
6283           `ethnotes` varchar(255) DEFAULT NULL,
6284           `sex` varchar(1) DEFAULT NULL,
6285           `password` varchar(30) DEFAULT NULL,
6286           `flags` int(11) DEFAULT NULL,
6287           `userid` varchar(75) DEFAULT NULL,
6288           `opacnote` mediumtext,
6289           `contactnote` varchar(255) DEFAULT NULL,
6290           `sort1` varchar(80) DEFAULT NULL,
6291           `sort2` varchar(80) DEFAULT NULL,
6292           `altcontactfirstname` varchar(255) DEFAULT NULL,
6293           `altcontactsurname` varchar(255) DEFAULT NULL,
6294           `altcontactaddress1` varchar(255) DEFAULT NULL,
6295           `altcontactaddress2` varchar(255) DEFAULT NULL,
6296           `altcontactaddress3` varchar(255) DEFAULT NULL,
6297           `altcontactstate` text,
6298           `altcontactzipcode` varchar(50) DEFAULT NULL,
6299           `altcontactcountry` text,
6300           `altcontactphone` varchar(50) DEFAULT NULL,
6301           `smsalertnumber` varchar(50) DEFAULT NULL,
6302           `privacy` int(11) DEFAULT NULL,
6303           PRIMARY KEY (`verification_token`,`borrowernumber`),
6304           KEY `verification_token` (`verification_token`),
6305           KEY `borrowernumber` (`borrowernumber`)
6306         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6307 ");
6308
6309     $dbh->do("
6310         INSERT INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES
6311         ('PatronSelfRegistration', '0', NULL, 'If enabled, patrons will be able to register themselves via the OPAC.', 'YesNo'),
6312         ('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'),
6313         ('PatronSelfRegistrationDefaultCategory', '', '', 'A patron registered via the OPAC will receive a borrower category code set in this system preference.', 'free'),
6314         ('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'),
6315         ('PatronSelfRegistrationBorrowerMandatoryField',  'surname|firstname', NULL ,  'Choose the mandatory fields for a patron''s account, when registering via the OPAC.',  'free'),
6316         ('PatronSelfRegistrationBorrowerUnwantedField',  '', NULL ,  'Name the fields you don''t want to display when registering a new patron via the OPAC.',  'free');
6317     ");
6318
6319     $dbh->do("
6320     INSERT INTO  letter ( `module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content` )
6321     VALUES ( 'members', 'OPAC_REG_VERIFY', '', 'Opac Self-Registration Verification Email', '1', 'Verify Your Account', 'Hello!
6322
6323     Your library account has been created. Please verify your email address by clicking this link to complete the signup process:
6324
6325     http://<<OPACBaseURL>>/cgi-bin/koha/opac-registration-verify.pl?token=<<borrower_modifications.verification_token>>
6326
6327     If you did not initiate this request, you may safely ignore this one-time message. The request will expire shortly.'
6328     )");
6329
6330     print "Upgrade to $DBversion done (Bug 7067: Add Patron Self Registration)\n";
6331     SetVersion ($DBversion);
6332 }
6333
6334 $DBversion = "3.11.00.009";
6335 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6336     $dbh->do("
6337         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
6338         ('SeparateHoldings', '0', 'Separate current branch holdings from other holdings', NULL, 'YesNo'),
6339         ('SeparateHoldingsBranch', 'homebranch', 'Branch used to separate holdings', 'homebranch|holdingbranch', 'Choice'),
6340         ('OpacSeparateHoldings', '0', 'Separate current branch holdings from other holdings (OPAC)', NULL, 'YesNo'),
6341         ('OpacSeparateHoldingsBranch', 'homebranch', 'Branch used to separate holdings (OPAC)', 'homebranch|holdingbranch', 'Choice')
6342     ");
6343
6344     print "Upgrade to $DBversion done (Bug 7674: Add systempreferences SeparateHoldings, SeparateHoldingsBranch, OpacSeparateHoldings and OpacSeparateHoldingsBranch) \n";
6345     SetVersion ($DBversion);
6346 }
6347
6348 $DBversion = "3.11.00.010";
6349 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6350     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('RenewalSendNotice', '0', '', NULL, 'YesNo')");
6351     $dbh->do(q{
6352         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
6353         ('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>>.');
6354     });
6355     print "Upgrade to $DBversion done (Bug 9151 - Renewal notice according to patron alert preferences)\n";
6356     SetVersion($DBversion);
6357 }
6358
6359 $DBversion = "3.11.00.011";
6360 if ( CheckVersion($DBversion) ) {
6361    $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');");
6362    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('HTML5MediaExtensions','webm|ogg|ogv|oga|vtt','Media file extensions','','free');");
6363    print "Upgrade to $DBversion done (Bug 8377: Add HTML5MediaEnabled and HTML5MediaExtensions sysprefs)\n";
6364    SetVersion ($DBversion);
6365 }
6366
6367 $DBversion = "3.11.00.012";
6368 if ( CheckVersion($DBversion) ) {
6369     $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')");
6370     print "Upgrade to $DBversion done (Bug 9206: Only allow place holds in records that the patron don't have in his possession)\n";
6371     SetVersion($DBversion);
6372 }
6373
6374 $DBversion = "3.11.00.013";
6375 if ( CheckVersion($DBversion) ) {
6376     $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')");
6377     print "Upgrade to $DBversion done (Bug 9162 - Add a system preference to set which notes fields appears on title notes/description separator)\n";
6378     SetVersion($DBversion);
6379 }
6380
6381 $DBversion = "3.11.00.014";
6382 if ( CheckVersion($DBversion) ) {
6383    $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' )");
6384    $dbh->do("INSERT INTO systempreferences ( variable, value, explanation, type ) VALUES ( 'SCOUserJS', '', 'Define custom javascript for inclusion in the SCO module', 'free' )");
6385    print "Upgrade to $DBversion done (Bug 9009: Add SCOUserCSS and SCOUserJS sysprefs)\n";
6386 }
6387
6388 $DBversion = "3.11.00.015";
6389 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6390     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('RentalsInNoissuesCharge', '1', 'Rental charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
6391     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('ManInvInNoissuesCharge', '1', 'MANUAL_INV charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
6392     print "Upgrade to $DBversion done (Add sysprefs RentalsInNoissuesCharge and ManInvInNoissuesCharge.)\n";
6393     SetVersion($DBversion);
6394 }
6395
6396 $DBversion = "3.11.00.016";
6397 if ( CheckVersion($DBversion) ) {
6398    $dbh->do(q{
6399         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";
6400         });
6401    $dbh->do(q{
6402         UPDATE userflags SET flagdesc="Edit Authorities" where flagdesc="Allow to edit authorities";
6403         });
6404    $dbh->do(q{
6405         UPDATE userflags SET flagdesc="Allow access to the reports module" where flagdesc="Allow to access to the reports module";
6406         });
6407    $dbh->do(q{
6408         UPDATE userflags SET flagdesc="Set library management parameters (deprecated)" where flagdesc="Set library management parameters";
6409         });
6410    $dbh->do(q{
6411         UPDATE userflags SET flagdesc="Manage serial subscriptions" where flagdesc="Allow to manage serials subscriptions";
6412         });
6413    $dbh->do(q{
6414         UPDATE userflags SET flagdesc="Manage patrons fines and fees" where flagdesc="Update borrower charges";
6415         });
6416    $dbh->do(q{
6417         UPDATE userflags SET flagdesc="Check out and check in items" where flagdesc="Circulate books";
6418         });
6419    $dbh->do(q{
6420         UPDATE userflags SET flagdesc="Manage Koha system settings (Administration panel)" where flagdesc="Set Koha system parameters";
6421         });
6422    $dbh->do(q{
6423         UPDATE userflags SET flagdesc="Add or modify patrons" where flagdesc="Add or modify borrowers";
6424         });
6425    $dbh->do(q{
6426         UPDATE userflags SET flagdesc="Use all tools (expand for granular tools permissions)" where flagdesc="Use tools (export, import, barcodes)";
6427         });
6428    $dbh->do(q{
6429         UPDATE userflags SET flagdesc="Allow staff members to modify permissions for other staff members" where flagdesc="Set user permissions";
6430         });
6431    $dbh->do(q{
6432         UPDATE permissions SET description="Perform batch modification of patrons" where description="Perform batch modifivation of patrons";
6433         });
6434
6435    print "Upgrade to $DBversion done (Bug 9382 (updated with bug 9745) - refresh permission descriptions to make more sense)\n";
6436    SetVersion ($DBversion);
6437 }
6438
6439 $DBversion ="3.11.00.017";
6440 if ( CheckVersion($DBversion) ) {
6441     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksReviews','0','Display book review snippets from IDreamBooks.com','','YesNo');");
6442     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksReadometer','0','Display Readometer from IDreamBooks.com','','YesNo');");
6443     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksResults','0','Display IDreamBooks.com rating in search results','','YesNo');");
6444     print "Upgrade to $DBversion done (Add IDreamBooks enhanced content)\n";
6445     SetVersion($DBversion);
6446 }
6447
6448 $DBversion = "3.11.00.018";
6449 if ( CheckVersion($DBversion) ) {
6450    $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')");
6451    $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')");
6452    print "Upgrade to $DBversion done (Bug 9395: Problem with callnumber and standard number search in OPAC and Staff Client)\n";
6453    SetVersion ($DBversion);
6454 }
6455
6456 $DBversion = "3.11.00.019";
6457 if ( CheckVersion($DBversion) ) {
6458     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('UNIMARCAuthorityField100', 'afrey50      ba0', NULL, NULL, 'Textarea')");
6459     print "Upgrade to $DBversion done (Bug 9145 - Add syspref UNIMARCAuthorityField100)\n";
6460     SetVersion ($DBversion);
6461 }
6462
6463 $DBversion = "3.11.00.020";
6464 if ( CheckVersion($DBversion) ) {
6465     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UNIMARCField100Language', 'fre','UNIMARC field 100 default language',NULL,'short')");
6466     print "Upgrade to $DBversion done (Bug 8347 - Koha forces UNIMARC 100 field code language to 'fre')\n";
6467     SetVersion($DBversion);
6468 }
6469
6470 $DBversion ="3.11.00.021";
6471 if ( CheckVersion($DBversion) ) {
6472     $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');");
6473     print "Upgrade to $DBversion done (Bug 5888 - Subject search pop-up for the OPAC)\n";
6474     SetVersion($DBversion);
6475 }
6476
6477 $DBversion = "3.11.00.022";
6478 if ( CheckVersion($DBversion) ) {
6479     $dbh->do(
6480 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('Persona',0,'Use Mozilla Persona for login','','YesNo')"
6481     );
6482     print "Upgrade to $DBversion done (Bug 9587 - Allow login via Persona)\n";
6483     SetVersion($DBversion);
6484 }
6485
6486 $DBversion = "3.11.00.023";
6487 if ( CheckVersion($DBversion) ) {
6488     $dbh->do("UPDATE z3950servers SET host = 'lx2.loc.gov', port = 210, db = 'LCDB', syntax = 'USMARC', encoding = 'utf8' WHERE name = 'LIBRARY OF CONGRESS'");
6489     print "Upgrade to $DBversion done (Bug 9520 - Update default LOC Z39.50 target)\n";
6490     SetVersion($DBversion);
6491 }
6492
6493 $DBversion = "3.11.00.024";
6494 if ( CheckVersion($DBversion) ) {
6495     $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');");
6496     print "Upgrade to $DBversion done (Bug 5079: Add OpacItemLocation syspref)\n";
6497     SetVersion ($DBversion);
6498 }
6499
6500 $DBversion = "3.11.00.025";
6501 if ( CheckVersion($DBversion) ) {
6502     $dbh->do(
6503         "CREATE TABLE linktracker (
6504   id int(11) NOT NULL AUTO_INCREMENT,
6505   biblionumber int(11) DEFAULT NULL,
6506   itemnumber int(11) DEFAULT NULL,
6507   borrowernumber int(11) DEFAULT NULL,
6508   url text,
6509   timeclicked datetime DEFAULT NULL,
6510   PRIMARY KEY (id),
6511   KEY bibidx (biblionumber),
6512   KEY itemidx (itemnumber),
6513   KEY borridx (borrowernumber),
6514   KEY dateidx (timeclicked)
6515     ) ENGINE=InnoDB DEFAULT CHARSET=utf8;"
6516     );
6517     $dbh->do( "
6518   INSERT INTO systempreferences (variable,value,explanation,options,type)
6519   VALUES('TrackClicks','0','Track links clicked',NULL,'Integer')" );
6520     print
6521 "Upgrade to $DBversion done (Adds feature Bug 8917, the ability to track links clicked)\n";
6522     SetVersion($DBversion);
6523 }
6524
6525 $DBversion = "3.11.00.026";
6526 if ( CheckVersion($DBversion) ) {
6527     $dbh->do(qq{
6528         ALTER TABLE import_records ADD INDEX batch_id_record_type ( import_batch_id, record_type );
6529     });
6530     print "Upgrade to $DBversion done (Bug 9207: Add new index batch_id_record_type to import_records)\n";
6531     SetVersion($DBversion);
6532 }
6533
6534 $DBversion = "3.11.00.027";
6535 if ( CheckVersion($DBversion) ) {
6536     $dbh->do(q{
6537         INSERT INTO permissions ( module_bit, code, description )
6538         VALUES  ( '1', 'overdues_report', 'Execute overdue items report' )
6539     });
6540     # add new permission for users with all report permissions and circulation remaining permission
6541     $dbh->do(q{
6542         INSERT INTO user_permissions (borrowernumber, module_bit, code)
6543         SELECT user_permissions.borrowernumber, 1, 'overdues_report'
6544         FROM user_permissions
6545         LEFT JOIN borrowers USING(borrowernumber)
6546         WHERE borrowers.flags & (1 << 16)
6547         AND user_permissions.code = 'circulate_remaining_permissions'
6548     });
6549     print "Upgrade to $DBversion done ( Add circ permission overdues_report )\n";
6550     SetVersion($DBversion);
6551 }
6552
6553 $DBversion = "3.11.00.028";
6554 if ( CheckVersion($DBversion) ) {
6555     $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'    );");
6556     print "Upgrade to $DBversion done (Bug 9756 - Patron self registration missing the system preference PatronSelfRegistrationAdditionalInstructions)\n";
6557     SetVersion($DBversion);
6558 }
6559
6560 $DBversion = "3.11.00.029";
6561 if (CheckVersion($DBversion)) {
6562     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UseQueryParser', '0', 'If enabled, try to use QueryParser for queries.', NULL, 'YesNo')");
6563     print "Upgrade to $DBversion done (Bug 9239: Make it possible for Koha to use QueryParser)\n";
6564     SetVersion ($DBversion);
6565 }
6566
6567 $DBversion = "3.11.00.030";
6568 if ( CheckVersion($DBversion) ) {
6569     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('FinesIncludeGracePeriod','1','If enabled, fines calculations will include the grace period.',NULL,'YesNo');");
6570     print "Upgrade to $DBversion done (Add system preference FinesIncludeGracePeriod)\n";
6571     SetVersion($DBversion);
6572 }
6573
6574 $DBversion = "3.11.00.100";
6575 if ( CheckVersion($DBversion) ) {
6576     print "Upgrade to $DBversion done (3.12-alpha release)\n";
6577     SetVersion ($DBversion);
6578 }
6579
6580 $DBversion = "3.11.00.101";
6581 if ( CheckVersion($DBversion) ) {
6582    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('UNIMARCAuthorsFacetsSeparator',', ', 'UNIMARC authors facets separator', NULL, 'short')");
6583    print "Upgrade to $DBversion done (Bug 9341: Problem with UNIMARC authors facets)\n";
6584    SetVersion ($DBversion);
6585 }
6586
6587 $DBversion = "3.11.00.102";
6588 if ( CheckVersion($DBversion) ) {
6589     $dbh->do(q{
6590         DELETE FROM systempreferences WHERE variable='NoZebra'
6591     });
6592     $dbh->do(q{
6593         DELETE FROM systempreferences WHERE variable='QueryRemoveStopwords'
6594     });
6595     print "Upgrade to $DBversion done (Remove deprecated NoZebra and QueryRemoveStopwords sysprefs)\n";
6596     SetVersion($DBversion);
6597 }
6598
6599 $DBversion = "3.11.00.103";
6600 if ( CheckVersion($DBversion) ) {
6601     $dbh->do("DELETE FROM systempreferences WHERE variable = 'insecure';");
6602     print "Upgrade to $DBversion done (Bug 9827 - Remove 'insecure' system preference)\n";
6603     SetVersion($DBversion);
6604 }
6605
6606 $DBversion = "3.11.00.104";
6607 if ( CheckVersion($DBversion) ) {
6608     print "Upgrade to $DBversion done (3.12-alpha2 release)\n";
6609     SetVersion ($DBversion);
6610 }
6611
6612 $DBversion = "3.11.00.105";
6613 if ( CheckVersion($DBversion) ) {
6614     if ( C4::Context->preference("marcflavour") eq 'MARC21' ) {
6615         $sth = $dbh->prepare(
6616 "SELECT frameworkcode FROM marc_tag_structure WHERE tagfield = '029'"
6617         );
6618         $sth->execute;
6619         my $frameworkcodes = $sth->fetchall_hashref('frameworkcode');
6620
6621         for my $frameworkcode ( keys %$frameworkcodes ) {
6622             $dbh->do( "
6623     INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian,
6624     libopac, repeatable, mandatory, kohafield, tab, authorised_value, authtypecode,
6625     value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
6626     ('029', 'a', 'OCLC library identifier', 'OCLC library identifier', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6627     ('029', 'b', 'System control number', 'System control number', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6628     ('029', 'c', 'OAI set name', 'OAI set name', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6629     ('029', 't', 'Content type identifier', 'Content type identifier', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL)
6630    " );
6631         }
6632
6633         for my $tag ( '863', '864', '865' ) {
6634             $sth = $dbh->prepare(
6635 "SELECT frameworkcode FROM marc_tag_structure WHERE tagfield = '$tag'"
6636             );
6637             $sth->execute;
6638             my $frameworkcodes = $sth->fetchall_hashref('frameworkcode');
6639
6640             for my $frameworkcode ( keys %$frameworkcodes ) {
6641                 $dbh->do( "
6642      INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian,
6643      libopac, repeatable, mandatory, kohafield, tab, authorised_value, authtypecode,
6644      value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
6645      ('$tag', '6', 'Linkage', 'Linkage', 0, 0, '', 8, '', '', '', NULL, 5, '$frameworkcode', '', '', NULL),
6646      ('$tag', '8', 'Field link and sequence number', 'Field link and sequence number', 0, 0, '', 8, '', '', '', NULL, 5, '$frameworkcode', '', '', NULL),
6647      ('$tag', 'a', 'First level of enumeration', 'First level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6648      ('$tag', 'b', 'Second level of enumeration', 'Second level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6649      ('$tag', 'c', 'Third level of enumeration', 'Third level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6650      ('$tag', 'd', 'Fourth level of enumeration', 'Fourth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6651      ('$tag', 'e', 'Fifth level of enumeration', 'Fifth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6652      ('$tag', 'f', 'Sixth level of enumeration', 'Sixth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6653      ('$tag', 'g', 'Alternative numbering scheme, first level of enumeration', 'Alternative numbering scheme, first level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6654      ('$tag', 'h', 'Alternative numbering scheme, second level of enumeration', 'Alternative numbering scheme, second level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6655      ('$tag', 'i', 'First level of chronology', 'First level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6656      ('$tag', 'j', 'Second level of chronology', 'Second level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6657      ('$tag', 'k', 'Third level of chronology', 'Third level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6658      ('$tag', 'l', 'Fourth level of chronology', 'Fourth level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6659      ('$tag', 'm', 'Alternative numbering scheme, chronology', 'Alternative numbering scheme, chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6660      ('$tag', 'n', 'Converted Gregorian year', 'Converted Gregorian year', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6661      ('$tag', 'o', 'Type of unit', 'Type of unit', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6662      ('$tag', 'p', 'Piece designation', 'Piece designation', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6663      ('$tag', 'q', 'Piece physical condition', 'Piece physical condition', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6664      ('$tag', 's', 'Copyright article-fee code', 'Copyright article-fee code', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6665      ('$tag', 't', 'Copy number', 'Copy number', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6666      ('$tag', 'v', 'Issuing date', 'Issuing date', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6667      ('$tag', 'w', 'Break indicator', 'Break indicator', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6668      ('$tag', 'x', 'Nonpublic note', 'Nonpublic note', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6669      ('$tag', 'z', 'Public note', 'Public note', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL)
6670     " );
6671             }
6672         }
6673     }
6674     print "Upgrade to $DBversion done (Bug 9353: Missing subfields on MARC21 frameworks)\n";
6675     SetVersion($DBversion);
6676 }
6677
6678
6679 $DBversion = "3.11.00.106";
6680 if ( CheckVersion($DBversion) ) {
6681     $dbh->do("INSERT INTO userflags (bit, flag, flagdesc, defaulton) VALUES ('19', 'plugins', 'Koha plugins', '0')");
6682     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
6683               ('19', 'manage', 'Manage plugins ( install / uninstall )'),
6684               ('19', 'tool', 'Use tool plugins'),
6685               ('19', 'report', 'Use report plugins'),
6686               ('19', 'configure', 'Configure plugins')
6687             ");
6688     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UseKohaPlugins','0','Enable or disable the ability to use Koha Plugins.','','YesNo')");
6689
6690     $dbh->do("
6691         CREATE TABLE IF NOT EXISTS plugin_data (
6692             plugin_class varchar(255) NOT NULL,
6693             plugin_key varchar(255) NOT NULL,
6694             plugin_value text,
6695             PRIMARY KEY (plugin_class,plugin_key)
6696         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6697     ");
6698
6699     print "Upgrade to $DBversion done (Bug 7804: Added plugin system.)\n";
6700     SetVersion($DBversion);
6701 }
6702
6703 $DBversion = "3.11.00.107";
6704 if ( CheckVersion($DBversion) ) {
6705    $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('TimeFormat','24hr','12hr|24hr','Defines the global time format for visual output.','Choice')");
6706    print "Upgrade to $DBversion done (Bug 9014: Add syspref TimeFormat)\n";
6707    SetVersion ($DBversion);
6708 }
6709
6710 $DBversion = "3.11.00.108";
6711 if ( CheckVersion($DBversion) ) {
6712     $dbh->do("ALTER TABLE action_logs CHANGE timestamp timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;");
6713     $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');");
6714     $dbh->do("ALTER TABLE action_logs CHANGE timestamp timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;");
6715     print "Upgrade to $DBversion done (Bug 7241: Fix on circulation logs)\n";
6716     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";
6717     SetVersion($DBversion);
6718 }
6719
6720 $DBversion = "3.11.00.109";
6721 if ( CheckVersion($DBversion) ) {
6722    $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');");
6723    print "Upgrade to $DBversion done (Bug 9403: Add DisplayIconsXSLT)\n";
6724    SetVersion ($DBversion);
6725 }
6726
6727 $DBversion = "3.11.00.110";
6728 if ( CheckVersion($DBversion) ) {
6729     $dbh->do("ALTER TABLE pending_offline_operations CHANGE barcode barcode VARCHAR( 20 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
6730     $dbh->do("ALTER TABLE pending_offline_operations ADD amount DECIMAL( 28, 6 ) NULL DEFAULT NULL");
6731     print "Upgrade to $DBversion done (Bug 8220 - Allow koc uploads to go to process queue)\n";
6732     SetVersion ($DBversion);
6733 }
6734
6735 $DBversion = "3.11.00.111";
6736 if ( CheckVersion($DBversion) ) {
6737     my $sth = $dbh->prepare("
6738         SELECT module, code, branchcode, content
6739         FROM letter
6740         WHERE content LIKE '%<fine>%'
6741     ");
6742     $sth->execute;
6743     my $sth_update = $dbh->prepare("UPDATE letter SET content = ? WHERE module = ? AND code = ? AND branchcode = ?");
6744     while(my $row = $sth->fetchrow_hashref){
6745         $row->{content} =~ s/<fine>\w+<\/fine>/<<items.fine>>/;
6746         $sth_update->execute($row->{content}, $row->{module}, $row->{code}, $row->{branchcode});
6747     }
6748     print "Upgrade to $DBversion done (use new <<items.fine>> syntax in notices)\n";
6749     SetVersion($DBversion);
6750 }
6751
6752 $DBversion = "3.11.00.112";
6753 if ( CheckVersion($DBversion) ) {
6754     $dbh->do(qq{
6755         ALTER TABLE issuingrules ADD COLUMN renewalperiod int(4) DEFAULT NULL AFTER renewalsallowed
6756     });
6757     $dbh->do(qq{
6758         UPDATE issuingrules SET renewalperiod = issuelength
6759     });
6760     print "Upgrade to $DBversion done (Bug 8365: Add colum issuingrules.renewalperiod)\n";
6761     SetVersion ($DBversion);
6762 }
6763
6764 $DBversion = "3.11.00.113";
6765 if ( CheckVersion($DBversion) ) {
6766     $dbh->do(q{
6767         ALTER TABLE branchcategories ADD show_in_pulldown BOOLEAN NOT NULL DEFAULT '0',
6768         ADD INDEX ( show_in_pulldown )
6769     });
6770     print "Upgrade to $DBversion done (Bug 9257 - Add groups to normal search pulldown)\n";
6771     SetVersion ($DBversion);
6772 }
6773
6774 $DBversion = "3.11.00.115";
6775 if ( CheckVersion($DBversion) ) {
6776     $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')");
6777     $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')");
6778     print "Upgrade to $DBversion done (Bug 7740: Add syspref HighlightOwnItemsOnOPAC)\n";
6779     SetVersion ($DBversion);
6780 }
6781
6782 $DBversion = "3.11.00.116";
6783 if ( CheckVersion($DBversion) ) {
6784     $dbh->do(q{ALTER TABLE aqorders DROP COLUMN serialid;});
6785     $dbh->do(q{ALTER TABLE aqorders DROP COLUMN subscription;});
6786     $dbh->do(q{ALTER TABLE aqorders ADD COLUMN subscriptionid INT(11) DEFAULT NULL;});
6787     $dbh->do(q{ALTER TABLE aqorders ADD CONSTRAINT aqorders_subscriptionid FOREIGN KEY (subscriptionid) REFERENCES subscription (subscriptionid) ON DELETE CASCADE ON UPDATE CASCADE;});
6788     $dbh->do(q{ALTER TABLE subscription ADD COLUMN reneweddate DATE DEFAULT NULL;});
6789     print "Upgrade to $DBversion done (Bug 5343: table aqorders: DROP serialid and subscription fields and ADD subscriptionid, table subscription: ADD reneweddate)\n";
6790     SetVersion ($DBversion);
6791 }
6792
6793 $DBversion = "3.11.00.200";
6794 if ( CheckVersion($DBversion) ) {
6795     print "Upgrade to $DBversion done (3.12-beta1 release)\n";
6796     SetVersion ($DBversion);
6797 }
6798
6799 $DBversion = "3.11.00.201";
6800 if ( CheckVersion($DBversion) ) {
6801     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'BIBSYS' AND host LIKE 'z3950.bibsys.no'");
6802     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'NORBOK' AND host LIKE 'z3950.nb.no'");
6803     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'SAMBOK' AND host LIKE 'z3950.nb.no'");
6804     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'DEICHMAN' AND host like 'z3950.deich.folkebibl.no'");
6805     print "Upgrade to $DBversion done (Bug 9498 - Update encoding for Norwegian sample Z39.50 servers)\n";
6806     SetVersion($DBversion);
6807 }
6808
6809 $DBversion = "3.11.00.202";
6810 if ( CheckVersion($DBversion) ) {
6811    $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ca', 'language', 'Catalan','2013-01-12' )");
6812    $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'ca','cat')");
6813    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'es', 'Catalán')");
6814    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'en', 'Catalan')");
6815    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'fr', 'Catalan')");
6816    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'ca', 'Català')");
6817    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'de', 'Katalanisch')");
6818    print "Upgrade to $DBversion done (Bug 9381: Add Catalan laguage)\n";
6819    SetVersion ($DBversion);
6820 }
6821
6822 $DBversion = "3.11.00.203";
6823 if ( CheckVersion($DBversion) ) {
6824     $dbh->do(q{ALTER TABLE suggestions CHANGE COLUMN title title VARCHAR(255) DEFAULT NULL;});
6825     print "Upgrade to $DBversion done (Bug 2046 - increasing title column length for suggestions)\n";
6826     SetVersion ($DBversion);
6827 }
6828
6829 $DBversion = "3.11.00.300";
6830 if ( CheckVersion($DBversion) ) {
6831     print "Upgrade to $DBversion done (3.12-beta3 release)\n";
6832     SetVersion ($DBversion);
6833 }
6834
6835 $DBversion = "3.11.00.301";
6836 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6837     #issues
6838     $dbh->do(q{
6839         ALTER TABLE `issues`
6840             ADD KEY `itemnumber_idx` (`itemnumber`),
6841             ADD KEY `branchcode_idx` (`branchcode`),
6842             ADD KEY `issuingbranch_idx` (`issuingbranch`)
6843     });
6844     $dbh->do(q{
6845         ALTER TABLE `old_issues`
6846             ADD KEY `branchcode_idx` (`branchcode`),
6847             ADD KEY `issuingbranch_idx` (`issuingbranch`)
6848     });
6849     #items
6850     $dbh->do(q{
6851         ALTER TABLE `items` ADD KEY `itype_idx` (`itype`)
6852     });
6853     $dbh->do(q{
6854         ALTER TABLE `deleteditems` ADD KEY `itype_idx` (`itype`)
6855     });
6856     # biblioitems
6857     $dbh->do(q{
6858         ALTER TABLE `biblioitems` ADD KEY `itemtype_idx` (`itemtype`)
6859     });
6860     $dbh->do(q{
6861         ALTER TABLE `deletedbiblioitems` ADD KEY `itemtype_idx` (`itemtype`)
6862     });
6863     # statistics
6864     $dbh->do(q{
6865         ALTER TABLE `statistics`
6866             ADD KEY `branch_idx` (`branch`),
6867             ADD KEY `proccode_idx` (`proccode`),
6868             ADD KEY `type_idx` (`type`),
6869             ADD KEY `usercode_idx` (`usercode`),
6870             ADD KEY `itemnumber_idx` (`itemnumber`),
6871             ADD KEY `itemtype_idx` (`itemtype`),
6872             ADD KEY `borrowernumber_idx` (`borrowernumber`),
6873             ADD KEY `associatedborrower_idx` (`associatedborrower`),
6874             ADD KEY `ccode_idx` (`ccode`)
6875     });
6876
6877     print "Upgrade to $DBversion done (Bug 9681: Add some database indexes)\n";
6878     SetVersion($DBversion);
6879 }
6880
6881 $DBversion = "3.12.00.000";
6882 if ( CheckVersion($DBversion) ) {
6883     print "Upgrade to $DBversion done (3.12.0 release)\n";
6884     SetVersion ($DBversion);
6885 }
6886
6887 $DBversion = '3.13.00.000';
6888 if ( CheckVersion($DBversion) ) {
6889     print "Upgrade to $DBversion done (start the journey to Koha Pi)\n";
6890     SetVersion ($DBversion);
6891 }
6892
6893 $DBversion = "3.13.00.001";
6894 if ( CheckVersion($DBversion) ) {
6895     $dbh->do("INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('UseCourseReserves', '0', NULL, 'Enable the course reserves feature.', 'YesNo')");
6896     $dbh->do("INSERT INTO userflags (bit,flag,flagdesc,defaulton) VALUES ('18','coursereserves','Course Reserves','0')");
6897     $dbh->do("
6898 CREATE TABLE `courses` (
6899   `course_id` int(11) NOT NULL AUTO_INCREMENT,
6900   `department` varchar(20) DEFAULT NULL,
6901   `course_number` varchar(255) DEFAULT NULL,
6902   `section` varchar(255) DEFAULT NULL,
6903   `course_name` varchar(255) DEFAULT NULL,
6904   `term` varchar(20) DEFAULT NULL,
6905   `staff_note` mediumtext,
6906   `public_note` mediumtext,
6907   `students_count` varchar(20) DEFAULT NULL,
6908   `enabled` enum('yes','no') NOT NULL DEFAULT 'yes',
6909   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6910    PRIMARY KEY (`course_id`)
6911 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6912     ");
6913
6914     $dbh->do("
6915 CREATE TABLE `course_instructors` (
6916   `course_id` int(11) NOT NULL,
6917   `borrowernumber` int(11) NOT NULL,
6918   PRIMARY KEY (`course_id`,`borrowernumber`),
6919   KEY `borrowernumber` (`borrowernumber`)
6920 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6921     ");
6922
6923     $dbh->do("
6924 ALTER TABLE `course_instructors`
6925   ADD CONSTRAINT `course_instructors_ibfk_2` FOREIGN KEY (`course_id`) REFERENCES `courses` (`course_id`),
6926   ADD CONSTRAINT `course_instructors_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE;
6927     ");
6928
6929     $dbh->do("
6930 CREATE TABLE `course_items` (
6931   `ci_id` int(11) NOT NULL AUTO_INCREMENT,
6932   `itemnumber` int(11) NOT NULL,
6933   `itype` varchar(10) DEFAULT NULL,
6934   `ccode` varchar(10) DEFAULT NULL,
6935   `holdingbranch` varchar(10) DEFAULT NULL,
6936   `location` varchar(80) DEFAULT NULL,
6937   `enabled` enum('yes','no') NOT NULL DEFAULT 'no',
6938   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6939    PRIMARY KEY (`ci_id`),
6940    UNIQUE KEY `itemnumber` (`itemnumber`),
6941    KEY `holdingbranch` (`holdingbranch`)
6942 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6943     ");
6944
6945     $dbh->do("
6946 ALTER TABLE `course_items`
6947   ADD CONSTRAINT `course_items_ibfk_2` FOREIGN KEY (`holdingbranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
6948   ADD CONSTRAINT `course_items_ibfk_1` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE;
6949 ");
6950
6951     $dbh->do("
6952 CREATE TABLE `course_reserves` (
6953   `cr_id` int(11) NOT NULL AUTO_INCREMENT,
6954   `course_id` int(11) NOT NULL,
6955   `ci_id` int(11) NOT NULL,
6956   `staff_note` mediumtext,
6957   `public_note` mediumtext,
6958   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6959    PRIMARY KEY (`cr_id`),
6960    UNIQUE KEY `pseudo_key` (`course_id`,`ci_id`),
6961    KEY `course_id` (`course_id`)
6962 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6963 ");
6964
6965     $dbh->do("
6966 ALTER TABLE `course_reserves`
6967   ADD CONSTRAINT `course_reserves_ibfk_1` FOREIGN KEY (`course_id`) REFERENCES `courses` (`course_id`);
6968     ");
6969
6970     $dbh->do("
6971 INSERT INTO permissions (module_bit, code, description) VALUES
6972   (18, 'manage_courses', 'Add, edit and delete courses'),
6973   (18, 'add_reserves', 'Add course reserves'),
6974   (18, 'delete_reserves', 'Remove course reserves')
6975 ;
6976     ");
6977
6978
6979     print "Upgrade to $DBversion done (Add Course Reserves ( system preference UseCourseReserves ))\n";
6980     SetVersion($DBversion);
6981 }
6982
6983 $DBversion = "3.13.00.002";
6984 if ( CheckVersion($DBversion) ) {
6985    $dbh->do("UPDATE systempreferences SET variable = 'IndependentBranches' WHERE variable = 'IndependantBranches'");
6986    print "Upgrade to $DBversion done (Bug 10080 - Change system pref IndependantBranches to IndependentBranches)\n";
6987    SetVersion ($DBversion);
6988 }
6989
6990 $DBversion = '3.13.00.003';
6991 if ( CheckVersion($DBversion) ) {
6992     $dbh->do("ALTER TABLE serial DROP itemnumber");
6993     print "Upgrade to $DBversion done (Bug 7718 - Remove itemnumber column from serials table)\n";
6994     SetVersion($DBversion);
6995 }
6996
6997 $DBversion = "3.13.00.004";
6998 if(CheckVersion($DBversion)) {
6999     $dbh->do(
7000 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacShowHoldNotes',0,'Show hold notes on OPAC','','YesNo')"
7001     );
7002     print "Upgrade to $DBversion done (Bug 9722: Allow users to add notes when placing a hold in OPAC)\n";
7003     SetVersion($DBversion);
7004 }
7005
7006 $DBversion = "3.13.00.005";
7007 if(CheckVersion($DBversion)) {
7008     my $intra= C4::Context->preference("intranetstylesheet");
7009     #if this pref is not blank or starting with http, https or / [root], then
7010     #add an additional / to the front
7011     if($intra && $intra !~ /^(\/|https?)/) {
7012         $dbh->do("UPDATE systempreferences SET value=? WHERE variable=?",
7013             undef,('/'.$intra,"intranetstylesheet"));
7014         print "WARNING: Your system preference intranetstylesheet has been prefixed with a slash to make it an absolute path.\n";
7015     }
7016     print "Upgrade to $DBversion done (Bug 10052: Make intranetstylesheet and intranetcolorstylesheet behave exactly like their opac counterparts)\n";
7017     SetVersion ($DBversion);
7018 }
7019
7020 $DBversion = "3.13.00.006";
7021 if ( CheckVersion($DBversion) ) {
7022     $dbh->do(
7023         q{
7024 INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('CalculateFinesOnReturn','1','Switch to control if overdue fines are calculated on return or not', '', 'YesNo');
7025 }
7026     );
7027     print
7028 "Upgrade to $DBversion done (Bug 10120 - Fines on item return controlled by a systempreference)\n";
7029     SetVersion($DBversion);
7030 }
7031
7032 $DBversion = "3.13.00.007";
7033 if ( CheckVersion($DBversion) ) {
7034     $dbh->do("UPDATE systempreferences SET variable='OpacHoldNotes' WHERE variable='OpacShowHoldNotes'");
7035     print "Upgrade to $DBversion done (Bug 10343: Rename OpacShowHoldNotes to OpacHoldNotes)\n";
7036     SetVersion($DBversion);
7037 }
7038
7039 $DBversion = "3.13.00.008";
7040 if ( CheckVersion($DBversion) ) {
7041     $dbh->do("
7042 CREATE TABLE IF NOT EXISTS borrower_files (
7043   file_id int(11) NOT NULL AUTO_INCREMENT,
7044   borrowernumber int(11) NOT NULL,
7045   file_name varchar(255) NOT NULL,
7046   file_type varchar(255) NOT NULL,
7047   file_description varchar(255) DEFAULT NULL,
7048   file_content longblob NOT NULL,
7049   date_uploaded timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
7050   PRIMARY KEY (file_id),
7051   KEY borrowernumber (borrowernumber),
7052   CONSTRAINT borrower_files_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
7053 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7054     ");
7055     print "Upgrade to $DBversion done (Bug 10443: make sure borrower_files table exists)\n";
7056     SetVersion($DBversion);
7057 }
7058
7059 $DBversion = "3.13.00.009";
7060 if ( CheckVersion($DBversion) ) {
7061     $dbh->do("ALTER TABLE aqorders DROP COLUMN biblioitemnumber");
7062     print "Upgrade to $DBversion done (Bug 9987 - Drop column aqorders.biblioitemnumber)\n";
7063     SetVersion($DBversion);
7064 }
7065
7066 $DBversion = "3.13.00.010";
7067 if ( CheckVersion($DBversion) ) {
7068     $dbh->do(
7069         q{
7070 INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AcqWarnOnDuplicateInvoice','0','Warn librarians when they try to create a duplicate invoice', '', 'YesNo');
7071 }
7072     );
7073     print
7074 "Upgrade to $DBversion done (Bug 10366 - Add system preference to enabling warning librarian when invoice is duplicated)\n";
7075     SetVersion($DBversion);
7076 }
7077
7078 $DBversion = "3.13.00.011";
7079 if ( CheckVersion($DBversion) ) {
7080     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='ita' WHERE rfc4646_subtag='it'");
7081     print "Upgrade to $DBversion done (Bug 9519: Wrong language code for Italian in the advanced search language limitations)\n";
7082     SetVersion($DBversion);
7083 }
7084
7085 $DBversion = "3.13.00.012";
7086 if ( CheckVersion($DBversion) ) {
7087     $dbh->do("ALTER TABLE issuingrules MODIFY COLUMN overduefinescap decimal(28,6) DEFAULT NULL;");
7088     print "Upgrade to $DBversion done (Bug 10490: Correct datatype for overduefinescap in issuingrules)\n";
7089     SetVersion($DBversion);
7090 }
7091
7092 $DBversion ="3.13.00.013";
7093 if ( CheckVersion($DBversion) ) {
7094     $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');");
7095     print "Upgrade to $DBversion done (Bug 9576: add AllowTooManyOverride syspref to enable or disable issue limit confirmation)\n";
7096     SetVersion($DBversion);
7097 }
7098
7099 $DBversion = "3.13.00.014";
7100 if ( CheckVersion($DBversion) ) {
7101     $dbh->do("ALTER TABLE courses MODIFY COLUMN department varchar(80) DEFAULT NULL;");
7102     $dbh->do("ALTER TABLE courses MODIFY COLUMN term       varchar(80) DEFAULT NULL;");
7103     print "Upgrade to $DBversion done (Bug 10604: correct width of courses.department and courses.term)\n";
7104     SetVersion($DBversion);
7105 }
7106
7107 $DBversion = "3.13.00.015";
7108 if ( CheckVersion($DBversion) ) {
7109     $dbh->do(
7110 "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')"
7111     );
7112     print "Upgrade to $DBversion done (Bug 7494: Add itemBarcodeFallbackSearch syspref)\n";
7113     SetVersion($DBversion);
7114 }
7115
7116 $DBversion = "3.13.00.016";
7117 if ( CheckVersion($DBversion) ) {
7118     $dbh->do(q{
7119         ALTER TABLE items CHANGE wthdrawn withdrawn TINYINT( 1 ) NOT NULL DEFAULT  '0'
7120     });
7121
7122     $dbh->do(q{
7123         ALTER TABLE deleteditems CHANGE wthdrawn withdrawn TINYINT( 1 ) NOT NULL DEFAULT  '0'
7124     });
7125
7126     $dbh->do(q{
7127         UPDATE saved_sql SET savedsql = REPLACE(savedsql, 'wthdrawn', 'withdrawn')
7128     });
7129
7130     $dbh->do(q{
7131         UPDATE marc_subfield_structure SET kohafield = 'items.withdrawn' WHERE kohafield = 'items.wthdrawn'
7132     });
7133
7134     print "Upgrade to $DBversion done (Bug 10550 - Fix database typo wthdrawn)\n";
7135     SetVersion($DBversion);
7136 }
7137
7138 $DBversion = "3.13.00.017";
7139 if ( CheckVersion($DBversion) ) {
7140     $dbh->do(
7141 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveClientKey','','Client key for OverDrive integration','30','Free')"
7142     );
7143     $dbh->do(
7144 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveClientSecret','','Client key for OverDrive integration','30','YesNo')"
7145     );
7146     $dbh->do(
7147 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveLibraryID','','Library ID for OverDrive integration','','Integer')"
7148     );
7149     print "Upgrade to $DBversion done (Bug 10320 - Show results from library's OverDrive collection in OPAC search)\n";
7150     SetVersion($DBversion);
7151 }
7152
7153 $DBversion = "3.13.00.018";
7154 if ( CheckVersion($DBversion) ) {
7155     $dbh->do(qq{DROP TABLE IF EXISTS aqorders_transfers;});
7156     $dbh->do(qq{
7157         CREATE TABLE aqorders_transfers (
7158           ordernumber_from int(11) NULL,
7159           ordernumber_to int(11) NULL,
7160           timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
7161           UNIQUE KEY ordernumber_from (ordernumber_from),
7162           UNIQUE KEY ordernumber_to (ordernumber_to),
7163           CONSTRAINT aqorders_transfers_ordernumber_from FOREIGN KEY (ordernumber_from) REFERENCES aqorders (ordernumber) ON DELETE SET NULL ON UPDATE CASCADE,
7164           CONSTRAINT aqorders_transfers_ordernumber_to FOREIGN KEY (ordernumber_to) REFERENCES aqorders (ordernumber) ON DELETE SET NULL ON UPDATE CASCADE
7165         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7166     });
7167     print "Upgrade to $DBversion done (Bug 5349: Add aqorders_transfers table)\n";
7168     SetVersion($DBversion);
7169 }
7170
7171 $DBversion = "3.13.00.019";
7172 if ( CheckVersion($DBversion) ) {
7173     $dbh->do("ALTER TABLE itemtypes ADD COLUMN checkinmsg VARCHAR(255) AFTER summary;");
7174     $dbh->do("ALTER TABLE itemtypes ADD COLUMN checkinmsgtype CHAR(16) DEFAULT 'message' NOT NULL AFTER checkinmsg;");
7175     print "Upgrade to $DBversion done (Bug 10513 - Light up a warning/message when returning a chosen item type)\n";
7176     SetVersion($DBversion);
7177 }
7178
7179 $DBversion = "3.13.00.020";
7180 if ( CheckVersion($DBversion) ) {
7181     $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')");
7182     $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')");
7183     print "Upgrade to $DBversion done (Bug 7639: system preferences to forgive fines on lost items)\n";
7184     SetVersion($DBversion);
7185 }
7186
7187 $DBversion ="3.13.00.021";
7188 if ( CheckVersion($DBversion) ) {
7189     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ConfirmFutureHolds','0','Number of days for confirming future holds','','Integer');");
7190     print "Upgrade to $DBversion done (Bug 9761: Add ConfirmFutureHolds pref)\n";
7191     SetVersion($DBversion);
7192 }
7193
7194 $DBversion = "3.13.00.022";
7195 if ( CheckVersion($DBversion) ) {
7196     $dbh->do("DELETE from auth_tag_structure WHERE tagfield IN ('68a','68b')");
7197     $dbh->do("DELETE from auth_subfield_structure WHERE tagfield IN ('68a','68b')");
7198     print "Upgrade to $DBversion done (Bug 10687 - Delete erroneous tags 68a and 68b on default MARC21 auth framework)\n";
7199     SetVersion($DBversion);
7200 }
7201
7202 $DBversion = "3.13.00.023";
7203 if ( CheckVersion($DBversion) ) {
7204     $dbh->do("ALTER TABLE borrowers CHANGE password password VARCHAR(60);");
7205     print "Upgrade to $DBversion done (Bug 9611 upgrading password storage system)\n";
7206     SetVersion($DBversion);
7207 }
7208
7209 $DBversion = "3.13.00.024";
7210 if ( CheckVersion($DBversion) ) {
7211     $dbh->do(q{ALTER TABLE z3950servers ADD COLUMN recordtype VARCHAR(45) NOT NULL DEFAULT 'biblio' AFTER description;});
7212     print "Upgrade to $DBversion done (Bug 10096 - Add a Z39.50 interface for authority searching)\n";
7213 }
7214
7215 $DBversion = "3.13.00.025";
7216 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
7217    $dbh->do("ALTER TABLE oai_sets_mappings ADD COLUMN operator varchar(8) NOT NULL default 'equal' AFTER marcsubfield;");
7218    print "Upgrade to $DBversion done (Bug 9295: OAI notequal: add operator column to OAI mappings table)\n";
7219    SetVersion ($DBversion);
7220 }
7221
7222 $DBversion = "3.13.00.026";
7223 if ( CheckVersion($DBversion) ) {
7224     $dbh->do(q|
7225         ALTER TABLE auth_subfield_structure ADD COLUMN defaultvalue TEXT DEFAULT NULL AFTER frameworkcode
7226     |);
7227     print "Upgrade to $DBversion done (Bug 10602: Add the column auth_subfield_structure.defaultvalue)\n";
7228     SetVersion($DBversion);
7229 }
7230
7231 $DBversion = "3.13.00.027";
7232 if ( CheckVersion($DBversion) ) {
7233     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('AllowOfflineCirculation','0','','If on, enables HTML5 offline circulation functionality.','YesNo')");
7234     print "Upgrade to $DBversion done (Bug 10240: Add syspref AllowOfflineCirculation)\n";
7235     SetVersion ($DBversion);
7236 }
7237
7238 $DBversion = "3.13.00.028";
7239 if ( CheckVersion($DBversion) ) {
7240     $dbh->do(q{
7241         ALTER TABLE export_format ADD type VARCHAR(255) DEFAULT 'marc' AFTER encoding
7242     });
7243     $dbh->do(q{
7244         ALTER TABLE export_format CHANGE marcfields content mediumtext NOT NULL
7245     });
7246     print "Upgrade to $DBversion done (Bug 10853: Add new field export_format.type and rename export_format.marcfields with export_format.content)\n";
7247     SetVersion($DBversion);
7248 }
7249
7250 $DBversion = "3.13.00.029";
7251 if ( CheckVersion($DBversion) ) {
7252     $dbh->do(q{
7253         INSERT IGNORE INTO export_format( profile, description, content, csv_separator, type )
7254         VALUES ( "issues to claim", "Default CSV export for serial issue claims",
7255                 "SUPPLIER=aqbooksellers.name|TITLE=subscription.title|ISSUE NUMBER=serial.serialseq|LATE SINCE=serial.planneddate",
7256                 ",", "sql" )
7257     });
7258     print "Upgrade to $DBversion done (Bug 10854: Add the default CSV profile for claiming issues)\n";
7259     SetVersion($DBversion);
7260 }
7261
7262 $DBversion = "3.13.00.030";
7263 if ( CheckVersion($DBversion) ) {
7264     $dbh->do(qq{
7265         DELETE FROM patronimage WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowers.cardnumber = patronimage.cardnumber)
7266     });
7267
7268     $dbh->do(qq{
7269         ALTER TABLE patronimage ADD borrowernumber INT( 11 ) NULL FIRST
7270     });
7271
7272     $dbh->{AutoCommit} = 0;
7273     $dbh->{RaiseError} = 1;
7274
7275     eval {
7276         $dbh->do(qq{
7277             UPDATE patronimage LEFT JOIN borrowers USING ( cardnumber ) SET patronimage.borrowernumber = borrowers.borrowernumber
7278         });
7279         $dbh->commit();
7280     };
7281
7282     if ($@) {
7283         print "Upgrade to $DBversion done (Bug 10636 - patronimage should have borrowernumber as PK, not cardnumber) failed! Transaction aborted because $@\n";
7284         eval { $dbh->rollback };
7285     }
7286     else {
7287         $dbh->do(qq{
7288             ALTER TABLE patronimage DROP FOREIGN KEY patronimage_fk1
7289         });
7290         $dbh->do(qq{
7291             ALTER TABLE patronimage DROP PRIMARY KEY, ADD PRIMARY KEY( borrowernumber )
7292         });
7293         $dbh->do(qq{
7294             ALTER TABLE patronimage DROP cardnumber
7295         });
7296         $dbh->do(qq{
7297             ALTER TABLE patronimage ADD FOREIGN KEY ( borrowernumber ) REFERENCES borrowers ( borrowernumber ) ON DELETE CASCADE ON UPDATE CASCADE
7298         });
7299
7300         print "Upgrade to $DBversion done (Bug 10636 - patronimage should have borrowernumber as PK, not cardnumber)\n";
7301         SetVersion($DBversion);
7302     }
7303
7304     $dbh->{AutoCommit} = 1;
7305     $dbh->{RaiseError} = 0;
7306 }
7307
7308 $DBversion = "3.13.00.031";
7309 if ( CheckVersion($DBversion) ) {
7310
7311     $dbh->do(q{
7312         CREATE TABLE IF NOT EXISTS `patron_lists` (
7313           patron_list_id int(11) NOT NULL AUTO_INCREMENT,
7314           name varchar(255) CHARACTER SET utf8 NOT NULL,
7315           owner int(11) NOT NULL,
7316           PRIMARY KEY (patron_list_id),
7317           KEY owner (owner)
7318         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7319     });
7320
7321     $dbh->do(q{
7322         ALTER TABLE `patron_lists`
7323           ADD CONSTRAINT patron_lists_ibfk_1 FOREIGN KEY (`owner`) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE;
7324     });
7325
7326     $dbh->do(q{
7327         CREATE TABLE patron_list_patrons (
7328           patron_list_patron_id int(11) NOT NULL AUTO_INCREMENT,
7329           patron_list_id int(11) NOT NULL,
7330           borrowernumber int(11) NOT NULL,
7331           PRIMARY KEY (patron_list_patron_id),
7332           KEY patron_list_id (patron_list_id),
7333           KEY borrowernumber (borrowernumber)
7334         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7335     });
7336
7337     $dbh->do(q{
7338         ALTER TABLE `patron_list_patrons`
7339           ADD CONSTRAINT patron_list_patrons_ibfk_1 FOREIGN KEY (patron_list_id) REFERENCES patron_lists (patron_list_id) ON DELETE CASCADE ON UPDATE CASCADE,
7340           ADD CONSTRAINT patron_list_patrons_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE;
7341     });
7342
7343     $dbh->do(q{
7344         INSERT INTO permissions (module_bit, code, description) VALUES
7345         (13, 'manage_patron_lists', 'Add, edit and delete patron lists and their contents')
7346     });
7347
7348     print "Upgrade to $DBversion done (Bug 10565 - Add a 'Patron List' feature for storing and manipulating collections of patrons)\n";
7349     SetVersion($DBversion);
7350 }
7351
7352 $DBversion = "3.13.00.032";
7353 if ( CheckVersion($DBversion) ) {
7354     $dbh->do("ALTER TABLE aqorders ADD COLUMN orderstatus varchar(16) DEFAULT 'new' AFTER parent_ordernumber");
7355     $dbh->do("UPDATE aqorders SET orderstatus='ordered' WHERE basketno IN (SELECT basketno FROM aqbasket WHERE closedate IS NOT NULL)");
7356     $dbh->do(q{
7357         UPDATE aqorders SET orderstatus='partial'
7358         WHERE quantity > quantityreceived
7359         AND quantityreceived > 0
7360         AND ordernumber IN (
7361             SELECT parent_ordernumber
7362             FROM (
7363                 SELECT DISTINCT(parent_ordernumber)
7364                 FROM aqorders
7365                 WHERE ordernumber != parent_ordernumber
7366             ) AS aq
7367         )
7368         AND basketno IN (SELECT basketno FROM aqbasket WHERE closedate IS NOT NULL)
7369     });
7370     $dbh->do("UPDATE aqorders SET orderstatus='complete' WHERE quantity=quantityreceived");
7371     $dbh->do("UPDATE aqorders SET orderstatus='cancelled' WHERE datecancellationprinted IS NOT NULL");
7372     print "Upgrade to $DBversion done (Bug 5336: Add the new column aqorders.orderstatus)\n";
7373     SetVersion($DBversion);
7374 }
7375
7376 $DBversion = "3.13.00.033";
7377 if ( CheckVersion($DBversion) ) {
7378     $dbh->do(qq|
7379         DROP TABLE IF EXISTS subscription_frequencies
7380     |);
7381     $dbh->do(qq|
7382         CREATE TABLE subscription_frequencies (
7383             id INTEGER NOT NULL AUTO_INCREMENT,
7384             description TEXT NOT NULL,
7385             displayorder INT DEFAULT NULL,
7386             unit ENUM('day','week','month','year') DEFAULT NULL,
7387             unitsperissue INTEGER NOT NULL DEFAULT '1',
7388             issuesperunit INTEGER NOT NULL DEFAULT '1',
7389             PRIMARY KEY (id)
7390         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
7391     |);
7392
7393     $dbh->do(qq|
7394         DROP TABLE IF EXISTS subscription_numberpatterns
7395     |);
7396     $dbh->do(qq|
7397         CREATE TABLE subscription_numberpatterns (
7398             id INTEGER NOT NULL AUTO_INCREMENT,
7399             label VARCHAR(255) NOT NULL,
7400             displayorder INTEGER DEFAULT NULL,
7401             description TEXT NOT NULL,
7402             numberingmethod VARCHAR(255) NOT NULL,
7403             label1 VARCHAR(255) DEFAULT NULL,
7404             add1 INTEGER DEFAULT NULL,
7405             every1 INTEGER DEFAULT NULL,
7406             whenmorethan1 INTEGER DEFAULT NULL,
7407             setto1 INTEGER DEFAULT NULL,
7408             numbering1 VARCHAR(255) DEFAULT NULL,
7409             label2 VARCHAR(255) DEFAULT NULL,
7410             add2 INTEGER DEFAULT NULL,
7411             every2 INTEGER DEFAULT NULL,
7412             whenmorethan2 INTEGER DEFAULT NULL,
7413             setto2 INTEGER DEFAULT NULL,
7414             numbering2 VARCHAR(255) DEFAULT NULL,
7415             label3 VARCHAR(255) DEFAULT NULL,
7416             add3 INTEGER DEFAULT NULL,
7417             every3 INTEGER DEFAULT NULL,
7418             whenmorethan3 INTEGER DEFAULT NULL,
7419             setto3 INTEGER DEFAULT NULL,
7420             numbering3 VARCHAR(255) DEFAULT NULL,
7421             PRIMARY KEY (id)
7422         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
7423     |);
7424
7425     $dbh->do(qq|
7426         INSERT INTO subscription_frequencies (description, unit, unitsperissue, issuesperunit, displayorder)
7427         VALUES
7428             ('2/day', 'day', 1, 2, 1),
7429             ('1/day', 'day', 1, 1, 2),
7430             ('3/week', 'week', 1, 3, 3),
7431             ('1/week', 'week', 1, 1, 4),
7432             ('1/2 weeks', 'week', 2, 1, 5),
7433             ('1/3 weeks', 'week', 3, 1, 6),
7434             ('1/month', 'month', 1, 1, 7),
7435             ('1/2 months', 'month', 2, 1, 8),
7436             ('1/3 months', 'month', 3, 1, 9),
7437             ('2/year', 'month', 6, 1, 10),
7438             ('1/year', 'year', 1, 1, 11),
7439             ('1/2 year', 'year', 2, 1, 12),
7440             ('Irregular', NULL, 1, 1, 13)
7441     |);
7442
7443     # Used to link existing subscription to newly created frequencies
7444     my $frequencies_mapping = {     # keys are old frequency numbers, values are the new ones
7445         1 => 2,     # daily (n/week)
7446         2 => 4,     # 1/week
7447         3 => 5,     # 1/2 weeks
7448         4 => 6,     # 1/3 weeks
7449         5 => 7,     # 1/month
7450         6 => 8,     # 1/2 months (6/year)
7451         7 => 9,     # 1/3 months (1/quarter)
7452         8 => 9,    # 1/quarter (seasonal)
7453         9 => 10,    # 2/year
7454         10 => 11,   # 1/year
7455         11 => 12,   # 1/2 years
7456         12 => 1,    # 2/day
7457         16 => 13,   # Without periodicity
7458         32 => 13,   # Irregular
7459         48 => 13    # Unknown
7460     };
7461
7462     $dbh->do(qq|
7463         INSERT INTO subscription_numberpatterns
7464             (label, displayorder, description, numberingmethod,
7465             label1, add1, every1, whenmorethan1, setto1, numbering1,
7466             label2, add2, every2, whenmorethan2, setto2, numbering2,
7467             label3, add3, every3, whenmorethan3, setto3, numbering3)
7468         VALUES
7469             ('Number', 1, 'Simple Numbering method', 'No.{X}',
7470             'Number', 1, 1, 99999, 1, NULL,
7471             NULL, NULL, NULL, NULL, NULL, NULL,
7472             NULL, NULL, NULL, NULL, NULL, NULL),
7473
7474             ('Volume, Number, Issue', 2, 'Volume Number Issue 1', 'Vol.{X}, Number {Y}, Issue {Z}',
7475             'Volume', 1, 48, 99999, 1, NULL,
7476             'Number', 1, 4, 12, 1, NULL,
7477             'Issue', 1, 1, 4, 1, NULL),
7478
7479             ('Volume, Number', 3, 'Volume Number 1', 'Vol {X}, No {Y}',
7480             'Volume', 1, 12, 99999, 1, NULL,
7481             'Number', 1, 1, 12, 1, NULL,
7482             NULL, NULL, NULL, NULL, NULL, NULL),
7483
7484             ('Seasonal', 4, 'Season Year', '{X} {Y}',
7485             'Season', 1, 1, 3, 0, 'season',
7486             'Year', 1, 4, 99999, 1, NULL,
7487             NULL, NULL, NULL, NULL, NULL, NULL)
7488     |);
7489
7490     $dbh->do(qq|
7491         ALTER TABLE subscription
7492         MODIFY COLUMN numberpattern INTEGER DEFAULT NULL,
7493         MODIFY COLUMN periodicity INTEGER DEFAULT NULL
7494     |);
7495
7496     # Update existing subscriptions
7497
7498     my $query = qq|
7499         SELECT subscriptionid, periodicity, numberingmethod,
7500             add1, every1, whenmorethan1, setto1,
7501             add2, every2, whenmorethan2, setto2,
7502             add3, every3, whenmorethan3, setto3
7503         FROM subscription
7504         ORDER BY subscriptionid
7505     |;
7506     my $sth = $dbh->prepare($query);
7507     $sth->execute;
7508     my $insert_numberpatterns_sth = $dbh->prepare(qq|
7509         INSERT INTO subscription_numberpatterns
7510              (label, displayorder, description, numberingmethod,
7511             label1, add1, every1, whenmorethan1, setto1, numbering1,
7512             label2, add2, every2, whenmorethan2, setto2, numbering2,
7513             label3, add3, every3, whenmorethan3, setto3, numbering3)
7514         VALUES
7515             (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
7516     |);
7517     my $check_numberpatterns_sth = $dbh->prepare(qq|
7518         SELECT * FROM subscription_numberpatterns
7519         WHERE (add1 = ? OR (add1 IS NULL AND ? IS NULL)) AND (add2 = ? OR (add2 IS NULL AND ? IS NULL))
7520         AND (add3 = ? OR (add3 IS NULL AND ? IS NULL)) AND (every1 = ? OR (every1 IS NULL AND ? IS NULL))
7521         AND (every2 = ? OR (every2 IS NULL AND ? IS NULL)) AND (every3 = ? OR (every3 IS NULL AND ? IS NULL))
7522         AND (whenmorethan1 = ? OR (whenmorethan1 IS NULL AND ? IS NULL)) AND (whenmorethan2 = ? OR (whenmorethan2 IS NULL AND ? IS NULL))
7523         AND (whenmorethan3 = ? OR (whenmorethan3 IS NULL AND ? IS NULL)) AND (setto1 = ? OR (setto1 IS NULL AND ? IS NULL))
7524         AND (setto2 = ? OR (setto2 IS NULL AND ? IS NULL)) AND (setto3 = ? OR (setto3 IS NULL AND ? IS NULL))
7525         AND (numberingmethod = ? OR (numberingmethod IS NULL AND ? IS NULL))
7526         LIMIT 1
7527     |);
7528     my $update_subscription_sth = $dbh->prepare(qq|
7529         UPDATE subscription
7530         SET numberpattern = ?,
7531             periodicity = ?
7532         WHERE subscriptionid = ?
7533     |);
7534
7535     my $i = 1;
7536     while(my $sub = $sth->fetchrow_hashref) {
7537         $check_numberpatterns_sth->execute(
7538             $sub->{add1}, $sub->{add1}, $sub->{add2}, $sub->{add2}, $sub->{add3}, $sub->{add3},
7539             $sub->{every1}, $sub->{every1}, $sub->{every2}, $sub->{every2}, $sub->{every3}, $sub->{every3},
7540             $sub->{whenmorethan1}, $sub->{whenmorethan1}, $sub->{whenmorethan2}, $sub->{whenmorethan2},
7541             $sub->{whenmorethan3}, $sub->{whenmorethan3}, $sub->{setto1}, $sub->{setto1}, $sub->{setto2},
7542             $sub->{setto2}, $sub->{setto3}, $sub->{setto3}, $sub->{numberingmethod}, $sub->{numberingmethod}
7543         );
7544         my $p = $check_numberpatterns_sth->fetchrow_hashref;
7545         if (defined $p) {
7546             # Pattern already exists, link to it
7547             $update_subscription_sth->execute($p->{id},
7548                 $frequencies_mapping->{$sub->{periodicity}},
7549                 $sub->{subscriptionid});
7550         } else {
7551             # Create a new numbering pattern for this subscription
7552             my $ok = $insert_numberpatterns_sth->execute(
7553                 "Backup pattern $i", 4+$i, "Automatically created pattern by updatedatabase", $sub->{numberingmethod},
7554                 "X", $sub->{add1}, $sub->{every1}, $sub->{whenmorethan1}, $sub->{setto1}, undef,
7555                 "Y", $sub->{add2}, $sub->{every2}, $sub->{whenmorethan2}, $sub->{setto2}, undef,
7556                 "Z", $sub->{add3}, $sub->{every3}, $sub->{whenmorethan3}, $sub->{setto3}, undef
7557             );
7558             if($ok) {
7559                 my $id = $dbh->last_insert_id(undef, undef, 'subscription_numberpatterns', undef);
7560                 # Link to subscription_numberpatterns and subscription_frequencies
7561                 $update_subscription_sth->execute($id,
7562                     $frequencies_mapping->{$sub->{periodicity}},
7563                     $sub->{subscriptionid});
7564             }
7565             $i++;
7566         }
7567     }
7568
7569     # Remove now useless columns
7570     $dbh->do(qq|
7571         ALTER TABLE subscription
7572         DROP COLUMN numberingmethod,
7573         DROP COLUMN add1,
7574         DROP COLUMN every1,
7575         DROP COLUMN whenmorethan1,
7576         DROP COLUMN setto1,
7577         DROP COLUMN add2,
7578         DROP COLUMN every2,
7579         DROP COLUMN whenmorethan2,
7580         DROP COLUMN setto2,
7581         DROP COLUMN add3,
7582         DROP COLUMN every3,
7583         DROP COLUMN whenmorethan3,
7584         DROP COLUMN setto3,
7585         DROP COLUMN dow,
7586         DROP COLUMN issuesatonce,
7587         DROP COLUMN hemisphere,
7588         ADD COLUMN countissuesperunit INTEGER NOT NULL DEFAULT 1 AFTER periodicity,
7589         ADD COLUMN skip_serialseq BOOLEAN NOT NULL DEFAULT 0 AFTER irregularity,
7590         ADD COLUMN locale VARCHAR(80) DEFAULT NULL AFTER numberpattern,
7591         ADD CONSTRAINT subscription_ibfk_1 FOREIGN KEY (periodicity) REFERENCES subscription_frequencies (id) ON DELETE SET NULL ON UPDATE CASCADE,
7592         ADD CONSTRAINT subscription_ibfk_2 FOREIGN KEY (numberpattern) REFERENCES subscription_numberpatterns (id) ON DELETE SET NULL ON UPDATE CASCADE
7593     |);
7594
7595     # Set firstacquidate if not already set (firstacquidate is now mandatory)
7596     my $get_first_planneddate_sth = $dbh->prepare(qq|
7597         SELECT planneddate
7598         FROM serial
7599         WHERE subscriptionid = ?
7600         ORDER BY serialid
7601         LIMIT 1
7602     |);
7603     my $update_firstacquidate_sth = $dbh->prepare(qq|
7604         UPDATE subscription
7605         SET firstacquidate = ?
7606         WHERE subscriptionid = ?
7607     |);
7608     my $get_subscriptions_sth = $dbh->prepare(qq|
7609         SELECT subscriptionid, startdate
7610         FROM subscription
7611         WHERE firstacquidate IS NULL
7612           OR firstacquidate = '0000-00-00'
7613     |);
7614     $get_subscriptions_sth->execute;
7615     while ( my ($subscriptionid, $startdate) = $get_subscriptions_sth->fetchrow ) {
7616         # Try to get the planned date of the first serial
7617         $get_first_planneddate_sth->execute($subscriptionid);
7618         my ($first_planneddate) = $get_first_planneddate_sth->fetchrow;
7619         if ($first_planneddate and $first_planneddate =~ /^\d{4}-\d{2}-\d{2}$/) {
7620             $update_firstacquidate_sth->execute($first_planneddate, $subscriptionid);
7621         } else {
7622             # Defaults to subscription start date
7623             $update_firstacquidate_sth->execute($startdate, $subscriptionid);
7624         }
7625     }
7626
7627     print "Upgrade to $DBversion done (Bug 7688: add subscription_frequencies and subscription_numberpatterns tables)\n";
7628     SetVersion($DBversion);
7629 }
7630
7631 $DBversion = "3.13.00.034";
7632 if ( CheckVersion($DBversion) ) {
7633     $dbh->do("
7634         ALTER TABLE `import_batches`
7635         CHANGE `item_action` `item_action`
7636           ENUM( 'always_add', 'add_only_for_matches', 'add_only_for_new', 'ignore', 'replace' )
7637           NOT NULL DEFAULT 'always_add'
7638     ");
7639     print "Upgrade to $DBversion done (Bug 7131 - way to overlay items in in marc import)\n";
7640     SetVersion($DBversion);
7641 }
7642
7643 $DBversion ="3.13.00.035";
7644 if ( CheckVersion($DBversion) ) {
7645     $dbh->do(q{
7646 CREATE TABLE borrower_debarments (
7647   borrower_debarment_id int(11) NOT NULL AUTO_INCREMENT,
7648   borrowernumber int(11) NOT NULL,
7649   expiration date DEFAULT NULL,
7650   `type` enum('SUSPENSION','OVERDUES','MANUAL') NOT NULL DEFAULT 'MANUAL',
7651   `comment` text,
7652   manager_id int(11) DEFAULT NULL,
7653   created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
7654   updated timestamp NULL DEFAULT NULL,
7655   PRIMARY KEY (borrower_debarment_id),
7656   KEY borrowernumber (borrowernumber) ,
7657   CONSTRAINT `borrower_debarments_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
7658     ON DELETE CASCADE ON UPDATE CASCADE
7659 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7660     });
7661
7662     # debarments with end date
7663     $dbh->do(q{
7664 INSERT INTO borrower_debarments ( borrowernumber, expiration, comment ) SELECT borrowernumber, debarred, debarredcomment FROM borrowers WHERE debarred IS NOT NULL AND debarred <> '9999-12-31'
7665     });
7666     # debarments with no end date
7667     $dbh->do(q{
7668 INSERT INTO borrower_debarments ( borrowernumber, comment ) SELECT borrowernumber, debarredcomment FROM borrowers WHERE debarred = '9999-12-31'
7669     });
7670
7671     $dbh->do(q{
7672 INSERT IGNORE INTO systempreferences (variable,value,explanation,type) VALUES
7673 ('AutoRemoveOverduesRestrictions','0','Defines whether an OVERDUES debarment should be lifted automatically if all overdue items are returned by the patron.','YesNo')
7674     });
7675
7676     print "Upgrade to $DBversion done (Bug 2720 - Overdues which debar automatically should undebar automatically when returned)\n";
7677     SetVersion($DBversion);
7678 }
7679
7680 $DBversion = "3.13.00.036";
7681 if ( CheckVersion($DBversion) ) {
7682     $dbh->do(qq{
7683         INSERT INTO systempreferences (variable, value, explanation, options, type)
7684         VALUES ('StaffDetailItemSelection', '1', 'Enable item selection in record detail page', NULL, 'YesNo')
7685     });
7686     print "Upgrade to $DBversion done (Add system preference StaffDetailItemSelection)\n";
7687     SetVersion($DBversion);
7688 }
7689
7690 $DBversion = "3.13.00.037";
7691 if ( CheckVersion($DBversion) ) {
7692     #add phone if it is not there already (explains the ignore option)
7693     $dbh->do("
7694 INSERT IGNORE INTO message_transport_types (message_transport_type) values ('phone');
7695     ");
7696     print "Upgrade to $DBversion done (Bug 10572: Add phone to message_transport_types table for new installs)\n";
7697     SetVersion($DBversion);
7698 }
7699
7700 $DBversion = "3.13.00.038";
7701 if ( CheckVersion($DBversion) ) {
7702     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES(15, 'superserials', 'Manage subscriptions from any branch (only applies when IndependentBranches is used)')");
7703     print "Upgrade to $DBversion done (Bug 8435: Add superserials permission)\n";
7704     SetVersion($DBversion);
7705 }
7706
7707 $DBversion = "3.13.00.039";
7708 if ( CheckVersion($DBversion) ) {
7709     $dbh->do("
7710         ALTER TABLE aqbasket ADD branch varchar(10) default NULL
7711     ");
7712     $dbh->do("
7713         ALTER TABLE aqbasket
7714         ADD CONSTRAINT aqbasket_ibfk_4 FOREIGN KEY (branch)
7715             REFERENCES branches (branchcode)
7716             ON UPDATE CASCADE ON DELETE SET NULL
7717     ");
7718     $dbh->do("
7719         DROP TABLE IF EXISTS aqbasketusers
7720     ");
7721     $dbh->do("
7722         CREATE TABLE aqbasketusers (
7723             basketno int(11) NOT NULL,
7724             borrowernumber int(11) NOT NULL,
7725             PRIMARY KEY (basketno,borrowernumber),
7726             CONSTRAINT aqbasketusers_ibfk_1 FOREIGN KEY (basketno) REFERENCES aqbasket (basketno) ON DELETE CASCADE ON UPDATE CASCADE,
7727             CONSTRAINT aqbasketusers_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
7728         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7729     ");
7730     $dbh->do("
7731         INSERT INTO permissions (module_bit, code, description)
7732         VALUES (11, 'order_manage_all', 'Manage all orders and baskets, regardless of restrictions on them')
7733     ");
7734
7735     print "Upgrade to $DBversion done (Add branch and users list to baskets. "
7736         . "New permission order_manage_all)\n";
7737     SetVersion($DBversion);
7738 }
7739
7740 $DBversion = "3.13.00.040";
7741 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
7742     $dbh->do("CREATE TABLE IF NOT EXISTS marc_modification_templates (
7743               template_id int(11) NOT NULL auto_increment,
7744               name text NOT NULL,
7745               PRIMARY KEY  (template_id)
7746               ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;"
7747     );
7748
7749     $dbh->do("
7750       CREATE TABLE IF NOT EXISTS marc_modification_template_actions (
7751       mmta_id int(11) NOT NULL auto_increment,
7752       template_id int(11) NOT NULL,
7753       ordering int(3) NOT NULL,
7754       action enum('delete_field','update_field','move_field','copy_field') NOT NULL,
7755       field_number smallint(6) NOT NULL default '0',
7756       from_field varchar(3) NOT NULL,
7757       from_subfield varchar(1) NULL,
7758       field_value varchar(100) default NULL,
7759       to_field varchar(3) default NULL,
7760       to_subfield varchar(1) default NULL,
7761       to_regex_search text,
7762       to_regex_replace text,
7763       to_regex_modifiers varchar(8) default '',
7764       conditional enum('if','unless') default NULL,
7765       conditional_field varchar(3) default NULL,
7766       conditional_subfield varchar(1) default NULL,
7767       conditional_comparison enum('exists','not_exists','equals','not_equals') default NULL,
7768       conditional_value text,
7769       conditional_regex tinyint(1) NOT NULL default '0',
7770       description text,
7771       PRIMARY KEY  (mmta_id),
7772       CONSTRAINT `mmta_ibfk_1` FOREIGN KEY (`template_id`) REFERENCES `marc_modification_templates` (`template_id`) ON DELETE CASCADE ON UPDATE CASCADE
7773       ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7774     ");
7775
7776     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('13', 'marc_modification_templates', 'Manage marc modification templates')");
7777
7778     print "Upgrade to $DBversion done ( Bug 8015: Added tables for MARC Modification Framework )\n";
7779     SetVersion($DBversion);
7780 }
7781
7782 $DBversion = "3.13.00.041";
7783 if(CheckVersion($DBversion)) {
7784     $dbh->do(q{
7785         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');
7786     });
7787     print "Upgrade to $DBversion done (Bug 10986: Added AcqItemSetSubfieldsWhenReceived syspref)\n";
7788     SetVersion($DBversion);
7789 }
7790
7791 $DBversion = "3.13.00.042";
7792 if(CheckVersion($DBversion)) {
7793     print "Upgrade to $DBversion done (Koha 3.14 beta)\n";
7794     SetVersion($DBversion);
7795 }
7796
7797 $DBversion = "3.13.00.043";
7798 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
7799     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('SearchEngine','Zebra','Solr|Zebra','Search Engine','Choice')");
7800     print "Upgrade to $DBversion done (Bug 11196: Add system preference SearchEngine if missing )\n";
7801     SetVersion($DBversion);
7802 }
7803
7804 $DBversion = "3.14.00.000";
7805 if ( CheckVersion($DBversion) ) {
7806     print "Upgrade to $DBversion done (3.14.0 release)\n";
7807     SetVersion ($DBversion);
7808 }
7809
7810 $DBversion = '3.15.00.000';
7811 if ( CheckVersion($DBversion) ) {
7812     print "Upgrade to $DBversion done (the road goes ever on)\n";
7813     SetVersion ($DBversion);
7814 }
7815
7816 $DBversion = "3.15.00.001";
7817 if ( CheckVersion($DBversion) ) {
7818     $dbh->do("UPDATE systempreferences SET value='clear' where variable = 'CircAutoPrintQuickSlip' and value = '0'");
7819     $dbh->do("UPDATE systempreferences SET value='qslip' where variable = 'CircAutoPrintQuickSlip' and value = '1'");
7820     $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'");
7821     print "Upgrade to $DBversion done (Bug 11040: Add option to print full slip when checking out a null barcode)\n";
7822     SetVersion($DBversion);
7823 }
7824
7825 $DBversion = "3.15.00.002";
7826 if(CheckVersion($DBversion)) {
7827     $dbh->do("ALTER TABLE deleteditems MODIFY materials text;");
7828     print "Upgrade to $DBversion done (Bug 11275: alter deleteditems.materials from varchar(10) to text)\n";
7829     SetVersion($DBversion);
7830 }
7831
7832 $DBversion = "3.15.00.003";
7833 if ( CheckVersion($DBversion) ) {
7834     $dbh->do(q{
7835         UPDATE accountlines
7836         SET description = ''
7837         WHERE description IN (
7838             ' New Card',
7839             ' Fine',
7840             ' Sundry',
7841             'Writeoff',
7842             ' Account Management fee',
7843             'Payment,thanks', 'Payment,thanks - ',
7844             ' Lost Item'
7845         )
7846     });
7847     print "Upgrade to $DBversion done (Bug 2546: Update fine descriptions)\n";
7848     SetVersion($DBversion);
7849 }
7850
7851 $DBversion = "3.15.00.004";
7852 if ( CheckVersion($DBversion) ) {
7853     if ( C4::Context->preference("marcflavour") eq 'MARC21' ) {
7854         $dbh->do(qq{
7855             INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian, libopac, repeatable, mandatory,
7856             kohafield, tab, authorised_value, authtypecode, value_builder, isurl, hidden, frameworkcode, seealso, link,
7857             defaultvalue) VALUES
7858             ('015', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7859             ('020', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7860             ('024', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7861             ('027', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7862             ('800', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7863             ('810', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7864             ('811', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7865             ('830', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL);
7866         });
7867         $dbh->do(qq{
7868             INSERT IGNORE INTO auth_subfield_structure (authtypecode, tagfield, tagsubfield, liblibrarian, libopac, repeatable,
7869             mandatory, tab, authorised_value, value_builder, seealso, isurl, hidden, linkid, kohafield, frameworkcode) VALUES
7870             ('', '020', 'q', 'Qualifying information', 'Qualifying information', 1, 0, 0, NULL, NULL, NULL, 0, 0, '', '', ''),
7871             ('', '024', 'q', 'Qualifying information', 'Qualifying information', 1, 0, 0, NULL, NULL, NULL, 0, 0, '', '', '');
7872         });
7873     }
7874     print "Upgrade to $DBversion done (Bug 10970 - Update MARC21 frameworks to Update Nr. 17 - DB update)\n";
7875     SetVersion($DBversion);
7876 }
7877
7878 $DBversion = "3.15.00.005";
7879 if ( CheckVersion($DBversion) ) {
7880    $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('AcquisitionDetails', '1', '', 'Hide/Show acquisition details on the biblio detail page.', 'YesNo');");
7881    print "Upgrade to $DBversion done (Bug 8230: Add AcquisitionDetails system preference)\n";
7882    SetVersion ($DBversion);
7883 }
7884
7885 $DBversion = "3.15.00.006";
7886 if(CheckVersion($DBversion)) {
7887     $dbh->do(q{
7888         ALTER TABLE `borrowers`
7889         ADD KEY `surname_idx` (`surname`(255)),
7890         ADD KEY `firstname_idx` (`firstname`(255)),
7891         ADD KEY `othernames_idx` (`othernames`(255))
7892     });
7893     print "Upgrade to $DBversion done (Bug 11249 - Add DB indexes on borrower names)\n";
7894     SetVersion($DBversion);
7895 }
7896
7897 $DBversion = "3.15.00.007";
7898 if ( CheckVersion($DBversion) ) {
7899    $dbh->do("ALTER TABLE items ADD itemlost_on DATETIME NULL AFTER itemlost");
7900    $dbh->do("ALTER TABLE items ADD withdrawn_on DATETIME NULL AFTER withdrawn");
7901    $dbh->do("ALTER TABLE deleteditems ADD itemlost_on DATETIME NULL AFTER itemlost");
7902    $dbh->do("ALTER TABLE deleteditems ADD withdrawn_on DATETIME NULL AFTER withdrawn");
7903    print "Upgrade to $DBversion done (Bug 9673 - Track when items are marked as lost or withdrawn)\n";
7904    SetVersion ($DBversion);
7905 }
7906
7907 $DBversion = "3.15.00.008";
7908 if ( CheckVersion($DBversion) ) {
7909     $dbh->do(q{
7910         ALTER TABLE collections_tracking CHANGE ctId collections_tracking_id integer(11) NOT NULL auto_increment;
7911     });
7912     print "Upgrade to $DBversion done (Bug 11384) - change name of collections_tracker.ctId column)\n";
7913    SetVersion ($DBversion);
7914 }
7915
7916 $DBversion = "3.15.00.009";
7917 if ( CheckVersion($DBversion) ) {
7918     $dbh->do(q{
7919         ALTER TABLE suggestions MODIFY suggesteddate DATE NOT NULL
7920     });
7921     print "Upgrade to $DBversion done (Bug 11391) - drop default value on suggestions.suggesteddate column)\n";
7922    SetVersion ($DBversion);
7923 }
7924
7925 $DBversion = "3.15.00.010";
7926 if(CheckVersion($DBversion)) {
7927     $dbh->do("ALTER TABLE deleteditems DROP COLUMN marc");
7928     print "Upgrade to $DBversion done (Bug 6331: remove obsolete column in deleteditems.marc)\n";
7929     SetVersion ($DBversion);
7930 }
7931
7932 $DBversion = "3.15.00.011";
7933 if(CheckVersion($DBversion)) {
7934     $dbh->do("UPDATE marc_subfield_structure SET maxlength=9999 WHERE maxlength IS NULL OR maxlength=0;");
7935     print "Upgrade to $DBversion done (Bug 8018: set 9999 as default max length for subfields)\n";
7936     SetVersion ($DBversion);
7937 }
7938
7939 $DBversion = "3.15.00.012";
7940 if ( CheckVersion($DBversion) ) {
7941     $dbh->do(q{
7942         INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'force_checkout', 'Force checkout if a limitation exists')
7943     });
7944     $dbh->do(q{
7945         INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'manage_restrictions', 'Manage restrictions for accounts')
7946     });
7947     $dbh->do(q{
7948         INSERT INTO user_permissions (borrowernumber, module_bit, code)
7949             SELECT user_permissions.borrowernumber, 1, 'force_checkout'
7950             FROM user_permissions
7951             LEFT JOIN borrowers USING(borrowernumber)
7952             WHERE borrowers.flags & (1 << 1)
7953     });
7954     $dbh->do(q{
7955         INSERT INTO user_permissions (borrowernumber, module_bit, code)
7956             SELECT user_permissions.borrowernumber, 1, 'manage_restrictions'
7957             FROM user_permissions
7958             LEFT JOIN borrowers USING(borrowernumber)
7959             WHERE borrowers.flags & (1 << 1)
7960     });
7961
7962     print "Upgrade to $DBversion done (Bug 10863 - Add permissions force_checkout and manage_restrictions)\n";
7963     SetVersion($DBversion);
7964 }
7965
7966 $DBversion = "3.15.00.013";
7967 if(CheckVersion($DBversion)) {
7968     $dbh->do(q{
7969         UPDATE systempreferences
7970         SET explanation = 'Upon receiving items, update their subfields if they were created when placing an order (e.g. o=5|a="foo bar")'
7971         WHERE variable = "AcqItemSetSubfieldsWhenReceived"
7972     });
7973
7974     $dbh->do(q{
7975         UPDATE systempreferences
7976         SET value = ''
7977         WHERE variable = "AcqItemSetSubfieldsWhenReceived"
7978             AND value = "0"
7979     });
7980     print "Upgrade to $DBversion done (Bug 11237: Update explanation and default value for AcqItemSetSubfieldsWhenReceived syspref)\n";
7981     SetVersion($DBversion);
7982 }
7983
7984 $DBversion = "3.15.00.014";
7985 if (CheckVersion($DBversion)) {
7986     $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');");
7987     print "Upgrade to $DBversion done (Bug 11415: add system preference for automatic self checkout receipt printing)\n";
7988     SetVersion($DBversion);
7989 }
7990
7991 $DBversion = "3.15.00.015";
7992 if (CheckVersion($DBversion)) {
7993     $dbh->do("INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
7994         ('OpacSuggestionManagedBy',1,'','Show the name of the staff member who managed a suggestion in OPAC','YesNo');");
7995     print "Upgrade to $DBversion done (Bug 10907: Add OpacSuggestionManagedBy system preference)\n";
7996     SetVersion($DBversion);
7997 }
7998
7999 $DBversion = "3.15.00.016";
8000 if (CheckVersion($DBversion)) {
8001     $dbh->do("ALTER TABLE biblioitems CHANGE url url TEXT NULL DEFAULT NULL");
8002     $dbh->do("ALTER TABLE deletedbiblioitems CHANGE url url TEXT NULL DEFAULT NULL");
8003     print "Upgrade to $DBversion done (Bug 11268 - Biblioitems URL field is too small for some URLs)\n";
8004     SetVersion($DBversion);
8005 }
8006
8007 $DBversion = "3.15.00.017";
8008 if(CheckVersion($DBversion)) {
8009     $dbh->do(q{
8010         UPDATE systempreferences
8011         SET explanation = 'Define the contents of UNIMARC authority control field 100 position 08-35'
8012         WHERE variable = "UNIMARCAuthorityField100"
8013     });
8014     $dbh->do(q{
8015         UPDATE systempreferences
8016         SET explanation = 'Define the contents of MARC21 authority control field 008 position 06-39'
8017         WHERE variable = "MARCAuthorityControlField008"
8018     });
8019     $dbh->do(q{
8020         UPDATE systempreferences
8021         SET explanation = 'Define MARC Organization Code for MARC21 records - http://www.loc.gov/marc/organizations/orgshome.html'
8022         WHERE variable = "MARCOrgCode"
8023     });
8024     print "Upgrade to $DBversion done (Bug 11611 - fix possible confusion between UNIMARC and MARC21 in some sysprefs)\n";
8025     SetVersion($DBversion);
8026 }
8027
8028 $DBversion = "3.15.00.018";
8029 if ( CheckVersion($DBversion) ) {
8030     $dbh->{AutoCommit} = 0;
8031     $dbh->{RaiseError} = 1;
8032
8033     eval {
8034         $dbh->selectcol_arrayref(q|SELECT COUNT(*) FROM roadtype|);
8035     };
8036     unless ( $@ ) {
8037         my $av_added = $dbh->do(q|
8038             INSERT INTO authorised_values(category, authorised_value, lib, lib_opac)
8039                 SELECT 'ROADTYPE', roadtypeid, road_type, road_type
8040                 FROM roadtype;
8041         |);
8042
8043         my $rt_deleted = $dbh->do(q|
8044             DELETE FROM roadtype
8045         |);
8046
8047         if ( $av_added == $rt_deleted or $rt_deleted eq "0E0" ) {
8048             $dbh->do(q|
8049                 DROP TABLE roadtype;
8050             |);
8051             $dbh->commit;
8052             print "Upgrade to $DBversion done (Bug 7372: Move road types from the roadtype table to the ROADTYPE authorised values)\n";
8053             SetVersion($DBversion);
8054         } else {
8055             print "Upgrade to $DBversion failed (Bug 7372: Move road types from the roadtype table to the ROADTYPE authorised values.\nTransaction aborted because $@\n)";
8056             $dbh->rollback;
8057         }
8058     }
8059     $dbh->{AutoCommit} = 1;
8060     $dbh->{RaiseError} = 0;
8061 }
8062
8063 $DBversion = "3.15.00.019";
8064 if ( CheckVersion($DBversion) ) {
8065     $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')");
8066     print "Upgrade to $DBversion done (Bug 11256: Add system preference OpacMaxItemsToDisplay)\n";
8067     SetVersion($DBversion);
8068 }
8069
8070 $DBversion = "3.15.00.020";
8071 if ( CheckVersion($DBversion) ) {
8072     $dbh->do(q|
8073         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')
8074     |);
8075     print "Upgrade to $DBversion done (Bug 11343: Add system preference MaxItemsForBatch )\n";
8076     SetVersion($DBversion);
8077 }
8078
8079 $DBversion = "3.15.00.021";
8080 if(CheckVersion($DBversion)) {
8081     $dbh->do(q{
8082         ALTER TABLE `action_logs`
8083             DROP KEY timestamp,
8084             ADD KEY `timestamp_idx` (`timestamp`),
8085             ADD KEY `user_idx` (`user`),
8086             ADD KEY `module_idx` (`module`(255)),
8087             ADD KEY `action_idx` (`action`(255)),
8088             ADD KEY `object_idx` (`object`),
8089             ADD KEY `info_idx` (`info`(255))
8090     });
8091     print "Upgrade to $DBversion done (Bug 3445: Add indexes to action_logs table)\n";
8092     SetVersion($DBversion);
8093 }
8094
8095 $DBversion = "3.15.00.022";
8096 if (CheckVersion($DBversion)) {
8097     $dbh->do(q|
8098         DELETE FROM systempreferences WHERE variable= "memberofinstitution"
8099     |);
8100     print "Upgrade to $DBversion done (Bug 11751: Remove memberofinstitytion system preference)\n";
8101     SetVersion($DBversion);
8102 }
8103
8104 $DBversion = "3.15.00.023";
8105 if ( CheckVersion($DBversion) ) {
8106    $dbh->do("
8107        INSERT INTO systempreferences (variable,value,options,explanation,type)
8108        VALUES('CardnumberLength', '', '', 'Set a length for card numbers.', 'Free');
8109     ");
8110    print "Upgrade to $DBversion done (Bug 10861: Add CardnumberLength syspref)\n";
8111    SetVersion ($DBversion);
8112 }
8113
8114 $DBversion = "3.15.00.024";
8115 if ( CheckVersion($DBversion) ) {
8116     $dbh->do(q{
8117         DELETE FROM systempreferences WHERE variable = 'NoZebraIndexes'
8118     });
8119     print "Upgrade to $DBversion done (Bug 10012 - remove last vestiges of NoZebra)\n";
8120     SetVersion($DBversion);
8121 }
8122
8123 $DBversion = "3.15.00.025";
8124 if ( CheckVersion($DBversion) ) {
8125     $dbh->do(q{
8126         DROP TABLE aqorderdelivery;
8127     });
8128     print "Upgrade to $DBversion done (Bug 11928 - remove unused table)\n";
8129     SetVersion($DBversion);
8130 }
8131
8132 $DBversion = "3.15.00.026";
8133 if ( CheckVersion($DBversion) ) {
8134     $dbh->do(q{
8135         UPDATE language_descriptions SET description = 'Հայերեն' WHERE subtag = 'hy' AND lang = 'hy';
8136     });
8137     print "Upgrade to $DBversion done (Bug 11973 - Fix Armenian language description)\n";
8138     SetVersion($DBversion);
8139 }
8140
8141 $DBversion = "3.15.00.027";
8142 if (CheckVersion($DBversion)) {
8143     $dbh->do(q{
8144         ALTER TABLE opac_news ADD branchcode varchar(10) DEFAULT NULL
8145                                   AFTER idnew,
8146                               ADD CONSTRAINT opac_news_branchcode_ibfk
8147                                   FOREIGN KEY (branchcode)
8148                                   REFERENCES branches (branchcode)
8149                                   ON DELETE CASCADE ON UPDATE CASCADE;
8150     });
8151     print "Upgrade to $DBversion done (Bug 7567: Add branchcode to opac_news)\n";
8152     SetVersion($DBversion);
8153 }
8154
8155 $DBversion = "3.15.00.028";
8156 if(CheckVersion($DBversion)) {
8157     $dbh->do(q{
8158         ALTER TABLE issuingrules ADD norenewalbefore int(4) default NULL AFTER renewalperiod
8159     });
8160     print "Upgrade to $DBversion done (Bug 7413: Allow OPAC renewal x days before due date)\n";
8161     SetVersion($DBversion);
8162 }
8163
8164 $DBversion = "3.15.00.029";
8165 if ( CheckVersion($DBversion) ) {
8166     $dbh->do(q{
8167         UPDATE borrower_debarments SET expiration = NULL WHERE expiration = '9999-12-31'
8168     });
8169     print "Upgrade to $DBversion done (Bug 11846 - correct borrower_debarments with expiration 9999-12-31)\n";
8170     SetVersion($DBversion);
8171 }
8172
8173 $DBversion = "3.15.00.030";
8174 if(CheckVersion($DBversion)) {
8175     $dbh->do(q|
8176         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')
8177     |);
8178     print "Upgrade to $DBversion done (Bug 12052: Add OPACMySummaryNote syspref)\n";
8179     SetVersion($DBversion);
8180 }
8181
8182 $DBversion = "3.15.00.031";
8183 if ( CheckVersion($DBversion) ) {
8184    $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('10', 'writeoff', 'Write off fines and fees')");
8185    $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('10', 'remaining_permissions', 'Remaining permissions for managing fines and fees')");
8186    print "Upgrade to $DBversion done (Bug 9448 - Add separate permission for writing off fees)\n";
8187    SetVersion ($DBversion);
8188 }
8189
8190 $DBversion = "3.15.00.032";
8191 if ( CheckVersion($DBversion) ) {
8192     $dbh->do("ALTER TABLE aqorders CHANGE notes order_internalnote MEDIUMTEXT;");
8193     $dbh->do("ALTER TABLE aqorders ADD COLUMN order_vendornote MEDIUMTEXT AFTER order_internalnote;");
8194     print "Upgrade to $DBversion done (Bug 9416 - In each order, add a new note made for the vendor)\n";
8195    SetVersion ($DBversion);
8196 }
8197
8198 $DBversion = "3.15.00.033";
8199 if ( CheckVersion($DBversion) ) {
8200     $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')");
8201     print "Upgrade to $DBversion done (Bug 10951: Add NoLoginInstructions pref)\n";
8202     SetVersion($DBversion);
8203 }
8204
8205 $DBversion = "3.15.00.034";
8206 if ( CheckVersion($DBversion) ) {
8207     $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')");
8208     print "Upgrade to $DBversion done (Bug 10986: system preferences to limit languages in advanced search )\n";
8209     SetVersion ($DBversion);
8210 }
8211
8212 $DBversion = "3.15.00.035";
8213 if ( CheckVersion($DBversion) ) {
8214     #insert a notice for sharing a list and accepting a share
8215     $dbh->do("
8216 INSERT INTO letter (module, code, branchcode, name, is_html, title, content)
8217 VALUES ( 'members', 'SHARE_INVITE', '', 'Invitation for sharing a list', '0', 'Share list <<listname>>', 'Dear patron,
8218
8219 One of our patrons, <<borrowers.firstname>> <<borrowers.surname>>, invites you to share a list <<listname>> in our library catalog.
8220
8221 To access this shared list, please click on the following URL or copy-and-paste it into your browser address bar.
8222
8223 <<shareurl>>
8224
8225 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.
8226
8227 Thank you.
8228
8229 Your library.'
8230     )");
8231     $dbh->do("
8232 INSERT INTO letter (module, code, branchcode, name, is_html, title, content)
8233 VALUES ( 'members', 'SHARE_ACCEPT', '', 'Notification about an accepted share', '0', 'Share on list <<listname>> accepted', 'Dear patron,
8234
8235 We want to inform you that <<borrowers.firstname>> <<borrowers.surname>> accepted your invitation to share your list <<listname>> in our library catalog.
8236
8237 Thank you.
8238
8239 Your library.'
8240     )");
8241     print "Upgrade to $DBversion done (Bug 9032: Share a list)\n";
8242     SetVersion($DBversion);
8243 }
8244
8245 $DBversion = "3.15.00.036";
8246 if ( CheckVersion($DBversion) ) {
8247     $dbh->do(q{
8248         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
8249         VALUES('AllowMultipleIssuesOnABiblio',1,'Allow/Don\'t allow patrons to check out multiple items from one biblio','','YesNo')
8250     });
8251
8252     print "Upgrade to $DBversion done (Bug 10859 - Add system preference AllowMultipleIssuesOnABiblio)\n";
8253     SetVersion($DBversion);
8254 }
8255
8256 $DBversion = "3.15.00.037";
8257 if(CheckVersion($DBversion)) {
8258     $dbh->do(q{
8259         ALTER TABLE itemtypes ADD sip_media_type VARCHAR( 3 ) DEFAULT NULL AFTER checkinmsgtype
8260     });
8261     $dbh->do(q{
8262         INSERT INTO authorised_values (category, authorised_value, lib) VALUES
8263          ('SIP_MEDIA_TYPE', '000', 'Other'),
8264          ('SIP_MEDIA_TYPE', '001', 'Book'),
8265          ('SIP_MEDIA_TYPE', '002', 'Magazine'),
8266          ('SIP_MEDIA_TYPE', '003', 'Bound journal'),
8267          ('SIP_MEDIA_TYPE', '004', 'Audio tape'),
8268          ('SIP_MEDIA_TYPE', '005', 'Video tape'),
8269          ('SIP_MEDIA_TYPE', '006', 'CD/CDROM'),
8270          ('SIP_MEDIA_TYPE', '007', 'Diskette'),
8271          ('SIP_MEDIA_TYPE', '008', 'Book with diskette'),
8272          ('SIP_MEDIA_TYPE', '009', 'Book with CD'),
8273          ('SIP_MEDIA_TYPE', '010', 'Book with audio tape')
8274     });
8275     print "Upgrade to $DBversion done (Bug 11351 - Add support for SIP2 media type)\n";
8276     SetVersion($DBversion);
8277 }
8278
8279 $DBversion = '3.15.00.038';
8280 if ( CheckVersion($DBversion) ) {
8281     $dbh->do(q{
8282         INSERT INTO  systempreferences (
8283             variable,
8284             value,
8285             options,
8286             explanation,
8287             type
8288             )
8289         VALUES (
8290             'DisplayLibraryFacets',  'holding',  'home|holding|both',  'Defines which library facets to display.',  'Choice'
8291         );
8292     });
8293     print "Upgrade to $DBversion done (Bug 11334 - Add facet for home library)\n";
8294     SetVersion ($DBversion);
8295 }
8296
8297 $DBversion = "3.15.00.039";
8298 if ( CheckVersion($DBversion) ) {
8299
8300     $dbh->do( q{
8301         ALTER TABLE letter ADD COLUMN message_transport_type VARCHAR(20) NOT NULL DEFAULT 'email' AFTER content
8302     } );
8303
8304     $dbh->do( q{
8305         ALTER TABLE letter ADD CONSTRAINT message_transport_type_fk FOREIGN KEY (message_transport_type) REFERENCES message_transport_types(message_transport_type);
8306     } );
8307
8308     $dbh->do( q{
8309         ALTER TABLE letter DROP PRIMARY KEY, ADD PRIMARY KEY (`module`,`code`,`branchcode`, message_transport_type);
8310     } );
8311
8312     $dbh->do( q{
8313         CREATE TABLE overduerules_transport_types(
8314             id INT(11) NOT NULL AUTO_INCREMENT,
8315             branchcode varchar(10) NOT NULL DEFAULT '',
8316             categorycode VARCHAR(10) NOT NULL DEFAULT '',
8317             letternumber INT(1) NOT NULL DEFAULT 1,
8318             message_transport_type VARCHAR(20) NOT NULL DEFAULT 'email',
8319             PRIMARY KEY (id),
8320             CONSTRAINT overduerules_fk FOREIGN KEY (branchcode, categorycode) REFERENCES overduerules (branchcode, categorycode) ON DELETE CASCADE ON UPDATE CASCADE,
8321             CONSTRAINT mtt_fk FOREIGN KEY (message_transport_type) REFERENCES message_transport_types (message_transport_type) ON DELETE CASCADE ON UPDATE CASCADE
8322         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
8323     } );
8324
8325     my $sth = $dbh->prepare( q{
8326         SELECT * FROM overduerules;
8327     } );
8328
8329     $sth->execute;
8330     my $sth_insert_mtt = $dbh->prepare( q{
8331         INSERT INTO overduerules_transport_types (branchcode, categorycode, letternumber, message_transport_type) VALUES ( ?, ?, ?, ? )
8332     } );
8333     while ( my $row = $sth->fetchrow_hashref ) {
8334         my $branchcode = $row->{branchcode};
8335         my $categorycode = $row->{categorycode};
8336         for my $letternumber ( 1 .. 3 ) {
8337             next unless $row->{"letter$letternumber"};
8338             $sth_insert_mtt->execute(
8339                 $branchcode, $categorycode, $letternumber, 'email'
8340             );
8341         }
8342     }
8343
8344     print "Upgrade done (Bug 9016: Adds multi transport types management for notices)\n";
8345     SetVersion($DBversion);
8346 }
8347
8348 $DBversion = "3.15.00.040";
8349 if ( CheckVersion($DBversion) ) {
8350     $dbh->do(q|
8351         UPDATE message_transports SET letter_code='HOLD' WHERE letter_code='HOLD_PHONE' OR letter_code='HOLD_PRINT'
8352     |);
8353     $dbh->do(q|
8354         UPDATE letter SET code='HOLD', message_transport_type='print' WHERE code='HOLD_PRINT'
8355     |);
8356     $dbh->do(q|
8357         UPDATE letter SET code='HOLD', message_transport_type='phone' WHERE code='HOLD_PHONE'
8358     |);
8359     print "Upgrade to $DBversion done (Bug 10845: Multi transport types for holds)\n";
8360     SetVersion($DBversion);
8361 }
8362
8363 $DBversion = "3.15.00.041";
8364 if ( CheckVersion($DBversion) ) {
8365     my $name = $dbh->selectcol_arrayref(q|
8366         SELECT name FROM letter WHERE code="HOLD"
8367     |);
8368     $name = $name->[0];
8369     $dbh->do(q|
8370         UPDATE letter
8371         SET code="HOLD",
8372             message_transport_type="phone",
8373             name= ?
8374         WHERE code="HOLD_PHONE"
8375     |, {}, $name);
8376
8377     $dbh->do(q|
8378         UPDATE letter
8379         SET code="PREDUE",
8380             message_transport_type="phone",
8381             name= ?
8382         WHERE code="PREDUE_PHONE"
8383     |, {}, $name);
8384
8385     $dbh->do(q|
8386         UPDATE letter
8387         SET code="OVERDUE",
8388             message_transport_type="phone",
8389             name= ?
8390         WHERE code="OVERDUE_PHONE"
8391     |, {}, $name);
8392
8393     print "Upgrade to $DBversion done (Bug 11867: Update letters *_PHONE)\n";
8394     SetVersion($DBversion);
8395 }
8396
8397 $DBversion = "3.15.00.042";
8398 if ( CheckVersion($DBversion) ) {
8399     $dbh->do(q{
8400         INSERT INTO systempreferences
8401             (variable,value,explanation,options,type)
8402         VALUES
8403             ('SpecifyReturnDate',0,'Define whether to display \"Specify Return Date\" form in Circulation','','YesNo')
8404     });
8405     print "Upgrade to $DBversion done (Bug 10694 - Allow arbitrary backdating of returns)\n";
8406     SetVersion($DBversion);
8407 }
8408
8409 $DBversion = "3.15.00.043";
8410 if ( CheckVersion($DBversion) ) {
8411     $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')");
8412    print "Upgrade to $DBversion done (Bug 7180: Added MarcFieldsToOrder syspref)\n";
8413    SetVersion ($DBversion);
8414 }
8415
8416 $DBversion = "3.15.00.044";
8417 if ( CheckVersion($DBversion) ) {
8418     $dbh->do("ALTER TABLE currency ADD isocode VARCHAR(5) default NULL AFTER symbol;");
8419     print "Upgrade to $DBversion done (Added isocode to the currency table)\n";
8420     SetVersion($DBversion);
8421 }
8422
8423 $DBversion = "3.15.00.045";
8424 if ( CheckVersion($DBversion) ) {
8425     $dbh->do("
8426         INSERT INTO systempreferences (variable,value,explanation,options,type)
8427         VALUES (
8428             'BlockExpiredPatronOpacActions',
8429             '0',
8430             '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',
8431             NULL,
8432             'YesNo'
8433         )
8434     ");
8435     $dbh->do("ALTER TABLE `categories` ADD COLUMN `BlockExpiredPatronOpacActions` TINYINT(1) DEFAULT -1 NOT NULL AFTER category_type");
8436     print "Upgraded to $DBversion done (Bug 6739 - expired patrons not blocked from opac actions)\n";
8437     SetVersion ($DBversion);
8438 }
8439
8440 $DBversion = "3.15.00.046";
8441 if ( CheckVersion($DBversion) ) {
8442     $dbh->do(q|
8443         ALTER TABLE search_history ADD COLUMN type VARCHAR(16) NOT NULL DEFAULT 'biblio' AFTER query_cgi
8444     |);
8445     print "Upgrade to $DBversion done (Bug 10807 - Add db field search_history.type)\n";
8446     SetVersion($DBversion);
8447 }
8448
8449 $DBversion = "3.15.00.047";
8450 if ( CheckVersion($DBversion) ) {
8451     $dbh->do(q|
8452         INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('EnableSearchHistory','0','','Enable or disable search history','YesNo')
8453     |);
8454     print "Upgrade to $DBversion done (Bug 10862: Add EnableSearchHistory syspref)\n";
8455     SetVersion($DBversion);
8456 }
8457
8458 $DBversion = "3.15.00.048";
8459 if ( CheckVersion($DBversion) ) {
8460     $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')");
8461     $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')");
8462     print "Upgrade to $DBversion done (Bug 10195: Records hidden with OpacSuppression can still be accessed)\n";
8463     SetVersion($DBversion);
8464 }
8465
8466 $DBversion = "3.15.00.049";
8467 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
8468     $dbh->do("ALTER TABLE biblioitems DROP INDEX isbn");
8469     $dbh->do("ALTER TABLE biblioitems DROP INDEX issn");
8470     $dbh->do("ALTER TABLE biblioitems
8471               CHANGE isbn isbn MEDIUMTEXT NULL DEFAULT NULL,
8472               CHANGE issn issn MEDIUMTEXT NULL DEFAULT NULL
8473     ");
8474     $dbh->do("ALTER TABLE biblioitems
8475               ADD INDEX isbn ( isbn ( 255 ) ),
8476               ADD INDEX issn ( issn ( 255 ) )
8477     ");
8478
8479     $dbh->do("ALTER TABLE deletedbiblioitems DROP INDEX isbn");
8480     $dbh->do("ALTER TABLE deletedbiblioitems
8481               CHANGE isbn isbn MEDIUMTEXT NULL DEFAULT NULL,
8482               CHANGE issn issn MEDIUMTEXT NULL DEFAULT NULL
8483     ");
8484     $dbh->do("ALTER TABLE deletedbiblioitems
8485               ADD INDEX isbn ( isbn ( 255 ) )
8486     ");
8487
8488     print "Upgrade to $DBversion done (Bug 5377 - Biblioitems isbn and issn fields too small for multiple ISBN and ISSN)\n";
8489     SetVersion($DBversion);
8490 }
8491
8492 $DBversion = "3.15.00.050";
8493 if ( CheckVersion($DBversion) ) {
8494     $dbh->do("
8495         INSERT INTO systempreferences (
8496             variable,
8497             value,
8498             explanation,
8499             type
8500         ) VALUES (
8501             'AggressiveMatchOnISBN',
8502             '0',
8503             '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',
8504             'YesNo'
8505         )
8506     ");
8507
8508     print "Upgrade to $DBversion done (Bug 10500 - Improve isbn matching when importing records)\n";
8509     SetVersion($DBversion);
8510 }
8511
8512 $DBversion = "3.15.00.051";
8513 if ( CheckVersion($DBversion) ) {
8514     print "Upgrade to $DBversion done (Koha 3.16 beta)\n";
8515     SetVersion($DBversion);
8516 }
8517
8518 $DBversion = "3.15.00.052";
8519 if ( CheckVersion($DBversion) ) {
8520     print "Upgrade to $DBversion done (Koha 3.16 RC)\n";
8521     SetVersion($DBversion);
8522 }
8523
8524 $DBversion = "3.16.00.000";
8525 if ( CheckVersion($DBversion) ) {
8526     print "Upgrade to $DBversion done (3.16.0 release)\n";
8527     SetVersion ($DBversion);
8528 }
8529
8530 $DBversion = '3.17.00.000';
8531 if ( CheckVersion($DBversion) ) {
8532     print "Upgrade to $DBversion done (there is no time to rest on our laurels)\n";
8533     SetVersion ($DBversion);
8534 }
8535
8536 $DBversion = '3.17.00.001';
8537 if ( CheckVersion($DBversion) ) {
8538    $dbh->do("UPDATE systempreferences SET variable = 'AuthoritySeparator' WHERE variable = 'authoritysep'");
8539    print "Upgrade to $DBversion done (Bug 10330 - Rename system preference authoritysep to AuthoritySeparator)\n";
8540    SetVersion ($DBversion);
8541 }
8542
8543 $DBversion = "3.17.00.002";
8544 if (CheckVersion($DBversion)) {
8545     $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')");
8546     $dbh->do("
8547 CREATE TABLE IF NOT EXISTS `misc_files` (
8548   `file_id` int(11) NOT NULL AUTO_INCREMENT,
8549   `table_tag` varchar(255) NOT NULL,
8550   `record_id` int(11) NOT NULL,
8551   `file_name` varchar(255) NOT NULL,
8552   `file_type` varchar(255) NOT NULL,
8553   `file_description` varchar(255) DEFAULT NULL,
8554   `file_content` longblob NOT NULL, -- file content
8555   `date_uploaded` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
8556   PRIMARY KEY (`file_id`),
8557   KEY `table_tag` (`table_tag`),
8558   KEY `record_id` (`record_id`)
8559 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
8560     ");
8561     print "Upgrade to $DBversion done (Bug 3050 - Add an option to upload scanned invoices)\n";
8562     SetVersion($DBversion);
8563 }
8564
8565 $DBversion = "3.17.00.003";
8566 if (CheckVersion($DBversion)) {
8567     $dbh->do("UPDATE systempreferences SET type = 'Choice', options = '0|1|force' WHERE variable = 'OPACItemHolds'");
8568     print "Upgrade to $DBversion done (Bug 7825 - Changed OPACItemHolds syspref to Choice)\n";
8569     SetVersion($DBversion);
8570 }
8571
8572 $DBversion = "3.17.00.004";
8573 if (CheckVersion($DBversion)) {
8574     $dbh->do("ALTER TABLE categories ADD default_privacy ENUM( 'default', 'never', 'forever' ) NOT NULL DEFAULT 'default' AFTER category_type");
8575     print "Upgrade to $DBversion done (Bug 6254 - can't set patron privacy by default)\n";
8576     SetVersion($DBversion);
8577 }
8578
8579 $DBversion = "3.17.00.005";
8580 if (CheckVersion($DBversion)) {
8581     $dbh->do(q|
8582         ALTER TABLE issuingrules
8583         ADD maxsuspensiondays INT(11) DEFAULT NULL AFTER finedays;
8584     |);
8585     print "Upgrade to $DBversion done (Bug 12230: Add new issuing rule maxsuspensiondays)\n";
8586     SetVersion($DBversion);
8587 }
8588
8589 $DBversion = "3.17.00.006";
8590 if ( CheckVersion($DBversion) ) {
8591     $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')");
8592     $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')");
8593     print "Upgrade to $DBversion done (Bug 7720 - Ambiguity in OPAC Details location.)\n";
8594     SetVersion($DBversion);
8595 }
8596
8597 $DBversion = "3.17.00.007";
8598 if (CheckVersion($DBversion)) {
8599     $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');");
8600     print "Upgrade to $DBversion done (Bug 11629 - Add ability to update not for loan status on checkin)\n";
8601     SetVersion($DBversion);
8602 }
8603
8604 $DBversion = "3.17.00.008";
8605 if ( CheckVersion($DBversion) ) {
8606     $dbh->do(q|
8607         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('OPACAcquisitionDetails','0', '','Show the acquisition details at the OPAC','YesNo')
8608     |);
8609     print "Upgrade to $DBversion done (Bug 11169 - Add OPACAcquisitionDetails syspref)\n";
8610     SetVersion($DBversion);
8611 }
8612
8613 $DBversion = "3.17.00.009";
8614 if ( CheckVersion($DBversion) ) {
8615     $dbh->do(q{
8616         DELETE FROM systempreferences WHERE variable = 'UseTablesortForCirc'
8617     });
8618
8619     print "Upgrade to $DBversion done (Bug 11703 - Remove UseTablesortForCirc syspref)\n";
8620     SetVersion($DBversion);
8621 }
8622
8623 $DBversion = "3.17.00.010";
8624 if ( CheckVersion($DBversion) ) {
8625     $dbh->do("DELETE FROM systempreferences WHERE variable='opacsmallimage'");
8626     print "Upgrade to $DBversion done (Bug 11347 - PROG/CCSR deprecation: Remove opacsmallimage system preference)\n";
8627     SetVersion($DBversion);
8628 }
8629
8630 $DBversion = "3.17.00.011";
8631 if ( CheckVersion($DBversion) ) {
8632     $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'hr', 'language', 'Croatian','2014-07-24' )");
8633     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'hr','hrv')");
8634     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'hr', 'Hrvatski')");
8635     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'en', 'Croatian')");
8636     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'fr', 'Croate')");
8637     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'de', 'Kroatisch')");
8638     print "Upgrade to $DBversion done (Bug 12649: Add Croatian language)\n";
8639     SetVersion ($DBversion);
8640 }
8641
8642 $DBversion = "3.17.00.012";
8643 if ( CheckVersion($DBversion) ) {
8644     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacShowFiltersPulldownMobile'");
8645     print "Upgrade to $DBversion done ( Bug 12512 - PROG/CCSR deprecation: Remove OpacShowFiltersPulldownMobile system preference )\n";
8646     SetVersion ($DBversion);
8647 }
8648
8649 $DBversion = "3.17.00.013";
8650 if ( CheckVersion($DBversion) ) {
8651     $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')");
8652     print "Upgrade to $DBversion done (Re-add system preference maxreserves)\n";
8653     SetVersion ($DBversion);
8654 }
8655
8656 $DBversion = '3.17.00.014';
8657 if ( CheckVersion($DBversion) ) {
8658     $dbh->do("
8659         INSERT INTO systempreferences (variable,value,explanation,type) VALUES
8660         ('OverdueNoticeCalendar',0,'Take calendar into consideration when working out sending overdue notices','YesNo')
8661     ");
8662     print "Upgrade to $DBversion done (Bug 12529 - Adding a syspref to allow the overdue notices to consider the calendar when generating notices)\n";
8663     SetVersion($DBversion);
8664 }
8665
8666 $DBversion = "3.17.00.015";
8667 if ( CheckVersion($DBversion) ) {
8668     $dbh->do(q{
8669         CREATE TABLE IF NOT EXISTS columns_settings (
8670             module varchar(255) NOT NULL,
8671             page varchar(255) NOT NULL,
8672             tablename varchar(255) NOT NULL,
8673             columnname varchar(255) NOT NULL,
8674             cannot_be_toggled int(1) NOT NULL DEFAULT 0,
8675             is_hidden int(1) NOT NULL DEFAULT 0,
8676             PRIMARY KEY(module, page, tablename, columnname)
8677         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
8678     });
8679     print "Upgrade to $DBversion done (Bug 10212 - Create new table columns_settings)\n";
8680     SetVersion ($DBversion);
8681 }
8682
8683 $DBversion = "3.17.00.016";
8684 if ( CheckVersion($DBversion) ) {
8685     $dbh->do("CREATE TABLE aqcontacts (
8686         id int(11) NOT NULL auto_increment,
8687         name varchar(100) default NULL,
8688         position varchar(100) default NULL,
8689         phone varchar(100) default NULL,
8690         altphone varchar(100) default NULL,
8691         fax varchar(100) default NULL,
8692         email varchar(100) default NULL,
8693         notes mediumtext,
8694         claimacquisition BOOLEAN NOT NULL DEFAULT 0,
8695         claimissues BOOLEAN NOT NULL DEFAULT 0,
8696         acqprimary BOOLEAN NOT NULL DEFAULT 0,
8697         serialsprimary BOOLEAN NOT NULL DEFAULT 0,
8698         booksellerid int(11) not NULL,
8699         PRIMARY KEY  (id),
8700         CONSTRAINT booksellerid_aqcontacts_fk FOREIGN KEY (booksellerid)
8701             REFERENCES aqbooksellers (id) ON DELETE CASCADE ON UPDATE CASCADE
8702         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;");
8703     $dbh->do("INSERT INTO aqcontacts (name, position, phone, altphone, fax,
8704             email, notes, booksellerid, claimacquisition, claimissues, acqprimary, serialsprimary)
8705         SELECT contact, contpos, contphone, contaltphone, contfax, contemail,
8706             contnotes, id, 1, 1, 1, 1 FROM aqbooksellers;");
8707     $dbh->do("ALTER TABLE aqbooksellers DROP COLUMN contact,
8708         DROP COLUMN contpos, DROP COLUMN contphone,
8709         DROP COLUMN contaltphone, DROP COLUMN contfax,
8710         DROP COLUMN contemail, DROP COLUMN contnotes;");
8711     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contact>>', '<<aqcontacts.name>>')");
8712     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contpos>>', '<<aqcontacts.position>>')");
8713     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contphone>>', '<<aqcontacts.phone>>')");
8714     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contaltphone>>', '<<aqcontacts.altphone>>')");
8715     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contfax>>', '<<aqcontacts.contfax>>')");
8716     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contemail>>', '<<aqcontacts.contemail>>')");
8717     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contnotes>>', '<<aqcontacts.contnotes>>')");
8718     print "Upgrade to $DBversion done (Bug 10402: Move bookseller contacts to separate table)\n";
8719     SetVersion($DBversion);
8720 }
8721
8722 $DBversion = "3.17.00.017";
8723 if ( CheckVersion($DBversion) ) {
8724     # Correct invalid recordtypes (should be very exceptional)
8725     $dbh->do(q{
8726         UPDATE z3950servers set recordtype='biblio' WHERE recordtype NOT IN ('authority','biblio')
8727     });
8728     # Correct invalid server types (should also be very exceptional)
8729     $dbh->do(q{
8730         UPDATE z3950servers set type='zed' WHERE type <> 'zed'
8731     });
8732     # Adjust table
8733     $dbh->do(q{
8734         ALTER TABLE z3950servers
8735         DROP COLUMN icon,
8736         DROP COLUMN description,
8737         DROP COLUMN position,
8738         MODIFY COLUMN id int NOT NULL AUTO_INCREMENT FIRST,
8739         MODIFY COLUMN recordtype enum('authority','biblio') NOT NULL DEFAULT 'biblio',
8740         CHANGE COLUMN name servername mediumtext NOT NULL,
8741         CHANGE COLUMN type servertype enum('zed','sru') NOT NULL DEFAULT 'zed',
8742         ADD COLUMN sru_options varchar(255) default NULL,
8743         ADD COLUMN sru_fields mediumtext default NULL,
8744         ADD COLUMN add_xslt mediumtext default NULL
8745     });
8746     print "Upgrade to $DBversion done (Bug 6536: Z3950 improvements)\n";
8747     SetVersion ($DBversion);
8748 }
8749
8750 $DBversion = "3.17.00.018";
8751 if ( CheckVersion($DBversion) ) {
8752     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('HoldsInNoissuesCharge', '0', 'Hold charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
8753     print "Upgrade to $DBversion done (Bug 12205: Add HoldsInNoissuesCharge systempreference)\n";
8754     SetVersion($DBversion);
8755 }
8756
8757 $DBversion = "3.17.00.019";
8758 if ( CheckVersion($DBversion) ) {
8759     $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')"
8760     );
8761     print "Upgrade to $DBversion done (Bug 6149: Operator highlighted in search results)\n";
8762     SetVersion($DBversion);
8763 }
8764
8765 $DBversion = "3.17.00.020";
8766 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
8767     $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')");
8768     print "Upgrade to $DBversion done (Bug 8735 - Expire holds waiting only on days the library is open)\n";
8769     SetVersion ($DBversion);
8770 }
8771
8772 $DBversion = "3.17.00.021";
8773 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
8774     my $pref = C4::Context->preference('HomeOrHoldingBranch');
8775     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
8776        VALUES ('StaffSearchResultsDisplayBranch', ?,'homebranch|holdingbranch','Controls the display of the home or holding branch for staff search results','choice')", undef, $pref);
8777     print "Upgrade to $DBversion done (Bug 12582 - Control of branch displayed in search results linked to HomeOrHoldingBranch)\n";
8778     SetVersion ($DBversion);
8779 }
8780
8781 $DBversion = '3.17.00.022';
8782 if ( CheckVersion($DBversion) ) {
8783     my @temp= $dbh->selectrow_array(qq|
8784         SELECT count(*)
8785         FROM marc_subfield_structure
8786         WHERE kohafield='permanent_location' OR kohafield='items.permanent_location'
8787     |);
8788     print "Upgrade to $DBversion done (Bug 7817: Check for permanent_location)\n";
8789     if( $temp[0] ) {
8790         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";
8791     }
8792     SetVersion($DBversion);
8793 }
8794
8795 $DBversion = "3.17.00.023";
8796 if ( CheckVersion($DBversion) ) {
8797     $dbh->do(q{
8798         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')
8799     });
8800     print "Upgrade to $DBversion done (Bug 11169 - Add AcqItemSetSubfieldsWhenReceiptIsCancelled syspref)\n";
8801     SetVersion($DBversion);
8802 }
8803
8804 $DBversion = "3.17.00.024";
8805 if(CheckVersion($DBversion)) {
8806     $dbh->do(q{
8807         ALTER TABLE issues ADD auto_renew BOOLEAN default FALSE AFTER renewals
8808     });
8809     $dbh->do(q{
8810         ALTER TABLE old_issues ADD auto_renew BOOLEAN default FALSE AFTER renewals
8811     });
8812     $dbh->do(q{
8813         ALTER TABLE issuingrules ADD auto_renew BOOLEAN default FALSE AFTER norenewalbefore
8814     });
8815     print "Upgrade to $DBversion done (Bug 11577: [ENH] Automatic renewal feature)\n";
8816     SetVersion($DBversion);
8817 }
8818
8819 $DBversion = '3.17.00.025';
8820 if ( CheckVersion($DBversion) ) {
8821     $dbh->do(qq{
8822         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')
8823     });
8824     print "Upgrade to $DBversion done (Bug 12728: Checked syspref StatisticsFields)\n";
8825 }
8826
8827 $DBversion = "3.17.00.026";
8828 if ( CheckVersion($DBversion) ) {
8829     if ( C4::Context->preference('marcflavour') eq 'MARC21' ) {
8830         $dbh->do("UPDATE marc_subfield_structure SET liblibrarian = 'Encoded bitrate', libopac = 'Encoded bitrate' WHERE tagfield = '347' AND tagsubfield = 'f'");
8831         $dbh->do("UPDATE marc_subfield_structure SET repeatable = 1 WHERE tagfield IN ('110','111','610','611','710','711','810','811') AND tagsubfield = 'c'");
8832         $dbh->do("UPDATE auth_subfield_structure SET repeatable = 1 WHERE tagfield IN ('110','111','410','411','510','511','710','711') AND tagsubfield = 'c'");
8833         print "Upgrade to $DBversion done (Bug 12435 - Update MARC21 frameworks to Update No. 18 (April 2014))\n";
8834     }
8835     SetVersion($DBversion);
8836 }
8837
8838 $DBversion = "3.17.00.027";
8839 if ( CheckVersion($DBversion) ) {
8840     $dbh->do(q{
8841         DELETE FROM systempreferences WHERE variable = 'SearchEngine'
8842     });
8843     print "Upgrade to $DBversion done (Bug 12538 - Remove SearchEngine syspref)\n";
8844     SetVersion($DBversion);
8845 }
8846
8847 $DBversion = "3.17.00.028";
8848 if ( CheckVersion($DBversion) ) {
8849     $dbh->do(q{
8850         INSERT INTO systempreferences (variable,value) VALUES('OpacCustomSearch','');
8851     });
8852     print "Upgrade to $DBversion done (Bug 12296 - search box replaceable with a system preference)\n";
8853     SetVersion($DBversion);
8854 }
8855
8856 $DBversion = "3.17.00.029";
8857 if ( CheckVersion($DBversion) ) {
8858     $dbh->do("ALTER TABLE  `items` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8859     $dbh->do("ALTER TABLE  `deleteditems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8860     $dbh->do("ALTER TABLE  `biblioitems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8861     $dbh->do("ALTER TABLE  `deletedbiblioitems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8862     print "Upgrade to $DBversion done (Bug 12424 - ddc sorting of call numbers truncates long Cutter parts)\n";
8863     SetVersion ($DBversion);
8864 }
8865
8866 $DBversion = "3.17.00.030";
8867 if ( CheckVersion($DBversion) ) {
8868     $dbh->do(
8869         q{
8870        INSERT INTO systempreferences (variable, value, options, explanation, type )
8871        VALUES
8872         ('UsageStatsCountry', '', NULL, 'The country where your library is located, to be shown on the Hea Koha community website', 'YesNo'),
8873         ('UsageStatsID', '', NULL, 'This preference is part of Koha but it should not be deleted or updated manually.',  'Free'),
8874         ('UsageStatsLastUpdateTime', '', NULL, 'This preference is part of Koha but it should not be deleted or updated manually.', 'Free'),
8875         ('UsageStatsLibraryName', '', NULL, 'The library name to be shown on Hea Koha community website', 'Free'),
8876         ('UsageStatsLibraryType', 'public', 'public|university', 'The library type to be shown on the Hea Koha community website', 'Choice'),
8877         ('UsageStatsLibraryUrl', '', NULL, 'The library URL to be shown on Hea Koha community website', 'Free'),
8878         ('UsageStats', 0, NULL, 'Share anonymous usage data on the Hea Koha community website.', 'YesNo')
8879     });
8880     print "Upgrade to $DBversion done (Bug 11926: Add UsageStats systempreferences (HEA))\n";
8881     SetVersion ($DBversion);
8882 }
8883
8884 $DBversion = "3.17.00.031";
8885 if ( CheckVersion($DBversion) ) {
8886    $dbh->do("ALTER TABLE saved_sql CHANGE report_name report_name VARCHAR( 255 ) NOT NULL DEFAULT '' ");
8887    print "Upgrade to $DBversion done (Bug 2969: Report Name should be mandatory for saved reports)\n";
8888    SetVersion ($DBversion);
8889 }
8890
8891 $DBversion = "3.17.00.032";
8892 if ( CheckVersion($DBversion) ) {
8893     $dbh->do(
8894 "INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('ReplytoDefault',  '',  NULL,  'The default email address to be set as replyto.',  'Free')"
8895     );
8896     $dbh->do(
8897 "INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('ReturnpathDefault',  '',  NULL,  'The default email address to be set as return-path',  'Free')"
8898     );
8899     $dbh->do("ALTER TABLE branches ADD branchreplyto mediumtext AFTER branchemail");
8900     $dbh->do("ALTER TABLE branches ADD branchreturnpath mediumtext AFTER branchreplyto");
8901     print "Upgrade to $DBversion done (Bug 9530: Adding replyto and returnpath addresses.)\n";
8902     SetVersion($DBversion);
8903 }
8904
8905 $DBversion = "3.17.00.033";
8906 if ( CheckVersion($DBversion) ) {
8907     $dbh->do(q{
8908         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
8909         VALUES('FacetMaxCount', '20','Specify the max facet count for each category',NULL,'Integer')
8910     });
8911     print "Upgrade to $DBversion done (Bug 13088 - Allow the user to specify a max amount of facets to show)\n";
8912     SetVersion($DBversion);
8913 }
8914
8915 $DBversion = "3.17.00.034";
8916 if ( CheckVersion($DBversion) ) {
8917     $dbh->do(q|
8918         ALTER TABLE aqorders DROP COLUMN cancelledby;
8919     |);
8920
8921     print "Upgrade to $DBversion done (Bug 11007 - DROP column aqorders.cancelledby)\n";
8922     SetVersion($DBversion);
8923 }
8924
8925 $DBversion = "3.17.00.035";
8926 if ( CheckVersion($DBversion) ) {
8927     $dbh->do(q|
8928         ALTER TABLE serial ADD COLUMN claims_count INT(11) DEFAULT 0 after claimdate
8929     |);
8930     $dbh->do(q|
8931         UPDATE serial
8932         SET claims_count = 1
8933         WHERE claimdate IS NOT NULL
8934     |);
8935     print "Upgrade to $DBversion done (Bug 5342: Add claims_count field in serial table)\n";
8936     SetVersion($DBversion);
8937 }
8938
8939 $DBversion = "3.17.00.036";
8940 if ( CheckVersion($DBversion) ) {
8941     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacShowLibrariesPulldownMobile'");
8942     print "Upgrade to $DBversion done ( Bug 12513 - PROG/CCSR deprecation: Remove OpacShowLibrariesPulldownMobile system preference )\n";
8943     SetVersion ($DBversion);
8944 }
8945
8946 $DBversion = "3.17.00.037";
8947 if ( CheckVersion($DBversion) ) {
8948     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacMainUserBlockMobile'");
8949     print "Upgrade to $DBversion done ( Bug 12246 - PROG/CCSR deprecation: Remove OpacMainUserBlockMobile system preference )\n";
8950     SetVersion ($DBversion);
8951 }
8952
8953 $DBversion = "3.17.00.038";
8954 if ( CheckVersion($DBversion) ) {
8955     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACMobileUserCSS'");
8956     print "Upgrade to $DBversion done ( Bug 12245 - PROG/CCSR deprecation: Remove OPACMobileUserCSS system preference )\n";
8957     SetVersion ($DBversion);
8958 }
8959
8960 $DBversion = "3.17.00.039";
8961 if ( CheckVersion($DBversion) ) {
8962     $dbh->do("INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES
8963     ('OPACFallback', 'prog', 'bootstrap|prog', 'Define the fallback theme for the OPAC interface.', 'Themes')");
8964     print "Upgrade to $DBversion done (Bug 12539 - PROG/CCSR deprecation: Remove hardcoded theme from C4/Templates.pm)\n";
8965     SetVersion ($DBversion);
8966 }
8967
8968 $DBversion = "3.17.00.040";
8969 if ( CheckVersion($DBversion) ) {
8970     my $opac_theme = C4::Context->preference( 'opacthemes' );
8971     if ( !defined $opac_theme || $opac_theme eq 'prog' || $opac_theme eq 'ccsr' ) {
8972         $dbh->do("UPDATE systempreferences SET value='bootstrap' WHERE variable='opacthemes'");
8973     }
8974     print "Upgrade to $DBversion done (Bug 12223: 'prog' and 'ccsr' themes removed)\n";
8975     SetVersion($DBversion);
8976 }
8977
8978 $DBversion = "3.17.00.041";
8979 if ( CheckVersion($DBversion) ) {
8980     print "Upgrade to $DBversion done (Bug 11346: Deprecate the 'prog' and 'CCSR' themes)\n";
8981     SetVersion($DBversion);
8982 }
8983
8984 $DBversion = "3.17.00.042";
8985 if ( CheckVersion($DBversion) ) {
8986     $dbh->do("DELETE FROM systempreferences WHERE variable='yuipath'");
8987     print "Upgrade to $DBversion done (Bug 12494: Remove yuipath system preference)\n";
8988     SetVersion ($DBversion);
8989 }
8990
8991 $DBversion = "3.17.00.043";
8992 if ( CheckVersion($DBversion) ) {
8993     $dbh->do("
8994         ALTER TABLE aqorders
8995         ADD COLUMN cancellationreason TEXT DEFAULT NULL AFTER datecancellationprinted
8996     ");
8997     print "Upgrade to $DBversion done (Bug 7162: Add aqorders.cancellationreason)\n";
8998     SetVersion ($DBversion);
8999 }
9000
9001 $DBversion = "3.17.00.044";
9002 if ( CheckVersion($DBversion) ) {
9003     $dbh->do(q{
9004         INSERT IGNORE INTO systempreferences
9005             (variable,value,explanation,options,type)
9006             VALUES('OnSiteCheckouts','0','Enable/Disable the on-site checkouts feature','','YesNo');
9007     });
9008     $dbh->do(q{
9009         INSERT IGNORE INTO systempreferences
9010             (variable,value,explanation,options,type)
9011             VALUES('OnSiteCheckoutsForce','0','Enable/Disable the on-site for all cases (Even if a user is debarred, etc.)','','YesNo');
9012     });
9013     $dbh->do(q{
9014         ALTER TABLE issues ADD COLUMN onsite_checkout INT(1) NOT NULL DEFAULT 0 AFTER issuedate;
9015     });
9016     $dbh->do(q{
9017         ALTER TABLE old_issues ADD COLUMN onsite_checkout INT(1) NOT NULL DEFAULT 0 AFTER issuedate;
9018     });
9019     print "Upgrade to $DBversion done (Bug 10860: Add new system preference OnSiteCheckouts + fields [old_]issues.onsite_checkout)\n";
9020     SetVersion($DBversion);
9021 }
9022
9023 $DBversion = "3.17.00.045";
9024 if ( CheckVersion($DBversion) ) {
9025     $dbh->do(q{
9026         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
9027         ('LocalHoldsPriority',  '0', NULL,  'Enables the LocalHoldsPriority feature',  'YesNo'),
9028         ('LocalHoldsPriorityItemControl',  'holdingbranch',  'holdingbranch|homebranch',  'decides if the feature operates using the item''s home or holding library.',  'Choice'),
9029         ('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')
9030     });
9031     print "Upgrade to $DBversion done (Bug 11126 - Make the holds system optionally give precedence to local holds)\n";
9032     SetVersion($DBversion);
9033 }
9034
9035 $DBversion = "3.17.00.046";
9036 if ( CheckVersion($DBversion) ) {
9037     $dbh->do(q{
9038         CREATE TABLE IF NOT EXISTS items_search_fields (
9039           name VARCHAR(255) NOT NULL,
9040           label VARCHAR(255) NOT NULL,
9041           tagfield CHAR(3) NOT NULL,
9042           tagsubfield CHAR(1) NULL DEFAULT NULL,
9043           authorised_values_category VARCHAR(16) NULL DEFAULT NULL,
9044           PRIMARY KEY(name),
9045           CONSTRAINT items_search_fields_authorised_values_category
9046             FOREIGN KEY (authorised_values_category) REFERENCES authorised_values (category)
9047             ON DELETE SET NULL ON UPDATE CASCADE
9048         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
9049     });
9050     print "Upgrade to $DBversion done (Bug 11425: Add items_search_fields table)\n";
9051     SetVersion($DBversion);
9052 }
9053
9054 $DBversion = "3.17.00.047";
9055 if ( CheckVersion($DBversion) ) {
9056     $dbh->do(q{
9057         ALTER TABLE collections
9058             CHANGE colBranchcode colBranchcode VARCHAR( 10 ) NULL DEFAULT NULL,
9059             ADD INDEX ( colBranchcode ),
9060             ADD CONSTRAINT collections_ibfk_1 FOREIGN KEY (colBranchcode) REFERENCES branches (branchcode) ON DELETE CASCADE ON UPDATE CASCADE
9061     });
9062     print "Upgrade to $DBversion done (Bug 8836 - Resurrect Rotating Collections)\n";
9063     SetVersion($DBversion);
9064 }
9065
9066 $DBversion = "3.17.00.048";
9067 if ( CheckVersion($DBversion) ) {
9068     $dbh->do(q|
9069         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')
9070     |);
9071     print "Upgrade to $DBversion done (Bug 12448 - Add RentalFeesCheckoutConfirmation syspref)\n";
9072     SetVersion($DBversion);
9073 }
9074
9075 $DBversion = "3.17.00.049";
9076 if ( CheckVersion($DBversion) ) {
9077     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'am', 'language', 'Amharic','2014-10-29')");
9078     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'am','amh')");
9079     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'am', 'language', 'am', 'አማርኛ')");
9080     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'am', 'language', 'en', 'Amharic')");
9081
9082     $dbh->do("UPDATE language_descriptions SET description = 'لعربية' WHERE subtag = 'ar' AND type = 'language' AND lang = 'ar'");
9083
9084     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'az', 'language', 'Azerbaijani','2014-10-30')");
9085     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'az','aze')");
9086     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'az', 'language', 'az', 'Azərbaycan dili')");
9087     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'az', 'language', 'en', 'Azerbaijani')");
9088
9089     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'be', 'language', 'Byelorussian','2014-10-30')");
9090     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'be','bel')");
9091     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'be', 'language', 'be', 'Беларуская мова')");
9092     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'be', 'language', 'en', 'Byelorussian')");
9093
9094     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'bn', 'language', 'Bengali','2014-10-30')");
9095     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'bn','ben')");
9096     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'bn', 'language', 'bn', 'বাংলা')");
9097     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'bn', 'language', 'en', 'Bengali')");
9098
9099     $dbh->do("UPDATE language_descriptions SET description = 'Български' WHERE subtag = 'bg' AND type = 'language' AND lang = 'bg'");
9100     $dbh->do("UPDATE language_descriptions SET description = 'Ceština' WHERE subtag = 'cs' AND type = 'language' AND lang = 'cs'");
9101     $dbh->do("UPDATE language_descriptions SET description = 'Ελληνικά' WHERE subtag = 'el' AND type = 'language' AND lang = 'el'");
9102     $dbh->do("UPDATE language_descriptions SET description = 'Español' WHERE subtag = 'es' AND type = 'language' AND lang = 'es'");
9103
9104     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'eu', 'language', 'Basque','2014-10-30')");
9105     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'eu','eus')");
9106     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'eu', 'language', 'eu', 'Euskera')");
9107     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'eu', 'language', 'en', 'Basque')");
9108
9109     $dbh->do("UPDATE language_descriptions SET description = 'فارسى' WHERE subtag = 'fa' AND type = 'language' AND lang = 'fa'");
9110     $dbh->do("UPDATE language_descriptions SET description = 'Suomi' WHERE subtag = 'fi' AND type = 'language' AND lang = 'fi'");
9111
9112     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'fo', 'language', 'Faroese','2014-10-30')");
9113     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'fo','fao')");
9114     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'fo', 'language', 'fo', 'Føroyskt')");
9115     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'fo', 'language', 'en', 'Faroese')");
9116
9117     $dbh->do("UPDATE language_descriptions SET description = 'Français' WHERE subtag = 'fr' AND type = 'language' AND lang = 'fr'");
9118     $dbh->do("UPDATE language_descriptions SET description = 'עִבְרִית' WHERE subtag = 'he' AND type = 'language' AND lang = 'he'");
9119     $dbh->do("UPDATE language_descriptions SET description = 'हिन्दी' WHERE subtag = 'hi' AND type = 'language' AND lang = 'hi'");
9120
9121     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'is', 'language', 'Icelandic','2014-10-30')");
9122     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'is','ice')");
9123     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'is', 'language', 'is', 'Íslenska')");
9124     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'is', 'language', 'en', 'Icelandic')");
9125
9126     $dbh->do("UPDATE language_descriptions SET description = '日本語' WHERE subtag = 'ja' AND type = 'language' AND lang = 'ja'");
9127
9128     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ka', 'language', 'Kannada','2014-10-30')");
9129     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ka','kan')");
9130     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'ka', 'ಕನ್ನಡ')");
9131     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'en', 'Kannada')");
9132
9133     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'km', 'language', 'Khmer','2014-10-30')");
9134     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'km','khm')");
9135     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'km', 'language', 'km', 'ភាសាខ្មែរ')");
9136     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'km', 'language', 'en', 'Khmer')");
9137
9138     $dbh->do("UPDATE language_descriptions SET description = '한국어' WHERE subtag = 'ko' AND type = 'language' AND lang = 'ko'");
9139
9140     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ku', 'language', 'Kurdish','2014-05-13')");
9141     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ku','kur')");
9142     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'ku', 'کوردی')");
9143     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'en', 'Kurdish')");
9144     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'fr', 'Kurde')");
9145     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'de', 'Kurdisch')");
9146     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'es', 'Kurdo')");
9147
9148     $dbh->do("UPDATE language_descriptions SET description = 'ພາສາລາວ' WHERE subtag = 'lo' AND type = 'language' AND lang = 'lo'");
9149
9150     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mi', 'language', 'Maori','2014-10-30')");
9151     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mi','mri')");
9152     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mi', 'language', 'mi', 'Te Reo Māori')");
9153     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mi', 'language', 'en', 'Maori')");
9154
9155     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mn', 'language', 'Mongolian','2014-10-30')");
9156     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mn','mon')");
9157     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mn', 'language', 'mn', 'Mонгол')");
9158     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mn', 'language', 'en', 'Mongolian')");
9159
9160     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mr', 'language', 'Marathi','2014-10-30')");
9161     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mr','mar')");
9162     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mr', 'language', 'mr', 'मराठी')");
9163     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mr', 'language', 'en', 'Marathi')");
9164
9165     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ms', 'language', 'Malay','2014-10-30')");
9166     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ms','may')");
9167     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ms', 'language', 'ms', 'Bahasa melayu')");
9168     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ms', 'language', 'en', 'Malay')");
9169
9170     $dbh->do("UPDATE language_descriptions SET description = 'Norsk bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'nb'");
9171     $dbh->do("UPDATE language_descriptions SET description = 'Norwegian bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'en'");
9172     $dbh->do("UPDATE language_descriptions SET description = 'Norvégien bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'fr'");
9173     $dbh->do("UPDATE language_descriptions SET description = 'Norwegisch bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'de'");
9174
9175     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ne', 'language', 'Nepali','2014-10-30')");
9176     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ne','nep')");
9177     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)VALUES ( 'ne', 'language', 'ne', 'नेपाली')");
9178     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ne', 'language', 'en', 'Nepali')");
9179
9180     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'pbr', 'language', 'Pangwa','2014-10-30')");
9181     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'pbr','pbr')");
9182     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'pbr', 'language', 'pbr', 'Ekipangwa')");
9183     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'pbr', 'language', 'en', 'Pangwa')");
9184
9185     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'prs', 'language', 'Dari','2014-10-30')");
9186     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'prs','prs')");
9187     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'prs', 'language', 'prs', 'درى')");
9188     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'prs', 'language', 'en', 'Dari')");
9189
9190     $dbh->do("UPDATE language_descriptions SET description = 'Português' WHERE subtag = 'pt' AND type = 'language' AND lang = 'pt'");
9191     $dbh->do("UPDATE language_descriptions SET description = 'Român' WHERE subtag = 'ro' AND type = 'language' AND lang = 'ro'");
9192     $dbh->do("UPDATE language_descriptions SET description = 'Русский' WHERE subtag = 'ru' AND type = 'language' AND lang = 'ru'");
9193
9194     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'rw', 'language', 'Kinyarwanda','2014-10-30')");
9195     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'rw','kin')");
9196     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'rw', 'language', 'rw', 'Ikinyarwanda')");
9197     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'rw', 'language', 'en', 'Kinyarwanda')");
9198
9199     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sd', 'language', 'Sindhi','2014-10-30')");
9200     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sd','snd')");
9201     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sd', 'language', 'sd', 'سنڌي')");
9202     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sd', 'language', 'en', 'Sindhi')");
9203
9204     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sk', 'language', 'Slovak','2014-10-30')");
9205     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sk','slk')");
9206     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sk', 'language', 'sk', 'Slovenčina')");
9207     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sk', 'language', 'en', 'Slovak')");
9208
9209     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sl', 'language', 'Slovene','2014-10-30')");
9210     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sl','slv')");
9211     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sl', 'language', 'sl', 'Slovenščina')");
9212     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sl', 'language', 'en', 'Slovene')");
9213
9214     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sq', 'language', 'Albanian','2014-10-30')");
9215     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sq','sqi')");
9216     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sq', 'language', 'sq', 'Shqip')");
9217     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sq', 'language', 'en', 'Albanian')");
9218
9219     $dbh->do("UPDATE language_descriptions SET description = 'Cрпски' WHERE subtag = 'sr' AND type = 'language' AND lang = 'sr'");
9220
9221     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sw', 'language', 'Swahili','2014-10-30')");
9222     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sw','swa')");
9223     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sw', 'language', 'sw', 'Kiswahili')");
9224     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sw', 'language', 'en', 'Swahili')");
9225
9226     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ta', 'language', 'Tamil','2014-10-30')");
9227     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ta','tam')");
9228     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ta', 'language', 'ta', 'தமிழ்')");
9229     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ta', 'language', 'en', 'Tamil')");
9230
9231     $dbh->do("UPDATE language_descriptions SET description = 'Tetun' WHERE subtag = 'tet' AND type = 'language' AND lang = 'tet'");
9232     $dbh->do("UPDATE language_descriptions SET description = 'ภาษาไทย' WHERE subtag = 'th' AND type = 'language' AND lang = 'th'");
9233
9234     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'tl', 'language', 'Tagalog','2014-10-30')");
9235     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'tl','tgl')");
9236     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'tl', 'language', 'tl', 'Tagalog')");
9237     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'tl', 'language', 'en', 'Tagalog')");
9238
9239     $dbh->do("UPDATE language_descriptions SET description = 'Türkçe' WHERE subtag = 'tr' AND type = 'language' AND lang = 'tr'");
9240     $dbh->do("UPDATE language_descriptions SET description = 'Українська' WHERE subtag = 'uk' AND type = 'language' AND lang = 'uk'");
9241     $dbh->do("UPDATE language_descriptions SET description = 'اردو' WHERE subtag = 'ur' AND type = 'language' AND lang = 'ur'");
9242
9243     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'vi', 'language', 'Vietnamese','2014-10-30')");
9244     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'vi','vie')");
9245     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'vi', 'language', 'vi', '㗂越')");
9246     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'vi', 'language', 'en', 'Vietnamese')");
9247
9248     $dbh->do("UPDATE language_descriptions SET description = '中文' WHERE subtag = 'zh' AND type = 'language' AND lang = 'zh'");
9249     $dbh->do("UPDATE language_descriptions SET description = '' WHERE subtag = 'Arab,script' AND type = 'Arab' AND lang = 'العربية'");
9250
9251     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Armn', 'script', 'Armenian','2014-10-30')");
9252     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Armn', 'script', 'Armn', 'Հայոց այբուբեն')");
9253     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Armn', 'script', 'en', 'Armenian')");
9254
9255     $dbh->do("UPDATE language_descriptions SET description = 'Кирилица' WHERE subtag = 'Cyrl' AND type = 'script' AND lang = 'Cyrl'");
9256
9257     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Ethi', 'script', 'Ethiopic','2014-10-30')");
9258     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Ethi', 'script', 'Ethi', 'ግዕዝ')");
9259     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Ethi', 'script', 'en', 'Ethiopic')");
9260
9261     $dbh->do("UPDATE language_descriptions SET description = 'Ελληνικό αλφάβητο' WHERE subtag = 'Grek' AND type = 'script' AND lang = 'Grek'");
9262     $dbh->do("UPDATE language_descriptions SET description = '简体字' WHERE subtag = 'Hans' AND type = 'script' AND lang = 'Hans'");
9263     $dbh->do("UPDATE language_descriptions SET description = '繁體字' WHERE subtag = 'Hant' AND type = 'script' AND lang = 'Hant'");
9264     $dbh->do("UPDATE language_descriptions SET description = 'אָלֶף־בֵּית עִבְרִי' WHERE subtag = 'Hebr' AND type = 'script' AND lang = 'Hebr'");
9265
9266     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Jpan', 'script', 'Japanese','2014-10-30')");
9267     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Jpan', 'script', 'Jpan', '漢字')");
9268     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Jpan', 'script', 'en', 'Japanese')");
9269
9270     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Knda', 'script', 'Kannada','2014-10-30')");
9271     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Knda', 'script', 'Knda', 'ಕನ್ನಡ ಲಿಪಿ')");
9272     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Knda', 'script', 'en', 'Kannada')");
9273
9274     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Kore', 'script', 'Korean','2014-10-30')");
9275     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Kore', 'script', 'Kore', '한글')");
9276     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Kore', 'script', 'en', 'Korean')");
9277
9278     $dbh->do("UPDATE language_descriptions SET description = 'ອັກສອນລາວ' WHERE subtag = 'Laoo' AND type = 'script' AND lang = 'Laoo'");
9279
9280     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'AL', 'region', 'Albania','2014-10-30')");
9281     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AL', 'region', 'en', 'Albania')");
9282     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AL', 'region', 'sq', 'Shqipërisë')");
9283
9284     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'AZ', 'region', 'Azerbaijan','2014-10-30')");
9285     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AZ', 'region', 'en', 'Azerbaijan')");
9286     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AZ', 'region', 'az', 'Azərbaycan')");
9287
9288     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BE', 'region', 'Belgium','2014-10-30')");
9289     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BE', 'region', 'en', 'Belgium')");
9290     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BE', 'region', 'nl', 'België')");
9291
9292     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BR', 'region', 'Brazil','2014-10-30')");
9293     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BR', 'region', 'en', 'Brazil')");
9294     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BR', 'region', 'pt', 'Brasil')");
9295
9296     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BY', 'region', 'Belarus','2014-10-30')");
9297     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BY', 'region', 'en', 'Belarus')");
9298     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BY', 'region', 'be', 'Беларусь')");
9299
9300     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CA', 'region', 'fr', 'Canada')");
9301
9302     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CH', 'region', 'Switzerland','2014-10-30')");
9303     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CH', 'region', 'en', 'Switzerland')");
9304     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CH', 'region', 'de', 'Schweiz')");
9305
9306     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CN', 'region', 'China','2014-10-30')");
9307     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CN', 'region', 'en', 'China')");
9308     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CN', 'region', 'zh', '中国')");
9309
9310     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CZ', 'region', 'Czech Republic','2014-10-30')");
9311     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CZ', 'region', 'en', 'Czech Republic')");
9312     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CZ', 'region', 'cs', 'Česká republika')");
9313
9314     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'DE', 'region', 'Germany','2014-10-30')");
9315     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DE', 'region', 'en', 'Germany')");
9316     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DE', 'region', 'de', 'Deutschland')");
9317
9318     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DK', 'region', 'en', 'Denmark')");
9319
9320     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ES', 'region', 'Spain','2014-10-30')");
9321     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ES', 'region', 'en', 'Spain')");
9322     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ES', 'region', 'es', 'España')");
9323
9324     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'FI', 'region', 'Finland','2014-10-30')");
9325     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FI', 'region', 'en', 'Finland')");
9326     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FI', 'region', 'fi', 'Suomi')");
9327
9328     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'FO', 'region', 'Faroe Islands','2014-10-30')");
9329     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FO', 'region', 'en', 'Faroe Islands')");
9330     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FO', 'region', 'fo', 'Føroyar')");
9331
9332     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'GR', 'region', 'Greece','2014-10-30')");
9333     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'GR', 'region', 'en', 'Greece')");
9334     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'GR', 'region', 'el', 'Ελλάδα')");
9335
9336     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'HR', 'region', 'Croatia','2014-10-30')");
9337     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HR', 'region', 'en', 'Croatia')");
9338     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HR', 'region', 'hr', 'Hrvatska')");
9339
9340     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'HU', 'region', 'Hungary','2014-10-30')");
9341     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HU', 'region', 'en', 'Hungary')");
9342     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HU', 'region', 'hu', 'Magyarország')");
9343
9344     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ID', 'region', 'Indonesia','2014-10-30')");
9345     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ID', 'region', 'en', 'Indonesia')");
9346     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ID', 'region', 'id', 'Indonesia')");
9347
9348     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'IS', 'region', 'Iceland','2014-10-30')");
9349     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IS', 'region', 'en', 'Iceland')");
9350     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IS', 'region', 'is', 'Ísland')");
9351
9352     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'IT', 'region', 'Italy','2014-10-30')");
9353     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IT', 'region', 'en', 'Italy')");
9354     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IT', 'region', 'it', 'Italia')");
9355
9356     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'JP', 'region', 'Japan','2014-10-30')");
9357     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'JP', 'region', 'en', 'Japan')");
9358     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'JP', 'region', 'ja', '日本')");
9359
9360     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KE', 'region', 'Kenya','2014-10-30')");
9361     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KE', 'region', 'en', 'Kenya')");
9362     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KE', 'region', 'rw', 'Kenya')");
9363
9364     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KH', 'region', 'Cambodia','2014-10-30')");
9365     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KH', 'region', 'en', 'Cambodia')");
9366     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KH', 'region', 'km', 'កម្ពុជា')");
9367
9368     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KP', 'region', 'North Korea','2014-10-30')");
9369     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KP', 'region', 'en', 'North Korea')");
9370     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KP', 'region', 'ko', '조선민주주의인민공화국')");
9371
9372     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'LK', 'region', 'Sri Lanka','2014-10-30')");
9373     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'LK', 'region', 'en', 'Sri Lanka')");
9374     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'LK', 'region', 'ta', 'இலங்கை')");
9375
9376     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'MY', 'region', 'Malaysia','2014-10-30')");
9377     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'MY', 'region', 'en', 'Malaysia')");
9378     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'MY', 'region', 'ms', 'Malaysia')");
9379
9380     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NE', 'region', 'Niger','2014-10-30')");
9381     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NE', 'region', 'en', 'Niger')");
9382     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NE', 'region', 'ne', 'Niger')");
9383
9384     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NL', 'region', 'Netherlands','2014-10-30')");
9385     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NL', 'region', 'en', 'Netherlands')");
9386     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NL', 'region', 'nl', 'Nederland')");
9387
9388     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NO', 'region', 'Norway','2014-10-30')");
9389     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'en', 'Norway')");
9390     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'ne', 'Noreg')");
9391     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'nn', 'Noreg')");
9392
9393     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PH', 'region', 'Philippines','2014-10-30')");
9394     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PH', 'region', 'en', 'Philippines')");
9395     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PH', 'region', 'tl', 'Pilipinas')");
9396
9397     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PK', 'region', 'Pakistan','2014-10-30')");
9398     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PK', 'region', 'en', 'Pakistan')");
9399     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PK', 'region', 'sd', 'پاكستان')");
9400
9401     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PL', 'region', 'Poland','2014-10-30')");
9402     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PL', 'region', 'en', 'Poland')");
9403     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PL', 'region', 'pl', 'Polska')");
9404
9405     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PT', 'region', 'Portugal','2014-10-30')");
9406     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PT', 'region', 'en', 'Portugal')");
9407     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PT', 'region', 'pt', 'Portugal')");
9408
9409     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RO', 'region', 'Romania','2014-10-30')");
9410     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RO', 'region', 'en', 'Romania')");
9411     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RO', 'region', 'ro', 'România')");
9412
9413     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RU', 'region', 'Russia','2014-10-30')");
9414     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RU', 'region', 'en', 'Russia')");
9415     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RU', 'region', 'ru', 'Россия')");
9416
9417     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RW', 'region', 'Rwanda','2014-10-30')");
9418     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RW', 'region', 'en', 'Rwanda')");
9419     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RW', 'region', 'rw', 'Rwanda')");
9420
9421     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SE', 'region', 'Sweden','2014-10-30')");
9422     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SE', 'region', 'en', 'Sweden')");
9423     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SE', 'region', 'sv', 'Sverige')");
9424
9425     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SI', 'region', 'Slovenia','2014-10-30')");
9426     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SI', 'region', 'en', 'Slovenia')");
9427     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SI', 'region', 'sl', 'Slovenija')");
9428
9429     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SK', 'region', 'Slovakia','2014-10-30')");
9430     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SK', 'region', 'en', 'Slovakia')");
9431     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SK', 'region', 'sk', 'Slovensko')");
9432
9433     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TH', 'region', 'Thailand','2014-10-30')");
9434     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TH', 'region', 'en', 'Thailand')");
9435     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TH', 'region', 'th', 'ประเทศไทย')");
9436
9437     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TR', 'region', 'Turkey','2014-10-30')");
9438     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TR', 'region', 'en', 'Turkey')");
9439     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TR', 'region', 'tr', 'Türkiye')");
9440
9441     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TW', 'region', 'Taiwan','2014-10-30')");
9442     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TW', 'region', 'en', 'Taiwan')");
9443     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TW', 'region', 'zh', '台灣')");
9444
9445     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'UA', 'region', 'Ukraine','2014-10-30')");
9446     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'UA', 'region', 'en', 'Ukraine')");
9447     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'UA', 'region', 'uk', 'Україна')");
9448
9449     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'VN', 'region', 'Vietnam','2014-10-30')");
9450     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'VN', 'region', 'en', 'Vietnam')");
9451     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'VN', 'region', 'vi', 'Việt Nam')");
9452
9453     print "Upgrade to $DBversion done (Bug 12250: Update descriptions for languages, scripts and regions)\n";
9454     SetVersion($DBversion);
9455 }
9456
9457 $DBversion = "3.17.00.050";
9458 if ( CheckVersion($DBversion) ) {
9459     $dbh->do(q|
9460         INSERT INTO permissions (module_bit, code, description) VALUES
9461           (13, 'records_batchdel', 'Perform batch deletion of records (bibliographic or authority)')
9462     |);
9463     print "Upgrade to $DBversion done (Bug 12403: Add permission tools_records_batchdelitem)\n";
9464     SetVersion($DBversion);
9465 }
9466
9467 $DBversion = "3.17.00.051";
9468 if ( CheckVersion($DBversion) ) {
9469     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('GoogleIndicTransliteration','0','','GoogleIndicTransliteration on the OPAC.','YesNo')");
9470     print "Upgrade to $DBversion done (Bug 13211: Added system preferences GoogleIndicTransliteration on the OPAC)\n";
9471     SetVersion($DBversion);
9472 }
9473
9474 $DBversion = "3.17.00.052";
9475 if ( CheckVersion($DBversion) ) {
9476     $dbh->do(q{
9477         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');
9478     });
9479
9480     $dbh->do(q{
9481         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');
9482    });
9483    print "Upgrade to $DBversion done (Bug 9043: Add system preference OpacAdvSearchOptions and OpacAdvSearchMoreOptions)\n";
9484    SetVersion ($DBversion);
9485 }
9486
9487 $DBversion = "3.17.00.053";
9488 if ( CheckVersion($DBversion) ) {
9489     $dbh->do(q{
9490         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)');
9491     });
9492
9493     $dbh->do(q{
9494         INSERT INTO permissions (module_bit, code, description) VALUES ('9', 'delete_all_items', 'Delete all items at once');
9495     });
9496
9497     $dbh->do(q{
9498         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)');
9499     });
9500
9501     # The delete_all_items permission should be added to users having the edit_items permission.
9502     $dbh->do(q{
9503         INSERT INTO user_permissions (borrowernumber, module_bit, code) SELECT borrowernumber, module_bit, "delete_all_items" FROM user_permissions WHERE code="edit_items";
9504     });
9505
9506     # Add 2 new prefs
9507     $dbh->do(q{
9508         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');
9509     });
9510
9511     $dbh->do(q{
9512         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');
9513     });
9514
9515     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";
9516     SetVersion($DBversion);
9517 }
9518
9519 $DBversion = "3.17.00.054";
9520 if (CheckVersion($DBversion)) {
9521     $dbh->do(q{
9522         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
9523         ('AllowRenewalIfOtherItemsAvailable','0',NULL,'If enabled, allow a patron to renew an item with unfilled holds if other available items can fill that hold.','YesNo')
9524     });
9525     print "Upgrade to $DBversion done (Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds)\n";
9526     SetVersion($DBversion);
9527 }
9528
9529 $DBversion = "3.17.00.055";
9530 if ( CheckVersion($DBversion) ) {
9531     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBEnable', '0', NULL, 'Enable communication with the Norwegian national patron database.', 'YesNo')");
9532     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBEndpoint', '', NULL, 'Which NL endpoint to use.', 'Free')");
9533     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBUsername', '', NULL, 'Username for communication with the Norwegian national patron database.', 'Free')");
9534     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBPassword', '', NULL, 'Password for communication with the Norwegian national patron database.', 'Free')");
9535     $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')");
9536     $dbh->do("
9537 CREATE TABLE borrower_sync (
9538     borrowersyncid int(11) NOT NULL AUTO_INCREMENT,
9539     borrowernumber int(11) NOT NULL,
9540     synctype varchar(32) NOT NULL,
9541     sync tinyint(1) NOT NULL DEFAULT '0',
9542     syncstatus varchar(10) DEFAULT NULL,
9543     lastsync varchar(50) DEFAULT NULL,
9544     hashed_pin varchar(64) DEFAULT NULL,
9545     PRIMARY KEY (borrowersyncid),
9546     KEY borrowernumber (borrowernumber),
9547     CONSTRAINT borrower_sync_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
9548 ) ENGINE=InnoDB DEFAULT CHARSET=utf8"
9549 );
9550     print "Upgrade to $DBversion done (Bug 11401 - Add support for Norwegian national library card)\n";
9551     SetVersion($DBversion);
9552 }
9553
9554 $DBversion = "3.17.00.056";
9555 if ( CheckVersion($DBversion) ) {
9556     $dbh->do(q{
9557         UPDATE systempreferences SET value = 'pubdate,itemtype,language,sorting,location' WHERE variable='OpacAdvSearchOptions'
9558     });
9559
9560     $dbh->do(q{
9561         UPDATE systempreferences SET value = 'pubdate,itemtype,language,subtype,sorting,location' WHERE variable='OpacAdvSearchMoreOptions'
9562     });
9563
9564     print "Upgrade to $DBversion done (Bug 9043 - Update the values for OpacAdvSearchOptions and OpacAdvSearchOptions)\n";
9565     SetVersion($DBversion);
9566 }
9567
9568 $DBversion = "3.17.00.057";
9569 if ( CheckVersion($DBversion) ) {
9570     print "Upgrade to $DBversion done (Koha 3.18 beta)\n";
9571     SetVersion ($DBversion);
9572 }
9573
9574 $DBversion = "3.17.00.058";
9575 if( CheckVersion($DBversion) ){
9576     $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')");
9577     $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')");
9578     $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')");
9579     print "Upgrade to $DBversion done (Bug 8337: System preferences for longoverdue cron)\n";
9580     SetVersion($DBversion);
9581 }
9582
9583 $DBversion = "3.17.00.059";
9584 if ( CheckVersion($DBversion) ) {
9585     $dbh->do(q{
9586         UPDATE permissions SET description = "Add and delete budgets (but can't modifiy budgets)" WHERE description = "Add and delete budgets (but cant modify budgets)";
9587     });
9588     print "Upgrade to $DBversion done (Bug 10749: Fix typo in budget_add_del permission description)\n";
9589     SetVersion ($DBversion);
9590 }
9591
9592 $DBversion = "3.17.00.060";
9593 if ( CheckVersion($DBversion) ) {
9594     my $count_l = $dbh->selectcol_arrayref(q|
9595         SELECT COUNT(*) FROM letter WHERE message_transport_type='feed'
9596     |);
9597     my $count_mq = $dbh->selectcol_arrayref(q|
9598         SELECT COUNT(*) FROM message_queue WHERE message_transport_type='feed'
9599     |);
9600     my $count_ott = $dbh->selectcol_arrayref(q|
9601         SELECT COUNT(*) FROM overduerules_transport_types WHERE message_transport_type='feed'
9602     |);
9603     my $count_mt = $dbh->selectcol_arrayref(q|
9604         SELECT COUNT(*) FROM message_transports WHERE message_transport_type='feed'
9605     |);
9606     my $count_bmtp = $dbh->selectcol_arrayref(q|
9607         SELECT COUNT(*) FROM borrower_message_transport_preferences WHERE message_transport_type='feed'
9608     |);
9609
9610     my $deleted = 0;
9611     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 ) {
9612         $deleted = $dbh->do(q|
9613             DELETE FROM message_transport_types where message_transport_type='feed'
9614         |);
9615         $deleted = $deleted ne '0E0' ? 1 : 0;
9616     }
9617
9618     print "Upgrade to $DBversion done (Bug 12298: Delete the 'feed' message transport type " . ($deleted ? '(deleted!)' : '(not deleted)') . ")\n";
9619     SetVersion($DBversion);
9620 }
9621
9622 $DBversion = "3.18.00.000";
9623 if ( CheckVersion($DBversion) ) {
9624     print "Upgrade to $DBversion done (3.18.0 release)\n";
9625     SetVersion($DBversion);
9626 }
9627
9628 $DBversion = "3.19.00.000";
9629 if ( CheckVersion($DBversion) ) {
9630     print "Upgrade to $DBversion done (there's life after 3.18)\n";
9631     SetVersion ($DBversion);
9632 }
9633
9634 $DBversion = "3.19.00.001";
9635 if ( CheckVersion($DBversion) ) {
9636     $dbh->do("
9637         UPDATE systempreferences
9638         SET options = 'public|school|academic|research|private|societyAssociation|corporate|government|religiousOrg|subscription'
9639         WHERE variable = 'UsageStatsLibraryType'
9640     ");
9641     if ( C4::Context->preference("UsageStatsLibraryType") eq "university" ) {
9642         C4::Context->set_preference("UsageStatsLibraryType", "academic")
9643     }
9644     print "Upgrade to $DBversion done (Bug 13436: Add more options to UsageStatsLibraryType)\n";
9645     SetVersion ($DBversion);
9646 }
9647
9648 $DBversion = "3.19.00.002";
9649 if ( CheckVersion($DBversion) ) {
9650     $dbh->do(q|
9651         UPDATE suggestions SET branchcode="" WHERE branchcode="__ANY__"
9652     |);
9653     print "upgrade to $DBversion done (Bug 10753: replace __ANY__ with empty string in suggestions.branchcode)\n";
9654     SetVersion ($DBversion);
9655 }
9656
9657 $DBversion = "3.19.00.003";
9658 if ( CheckVersion($DBversion) ) {
9659     my ($count) = $dbh->selectrow_array("SELECT COUNT(*) FROM borrowers GROUP BY userid HAVING COUNT(userid) > 1");
9660
9661     if ( $count ) {
9662         print "Upgrade to $DBversion done (Bug 1861 - Unique patrons logins not (totally) enforced) FAILED!\n";
9663         print "Your database has users with duplicate user logins. Please have your administrator deduplicate your user logins.\n";
9664         print "Afterward, your Koha administrator should execute the following database query: ALTER TABLE borrowers DROP INDEX userid, ADD UNIQUE userid (userid)";
9665     } else {
9666         $dbh->do(q{
9667             ALTER TABLE borrowers
9668                 DROP INDEX userid ,
9669                 ADD UNIQUE userid (userid)
9670         });
9671         print "Upgrade to $DBversion done (Bug 1861: Unique patrons logins not (totally) enforced)\n";
9672     }
9673
9674     SetVersion($DBversion);
9675 }
9676
9677 $DBversion = "3.19.00.004";
9678 if ( CheckVersion($DBversion) ) {
9679     my $pref_value = C4::Context->preference('OpacExportOptions');
9680     $pref_value =~ s/\|/,/g; # multiple is separated by ,
9681     $dbh->do(q{
9682         UPDATE systempreferences
9683             SET value = ?,
9684                 type = 'multiple'
9685         WHERE variable = 'OpacExportOptions'
9686     }, {}, $pref_value );
9687     print "Upgrade to $DBversion done (Bug 13346: OpacExportOptions is now multiple)\n";
9688     SetVersion ($DBversion);
9689 }
9690
9691 $DBversion = "3.19.00.005";
9692 if(CheckVersion($DBversion)) {
9693     $dbh->do(q{
9694         ALTER TABLE authorised_values MODIFY COLUMN category VARCHAR(32) NOT NULL DEFAULT ''
9695     });
9696
9697     $dbh->do(q{
9698         ALTER TABLE borrower_attribute_types MODIFY COLUMN authorised_value_category VARCHAR(32) DEFAULT NULL
9699     });
9700
9701     print "Upgrade to $DBversion done (Bug 13379: Modify authorised_values.category to varchar(32))\n";
9702     SetVersion($DBversion);
9703 }
9704
9705 $DBversion = "3.19.00.006";
9706 if ( CheckVersion($DBversion) ) {
9707     $dbh->do(q|SET foreign_key_checks = 0|);
9708     my $sth = $dbh->table_info( '','','','TABLE' );
9709     my ( $cat, $schema, $name, $type, $remarks );
9710     while ( ( $cat, $schema, $name, $type, $remarks ) = $sth->fetchrow_array ) {
9711         my $table_sth = $dbh->prepare(qq|SHOW CREATE TABLE $name|);
9712         $table_sth->execute;
9713         my @table = $table_sth->fetchrow_array;
9714         unless ( $table[1] =~ /COLLATE=utf8mb4_unicode_ci/ ) { #catches utf8mb4 collated tables
9715             if ( $name eq 'marc_subfield_structure' ) {
9716                 $dbh->do(q|
9717                     ALTER TABLE marc_subfield_structure
9718                     MODIFY COLUMN tagfield varchar(3) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9719                     MODIFY COLUMN tagsubfield varchar(1) COLLATE utf8_bin NOT NULL DEFAULT '',
9720                     MODIFY COLUMN liblibrarian varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9721                     MODIFY COLUMN libopac varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9722                     MODIFY COLUMN kohafield varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
9723                     MODIFY COLUMN authorised_value varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
9724                     MODIFY COLUMN authtypecode varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
9725                     MODIFY COLUMN value_builder varchar(80) COLLATE utf8_unicode_ci DEFAULT NULL,
9726                     MODIFY COLUMN frameworkcode varchar(4) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9727                     MODIFY COLUMN seealso varchar(1100) COLLATE utf8_unicode_ci DEFAULT NULL,
9728                     MODIFY COLUMN link varchar(80) COLLATE utf8_unicode_ci DEFAULT NULL
9729                 |);
9730             }
9731             else {
9732                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci|);
9733             }
9734         }
9735     }
9736     $dbh->do(q|SET foreign_key_checks = 1|);;
9737
9738     print "Upgrade to $DBversion done (Bug 11944: Convert DB tables to utf8_unicode_ci)\n";
9739     SetVersion($DBversion);
9740 }
9741
9742 $DBversion = "3.19.00.007";
9743 if ( CheckVersion($DBversion) ) {
9744     my $orphan_budgets = $dbh->selectall_arrayref(q|
9745         SELECT budget_id, budget_name, budget_code
9746         FROM aqbudgets
9747         WHERE   budget_parent_id IS NOT NULL
9748             AND budget_parent_id NOT IN (
9749                 SELECT DISTINCT budget_id FROM aqbudgets
9750             )
9751     |, { Slice => {} } );
9752
9753     if ( @$orphan_budgets ) {
9754         for my $b ( @$orphan_budgets ) {
9755             print "Fund $b->{budget_name} (code:$b->{budget_code}, id:$b->{budget_id}) does not have a parent, it may cause problem\n";
9756         }
9757         print "Upgrade to $DBversion done (Bug 12905: Check budget integrity: FAIL)\n";
9758     } else {
9759         print "Upgrade to $DBversion done (Bug 12905: Check budget integrity: OK)\n";
9760     }
9761     SetVersion($DBversion);
9762 }
9763
9764 $DBversion = "3.19.00.008";
9765 if ( CheckVersion($DBversion) ) {
9766     my $number_of_orders_not_linked = $dbh->selectcol_arrayref(q|
9767         SELECT COUNT(*)
9768         FROM aqorders o
9769         WHERE NOT EXISTS (
9770             SELECT NULL
9771             FROM aqbudgets b
9772             WHERE b.budget_id = o.budget_id
9773         );
9774     |);
9775
9776     if ( $number_of_orders_not_linked->[0] > 0 ) {
9777         $dbh->do(q|
9778             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)
9779         |);
9780         my $budget_period_id = $dbh->last_insert_id( undef, undef, 'aqbudgetperiods', undef );
9781         $dbh->do(qq|
9782             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 );
9783         |);
9784         my $budget_id = $dbh->last_insert_id( undef, undef, 'aqbudgets', undef );
9785         $dbh->do(qq|
9786             UPDATE aqorders o
9787             SET budget_id = $budget_id
9788             WHERE NOT EXISTS (
9789                 SELECT NULL
9790                 FROM aqbudgets b
9791                 WHERE b.budget_id = o.budget_id
9792             )
9793         |);
9794     }
9795
9796     $dbh->do(q|
9797         ALTER TABLE aqorders
9798         ADD CONSTRAINT aqorders_budget_id_fk FOREIGN KEY (budget_id) REFERENCES aqbudgets(budget_id) ON DELETE CASCADE ON UPDATE CASCADE
9799     |);
9800
9801     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";
9802     SetVersion($DBversion);
9803 }
9804
9805 $DBversion = "3.19.00.009";
9806 if ( CheckVersion($DBversion) ) {
9807     $dbh->do(q|
9808         UPDATE suggestions s SET s.budgetid = NULL
9809         WHERE NOT EXISTS (
9810             SELECT NULL
9811             FROM aqbudgets b
9812             WHERE b.budget_id = s.budgetid
9813         );
9814     |);
9815
9816     $dbh->do(q|
9817         ALTER TABLE suggestions
9818         ADD CONSTRAINT suggestions_budget_id_fk FOREIGN KEY (budgetid) REFERENCES aqbudgets(budget_id) ON DELETE SET NULL ON UPDATE CASCADE
9819     |);
9820
9821     print "Upgrade to $DBversion done (Bug 13007: Add new foreign key suggestions.budgetid)\n";
9822     SetVersion($DBversion);
9823 }
9824
9825 $DBversion = "3.19.00.010";
9826 if ( CheckVersion($DBversion) ) {
9827     $dbh->do(q|
9828         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
9829         VALUES('SessionRestrictionByIP','1','Check for Change in  Remote IP address for Session Security. Disable when remote ip address changes frequently.','','YesNo')
9830     |);
9831     print "Upgrade to $DBversion done (Bug 5511: SessionRestrictionByIP)\n";
9832     SetVersion ($DBversion);
9833 }
9834
9835 $DBversion = "3.19.00.011";
9836 if ( CheckVersion($DBversion) ) {
9837     $dbh->do(q|
9838         INSERT INTO userflags (bit, flag, flagdesc, defaulton) VALUES
9839         (20, 'lists', 'Lists', 0)
9840     |);
9841     $dbh->do(q|
9842         INSERT INTO permissions (module_bit, code, description) VALUES
9843         (20, 'delete_public_lists', 'Delete public lists')
9844     |);
9845     print "Upgrade to $DBversion done (Bug 13417: Add permission to delete public lists)\n";
9846     SetVersion ($DBversion);
9847 }
9848
9849 $DBversion = "3.19.00.012";
9850 if(CheckVersion($DBversion)) {
9851     $dbh->do(q{
9852         ALTER TABLE biblioitems MODIFY COLUMN marcxml longtext
9853     });
9854
9855     $dbh->do(q{
9856         ALTER TABLE deletedbiblioitems MODIFY COLUMN marcxml longtext
9857     });
9858
9859     print "Upgrade to $DBversion done (Bug 13523 Remove NOT NULL restriction on field marcxml due to mysql STRICT_TRANS_TABLES)\n";
9860     SetVersion ($DBversion);
9861 }
9862
9863 $DBversion = "3.19.00.013";
9864 if ( CheckVersion($DBversion) ) {
9865     $dbh->do(q|
9866         INSERT INTO permissions (module_bit, code, description) VALUES
9867           (13, 'records_batchmod', 'Perform batch modification of records (biblios or authorities)')
9868     |);
9869     print "Upgrade to $DBversion done (Bug 11395: Add permission tools_records_batchmod)\n";
9870     SetVersion($DBversion);
9871 }
9872
9873 $DBversion = "3.19.00.014";
9874 if ( CheckVersion($DBversion) ) {
9875     $dbh->do(q|
9876         CREATE TABLE aqorder_users (
9877             ordernumber int(11) NOT NULL,
9878             borrowernumber int(11) NOT NULL,
9879             PRIMARY KEY (ordernumber, borrowernumber),
9880             CONSTRAINT aqorder_users_ibfk_1 FOREIGN KEY (ordernumber) REFERENCES aqorders (ordernumber) ON DELETE CASCADE ON UPDATE CASCADE,
9881             CONSTRAINT aqorder_users_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
9882         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
9883     |);
9884
9885     $dbh->do(q|
9886         INSERT INTO letter(module, code, branchcode, name, title, content, message_transport_type)
9887         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')
9888     |);
9889     print "Upgrade to $DBversion done (Bug 12648: Add letter ACQ_NOTIF_ON_RECEIV )\n";
9890     SetVersion ($DBversion);
9891 }
9892
9893 $DBversion = "3.19.00.015";
9894 if ( CheckVersion($DBversion) ) {
9895     $dbh->do(q|
9896         ALTER TABLE search_history ADD COLUMN id INT(11) NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY(id);
9897     |);
9898     print "Upgrade to $DBversion done (Bug 11430: Add primary key for search_history)\n";
9899     SetVersion($DBversion);
9900 }
9901
9902 $DBversion = "3.19.00.016";
9903 if(CheckVersion($DBversion)) {
9904     my @order_cancellation_reason = $dbh->selectrow_array("SELECT count(*) FROM authorised_values WHERE category='ORDER_CANCELLATION_REASON'");
9905     if ($order_cancellation_reason[0] == 0) {
9906         $dbh->do(q{
9907             INSERT INTO authorised_values (category, authorised_value, lib) VALUES
9908              ('ORDER_CANCELLATION_REASON', 0, 'No reason provided'),
9909              ('ORDER_CANCELLATION_REASON', 1, 'Out of stock'),
9910              ('ORDER_CANCELLATION_REASON', 2, 'Restocking')
9911         });
9912
9913         my $already_existing_reasons = $dbh->selectcol_arrayref(q{
9914             SELECT DISTINCT( cancellationreason )
9915             FROM aqorders;
9916         }, { Slice => {} });
9917
9918         my $update_orders_sth = $dbh->prepare(q{
9919             UPDATE aqorders
9920             SET cancellationreason = ?
9921             WHERE cancellationreason = ?
9922         });
9923
9924         my $insert_av_sth = $dbh->prepare(q{
9925             INSERT INTO authorised_values (category, authorised_value, lib) VALUES
9926              ('ORDER_CANCELLATION_REASON', ?, ?)
9927         });
9928         my $i = 3;
9929         for my $reason ( @$already_existing_reasons ) {
9930             next unless $reason;
9931             $insert_av_sth->execute( $i, $reason );
9932             $update_orders_sth->execute( $i, $reason );
9933             $i++;
9934         }
9935         print "Upgrade to $DBversion done (Bug 13380: Add the ORDER_CANCELLATION_REASON authorised value)\n";
9936     }
9937     else {
9938         print "Upgrade to $DBversion done (Bug 13380: ORDER_CANCELLATION_REASON authorised value already existed from earlier update!)\n";
9939     }
9940
9941     SetVersion($DBversion);
9942 }
9943
9944 $DBversion = '3.19.00.017';
9945 if ( CheckVersion($DBversion) ) {
9946     # First create the column
9947     $dbh->do("ALTER TABLE issuingrules ADD onshelfholds tinyint(1) default 0 NOT NULL");
9948     # Now update the column
9949     if (C4::Context->preference("AllowOnShelfHolds")){
9950         # Pref is on, set allow for all rules
9951         $dbh->do("UPDATE issuingrules SET onshelfholds=1");
9952     } else {
9953         # If the preference is not set, leave off
9954         $dbh->do("UPDATE issuingrules SET onshelfholds=0");
9955     }
9956     # Remove from the systempreferences table
9957     $dbh->do("DELETE FROM systempreferences WHERE variable = 'AllowOnShelfHolds'");
9958
9959     # First create the column
9960     $dbh->do("ALTER TABLE issuingrules ADD opacitemholds char(1) DEFAULT 'N' NOT NULL");
9961     # Now update the column
9962     my $opacitemholds = C4::Context->preference("OPACItemHolds") || '';
9963     if (lc ($opacitemholds) eq 'force') {
9964         $opacitemholds = 'F';
9965     }
9966     else {
9967         $opacitemholds = $opacitemholds ? 'Y' : 'N';
9968     }
9969     # Set allow for all rules
9970     $dbh->do("UPDATE issuingrules SET opacitemholds='$opacitemholds'");
9971
9972     # Remove from the systempreferences table
9973     $dbh->do("DELETE FROM systempreferences WHERE variable = 'OPACItemHolds'");
9974
9975     print "Upgrade to $DBversion done (Bug 5786: Move AllowOnShelfHolds to circulation matrix; Move OPACItemHolds system preference to circulation matrix)\n";
9976     SetVersion ($DBversion);
9977 }
9978
9979
9980 $DBversion = "3.19.00.018";
9981 if ( CheckVersion($DBversion) ) {
9982     $dbh->do(q|
9983         UPDATE systempreferences set variable="OpacAdditionalStylesheet" WHERE variable="opaccolorstylesheet"
9984     |);
9985     print "Upgrade to $DBversion done (Bug 10328: Rename opaccolorstylesheet to OpacAdditionalStylesheet\n";
9986     SetVersion ($DBversion);
9987 }
9988
9989 $DBversion = "3.19.00.019";
9990 if ( CheckVersion($DBversion) ) {
9991     $dbh->do(q{
9992         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
9993         VALUES('Coce','0', 'If on, enables cover retrieval from the configured Coce server', NULL, 'YesNo')
9994     });
9995     $dbh->do(q{
9996         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
9997         VALUES('CoceHost', NULL, 'Coce server URL', NULL,'Free')
9998     });
9999     $dbh->do(q{
10000         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
10001         VALUES('CoceProviders', NULL, 'Coce providers', 'aws,gb,ol', 'multiple')
10002     });
10003     print "Upgrade to $DBversion done (Bug 9580: Cover image from Coce, a remote image URL cache)\n";
10004     SetVersion($DBversion);
10005 }
10006
10007 $DBversion = "3.19.00.020";
10008 if ( CheckVersion($DBversion) ) {
10009     $dbh->do(q|
10010         ALTER TABLE aqorders DROP COLUMN supplierreference;
10011     |);
10012
10013     print "Upgrade to $DBversion done (Bug 11008: DROP column aqorders.supplierreference)\n";
10014     SetVersion($DBversion);
10015 }
10016
10017 $DBversion = "3.19.00.021";
10018 if ( CheckVersion($DBversion) ) {
10019     $dbh->do(q|
10020         ALTER TABLE issues DROP COLUMN issuingbranch
10021     |);
10022     $dbh->do(q|
10023         ALTER TABLE old_issues DROP COLUMN issuingbranch
10024     |);
10025     print "Upgrade to $DBversion done (Bug 2806: Remove issuingbranch columns)\n";
10026     SetVersion ($DBversion);
10027 }
10028
10029 $DBversion = '3.19.00.022';
10030 if ( CheckVersion($DBversion) ) {
10031     $dbh->do(q{
10032         ALTER TABLE suggestions DROP COLUMN mailoverseeing;
10033     });
10034     print "Upgrade to $DBversion done (Bug 13006: Drop column suggestion.mailoverseeing)\n";
10035     SetVersion($DBversion);
10036 }
10037
10038 $DBversion = "3.19.00.023";
10039 if ( CheckVersion($DBversion) ) {
10040     $dbh->do(q|
10041         DELETE FROM systempreferences where variable = 'AddPatronLists'
10042     |);
10043     print "Upgrade to $DBversion done (Bug 13497: Remove the AddPatronLists system preferences)\n";
10044     SetVersion ($DBversion);
10045 }
10046
10047 $DBversion = "3.19.00.024";
10048 if ( CheckVersion($DBversion) ) {
10049     $dbh->do(qq|DROP table patroncards;|);
10050     print "Upgrade to $DBversion done (Bug 13539: Remove table patroncards from database as it's no longer in use)\n";
10051     SetVersion ($DBversion);
10052 }
10053
10054 $DBversion = "3.19.00.025";
10055 if ( CheckVersion($DBversion) ) {
10056     $dbh->do(q|
10057         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
10058         ('SearchWithISBNVariations','0',NULL,'If enabled, search on all variations of the ISBN','YesNo')
10059     |);
10060     print "Upgrade to $DBversion done (Bug 13528: Add the SearchWithISBNVariations syspref)\n";
10061     SetVersion ($DBversion);
10062 }
10063
10064 $DBversion = "3.19.00.026";
10065 if( CheckVersion($DBversion) ) {
10066     if ( C4::Context->preference('marcflavour') eq 'MARC21' ) {
10067     $dbh->do(q{
10068         INSERT IGNORE INTO auth_tag_structure (authtypecode, tagfield, liblibrarian, libopac, repeatable, mandatory, authorised_value) VALUES
10069         ('', '388', 'TIME PERIOD OF CREATION', 'TIME PERIOD OF CREATION', 1, 0, NULL);
10070     });
10071
10072     $dbh->do(q{
10073         INSERT IGNORE INTO auth_subfield_structure (authtypecode, tagfield, tagsubfield, liblibrarian, libopac, repeatable,
10074         mandatory, tab, authorised_value, value_builder, seealso, isurl, hidden, linkid, kohafield, frameworkcode) VALUES
10075         ('', '388', '0', 'Authority record control number or standard number', 'Authority record control number or standard number', 1, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10076         ('', '388', '2', 'Source of term', 'Source of term', 0, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10077         ('', '388', '3', 'Materials specified', 'Materials specified', 0, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10078         ('', '388', '6', 'Linkage', 'Linkage', 0, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10079         ('', '388', '8', 'Field link and sequence number', 'Field link and sequence number', 1, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10080         ('', '388', 'a', 'Time period of creation term', 'Time period of creation term', 1, 0, 3, NULL, NULL, NULL, 0, 0, '', '', '');
10081     });
10082
10083     $dbh->do(q{
10084         UPDATE IGNORE auth_subfield_structure SET repeatable = 1 WHERE tagsubfield = 'g' AND tagfield IN
10085         ('100','110','111','130','400','410','411','430','500','510','511','530','700','710','730');
10086     });
10087
10088     $dbh->do(q{
10089         INSERT IGNORE INTO auth_subfield_structure (authtypecode, tagfield, tagsubfield, liblibrarian, libopac, repeatable,
10090         mandatory, tab, authorised_value, value_builder, seealso, isurl, hidden, linkid, kohafield, frameworkcode) VALUES
10091         ('', '150', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 1, NULL, NULL, NULL, 0, 0, '', '', ''),
10092         ('', '151', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 1, NULL, NULL, NULL, 0, 0, '', '', ''),
10093         ('', '450', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 4, NULL, NULL, NULL, 0, 0, '', '', ''),
10094         ('', '451', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 4, NULL, NULL, NULL, 0, 0, '', '', ''),
10095         ('', '550', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 5, NULL, NULL, NULL, 0, 0, '', '', ''),
10096         ('', '551', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 5, NULL, NULL, NULL, 0, 0, '', '', ''),
10097         ('', '750', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10098         ('', '751', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10099         ('', '748', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10100         ('', '755', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10101         ('', '780', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10102         ('', '781', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10103         ('', '782', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10104         ('', '785', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10105         ('', '710', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10106         ('', '730', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10107         ('', '748', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10108         ('', '750', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10109         ('', '751', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10110         ('', '755', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10111         ('', '762', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10112         ('', '780', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10113         ('', '781', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10114         ('', '782', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10115         ('', '785', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10116         ('', '788', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', '');
10117     });
10118
10119     $dbh->do(q{
10120         UPDATE IGNORE auth_subfield_structure SET liblibrarian = 'Relationship information', libopac = 'Relationship information'
10121         WHERE tagsubfield = 'i' AND tagfield IN ('700','710','730','750','751','762');
10122     });
10123
10124     $dbh->do(q{
10125         UPDATE IGNORE auth_subfield_structure SET liblibrarian = 'Relationship code', libopac = 'Relationship code'
10126         WHERE tagsubfield = '4' AND tagfield IN ('700','710');
10127     });
10128
10129     $dbh->do(q{
10130         INSERT IGNORE INTO marc_tag_structure (tagfield, liblibrarian, libopac, repeatable, mandatory, authorised_value, frameworkcode) VALUES
10131         ('370', 'ASSOCIATED PLACE', 'ASSOCIATED PLACE', 1, 0, NULL, ''),
10132         ('388', 'TIME PERIOD OF CREATION', 'TIME PERIOD OF CREATION', 1, 0, NULL, '');
10133     });
10134
10135     $dbh->do(q{
10136         INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian, libopac, repeatable, mandatory,
10137         kohafield, tab, authorised_value, authtypecode, value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
10138         ('370', '0', 'Authority record control number or standard number', 'Authority record control number or standard number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10139         ('370', '2', 'Source of term', 'Source of term', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10140         ('370', '6', 'Linkage', 'Linkage', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10141         ('370', '8', 'Field link and sequence number', 'Field link and sequence number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10142         ('370', 'c', 'Associated country', 'Associated country', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10143         ('370', 'f', 'Other associated place', 'Other associated place', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10144         ('370', 'g', 'Place of origin of work', 'Place of origin of work', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10145         ('370', 's', 'Start period', 'Start period', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10146         ('370', 't', 'End period', 'End period', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10147         ('370', 'u', 'Uniform Resource Identifier', 'Uniform Resource Identifier', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10148         ('370', 'v', 'Source of information', 'Source of information', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10149         ('377', 'l', 'Language term', 'Language term', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10150         ('382', 's', 'Total number of performers', 'Total number of performers', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10151         ('388', '0', 'Authority record control number or standard number', 'Authority record control number or standard number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10152         ('388', '2', 'Source of term', 'Source of term', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10153         ('388', '3', ' Materials specified', ' Materials specified', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10154         ('388', '6', ' Linkage', ' Linkage', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10155         ('388', '8', 'Field link and sequence number', 'Field link and sequence number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10156         ('388', 'a', 'Time period of creation term', 'Time period of creation term', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10157         ('650', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, '', 6, '', '', '', 0, -1, '', '', '', NULL),
10158         ('651', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, '', 6, '', '', '', 0, -1, '', '', '', NULL);
10159     });
10160
10161     $dbh->do(q{
10162         UPDATE IGNORE marc_subfield_structure SET repeatable = 1 WHERE tagsubfield = 'g' AND
10163         tagfield IN ('100','110','111','130','240','243','246','247','600','610','611','630','700','710','711','730','800','810','811','830');
10164     });
10165     }
10166
10167     print "Upgrade to $DBversion done (Bug 13322: Update MARC21 frameworks to Update No. 19 - October 2014)\n";
10168     SetVersion($DBversion);
10169 }
10170
10171 $DBversion = '3.19.00.027';
10172 if ( CheckVersion($DBversion) ) {
10173     $dbh->do("ALTER TABLE items ADD COLUMN itemnotes_nonpublic MEDIUMTEXT AFTER itemnotes");
10174     $dbh->do("ALTER TABLE deleteditems ADD COLUMN itemnotes_nonpublic MEDIUMTEXT AFTER itemnotes");
10175     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";
10176     SetVersion($DBversion);
10177 }
10178
10179 $DBversion = "3.19.00.028";
10180 if( CheckVersion($DBversion) ) {
10181     eval {
10182         local $dbh->{PrintError} = 0;
10183         $dbh->do(q{
10184             ALTER TABLE issues DROP PRIMARY KEY
10185         });
10186     };
10187
10188     $dbh->do(q{
10189         ALTER TABLE old_issues ADD issue_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10190     });
10191
10192     $dbh->do(q{
10193         ALTER TABLE old_issues CHANGE issue_id issue_id INT( 11 ) NOT NULL
10194     });
10195
10196     $dbh->do(q{
10197         ALTER TABLE issues ADD issue_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10198     });
10199
10200     $dbh->do(q{
10201         UPDATE issues SET issue_id = issue_id + ( SELECT COUNT(*) FROM old_issues ) ORDER BY issue_id DESC
10202     });
10203
10204     my $max_issue_id = $schema->resultset('Issue')->get_column('issue_id')->max();
10205     if ($max_issue_id) {
10206         $max_issue_id++;
10207         $dbh->do(qq{
10208             ALTER TABLE issues AUTO_INCREMENT = $max_issue_id
10209         });
10210     }
10211
10212     print "Upgrade to $DBversion done (Bug 13790: Add unique id issue_id to issues and oldissues tables)\n";
10213     SetVersion($DBversion);
10214 }
10215
10216 $DBversion = "3.19.00.029";
10217 if ( CheckVersion($DBversion) ) {
10218     $dbh->do(q|
10219          ALTER TABLE sessions CHANGE COLUMN a_session a_session MEDIUMTEXT
10220     |);
10221     print "Upgrade to $DBversion done (Bug 13606: Upgrade sessions.a_session to MEDIUMTEXT)\n";
10222     SetVersion($DBversion);
10223 }
10224
10225 $DBversion = "3.19.00.030";
10226 if ( CheckVersion($DBversion) ) {
10227     $dbh->do(q|
10228 UPDATE language_subtag_registry SET subtag = 'kn' WHERE subtag = 'ka' AND description = 'Kannada';
10229     |);
10230     $dbh->do(q|
10231 UPDATE language_rfc4646_to_iso639 SET rfc4646_subtag = 'kn' WHERE rfc4646_subtag = 'ka' AND iso639_2_code = 'kan';
10232     |);
10233     $dbh->do(q|
10234 UPDATE language_descriptions SET subtag = 'kn', lang = 'kn' WHERE subtag = 'ka' AND lang = 'ka' AND description = 'ಕನ್ನಡ';
10235     |);
10236     $dbh->do(q|
10237 UPDATE language_descriptions SET subtag = 'kn' WHERE subtag = 'ka' AND description = 'Kannada';
10238     |);
10239     $dbh->do(q|
10240 INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ka', 'language', 'Georgian','2015-04-20');
10241     |);
10242     $dbh->do(q|
10243 DELETE FROM language_subtag_registry
10244        WHERE NOT id IN
10245          (SELECT id FROM
10246            (SELECT MIN(id) as id,subtag,type,description,added
10247             FROM language_subtag_registry
10248             GROUP BY subtag,type,description,added)
10249            AS subtable);
10250     |);
10251     $dbh->do(q|
10252 INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ka', 'geo');
10253     |);
10254     $dbh->do(q|
10255 DELETE FROM language_rfc4646_to_iso639
10256        WHERE NOT id IN
10257          (SELECT id FROM
10258            (SELECT MIN(id) as id,rfc4646_subtag,iso639_2_code
10259             FROM language_rfc4646_to_iso639
10260             GROUP BY rfc4646_subtag,iso639_2_code)
10261            AS subtable);
10262     |);
10263     $dbh->do(q|
10264 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'ka', 'ქართული');
10265     |);
10266     $dbh->do(q|
10267 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'en', 'Georgian');
10268     |);
10269     $dbh->do(q|
10270 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'fr', 'Géorgien');
10271     |);
10272     $dbh->do(q|
10273 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'de', 'Georgisch');
10274     |);
10275     $dbh->do(q|
10276 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'es', 'Georgiano');
10277     |);
10278     $dbh->do(q|
10279 DELETE FROM language_descriptions
10280        WHERE NOT id IN
10281          (SELECT id FROM
10282            (SELECT MIN(id) as id,subtag,type,lang,description
10283             FROM language_descriptions GROUP BY subtag,type,lang,description)
10284            AS subtable);
10285     |);
10286     print "Upgrade to $DBversion done (Bug 14030: Add Georgian language and fix Kannada language code)\n";
10287     SetVersion($DBversion);
10288 }
10289
10290 $DBversion = "3.19.00.031";
10291 if ( CheckVersion($DBversion) ) {
10292     $dbh->do(q{
10293         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10294         VALUES('IdRef','0','Disable/enable the IdRef webservice from the OPAC detail page.',NULL,'YesNo')
10295     });
10296     print "Upgrade to $DBversion done (Bug 8992: Add system preference IdRef))\n";
10297     SetVersion($DBversion);
10298 }
10299
10300 $DBversion = "3.19.00.032";
10301 if ( CheckVersion($DBversion) ) {
10302     $dbh->do(q|
10303         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10304         VALUES('AddressFormat','us','Choose format to display postal addresses','','Choice')
10305     |);
10306     print "Upgrade to $DBversion done (Bug 4041: Address Format as a I18N/L10N system preference\n";
10307     SetVersion ($DBversion);
10308 }
10309
10310 $DBversion = "3.19.00.033";
10311 if ( CheckVersion($DBversion) ) {
10312     $dbh->do(q|
10313         ALTER TABLE auth_header
10314         CHANGE COLUMN datemodified modification_time TIMESTAMP NOT NULL default CURRENT_TIMESTAMP
10315     |);
10316     $dbh->do(q|
10317         ALTER TABLE auth_header
10318         CHANGE COLUMN modification_time modification_time TIMESTAMP NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP
10319     |);
10320     print "Upgrade to $DBversion done (Bug 11165: Update auth_header.datemodified when updated)\n";
10321     SetVersion ($DBversion);
10322 }
10323
10324 $DBversion = "3.19.00.034";
10325 if ( CheckVersion($DBversion) ) {
10326     $dbh->do(q|
10327         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10328         VALUES('CardnumberLength', '', '', 'Set a length for card numbers.', 'Free')
10329     |);
10330     print "Upgrade to $DBversion done (Bug 13984: CardnumberLength syspref missing on some setups\n";
10331     SetVersion ($DBversion);
10332 }
10333
10334 $DBversion = "3.19.00.035";
10335 if ( CheckVersion($DBversion) ) {
10336     $dbh->do(q|
10337         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('useDischarge','','Allows librarians to discharge borrowers and borrowers to request a discharge','','YesNo')
10338     |);
10339     $dbh->do(q|
10340         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.')
10341     |);
10342
10343     $dbh->do(q|
10344         ALTER TABLE borrower_debarments CHANGE type type ENUM('SUSPENSION','OVERDUES','MANUAL','DISCHARGE') NOT NULL DEFAULT 'MANUAL'
10345     |);
10346
10347     $dbh->do(q|
10348         CREATE TABLE discharges (
10349           borrower int(11) DEFAULT NULL,
10350           needed timestamp NULL DEFAULT NULL,
10351           validated timestamp NULL DEFAULT NULL,
10352           KEY borrower_discharges_ibfk1 (borrower),
10353           CONSTRAINT borrower_discharges_ibfk1 FOREIGN KEY (borrower) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
10354         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
10355     |);
10356
10357     print "Upgrade to $DBversion done (Bug 8007: Add System Preferences useDischarge, the discharge notice and the new table discharges)\n";
10358     SetVersion($DBversion);
10359 }
10360
10361 $DBversion = "3.19.00.036";
10362 if ( CheckVersion($DBversion) ) {
10363     $dbh->do(q|
10364         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10365         VALUES ('CronjobLog','0',NULL,'If ON, log information from cron jobs.','YesNo')
10366     |);
10367     print "Upgrade to $DBversion done (Bug 13889: Add cron jobs information to system log)\n";
10368     SetVersion ($DBversion);
10369 }
10370
10371 $DBversion = "3.19.00.037";
10372 if ( CheckVersion($DBversion) ) {
10373     $dbh->do(q|
10374         ALTER TABLE marc_subfield_structure
10375         MODIFY COLUMN tagsubfield varchar(1) COLLATE utf8_bin NOT NULL DEFAULT ''
10376     |);
10377     print "Upgrade to $DBversion done (Bug 13810: Change collate for tagsubfield (utf8_bin))\n";
10378     SetVersion ($DBversion);
10379 }
10380
10381 $DBversion = "3.19.00.038";
10382 if ( CheckVersion($DBversion) ) {
10383     $dbh->do(q|
10384         ALTER TABLE virtualshelves
10385         ADD COLUMN created_on TIMESTAMP NOT NULL AFTER lastmodified
10386     |);
10387     # Set created_on = lastmodified
10388     # I would say it's better than 0000-00-00
10389     # Set modified to the existing value (do not get the current ts!)
10390     $dbh->do(q|
10391         UPDATE virtualshelves
10392         SET created_on = lastmodified, lastmodified = lastmodified
10393     |);
10394     print "Upgrade to $DBversion done (Bug 13421: Add DB field virtualshelves.created_on)\n";
10395     SetVersion ($DBversion);
10396 }
10397
10398 $DBversion = "3.19.00.039";
10399 if ( CheckVersion($DBversion) ) {
10400     print "Upgrade to $DBversion done (Koha 3.20 beta)\n";
10401     SetVersion ($DBversion);
10402 }
10403
10404 $DBversion = "3.19.00.040";
10405 if ( CheckVersion($DBversion) ) {
10406     $dbh->do(q|
10407         ALTER TABLE aqorders DROP COLUMN totalamount
10408     |);
10409     print "Upgrade to $DBversion done (Bug 11006: Drop column aqorders.totalamount)\n";
10410     SetVersion ($DBversion);
10411 }
10412
10413 $DBversion = "3.19.00.041";
10414 if ( CheckVersion($DBversion) ) {
10415     $dbh->do(q|
10416         ALTER IGNORE TABLE suggestions ADD KEY status (STATUS)
10417     |);
10418     $dbh->do(q|
10419         ALTER IGNORE TABLE suggestions ADD KEY biblionumber (biblionumber)
10420     |);
10421     $dbh->do(q|
10422         ALTER IGNORE TABLE suggestions ADD KEY branchcode (branchcode)
10423     |);
10424     print "Upgrade to $DBversion done (Bug 14132: suggestions table is missing indexes)\n";
10425     SetVersion ($DBversion);
10426 }
10427
10428 $DBversion = "3.19.00.042";
10429 if ( CheckVersion($DBversion) ) {
10430     $dbh->do(q{
10431         DELETE ass.*
10432         FROM auth_subfield_structure AS ass
10433         LEFT JOIN auth_types USING(authtypecode)
10434         WHERE auth_types.authtypecode IS NULL
10435     });
10436
10437     $dbh->do(q{
10438         ALTER IGNORE TABLE auth_subfield_structure
10439         ADD CONSTRAINT auth_subfield_structure_ibfk_1
10440         FOREIGN KEY (authtypecode) REFERENCES auth_types(authtypecode)
10441         ON DELETE CASCADE ON UPDATE CASCADE
10442     });
10443
10444     print "Upgrade to $DBversion done (Bug 8480: Add foreign key on auth_subfield_structure.authtypecode)\n";
10445     SetVersion($DBversion);
10446 }
10447
10448 $DBversion = "3.19.00.043";
10449 if ( CheckVersion($DBversion) ) {
10450     $dbh->do(q|
10451         INSERT IGNORE INTO authorised_values (category, authorised_value, lib) VALUES
10452         ('REPORT_GROUP', 'SER', 'Serials')
10453     |);
10454
10455     print "Upgrade to $DBversion done (Bug 5338: Add Serial to the report groups if does not exist)\n";
10456     SetVersion ($DBversion);
10457 }
10458
10459 $DBversion = "3.20.00.000";
10460 if ( CheckVersion($DBversion) ) {
10461     print "Upgrade to $DBversion done (Koha 3.20)\n";
10462     SetVersion ($DBversion);
10463 }
10464
10465 $DBversion = "3.21.00.000";
10466 if ( CheckVersion($DBversion) ) {
10467     print "Upgrade to $DBversion done (El tiempo vuela, un nuevo ciclo comienza.)\n";
10468     SetVersion ($DBversion);
10469 }
10470
10471 $DBversion = "3.21.00.001";
10472 if ( CheckVersion($DBversion) ) {
10473     $dbh->do(q|
10474         UPDATE systempreferences SET variable='IntranetUserJS' where variable='intranetuserjs'
10475     |);
10476     print "Upgrade to $DBversion done (Bug 12160: Rename intranetuserjs to IntranetUserJS)\n";
10477     SetVersion ($DBversion);
10478 }
10479
10480 $DBversion = "3.21.00.002";
10481 if ( CheckVersion($DBversion) ) {
10482     $dbh->do(q|
10483         UPDATE systempreferences SET variable='OPACUserJS' where variable='opacuserjs'
10484     |);
10485     print "Upgrade to $DBversion done (Bug 12160: Rename opacuserjs to OPACUserJS)\n";
10486     SetVersion ($DBversion);
10487 }
10488
10489 $DBversion = "3.21.00.003";
10490 if ( CheckVersion($DBversion) ) {
10491     $dbh->do(q|
10492         INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added)
10493         VALUES ( 'IN', 'region', 'India','2015-05-28');
10494     |);
10495     $dbh->do(q|
10496         INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)
10497         VALUES ( 'IN', 'region', 'en', 'India');
10498     |);
10499     $dbh->do(q|
10500         INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)
10501         VALUES ( 'IN', 'region', 'bn', 'ভারত');
10502     |);
10503     print "Upgrade to $DBversion done (Bug 14285: Add new region India)\n";
10504     SetVersion ($DBversion);
10505 }
10506
10507 $DBversion = '3.21.00.004';
10508 if ( CheckVersion($DBversion) ) {
10509     my $OPACBaseURL = C4::Context->preference('OPACBaseURL');
10510     if (defined($OPACBaseURL) && substr($OPACBaseURL,0,4) ne "http") {
10511         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.};
10512         $OPACBaseURL = 'http://' . $OPACBaseURL;
10513         my $sth_OPACBaseURL = $dbh->prepare( q{
10514             UPDATE systempreferences SET value=?,explanation=?
10515             WHERE variable='OPACBaseURL'; } );
10516         $sth_OPACBaseURL->execute($OPACBaseURL,$explanation);
10517     }
10518     if (defined($OPACBaseURL)) {
10519         $dbh->do( q{ UPDATE letter
10520                      SET content=replace(content,
10521                                          'http://<<OPACBaseURL>>',
10522                                          '<<OPACBaseURL>>')
10523                      WHERE content LIKE "%http://<<OPACBaseURL>>%"; } );
10524     }
10525
10526     print "Upgrade to $DBversion done (Bug 5010: Fix OPACBaseURL to include protocol)\n";
10527     SetVersion($DBversion);
10528 }
10529
10530 $DBversion = "3.21.00.005";
10531 if ( CheckVersion($DBversion) ) {
10532     $dbh->do(q|
10533         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10534         VALUES ('ReportsLog','0',NULL,'If ON, log information about reports.','YesNo')
10535     |);
10536     print "Upgrade to $DBversion done (Bug 14024: Add reports to action logs)\n";
10537     SetVersion ($DBversion);
10538 }
10539
10540 $DBversion = "3.21.00.006";
10541 if ( CheckVersion($DBversion) ) {
10542     # Remove the borrow permission flag (bit 7)
10543     $dbh->do(q|
10544         UPDATE borrowers
10545         SET flags = flags - ( flags & (1<<7) )
10546         WHERE flags IS NOT NULL
10547             AND flags > 0
10548     |);
10549     $dbh->do(q|
10550         DELETE FROM userflags WHERE bit=7;
10551     |);
10552     print "Upgrade to $DBversion done (Bug 7976: Remove the 'borrow' permission)\n";
10553     SetVersion($DBversion);
10554 }
10555
10556 $DBversion = "3.21.00.007";
10557 if ( CheckVersion($DBversion) ) {
10558     $dbh->do(q|
10559         ALTER IGNORE TABLE aqbasket
10560             ADD KEY authorisedby (authorisedby)
10561     |);
10562     $dbh->do(q|
10563         ALTER IGNORE TABLE aqbooksellers
10564             ADD KEY name (name(255))
10565     |);
10566     $dbh->do(q|
10567         ALTER IGNORE TABLE aqbudgets
10568             ADD KEY budget_parent_id (budget_parent_id),
10569             ADD KEY budget_code (budget_code),
10570             ADD KEY budget_branchcode (budget_branchcode),
10571             ADD KEY budget_period_id (budget_period_id),
10572             ADD KEY budget_owner_id (budget_owner_id)
10573     |);
10574     $dbh->do(q|
10575         ALTER IGNORE TABLE aqbudgets_planning
10576             ADD KEY budget_period_id (budget_period_id)
10577     |);
10578     $dbh->do(q|
10579         ALTER IGNORE TABLE aqorders
10580             ADD KEY parent_ordernumber (parent_ordernumber),
10581             ADD KEY orderstatus (orderstatus)
10582     |);
10583     print "Upgrade to $DBversion done (Bug 14053: Acquisition db tables are missing indexes)\n";
10584     SetVersion ($DBversion);
10585 }
10586
10587 $DBversion = "3.21.00.008";
10588 if ( CheckVersion($DBversion) ) {
10589     $dbh->do(q{
10590         DELETE IGNORE FROM systempreferences
10591         WHERE variable = 'HomeOrHoldingBranchReturn';
10592     });
10593     print "Upgrade to $DBversion done (Bug 7981: Transfer message on return. HomeOrHoldingBranchReturn syspref removed in favour of circulation rules.)\n";
10594     SetVersion($DBversion);
10595 }
10596
10597 $DBversion = "3.21.00.009";
10598 if ( CheckVersion($DBversion) ) {
10599     $dbh->do(q|
10600         UPDATE aqorders SET orderstatus='cancelled'
10601         WHERE (datecancellationprinted IS NOT NULL OR
10602                datecancellationprinted<>'0000-00-00');
10603     |);
10604     print "Upgrade to $DBversion done (Bug 13993: Correct orderstatus for transferred orders)\n";
10605     SetVersion($DBversion);
10606 }
10607
10608 $DBversion = "3.21.00.010";
10609 if ( CheckVersion($DBversion) ) {
10610     $dbh->do(q|
10611         ALTER TABLE message_queue
10612             DROP message_id
10613     |);
10614     $dbh->do(q|
10615         ALTER TABLE message_queue
10616             ADD message_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10617     |);
10618     print "Upgrade to $DBversion done (Bug 7793: redefine the field message_id as PRIMARY KEY of message_queue)\n";
10619     SetVersion ($DBversion);
10620 }
10621
10622 $DBversion = "3.21.00.011";
10623 if ( CheckVersion($DBversion) ) {
10624     $dbh->do(q{
10625         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10626         VALUES ('OpacLangSelectorMode','footer','top|both|footer','Select the location to display the language selector','Choice')
10627     });
10628     print "Upgrade to $DBversion done (Bug 14252: Make the OPAC language switcher available in the masthead navbar, footer, or both)\n";
10629     SetVersion ($DBversion);
10630 }
10631
10632 $DBversion = "3.21.00.012";
10633 if ( CheckVersion($DBversion) ) {
10634     $dbh->do(q|
10635         INSERT INTO letter (module, code, name, title, content, message_transport_type)
10636         VALUES
10637         ('suggestions','TO_PROCESS','Notify budget 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')
10638     |);
10639     print "Upgrade to $DBversion done (Bug 13014: Add the TO_PROCESS letter code)\n";
10640     SetVersion($DBversion);
10641 }
10642
10643 $DBversion = "3.21.00.013";
10644 if ( CheckVersion($DBversion) ) {
10645     my $msg;
10646     if ( C4::Context->preference('OPACPrivacy') ) {
10647         if ( my $anonymous_patron = C4::Context->preference('AnonymousPatron') ) {
10648             my $anonymous_patron_exists = $dbh->selectcol_arrayref(q|
10649                 SELECT COUNT(*)
10650                 FROM borrowers
10651                 WHERE borrowernumber=?
10652             |, {}, $anonymous_patron);
10653             unless ( $anonymous_patron_exists->[0] ) {
10654                 $msg = "Configuration WARNING: OPACPrivacy is set but AnonymousPatron is not linked to an existing patron";
10655             }
10656         }
10657         else {
10658             $msg = "Configuration WARNING: OPACPrivacy is set but AnonymousPatron is not";
10659         }
10660     }
10661     else {
10662         my $patrons_have_required_anonymity = $dbh->selectcol_arrayref(q|
10663             SELECT COUNT(*)
10664             FROM borrowers
10665             WHERE privacy = 2
10666         |, {} );
10667         if ( $patrons_have_required_anonymity->[0] ) {
10668             $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.";
10669         }
10670     }
10671
10672     $msg //= "Privacy is correctly set";
10673     print "Upgrade to $DBversion done (Bug 9942: $msg)\n";
10674     SetVersion ($DBversion);
10675 }
10676
10677 $DBversion = "3.21.00.014";
10678 if ( CheckVersion($DBversion) ) {
10679     $dbh->do(q{
10680         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10681         VALUES ('OAI-PMH:DeletedRecord','persistent','Koha\'s deletedbiblio table will never be deleted (persistent) or might be deleted (transient)','transient|persistent','Choice')
10682     });
10683     $dbh->do(q|
10684         ALTER TABLE oai_sets_biblios DROP FOREIGN KEY oai_sets_biblios_ibfk_1
10685     |);
10686     print "Upgrade to $DBversion done (Bug 3206: OAI repository deleted record support)\n";
10687     SetVersion ($DBversion);
10688 }
10689
10690 $DBversion = "3.21.00.015";
10691 if ( CheckVersion($DBversion) ) {
10692     $dbh->do(q{
10693         UPDATE systempreferences SET value='0' WHERE variable='CalendarFirstDayOfWeek' AND value='Sunday';
10694     });
10695     $dbh->do(q{
10696         UPDATE systempreferences SET value='1' WHERE variable='CalendarFirstDayOfWeek' AND value='Monday';
10697     });
10698     $dbh->do(q{
10699         UPDATE systempreferences SET options='0|1|2|3|4|5|6' WHERE variable='CalendarFirstDayOfWeek';
10700     });
10701
10702     print "Upgrade to $DBversion done (Bug 12137: Extend functionality of CalendarFirstDayOfWeek to be any day)\n";
10703     SetVersion($DBversion);
10704 }
10705
10706 $DBversion = "3.21.00.016";
10707 if ( CheckVersion($DBversion) ) {
10708     my $rs = $schema->resultset('Systempreference');
10709     $rs->find_or_create(
10710         {
10711             variable => 'DumpTemplateVarsIntranet',
10712             value    => 0,
10713             explanation => 'If enabled, dump all Template Toolkit variable to a comment in the html source for the staff intranet.',
10714             type => 'YesNo',
10715         }
10716     );
10717     $rs->find_or_create(
10718         {
10719             variable => 'DumpTemplateVarsOpac',
10720             value    => 0,
10721             explanation => 'If enabled, dump all Template Toolkit variable to a comment in the html source for the opac.',
10722             type => 'YesNo',
10723         }
10724     );
10725     print "Upgrade to $DBversion done (Bug 13948: Add ability to dump template toolkit variables to html comment)\n";
10726     SetVersion($DBversion);
10727 }
10728
10729 $DBversion = "3.21.00.017";
10730 if ( CheckVersion($DBversion) ) {
10731     $dbh->do("
10732         CREATE TABLE uploaded_files (
10733             id int(11) NOT NULL AUTO_INCREMENT,
10734             hashvalue CHAR(40) NOT NULL,
10735             filename TEXT NOT NULL,
10736             dir TEXT NOT NULL,
10737             filesize int(11),
10738             dtcreated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
10739             categorycode tinytext,
10740             owner int(11),
10741             PRIMARY KEY (id)
10742         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
10743     ");
10744
10745     print "Upgrade to $DBversion done (Bug 6874: New cataloging plugin upload.pl)\n";
10746     print "This plugin comes with a new config variable (upload_path) and a new table (uploaded_files)\n";
10747     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";
10748     SetVersion($DBversion);
10749 }
10750
10751 $DBversion = "3.21.00.018";
10752 if ( CheckVersion($DBversion) ) {
10753     $dbh->do(q{
10754         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10755         VALUES
10756             ('RestrictedPageLocalIPs','',NULL,'Beginning of IP addresses considered as local (comma separated ex: \"127.0.0,127.0.2\")','Free'),
10757             ('RestrictedPageContent','',NULL,'HTML content of the restricted page','TextArea'),
10758             ('RestrictedPageTitle','',NULL,'Title of the restricted page (breadcrumb and header)','Free')
10759     });
10760     print "Upgrade to $DBversion done (Bug 13485: Add a page to display links to restricted sites)\n";
10761     SetVersion ($DBversion);
10762 }
10763
10764 $DBversion = "3.21.00.019";
10765 if ( CheckVersion($DBversion) ) {
10766     $dbh->do(q{
10767         ALTER TABLE reserves DROP constrainttype
10768     });
10769     $dbh->do(q{
10770         ALTER TABLE old_reserves DROP constrainttype
10771     });
10772     $dbh->do(q{
10773         DROP TABLE IF EXISTS reserveconstraints
10774     });
10775     print "Upgrade to $DBversion done (Bug 9809: Get rid of reserveconstraints)\n";
10776     SetVersion ($DBversion);
10777 }
10778
10779 $DBversion = "3.21.00.020";
10780 if ( CheckVersion($DBversion) ) {
10781     $dbh->do(q{
10782         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`)
10783         VALUES ('FeeOnChangePatronCategory','1','','If set, when a patron changes to a category with enrolment fee, a fee is charged','YesNo')
10784     });
10785     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";
10786     SetVersion($DBversion);
10787 }
10788
10789 $DBversion = "3.21.00.021";
10790 if ( CheckVersion($DBversion) ) {
10791     $dbh->do(q{
10792         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10793         VALUES ('UseWYSIWYGinSystemPreferences','0','','Show WYSIWYG editor when editing certain HTML system preferences.','YesNo')
10794     });
10795     print "Upgrade to $DBversion done (Bug 11584: Add wysiwyg editor to system preferences dealing with HTML)\n";
10796     SetVersion($DBversion);
10797 }
10798
10799 $DBversion = "3.21.00.022";
10800 if ( CheckVersion($DBversion) ) {
10801     $dbh->do(q{
10802         DELETE cr.*
10803         FROM course_reserves AS cr
10804         LEFT JOIN course_items USING(ci_id)
10805         WHERE course_items.ci_id IS NULL
10806     });
10807     $dbh->do(q{
10808         ALTER IGNORE TABLE course_reserves
10809             add CONSTRAINT course_reserves_ibfk_2
10810                 FOREIGN KEY (ci_id) REFERENCES course_items (ci_id)
10811                 ON DELETE CASCADE ON UPDATE CASCADE
10812     });
10813     print "Upgrade to $DBversion done (Bug 14205: Deleting an Item/Record does not remove link to course reserve)\n";
10814     SetVersion($DBversion);
10815 }
10816
10817 $DBversion = "3.21.00.023";
10818 if ( CheckVersion($DBversion) ) {
10819     $dbh->do(q{
10820         UPDATE borrowers SET debarred=NULL WHERE debarred='0000-00-00'
10821     });
10822     $dbh->do(q{
10823         UPDATE borrowers SET dateexpiry=NULL where dateexpiry='0000-00-00'
10824     });
10825     $dbh->do(q{
10826         UPDATE borrowers SET dateofbirth=NULL where dateofbirth='0000-00-00'
10827     });
10828     $dbh->do(q{
10829         UPDATE borrowers SET dateenrolled=NULL where dateenrolled='0000-00-00'
10830     });
10831     print "Upgrade to $DBversion done (Bug 14717: Prevent 0000-00-00 dates in patron data)\n";
10832     SetVersion($DBversion);
10833 }
10834
10835 $DBversion = "3.21.00.024";
10836 if ( CheckVersion($DBversion) ) {
10837     $dbh->do(q{
10838         ALTER TABLE marc_modification_template_actions
10839         MODIFY COLUMN action
10840             ENUM('delete_field','update_field','move_field','copy_field','copy_and_replace_field')
10841     });
10842     print "Upgrade to $DBversion done (Bug 14098: Regression in Marc Modification Templates)\n";
10843     SetVersion($DBversion);
10844 }
10845
10846 $DBversion = "3.21.00.025";
10847 if ( CheckVersion($DBversion) ) {
10848     $dbh->do(q{
10849         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10850         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')
10851     });
10852     $dbh->do(q{
10853         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10854         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')
10855     });
10856     print "Upgrade to $DBversion done (Bug 12357: Enhancements to RIS and BibTeX exporting)\n";
10857     SetVersion($DBversion);
10858 }
10859
10860 $DBversion = "3.21.00.026";
10861 if ( CheckVersion($DBversion) ) {
10862     $dbh->do(q{
10863         UPDATE matchpoints
10864         SET search_index='issn'
10865         WHERE matcher_id IN (SELECT matcher_id FROM marc_matchers WHERE code = 'ISSN')
10866     });
10867     print "Upgrade to $DBversion done (Bug 14472: Wrong ISSN search index in record matching rules)\n";
10868     SetVersion($DBversion);
10869 }
10870
10871 $DBversion = "3.21.00.027";
10872 if ( CheckVersion($DBversion) ) {
10873     $dbh->do(q|
10874         INSERT INTO permissions (module_bit, code, description)
10875         VALUES (1, 'self_checkout', 'Perform self checkout at the OPAC. It should be used for the patron matching the AutoSelfCheckID')
10876     |);
10877
10878     my $AutoSelfCheckID = C4::Context->preference('AutoSelfCheckID');
10879
10880     $dbh->do(q|
10881         UPDATE borrowers
10882         SET flags=0
10883         WHERE userid=?
10884     |, undef, $AutoSelfCheckID);
10885
10886     $dbh->do(q|
10887         DELETE FROM user_permissions
10888         WHERE borrowernumber=(SELECT borrowernumber FROM borrowers WHERE userid=?)
10889     |, undef, $AutoSelfCheckID);
10890
10891     $dbh->do(q|
10892         INSERT INTO user_permissions(borrowernumber, module_bit, code)
10893         SELECT borrowernumber, 1, 'self_checkout' FROM borrowers WHERE userid=?
10894     |, undef, $AutoSelfCheckID);
10895     print "Upgrade to $DBversion done (Bug 14298: AutoSelfCheckID user should only be able to access SCO)\n";
10896     SetVersion($DBversion);
10897 }
10898
10899 $DBversion = "3.21.00.028";
10900 if ( CheckVersion($DBversion) ) {
10901     $dbh->do(q{
10902         ALTER TABLE uploaded_files
10903             ADD COLUMN public tinyint,
10904             ADD COLUMN permanent tinyint
10905     });
10906     $dbh->do(q{
10907         UPDATE uploaded_files SET public=1, permanent=1
10908     });
10909     $dbh->do(q{
10910         ALTER TABLE uploaded_files
10911             CHANGE COLUMN categorycode uploadcategorycode tinytext
10912     });
10913     print "Upgrade to $DBversion done (Bug 14321: Merge UploadedFile and UploadedFiles into Koha::Upload)\n";
10914     SetVersion($DBversion);
10915 }
10916
10917 $DBversion = "3.21.00.029";
10918 if ( CheckVersion($DBversion) ) {
10919     $dbh->do(q{
10920         ALTER IGNORE TABLE discharges
10921             ADD COLUMN discharge_id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10922     });
10923     print "Upgrade to $DBversion done (Bug 14368: Add discharges history)\n";
10924     SetVersion($DBversion);
10925 }
10926
10927 $DBversion = "3.21.00.030";
10928 if ( CheckVersion($DBversion) ) {
10929     $dbh->do(q{
10930         UPDATE marc_subfield_structure
10931         SET value_builder='marc21_leader.pl'
10932         WHERE value_builder='marc21_leader_book.pl'
10933     });
10934     $dbh->do(q{
10935         UPDATE marc_subfield_structure
10936         SET value_builder='marc21_leader.pl'
10937         WHERE value_builder='marc21_leader_computerfile.pl'
10938     });
10939     $dbh->do(q{
10940         UPDATE marc_subfield_structure
10941         SET value_builder='marc21_leader.pl'
10942         WHERE value_builder='marc21_leader_video.pl'
10943     });
10944     print "Upgrade to $DBversion done (Bug 14201: Remove unused code or template from some MARC21 leader plugins )\n";
10945     SetVersion($DBversion);
10946 }
10947
10948 $DBversion = "3.21.00.031";
10949 if ( CheckVersion($DBversion) ) {
10950     $dbh->do(q{
10951         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10952         VALUES
10953             ('SMSSendPassword', '', '', 'Password used to send SMS messages', 'free'),
10954             ('SMSSendUsername', '', '', 'Username/Login used to send SMS messages', 'free')
10955     });
10956     print "Upgrade to $DBversion done (Bug 14820: SMSSendUsername and SMSSendPassword are not listed in the system preferences)\n";
10957     SetVersion($DBversion);
10958 }
10959
10960 $DBversion = "3.21.00.032";
10961 if ( CheckVersion($DBversion) ) {
10962     $dbh->do(q{
10963         CREATE TABLE additional_fields (
10964             id int(11) NOT NULL AUTO_INCREMENT,
10965             tablename varchar(255) NOT NULL DEFAULT '',
10966             name varchar(255) NOT NULL DEFAULT '',
10967             authorised_value_category varchar(16) NOT NULL DEFAULT '',
10968             marcfield varchar(16) NOT NULL DEFAULT '',
10969             searchable tinyint(1) NOT NULL DEFAULT '0',
10970             PRIMARY KEY (id),
10971             UNIQUE KEY fields_uniq (tablename,name)
10972         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
10973     });
10974     $dbh->do(q{
10975         CREATE TABLE additional_field_values (
10976             id int(11) NOT NULL AUTO_INCREMENT,
10977             field_id int(11) NOT NULL,
10978             record_id int(11) NOT NULL,
10979             value varchar(255) NOT NULL DEFAULT '',
10980             PRIMARY KEY (id),
10981             UNIQUE KEY field_record (field_id,record_id),
10982             CONSTRAINT afv_fk FOREIGN KEY (field_id) REFERENCES additional_fields (id) ON DELETE CASCADE ON UPDATE CASCADE
10983         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
10984     });
10985     print "Upgrade to $DBversion done (Bug 10855: Additional fields for subscriptions)\n";
10986     SetVersion($DBversion);
10987 }
10988
10989 $DBversion = "3.21.00.033";
10990 if ( CheckVersion($DBversion) ) {
10991
10992     my $done = 0;
10993     my $count_ethnicity = $dbh->selectrow_arrayref(q|
10994         SELECT COUNT(*) FROM ethnicity
10995     |);
10996     my $count_borrower_modifications = $dbh->selectrow_arrayref(q|
10997         SELECT COUNT(*)
10998         FROM borrower_modifications
10999         WHERE ethnicity IS NOT NULL
11000             OR ethnotes IS NOT NULL
11001     |);
11002     my $count_borrowers = $dbh->selectrow_arrayref(q|
11003         SELECT COUNT(*)
11004         FROM borrowers
11005         WHERE ethnicity IS NOT NULL
11006             OR ethnotes IS NOT NULL
11007     |);
11008     # We don't care about the ethnicity of the deleted borrowers, right?
11009     if ( $count_ethnicity->[0] == 0
11010             and $count_borrower_modifications->[0] == 0
11011             and $count_borrowers->[0] == 0
11012     ) {
11013         $dbh->do(q|
11014             DROP TABLE ethnicity
11015         |);
11016         $dbh->do(q|
11017             ALTER TABLE borrower_modifications
11018             DROP COLUMN ethnicity,
11019             DROP COLUMN ethnotes
11020         |);
11021         $dbh->do(q|
11022             ALTER TABLE borrowers
11023             DROP COLUMN ethnicity,
11024             DROP COLUMN ethnotes
11025         |);
11026         $dbh->do(q|
11027             ALTER TABLE deletedborrowers
11028             DROP COLUMN ethnicity,
11029             DROP COLUMN ethnotes
11030         |);
11031         $done = 1;
11032     }
11033     if ( $done ) {
11034         print "Upgrade to $DBversion done (Bug 10020: Drop table ethnicity and columns ethnicity and ethnotes)\n";
11035     }
11036     else {
11037         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";
11038     }
11039
11040     SetVersion ($DBversion);
11041 }
11042
11043 $DBversion = "3.21.00.034";
11044 if ( CheckVersion($DBversion) ) {
11045     $dbh->do(q{
11046         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11047         VALUES('MembershipExpiryDaysNotice',NULL,'Send an account expiration notice that a patron''s card is about to expire after',NULL,'Integer')
11048     });
11049     $dbh->do(q{
11050         INSERT IGNORE INTO letter (module, code, branchcode, name, title, content, message_transport_type)
11051         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')
11052     });
11053     print "Upgrade to $DBversion done (Bug 6810: Send membership expiry reminder notices)\n";
11054     SetVersion($DBversion);
11055 }
11056
11057 $DBversion = "3.21.00.035";
11058 if ( CheckVersion($DBversion) ) {
11059     $dbh->do(q|
11060         ALTER TABLE branch_borrower_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11061     |);
11062     $dbh->do(q|
11063         UPDATE branch_borrower_circ_rules SET maxonsiteissueqty = maxissueqty;
11064     |);
11065     $dbh->do(q|
11066         ALTER TABLE default_borrower_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11067     |);
11068     $dbh->do(q|
11069         UPDATE default_borrower_circ_rules SET maxonsiteissueqty = maxissueqty;
11070     |);
11071     $dbh->do(q|
11072         ALTER TABLE default_branch_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11073     |);
11074     $dbh->do(q|
11075         UPDATE default_branch_circ_rules SET maxonsiteissueqty = maxissueqty;
11076     |);
11077     $dbh->do(q|
11078         ALTER TABLE default_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11079     |);
11080     $dbh->do(q|
11081         UPDATE default_circ_rules SET maxonsiteissueqty = maxissueqty;
11082     |);
11083     $dbh->do(q|
11084         ALTER TABLE issuingrules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11085     |);
11086     $dbh->do(q|
11087         UPDATE issuingrules SET maxonsiteissueqty = maxissueqty;
11088     |);
11089     $dbh->do(q|
11090         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11091         VALUES ('ConsiderOnSiteCheckoutsAsNormalCheckouts','1',NULL,'Consider on-site checkouts as normal checkouts','YesNo');
11092     |);
11093
11094     print "Upgrade to $DBversion done (Bug 14045: Add DB fields maxonsiteissueqty and pref ConsiderOnSiteCheckoutsAsNormalCheckouts)\n";
11095     SetVersion ($DBversion);
11096 }
11097
11098 $DBversion = "3.21.00.036";
11099 if ( CheckVersion($DBversion) ) {
11100    $dbh->do(q{
11101        ALTER TABLE authorised_values_branches
11102          CHANGE av_id av_id INT( 11 ) NOT NULL,
11103          CHANGE branchcode branchcode VARCHAR( 10 ) NOT NULL
11104    });
11105    print "Upgrade to $DBversion done (Bug 10363: There is no package for authorised values)\n";
11106    SetVersion($DBversion);
11107 }
11108
11109 $DBversion = "3.21.00.037";
11110 if ( CheckVersion($DBversion) ) {
11111    $dbh->do(q{
11112        INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11113        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')
11114    });
11115    $dbh->do(q{
11116        INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11117        VALUES ('RestrictionBlockRenewing','0','If patron is restricted, should renewal be allowed or blocked',NULL,'YesNo')
11118     });
11119    print "Upgrade to $DBversion done (Bug 8236: Prevent renewing if overdue or restriction)\n";
11120    SetVersion($DBversion);
11121 }
11122
11123 # DEVELOPER PROCESS, search for anything to execute in the db_update directory
11124 # SEE bug 13068
11125 # if there is anything in the atomicupdate, read and execute it.
11126
11127 my $update_dir = C4::Context->config('intranetdir') . '/installer/data/mysql/atomicupdate/';
11128 opendir( my $dirh, $update_dir );
11129 foreach my $file ( sort readdir $dirh ) {
11130     next if $file !~ /\.(sql|perl)$/;  #skip other files
11131     print "DEV atomic update: $file\n";
11132     if ( $file =~ /\.sql$/ ) {
11133         my $installer = C4::Installer->new();
11134         my $rv = $installer->load_sql( $update_dir . $file ) ? 0 : 1;
11135     } elsif ( $file =~ /\.perl$/ ) {
11136         do $update_dir . $file;
11137     }
11138 }
11139
11140 =head1 FUNCTIONS
11141
11142 =head2 TableExists($table)
11143
11144 =cut
11145
11146 sub TableExists {
11147     my $table = shift;
11148     eval {
11149                 local $dbh->{PrintError} = 0;
11150                 local $dbh->{RaiseError} = 1;
11151                 $dbh->do(qq{SELECT * FROM $table WHERE 1 = 0 });
11152             };
11153     return 1 unless $@;
11154     return 0;
11155 }
11156
11157 =head2 DropAllForeignKeys($table)
11158
11159 Drop all foreign keys of the table $table
11160
11161 =cut
11162
11163 sub DropAllForeignKeys {
11164     my ($table) = @_;
11165     # get the table description
11166     my $sth = $dbh->prepare("SHOW CREATE TABLE $table");
11167     $sth->execute;
11168     my $vsc_structure = $sth->fetchrow;
11169     # split on CONSTRAINT keyword
11170     my @fks = split /CONSTRAINT /,$vsc_structure;
11171     # parse each entry
11172     foreach (@fks) {
11173         # isolate what is before FOREIGN KEY, if there is something, it's a foreign key to drop
11174         $_ = /(.*) FOREIGN KEY.*/;
11175         my $id = $1;
11176         if ($id) {
11177             # we have found 1 foreign, drop it
11178             $dbh->do("ALTER TABLE $table DROP FOREIGN KEY $id");
11179             $id="";
11180         }
11181     }
11182 }
11183
11184
11185 =head2 TransformToNum
11186
11187 Transform the Koha version from a 4 parts string
11188 to a number, with just 1 .
11189
11190 =cut
11191
11192 sub TransformToNum {
11193     my $version = shift;
11194     # remove the 3 last . to have a Perl number
11195     $version =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
11196     # three X's at the end indicate that you are testing patch with dbrev
11197     # change it into 999
11198     # prevents error on a < comparison between strings (should be: lt)
11199     $version =~ s/XXX$/999/;
11200     return $version;
11201 }
11202
11203 =head2 SetVersion
11204
11205 set the DBversion in the systempreferences
11206
11207 =cut
11208
11209 sub SetVersion {
11210     return if $_[0]=~ /XXX$/;
11211       #you are testing a patch with a db revision; do not change version
11212     my $kohaversion = TransformToNum($_[0]);
11213     if (C4::Context->preference('Version')) {
11214       my $finish=$dbh->prepare("UPDATE systempreferences SET value=? WHERE variable='Version'");
11215       $finish->execute($kohaversion);
11216     } else {
11217       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')");
11218       $finish->execute($kohaversion);
11219     }
11220     C4::Context::clear_syspref_cache(); # invalidate cached preferences
11221 }
11222
11223 =head2 CheckVersion
11224
11225 Check whether a given update should be run when passed the proposed version
11226 number. The update will always be run if the proposed version is greater
11227 than the current database version and less than or equal to the version in
11228 kohaversion.pl. The update is also run if the version contains XXX, though
11229 this behavior will be changed following the adoption of non-linear updates
11230 as implemented in bug 7167.
11231
11232 =cut
11233
11234 sub CheckVersion {
11235     my ($proposed_version) = @_;
11236     my $version_number = TransformToNum($proposed_version);
11237
11238     # The following line should be deleted when bug 7167 is pushed
11239     return 1 if ( $proposed_version =~ m/XXX/ );
11240
11241     if ( C4::Context->preference("Version") < $version_number
11242         && $version_number <= TransformToNum( $Koha::VERSION ) )
11243     {
11244         return 1;
11245     }
11246     else {
11247         return 0;
11248     }
11249 }
11250
11251 exit;