Koha 3.20 beta
[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
42 use Koha;
43
44 use MARC::Record;
45 use MARC::File::XML ( BinaryEncoding => 'utf8' );
46
47 # FIXME - The user might be installing a new database, so can't rely
48 # on /etc/koha.conf anyway.
49
50 my $debug = 0;
51
52 my (
53     $sth, $sti,
54     $query,
55     %existingtables,    # tables already in database
56     %types,
57     $table,
58     $column,
59     $type, $null, $key, $default, $extra,
60     $prefitem,          # preference item in systempreferences table
61 );
62
63 my $schema = Koha::Database->new()->schema();
64
65 my $silent;
66 GetOptions(
67     's' =>\$silent
68     );
69 my $dbh = C4::Context->dbh;
70 $|=1; # flushes output
71
72 local $dbh->{RaiseError} = 0;
73
74 # Record the version we are coming from
75
76 my $original_version = C4::Context->preference("Version");
77
78 # Deal with virtualshelves
79 my $DBversion = "3.00.00.001";
80 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
81     # update virtualshelves table to
82     #
83     $dbh->do("ALTER TABLE `bookshelf` RENAME `virtualshelves`");
84     $dbh->do("ALTER TABLE `shelfcontents` RENAME `virtualshelfcontents`");
85     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD `biblionumber` INT( 11 ) NOT NULL default '0' AFTER shelfnumber");
86     $dbh->do("UPDATE `virtualshelfcontents` SET biblionumber=(SELECT biblionumber FROM items WHERE items.itemnumber=virtualshelfcontents.itemnumber)");
87     # drop all foreign keys : otherwise, we can't drop itemnumber field.
88     DropAllForeignKeys('virtualshelfcontents');
89     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD KEY biblionumber (biblionumber)");
90     # create the new foreign keys (on biblionumber)
91     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD CONSTRAINT `virtualshelfcontents_ibfk_1` FOREIGN KEY (`shelfnumber`) REFERENCES `virtualshelves` (`shelfnumber`) ON DELETE CASCADE ON UPDATE CASCADE");
92     # re-create the foreign key on virtualshelf
93     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD CONSTRAINT `shelfcontents_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE");
94     $dbh->do("ALTER TABLE `virtualshelfcontents` DROP `itemnumber`");
95     print "Upgrade to $DBversion done (virtualshelves)\n";
96     SetVersion ($DBversion);
97 }
98
99
100 $DBversion = "3.00.00.002";
101 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
102     $dbh->do("DROP TABLE sessions");
103     $dbh->do("CREATE TABLE `sessions` (
104   `id` varchar(32) NOT NULL,
105   `a_session` text NOT NULL,
106   UNIQUE KEY `id` (`id`)
107 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
108     print "Upgrade to $DBversion done (sessions uses CGI::session, new table structure for sessions)\n";
109     SetVersion ($DBversion);
110 }
111
112
113 $DBversion = "3.00.00.003";
114 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
115     if (C4::Context->preference("opaclanguages") eq "fr") {
116         $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')");
117     } else {
118         $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')");
119     }
120     print "Upgrade to $DBversion done (adding ReservesNeedReturns systempref, in circulation)\n";
121     SetVersion ($DBversion);
122 }
123
124
125 $DBversion = "3.00.00.004";
126 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
127     $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')");
128     print "Upgrade to $DBversion done (adding DebugLevel systempref, in 'Admin' tab)\n";
129     SetVersion ($DBversion);
130 }
131
132 $DBversion = "3.00.00.005";
133 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
134     $dbh->do("CREATE TABLE `tags` (
135                     `entry` varchar(255) NOT NULL default '',
136                     `weight` bigint(20) NOT NULL default 0,
137                     PRIMARY KEY  (`entry`)
138                     ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
139                 ");
140         $dbh->do("CREATE TABLE `nozebra` (
141                 `server` varchar(20)     NOT NULL,
142                 `indexname` varchar(40)  NOT NULL,
143                 `value` varchar(250)     NOT NULL,
144                 `biblionumbers` longtext NOT NULL,
145                 KEY `indexname` (`server`,`indexname`),
146                 KEY `value` (`server`,`value`))
147                 ENGINE=InnoDB DEFAULT CHARSET=utf8;
148                 ");
149     print "Upgrade to $DBversion done (adding tags and nozebra tables )\n";
150     SetVersion ($DBversion);
151 }
152
153 $DBversion = "3.00.00.006";
154 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
155     $dbh->do("UPDATE issues SET issuedate=timestamp WHERE issuedate='0000-00-00'");
156     print "Upgrade to $DBversion done (filled issues.issuedate with timestamp)\n";
157     SetVersion ($DBversion);
158 }
159
160 $DBversion = "3.00.00.007";
161 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
162     $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')");
163     print "Upgrade to $DBversion done (set SessionStorage variable)\n";
164     SetVersion ($DBversion);
165 }
166
167 $DBversion = "3.00.00.008";
168 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
169     $dbh->do("ALTER TABLE `biblio` ADD `datecreated` DATE NOT NULL AFTER `timestamp` ;");
170     $dbh->do("UPDATE biblio SET datecreated=timestamp");
171     print "Upgrade to $DBversion done (biblio creation date)\n";
172     SetVersion ($DBversion);
173 }
174
175 $DBversion = "3.00.00.009";
176 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
177
178     # Create backups of call number columns
179     # in case default migration needs to be customized
180     #
181     # UPGRADE NOTE: temp_upg_biblioitems_call_num should be dropped
182     #               after call numbers have been transformed to the new structure
183     #
184     # Not bothering to do the same with deletedbiblioitems -- assume
185     # default is good enough.
186     $dbh->do("CREATE TABLE `temp_upg_biblioitems_call_num` AS
187               SELECT `biblioitemnumber`, `biblionumber`,
188                      `classification`, `dewey`, `subclass`,
189                      `lcsort`, `ccode`
190               FROM `biblioitems`");
191
192     # biblioitems changes
193     $dbh->do("ALTER TABLE `biblioitems` CHANGE COLUMN `volumeddesc` `volumedesc` TEXT,
194                                     ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
195                                     ADD `cn_class` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
196                                     ADD `cn_item` VARCHAR(10) DEFAULT NULL AFTER `cn_class`,
197                                     ADD `cn_suffix` VARCHAR(10) DEFAULT NULL AFTER `cn_item`,
198                                     ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_suffix`,
199                                     ADD `totalissues` INT(10) AFTER `cn_sort`");
200
201     # default mapping of call number columns:
202     #   cn_class = concatentation of classification + dewey,
203     #              trimmed to fit -- assumes that most users do not
204     #              populate both classification and dewey in a single record
205     #   cn_item  = subclass
206     #   cn_source = left null
207     #   cn_sort = lcsort
208     #
209     # After upgrade, cn_sort will have to be set based on whatever
210     # default call number scheme user sets as a preference.  Misc
211     # script will be added at some point to do that.
212     #
213     $dbh->do("UPDATE `biblioitems`
214               SET cn_class = SUBSTR(TRIM(CONCAT_WS(' ', `classification`, `dewey`)), 1, 30),
215                     cn_item = subclass,
216                     `cn_sort` = `lcsort`
217             ");
218
219     # Now drop the old call number columns
220     $dbh->do("ALTER TABLE `biblioitems` DROP COLUMN `classification`,
221                                         DROP COLUMN `dewey`,
222                                         DROP COLUMN `subclass`,
223                                         DROP COLUMN `lcsort`,
224                                         DROP COLUMN `ccode`");
225
226     # deletedbiblio changes
227     $dbh->do("ALTER TABLE `deletedbiblio` ALTER COLUMN `frameworkcode` SET DEFAULT '',
228                                         DROP COLUMN `marc`,
229                                         ADD `datecreated` DATE NOT NULL AFTER `timestamp`");
230     $dbh->do("UPDATE deletedbiblio SET datecreated = timestamp");
231
232     # deletedbiblioitems changes
233     $dbh->do("ALTER TABLE `deletedbiblioitems`
234                         MODIFY `publicationyear` TEXT,
235                         CHANGE `volumeddesc` `volumedesc` TEXT,
236                         MODIFY `collectiontitle` MEDIUMTEXT DEFAULT NULL AFTER `volumedesc`,
237                         MODIFY `collectionissn` TEXT DEFAULT NULL AFTER `collectiontitle`,
238                         MODIFY `collectionvolume` MEDIUMTEXT DEFAULT NULL AFTER `collectionissn`,
239                         MODIFY `editionstatement` TEXT DEFAULT NULL AFTER `collectionvolume`,
240                         MODIFY `editionresponsibility` TEXT DEFAULT NULL AFTER `editionstatement`,
241                         MODIFY `place` VARCHAR(255) DEFAULT NULL AFTER `size`,
242                         MODIFY `marc` LONGBLOB,
243                         ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `url`,
244                         ADD `cn_class` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
245                         ADD `cn_item` VARCHAR(10) DEFAULT NULL AFTER `cn_class`,
246                         ADD `cn_suffix` VARCHAR(10) DEFAULT NULL AFTER `cn_item`,
247                         ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_suffix`,
248                         ADD `totalissues` INT(10) AFTER `cn_sort`,
249                         ADD `marcxml` LONGTEXT NOT NULL AFTER `totalissues`,
250                         ADD KEY `isbn` (`isbn`),
251                         ADD KEY `publishercode` (`publishercode`)
252                     ");
253
254     $dbh->do("UPDATE `deletedbiblioitems`
255                 SET `cn_class` = SUBSTR(TRIM(CONCAT_WS(' ', `classification`, `dewey`)), 1, 30),
256                `cn_item` = `subclass`,
257                 `cn_sort` = `lcsort`
258             ");
259     $dbh->do("ALTER TABLE `deletedbiblioitems`
260                         DROP COLUMN `classification`,
261                         DROP COLUMN `dewey`,
262                         DROP COLUMN `subclass`,
263                         DROP COLUMN `lcsort`,
264                         DROP COLUMN `ccode`
265             ");
266
267     # deleteditems changes
268     $dbh->do("ALTER TABLE `deleteditems`
269                         MODIFY `barcode` VARCHAR(20) DEFAULT NULL,
270                         MODIFY `price` DECIMAL(8,2) DEFAULT NULL,
271                         MODIFY `replacementprice` DECIMAL(8,2) DEFAULT NULL,
272                         DROP `bulk`,
273                         MODIFY `itemcallnumber` VARCHAR(30) DEFAULT NULL AFTER `wthdrawn`,
274                         MODIFY `holdingbranch` VARCHAR(10) DEFAULT NULL,
275                         DROP `interim`,
276                         MODIFY `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP AFTER `paidfor`,
277                         DROP `cutterextra`,
278                         ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `onloan`,
279                         ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
280                         ADD `ccode` VARCHAR(10) DEFAULT NULL AFTER `cn_sort`,
281                         ADD `materials` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
282                         ADD `uri` VARCHAR(255) DEFAULT NULL AFTER `materials`,
283                         MODIFY `marc` LONGBLOB AFTER `uri`,
284                         DROP KEY `barcode`,
285                         DROP KEY `itembarcodeidx`,
286                         DROP KEY `itembinoidx`,
287                         DROP KEY `itembibnoidx`,
288                         ADD UNIQUE KEY `delitembarcodeidx` (`barcode`),
289                         ADD KEY `delitembinoidx` (`biblioitemnumber`),
290                         ADD KEY `delitembibnoidx` (`biblionumber`),
291                         ADD KEY `delhomebranch` (`homebranch`),
292                         ADD KEY `delholdingbranch` (`holdingbranch`)");
293     $dbh->do("UPDATE deleteditems SET `ccode` = `itype`");
294     $dbh->do("ALTER TABLE deleteditems DROP `itype`");
295     $dbh->do("UPDATE `deleteditems` SET `cn_sort` = `itemcallnumber`");
296
297     # items changes
298     $dbh->do("ALTER TABLE `items` ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `onloan`,
299                                 ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
300                                 ADD `ccode` VARCHAR(10) DEFAULT NULL AFTER `cn_sort`,
301                                 ADD `materials` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
302                                 ADD `uri` VARCHAR(255) DEFAULT NULL AFTER `materials`
303             ");
304     $dbh->do("ALTER TABLE `items`
305                         DROP KEY `itembarcodeidx`,
306                         ADD UNIQUE KEY `itembarcodeidx` (`barcode`)");
307
308     # map items.itype to items.ccode and
309     # set cn_sort to itemcallnumber -- as with biblioitems.cn_sort,
310     # will have to be subsequently updated per user's default
311     # classification scheme
312     $dbh->do("UPDATE `items` SET `cn_sort` = `itemcallnumber`,
313                             `ccode` = `itype`");
314
315     $dbh->do("ALTER TABLE `items` DROP `cutterextra`,
316                                 DROP `itype`");
317
318     print "Upgrade to $DBversion done (major changes to biblio, biblioitems, items, and deleted* versions of same\n";
319     SetVersion ($DBversion);
320 }
321
322 $DBversion = "3.00.00.010";
323 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
324     $dbh->do("CREATE INDEX `userid` ON borrowers (`userid`) ");
325     print "Upgrade to $DBversion done (userid index added)\n";
326     SetVersion ($DBversion);
327 }
328
329 $DBversion = "3.00.00.011";
330 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
331     $dbh->do("ALTER TABLE `branchcategories` CHANGE `categorycode` `categorycode` varchar(10) ");
332     $dbh->do("ALTER TABLE `branchcategories` CHANGE `categoryname` `categoryname` varchar(32) ");
333     $dbh->do("ALTER TABLE `branchcategories` ADD COLUMN `categorytype` varchar(16) ");
334     $dbh->do("UPDATE `branchcategories` SET `categorytype` = 'properties'");
335     $dbh->do("ALTER TABLE `branchrelations` CHANGE `categorycode` `categorycode` varchar(10) ");
336     print "Upgrade to $DBversion done (added branchcategory type)\n";
337     SetVersion ($DBversion);
338 }
339
340 $DBversion = "3.00.00.012";
341 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
342     $dbh->do("CREATE TABLE `class_sort_rules` (
343                                `class_sort_rule` varchar(10) NOT NULL default '',
344                                `description` mediumtext,
345                                `sort_routine` varchar(30) NOT NULL default '',
346                                PRIMARY KEY (`class_sort_rule`),
347                                UNIQUE KEY `class_sort_rule_idx` (`class_sort_rule`)
348                              ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
349     $dbh->do("CREATE TABLE `class_sources` (
350                                `cn_source` varchar(10) NOT NULL default '',
351                                `description` mediumtext,
352                                `used` tinyint(4) NOT NULL default 0,
353                                `class_sort_rule` varchar(10) NOT NULL default '',
354                                PRIMARY KEY (`cn_source`),
355                                UNIQUE KEY `cn_source_idx` (`cn_source`),
356                                KEY `used_idx` (`used`),
357                                CONSTRAINT `class_source_ibfk_1` FOREIGN KEY (`class_sort_rule`)
358                                           REFERENCES `class_sort_rules` (`class_sort_rule`)
359                              ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
360     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type)
361               VALUES('DefaultClassificationSource','ddc',
362                      'Default classification scheme used by the collection. E.g., Dewey, LCC, etc.', NULL,'free')");
363     $dbh->do("INSERT INTO `class_sort_rules` (`class_sort_rule`, `description`, `sort_routine`) VALUES
364                                ('dewey', 'Default filing rules for DDC', 'Dewey'),
365                                ('lcc', 'Default filing rules for LCC', 'LCC'),
366                                ('generic', 'Generic call number filing rules', 'Generic')");
367     $dbh->do("INSERT INTO `class_sources` (`cn_source`, `description`, `used`, `class_sort_rule`) VALUES
368                             ('ddc', 'Dewey Decimal Classification', 1, 'dewey'),
369                             ('lcc', 'Library of Congress Classification', 1, 'lcc'),
370                             ('udc', 'Universal Decimal Classification', 0, 'generic'),
371                             ('sudocs', 'SuDoc Classification (U.S. GPO)', 0, 'generic'),
372                             ('z', 'Other/Generic Classification Scheme', 0, 'generic')");
373     print "Upgrade to $DBversion done (classification sources added)\n";
374     SetVersion ($DBversion);
375 }
376
377 $DBversion = "3.00.00.013";
378 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
379     $dbh->do("CREATE TABLE `import_batches` (
380               `import_batch_id` int(11) NOT NULL auto_increment,
381               `template_id` int(11) default NULL,
382               `branchcode` varchar(10) default NULL,
383               `num_biblios` int(11) NOT NULL default 0,
384               `num_items` int(11) NOT NULL default 0,
385               `upload_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
386               `overlay_action` enum('replace', 'create_new', 'use_template') NOT NULL default 'create_new',
387               `import_status` enum('staging', 'staged', 'importing', 'imported', 'reverting', 'reverted', 'cleaned') NOT NULL default 'staging',
388               `batch_type` enum('batch', 'z3950') NOT NULL default 'batch',
389               `file_name` varchar(100),
390               `comments` mediumtext,
391               PRIMARY KEY (`import_batch_id`),
392               KEY `branchcode` (`branchcode`)
393               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
394     $dbh->do("CREATE TABLE `import_records` (
395               `import_record_id` int(11) NOT NULL auto_increment,
396               `import_batch_id` int(11) NOT NULL,
397               `branchcode` varchar(10) default NULL,
398               `record_sequence` int(11) NOT NULL default 0,
399               `upload_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
400               `import_date` DATE default NULL,
401               `marc` longblob NOT NULL,
402               `marcxml` longtext NOT NULL,
403               `marcxml_old` longtext NOT NULL,
404               `record_type` enum('biblio', 'auth', 'holdings') NOT NULL default 'biblio',
405               `overlay_status` enum('no_match', 'auto_match', 'manual_match', 'match_applied') NOT NULL default 'no_match',
406               `status` enum('error', 'staged', 'imported', 'reverted', 'items_reverted') NOT NULL default 'staged',
407               `import_error` mediumtext,
408               `encoding` varchar(40) NOT NULL default '',
409               `z3950random` varchar(40) default NULL,
410               PRIMARY KEY (`import_record_id`),
411               CONSTRAINT `import_records_ifbk_1` FOREIGN KEY (`import_batch_id`)
412                           REFERENCES `import_batches` (`import_batch_id`) ON DELETE CASCADE ON UPDATE CASCADE,
413               KEY `branchcode` (`branchcode`),
414               KEY `batch_sequence` (`import_batch_id`, `record_sequence`)
415               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
416     $dbh->do("CREATE TABLE `import_record_matches` (
417               `import_record_id` int(11) NOT NULL,
418               `candidate_match_id` int(11) NOT NULL,
419               `score` int(11) NOT NULL default 0,
420               CONSTRAINT `import_record_matches_ibfk_1` FOREIGN KEY (`import_record_id`)
421                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
422               KEY `record_score` (`import_record_id`, `score`)
423               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
424     $dbh->do("CREATE TABLE `import_biblios` (
425               `import_record_id` int(11) NOT NULL,
426               `matched_biblionumber` int(11) default NULL,
427               `control_number` varchar(25) default NULL,
428               `original_source` varchar(25) default NULL,
429               `title` varchar(128) default NULL,
430               `author` varchar(80) default NULL,
431               `isbn` varchar(14) default NULL,
432               `issn` varchar(9) default NULL,
433               `has_items` tinyint(1) NOT NULL default 0,
434               CONSTRAINT `import_biblios_ibfk_1` FOREIGN KEY (`import_record_id`)
435                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
436               KEY `matched_biblionumber` (`matched_biblionumber`),
437               KEY `title` (`title`),
438               KEY `isbn` (`isbn`)
439               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
440     $dbh->do("CREATE TABLE `import_items` (
441               `import_items_id` int(11) NOT NULL auto_increment,
442               `import_record_id` int(11) NOT NULL,
443               `itemnumber` int(11) default NULL,
444               `branchcode` varchar(10) default NULL,
445               `status` enum('error', 'staged', 'imported', 'reverted') NOT NULL default 'staged',
446               `marcxml` longtext NOT NULL,
447               `import_error` mediumtext,
448               PRIMARY KEY (`import_items_id`),
449               CONSTRAINT `import_items_ibfk_1` FOREIGN KEY (`import_record_id`)
450                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
451               KEY `itemnumber` (`itemnumber`),
452               KEY `branchcode` (`branchcode`)
453               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
454
455     $dbh->do("INSERT INTO `import_batches`
456                 (`overlay_action`, `import_status`, `batch_type`, `file_name`)
457               SELECT distinct 'create_new', 'staged', 'z3950', `file`
458               FROM   `marc_breeding`");
459
460     $dbh->do("INSERT INTO `import_records`
461                 (`import_batch_id`, `import_record_id`, `record_sequence`, `marc`, `record_type`, `status`,
462                 `encoding`, `z3950random`, `marcxml`, `marcxml_old`)
463               SELECT `import_batch_id`, `id`, 1, `marc`, 'biblio', 'staged', `encoding`, `z3950random`, '', ''
464               FROM `marc_breeding`
465               JOIN `import_batches` ON (`file_name` = `file`)");
466
467     $dbh->do("INSERT INTO `import_biblios`
468                 (`import_record_id`, `title`, `author`, `isbn`)
469               SELECT `import_record_id`, `title`, `author`, `isbn`
470               FROM   `marc_breeding`
471               JOIN   `import_records` ON (`import_record_id` = `id`)");
472
473     $dbh->do("UPDATE `import_batches`
474               SET `num_biblios` = (
475               SELECT COUNT(*)
476               FROM `import_records`
477               WHERE `import_batch_id` = `import_batches`.`import_batch_id`
478               )");
479
480     $dbh->do("DROP TABLE `marc_breeding`");
481
482     print "Upgrade to $DBversion done (import_batches et al. added)\n";
483     SetVersion ($DBversion);
484 }
485
486 $DBversion = "3.00.00.014";
487 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
488     $dbh->do("ALTER TABLE subscription ADD lastbranch VARCHAR(4)");
489     print "Upgrade to $DBversion done (userid index added)\n";
490     SetVersion ($DBversion);
491 }
492
493 $DBversion = "3.00.00.015";
494 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
495     $dbh->do("CREATE TABLE `saved_sql` (
496            `id` int(11) NOT NULL auto_increment,
497            `borrowernumber` int(11) default NULL,
498            `date_created` datetime default NULL,
499            `last_modified` datetime default NULL,
500            `savedsql` text,
501            `last_run` datetime default NULL,
502            `report_name` varchar(255) default NULL,
503            `type` varchar(255) default NULL,
504            `notes` text,
505            PRIMARY KEY  (`id`),
506            KEY boridx (`borrowernumber`)
507         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
508     $dbh->do("CREATE TABLE `saved_reports` (
509            `id` int(11) NOT NULL auto_increment,
510            `report_id` int(11) default NULL,
511            `report` longtext,
512            `date_run` datetime default NULL,
513            PRIMARY KEY  (`id`)
514         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
515     print "Upgrade to $DBversion done (saved_sql and saved_reports added)\n";
516     SetVersion ($DBversion);
517 }
518
519 $DBversion = "3.00.00.016";
520 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
521     $dbh->do(" CREATE TABLE reports_dictionary (
522           id int(11) NOT NULL auto_increment,
523           name varchar(255) default NULL,
524           description text,
525           date_created datetime default NULL,
526           date_modified datetime default NULL,
527           saved_sql text,
528           area int(11) default NULL,
529           PRIMARY KEY  (id)
530         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
531     print "Upgrade to $DBversion done (reports_dictionary) added)\n";
532     SetVersion ($DBversion);
533 }
534
535 $DBversion = "3.00.00.017";
536 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
537     $dbh->do("ALTER TABLE action_logs DROP PRIMARY KEY");
538     $dbh->do("ALTER TABLE action_logs ADD KEY  timestamp (timestamp,user)");
539     $dbh->do("ALTER TABLE action_logs ADD action_id INT(11) NOT NULL FIRST");
540     $dbh->do("UPDATE action_logs SET action_id = if (\@a, \@a:=\@a+1, \@a:=1)");
541     $dbh->do("ALTER TABLE action_logs MODIFY action_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY");
542     print "Upgrade to $DBversion done (added column to action_logs)\n";
543     SetVersion ($DBversion);
544 }
545
546 $DBversion = "3.00.00.018";
547 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
548     $dbh->do("ALTER TABLE `zebraqueue`
549                     ADD `done` INT NOT NULL DEFAULT '0',
550                     ADD `time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ;
551             ");
552     print "Upgrade to $DBversion done (adding timestamp and done columns to zebraque table to improve problem tracking) added)\n";
553     SetVersion ($DBversion);
554 }
555
556 $DBversion = "3.00.00.019";
557 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
558     $dbh->do("ALTER TABLE biblio MODIFY biblionumber INT(11) NOT NULL AUTO_INCREMENT");
559     $dbh->do("ALTER TABLE biblioitems MODIFY biblioitemnumber INT(11) NOT NULL AUTO_INCREMENT");
560     $dbh->do("ALTER TABLE items MODIFY itemnumber INT(11) NOT NULL AUTO_INCREMENT");
561     print "Upgrade to $DBversion done (made bib/item PKs auto_increment)\n";
562     SetVersion ($DBversion);
563 }
564
565 $DBversion = "3.00.00.020";
566 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
567     $dbh->do("ALTER TABLE deleteditems
568               DROP KEY `delitembarcodeidx`,
569               ADD KEY `delitembarcodeidx` (`barcode`)");
570     print "Upgrade to $DBversion done (dropped uniqueness of key on deleteditems.barcode)\n";
571     SetVersion ($DBversion);
572 }
573
574 $DBversion = "3.00.00.021";
575 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
576     $dbh->do("ALTER TABLE items CHANGE homebranch homebranch VARCHAR(10)");
577     $dbh->do("ALTER TABLE deleteditems CHANGE homebranch homebranch VARCHAR(10)");
578     $dbh->do("ALTER TABLE statistics CHANGE branch branch VARCHAR(10)");
579     $dbh->do("ALTER TABLE subscription CHANGE lastbranch lastbranch VARCHAR(10)");
580     print "Upgrade to $DBversion done (extended missed branchcode columns to 10 chars)\n";
581     SetVersion ($DBversion);
582 }
583
584 $DBversion = "3.00.00.022";
585 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
586     $dbh->do("ALTER TABLE items
587                 ADD `damaged` tinyint(1) default NULL AFTER notforloan");
588     $dbh->do("ALTER TABLE deleteditems
589                 ADD `damaged` tinyint(1) default NULL AFTER notforloan");
590     print "Upgrade to $DBversion done (adding damaged column to items table)\n";
591     SetVersion ($DBversion);
592 }
593
594 $DBversion = "3.00.00.023";
595 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
596      $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
597          VALUES ('yuipath','http://yui.yahooapis.com/2.3.1/build','Insert the path to YUI libraries','','free')");
598     print "Upgrade to $DBversion done (adding new system preference for controlling YUI path)\n";
599     SetVersion ($DBversion);
600 }
601 $DBversion = "3.00.00.024";
602 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
603     $dbh->do("ALTER TABLE biblioitems CHANGE  itemtype itemtype VARCHAR(10)");
604     print "Upgrade to $DBversion done (changing itemtype to (10))\n";
605     SetVersion ($DBversion);
606 }
607
608 $DBversion = "3.00.00.025";
609 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
610     $dbh->do("ALTER TABLE items ADD COLUMN itype VARCHAR(10)");
611     $dbh->do("ALTER TABLE deleteditems ADD COLUMN itype VARCHAR(10) AFTER uri");
612     if(C4::Context->preference('item-level_itypes')){
613         $dbh->do('update items,biblioitems set items.itype=biblioitems.itemtype where items.biblionumber=biblioitems.biblionumber and itype is null');
614     }
615     print "Upgrade to $DBversion done (reintroduce items.itype - fill from itemtype)\n ";
616     SetVersion ($DBversion);
617 }
618
619 $DBversion = "3.00.00.026";
620 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
621     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
622        VALUES ('HomeOrHoldingBranch','homebranch','homebranch|holdingbranch','With independent branches turned on this decides whether to check the items holdingbranch or homebranch at circulatilon','choice')");
623     print "Upgrade to $DBversion done (adding new system preference for choosing whether homebranch or holdingbranch is checked in circulation)\n";
624     SetVersion ($DBversion);
625 }
626
627 $DBversion = "3.00.00.027";
628 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
629     $dbh->do("CREATE TABLE `marc_matchers` (
630                 `matcher_id` int(11) NOT NULL auto_increment,
631                 `code` varchar(10) NOT NULL default '',
632                 `description` varchar(255) NOT NULL default '',
633                 `record_type` varchar(10) NOT NULL default 'biblio',
634                 `threshold` int(11) NOT NULL default 0,
635                 PRIMARY KEY (`matcher_id`),
636                 KEY `code` (`code`),
637                 KEY `record_type` (`record_type`)
638               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
639     $dbh->do("CREATE TABLE `matchpoints` (
640                 `matcher_id` int(11) NOT NULL,
641                 `matchpoint_id` int(11) NOT NULL auto_increment,
642                 `search_index` varchar(30) NOT NULL default '',
643                 `score` int(11) NOT NULL default 0,
644                 PRIMARY KEY (`matchpoint_id`),
645                 CONSTRAINT `matchpoints_ifbk_1` FOREIGN KEY (`matcher_id`)
646                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE
647               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
648     $dbh->do("CREATE TABLE `matchpoint_components` (
649                 `matchpoint_id` int(11) NOT NULL,
650                 `matchpoint_component_id` int(11) NOT NULL auto_increment,
651                 sequence int(11) NOT NULL default 0,
652                 tag varchar(3) NOT NULL default '',
653                 subfields varchar(40) NOT NULL default '',
654                 offset int(4) NOT NULL default 0,
655                 length int(4) NOT NULL default 0,
656                 PRIMARY KEY (`matchpoint_component_id`),
657                 KEY `by_sequence` (`matchpoint_id`, `sequence`),
658                 CONSTRAINT `matchpoint_components_ifbk_1` FOREIGN KEY (`matchpoint_id`)
659                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
660               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
661     $dbh->do("CREATE TABLE `matchpoint_component_norms` (
662                 `matchpoint_component_id` int(11) NOT NULL,
663                 `sequence`  int(11) NOT NULL default 0,
664                 `norm_routine` varchar(50) NOT NULL default '',
665                 KEY `matchpoint_component_norms` (`matchpoint_component_id`, `sequence`),
666                 CONSTRAINT `matchpoint_component_norms_ifbk_1` FOREIGN KEY (`matchpoint_component_id`)
667                            REFERENCES `matchpoint_components` (`matchpoint_component_id`) ON DELETE CASCADE ON UPDATE CASCADE
668               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
669     $dbh->do("CREATE TABLE `matcher_matchpoints` (
670                 `matcher_id` int(11) NOT NULL,
671                 `matchpoint_id` int(11) NOT NULL,
672                 CONSTRAINT `matcher_matchpoints_ifbk_1` FOREIGN KEY (`matcher_id`)
673                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE,
674                 CONSTRAINT `matcher_matchpoints_ifbk_2` FOREIGN KEY (`matchpoint_id`)
675                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
676               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
677     $dbh->do("CREATE TABLE `matchchecks` (
678                 `matcher_id` int(11) NOT NULL,
679                 `matchcheck_id` int(11) NOT NULL auto_increment,
680                 `source_matchpoint_id` int(11) NOT NULL,
681                 `target_matchpoint_id` int(11) NOT NULL,
682                 PRIMARY KEY (`matchcheck_id`),
683                 CONSTRAINT `matcher_matchchecks_ifbk_1` FOREIGN KEY (`matcher_id`)
684                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE,
685                 CONSTRAINT `matcher_matchchecks_ifbk_2` FOREIGN KEY (`source_matchpoint_id`)
686                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE,
687                 CONSTRAINT `matcher_matchchecks_ifbk_3` FOREIGN KEY (`target_matchpoint_id`)
688                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
689               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
690     print "Upgrade to $DBversion done (added C4::Matcher serialization tables)\n ";
691     SetVersion ($DBversion);
692 }
693
694 $DBversion = "3.00.00.028";
695 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
696     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
697        VALUES ('canreservefromotherbranches','1','','With Independent branches on, can a user from one library reserve an item from another library','YesNo')");
698     print "Upgrade to $DBversion done (adding new system preference for changing reserve/holds behaviour with independent branches)\n";
699     SetVersion ($DBversion);
700 }
701
702
703 $DBversion = "3.00.00.029";
704 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
705     $dbh->do("ALTER TABLE `import_batches` ADD `matcher_id` int(11) NULL AFTER `import_batch_id`");
706     print "Upgrade to $DBversion done (adding matcher_id to import_batches)\n";
707     SetVersion ($DBversion);
708 }
709
710 $DBversion = "3.00.00.030";
711 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
712     $dbh->do("
713 CREATE TABLE services_throttle (
714   service_type varchar(10) NOT NULL default '',
715   service_count varchar(45) default NULL,
716   PRIMARY KEY  (service_type)
717 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
718 ");
719     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
720        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')");
721  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
722        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')");
723  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
724        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')");
725  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
726        VALUES ('XISBNDailyLimit',499,'','The xISBN Web service is free for non-commercial use when usage does not exceed 500 requests per day','free')");
727  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
728        VALUES ('PINESISBN',0,'','Use with FRBRizeEditions. If ON, Koha will use PINES OISBN web service in the Editions tab on the detail pages.','YesNo')");
729  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
730        VALUES ('ThingISBN',0,'','Use with FRBRizeEditions. If ON, Koha will use the ThingISBN web service in the Editions tab on the detail pages.','YesNo')");
731     print "Upgrade to $DBversion done (adding services throttle table and sysprefs for xISBN)\n";
732     SetVersion ($DBversion);
733 }
734
735 $DBversion = "3.00.00.031";
736 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
737
738 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryStemming',1,'If ON, enables query stemming',NULL,'YesNo')");
739 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryFuzzy',1,'If ON, enables fuzzy option for searches',NULL,'YesNo')");
740 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryWeightFields',1,'If ON, enables field weighting',NULL,'YesNo')");
741 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('WebBasedSelfCheck',0,'If ON, enables the web-based self-check system',NULL,'YesNo')");
742 $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')");
743 $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')");
744 $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')");
745 $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')");
746 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('defaultSortOrder',NULL,'Specify the default sort order','asc|dsc|az|za','Choice')");
747 $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')");
748 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACdefaultSortOrder',NULL,'Specify the default sort order','asc|dsc|za|az','Choice')");
749 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('staffClientBaseURL','','Specify the base URL of the staff client',NULL,'free')");
750 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('minPasswordLength',3,'Specify the minimum length of a patron/staff password',NULL,'free')");
751 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('noItemTypeImages',0,'If ON, disables item-type images',NULL,'YesNo')");
752 $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')");
753 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('holdCancelLength','','Specify how many days before a hold is canceled',NULL,'free')");
754 $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')");
755 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('finesMode','test','Choose the fines mode, test or production','test|production','Choice')");
756 $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')");
757 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('itemBarcodeInputFilter','','If set, allows specification of a item barcode input filter','cuecat','Choice')");
758 $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')");
759 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('URLLinkText','','Text to display as the link anchor in the OPAC',NULL,'free')");
760 $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')");
761 $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')");
762 $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')");
763 $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')");
764 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACUserCSS',0,'Add CSS to be included in the OPAC',NULL,'free')");
765
766     print "Upgrade to $DBversion done (adding additional system preference)\n";
767     SetVersion ($DBversion);
768 }
769
770 $DBversion = "3.00.00.032";
771 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
772     $dbh->do("UPDATE `marc_subfield_structure` SET `kohafield` = 'items.wthdrawn' WHERE `kohafield` = 'items.withdrawn'");
773     print "Upgrade to $DBversion done (fixed MARC framework references to items.withdrawn)\n";
774     SetVersion ($DBversion);
775 }
776
777 $DBversion = "3.00.00.033";
778 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
779     $dbh->do("INSERT INTO `userflags` VALUES(17,'staffaccess','Modify login / permissions for staff users',0)");
780     print "Upgrade to $DBversion done (Adding permissions flag for staff member access modification.  )\n";
781     SetVersion ($DBversion);
782 }
783
784 $DBversion = "3.00.00.034";
785 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
786     $dbh->do("ALTER TABLE `virtualshelves` ADD COLUMN `sortfield` VARCHAR(16) ");
787     print "Upgrade to $DBversion done (Adding sortfield for Virtual Shelves.  )\n";
788     SetVersion ($DBversion);
789 }
790
791 $DBversion = "3.00.00.035";
792 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
793     $dbh->do("UPDATE marc_subfield_structure
794               SET authorised_value = 'cn_source'
795               WHERE kohafield IN ('items.cn_source', 'biblioitems.cn_source')
796               AND (authorised_value is NULL OR authorised_value = '')");
797     print "Upgrade to $DBversion done (MARC frameworks: make classification source a drop-down)\n";
798     SetVersion ($DBversion);
799 }
800
801 $DBversion = "3.00.00.036";
802 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
803     $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');");
804     print "Upgrade to $DBversion done (OPACItemsResultsDisplay systempreference added)\n";
805     SetVersion ($DBversion);
806 }
807
808 $DBversion = "3.00.00.037";
809 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
810     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactfirstname` varchar(255)");
811     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactsurname` varchar(255)");
812     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress1` varchar(255)");
813     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress2` varchar(255)");
814     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress3` varchar(255)");
815     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactzipcode` varchar(50)");
816     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactphone` varchar(50)");
817     print "Upgrade to $DBversion done (Adding Alternative Contact Person information to borrowers table)\n";
818     SetVersion ($DBversion);
819 }
820
821 $DBversion = "3.00.00.038";
822 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
823     $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'");
824     $dbh->do("DELETE FROM `systempreferences` WHERE variable='hideBiblioNumber'");
825     print "Upgrade to $DBversion done ('alter finesMode systempreference, remove superfluous syspref.')\n";
826     SetVersion ($DBversion);
827 }
828
829 $DBversion = "3.00.00.039";
830 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
831     $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')");
832     $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')");
833     $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')");
834     # $dbh->do("DELETE FROM `systempreferences` WHERE variable='HomeOrHoldingBranch'"); # Bug #2752
835     print "Upgrade to $DBversion done ('add circ sysprefs CircControl, finesCalendar, and uppercasesurnames, and delete HomeOrHoldingBranch.')\n";
836     SetVersion ($DBversion);
837 }
838
839 $DBversion = "3.00.00.040";
840 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
841         $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')");
842         $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')");
843         print "Upgrade to $DBversion done ('add circ sysprefs todaysIssuesDefaultSortOrder and previousIssuesDefaultSortOrder.')\n";
844     SetVersion ($DBversion);
845 }
846
847
848 $DBversion = "3.00.00.041";
849 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
850     # Strictly speaking it is not necessary to explicitly change
851     # NULL values to 0, because the ALTER TABLE statement will do that.
852     # However, setting them first avoids a warning.
853     $dbh->do("UPDATE items SET notforloan = 0 WHERE notforloan IS NULL");
854     $dbh->do("UPDATE items SET damaged = 0 WHERE damaged IS NULL");
855     $dbh->do("UPDATE items SET itemlost = 0 WHERE itemlost IS NULL");
856     $dbh->do("UPDATE items SET wthdrawn = 0 WHERE wthdrawn IS NULL");
857     $dbh->do("ALTER TABLE items
858                 MODIFY notforloan tinyint(1) NOT NULL default 0,
859                 MODIFY damaged    tinyint(1) NOT NULL default 0,
860                 MODIFY itemlost   tinyint(1) NOT NULL default 0,
861                 MODIFY wthdrawn   tinyint(1) NOT NULL default 0");
862     $dbh->do("UPDATE deleteditems SET notforloan = 0 WHERE notforloan IS NULL");
863     $dbh->do("UPDATE deleteditems SET damaged = 0 WHERE damaged IS NULL");
864     $dbh->do("UPDATE deleteditems SET itemlost = 0 WHERE itemlost IS NULL");
865     $dbh->do("UPDATE deleteditems SET wthdrawn = 0 WHERE wthdrawn IS NULL");
866     $dbh->do("ALTER TABLE deleteditems
867                 MODIFY notforloan tinyint(1) NOT NULL default 0,
868                 MODIFY damaged    tinyint(1) NOT NULL default 0,
869                 MODIFY itemlost   tinyint(1) NOT NULL default 0,
870                 MODIFY wthdrawn   tinyint(1) NOT NULL default 0");
871         print "Upgrade to $DBversion done (disallow NULL in several item status columns)\n";
872     SetVersion ($DBversion);
873 }
874
875 $DBversion = "3.00.00.04";
876 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
877     $dbh->do("ALTER TABLE aqbooksellers CHANGE name name mediumtext NOT NULL");
878         print "Upgrade to $DBversion done (disallow NULL in aqbooksellers.name; part of fix for bug 1251)\n";
879     SetVersion ($DBversion);
880 }
881
882 $DBversion = "3.00.00.043";
883 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
884     $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");
885         print "Upgrade to $DBversion done (currency table: add symbol and timestamp columns)\n";
886     SetVersion ($DBversion);
887 }
888
889 $DBversion = "3.00.00.044";
890 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
891     $dbh->do("ALTER TABLE deletedborrowers
892   ADD `altcontactfirstname` varchar(255) default NULL,
893   ADD `altcontactsurname` varchar(255) default NULL,
894   ADD `altcontactaddress1` varchar(255) default NULL,
895   ADD `altcontactaddress2` varchar(255) default NULL,
896   ADD `altcontactaddress3` varchar(255) default NULL,
897   ADD `altcontactzipcode` varchar(50) default NULL,
898   ADD `altcontactphone` varchar(50) default NULL
899   ");
900   $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES
901 ('OPACBaseURL',NULL,'Specify the Base URL of the OPAC, e.g., opac.mylibrary.com, the http:// will be added automatically by Koha.',NULL,'Free'),
902 ('language','en','Set the default language in the staff client.',NULL,'Languages'),
903 ('QueryAutoTruncate',1,'If ON, query truncation is enabled by default',NULL,'YesNo'),
904 ('QueryRemoveStopwords',0,'If ON, stopwords listed in the Administration area will be removed from queries',NULL,'YesNo')
905   ");
906         print "Upgrade to $DBversion done (syncing deletedborrowers table with borrowers table)\n";
907     SetVersion ($DBversion);
908 }
909
910 #-- http://www.w3.org/International/articles/language-tags/
911
912 #-- RFC4646
913 $DBversion = "3.00.00.045";
914 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
915     $dbh->do("
916 CREATE TABLE language_subtag_registry (
917         subtag varchar(25),
918         type varchar(25), -- language-script-region-variant-extension-privateuse
919         description varchar(25), -- only one of the possible descriptions for ease of reference, see language_descriptions for the complete list
920         added date,
921         KEY `subtag` (`subtag`)
922 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
923
924 #-- TODO: add suppress_scripts
925 #-- this maps three letter codes defined in iso639.2 back to their
926 #-- two letter equivilents in rfc4646 (LOC maintains iso639+)
927  $dbh->do("CREATE TABLE language_rfc4646_to_iso639 (
928         rfc4646_subtag varchar(25),
929         iso639_2_code varchar(25),
930         KEY `rfc4646_subtag` (`rfc4646_subtag`)
931 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
932
933  $dbh->do("CREATE TABLE language_descriptions (
934         subtag varchar(25),
935         type varchar(25),
936         lang varchar(25),
937         description varchar(255),
938         KEY `lang` (`lang`)
939 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
940
941 #-- bi-directional support, keyed by script subcode
942  $dbh->do("CREATE TABLE language_script_bidi (
943         rfc4646_subtag varchar(25), -- script subtag, Arab, Hebr, etc.
944         bidi varchar(3), -- rtl ltr
945         KEY `rfc4646_subtag` (`rfc4646_subtag`)
946 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
947
948 #-- BIDI Stuff, Arabic and Hebrew
949  $dbh->do("INSERT INTO language_script_bidi(rfc4646_subtag,bidi)
950 VALUES( 'Arab', 'rtl')");
951  $dbh->do("INSERT INTO language_script_bidi(rfc4646_subtag,bidi)
952 VALUES( 'Hebr', 'rtl')");
953
954 #-- TODO: need to map language subtags to script subtags for detection
955 #-- of bidi when script is not specified (like ar, he)
956  $dbh->do("CREATE TABLE language_script_mapping (
957         language_subtag varchar(25),
958         script_subtag varchar(25),
959         KEY `language_subtag` (`language_subtag`)
960 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
961
962 #-- Default mappings between script and language subcodes
963  $dbh->do("INSERT INTO language_script_mapping(language_subtag,script_subtag)
964 VALUES( 'ar', 'Arab')");
965  $dbh->do("INSERT INTO language_script_mapping(language_subtag,script_subtag)
966 VALUES( 'he', 'Hebr')");
967
968         print "Upgrade to $DBversion done (adding language subtag registry and basic BiDi support NOTE: You should import the subtag registry SQL)\n";
969     SetVersion ($DBversion);
970 }
971
972 $DBversion = "3.00.00.046";
973 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
974     $dbh->do("ALTER TABLE `subscription` CHANGE `numberlength` `numberlength` int(11) default '0' ,
975                  CHANGE `weeklength` `weeklength` int(11) default '0'");
976     $dbh->do("CREATE TABLE `serialitems` (`serialid` int(11) NOT NULL, `itemnumber` int(11) NOT NULL, UNIQUE KEY `serialididx` (`serialid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
977     $dbh->do("INSERT INTO `serialitems` SELECT `serialid`,`itemnumber` from serial where NOT ISNULL(itemnumber) && itemnumber <> '' && itemnumber NOT LIKE '%,%'");
978         print "Upgrade to $DBversion done (Add serialitems table to link serial issues to items. )\n";
979     SetVersion ($DBversion);
980 }
981
982 $DBversion = "3.00.00.047";
983 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
984     $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');");
985         print "Upgrade to $DBversion done ( Added OpacRenewalAllowed syspref )\n";
986     SetVersion ($DBversion);
987 }
988
989 $DBversion = "3.00.00.048";
990 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
991     $dbh->do("ALTER TABLE `items` ADD `more_subfields_xml` longtext default NULL AFTER `itype`");
992         print "Upgrade to $DBversion done (added items.more_subfields_xml)\n";
993     SetVersion ($DBversion);
994 }
995
996 $DBversion = "3.00.00.049";
997 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
998         $dbh->do("ALTER TABLE `z3950servers` ADD `encoding` text default NULL AFTER type ");
999         print "Upgrade to $DBversion done ( Added encoding field to z3950servers table )\n";
1000     SetVersion ($DBversion);
1001 }
1002
1003 $DBversion = "3.00.00.050";
1004 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1005     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacHighlightedWords','0','If Set, query matched terms are highlighted in OPAC',NULL,'YesNo');");
1006         print "Upgrade to $DBversion done ( Added OpacHighlightedWords syspref )\n";
1007     SetVersion ($DBversion);
1008 }
1009
1010 $DBversion = "3.00.00.051";
1011 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1012     $dbh->do("UPDATE systempreferences SET explanation = 'Define the current theme for the OPAC interface.' WHERE variable = 'opacthemes';");
1013         print "Upgrade to $DBversion done ( Corrected opacthemes explanation. )\n";
1014     SetVersion ($DBversion);
1015 }
1016
1017 $DBversion = "3.00.00.052";
1018 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1019     $dbh->do("ALTER TABLE `deleteditems` ADD `more_subfields_xml` LONGTEXT DEFAULT NULL AFTER `itype`");
1020         print "Upgrade to $DBversion done ( Adding missing column to deleteditems table. )\n";
1021     SetVersion ($DBversion);
1022 }
1023
1024 $DBversion = "3.00.00.053";
1025 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1026     $dbh->do("CREATE TABLE `printers_profile` (
1027             `prof_id` int(4) NOT NULL auto_increment,
1028             `printername` varchar(40) NOT NULL,
1029             `tmpl_id` int(4) NOT NULL,
1030             `paper_bin` varchar(20) NOT NULL,
1031             `offset_horz` float default NULL,
1032             `offset_vert` float default NULL,
1033             `creep_horz` float default NULL,
1034             `creep_vert` float default NULL,
1035             `unit` char(20) NOT NULL default 'POINT',
1036             PRIMARY KEY  (`prof_id`),
1037             UNIQUE KEY `printername` (`printername`,`tmpl_id`,`paper_bin`),
1038             CONSTRAINT `printers_profile_pnfk_1` FOREIGN KEY (`tmpl_id`) REFERENCES `labels_templates` (`tmpl_id`) ON DELETE CASCADE ON UPDATE CASCADE
1039             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1040     $dbh->do("CREATE TABLE `labels_profile` (
1041             `tmpl_id` int(4) NOT NULL,
1042             `prof_id` int(4) NOT NULL,
1043             UNIQUE KEY `tmpl_id` (`tmpl_id`),
1044             UNIQUE KEY `prof_id` (`prof_id`)
1045             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1046     print "Upgrade to $DBversion done ( Printer Profile tables added )\n";
1047     SetVersion ($DBversion);
1048 }
1049
1050 $DBversion = "3.00.00.054";
1051 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1052     $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';");
1053         print "Upgrade to $DBversion done ( Added another barcode autogeneration sequence to barcode.pl. )\n";
1054     SetVersion ($DBversion);
1055 }
1056
1057 $DBversion = "3.00.00.055";
1058 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1059     $dbh->do("ALTER TABLE `zebraqueue` ADD KEY `zebraqueue_lookup` (`server`, `biblio_auth_number`, `operation`, `done`)");
1060         print "Upgrade to $DBversion done ( Added index on zebraqueue. )\n";
1061     SetVersion ($DBversion);
1062 }
1063 $DBversion = "3.00.00.056";
1064 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1065     if (C4::Context->preference("marcflavour") eq 'UNIMARC') {
1066         $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) ");
1067     } else {
1068         $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) ");
1069     }
1070     $dbh->do("ALTER TABLE `items` ADD `enumchron` VARCHAR(80) DEFAULT NULL;");
1071     print "Upgrade to $DBversion done ( Added item.enumchron column, and framework map to 952h )\n";
1072     SetVersion ($DBversion);
1073 }
1074
1075 $DBversion = "3.00.00.057";
1076 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1077     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH','0','if ON, OAI-PMH server is enabled',NULL,'YesNo');");
1078     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH:archiveID','KOHA-OAI-TEST','OAI-PMH archive identification',NULL,'Free');");
1079     $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');");
1080     $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');");
1081     $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');");
1082     SetVersion ($DBversion);
1083 }
1084
1085 $DBversion = "3.00.00.058";
1086 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1087     $dbh->do("ALTER TABLE `opac_news`
1088                 CHANGE `lang` `lang` VARCHAR( 25 )
1089                 CHARACTER SET utf8
1090                 COLLATE utf8_general_ci
1091                 NOT NULL default ''");
1092         print "Upgrade to $DBversion done ( lang field in opac_news made longer )\n";
1093     SetVersion ($DBversion);
1094 }
1095
1096 $DBversion = "3.00.00.059";
1097 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1098
1099     $dbh->do("CREATE TABLE IF NOT EXISTS `labels_templates` (
1100             `tmpl_id` int(4) NOT NULL auto_increment,
1101             `tmpl_code` char(100)  default '',
1102             `tmpl_desc` char(100) default '',
1103             `page_width` float default '0',
1104             `page_height` float default '0',
1105             `label_width` float default '0',
1106             `label_height` float default '0',
1107             `topmargin` float default '0',
1108             `leftmargin` float default '0',
1109             `cols` int(2) default '0',
1110             `rows` int(2) default '0',
1111             `colgap` float default '0',
1112             `rowgap` float default '0',
1113             `active` int(1) default NULL,
1114             `units` char(20)  default 'PX',
1115             `fontsize` int(4) NOT NULL default '3',
1116             PRIMARY KEY  (`tmpl_id`)
1117             ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1118     $dbh->do("CREATE TABLE  IF NOT EXISTS `printers_profile` (
1119             `prof_id` int(4) NOT NULL auto_increment,
1120             `printername` varchar(40) NOT NULL,
1121             `tmpl_id` int(4) NOT NULL,
1122             `paper_bin` varchar(20) NOT NULL,
1123             `offset_horz` float default NULL,
1124             `offset_vert` float default NULL,
1125             `creep_horz` float default NULL,
1126             `creep_vert` float default NULL,
1127             `unit` char(20) NOT NULL default 'POINT',
1128             PRIMARY KEY  (`prof_id`),
1129             UNIQUE KEY `printername` (`printername`,`tmpl_id`,`paper_bin`),
1130             CONSTRAINT `printers_profile_pnfk_1` FOREIGN KEY (`tmpl_id`) REFERENCES `labels_templates` (`tmpl_id`) ON DELETE CASCADE ON UPDATE CASCADE
1131             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1132     print "Upgrade to $DBversion done ( Added labels_templates table if it did not exist. )\n";
1133     SetVersion ($DBversion);
1134 }
1135
1136 $DBversion = "3.00.00.060";
1137 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1138     $dbh->do("CREATE TABLE IF NOT EXISTS `patronimage` (
1139             `cardnumber` varchar(16) NOT NULL,
1140             `mimetype` varchar(15) NOT NULL,
1141             `imagefile` mediumblob NOT NULL,
1142             PRIMARY KEY  (`cardnumber`),
1143             CONSTRAINT `patronimage_fk1` FOREIGN KEY (`cardnumber`) REFERENCES `borrowers` (`cardnumber`) ON DELETE CASCADE ON UPDATE CASCADE
1144             ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1145         print "Upgrade to $DBversion done ( Added patronimage table. )\n";
1146     SetVersion ($DBversion);
1147 }
1148
1149 $DBversion = "3.00.00.061";
1150 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1151     $dbh->do("ALTER TABLE labels_templates ADD COLUMN font char(10) NOT NULL DEFAULT 'TR';");
1152         print "Upgrade to $DBversion done ( Added font column to labels_templates )\n";
1153     SetVersion ($DBversion);
1154 }
1155
1156 $DBversion = "3.00.00.062";
1157 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1158     $dbh->do("CREATE TABLE `old_issues` (
1159                 `borrowernumber` int(11) default NULL,
1160                 `itemnumber` int(11) default NULL,
1161                 `date_due` date default NULL,
1162                 `branchcode` varchar(10) default NULL,
1163                 `issuingbranch` varchar(18) default NULL,
1164                 `returndate` date default NULL,
1165                 `lastreneweddate` date default NULL,
1166                 `return` varchar(4) default NULL,
1167                 `renewals` tinyint(4) default NULL,
1168                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1169                 `issuedate` date default NULL,
1170                 KEY `old_issuesborridx` (`borrowernumber`),
1171                 KEY `old_issuesitemidx` (`itemnumber`),
1172                 KEY `old_bordate` (`borrowernumber`,`timestamp`),
1173                 CONSTRAINT `old_issues_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1174                     ON DELETE SET NULL ON UPDATE SET NULL,
1175                 CONSTRAINT `old_issues_ibfk_2` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`)
1176                     ON DELETE SET NULL ON UPDATE SET NULL
1177                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1178     $dbh->do("CREATE TABLE `old_reserves` (
1179                 `borrowernumber` int(11) default NULL,
1180                 `reservedate` date default NULL,
1181                 `biblionumber` int(11) default NULL,
1182                 `constrainttype` varchar(1) default NULL,
1183                 `branchcode` varchar(10) default NULL,
1184                 `notificationdate` date default NULL,
1185                 `reminderdate` date default NULL,
1186                 `cancellationdate` date default NULL,
1187                 `reservenotes` mediumtext,
1188                 `priority` smallint(6) default NULL,
1189                 `found` varchar(1) default NULL,
1190                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1191                 `itemnumber` int(11) default NULL,
1192                 `waitingdate` date default NULL,
1193                 KEY `old_reserves_borrowernumber` (`borrowernumber`),
1194                 KEY `old_reserves_biblionumber` (`biblionumber`),
1195                 KEY `old_reserves_itemnumber` (`itemnumber`),
1196                 KEY `old_reserves_branchcode` (`branchcode`),
1197                 CONSTRAINT `old_reserves_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1198                     ON DELETE SET NULL ON UPDATE SET NULL,
1199                 CONSTRAINT `old_reserves_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`)
1200                     ON DELETE SET NULL ON UPDATE SET NULL,
1201                 CONSTRAINT `old_reserves_ibfk_3` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`)
1202                     ON DELETE SET NULL ON UPDATE SET NULL
1203                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1204
1205     # move closed transactions to old_* tables
1206     $dbh->do("INSERT INTO old_issues SELECT * FROM issues WHERE returndate IS NOT NULL");
1207     $dbh->do("DELETE FROM issues WHERE returndate IS NOT NULL");
1208     $dbh->do("INSERT INTO old_reserves SELECT * FROM reserves WHERE cancellationdate IS NOT NULL OR found = 'F'");
1209     $dbh->do("DELETE FROM reserves WHERE cancellationdate IS NOT NULL OR found = 'F'");
1210
1211         print "Upgrade to $DBversion done ( Added old_issues and old_reserves tables )\n";
1212     SetVersion ($DBversion);
1213 }
1214
1215 $DBversion = "3.00.00.063";
1216 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1217     $dbh->do("ALTER TABLE deleteditems
1218                 CHANGE COLUMN booksellerid booksellerid MEDIUMTEXT DEFAULT NULL,
1219                 ADD COLUMN enumchron VARCHAR(80) DEFAULT NULL AFTER more_subfields_xml,
1220                 ADD COLUMN copynumber SMALLINT(6) DEFAULT NULL AFTER enumchron;");
1221     $dbh->do("ALTER TABLE items
1222                 CHANGE COLUMN booksellerid booksellerid MEDIUMTEXT,
1223                 ADD COLUMN copynumber SMALLINT(6) DEFAULT NULL AFTER enumchron;");
1224         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";
1225     SetVersion ($DBversion);
1226 }
1227
1228 $DBversion = "3.00.00.064";
1229 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1230     $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');");
1231     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AWSAccessKeyID','','See:  http://aws.amazon.com','','free');");
1232     $dbh->do("DELETE FROM `systempreferences` WHERE variable='AmazonDevKey';");
1233     $dbh->do("DELETE FROM `systempreferences` WHERE variable='XISBNAmazonSimilarItems';");
1234     $dbh->do("DELETE FROM `systempreferences` WHERE variable='OPACXISBNAmazonSimilarItems';");
1235     print "Upgrade to $DBversion done (IMPORTANT: Upgrading to Amazon.com Associates Web Service 4.0 ) \n";
1236     SetVersion ($DBversion);
1237 }
1238
1239 $DBversion = "3.00.00.065";
1240 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1241     $dbh->do("CREATE TABLE `patroncards` (
1242                 `cardid` int(11) NOT NULL auto_increment,
1243                 `batch_id` varchar(10) NOT NULL default '1',
1244                 `borrowernumber` int(11) NOT NULL,
1245                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1246                 PRIMARY KEY  (`cardid`),
1247                 KEY `patroncards_ibfk_1` (`borrowernumber`),
1248                 CONSTRAINT `patroncards_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE
1249                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1250     print "Upgrade to $DBversion done (Adding patroncards table for patroncards generation feature. ) \n";
1251     SetVersion ($DBversion);
1252 }
1253
1254 $DBversion = "3.00.00.066";
1255 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1256     $dbh->do("ALTER TABLE `virtualshelfcontents` MODIFY `dateadded` timestamp NOT NULL
1257 DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP;
1258 ");
1259     print "Upgrade to $DBversion done (fix for bug 1873: virtualshelfcontents dateadded column empty. ) \n";
1260     SetVersion ($DBversion);
1261 }
1262
1263 $DBversion = "3.00.00.067";
1264 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1265     $dbh->do("UPDATE systempreferences SET explanation = 'Enable patron images for the Staff Client', type = 'YesNo' WHERE variable = 'patronimages'");
1266     print "Upgrade to $DBversion done (Updating patronimages syspref to reflect current kohastructure.sql. ) \n";
1267     SetVersion ($DBversion);
1268 }
1269
1270 $DBversion = "3.00.00.068";
1271 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1272     $dbh->do("CREATE TABLE `permissions` (
1273                 `module_bit` int(11) NOT NULL DEFAULT 0,
1274                 `code` varchar(30) DEFAULT NULL,
1275                 `description` varchar(255) DEFAULT NULL,
1276                 PRIMARY KEY  (`module_bit`, `code`),
1277                 CONSTRAINT `permissions_ibfk_1` FOREIGN KEY (`module_bit`) REFERENCES `userflags` (`bit`)
1278                     ON DELETE CASCADE ON UPDATE CASCADE
1279               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1280     $dbh->do("CREATE TABLE `user_permissions` (
1281                 `borrowernumber` int(11) NOT NULL DEFAULT 0,
1282                 `module_bit` int(11) NOT NULL DEFAULT 0,
1283                 `code` varchar(30) DEFAULT NULL,
1284                 CONSTRAINT `user_permissions_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1285                     ON DELETE CASCADE ON UPDATE CASCADE,
1286                 CONSTRAINT `user_permissions_ibfk_2` FOREIGN KEY (`module_bit`, `code`)
1287                     REFERENCES `permissions` (`module_bit`, `code`)
1288                     ON DELETE CASCADE ON UPDATE CASCADE
1289               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1290
1291     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
1292     (13, 'edit_news', 'Write news for the OPAC and staff interfaces'),
1293     (13, 'label_creator', 'Create printable labels and barcodes from catalog and patron data'),
1294     (13, 'edit_calendar', 'Define days when the library is closed'),
1295     (13, 'moderate_comments', 'Moderate patron comments'),
1296     (13, 'edit_notices', 'Define notices'),
1297     (13, 'edit_notice_status_triggers', 'Set notice/status triggers for overdue items'),
1298     (13, 'view_system_logs', 'Browse the system logs'),
1299     (13, 'inventory', 'Perform inventory (stocktaking) of your catalogue'),
1300     (13, 'stage_marc_import', 'Stage MARC records into the reservoir'),
1301     (13, 'manage_staged_marc', 'Managed staged MARC records, including completing and reversing imports'),
1302     (13, 'export_catalog', 'Export bibliographic and holdings data'),
1303     (13, 'import_patrons', 'Import patron data'),
1304     (13, 'delete_anonymize_patrons', 'Delete old borrowers and anonymize circulation history (deletes borrower reading history)'),
1305     (13, 'batch_upload_patron_images', 'Upload patron images in batch or one at a time'),
1306     (13, 'schedule_tasks', 'Schedule tasks to run')");
1307
1308     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('GranularPermissions','0','Use detailed staff user permissions',NULL,'YesNo')");
1309
1310     print "Upgrade to $DBversion done (adding permissions and user_permissions tables and GranularPermissions syspref) \n";
1311     SetVersion ($DBversion);
1312 }
1313 $DBversion = "3.00.00.069";
1314 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1315     $dbh->do("ALTER TABLE labels_conf CHANGE COLUMN class classification int(1) DEFAULT NULL;");
1316         print "Upgrade to $DBversion done ( Correcting columname in labels_conf )\n";
1317     SetVersion ($DBversion);
1318 }
1319
1320 $DBversion = "3.00.00.070";
1321 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1322     $sth = $dbh->prepare("SELECT value FROM systempreferences WHERE variable='yuipath'");
1323     $sth->execute;
1324     my ($value) = $sth->fetchrow;
1325     $value =~ s/2.3.1/2.5.1/;
1326     $dbh->do("UPDATE systempreferences SET value='$value' WHERE variable='yuipath';");
1327         print "Update yuipath syspref to 2.5.1 if necessary\n";
1328     SetVersion ($DBversion);
1329 }
1330
1331 $DBversion = "3.00.00.071";
1332 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1333     $dbh->do(" ALTER TABLE `subscription` ADD `serialsadditems` TINYINT( 1 ) NOT NULL DEFAULT '0';");
1334     # fill the new field with the previous systempreference value, then drop the syspref
1335     my $sth = $dbh->prepare("SELECT value FROM systempreferences WHERE variable='serialsadditems'");
1336     $sth->execute;
1337     my ($serialsadditems) = $sth->fetchrow();
1338     $dbh->do("UPDATE subscription SET serialsadditems=$serialsadditems");
1339     $dbh->do("DELETE FROM systempreferences WHERE variable='serialsadditems'");
1340     print "Upgrade to $DBversion done ( moving serialsadditems from syspref to subscription )\n";
1341     SetVersion ($DBversion);
1342 }
1343
1344 $DBversion = "3.00.00.072";
1345 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1346     $dbh->do("ALTER TABLE labels_conf ADD COLUMN formatstring mediumtext DEFAULT NULL AFTER printingtype");
1347         print "Upgrade to $DBversion done ( Adding format string to labels generator. )\n";
1348     SetVersion ($DBversion);
1349 }
1350
1351 $DBversion = "3.00.00.073";
1352 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1353         $dbh->do("DROP TABLE IF EXISTS `tags_all`;");
1354         $dbh->do(q#
1355         CREATE TABLE `tags_all` (
1356           `tag_id`         int(11) NOT NULL auto_increment,
1357           `borrowernumber` int(11) NOT NULL,
1358           `biblionumber`   int(11) NOT NULL,
1359           `term`      varchar(255) NOT NULL,
1360           `language`       int(4) default NULL,
1361           `date_created` datetime  NOT NULL,
1362           PRIMARY KEY  (`tag_id`),
1363           KEY `tags_borrowers_fk_1` (`borrowernumber`),
1364           KEY `tags_biblionumber_fk_1` (`biblionumber`),
1365           CONSTRAINT `tags_borrowers_fk_1` FOREIGN KEY (`borrowernumber`)
1366                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1367           CONSTRAINT `tags_biblionumber_fk_1` FOREIGN KEY (`biblionumber`)
1368                 REFERENCES `biblio`     (`biblionumber`)  ON DELETE CASCADE ON UPDATE CASCADE
1369         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1370         #);
1371         $dbh->do("DROP TABLE IF EXISTS `tags_approval`;");
1372         $dbh->do(q#
1373         CREATE TABLE `tags_approval` (
1374           `term`   varchar(255) NOT NULL,
1375           `approved`     int(1) NOT NULL default '0',
1376           `date_approved` datetime       default NULL,
1377           `approved_by` int(11)          default NULL,
1378           `weight_total` int(9) NOT NULL default '1',
1379           PRIMARY KEY  (`term`),
1380           KEY `tags_approval_borrowers_fk_1` (`approved_by`),
1381           CONSTRAINT `tags_approval_borrowers_fk_1` FOREIGN KEY (`approved_by`)
1382                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE
1383         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1384         #);
1385         $dbh->do("DROP TABLE IF EXISTS `tags_index`;");
1386         $dbh->do(q#
1387         CREATE TABLE `tags_index` (
1388           `term`    varchar(255) NOT NULL,
1389           `biblionumber` int(11) NOT NULL,
1390           `weight`        int(9) NOT NULL default '1',
1391           PRIMARY KEY  (`term`,`biblionumber`),
1392           KEY `tags_index_biblionumber_fk_1` (`biblionumber`),
1393           CONSTRAINT `tags_index_term_fk_1` FOREIGN KEY (`term`)
1394                 REFERENCES `tags_approval` (`term`)  ON DELETE CASCADE ON UPDATE CASCADE,
1395           CONSTRAINT `tags_index_biblionumber_fk_1` FOREIGN KEY (`biblionumber`)
1396                 REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
1397         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1398         #);
1399         $dbh->do(q#
1400         INSERT INTO `systempreferences` VALUES
1401                 ('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=',''),
1402                 ('BakerTaylorEnabled','0','','Enable or disable all Baker & Taylor features.','YesNo'),
1403                 ('BakerTaylorPassword','','','Baker & Taylor Password for Content Cafe (external content)','Textarea'),
1404                 ('BakerTaylorUsername','','','Baker & Taylor Username for Content Cafe (external content)','Textarea'),
1405                 ('TagsEnabled','1','','Enables or disables all tagging features.  This is the main switch for tags.','YesNo'),
1406                 ('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.',''),
1407                 ('TagsInputOnDetail','1','','Allow users to input tags from the detail page.',         'YesNo'),
1408                 ('TagsInputOnList',  '0','','Allow users to input tags from the search results list.', 'YesNo'),
1409                 ('TagsModeration',  NULL,'','Require tags from patrons to be approved before becoming visible.','YesNo'),
1410                 ('TagsShowOnDetail','10','','Number of tags to display on detail page.  0 is off.',        'Integer'),
1411                 ('TagsShowOnList',   '6','','Number of tags to display on search results list.  0 is off.','Integer')
1412         #);
1413         print "Upgrade to $DBversion done (Baker/Taylor,Tags: sysprefs and tables (tags_all, tags_index, tags_approval)) \n";
1414         SetVersion ($DBversion);
1415 }
1416
1417 $DBversion = "3.00.00.074";
1418 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1419     $dbh->do( q(update itemtypes set imageurl = concat( 'npl/', imageurl )
1420                   where imageurl not like 'http%'
1421                     and imageurl is not NULL
1422                     and imageurl != '') );
1423     print "Upgrade to $DBversion done (updating imagetype.imageurls to reflect new icon locations.)\n";
1424     SetVersion ($DBversion);
1425 }
1426
1427 $DBversion = "3.00.00.075";
1428 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1429     $dbh->do( q(alter table authorised_values add imageurl varchar(200) default NULL) );
1430     print "Upgrade to $DBversion done (adding imageurl field to authorised_values table)\n";
1431     SetVersion ($DBversion);
1432 }
1433
1434 $DBversion = "3.00.00.076";
1435 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1436     $dbh->do("ALTER TABLE import_batches
1437               ADD COLUMN nomatch_action enum('create_new', 'ignore') NOT NULL default 'create_new' AFTER overlay_action");
1438     $dbh->do("ALTER TABLE import_batches
1439               ADD COLUMN item_action enum('always_add', 'add_only_for_matches', 'add_only_for_new', 'ignore')
1440                   NOT NULL default 'always_add' AFTER nomatch_action");
1441     $dbh->do("ALTER TABLE import_batches
1442               MODIFY overlay_action  enum('replace', 'create_new', 'use_template', 'ignore')
1443                   NOT NULL default 'create_new'");
1444     $dbh->do("ALTER TABLE import_records
1445               MODIFY status  enum('error', 'staged', 'imported', 'reverted', 'items_reverted',
1446                                   'ignored') NOT NULL default 'staged'");
1447     $dbh->do("ALTER TABLE import_items
1448               MODIFY status enum('error', 'staged', 'imported', 'reverted', 'ignored') NOT NULL default 'staged'");
1449
1450         print "Upgrade to $DBversion done (changes to import_batches and import_records)\n";
1451         SetVersion ($DBversion);
1452 }
1453
1454 $DBversion = "3.00.00.077";
1455 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1456     # drop these tables only if they exist and none of them are empty
1457     # these tables are not defined in the packaged 2.2.9, but since it is believed
1458     # that at least one library may be using them in a post-2.2.9 but pre-3.0 Koha,
1459     # some care is taken.
1460     my ($print_error) = $dbh->{PrintError};
1461     $dbh->{PrintError} = 0;
1462     my ($raise_error) = $dbh->{RaiseError};
1463     $dbh->{RaiseError} = 1;
1464
1465     my $count = 0;
1466     my $do_drop = 1;
1467     eval { $count = $dbh->do("SELECT 1 FROM categorytable"); };
1468     if ($count > 0) {
1469         $do_drop = 0;
1470     }
1471     eval { $count = $dbh->do("SELECT 1 FROM mediatypetable"); };
1472     if ($count > 0) {
1473         $do_drop = 0;
1474     }
1475     eval { $count = $dbh->do("SELECT 1 FROM subcategorytable"); };
1476     if ($count > 0) {
1477         $do_drop = 0;
1478     }
1479
1480     if ($do_drop) {
1481         $dbh->do("DROP TABLE IF EXISTS `categorytable`");
1482         $dbh->do("DROP TABLE IF EXISTS `mediatypetable`");
1483         $dbh->do("DROP TABLE IF EXISTS `subcategorytable`");
1484     }
1485
1486     $dbh->{PrintError} = $print_error;
1487     $dbh->{RaiseError} = $raise_error;
1488         print "Upgrade to $DBversion done (drop categorytable, subcategorytable, and mediatypetable)\n";
1489         SetVersion ($DBversion);
1490 }
1491
1492 $DBversion = "3.00.00.078";
1493 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1494     my ($print_error) = $dbh->{PrintError};
1495     $dbh->{PrintError} = 0;
1496
1497     unless ($dbh->do("SELECT 1 FROM browser")) {
1498         $dbh->{PrintError} = $print_error;
1499         $dbh->do("CREATE TABLE `browser` (
1500                     `level` int(11) NOT NULL,
1501                     `classification` varchar(20) NOT NULL,
1502                     `description` varchar(255) NOT NULL,
1503                     `number` bigint(20) NOT NULL,
1504                     `endnode` tinyint(4) NOT NULL
1505                   ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1506     }
1507     $dbh->{PrintError} = $print_error;
1508         print "Upgrade to $DBversion done (add browser table if not already present)\n";
1509         SetVersion ($DBversion);
1510 }
1511
1512 $DBversion = "3.00.00.079";
1513 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1514  my ($print_error) = $dbh->{PrintError};
1515     $dbh->{PrintError} = 0;
1516
1517     $dbh->do("INSERT INTO `systempreferences` (variable, value,options,type, explanation)VALUES
1518         ('AddPatronLists','categorycode','categorycode|category_type','Choice','Allow user to choose what list to pick up from when adding patrons')");
1519     print "Upgrade to $DBversion done (add browser table if not already present)\n";
1520         SetVersion ($DBversion);
1521 }
1522
1523 $DBversion = "3.00.00.080";
1524 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1525     $dbh->do("ALTER TABLE subscription CHANGE monthlength monthlength int(11) default '0'");
1526     $dbh->do("ALTER TABLE deleteditems MODIFY marc LONGBLOB AFTER copynumber");
1527     $dbh->do("ALTER TABLE aqbooksellers CHANGE name name mediumtext NOT NULL");
1528         print "Upgrade to $DBversion done (catch up on DB schema changes since alpha and beta)\n";
1529         SetVersion ($DBversion);
1530 }
1531
1532 $DBversion = "3.00.00.081";
1533 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1534     $dbh->do("CREATE TABLE `borrower_attribute_types` (
1535                 `code` varchar(10) NOT NULL,
1536                 `description` varchar(255) NOT NULL,
1537                 `repeatable` tinyint(1) NOT NULL default 0,
1538                 `unique_id` tinyint(1) NOT NULL default 0,
1539                 `opac_display` tinyint(1) NOT NULL default 0,
1540                 `password_allowed` tinyint(1) NOT NULL default 0,
1541                 `staff_searchable` tinyint(1) NOT NULL default 0,
1542                 `authorised_value_category` varchar(10) default NULL,
1543                 PRIMARY KEY  (`code`)
1544               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1545     $dbh->do("CREATE TABLE `borrower_attributes` (
1546                 `borrowernumber` int(11) NOT NULL,
1547                 `code` varchar(10) NOT NULL,
1548                 `attribute` varchar(30) default NULL,
1549                 `password` varchar(30) default NULL,
1550                 KEY `borrowernumber` (`borrowernumber`),
1551                 KEY `code_attribute` (`code`, `attribute`),
1552                 CONSTRAINT `borrower_attributes_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1553                     ON DELETE CASCADE ON UPDATE CASCADE,
1554                 CONSTRAINT `borrower_attributes_ibfk_2` FOREIGN KEY (`code`) REFERENCES `borrower_attribute_types` (`code`)
1555                     ON DELETE CASCADE ON UPDATE CASCADE
1556             ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1557     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('ExtendedPatronAttributes','0','Use extended patron IDs and attributes',NULL,'YesNo')");
1558     print "Upgrade to $DBversion done (added borrower_attributes and  borrower_attribute_types)\n";
1559  SetVersion ($DBversion);
1560 }
1561
1562 $DBversion = "3.00.00.082";
1563 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1564     $dbh->do( q(alter table accountlines add column lastincrement decimal(28,6) default NULL) );
1565     print "Upgrade to $DBversion done (adding lastincrement column to accountlines table)\n";
1566     SetVersion ($DBversion);
1567 }
1568
1569 $DBversion = "3.00.00.083";
1570 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1571     $dbh->do( qq(UPDATE systempreferences SET value='local' where variable='yuipath' and value like "%/intranet-tmpl/prog/%"));
1572     print "Upgrade to $DBversion done (Changing yuipath behaviour in managing a local value)\n";
1573     SetVersion ($DBversion);
1574 }
1575 $DBversion = "3.00.00.084";
1576     if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1577     $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')");
1578     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('GoogleJackets','0','if ON, displays jacket covers from Google Books API',NULL,'YesNo')");
1579     print "Upgrade to $DBversion done (add new sysprefs)\n";
1580     SetVersion ($DBversion);
1581 }
1582
1583 $DBversion = "3.00.00.085";
1584 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1585     if (C4::Context->preference("marcflavour") eq 'MARC21') {
1586         $dbh->do("UPDATE marc_subfield_structure SET tab = 0 WHERE tab =  9 AND tagfield = '037'");
1587         $dbh->do("UPDATE marc_subfield_structure SET tab = 1 WHERE tab =  6 AND tagfield in ('100', '110', '111', '130')");
1588         $dbh->do("UPDATE marc_subfield_structure SET tab = 2 WHERE tab =  6 AND tagfield in ('240', '243')");
1589         $dbh->do("UPDATE marc_subfield_structure SET tab = 4 WHERE tab =  6 AND tagfield in ('400', '410', '411', '440')");
1590         $dbh->do("UPDATE marc_subfield_structure SET tab = 5 WHERE tab =  9 AND tagfield = '584'");
1591         $dbh->do("UPDATE marc_subfield_structure SET tab = 7 WHERE tab = -6 AND tagfield = '760'");
1592     }
1593     print "Upgrade to $DBversion done (move editing tab of various MARC21 subfields)\n";
1594     SetVersion ($DBversion);
1595 }
1596
1597 $DBversion = "3.00.00.086";
1598 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1599         $dbh->do(
1600         "CREATE TABLE `tmp_holdsqueue` (
1601         `biblionumber` int(11) default NULL,
1602         `itemnumber` int(11) default NULL,
1603         `barcode` varchar(20) default NULL,
1604         `surname` mediumtext NOT NULL,
1605         `firstname` text,
1606         `phone` text,
1607         `borrowernumber` int(11) NOT NULL,
1608         `cardnumber` varchar(16) default NULL,
1609         `reservedate` date default NULL,
1610         `title` mediumtext,
1611         `itemcallnumber` varchar(30) default NULL,
1612         `holdingbranch` varchar(10) default NULL,
1613         `pickbranch` varchar(10) default NULL,
1614         `notes` text
1615         ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1616
1617         $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')");
1618         $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')");
1619
1620         print "Upgrade to $DBversion done (Table structure for table `tmp_holdsqueue`)\n";
1621         SetVersion ($DBversion);
1622 }
1623
1624 $DBversion = "3.00.00.087";
1625 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1626     $dbh->do("INSERT INTO `systempreferences` VALUES ('AutoEmailOpacUser','0','','Sends notification emails containing new account details to patrons - when account is created.','YesNo')" );
1627     $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')");
1628     print "Upgrade to $DBversion done (added 2 new 'AutoEmailOpacUser' sysprefs)\n";
1629     SetVersion ($DBversion);
1630 }
1631
1632 $DBversion = "3.00.00.088";
1633 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1634         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('OPACShelfBrowser','1','','Enable/disable Shelf Browser on item details page','YesNo')");
1635         $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')");
1636         $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')");
1637         $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')");
1638         print "Upgrade to $DBversion done (added 2 new 'AutoEmailOpacUser' sysprefs)\n";
1639     SetVersion ($DBversion);
1640 }
1641
1642 $DBversion = "3.00.00.089";
1643 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1644         $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')");
1645         print "Upgrade to $DBversion done (added new AdvancedSearchTypes syspref)\n";
1646     SetVersion ($DBversion);
1647 }
1648
1649 $DBversion = "3.00.00.090";
1650 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1651     $dbh->do("
1652         CREATE TABLE `branch_borrower_circ_rules` (
1653           `branchcode` VARCHAR(10) NOT NULL,
1654           `categorycode` VARCHAR(10) NOT NULL,
1655           `maxissueqty` int(4) default NULL,
1656           PRIMARY KEY (`categorycode`, `branchcode`),
1657           CONSTRAINT `branch_borrower_circ_rules_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
1658             ON DELETE CASCADE ON UPDATE CASCADE,
1659           CONSTRAINT `branch_borrower_circ_rules_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`)
1660             ON DELETE CASCADE ON UPDATE CASCADE
1661         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1662     ");
1663     $dbh->do("
1664         CREATE TABLE `default_borrower_circ_rules` (
1665           `categorycode` VARCHAR(10) NOT NULL,
1666           `maxissueqty` int(4) default NULL,
1667           PRIMARY KEY (`categorycode`),
1668           CONSTRAINT `borrower_borrower_circ_rules_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
1669             ON DELETE CASCADE ON UPDATE CASCADE
1670         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1671     ");
1672     $dbh->do("
1673         CREATE TABLE `default_branch_circ_rules` (
1674           `branchcode` VARCHAR(10) NOT NULL,
1675           `maxissueqty` int(4) default NULL,
1676           PRIMARY KEY (`branchcode`),
1677           CONSTRAINT `default_branch_circ_rules_ibfk_1` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`)
1678             ON DELETE CASCADE ON UPDATE CASCADE
1679         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1680     ");
1681     $dbh->do("
1682         CREATE TABLE `default_circ_rules` (
1683             `singleton` enum('singleton') NOT NULL default 'singleton',
1684             `maxissueqty` int(4) default NULL,
1685             PRIMARY KEY (`singleton`)
1686         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1687     ");
1688     print "Upgrade to $DBversion done (added several circ rules tables)\n";
1689     SetVersion ($DBversion);
1690 }
1691
1692
1693 $DBversion = "3.00.00.091";
1694 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1695     $dbh->do(<<'END_SQL');
1696 ALTER TABLE borrowers
1697 ADD `smsalertnumber` varchar(50) default NULL
1698 END_SQL
1699
1700     $dbh->do(<<'END_SQL');
1701 CREATE TABLE `message_attributes` (
1702   `message_attribute_id` int(11) NOT NULL auto_increment,
1703   `message_name` varchar(20) NOT NULL default '',
1704   `takes_days` tinyint(1) NOT NULL default '0',
1705   PRIMARY KEY  (`message_attribute_id`),
1706   UNIQUE KEY `message_name` (`message_name`)
1707 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1708 END_SQL
1709
1710     $dbh->do(<<'END_SQL');
1711 CREATE TABLE `message_transport_types` (
1712   `message_transport_type` varchar(20) NOT NULL,
1713   PRIMARY KEY  (`message_transport_type`)
1714 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1715 END_SQL
1716
1717     $dbh->do(<<'END_SQL');
1718 CREATE TABLE `message_transports` (
1719   `message_attribute_id` int(11) NOT NULL,
1720   `message_transport_type` varchar(20) NOT NULL,
1721   `is_digest` tinyint(1) NOT NULL default '0',
1722   `letter_module` varchar(20) NOT NULL default '',
1723   `letter_code` varchar(20) NOT NULL default '',
1724   PRIMARY KEY  (`message_attribute_id`,`message_transport_type`,`is_digest`),
1725   KEY `message_transport_type` (`message_transport_type`),
1726   KEY `letter_module` (`letter_module`,`letter_code`),
1727   CONSTRAINT `message_transports_ibfk_1` FOREIGN KEY (`message_attribute_id`) REFERENCES `message_attributes` (`message_attribute_id`) ON DELETE CASCADE ON UPDATE CASCADE,
1728   CONSTRAINT `message_transports_ibfk_2` FOREIGN KEY (`message_transport_type`) REFERENCES `message_transport_types` (`message_transport_type`) ON DELETE CASCADE ON UPDATE CASCADE,
1729   CONSTRAINT `message_transports_ibfk_3` FOREIGN KEY (`letter_module`, `letter_code`) REFERENCES `letter` (`module`, `code`) ON DELETE CASCADE ON UPDATE CASCADE
1730 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1731 END_SQL
1732
1733     $dbh->do(<<'END_SQL');
1734 CREATE TABLE `borrower_message_preferences` (
1735   `borrower_message_preference_id` int(11) NOT NULL auto_increment,
1736   `borrowernumber` int(11) NOT NULL default '0',
1737   `message_attribute_id` int(11) default '0',
1738   `days_in_advance` int(11) default '0',
1739   `wants_digets` tinyint(1) NOT NULL default '0',
1740   PRIMARY KEY  (`borrower_message_preference_id`),
1741   KEY `borrowernumber` (`borrowernumber`),
1742   KEY `message_attribute_id` (`message_attribute_id`),
1743   CONSTRAINT `borrower_message_preferences_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1744   CONSTRAINT `borrower_message_preferences_ibfk_2` FOREIGN KEY (`message_attribute_id`) REFERENCES `message_attributes` (`message_attribute_id`) ON DELETE CASCADE ON UPDATE CASCADE
1745 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1746 END_SQL
1747
1748     $dbh->do(<<'END_SQL');
1749 CREATE TABLE `borrower_message_transport_preferences` (
1750   `borrower_message_preference_id` int(11) NOT NULL default '0',
1751   `message_transport_type` varchar(20) NOT NULL default '0',
1752   PRIMARY KEY  (`borrower_message_preference_id`,`message_transport_type`),
1753   KEY `message_transport_type` (`message_transport_type`),
1754   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,
1755   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
1756 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1757 END_SQL
1758
1759     $dbh->do(<<'END_SQL');
1760 CREATE TABLE `message_queue` (
1761   `message_id` int(11) NOT NULL auto_increment,
1762   `borrowernumber` int(11) NOT NULL,
1763   `subject` text,
1764   `content` text,
1765   `message_transport_type` varchar(20) NOT NULL,
1766   `status` enum('sent','pending','failed','deleted') NOT NULL default 'pending',
1767   `time_queued` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1768   KEY `message_id` (`message_id`),
1769   KEY `borrowernumber` (`borrowernumber`),
1770   KEY `message_transport_type` (`message_transport_type`),
1771   CONSTRAINT `messageq_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1772   CONSTRAINT `messageq_ibfk_2` FOREIGN KEY (`message_transport_type`) REFERENCES `message_transport_types` (`message_transport_type`) ON DELETE RESTRICT ON UPDATE CASCADE
1773 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1774 END_SQL
1775
1776     $dbh->do(<<'END_SQL');
1777 INSERT INTO `systempreferences`
1778   (variable,value,explanation,options,type)
1779 VALUES
1780 ('EnhancedMessagingPreferences',0,'If ON, allows patrons to select to receive additional messages about items due or nearly due.','','YesNo')
1781 END_SQL
1782
1783     $dbh->do( <<'END_SQL');
1784 INSERT INTO `letter`
1785 (module, code, name, title, content)
1786 VALUES
1787 ('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>>'),
1788 ('circulation','DUEDGST','Item Due Reminder (Digest)','Item Due Reminder','You have <<count>> items due'),
1789 ('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>>'),
1790 ('circulation','PREDUEDGST','Advance Notice of Item Due (Digest)','Advance Notice of Item Due','You have <<count>> items due soon'),
1791 ('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.');
1792 END_SQL
1793
1794     my @sql_scripts = (
1795         'installer/data/mysql/en/mandatory/message_transport_types.sql',
1796         'installer/data/mysql/en/optional/sample_notices_message_attributes.sql',
1797         'installer/data/mysql/en/optional/sample_notices_message_transports.sql',
1798     );
1799
1800     my $installer = C4::Installer->new();
1801     foreach my $script ( @sql_scripts ) {
1802         my $full_path = $installer->get_file_path_from_name($script);
1803         my $error = $installer->load_sql($full_path);
1804         warn $error if $error;
1805     }
1806
1807     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";
1808     SetVersion ($DBversion);
1809 }
1810
1811 $DBversion = "3.00.00.092";
1812 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1813     $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')");
1814     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES('AllowHoldsOnDamagedItems', '1', '', 'Allow hold requests to be placed on damaged items', 'YesNo')");
1815         print "Upgrade to $DBversion done (added new AllowOnShelfHolds syspref)\n";
1816     SetVersion ($DBversion);
1817 }
1818
1819 $DBversion = "3.00.00.093";
1820 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1821     $dbh->do("ALTER TABLE `items` MODIFY COLUMN `copynumber` VARCHAR(32) DEFAULT NULL");
1822     $dbh->do("ALTER TABLE `deleteditems` MODIFY COLUMN `copynumber` VARCHAR(32) DEFAULT NULL");
1823         print "Upgrade to $DBversion done (Change data type of items.copynumber to allow free text)\n";
1824     SetVersion ($DBversion);
1825 }
1826
1827 $DBversion = "3.00.00.094";
1828 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1829     $dbh->do("ALTER TABLE `marc_subfield_structure` MODIFY `tagsubfield` VARCHAR(1) NOT NULL DEFAULT '' COLLATE utf8_bin");
1830         print "Upgrade to $DBversion done (Change Collation of marc_subfield_structure to allow mixed case in subfield labels.)\n";
1831     SetVersion ($DBversion);
1832 }
1833
1834 $DBversion = "3.00.00.095";
1835 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1836     if (C4::Context->preference("marcflavour") eq 'MARC21') {
1837         $dbh->do("UPDATE marc_subfield_structure SET authtypecode = 'MEETI_NAME' WHERE authtypecode = 'Meeting Name'");
1838         $dbh->do("UPDATE marc_subfield_structure SET authtypecode = 'CORPO_NAME' WHERE authtypecode = 'CORP0_NAME'");
1839     }
1840         print "Upgrade to $DBversion done (fix invalid authority types in MARC21 frameworks [bug 2254])\n";
1841     SetVersion ($DBversion);
1842 }
1843
1844 $DBversion = "3.00.00.096";
1845 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1846     $sth = $dbh->prepare("SHOW COLUMNS FROM borrower_message_preferences LIKE 'wants_digets'");
1847     $sth->execute();
1848     if (my $row = $sth->fetchrow_hashref) {
1849         $dbh->do("ALTER TABLE borrower_message_preferences CHANGE wants_digets wants_digest tinyint(1) NOT NULL default 0");
1850     }
1851         print "Upgrade to $DBversion done (fix name borrower_message_preferences.wants_digest)\n";
1852     SetVersion ($DBversion);
1853 }
1854
1855 $DBversion = '3.00.00.097';
1856 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1857
1858     $dbh->do('ALTER TABLE message_queue ADD to_address   mediumtext default NULL');
1859     $dbh->do('ALTER TABLE message_queue ADD from_address mediumtext default NULL');
1860     $dbh->do('ALTER TABLE message_queue ADD content_type text');
1861     $dbh->do('ALTER TABLE message_queue CHANGE borrowernumber borrowernumber int(11) default NULL');
1862
1863     print "Upgrade to $DBversion done (updating 4 fields in message_queue table)\n";
1864     SetVersion($DBversion);
1865 }
1866
1867 $DBversion = '3.00.00.098';
1868 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1869
1870     $dbh->do(q(DELETE FROM message_transport_types WHERE message_transport_type = 'rss'));
1871     $dbh->do(q(DELETE FROM message_transports WHERE message_transport_type = 'rss'));
1872
1873     print "Upgrade to $DBversion done (removing unused RSS message_transport_type)\n";
1874     SetVersion($DBversion);
1875 }
1876
1877 $DBversion = '3.00.00.099';
1878 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1879     $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')");
1880     print "Upgrade to $DBversion done (Adding OpacSuppression syspref)\n";
1881     SetVersion($DBversion);
1882 }
1883
1884 $DBversion = '3.00.00.100';
1885 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1886         $dbh->do('ALTER TABLE virtualshelves ADD COLUMN lastmodified timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP');
1887     print "Upgrade to $DBversion done (Adding lastmodified column to virtualshelves)\n";
1888     SetVersion($DBversion);
1889 }
1890
1891 $DBversion = '3.00.00.101';
1892 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1893         $dbh->do('ALTER TABLE `overduerules` CHANGE `categorycode` `categorycode` VARCHAR(10) NOT NULL');
1894         $dbh->do('ALTER TABLE `deletedborrowers` CHANGE `categorycode` `categorycode` VARCHAR(10) NOT NULL');
1895     print "Upgrade to $DBversion done (Updating columnd definitions for patron category codes in notice/statsu triggers and deletedborrowers tables.)\n";
1896     SetVersion($DBversion);
1897 }
1898
1899 $DBversion = '3.00.00.102';
1900 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1901         $dbh->do('ALTER TABLE serialitems MODIFY `serialid` int(11) NOT NULL AFTER itemnumber' );
1902         $dbh->do('ALTER TABLE serialitems DROP KEY serialididx' );
1903         $dbh->do('ALTER TABLE serialitems ADD CONSTRAINT UNIQUE KEY serialitemsidx (itemnumber)' );
1904         # before setting constraint, delete any unvalid data
1905         $dbh->do('DELETE from serialitems WHERE serialid not in (SELECT serial.serialid FROM serial)');
1906         $dbh->do('ALTER TABLE serialitems ADD CONSTRAINT serialitems_sfk_1 FOREIGN KEY (serialid) REFERENCES serial (serialid) ON DELETE CASCADE ON UPDATE CASCADE' );
1907     print "Upgrade to $DBversion done (Updating serialitems table to allow for multiple items per serial fixing kohabug 2380)\n";
1908     SetVersion($DBversion);
1909 }
1910
1911 $DBversion = "3.00.00.103";
1912 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1913     $dbh->do("DELETE FROM systempreferences WHERE variable='serialsadditems'");
1914     print "Upgrade to $DBversion done ( Verifying the removal of serialsadditems from syspref fixing kohabug 2219)\n";
1915     SetVersion ($DBversion);
1916 }
1917
1918 $DBversion = "3.00.00.104";
1919 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1920     $dbh->do("DELETE FROM systempreferences WHERE variable='noOPACHolds'");
1921     print "Upgrade to $DBversion done (remove superseded 'noOPACHolds' system preference per bug 2413)\n";
1922     SetVersion ($DBversion);
1923 }
1924
1925 $DBversion = '3.00.00.105';
1926 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
1927
1928     # it is possible that this syspref is already defined since the feature was added some time ago.
1929     unless ( $dbh->do(q(SELECT variable FROM systempreferences WHERE variable = 'SMSSendDriver')) ) {
1930         $dbh->do(<<'END_SQL');
1931 INSERT INTO `systempreferences`
1932   (variable,value,explanation,options,type)
1933 VALUES
1934 ('SMSSendDriver','','Sets which SMS::Send driver is used to send SMS messages.','','free')
1935 END_SQL
1936     }
1937     print "Upgrade to $DBversion done (added SMSSendDriver system preference)\n";
1938     SetVersion($DBversion);
1939 }
1940
1941 $DBversion = "3.00.00.106";
1942 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1943     $dbh->do("DELETE FROM systempreferences WHERE variable='noOPACHolds'");
1944
1945 # db revision 105 didn't apply correctly, so we're rolling this into 106
1946         $dbh->do("INSERT INTO `systempreferences`
1947    (variable,value,explanation,options,type)
1948         VALUES
1949         ('SMSSendDriver','','Sets which SMS::Send driver is used to send SMS messages.','','free')");
1950
1951     print "Upgrade to $DBversion done (remove default '0000-00-00' in subscriptionhistory.enddate field)\n";
1952     $dbh->do("ALTER TABLE `subscriptionhistory` CHANGE `enddate` `enddate` DATE NULL DEFAULT NULL ");
1953     $dbh->do("UPDATE subscriptionhistory SET enddate=NULL WHERE enddate='0000-00-00'");
1954     SetVersion ($DBversion);
1955 }
1956
1957 $DBversion = '3.00.00.107';
1958 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1959     $dbh->do(<<'END_SQL');
1960 UPDATE systempreferences
1961   SET explanation = CONCAT( explanation, '. WARNING: this feature is very resource consuming on collections with large numbers of items.' )
1962   WHERE variable = 'OPACShelfBrowser'
1963     AND explanation NOT LIKE '%WARNING%'
1964 END_SQL
1965     $dbh->do(<<'END_SQL');
1966 UPDATE systempreferences
1967   SET explanation = CONCAT( explanation, '. WARNING: this feature is very resource consuming.' )
1968   WHERE variable = 'CataloguingLog'
1969     AND explanation NOT LIKE '%WARNING%'
1970 END_SQL
1971     $dbh->do(<<'END_SQL');
1972 UPDATE systempreferences
1973   SET explanation = CONCAT( explanation, '. WARNING: using NoZebra on even modest sized collections is very slow.' )
1974   WHERE variable = 'NoZebra'
1975     AND explanation NOT LIKE '%WARNING%'
1976 END_SQL
1977     print "Upgrade to $DBversion done (warning added to OPACShelfBrowser system preference)\n";
1978     SetVersion ($DBversion);
1979 }
1980
1981 $DBversion = '3.01.00.000';
1982 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1983     print "Upgrade to $DBversion done (start of 3.1)\n";
1984     SetVersion ($DBversion);
1985 }
1986
1987 $DBversion = '3.01.00.001';
1988 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1989     $dbh->do("
1990         CREATE TABLE hold_fill_targets (
1991             `borrowernumber` int(11) NOT NULL,
1992             `biblionumber` int(11) NOT NULL,
1993             `itemnumber` int(11) NOT NULL,
1994             `source_branchcode`  varchar(10) default NULL,
1995             `item_level_request` tinyint(4) NOT NULL default 0,
1996             PRIMARY KEY `itemnumber` (`itemnumber`),
1997             KEY `bib_branch` (`biblionumber`, `source_branchcode`),
1998             CONSTRAINT `hold_fill_targets_ibfk_1` FOREIGN KEY (`borrowernumber`)
1999                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
2000             CONSTRAINT `hold_fill_targets_ibfk_2` FOREIGN KEY (`biblionumber`)
2001                 REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
2002             CONSTRAINT `hold_fill_targets_ibfk_3` FOREIGN KEY (`itemnumber`)
2003                 REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
2004             CONSTRAINT `hold_fill_targets_ibfk_4` FOREIGN KEY (`source_branchcode`)
2005                 REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
2006         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2007     ");
2008     $dbh->do("
2009         ALTER TABLE tmp_holdsqueue
2010             ADD item_level_request tinyint(4) NOT NULL default 0
2011     ");
2012
2013     print "Upgrade to $DBversion done (add hold_fill_targets table and a column to tmp_holdsqueue)\n";
2014     SetVersion($DBversion);
2015 }
2016
2017 $DBversion = '3.01.00.002';
2018 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2019     # use statistics where available
2020     $dbh->do("
2021         ALTER TABLE statistics ADD KEY  tmp_stats (type, itemnumber, borrowernumber)
2022     ");
2023     $dbh->do("
2024         UPDATE issues iss
2025         SET issuedate = (
2026             SELECT max(datetime)
2027             FROM statistics
2028             WHERE type = 'issue'
2029             AND itemnumber = iss.itemnumber
2030             AND borrowernumber = iss.borrowernumber
2031         )
2032         WHERE issuedate IS NULL;
2033     ");
2034     $dbh->do("ALTER TABLE statistics DROP KEY tmp_stats");
2035
2036     # default to last renewal date
2037     $dbh->do("
2038         UPDATE issues
2039         SET issuedate = lastreneweddate
2040         WHERE issuedate IS NULL
2041         and lastreneweddate IS NOT NULL
2042     ");
2043
2044     my $num_bad_issuedates = $dbh->selectrow_array("SELECT COUNT(*) FROM issues WHERE issuedate IS NULL");
2045     if ($num_bad_issuedates > 0) {
2046         print STDERR "After the upgrade to $DBversion, there are still $num_bad_issuedates loan(s) with a NULL (blank) loan date. ",
2047                      "Please check the issues table in your database.";
2048     }
2049     print "Upgrade to $DBversion done (bug 2582: set null issues.issuedate to lastreneweddate)\n";
2050     SetVersion($DBversion);
2051 }
2052
2053 $DBversion = "3.01.00.003";
2054 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2055     $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')");
2056     print "Upgrade to $DBversion done (add new syspref)\n";
2057     SetVersion ($DBversion);
2058 }
2059
2060 $DBversion = '3.01.00.004';
2061 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2062     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACDisplayRequestPriority','0','Show patrons the priority level on holds in the OPAC','','YesNo')");
2063     print "Upgrade to $DBversion done (added OPACDisplayRequestPriority system preference)\n";
2064     SetVersion ($DBversion);
2065 }
2066
2067 $DBversion = '3.01.00.005';
2068 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2069     $dbh->do("
2070         INSERT INTO `letter` (module, code, name, title, content)
2071         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>>')
2072     ");
2073     $dbh->do("INSERT INTO `message_attributes` (message_attribute_id, message_name, takes_days) values(4, 'Hold Filled', 0)");
2074     $dbh->do("INSERT INTO `message_transports` (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) values(4, 'sms', 0, 'reserves', 'HOLD')");
2075     $dbh->do("INSERT INTO `message_transports` (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) values(4, 'email', 0, 'reserves', 'HOLD')");
2076     print "Upgrade to $DBversion done (Add letter for holds notifications)\n";
2077     SetVersion ($DBversion);
2078 }
2079
2080 $DBversion = '3.01.00.006';
2081 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2082     $dbh->do("ALTER TABLE `biblioitems` ADD KEY issn (issn)");
2083     print "Upgrade to $DBversion done (add index on biblioitems.issn)\n";
2084     SetVersion ($DBversion);
2085 }
2086
2087 $DBversion = "3.01.00.007";
2088 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2089     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='intranetmainUserblock'");
2090     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='intranetuserjs'");
2091     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='opacheader'");
2092     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='OpacMainUserBlock'");
2093     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='OpacNav'");
2094     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='opacuserjs'");
2095     $dbh->do("UPDATE `systempreferences` SET options='30|10', type='Textarea' WHERE variable='OAI-PMH:Set'");
2096     $dbh->do("UPDATE `systempreferences` SET options='50' WHERE variable='intranetstylesheet'");
2097     $dbh->do("UPDATE `systempreferences` SET options='50' WHERE variable='intranetcolorstylesheet'");
2098     $dbh->do("UPDATE `systempreferences` SET options='10' WHERE variable='globalDueDate'");
2099     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='numSearchResults'");
2100     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='OPACnumSearchResults'");
2101     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='ReservesMaxPickupDelay'");
2102     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='TransfersMaxDaysWarning'");
2103     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='StaticHoldsQueueWeight'");
2104     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='holdCancelLength'");
2105     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='XISBNDailyLimit'");
2106     $dbh->do("UPDATE `systempreferences` SET type='Float' WHERE variable='gist'");
2107     $dbh->do("UPDATE `systempreferences` SET type='Free' WHERE variable='BakerTaylorUsername'");
2108     $dbh->do("UPDATE `systempreferences` SET type='Free' WHERE variable='BakerTaylorPassword'");
2109     $dbh->do("UPDATE `systempreferences` SET type='Textarea', options='70|10' WHERE variable='ISBD'");
2110     $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'");
2111     print "Upgrade to $DBversion done (fix display of many sysprefs)\n";
2112     SetVersion ($DBversion);
2113 }
2114
2115 $DBversion = '3.01.00.008';
2116 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2117
2118     $dbh->do("CREATE TABLE branch_transfer_limits (
2119                           limitId int(8) NOT NULL auto_increment,
2120                           toBranch varchar(4) NOT NULL,
2121                           fromBranch varchar(4) NOT NULL,
2122                           itemtype varchar(4) NOT NULL,
2123                           PRIMARY KEY  (limitId)
2124                           ) ENGINE=InnoDB DEFAULT CHARSET=utf8"
2125                         );
2126
2127     $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')");
2128
2129     print "Upgrade to $DBversion done (added branch_transfer_limits table and UseBranchTransferLimits system preference)\n";
2130     SetVersion ($DBversion);
2131 }
2132
2133 $DBversion = "3.01.00.009";
2134 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2135     $dbh->do("ALTER TABLE permissions MODIFY `code` varchar(64) DEFAULT NULL");
2136     $dbh->do("ALTER TABLE user_permissions MODIFY `code` varchar(64) DEFAULT NULL");
2137     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'circulate_remaining_permissions', 'Remaining circulation permissions')");
2138     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'override_renewals', 'Override blocked renewals')");
2139     print "Upgrade to $DBversion done (added subpermissions for circulate permission)\n";
2140 }
2141
2142 $DBversion = '3.01.00.010';
2143 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2144     $dbh->do("ALTER TABLE `borrower_attributes` MODIFY COLUMN `attribute` VARCHAR(64) DEFAULT NULL");
2145     $dbh->do("ALTER TABLE `borrower_attributes` MODIFY COLUMN `password` VARCHAR(64) DEFAULT NULL");
2146     print "Upgrade to $DBversion done (bug 2687: increase length of borrower attribute fields)\n";
2147     SetVersion ($DBversion);
2148 }
2149
2150 $DBversion = '3.01.00.011';
2151 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2152
2153     # Yes, the old value was ^M terminated.
2154     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);";
2155
2156     my $intranetuserjs = C4::Context->preference('intranetuserjs');
2157     if ($intranetuserjs  and  $intranetuserjs eq $bad_value) {
2158         my $sql = <<'END_SQL';
2159 UPDATE systempreferences
2160 SET value = ''
2161 WHERE variable = 'intranetuserjs'
2162 END_SQL
2163         $dbh->do($sql);
2164     }
2165     print "Upgrade to $DBversion done (removed bogus intranetuserjs syspref)\n";
2166     SetVersion($DBversion);
2167 }
2168
2169 $DBversion = "3.01.00.012";
2170 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2171     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowHoldPolicyOverride', '0', 'Allow staff to override hold policies when placing holds',NULL,'YesNo')");
2172     $dbh->do("
2173         CREATE TABLE `branch_item_rules` (
2174           `branchcode` varchar(10) NOT NULL,
2175           `itemtype` varchar(10) NOT NULL,
2176           `holdallowed` tinyint(1) default NULL,
2177           PRIMARY KEY  (`itemtype`,`branchcode`),
2178           KEY `branch_item_rules_ibfk_2` (`branchcode`),
2179           CONSTRAINT `branch_item_rules_ibfk_1` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE,
2180           CONSTRAINT `branch_item_rules_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
2181         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2182     ");
2183     $dbh->do("
2184         CREATE TABLE `default_branch_item_rules` (
2185           `itemtype` varchar(10) NOT NULL,
2186           `holdallowed` tinyint(1) default NULL,
2187           PRIMARY KEY  (`itemtype`),
2188           CONSTRAINT `default_branch_item_rules_ibfk_1` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE
2189         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2190     ");
2191     $dbh->do("
2192         ALTER TABLE default_branch_circ_rules
2193             ADD COLUMN holdallowed tinyint(1) NULL
2194     ");
2195     $dbh->do("
2196         ALTER TABLE default_circ_rules
2197             ADD COLUMN holdallowed tinyint(1) NULL
2198     ");
2199     print "Upgrade to $DBversion done (Add tables and system preferences for holds policies)\n";
2200     SetVersion ($DBversion);
2201 }
2202
2203 $DBversion = '3.01.00.013';
2204 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2205     $dbh->do("
2206         CREATE TABLE item_circulation_alert_preferences (
2207             id           int(11) AUTO_INCREMENT,
2208             branchcode   varchar(10) NOT NULL,
2209             categorycode varchar(10) NOT NULL,
2210             item_type    varchar(10) NOT NULL,
2211             notification varchar(16) NOT NULL,
2212             PRIMARY KEY (id),
2213             KEY (branchcode, categorycode, item_type, notification)
2214         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2215     ");
2216
2217     $dbh->do(q{ ALTER TABLE `message_queue` ADD metadata text DEFAULT NULL           AFTER content;  });
2218     $dbh->do(q{ ALTER TABLE `message_queue` ADD letter_code varchar(64) DEFAULT NULL AFTER metadata; });
2219
2220     $dbh->do(q{
2221         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
2222         ('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.');
2223     });
2224     $dbh->do(q{
2225         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
2226         ('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>>.');
2227     });
2228
2229     $dbh->do(q{INSERT INTO message_attributes (message_attribute_id, message_name, takes_days) VALUES (5, 'Item Check-in', 0);});
2230     $dbh->do(q{INSERT INTO message_attributes (message_attribute_id, message_name, takes_days) VALUES (6, 'Item Checkout', 0);});
2231
2232     $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');});
2233     $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');});
2234     $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');});
2235     $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');});
2236
2237     print "Upgrade to $DBversion done (data for Email Checkout Slips project)\n";
2238          SetVersion ($DBversion);
2239 }
2240
2241 $DBversion = "3.01.00.014";
2242 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2243     $dbh->do("ALTER TABLE `branch_transfer_limits` CHANGE `itemtype` `itemtype` VARCHAR( 4 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL");
2244     $dbh->do("ALTER TABLE `branch_transfer_limits` ADD `ccode` VARCHAR( 10 ) NULL ;");
2245     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2246     VALUES (
2247     'BranchTransferLimitsType', 'ccode', 'itemtype|ccode', 'When using branch transfer limits, choose whether to limit by itemtype or collection code.', 'Choice'
2248     );");
2249
2250     print "Upgrade to $DBversion done ( Updated table for Branch Transfer Limits)\n";
2251     SetVersion ($DBversion);
2252 }
2253
2254 $DBversion = '3.01.00.015';
2255 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2256     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsClientCode', '0', 'Client Code for using Syndetics Solutions content','','free')");
2257
2258     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsEnabled', '0', 'Turn on Syndetics Enhanced Content','','YesNo')");
2259
2260     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsCoverImages', '0', 'Display Cover Images from Syndetics','','YesNo')");
2261
2262     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsTOC', '0', 'Display Table of Content information from Syndetics','','YesNo')");
2263
2264     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsSummary', '0', 'Display Summary Information from Syndetics','','YesNo')");
2265
2266     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsEditions', '0', 'Display Editions from Syndetics','','YesNo')");
2267
2268     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsExcerpt', '0', 'Display Excerpts and first chapters on OPAC from Syndetics','','YesNo')");
2269
2270     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsReviews', '0', 'Display Reviews on OPAC from Syndetics','','YesNo')");
2271
2272     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsAuthorNotes', '0', 'Display Notes about the Author on OPAC from Syndetics','','YesNo')");
2273
2274     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsAwards', '0', 'Display Awards on OPAC from Syndetics','','YesNo')");
2275
2276     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsSeries', '0', 'Display Series information on OPAC from Syndetics','','YesNo')");
2277
2278     $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')");
2279
2280     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAmazonCoverImages', '0', 'Display cover images on OPAC from Amazon Web Services','','YesNo')");
2281
2282     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AmazonCoverImages', '0', 'Display Cover Images in Staff Client from Amazon Web Services','','YesNo')");
2283
2284     $dbh->do("UPDATE systempreferences SET variable='AmazonEnabled' WHERE variable = 'AmazonContent'");
2285
2286     $dbh->do("UPDATE systempreferences SET variable='OPACAmazonEnabled' WHERE variable = 'OPACAmazonContent'");
2287
2288     print "Upgrade to $DBversion done (added Syndetics Enhanced Content system preferences)\n";
2289     SetVersion ($DBversion);
2290 }
2291
2292 $DBversion = "3.01.00.016";
2293 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2294     $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')");
2295     print "Upgrade to $DBversion done (Added Babeltheque syspref)\n";
2296     SetVersion ($DBversion);
2297 }
2298
2299 $DBversion = "3.01.00.017";
2300 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2301     $dbh->do("ALTER TABLE `subscription` ADD `staffdisplaycount` VARCHAR(10) NULL;");
2302     $dbh->do("ALTER TABLE `subscription` ADD `opacdisplaycount` VARCHAR(10) NULL;");
2303     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2304     VALUES (
2305     'StaffSerialIssueDisplayCount', '3', '', 'Number of serial issues to display per subscription in the Staff client', 'Integer'
2306     );");
2307         $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2308     VALUES (
2309     'OPACSerialIssueDisplayCount', '3', '', 'Number of serial issues to display per subscription in the OPAC', 'Integer'
2310     );");
2311
2312     print "Upgrade to $DBversion done ( Updated table for Serials Display)\n";
2313     SetVersion ($DBversion);
2314 }
2315
2316 $DBversion = "3.01.00.018";
2317 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2318     $dbh->do("ALTER TABLE deletedborrowers ADD `smsalertnumber` varchar(50) default NULL");
2319     print "Upgrade to $DBversion done (added deletedborrowers.smsalertnumber, missed in 3.00.00.091)\n";
2320     SetVersion ($DBversion);
2321 }
2322
2323 $DBversion = "3.01.00.019";
2324 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2325         $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')");
2326     print "Upgrade to $DBversion done (adding OPACShowCheckoutName systempref)\n";
2327     SetVersion ($DBversion);
2328 }
2329
2330 $DBversion = "3.01.00.020";
2331 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2332     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesID','','See:http://librarything.com/forlibraries/','','free')");
2333     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesEnabled','0','Enable or Disable Library Thing for Libraries Features','','YesNo')");
2334     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesTabbedView','0','Put LibraryThingForLibraries Content in Tabs.','','YesNo')");
2335     print "Upgrade to $DBversion done (adding LibraryThing for Libraries sysprefs)\n";
2336     SetVersion ($DBversion);
2337 }
2338
2339 $DBversion = "3.01.00.021";
2340 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2341     my $enable_reviews = C4::Context->preference('OPACAmazonEnabled') ? '1' : '0';
2342     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAmazonReviews', '$enable_reviews', 'Display Amazon readers reviews on OPAC','','YesNo')");
2343     print "Upgrade to $DBversion done (adding OPACAmazonReviews syspref)\n";
2344     SetVersion ($DBversion);
2345 }
2346
2347 $DBversion = '3.01.00.022';
2348 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2349     $dbh->do("ALTER TABLE `labels_conf` MODIFY COLUMN `formatstring` mediumtext DEFAULT NULL");
2350     print "Upgrade to $DBversion done (bug 2945: increase size of labels_conf.formatstring)\n";
2351     SetVersion ($DBversion);
2352 }
2353
2354 $DBversion = '3.01.00.023';
2355 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2356     $dbh->do("ALTER TABLE biblioitems        MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2357     $dbh->do("ALTER TABLE deletedbiblioitems MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2358     $dbh->do("ALTER TABLE import_biblios     MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2359     $dbh->do("ALTER TABLE suggestions        MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2360     print "Upgrade to $DBversion done (bug 2765: increase width of isbn column in several tables)\n";
2361     SetVersion ($DBversion);
2362 }
2363
2364 $DBversion = "3.01.00.024";
2365 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2366     $dbh->do("ALTER TABLE labels MODIFY COLUMN batch_id int(10) NOT NULL default 1;");
2367     print "Upgrade to $DBversion done (change labels.batch_id from varchar to int)\n";
2368     SetVersion ($DBversion);
2369 }
2370
2371 $DBversion = '3.01.00.025';
2372 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2373     $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')");
2374
2375     print "Upgrade to $DBversion done (added ceilingDueDate system preference)\n";
2376     SetVersion ($DBversion);
2377 }
2378
2379 $DBversion = '3.01.00.026';
2380 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2381     $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')");
2382
2383     print "Upgrade to $DBversion done (added numReturnedItemsToShow system preference)\n";
2384     SetVersion ($DBversion);
2385 }
2386
2387 $DBversion = '3.01.00.027';
2388 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2389     $dbh->do("ALTER TABLE zebraqueue CHANGE `biblio_auth_number` `biblio_auth_number` bigint(20) unsigned NOT NULL default 0");
2390     print "Upgrade to $DBversion done (Increased size of zebraqueue biblio_auth_number to address bug 3148.)\n";
2391     SetVersion ($DBversion);
2392 }
2393
2394 $DBversion = '3.01.00.028';
2395 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2396     my $enable_reviews = C4::Context->preference('AmazonEnabled') ? '1' : '0';
2397     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AmazonReviews', '$enable_reviews', 'Display Amazon reviews on staff interface','','YesNo')");
2398     print "Upgrade to $DBversion done (added AmazonReviews)\n";
2399     SetVersion ($DBversion);
2400 }
2401
2402 $DBversion = '3.01.00.029';
2403 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2404     $dbh->do(q( UPDATE language_rfc4646_to_iso639
2405                 SET iso639_2_code = 'spa'
2406                 WHERE rfc4646_subtag = 'es'
2407                 AND   iso639_2_code = 'rus' )
2408             );
2409     print "Upgrade to $DBversion done (fixed bug 2599: using Spanish search limit retrieves Russian results)\n";
2410     SetVersion ($DBversion);
2411 }
2412
2413 $DBversion = "3.01.00.030";
2414 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2415     $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')");
2416     print "Upgrade to $DBversion done (added AllowNotForLoanOverride system preference)\n";
2417     SetVersion ($DBversion);
2418 }
2419
2420 $DBversion = "3.01.00.031";
2421 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2422     $dbh->do("ALTER TABLE branch_transfer_limits
2423               MODIFY toBranch   varchar(10) NOT NULL,
2424               MODIFY fromBranch varchar(10) NOT NULL,
2425               MODIFY itemtype   varchar(10) NULL");
2426     print "Upgrade to $DBversion done (fix column widths in branch_transfer_limits)\n";
2427     SetVersion ($DBversion);
2428 }
2429
2430 $DBversion = "3.01.00.032";
2431 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2432     $dbh->do(<<ENDOFRENEWAL);
2433 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');
2434 ENDOFRENEWAL
2435     print "Upgrade to $DBversion done (Change the field)\n";
2436     SetVersion ($DBversion);
2437 }
2438
2439 $DBversion = "3.01.00.033";
2440 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2441     $dbh->do(q/
2442         ALTER TABLE borrower_message_preferences
2443         MODIFY borrowernumber int(11) default NULL,
2444         ADD    categorycode varchar(10) default NULL AFTER borrowernumber,
2445         ADD KEY `categorycode` (`categorycode`),
2446         ADD CONSTRAINT `borrower_message_preferences_ibfk_3`
2447                        FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
2448                        ON DELETE CASCADE ON UPDATE CASCADE
2449     /);
2450     print "Upgrade to $DBversion done (DB changes to allow patron category defaults for messaging preferences)\n";
2451     SetVersion ($DBversion);
2452 }
2453
2454 $DBversion = "3.01.00.034";
2455 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2456     $dbh->do("ALTER TABLE `subscription` ADD COLUMN `graceperiod` INT(11) NOT NULL default '0';");
2457     print "Upgrade to $DBversion done (Adding graceperiod column to subscription table)\n";
2458     SetVersion ($DBversion);
2459 }
2460
2461 $DBversion = '3.01.00.035';
2462 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2463     $dbh->do(q{ ALTER TABLE `subscription` ADD location varchar(80) NULL DEFAULT '' AFTER callnumber; });
2464    print "Upgrade to $DBversion done (Adding location to subscription table)\n";
2465     SetVersion ($DBversion);
2466 }
2467
2468 $DBversion = '3.01.00.036';
2469 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2470     $dbh->do("UPDATE systempreferences SET explanation = 'Choose the default detail view in the staff interface; choose between normal, labeled_marc, marc or isbd'
2471               WHERE variable = 'IntranetBiblioDefaultView'
2472               AND   explanation = 'IntranetBiblioDefaultView'");
2473     $dbh->do("UPDATE systempreferences SET type = 'Choice', options = 'normal|marc|isbd|labeled_marc'
2474               WHERE variable = 'IntranetBiblioDefaultView'");
2475     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewISBD','1','Allow display of ISBD view of bibiographic records','','YesNo')");
2476     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewLabeledMARC','0','Allow display of labeled MARC view of bibiographic records','','YesNo')");
2477     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewMARC','1','Allow display of MARC view of bibiographic records','','YesNo')");
2478     print "Upgrade to $DBversion done (new viewISBD, viewLabeledMARC, viewMARC sysprefs and tweak IntranetBiblioDefaultView)\n";
2479     SetVersion ($DBversion);
2480 }
2481
2482 $DBversion = '3.01.00.037';
2483 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2484     $dbh->do('ALTER TABLE authorised_values ADD KEY `lib` (`lib`)');
2485     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('FilterBeforeOverdueReport','0','Do not run overdue report until filter selected','','YesNo')");
2486     SetVersion ($DBversion);
2487     print "Upgrade to $DBversion done (added FilterBeforeOverdueReport syspref and new index on authorised_values)\n";
2488 }
2489
2490 $DBversion = "3.01.00.038";
2491 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2492     # update branches table
2493     #
2494     $dbh->do("ALTER TABLE branches ADD `branchzip` varchar(25) default NULL AFTER `branchaddress3`");
2495     $dbh->do("ALTER TABLE branches ADD `branchcity` mediumtext AFTER `branchzip`");
2496     $dbh->do("ALTER TABLE branches ADD `branchcountry` text AFTER `branchcity`");
2497     $dbh->do("ALTER TABLE branches ADD `branchurl` mediumtext AFTER `branchemail`");
2498     $dbh->do("ALTER TABLE branches ADD `branchnotes` mediumtext AFTER `branchprinter`");
2499     print "Upgrade to $DBversion done (add ZIP, city, country, URL, and notes column to branches)\n";
2500     SetVersion ($DBversion);
2501 }
2502
2503 $DBversion = '3.01.00.039';
2504 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2505     $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')");
2506     $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')");
2507     SetVersion ($DBversion);
2508     print "Upgrade to $DBversion done (added SpineLabelFormat and SpineLabelAutoPrint sysprefs)\n";
2509 }
2510
2511 $DBversion = '3.01.00.040';
2512 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2513     $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')");
2514     $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')");
2515     SetVersion ($DBversion);
2516     print "Upgrade to $DBversion done (AllowHoldDateInFuture and OPACAllowHoldDateInFuture sysprefs)\n";
2517 }
2518
2519 $DBversion = '3.01.00.041';
2520 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2521     $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')");
2522     SetVersion ($DBversion);
2523     print "Upgrade to $DBversion done (added AWSPrivateKey syspref - note that if you use enhanced content from Amazon, this should be set right away.)\n";
2524 }
2525
2526 $DBversion = '3.01.00.042';
2527 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2528     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACFineNoRenewals','99999','Fine Limit above which user canmot renew books via OPAC','','Integer')");
2529     SetVersion ($DBversion);
2530     print "Upgrade to $DBversion done (added OPACFineNoRenewals syspref)\n";
2531 }
2532
2533 $DBversion = '3.01.00.043';
2534 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2535     $dbh->do('ALTER TABLE items ADD COLUMN permanent_location VARCHAR(80) DEFAULT NULL AFTER location');
2536     $dbh->do('UPDATE items SET permanent_location = location');
2537     $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 )', '')");
2538     $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')");
2539     $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')");
2540     SetVersion ($DBversion);
2541     print "Upgrade to $DBversion done (amended Item added NewItemsDefaultLocation, InProcessingToShelvingCart, ReturnToShelvingCart sysprefs)\n";
2542 }
2543
2544 $DBversion = '3.01.00.044';
2545 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2546     $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')");
2547     SetVersion ($DBversion);
2548     print "Upgrade to $DBversion done (added DisplayClearScreenButton system preference)\n";
2549 }
2550
2551 $DBversion = '3.01.00.045';
2552 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2553     $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')");
2554     SetVersion ($DBversion);
2555     print "Upgrade to $DBversion done (added a preference to hide the patrons name in the staff catalog)\n";
2556 }
2557
2558 $DBversion = "3.01.00.046";
2559 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2560     # update borrowers table
2561     #
2562     $dbh->do("ALTER TABLE borrowers ADD `country` text AFTER zipcode");
2563     $dbh->do("ALTER TABLE borrowers ADD `B_country` text AFTER B_zipcode");
2564     $dbh->do("ALTER TABLE deletedborrowers ADD `country` text AFTER zipcode");
2565     $dbh->do("ALTER TABLE deletedborrowers ADD `B_country` text AFTER B_zipcode");
2566     print "Upgrade to $DBversion done (add country and B_country to borrowers)\n";
2567     SetVersion ($DBversion);
2568 }
2569
2570 $DBversion = '3.01.00.047';
2571 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2572     $dbh->do("ALTER TABLE items MODIFY itemcallnumber varchar(255);");
2573     $dbh->do("ALTER TABLE deleteditems MODIFY itemcallnumber varchar(255);");
2574     $dbh->do("ALTER TABLE tmp_holdsqueue MODIFY itemcallnumber varchar(255);");
2575     SetVersion ($DBversion);
2576     print " Upgrade to $DBversion done (bug 2761: change max length of itemcallnumber to 255 from 30)\n";
2577 }
2578
2579 $DBversion = '3.01.00.048';
2580 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2581     $dbh->do("UPDATE userflags SET flagdesc='View Catalog (Librarian Interface)' WHERE bit=2;");
2582     $dbh->do("UPDATE userflags SET flagdesc='Edit Catalog (Modify bibliographic/holdings data)' WHERE bit=9;");
2583     $dbh->do("UPDATE userflags SET flagdesc='Allow to edit authorities' WHERE bit=14;");
2584     $dbh->do("UPDATE userflags SET flagdesc='Allow to access to the reports module' WHERE bit=16;");
2585     $dbh->do("UPDATE userflags SET flagdesc='Allow to manage serials subscriptions' WHERE bit=15;");
2586     SetVersion ($DBversion);
2587     print " Upgrade to $DBversion done (bug 2611: fix spelling/capitalization in permission flag descriptions)\n";
2588 }
2589
2590 $DBversion = '3.01.00.049';
2591 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2592     $dbh->do("UPDATE permissions SET description = 'Perform inventory (stocktaking) of your catalog' WHERE code = 'inventory';");
2593      SetVersion ($DBversion);
2594     print "Upgrade to $DBversion done (bug 2611: changed catalogue to catalog per the standard)\n";
2595 }
2596
2597 $DBversion = '3.01.00.050';
2598 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2599     $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');");
2600     SetVersion ($DBversion);
2601     print "Upgrade to $DBversion done (bug 1934: Add OPACSearchForTitleIn syspref)\n";
2602 }
2603
2604 $DBversion = '3.01.00.051';
2605 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2606     $dbh->do("UPDATE systempreferences SET explanation='Fine limit above which user cannot renew books via OPAC' WHERE variable='OPACFineNoRenewals';");
2607     $dbh->do("UPDATE systempreferences SET explanation='If set to ON, a clear screen button will appear on the circulation page.' WHERE variable='DisplayClearScreenButton';");
2608     SetVersion ($DBversion);
2609     print "Upgrade to $DBversion done (fixed typos in new sysprefs)\n";
2610 }
2611
2612 $DBversion = '3.01.00.052';
2613 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2614     $dbh->do('ALTER TABLE deleteditems ADD COLUMN permanent_location VARCHAR(80) DEFAULT NULL AFTER location');
2615     SetVersion ($DBversion);
2616     print "Upgrade to $DBversion done (bug 3481: add permanent_location column to deleteditems)\n";
2617 }
2618
2619 $DBversion = '3.01.00.053';
2620 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2621     my $upgrade_script = C4::Context->config("intranetdir") . "/installer/data/mysql/labels_upgrade.pl";
2622     system("perl $upgrade_script");
2623     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";
2624     SetVersion ($DBversion);
2625 }
2626
2627 $DBversion = '3.01.00.054';
2628 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2629     $dbh->do("ALTER TABLE borrowers ADD `B_address2` text AFTER B_address");
2630     $dbh->do("ALTER TABLE borrowers ADD `altcontactcountry` text AFTER altcontactzipcode");
2631     $dbh->do("ALTER TABLE deletedborrowers ADD `B_address2` text AFTER B_address");
2632     $dbh->do("ALTER TABLE deletedborrowers ADD `altcontactcountry` text AFTER altcontactzipcode");
2633     SetVersion ($DBversion);
2634     print "Upgrade to $DBversion done (bug 1600, bug 3454: add altcontactcountry and B_address2 to borrowers and deletedborrowers)\n";
2635 }
2636
2637 $DBversion = '3.01.00.055';
2638 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2639     $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'|);
2640     SetVersion ($DBversion);
2641     print "Upgrade to $DBversion done (changed OPACSearchForTitleIn per requests in bug 1934)\n";
2642 }
2643
2644 $DBversion = '3.01.00.056';
2645 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2646     $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');");
2647     SetVersion ($DBversion);
2648     print "Upgrade to $DBversion done (Bug 1172 : Add OPACPatronDetails syspref)\n";
2649 }
2650
2651 $DBversion = '3.01.00.057';
2652 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2653     $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');");
2654     SetVersion ($DBversion);
2655     print "Upgrade to $DBversion done (Bug 2576 : Add OPACFinesTab syspref)\n";
2656 }
2657
2658 $DBversion = '3.01.00.058';
2659 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2660     $dbh->do("ALTER TABLE `language_subtag_registry` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2661     $dbh->do("ALTER TABLE `language_rfc4646_to_iso639` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2662     $dbh->do("ALTER TABLE `language_descriptions` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2663     SetVersion ($DBversion);
2664     print "Upgrade to $DBversion done (Added primary keys to language tables)\n";
2665 }
2666
2667 $DBversion = '3.01.00.059';
2668 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2669     $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')");
2670     SetVersion ($DBversion);
2671     print "Upgrade to $DBversion done (added DisplayOPACiconsXSLT sysprefs)\n";
2672 }
2673
2674 $DBversion = '3.01.00.060';
2675 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2676     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowAllMessageDeletion','0','Allow any Library to delete any message','','YesNo');");
2677     $dbh->do('DROP TABLE IF EXISTS messages');
2678     $dbh->do("CREATE TABLE messages ( `message_id` int(11) NOT NULL auto_increment,
2679         `borrowernumber` int(11) NOT NULL,
2680         `branchcode` varchar(4) default NULL,
2681         `message_type` varchar(1) NOT NULL,
2682         `message` text NOT NULL,
2683         `message_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
2684         PRIMARY KEY (`message_id`)
2685         ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
2686
2687         print "Upgrade to $DBversion done ( Added AllowAllMessageDeletion syspref and messages table )\n";
2688     SetVersion ($DBversion);
2689 }
2690
2691 $DBversion = '3.01.00.061';
2692 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2693     $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')");
2694         print "Upgrade to $DBversion done ( Added ShowPatronImageInWebBasedSelfCheck system preference )\n";
2695     SetVersion ($DBversion);
2696 }
2697
2698 $DBversion = "3.01.00.062";
2699 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2700     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'manage_csv_profiles', 'Manage CSV export profiles')");
2701     $dbh->do(q/
2702         CREATE TABLE `export_format` (
2703           `export_format_id` int(11) NOT NULL auto_increment,
2704           `profile` varchar(255) NOT NULL,
2705           `description` mediumtext NOT NULL,
2706           `marcfields` mediumtext NOT NULL,
2707           PRIMARY KEY  (`export_format_id`)
2708         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Used for CSV export';
2709     /);
2710     print "Upgrade to $DBversion done (added csv export profiles)\n";
2711 }
2712
2713 $DBversion = "3.01.00.063";
2714 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2715     $dbh->do("
2716         CREATE TABLE `fieldmapping` (
2717           `id` int(11) NOT NULL auto_increment,
2718           `field` varchar(255) NOT NULL,
2719           `frameworkcode` char(4) NOT NULL default '',
2720           `fieldcode` char(3) NOT NULL,
2721           `subfieldcode` char(1) NOT NULL,
2722           PRIMARY KEY  (`id`)
2723         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2724              ");
2725     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";
2726 }
2727
2728 $DBversion = '3.01.00.065';
2729 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2730     $dbh->do('ALTER TABLE issuingrules ADD COLUMN `renewalsallowed` smallint(6) NOT NULL default "0" AFTER `issuelength`;');
2731     $sth = $dbh->prepare("SELECT itemtype, renewalsallowed FROM itemtypes");
2732     $sth->execute();
2733
2734     my $sthupd = $dbh->prepare("UPDATE issuingrules SET renewalsallowed = ? WHERE itemtype = ?");
2735
2736     while(my $row = $sth->fetchrow_hashref){
2737         $sthupd->execute($row->{renewalsallowed}, $row->{itemtype});
2738     }
2739
2740     $dbh->do('ALTER TABLE itemtypes DROP COLUMN `renewalsallowed`;');
2741
2742     SetVersion ($DBversion);
2743     print "Upgrade to $DBversion done (Moving allowed renewals from itemtypes to issuingrule)\n";
2744 }
2745
2746 $DBversion = '3.01.00.066';
2747 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2748     $dbh->do('ALTER TABLE issuingrules ADD COLUMN `reservesallowed` smallint(6) NOT NULL default "0" AFTER `renewalsallowed`;');
2749
2750     my $maxreserves = C4::Context->preference('maxreserves');
2751     $sth = $dbh->prepare('UPDATE issuingrules SET reservesallowed = ?;');
2752     $sth->execute($maxreserves);
2753
2754     $dbh->do('DELETE FROM systempreferences WHERE variable = "maxreserves";');
2755
2756     $dbh->do("INSERT INTO systempreferences (variable,value, options, explanation, type) VALUES('ReservesControlBranch','PatronLibrary','ItemHomeLibrary|PatronLibrary','Branch checked for members reservations rights','Choice')");
2757
2758     SetVersion ($DBversion);
2759     print "Upgrade to $DBversion done (Moving max allowed reserves from system preference to issuingrule)\n";
2760 }
2761
2762 $DBversion = "3.01.00.067";
2763 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2764     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'batchmod', 'Perform batch modification of items')");
2765     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'batchdel', 'Perform batch deletion of items')");
2766     print "Upgrade to $DBversion done (added permissions for batch modification and deletion)\n";
2767     SetVersion ($DBversion);
2768 }
2769
2770 $DBversion = "3.01.00.068";
2771 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2772         $dbh->do("ALTER TABLE issuingrules ADD COLUMN `finedays` int(11) default NULL AFTER `fine` ");
2773         print "Upgrade to $DBversion done (Adding finedays in issuingrules table)\n";
2774     SetVersion ($DBversion);
2775 }
2776
2777
2778 $DBversion = "3.01.00.069";
2779 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2780         $dbh->do("INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('EnableOpacSearchHistory', '1', '', 'Enable or disable opac search history', 'YesNo')");
2781
2782         my $create = <<SEARCHHIST;
2783 CREATE TABLE IF NOT EXISTS `search_history` (
2784   `userid` int(11) NOT NULL,
2785   `sessionid` varchar(32) NOT NULL,
2786   `query_desc` varchar(255) NOT NULL,
2787   `query_cgi` varchar(255) NOT NULL,
2788   `total` int(11) NOT NULL,
2789   `time` timestamp NOT NULL default CURRENT_TIMESTAMP,
2790   KEY `userid` (`userid`),
2791   KEY `sessionid` (`sessionid`)
2792 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Opac search history results';
2793 SEARCHHIST
2794         $dbh->do($create);
2795
2796         print "Upgrade to $DBversion done (added OPAC search history preference and table)\n";
2797 }
2798
2799 $DBversion = "3.01.00.070";
2800 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2801         $dbh->do("ALTER TABLE authorised_values ADD COLUMN `lib_opac` VARCHAR(80) default NULL AFTER `lib`");
2802         print "Upgrade to $DBversion done (Added a lib_opac field in authorised_values table)\n";
2803 }
2804
2805 $DBversion = "3.01.00.071";
2806 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2807         $dbh->do("ALTER TABLE `subscription` ADD `enddate` date default NULL");
2808         $dbh->do("ALTER TABLE subscriptionhistory CHANGE enddate histenddate DATE default NULL");
2809         print "Upgrade to $DBversion done ( Adding enddate to subscription)\n";
2810 }
2811
2812 # Acquisitions update
2813
2814 $DBversion = "3.01.00.072";
2815 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2816     $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')");
2817     # create a new syspref for the 'Mr anonymous' patron
2818     $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,'')");
2819     # fill AnonymousPatron with AnonymousSuggestion value (copy)
2820     my $sth=$dbh->prepare("SELECT value FROM systempreferences WHERE variable='AnonSuggestions'");
2821     $sth->execute;
2822     my ($value) = $sth->fetchrow() || 0;
2823     $dbh->do("UPDATE systempreferences SET value='$value' WHERE variable='AnonymousPatron'");
2824     # set AnonymousSuggestion do YesNo
2825     # 1st, set the value (1/True if it had a borrowernumber)
2826     $dbh->do("UPDATE systempreferences SET value=1 WHERE variable='AnonSuggestions' AND value>0");
2827     # 2nd, change the type to Choice
2828     $dbh->do("UPDATE systempreferences SET type='YesNo' WHERE variable='AnonSuggestions'");
2829         # borrower reading record privacy : 0 : forever, 1 : laws, 2 : don't keep at all
2830     $dbh->do("ALTER TABLE `borrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
2831     print "Upgrade to $DBversion done (add new syspref and column in borrowers)\n";
2832     SetVersion ($DBversion);
2833 }
2834
2835 $DBversion = '3.01.00.073';
2836 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2837     $dbh->do('SET FOREIGN_KEY_CHECKS=0 ');
2838     $dbh->do(<<'END_SQL');
2839 CREATE TABLE IF NOT EXISTS `aqcontract` (
2840   `contractnumber` int(11) NOT NULL auto_increment,
2841   `contractstartdate` date default NULL,
2842   `contractenddate` date default NULL,
2843   `contractname` varchar(50) default NULL,
2844   `contractdescription` mediumtext,
2845   `booksellerid` int(11) not NULL,
2846     PRIMARY KEY  (`contractnumber`),
2847         CONSTRAINT `booksellerid_fk1` FOREIGN KEY (`booksellerid`)
2848         REFERENCES `aqbooksellers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
2849 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
2850 END_SQL
2851     $dbh->do('SET FOREIGN_KEY_CHECKS=1 ');
2852     print "Upgrade to $DBversion done (adding aqcontract table)\n";
2853     SetVersion ($DBversion);
2854 }
2855
2856 $DBversion = '3.01.00.074';
2857 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2858     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `basketname` varchar(50) default NULL AFTER `basketno`");
2859     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `note` mediumtext AFTER `basketname`");
2860     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `booksellernote` mediumtext AFTER `note`");
2861     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `contractnumber` int(11) AFTER `booksellernote`");
2862     $dbh->do("ALTER TABLE `aqbasket` ADD FOREIGN KEY (`contractnumber`) REFERENCES `aqcontract` (`contractnumber`)");
2863     print "Upgrade to $DBversion done (edit aqbasket table done)\n";
2864     SetVersion ($DBversion);
2865 }
2866
2867 $DBversion = '3.01.00.075';
2868 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2869     $dbh->do("ALTER TABLE `aqorders` ADD COLUMN `uncertainprice` tinyint(1)");
2870
2871     print "Upgrade to $DBversion done (adding uncertainprices)\n";
2872     SetVersion ($DBversion);
2873 }
2874
2875 $DBversion = '3.01.00.076';
2876 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2877     $dbh->do('SET FOREIGN_KEY_CHECKS=0 ');
2878     $dbh->do("CREATE TABLE IF NOT EXISTS `aqbasketgroups` (
2879                          `id` int(11) NOT NULL auto_increment,
2880                          `name` varchar(50) default NULL,
2881                          `closed` tinyint(1) default NULL,
2882                          `booksellerid` int(11) NOT NULL,
2883                          PRIMARY KEY (`id`),
2884                          KEY `booksellerid` (`booksellerid`),
2885                          CONSTRAINT `aqbasketgroups_ibfk_1` FOREIGN KEY (`booksellerid`) REFERENCES `aqbooksellers` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
2886                          ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
2887     $dbh->do("ALTER TABLE aqbasket ADD COLUMN `basketgroupid` int(11)");
2888     $dbh->do("ALTER TABLE aqbasket ADD FOREIGN KEY (`basketgroupid`) REFERENCES `aqbasketgroups` (`id`) ON UPDATE CASCADE ON DELETE SET NULL");
2889     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('pdfformat','pdfformat::layout2pages','Controls what script is used for printing (basketgroups)','','free')");
2890     $dbh->do('SET FOREIGN_KEY_CHECKS=1 ');
2891     print "Upgrade to $DBversion done (adding basketgroups)\n";
2892     SetVersion ($DBversion);
2893 }
2894 $DBversion = '3.01.00.077';
2895 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2896
2897     $dbh->do("SET FOREIGN_KEY_CHECKS=0 ");
2898     # create a mapping table holding the info we need to match orders to budgets
2899     $dbh->do('DROP TABLE IF EXISTS fundmapping');
2900     $dbh->do(
2901         q|CREATE TABLE fundmapping AS
2902         SELECT aqorderbreakdown.ordernumber, branchcode, bookfundid, budgetdate, entrydate
2903         FROM aqorderbreakdown JOIN aqorders ON aqorderbreakdown.ordernumber = aqorders.ordernumber|);
2904     # match the new type of the corresponding field
2905     $dbh->do('ALTER TABLE fundmapping modify column bookfundid varchar(30)');
2906     # System did not ensure budgetdate was valid historically
2907     $dbh->do(q|UPDATE fundmapping SET budgetdate = entrydate WHERE budgetdate = '0000-00-00' OR budgetdate IS NULL|);
2908     # We save the map in fundmapping in case you need later processing
2909     $dbh->do(q|ALTER TABLE fundmapping add column aqbudgetid integer|);
2910     # these can speed processing up
2911     $dbh->do(q|CREATE INDEX fundmaporder ON fundmapping (ordernumber)|);
2912     $dbh->do(q|CREATE INDEX fundmapid ON fundmapping (bookfundid)|);
2913
2914     $dbh->do("DROP TABLE IF EXISTS `aqbudgetperiods` ");
2915
2916     $dbh->do(qq|
2917                     CREATE TABLE `aqbudgetperiods` (
2918                     `budget_period_id` int(11) NOT NULL auto_increment,
2919                     `budget_period_startdate` date NOT NULL,
2920                     `budget_period_enddate` date NOT NULL,
2921                     `budget_period_active` tinyint(1) default '0',
2922                     `budget_period_description` mediumtext,
2923                     `budget_period_locked` tinyint(1) default NULL,
2924                     `sort1_authcat` varchar(10) default NULL,
2925                     `sort2_authcat` varchar(10) default NULL,
2926                     PRIMARY KEY  (`budget_period_id`)
2927                     ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 |);
2928
2929    $dbh->do(<<ADDPERIODS);
2930 INSERT INTO aqbudgetperiods (budget_period_startdate,budget_period_enddate,budget_period_active,budget_period_description,budget_period_locked)
2931 SELECT DISTINCT startdate, enddate, NOW() BETWEEN startdate and enddate, concat(startdate," ",enddate),NOT NOW() BETWEEN startdate AND enddate from aqbudget
2932 ADDPERIODS
2933 # SORRY , NO AQBUDGET/AQBOOKFUND -> AQBUDGETS IMPORT JUST YET,
2934 # BUT A NEW CLEAN AQBUDGETS TABLE CREATE FOR NOW..
2935 # DROP TABLE IF EXISTS `aqbudget`;
2936 #CREATE TABLE `aqbudget` (
2937 #  `bookfundid` varchar(10) NOT NULL default ',
2938 #    `startdate` date NOT NULL default 0,
2939 #         `enddate` date default NULL,
2940 #           `budgetamount` decimal(13,2) default NULL,
2941 #                 `aqbudgetid` tinyint(4) NOT NULL auto_increment,
2942 #                   `branchcode` varchar(10) default NULL,
2943     DropAllForeignKeys('aqbudget');
2944   #$dbh->do("drop table aqbudget;");
2945
2946
2947     my $maxbudgetid = $dbh->selectcol_arrayref(<<IDsBUDGET);
2948 SELECT MAX(aqbudgetid) from aqbudget
2949 IDsBUDGET
2950
2951 $$maxbudgetid[0] = 0 if !$$maxbudgetid[0];
2952
2953     $dbh->do(<<BUDGETAUTOINCREMENT);
2954 ALTER TABLE aqbudget AUTO_INCREMENT=$$maxbudgetid[0]
2955 BUDGETAUTOINCREMENT
2956
2957     $dbh->do(<<BUDGETNAME);
2958 ALTER TABLE aqbudget RENAME `aqbudgets`
2959 BUDGETNAME
2960
2961     $dbh->do(<<BUDGETS);
2962 ALTER TABLE `aqbudgets`
2963    CHANGE  COLUMN aqbudgetid `budget_id` int(11) NOT NULL AUTO_INCREMENT,
2964    CHANGE  COLUMN branchcode `budget_branchcode` varchar(10) default NULL,
2965    CHANGE  COLUMN budgetamount `budget_amount` decimal(28,6) NOT NULL default '0.00',
2966    CHANGE  COLUMN bookfundid   `budget_code` varchar(30) default NULL,
2967    ADD     COLUMN `budget_parent_id` int(11) default NULL,
2968    ADD     COLUMN `budget_name` varchar(80) default NULL,
2969    ADD     COLUMN `budget_encumb` decimal(28,6) default '0.00',
2970    ADD     COLUMN `budget_expend` decimal(28,6) default '0.00',
2971    ADD     COLUMN `budget_notes` mediumtext,
2972    ADD     COLUMN `budget_description` mediumtext,
2973    ADD     COLUMN `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
2974    ADD     COLUMN `budget_amount_sublevel`  decimal(28,6) AFTER `budget_amount`,
2975    ADD     COLUMN `budget_period_id` int(11) default NULL,
2976    ADD     COLUMN `sort1_authcat` varchar(80) default NULL,
2977    ADD     COLUMN `sort2_authcat` varchar(80) default NULL,
2978    ADD     COLUMN `budget_owner_id` int(11) default NULL,
2979    ADD     COLUMN `budget_permission` int(1) default '0';
2980 BUDGETS
2981
2982     $dbh->do(<<BUDGETCONSTRAINTS);
2983 ALTER TABLE `aqbudgets`
2984    ADD CONSTRAINT `aqbudgets_ifbk_1` FOREIGN KEY (`budget_period_id`) REFERENCES `aqbudgetperiods` (`budget_period_id`) ON DELETE CASCADE ON UPDATE CASCADE
2985 BUDGETCONSTRAINTS
2986 #    $dbh->do(<<BUDGETPKDROP);
2987 #ALTER TABLE `aqbudgets`
2988 #   DROP PRIMARY KEY
2989 #BUDGETPKDROP
2990 #    $dbh->do(<<BUDGETPKADD);
2991 #ALTER TABLE `aqbudgets`
2992 #   ADD PRIMARY KEY budget_id
2993 #BUDGETPKADD
2994
2995
2996         my $query_period= $dbh->prepare(qq|SELECT budget_period_id from aqbudgetperiods where budget_period_startdate=? and budget_period_enddate=?|);
2997         my $query_bookfund= $dbh->prepare(qq|SELECT * from aqbookfund where bookfundid=?|);
2998         my $selectbudgets=$dbh->prepare(qq|SELECT * from aqbudgets|);
2999         my $updatebudgets=$dbh->prepare(qq|UPDATE aqbudgets SET budget_period_id= ? , budget_name=?, budget_branchcode=? where budget_id=?|);
3000         $selectbudgets->execute;
3001         while (my $databudget=$selectbudgets->fetchrow_hashref){
3002                 $query_period->execute ($$databudget{startdate},$$databudget{enddate});
3003                 my ($budgetperiodid)=$query_period->fetchrow;
3004                 $query_bookfund->execute ($$databudget{budget_code});
3005                 my $databf=$query_bookfund->fetchrow_hashref;
3006                 my $branchcode=$$databudget{budget_branchcode}||$$databf{branchcode};
3007                 $updatebudgets->execute($budgetperiodid,$$databf{bookfundname},$branchcode,$$databudget{budget_id});
3008         }
3009     $dbh->do(<<BUDGETDROPDATES);
3010 ALTER TABLE `aqbudgets`
3011    DROP startdate,
3012    DROP enddate
3013 BUDGETDROPDATES
3014
3015
3016     $dbh->do("DROP TABLE IF EXISTS `aqbudgets_planning` ");
3017     $dbh->do("CREATE TABLE  `aqbudgets_planning` (
3018                     `plan_id` int(11) NOT NULL auto_increment,
3019                     `budget_id` int(11) NOT NULL,
3020                     `budget_period_id` int(11) NOT NULL,
3021                     `estimated_amount` decimal(28,6) default NULL,
3022                     `authcat` varchar(30) NOT NULL,
3023                     `authvalue` varchar(30) NOT NULL,
3024                                         `display` tinyint(1) DEFAULT 1,
3025                         PRIMARY KEY  (`plan_id`),
3026                         CONSTRAINT `aqbudgets_planning_ifbk_1` FOREIGN KEY (`budget_id`) REFERENCES `aqbudgets` (`budget_id`) ON DELETE CASCADE ON UPDATE CASCADE
3027                         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
3028
3029     $dbh->do("ALTER TABLE `aqorders`
3030                     ADD COLUMN `budget_id` tinyint(4) NOT NULL,
3031                     ADD COLUMN `budgetgroup_id` int(11) NOT NULL,
3032                     ADD COLUMN  `sort1_authcat` varchar(10) default NULL,
3033                     ADD COLUMN  `sort2_authcat` varchar(10) default NULL" );
3034                 # We need to map the orders to the budgets
3035                 # For Historic reasons this is more complex than it should be on occasions
3036                 my $budg_arr = $dbh->selectall_arrayref(
3037                     q|SELECT aqbudgets.budget_id, aqbudgets.budget_code, aqbudgetperiods.budget_period_startdate,
3038                     aqbudgetperiods.budget_period_enddate
3039                     FROM aqbudgets JOIN aqbudgetperiods ON aqbudgets.budget_period_id = aqbudgetperiods.budget_period_id
3040                     ORDER BY budget_code, budget_period_startdate|, { Slice => {} });
3041                 # We arbitarily order on start date, this means if you have overlapping periods the order will be
3042                 # linked to the latest matching budget YMMV
3043                 my $b_sth = $dbh->prepare(
3044                     'UPDATE fundmapping set aqbudgetid = ? where bookfundid =? AND budgetdate >= ? AND budgetdate <= ?');
3045                 for my $b ( @{$budg_arr}) {
3046                     $b_sth->execute($b->{budget_id}, $b->{budget_code}, $b->{budget_period_startdate}, $b->{budget_period_enddate});
3047                 }
3048                 # move the budgetids to aqorders
3049                 $dbh->do(q|UPDATE aqorders, fundmapping SET aqorders.budget_id = fundmapping.aqbudgetid
3050                     WHERE aqorders.ordernumber = fundmapping.ordernumber AND fundmapping.aqbudgetid IS NOT NULL|);
3051                 # NB fundmapping is left as an accontants trail also if you have budgetids that werent set
3052                 # you can decide what to do with them
3053
3054      $dbh->do(
3055          q|UPDATE aqorders, aqbudgets SET aqorders.budgetgroup_id = aqbudgets.budget_period_id
3056          WHERE aqorders.budget_id = aqbudgets.budget_id|);
3057                 # cannot do until aqorderbreakdown removed
3058 #    $dbh->do("DROP TABLE aqbookfund ");
3059 #    $dbh->do("ALTER TABLE aqorders  ADD FOREIGN KEY (`budget_id`) REFERENCES `aqbudgets` (`budget_id`) ON UPDATE CASCADE  " ); ????
3060     $dbh->do("SET FOREIGN_KEY_CHECKS=1 ");
3061
3062     print "Upgrade to $DBversion done (Adding new aqbudgetperiods, aqbudgets and aqbudget_planning tables  )\n";
3063     SetVersion ($DBversion);
3064 }
3065
3066
3067
3068 $DBversion = '3.01.00.078';
3069 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3070     $dbh->do("ALTER TABLE aqbudgetperiods ADD COLUMN budget_period_total decimal(28,6)");
3071     print "Upgrade to $DBversion done (adds 'budget_period_total' column to aqbudgetperiods table)\n";
3072     SetVersion($DBversion);
3073 }
3074
3075
3076 $DBversion = '3.01.00.079';
3077 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3078     $dbh->do("ALTER TABLE currency ADD COLUMN active  tinyint(1)");
3079
3080     print "Upgrade to $DBversion done (adds 'active' column to currencies table)\n";
3081     SetVersion($DBversion);
3082 }
3083
3084 $DBversion = '3.01.00.080';
3085 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3086     $dbh->do(<<BUDG_PERM );
3087 INSERT INTO permissions (module_bit, code, description) VALUES
3088             (11, 'vendors_manage', 'Manage vendors'),
3089             (11, 'contracts_manage', 'Manage contracts'),
3090             (11, 'period_manage', 'Manage periods'),
3091             (11, 'budget_manage', 'Manage budgets'),
3092             (11, 'budget_modify', "Modify budget (can't create lines but can modify existing ones)"),
3093             (11, 'planning_manage', 'Manage budget plannings'),
3094             (11, 'order_manage', 'Manage orders & basket'),
3095             (11, 'group_manage', 'Manage orders & basketgroups'),
3096             (11, 'order_receive', 'Manage orders & basket'),
3097             (11, 'budget_add_del', "Add and delete budgets (but can't modify budgets)");
3098 BUDG_PERM
3099
3100     print "Upgrade to $DBversion done (adds permissions for the acquisitions module)\n";
3101     SetVersion($DBversion);
3102 }
3103
3104
3105 $DBversion = '3.01.00.081';
3106 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3107     $dbh->do("ALTER TABLE aqbooksellers ADD COLUMN `gstrate` decimal(6,4) default NULL");
3108     if (my $gist=C4::Context->preference("gist")){
3109                 my $sql=$dbh->prepare("UPDATE aqbooksellers set `gstrate`=? ");
3110         $sql->execute($gist) ;
3111         }
3112     print "Upgrade to $DBversion done (added per-supplier gstrate setting)\n";
3113     SetVersion($DBversion);
3114 }
3115
3116 $DBversion = "3.01.00.082";
3117 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3118     if (C4::Context->preference("opaclanguages") eq "fr") {
3119         $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')#);
3120     } else {
3121         $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')");
3122     }
3123     print "Upgrade to $DBversion done (adding ReservesNeedReturns systempref, in circulation)\n";
3124     SetVersion ($DBversion);
3125 }
3126
3127 $DBversion = "3.01.00.083";
3128 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3129     $dbh->do(qq|
3130  CREATE TABLE `aqorders_items` (
3131   `ordernumber` int(11) NOT NULL,
3132   `itemnumber` int(11) NOT NULL,
3133   `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
3134   PRIMARY KEY  (`itemnumber`),
3135   KEY `ordernumber` (`ordernumber`)
3136 ) ENGINE=InnoDB DEFAULT CHARSET=utf8   |
3137     );
3138
3139     $dbh->do(qq| DROP TABLE aqorderbreakdown |);
3140     $dbh->do('DROP TABLE aqbookfund');
3141     print "Upgrade to $DBversion done (New aqorders_items table for acqui)\n";
3142     SetVersion ($DBversion);
3143 }
3144
3145 $DBversion = "3.01.00.084";
3146 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3147     $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')  #);
3148
3149     print "Upgrade to $DBversion done (CurrencyFormat syspref added)\n";
3150     SetVersion ($DBversion);
3151 }
3152
3153 $DBversion = "3.01.00.085";
3154 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3155     $dbh->do("ALTER table aqorders drop column title");
3156     $dbh->do("ALTER TABLE `aqorders` CHANGE `budget_id` `budget_id` INT( 11 ) NOT NULL");
3157     print "Upgrade to $DBversion done update budget_id size that should not be a tinyint\n";
3158     SetVersion ($DBversion);
3159 }
3160
3161 $DBversion = "3.01.00.086";
3162 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3163     $dbh->do(<<SUGGESTIONS);
3164 ALTER table suggestions
3165     ADD budgetid INT(11),
3166     ADD branchcode VARCHAR(10) default NULL,
3167     ADD acceptedby INT(11) default NULL,
3168     ADD accepteddate date default NULL,
3169     ADD suggesteddate date default NULL,
3170     ADD manageddate date default NULL,
3171     ADD rejectedby INT(11) default NULL,
3172     ADD rejecteddate date default NULL,
3173     ADD collectiontitle text default NULL,
3174     ADD itemtype VARCHAR(30) default NULL
3175     ;
3176 SUGGESTIONS
3177     print "Upgrade to $DBversion done (Suggestions)\n";
3178     SetVersion ($DBversion);
3179 }
3180
3181 $DBversion = "3.01.00.087";
3182 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3183     $dbh->do("ALTER table aqbudgets drop column budget_amount_sublevel;");
3184     print "Upgrade to $DBversion done (Drop column budget_amount_sublevel from aqbudgets)\n";
3185     SetVersion ($DBversion);
3186 }
3187
3188 $DBversion = "3.01.00.088";
3189 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3190     $dbh->do(  qq# INSERT INTO `systempreferences` VALUES ('intranetbookbag','1','','If ON, enables display of Cart feature in the intranet','YesNo')  #);
3191
3192     print "Upgrade to $DBversion done (intranetbookbag syspref added)\n";
3193     SetVersion ($DBversion);
3194 }
3195
3196 $DBversion = "3.01.00.090";
3197 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3198 $dbh->do("
3199        INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3200                 (16, 'execute_reports', 'Execute SQL reports'),
3201                 (16, 'create_reports', 'Create SQL Reports')
3202         ");
3203
3204     print "Upgrade to $DBversion done (granular permissions for guided reports added)\n";
3205     SetVersion ($DBversion);
3206 }
3207
3208 $DBversion = "3.01.00.091";
3209 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3210 $dbh->do("
3211         UPDATE `systempreferences` SET `options` = 'holdings|serialcollection|subscriptions'
3212         WHERE `systempreferences`.`variable` = 'opacSerialDefaultTab' LIMIT 1
3213         ");
3214
3215     print "Upgrade to $DBversion done (opac-detail default tag updated)\n";
3216     SetVersion ($DBversion);
3217 }
3218
3219 $DBversion = "3.01.00.092";
3220 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3221     if (C4::Context->preference("opaclanguages") =~ /fr/) {
3222         $dbh->do(qq{
3223 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');
3224         });
3225         }else{
3226         $dbh->do(qq{
3227 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');
3228         });
3229         }
3230     print "Upgrade to $DBversion done (Added RoutingListAddReserves syspref)\n";
3231     SetVersion ($DBversion);
3232 }
3233
3234 $DBversion = "3.01.00.093";
3235 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3236         $dbh->do(qq{
3237         ALTER TABLE biblioitems ADD INDEX issn_idx (issn);
3238         });
3239     print "Upgrade to $DBversion done (added index to ISSN)\n";
3240     SetVersion ($DBversion);
3241 }
3242
3243 $DBversion = "3.01.00.094";
3244 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3245         $dbh->do(qq{
3246         ALTER TABLE aqbasketgroups ADD deliveryplace VARCHAR(10) default NULL, ADD deliverycomment VARCHAR(255) default NULL;
3247         });
3248
3249     print "Upgrade to $DBversion done (adding deliveryplace deliverycomment to basketgroups)\n";
3250     SetVersion ($DBversion);
3251 }
3252
3253 $DBversion = "3.01.00.095";
3254 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3255         $dbh->do(qq{
3256         ALTER TABLE items ADD stocknumber VARCHAR(32) DEFAULT NULL COMMENT "stores the inventory number";
3257         });
3258         $dbh->do(qq{
3259         ALTER TABLE items ADD UNIQUE INDEX itemsstocknumberidx (stocknumber);
3260         });
3261         $dbh->do(qq{
3262         ALTER TABLE deleteditems ADD stocknumber VARCHAR(32) DEFAULT NULL COMMENT "stores the inventory number of deleted items";
3263         });
3264         $dbh->do(qq{
3265         ALTER TABLE deleteditems ADD UNIQUE INDEX deleteditemsstocknumberidx (stocknumber);
3266         });
3267         if (C4::Context->preference('marcflavour') eq 'UNIMARC'){
3268                 $dbh->do(qq{
3269         INSERT IGNORE INTO marc_subfield_structure (frameworkcode,tagfield, tagsubfield, tab, repeatable, mandatory,kohafield)
3270         SELECT DISTINCT (frameworkcode),995,"j",10,0,0,"items.stocknumber" from biblio_framework ;
3271                 });
3272                 #Previously, copynumber was used as stocknumber
3273                 $dbh->do(qq{
3274         UPDATE items set stocknumber=copynumber;
3275                 });
3276                 $dbh->do(qq{
3277         UPDATE items set copynumber=NULL;
3278                 });
3279         }
3280     print "Upgrade to $DBversion done (stocknumber field added)\n";
3281     SetVersion ($DBversion);
3282 }
3283
3284 $DBversion = "3.01.00.096";
3285 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3286     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OrderPdfTemplate','','Uploads a PDF template to use for printing baskets','NULL','Upload')");
3287     $dbh->do("UPDATE systempreferences SET variable='OrderPdfFormat' WHERE variable='pdfformat'");
3288     print "Upgrade to $DBversion done (PDF orders system preferences added and updated)\n";
3289     SetVersion ($DBversion);
3290 }
3291
3292 $DBversion = "3.01.00.097";
3293 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3294         $dbh->do(qq{
3295         ALTER TABLE aqbasketgroups ADD billingplace VARCHAR(10) NOT NULL AFTER deliverycomment;
3296         });
3297
3298     print "Upgrade to $DBversion done (Adding billingplace to aqbasketgroups)\n";
3299     SetVersion ($DBversion);
3300 }
3301
3302 $DBversion = "3.01.00.098";
3303 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3304         $dbh->do(qq{
3305         ALTER TABLE auth_subfield_structure MODIFY frameworkcode VARCHAR(10) NULL;
3306         });
3307
3308     print "Upgrade to $DBversion done (changing frameworkcode length in auth_subfield_structure)\n";
3309     SetVersion ($DBversion);
3310 }
3311
3312 $DBversion = "3.01.00.099";
3313 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3314         $dbh->do(qq{
3315                 INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3316                 (9, 'edit_catalogue', 'Edit catalogue'),
3317                 (9, 'fast_cataloging', 'Fast cataloging')
3318         });
3319
3320     print "Upgrade to $DBversion done (granular permissions for cataloging added)\n";
3321     SetVersion ($DBversion);
3322 }
3323
3324 $DBversion = "3.01.00.100";
3325 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3326         $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')");
3327         print "Upgrade to $DBversion done (added CAS authentication system preferences)\n";
3328     SetVersion ($DBversion);
3329 }
3330
3331 $DBversion = "3.01.00.101";
3332 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3333         $dbh->do(
3334         "INSERT INTO systempreferences
3335            (variable, value, options, explanation, type)
3336          VALUES (
3337             'OverdueNoticeBcc', '', '',
3338             'Email address to Bcc outgoing notices sent by email',
3339             'free')
3340          ");
3341         print "Upgrade to $DBversion done (added OverdueNoticeBcc system preferences)\n";
3342     SetVersion ($DBversion);
3343 }
3344 $DBversion = "3.01.00.102";
3345 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3346     $dbh->do(
3347     "UPDATE permissions set description = 'Edit catalog (Modify bibliographic/holdings data)' where module_bit = 9 and code = 'edit_catalogue'"
3348     );
3349         print "Upgrade to $DBversion done (fixed spelling error in edit_catalogue permission)\n";
3350     SetVersion ($DBversion);
3351 }
3352
3353 $DBversion = "3.01.00.103";
3354 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3355         $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES (13, 'moderate_tags', 'Moderate patron tags')");
3356         print "Upgrade to $DBversion done (adding patron permissions for tags tool)\n";
3357     SetVersion ($DBversion);
3358 }
3359
3360 $DBversion = "3.01.00.104";
3361 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3362
3363     my ($maninv_count, $borrnotes_count);
3364     eval { $maninv_count = $dbh->do("SELECT 1 FROM authorised_values WHERE category='MANUAL_INV'"); };
3365     if ($maninv_count == 0) {
3366         $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('MANUAL_INV','Copier Fees','.25')");
3367     }
3368     eval { $borrnotes_count = $dbh->do("SELECT 1 FROM authorised_values WHERE category='BOR_NOTES'"); };
3369     if ($borrnotes_count == 0) {
3370         $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('BOR_NOTES','ADDR','Address Notes')");
3371     }
3372
3373     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('LOC','CART','Book Cart')");
3374     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('LOC','PROC','Processing Center')");
3375
3376         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";
3377         SetVersion ($DBversion);
3378 }
3379
3380
3381 $DBversion = "3.01.00.105";
3382 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3383     $dbh->do("
3384       CREATE TABLE `collections` (
3385         `colId` int(11) NOT NULL auto_increment,
3386         `colTitle` varchar(100) NOT NULL default '',
3387         `colDesc` text NOT NULL,
3388         `colBranchcode` varchar(4) default NULL COMMENT 'branchcode for branch where item should be held.',
3389         PRIMARY KEY  (`colId`)
3390       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3391     ");
3392
3393     $dbh->do("
3394       CREATE TABLE `collections_tracking` (
3395         `ctId` int(11) NOT NULL auto_increment,
3396         `colId` int(11) NOT NULL default '0' COMMENT 'collections.colId',
3397         `itemnumber` int(11) NOT NULL default '0' COMMENT 'items.itemnumber',
3398         PRIMARY KEY  (`ctId`)
3399       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3400     ");
3401     $dbh->do("
3402         INSERT INTO permissions (module_bit, code, description)
3403         VALUES ( 13, 'rotating_collections', 'Manage Rotating collections')" );
3404         print "Upgrade to $DBversion done (added collection and collection_tracking tables for rotating collections functionality)\n";
3405     SetVersion ($DBversion);
3406 }
3407 $DBversion = "3.01.00.106";
3408 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3409         $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' )");
3410         print "Upgrade to $DBversion done (added OpacAddMastheadLibraryPulldown system preferences)\n";
3411     SetVersion ($DBversion);
3412 }
3413
3414 $DBversion = '3.01.00.107';
3415 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3416     my $upgrade_script = C4::Context->config("intranetdir") . "/installer/data/mysql/patroncards_upgrade.pl";
3417     system("perl $upgrade_script");
3418     print "Upgrade to $DBversion done (Migrated labels and patroncards tables and data to new schema.)\n";
3419     SetVersion ($DBversion);
3420 }
3421
3422 $DBversion = '3.01.00.108';
3423 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3424         $dbh->do(qq{
3425     ALTER TABLE `export_format` ADD `csv_separator` VARCHAR( 2 ) NOT NULL AFTER `marcfields` ,
3426     ADD `field_separator` VARCHAR( 2 ) NOT NULL AFTER `csv_separator` ,
3427     ADD `subfield_separator` VARCHAR( 2 ) NOT NULL AFTER `field_separator`
3428     });
3429         print "Upgrade to $DBversion done (added separators for csv export)\n";
3430     SetVersion ($DBversion);
3431 }
3432
3433 $DBversion = "3.01.00.109";
3434 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3435         $dbh->do(qq{
3436         ALTER TABLE `export_format` ADD `encoding` VARCHAR(255) NOT NULL AFTER `subfield_separator`
3437         });
3438         print "Upgrade to $DBversion done (added encoding for csv export)\n";
3439     SetVersion ($DBversion);
3440 }
3441
3442 $DBversion = '3.01.00.110';
3443 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3444     $dbh->do('ALTER TABLE `categories` ADD COLUMN `enrolmentperioddate` DATE NULL DEFAULT NULL AFTER `enrolmentperiod`');
3445     print "Upgrade to $DBversion done (Add enrolment period date support)\n";
3446     SetVersion ($DBversion);
3447 }
3448
3449 $DBversion = '3.01.00.111';
3450 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3451     print "Upgrade to $DBversion done (mark DBrev for 3.2-alpha release)\n";
3452     SetVersion ($DBversion);
3453 }
3454
3455 $DBversion = '3.01.00.112';
3456 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3457         $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');");
3458         print "Upgrade to $DBversion done ( added Show Spine Label Printer on Bib Items Details preferences )\n";
3459     SetVersion ($DBversion);
3460 }
3461
3462 $DBversion = '3.01.00.113';
3463 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3464     my $value = C4::Context->preference("XSLTResultsDisplay");
3465     $dbh->do(
3466         "INSERT INTO systempreferences (variable,value,type)
3467          VALUES('OPACXSLTResultsDisplay',?,'YesNo')", {}, $value ? 1 : 0);
3468     $value = C4::Context->preference("XSLTDetailsDisplay");
3469     $dbh->do(
3470         "INSERT INTO systempreferences (variable,value,type)
3471          VALUES('OPACXSLTDetailsDisplay',?,'YesNo')", {}, $value ? 1 : 0);
3472     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";
3473     SetVersion ($DBversion);
3474 }
3475
3476 $DBversion = '3.01.00.114';
3477 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3478     $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')");
3479     $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')");
3480     $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')");
3481         print "Upgrade to $DBversion done ( Added AutoSelfCheckAllowed, AutoSelfCheckID, and AutoShelfCheckPass system preference )\n";
3482     SetVersion ($DBversion);
3483 }
3484
3485 $DBversion = '3.01.00.115';
3486 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3487     $dbh->do('UPDATE aqorders SET quantityreceived = 0 WHERE quantityreceived IS NULL');
3488     $dbh->do('ALTER TABLE aqorders MODIFY COLUMN quantityreceived smallint(6) NOT NULL DEFAULT 0');
3489         print "Upgrade to $DBversion done ( Default aqorders.quantityreceived to 0 )\n";
3490     SetVersion ($DBversion);
3491 }
3492
3493 $DBversion = '3.01.00.116';
3494 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3495         if (C4::Context->preference('OrderPdfFormat') eq 'pdfformat::example'){
3496                 $dbh->do("UPDATE `systempreferences` set value='pdfformat::layout2pages' WHERE variable='OrderPdfFormat'");
3497         }
3498         print "Upgrade to $DBversion done (corrected default OrderPdfFormat value if still set wrong )\n";
3499     SetVersion ($DBversion);
3500 }
3501
3502 $DBversion = '3.01.00.117';
3503 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3504     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'por' WHERE rfc4646_subtag='pt' ");
3505     print "Upgrade to $DBversion done (corrected ISO 639-2 language code for Portuguese)\n";
3506     SetVersion ($DBversion);
3507 }
3508
3509 $DBversion = '3.01.00.118';
3510 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3511     my ($count) = $dbh->selectrow_array("SELECT count(*) FROM information_schema.columns
3512                                          WHERE table_name = 'aqbudgets_planning'
3513                                          AND column_name = 'display'");
3514     if ($count < 1) {
3515         $dbh->do("ALTER TABLE aqbudgets_planning ADD COLUMN display tinyint(1) DEFAULT 1");
3516     }
3517     print "Upgrade to $DBversion done (bug 4203: add display column to aqbudgets_planning if missing)\n";
3518     SetVersion ($DBversion);
3519 }
3520
3521 $DBversion = '3.01.00.119';
3522 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3523     eval{require Locale::Currency::Format};
3524     if (!$@) {
3525         print "Upgrade to $DBversion done (Locale::Currency::Format installed.)\n";
3526         SetVersion ($DBversion);
3527     }
3528     else {
3529         print "Upgrade to $DBversion done.\n";
3530         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";
3531         SetVersion ($DBversion);
3532     }
3533 }
3534
3535 $DBversion = '3.01.00.120';
3536 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3537     $dbh->do(q{
3538 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');
3539 });
3540     print "Upgrade to $DBversion done (bug 1080: add soundon system preference for circulation sounds)\n";
3541     SetVersion ($DBversion);
3542 }
3543
3544 $DBversion = '3.01.00.121';
3545 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3546     $dbh->do("ALTER TABLE `reserves` ADD `expirationdate` DATE DEFAULT NULL");
3547     $dbh->do("ALTER TABLE `reserves` ADD `lowestPriority` tinyint(1) NOT NULL");
3548     $dbh->do("ALTER TABLE `old_reserves` ADD `expirationdate` DATE DEFAULT NULL");
3549     $dbh->do("ALTER TABLE `old_reserves` ADD `lowestPriority` tinyint(1) NOT NULL");
3550     print "Upgrade to $DBversion done ( Added Additional Fields to Reserves tables )\n";
3551     SetVersion ($DBversion);
3552 }
3553
3554 $DBversion = '3.01.00.122';
3555 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3556     $dbh->do(q{
3557       INSERT INTO systempreferences (variable,value,explanation,options,type)
3558       VALUES ('OAI-PMH:ConfFile', '', 'If empty, Koha OAI Server operates in normal mode, otherwise it operates in extended mode.','','File');
3559 });
3560     print "Upgrade to $DBversion done. — Add a new system preference OAI-PMF:ConfFile\n";
3561     SetVersion ($DBversion);
3562 }
3563
3564 $DBversion = "3.01.00.123";
3565 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3566     $dbh->do("INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3567         (6, 'place_holds', 'Place holds for patrons')");
3568     $dbh->do("INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3569         (6, 'modify_holds_priority', 'Modify holds priority')");
3570     $dbh->do("UPDATE `userflags` SET `flagdesc` = 'Place and modify holds for patrons' WHERE `flag` = 'reserveforothers'");
3571     print "Upgrade to $DBversion done (Add granular permission for holds modification and update description of reserveforothers permission)\n";
3572     SetVersion ($DBversion);
3573 }
3574
3575 $DBversion = '3.01.00.124';
3576 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3577     $dbh->do("
3578         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>>).');
3579     ");
3580     print "Upgrade to $DBversion done (bug 3242: add HOLDPLACED letter template, which is used when emailLibrarianWhenHoldIsPlaced is enabled)\n";
3581     SetVersion ($DBversion);
3582 }
3583
3584 $DBversion = '3.01.00.125';
3585 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3586     $dbh->do("
3587         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' );
3588     ");
3589     $dbh->do("
3590         INSERT INTO message_transport_types (message_transport_type) values ('print');
3591     ");
3592     print "Upgrade to $DBversion done (bug 3482: Printable hold and overdue notices)\n";
3593     SetVersion ($DBversion);
3594 }
3595
3596 $DBversion = "3.01.00.126";
3597 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3598         $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')");
3599         $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')");
3600
3601     print "Upgrade to $DBversion done (Adding ILS-DI updates and ILS-DI:AuthorizedIPs)\n";
3602     SetVersion ($DBversion);
3603 }
3604
3605 $DBversion = '3.01.00.127';
3606 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3607     $dbh->do("ALTER TABLE messages CHANGE branchcode branchcode varchar(10);");
3608     print "Upgrade to $DBversion done (bug 4190: messages in patron account did not work with branchcodes > 4)\n";
3609     SetVersion ($DBversion);
3610 }
3611
3612 $DBversion = '3.01.00.128';
3613 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3614     $dbh->do('CREATE INDEX budget_id ON aqorders (budget_id );');
3615     print "Upgrade to $DBversion done (bug 4331: index orders by budget_id)\n";
3616     SetVersion ($DBversion);
3617 }
3618
3619 $DBversion = "3.01.00.129";
3620 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3621         $dbh->do("UPDATE `permissions` SET `code` = 'items_batchdel' WHERE `permissions`.`module_bit` =13 AND `permissions`.`code` = 'batchdel' LIMIT 1 ;");
3622         $dbh->do("UPDATE `permissions` SET `code` = 'items_batchmod' WHERE `permissions`.`module_bit` =13 AND `permissions`.`code` = 'batchmod' LIMIT 1 ;");
3623         print "Upgrade to $DBversion done (Change permissions names for item batch modification / deletion)\n";
3624
3625     SetVersion ($DBversion);
3626 }
3627
3628 $DBversion = "3.01.00.130";
3629 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3630     $dbh->do("UPDATE reserves SET expirationdate = NULL WHERE expirationdate = '0000-00-00'");
3631     print "Upgrade to $DBversion done (change reserves.expirationdate values of 0000-00-00 to NULL (bug 1532)\n";
3632     SetVersion ($DBversion);
3633 }
3634
3635 $DBversion = "3.01.00.131";
3636 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3637         $dbh->do(q{
3638 INSERT IGNORE INTO message_transport_types (message_transport_type) VALUES ('print'),('feed');
3639     });
3640     print "Upgrade to $DBversion done (adding print and feed message transport types)\n";
3641     SetVersion ($DBversion);
3642 }
3643
3644 $DBversion = "3.01.00.132";
3645 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3646         $dbh->do(q{
3647     ALTER TABLE language_descriptions ADD INDEX subtag_type_lang (subtag, type, lang);
3648     });
3649     print "Upgrade to $DBversion done (Adding index to language_descriptions table)\n";
3650     SetVersion ($DBversion);
3651 }
3652
3653 $DBversion = '3.01.00.133';
3654 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3655     $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')");
3656     print "Upgrade to $DBversion done (bug 4405: added OverduesBlockCirc syspref to control whether circulation is blocked if a borrower has overdues)\n";
3657     SetVersion ($DBversion);
3658 }
3659
3660 $DBversion = '3.01.00.134';
3661 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3662     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('DisplayMultiPlaceHold','1','Display the ability to place multiple holds or not','','YesNo')");
3663     print "Upgrade to $DBversion done (adding syspref DisplayMultiPlaceHold to control whether multiple holds can be placed from the search results page)\n";
3664     SetVersion ($DBversion);
3665 }
3666
3667 $DBversion = '3.01.00.135';
3668 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3669     $dbh->do("
3670         INSERT INTO `letter` (module, code, name, title, content) VALUES
3671 ('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')
3672 ");
3673     print "Upgrade to $DBversion done (bug 4377: added HOLD_PRINT message template)\n";
3674     SetVersion ($DBversion);
3675 }
3676
3677 $DBversion = '3.01.00.136';
3678 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3679     $dbh->do(qq{
3680 INSERT INTO permissions (module_bit, code, description) VALUES
3681    ( 9, 'edit_items', 'Edit Items');});
3682     print "Upgrade to $DBversion done (Adding a new permission to edit items)\n";
3683     SetVersion ($DBversion);
3684 }
3685
3686 $DBversion = "3.01.00.137";
3687 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3688         $dbh->do("
3689           INSERT INTO permissions (module_bit, code, description) VALUES
3690           (15, 'check_expiration', 'Check the expiration of a serial'),
3691           (15, 'claim_serials', 'Claim missing serials'),
3692           (15, 'create_subscription', 'Create a new subscription'),
3693           (15, 'delete_subscription', 'Delete an existing subscription'),
3694           (15, 'edit_subscription', 'Edit an existing subscription'),
3695           (15, 'receive_serials', 'Serials receiving'),
3696           (15, 'renew_subscription', 'Renew a subscription'),
3697           (15, 'routing', 'Routing');
3698                  ");
3699     print "Upgrade to $DBversion done (adding granular permissions for serials)\n";
3700     SetVersion ($DBversion);
3701 }
3702
3703 $DBversion = "3.01.00.138";
3704 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3705     $dbh->do("DELETE FROM systempreferences WHERE variable = 'GranularPermissions'");
3706     print "Upgrade to $DBversion done (bug 4896: removing GranularPermissions syspref; use of granular permissions is now the default)\n";
3707     SetVersion ($DBversion);
3708 }
3709
3710 $DBversion = '3.01.00.139';
3711 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3712     $dbh->do("ALTER TABLE message_attributes CHANGE message_name message_name varchar(40);");
3713     print "Upgrade to $DBversion done (bug 3682: change message_name from varchar(20) to varchar(40))\n";
3714     SetVersion ($DBversion);
3715 }
3716
3717 $DBversion = '3.01.00.140';
3718 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3719     $dbh->do("UPDATE systempreferences SET value = '0' WHERE variable = 'TagsModeration' AND value is NULL");
3720     print "Upgrade to $DBversion done (bug 4312 TagsModeration changed from NULL to 0)\n";
3721     SetVersion ($DBversion);
3722 }
3723
3724 $DBversion = '3.01.00.141';
3725 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3726     $dbh->do(qq{DELETE FROM message_attributes WHERE message_attribute_id=3;});
3727     $dbh->do(qq{DELETE FROM letter WHERE code='EVENT' AND title='Upcoming Library Event';});
3728     print "Upgrade to $DBversion done Remove upcoming events messaging option (bug 2434)\n";
3729     SetVersion ($DBversion);
3730 }
3731
3732 $DBversion = '3.01.00.142';
3733 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3734     $dbh->do(qq{DELETE FROM message_transports WHERE message_attribute_id=3;});
3735     print "Upgrade to $DBversion done (Remove upcoming events messaging option part 2 (bug 2434))\n";
3736     SetVersion ($DBversion);
3737 }
3738
3739 $DBversion = '3.01.00.143';
3740 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3741     $dbh->do(qq{CREATE INDEX auth_value_idx ON authorised_values (authorised_value)});
3742     $dbh->do(qq{CREATE INDEX auth_val_cat_idx ON borrower_attribute_types (authorised_value_category)});
3743     print "Upgrade to $DBversion done (Create index on authorised_values and borrower_attribute_types (bug 4139))\n";
3744     SetVersion ($DBversion);
3745 }
3746
3747 $DBversion = '3.01.00.144';
3748 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3749     $dbh->do(qq{UPDATE systempreferences SET value='normal' where value='default' and variable='IntranetBiblioDefaultView'});
3750     print "Upgrade to $DBversion done (Update the 'default' to 'normal' for the IntranetBiblioDefaultView syspref (bug 5007))\n";
3751     SetVersion ($DBversion);
3752 }
3753
3754 $DBversion = "3.01.00.145";
3755 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3756     $dbh->do("ALTER TABLE borrowers ADD KEY `guarantorid` (guarantorid);");
3757     print "Upgrade to $DBversion done (Add index on guarantorid)\n";
3758     SetVersion ($DBversion);
3759 }
3760
3761 $DBversion = '3.01.00.999';
3762 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3763     print "Upgrade to $DBversion done (3.2.0 release candidate)\n";
3764     SetVersion ($DBversion);
3765 }
3766
3767 $DBversion = "3.02.00.000";
3768 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3769     my $value = $dbh->selectrow_array("SELECT value FROM systempreferences WHERE variable = 'HomeOrHoldingBranch'");
3770     $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');");
3771     print "Upgrade to $DBversion done (Add HomeOrHoldingBranchReturn system preference)\n";
3772     SetVersion ($DBversion);
3773 }
3774
3775 $DBversion = "3.02.00.001";
3776 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3777     $dbh->do(q{DELETE FROM systempreferences WHERE variable IN (
3778                 'holdCancelLength',
3779                 'PINESISBN',
3780                 'sortbynonfiling',
3781                 'TemplateEncoding',
3782                 'OPACSubscriptionDisplay',
3783                 'OPACDisplayExtendedSubInfo',
3784                 'OAI-PMH:Set',
3785                 'OAI-PMH:Subset',
3786                 'libraryAddress',
3787                 'kohaspsuggest',
3788                 'OrderPdfTemplate',
3789                 'marc',
3790                 'acquisitions',
3791                 'MIME')
3792                }
3793     );
3794     print "Upgrade to $DBversion done (bug 3756: remove disused system preferences)\n";
3795     SetVersion ($DBversion);
3796 }
3797
3798 $DBversion = "3.02.00.002";
3799 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3800     $dbh->do(q{DELETE FROM systempreferences WHERE variable = 'OpacPrivacy'});
3801     print "Upgrade to $DBversion done (bug 3881: remove unused OpacPrivacy system preference)\n";
3802     SetVersion ($DBversion);
3803 }
3804
3805 $DBversion = "3.02.00.003";
3806 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3807     $dbh->do(q{UPDATE systempreferences SET variable = 'ILS-DI:AuthorizedIPs' WHERE variable = 'ILS-DI:Authorized_IPs'});
3808     print "Upgrade to $DBversion done (correct ILS-DI:AuthorizedIPs)\n";
3809     SetVersion ($DBversion);
3810 }
3811
3812 $DBversion = "3.02.00.004";
3813 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3814     print "Upgrade to $DBversion done (3.2.0 general release)\n";
3815     SetVersion ($DBversion);
3816 }
3817 # This is the point where 3.2.x and master diverged, we can use $original_version to make sure we don't
3818
3819 # apply updates that have already been done
3820
3821 $DBversion = "3.03.00.001";
3822 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.005")) {
3823     $dbh->do("DELETE FROM subscriptionroutinglist WHERE borrowernumber IS NULL;");
3824     $dbh->do("ALTER TABLE subscriptionroutinglist MODIFY COLUMN `borrowernumber` int(11) NOT NULL;");
3825     $dbh->do("DELETE FROM subscriptionroutinglist WHERE subscriptionid IS NULL;");
3826     $dbh->do("ALTER TABLE subscriptionroutinglist MODIFY COLUMN `subscriptionid` int(11) NOT NULL;");
3827     $dbh->do("CREATE TEMPORARY TABLE del_subscriptionroutinglist
3828               SELECT s1.routingid FROM subscriptionroutinglist s1
3829               WHERE EXISTS (SELECT * FROM subscriptionroutinglist s2
3830                             WHERE s2.borrowernumber = s1.borrowernumber
3831                             AND   s2.subscriptionid = s1.subscriptionid
3832                             AND   s2.routingid < s1.routingid);");
3833     $dbh->do("DELETE FROM subscriptionroutinglist
3834               WHERE routingid IN (SELECT routingid FROM del_subscriptionroutinglist);");
3835     $dbh->do("ALTER TABLE subscriptionroutinglist ADD UNIQUE (subscriptionid, borrowernumber);");
3836     $dbh->do("ALTER TABLE subscriptionroutinglist
3837                 ADD CONSTRAINT `subscriptionroutinglist_ibfk_1` FOREIGN KEY (`borrowernumber`)
3838                 REFERENCES `borrowers` (`borrowernumber`)
3839                 ON DELETE CASCADE ON UPDATE CASCADE");
3840     $dbh->do("ALTER TABLE subscriptionroutinglist
3841                 ADD CONSTRAINT `subscriptionroutinglist_ibfk_2` FOREIGN KEY (`subscriptionid`)
3842                 REFERENCES `subscription` (`subscriptionid`)
3843                 ON DELETE CASCADE ON UPDATE CASCADE");
3844     print "Upgrade to $DBversion done (Make subscriptionroutinglist more strict)\n";
3845     SetVersion ($DBversion);
3846 }
3847
3848 $DBversion = '3.03.00.002';
3849 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.006")) {
3850     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='arm' WHERE rfc4646_subtag='hy';");
3851     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='eng' WHERE rfc4646_subtag='en';");
3852     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'fi','fin');");
3853     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='fre' WHERE rfc4646_subtag='fr';");
3854     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'lo','lao');");
3855     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='ita' WHERE rfc4646_subtag='it';");
3856     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'sr','srp');");
3857     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'tet','tet');");
3858     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'ur','urd');");
3859
3860     print "Upgrade to $DBversion done (Correct language mappings)\n";
3861     SetVersion ($DBversion);
3862 }
3863
3864 $DBversion = '3.03.00.003';
3865 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.007")) {
3866     $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');");
3867     print "Upgrade to $DBversion done (Add UseTablesortForCirc syspref)\n";
3868     SetVersion ($DBversion);
3869 }
3870
3871 $DBversion = '3.03.00.004';
3872 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.001")) {
3873     my $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'ACCEPTED');
3874     $dbh->do(q/
3875 INSERT INTO `letter`
3876 (module, code, name, title, content)
3877 VALUES
3878 ('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>>')
3879 /) unless $count > 0;
3880     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'AVAILABLE');
3881     $dbh->do(q/
3882 INSERT INTO `letter`
3883 (module, code, name, title, content)
3884 VALUES
3885 ('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>>')
3886 /) unless $count > 0;
3887     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'ORDERED');
3888     $dbh->do(q/
3889 INSERT INTO `letter`
3890 (module, code, name, title, content)
3891 VALUES
3892 ('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>>')
3893 /) unless $count > 0;
3894     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'REJECTED');
3895     $dbh->do(q/
3896 INSERT INTO `letter`
3897 (module, code, name, title, content)
3898 VALUES
3899 ('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>>')
3900 /) unless $count > 0;
3901     print "Upgrade to $DBversion done (bug 5127: add default templates for suggestion status change notifications)\n";
3902     SetVersion ($DBversion);
3903 };
3904
3905 $DBversion = '3.03.00.005';
3906 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3907     $dbh->do("update `systempreferences` set options='whitespace|T-prefix|cuecat|libsuite8' where variable='itemBarcodeInputFilter'");
3908     print "Upgrade to $DBversion done (Add itemBarcodeInputFilter choice libsuite8)\n";
3909 }
3910
3911 $DBversion = '3.03.00.006';
3912 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.002")) {
3913     $dbh->do("ALTER TABLE deletedborrowers ADD `privacy` int(11) AFTER smsalertnumber;");
3914     $dbh->do("ALTER TABLE deletedborrowers CHANGE `cardnumber` `cardnumber` varchar(16);");
3915     print "Upgrade to $DBversion done (Fix differences between borrowers and deletedborrowers)\n";
3916     SetVersion ($DBversion);
3917 }
3918
3919 $DBversion = '3.03.00.007';
3920 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3921     $dbh->do("ALTER table suggestions ADD quantity SMALLINT(6) default NULL,
3922                 ADD currency VARCHAR(3) default NULL,
3923                 ADD price DECIMAL(28,6) default NULL,
3924                 ADD total DECIMAL(28,6) default NULL;
3925                 ");
3926     print "Upgrade to $DBversion done (Added acq related columns to suggestions)\n";
3927     SetVersion ($DBversion);
3928 }
3929
3930 $DBversion = '3.03.00.008';
3931 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3932     $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')");
3933     print "Upgrade to $DBversion done (adding syspref OPACNoResultsFound to control what displays when no results are found for a search in the OPAC.)\n";
3934     SetVersion ($DBversion);
3935 }
3936
3937 $DBversion = '3.03.00.009';
3938 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.003")) {
3939     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('IntranetUserCSS','','Add CSS to be included in the Intranet',NULL,'free')");
3940     print "Upgrade to $DBversion done (Add IntranetUserCSS syspref)\n";
3941     SetVersion ($DBversion);
3942 }
3943
3944 $DBversion = "3.03.00.010";
3945 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.02.001")) {
3946     $dbh->do("UPDATE `marc_subfield_structure` SET liblibrarian = 'Distance from earth' WHERE liblibrarian = 'Distrance from earth' AND tagfield = '034' AND tagsubfield = 'r';");
3947     $dbh->do("UPDATE `marc_subfield_structure` SET libopac = 'Distance from earth' WHERE libopac = 'Distrance from earth' AND tagfield = '034' AND tagsubfield = 'r';");
3948     print "Upgrade to $DBversion done (Fix misspelled 034r subfield in MARC21 Frameworks)\n";
3949     SetVersion ($DBversion);
3950 }
3951
3952 $DBversion = "3.03.00.011";
3953 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3954     $dbh->do("UPDATE aqbooksellers SET gstrate=NULL WHERE gstrate=0.0");
3955     print "Upgrade to $DBversion done (Bug 5186: allow GST rate to be set to 0)\n";
3956     SetVersion ($DBversion);
3957 }
3958
3959 $DBversion = "3.03.00.012";
3960 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3961    $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')");
3962    print "Upgrade to $DBversion done (Bug 2142: maxItemsInSearchResults syspref resurrected)\n";
3963    SetVersion ($DBversion);
3964 }
3965
3966 $DBversion = "3.03.00.013";
3967 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3968     $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')");
3969     print "Upgrade to $DBversion done (added 'OpacPublic' syspref)\n";
3970    SetVersion ($DBversion);
3971 }
3972
3973 $DBversion = "3.03.00.014";
3974 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3975     $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')");
3976     $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')");
3977     $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')");
3978     print "Upgrade to $DBversion done (Add flexible shelf browser constraints)\n";
3979     SetVersion ($DBversion);
3980 }
3981
3982 $DBversion = "3.03.00.015";
3983 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3984     if ( C4::Context->preference("marcflavour") eq "MARC21" ) {
3985         my $sth = $dbh->prepare(
3986 "INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`,
3987                              `tab`, `authorised_value`, `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`)
3988                              VALUES ( ?, '9', '9 (RLIN)', '9 (RLIN)', 0, 0, '', 6, '', '', '', 0, -5, '', '', '', NULL)"
3989         );
3990         $sth->execute('648');
3991         $sth->execute('654');
3992         $sth->execute('655');
3993         $sth->execute('656');
3994         $sth->execute('657');
3995         $sth->execute('658');
3996         $sth->execute('662');
3997         $sth->finish;
3998         print
3999 "Upgrade to $DBversion done (Bug 5619: Add subfield 9 to marc21 648,654,655,656,657,658,662)\n";
4000     }
4001     SetVersion($DBversion);
4002 }
4003
4004 $DBversion = '3.03.00.016';
4005 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4006     # reimplement OpacPrivacy system preference
4007     $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')");
4008     $dbh->do("ALTER TABLE `borrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
4009     $dbh->do("ALTER TABLE `deletedborrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
4010     print "Upgrade to $DBversion done (OpacPrivacy reimplementation)\n";
4011     SetVersion($DBversion);
4012 };
4013
4014 $DBversion = '3.03.00.017';
4015 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.001")) {
4016     $dbh->do("ALTER TABLE  `currency` CHANGE `rate` `rate` FLOAT( 15, 5 ) NULL DEFAULT NULL;");
4017     print "Upgrade to $DBversion done (Enable currency rates >= 100)\n";
4018     SetVersion ($DBversion);
4019 }
4020
4021 $DBversion = '3.03.00.018';
4022 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.002")) {
4023     $dbh->do( q|update language_descriptions set description = 'Nederlands' where lang = 'nl' and subtag = 'nl'|);
4024     $dbh->do( q|update language_descriptions set description = 'Dansk' where lang = 'da' and subtag = 'da'|);
4025     print "Upgrade to $DBversion done (Correct language descriptions)\n";
4026     SetVersion ($DBversion);
4027 }
4028
4029 $DBversion = '3.03.00.019';
4030 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.003")) {
4031     # Fix bokmål
4032     $dbh->do("UPDATE language_subtag_registry SET description = 'Norwegian bokm&#229;l' WHERE subtag = 'nb';");
4033     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'nb','nob');");
4034     $dbh->do("UPDATE language_descriptions SET description = 'Norsk bokm&#229;l' WHERE subtag = 'nb' AND lang = 'nb';");
4035     $dbh->do("UPDATE language_descriptions SET description = 'Norwegian bokm&#229;l' WHERE subtag = 'nb' AND lang = 'en';");
4036     $dbh->do("UPDATE language_descriptions SET description = 'Norvégien bokm&#229;l' WHERE subtag = 'nb' AND lang = 'fr';");
4037     # Add nynorsk
4038     $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'nn', 'language', 'Norwegian nynorsk','2011-02-14' )");
4039     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'nn','nno')");
4040     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'nb', 'Norsk nynorsk')");
4041     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'nn', 'Norsk nynorsk')");
4042     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'en', 'Norwegian nynorsk')");
4043     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'fr', 'Norvégien nynorsk')");
4044     print "Upgrade to $DBversion done (Correct language descriptions for Norwegian)\n";
4045     SetVersion ($DBversion);
4046 }
4047
4048 $DBversion = '3.03.00.020';
4049 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4050     $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')");
4051     $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')");
4052     print "Upgrade to $DBversion done (Bug 5811: Add sysprefs controlling overriding fines)\n";
4053     SetVersion($DBversion);
4054 };
4055
4056 $DBversion = '3.03.00.021';
4057 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.001")) {
4058     $dbh->do("ALTER TABLE items MODIFY enumchron TEXT");
4059     $dbh->do("ALTER TABLE deleteditems MODIFY enumchron TEXT");
4060     print "Upgrade to $DBversion done (bug 5642: longer serial enumeration)\n";
4061     SetVersion ($DBversion);
4062 }
4063
4064 $DBversion = '3.03.00.022';
4065 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4066     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('AuthoritiesLog','0','If ON, log edit/create/delete actions on authorities.','','YesNo');");
4067     print "Upgrade to $DBversion done (Add AuthoritiesLog syspref)\n";
4068     SetVersion ($DBversion);
4069 }
4070
4071 # due to a mismatch in kohastructure.sql some koha will have missing columns in aqbasketgroup
4072 # this attempts to fix that
4073 $DBversion = '3.03.00.023';
4074 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.002")) {
4075     my $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'billingplace'");
4076     $sth->execute;
4077     $dbh->do("ALTER TABLE aqbasketgroups ADD billingplace VARCHAR(10)") if ! $sth->fetchrow_hashref;
4078     $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'deliveryplace'");
4079     $sth->execute;
4080     $dbh->do("ALTER TABLE aqbasketgroups ADD deliveryplace VARCHAR(10)") if ! $sth->fetchrow_hashref;
4081     $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'deliverycomment'");
4082     $sth->execute;
4083     $dbh->do("ALTER TABLE aqbasketgroups ADD deliverycomment VARCHAR(255)") if ! $sth->fetchrow_hashref;
4084     print "Upgrade to $DBversion done (Reconcile aqbasketgroups)\n";
4085     SetVersion ($DBversion);
4086 }
4087
4088 $DBversion = '3.03.00.024';
4089 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4090     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('TraceCompleteSubfields','0','Force subject tracings to only match complete subfields.','0','YesNo')");
4091     $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')");
4092     print "Upgrade to $DBversion done (Add syspref to force whole-subfield matching on subject tracings)\n";
4093     SetVersion($DBversion);
4094 };
4095
4096 $DBversion = "3.03.00.025";
4097 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4098     $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')");
4099     print "Upgrade to $DBversion done (Add syspref to control if user can choose pickup branch for holds)\n";
4100     SetVersion ($DBversion);
4101 }
4102
4103 $DBversion = '3.03.00.026';
4104 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.003")) {
4105     $dbh->do("UPDATE `message_attributes` SET message_name='Item Due' WHERE message_attribute_id=1 AND message_name LIKE 'Item DUE'");
4106         print "Upgrade to $DBversion done ( fix capitalization in message type )\n";
4107     SetVersion ($DBversion);
4108 }
4109
4110 $DBversion = '3.03.00.027';
4111 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4112     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('displayFacetCount', '0', NULL, NULL, 'YesNo')");
4113     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('maxRecordsForFacets', '20', NULL, NULL, 'Integer')");
4114     print "Upgrade to $DBversion done (Preferences for facet count)\n";
4115     SetVersion ($DBversion);
4116 }
4117
4118 $DBversion = "3.03.00.028";
4119 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4120     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('FacetLabelTruncationLength', 20, 'Truncate facets length to','','free')");
4121     print "Upgrade to $DBversion done (Add FacetLabelTruncationLength syspref to control facets displayed length)\n";
4122     SetVersion ($DBversion);
4123 }
4124
4125 $DBversion = "3.03.00.029";
4126 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4127     $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')");
4128     print "Upgrade to $DBversion done (Add syspref to control if user can choose branch when making purchase suggestion)\n";
4129     SetVersion ($DBversion);
4130 }
4131
4132 $DBversion = "3.03.00.030";
4133 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4134     $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')");
4135     $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')");
4136     print "Upgrade to $DBversion done (Add sysprefs to control custom favicons)\n";
4137     SetVersion ($DBversion);
4138 }
4139
4140 $DBversion = "3.03.00.031";
4141 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4142     $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');");
4143     print "Upgrade to $DBversion done (Add syspref FineNotifyAtCheckin)\n";
4144     SetVersion ($DBversion);
4145 }
4146
4147 $DBversion = '3.03.00.032';
4148 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4149     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('TraceSubjectSubdivisions', 1, 'Create searches on all subdivisions for subject tracings.','1','YesNo')");
4150     print "Upgrade to $DBversion done ( include subdivisions when generating subject tracing searches )\n";
4151 }
4152
4153
4154 $DBversion = '3.03.00.033';
4155 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4156     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('StaffAuthorisedValueImages', '1', '', NULL, 'YesNo')");
4157     print "Upgrade to $DBversion done (System pref StaffAuthorisedValueImages)\n";
4158     SetVersion ($DBversion);
4159 }
4160
4161 $DBversion = '3.03.00.034';
4162 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4163     $dbh->do("ALTER TABLE `categories` ADD `hidelostitems` tinyint(1) NOT NULL default '0' AFTER `reservefee`");
4164     print "Upgrade to $DBversion done (Add hidelostitems preference to borrower categories)\n";
4165     SetVersion ($DBversion);
4166 }
4167
4168 $DBversion = '3.03.00.035';
4169 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4170     $dbh->do("ALTER TABLE `issuingrules` ADD hardduedate date default NULL AFTER issuelength");
4171     $dbh->do("ALTER TABLE `issuingrules` ADD hardduedatecompare tinyint NOT NULL default 0 AFTER hardduedate");
4172     my $duedate;
4173     if (C4::Context->preference("globalDueDate")) {
4174       $duedate = C4::Dates::format_date_in_iso(C4::Context->preference("globalDueDate"));
4175       $dbh->do("UPDATE `issuingrules` SET hardduedate = '$duedate', hardduedatecompare = 0");
4176     } elsif (C4::Context->preference("ceilingDueDate")) {
4177       $duedate = C4::Dates::format_date_in_iso(C4::Context->preference("ceilingDueDate"));
4178       $dbh->do("UPDATE `issuingrules` SET hardduedate = '$duedate', hardduedatecompare = -1");
4179     }
4180     $dbh->do("DELETE FROM `systempreferences` WHERE variable = 'globalDueDate' OR variable = 'ceilingDueDate'");
4181     print "Upgrade to $DBversion done (Move global and ceiling due dates to Circ Rules level)\n";
4182     SetVersion ($DBversion);
4183 }
4184
4185 $DBversion = '3.03.00.036';
4186 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4187     $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')");
4188     print "Upgrade to $DBversion done ( Make COinS optional in OPAC search results )\n";
4189     SetVersion ($DBversion);
4190 }
4191
4192 $DBversion = '3.03.00.037';
4193 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4194     $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')");
4195     $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')");
4196     print "Upgrade to $DBversion done (Add 'Display856uAsImage' and 'OPACDisplay856uAsImage' syspref)\n";
4197     SetVersion ($DBversion);
4198 }
4199
4200 $DBversion = '3.03.00.038';
4201 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4202     $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')");
4203     $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')");
4204     $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')");
4205     print "Upgrade to $DBversion done ( Add Self-checkout by Login system preferences )\n";
4206 }
4207
4208 $DBversion = "3.03.00.039";
4209 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4210     $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');");
4211     print "Upgrade to $DBversion done (Add syspref ShowReviewer)\n";
4212 }
4213
4214 $DBversion = "3.03.00.040";
4215 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4216     $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');");
4217     print "Upgrade to $DBversion done (Add syspref UseControlNumber)\n";
4218 }
4219
4220 $DBversion = "3.03.00.041";
4221 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4222     $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')");
4223     $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')");
4224     print "Upgrade to $DBversion done (Add sysprefs to control alternate holdings information display)\n";
4225     SetVersion ($DBversion);
4226 }
4227
4228 $DBversion = '3.03.00.042';
4229 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4230     stocknumber_checker();
4231     print "Upgrade to $DBversion done (5860 Index itemstocknumber)\n";
4232     SetVersion ($DBversion);
4233 }
4234
4235 sub stocknumber_checker { #code reused later on
4236   my @row;
4237   #drop the obsolete itemSStocknumber idx if it exists
4238   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemsstocknumberidx'");
4239   $dbh->do("ALTER TABLE `items` DROP INDEX `itemsstocknumberidx`;") if @row;
4240
4241   #check itemstocknumber idx; remove it if it is unique
4242   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemstocknumberidx' AND non_unique=0");
4243   $dbh->do("ALTER TABLE `items` DROP INDEX `itemstocknumberidx`;") if @row;
4244
4245   #add itemstocknumber index non-unique IF it still not exists
4246   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemstocknumberidx'");
4247   $dbh->do("ALTER TABLE items ADD INDEX itemstocknumberidx (stocknumber);") unless @row;
4248 }
4249
4250 $DBversion = "3.03.00.043";
4251 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4252
4253     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib,lib_opac) VALUES ('YES_NO','0','No','No')");
4254     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib,lib_opac) VALUES ('YES_NO','1','Yes','Yes')");
4255
4256         print "Upgrade to $DBversion done ( add generic boolean YES_NO authorised_values pair )\n";
4257         SetVersion ($DBversion);
4258 }
4259
4260 $DBversion = '3.03.00.044';
4261 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4262     $dbh->do("ALTER TABLE `aqbasketgroups` ADD `freedeliveryplace` TEXT NULL AFTER `deliveryplace`;");
4263     print "Upgrade to $DBversion done (adding freedeliveryplace to basketgroups)\n";
4264 }
4265
4266 $DBversion = '3.03.00.045';
4267 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4268     #Remove obsolete columns from aqbooksellers if needed
4269     my $a = $dbh->selectall_hashref('SHOW columns from aqbooksellers','Field');
4270     my $sqldrop="ALTER TABLE aqbooksellers DROP COLUMN ";
4271     foreach(qw/deliverydays followupdays followupscancel invoicedisc nocalc specialty/) {
4272       $dbh->do($sqldrop.$_) if exists $a->{$_};
4273     }
4274     #Remove obsolete column from aqbudgets if needed
4275     #The correct column is budget_notes
4276     $a = $dbh->selectall_hashref('SHOW columns from aqbudgets','Field');
4277     if(exists $a->{budget_description}) {
4278       $dbh->do("ALTER TABLE aqbudgets DROP COLUMN budget_description");
4279     }
4280     print "Upgrade to $DBversion done (Remove obsolete columns from aqbooksellers and aqbudgets if needed)\n";
4281     SetVersion ($DBversion);
4282 }
4283
4284 $DBversion = "3.03.00.046";
4285 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4286     $dbh->do("ALTER TABLE overduerules ALTER delay1 SET DEFAULT NULL, ALTER delay2 SET DEFAULT NULL, ALTER delay3 SET DEFAULT NULL");
4287     print "Upgrade to $DBversion done (Setting NULL default value for delayn columns in table overduerules)\n";
4288     SetVersion($DBversion);
4289 }
4290
4291 $DBversion = '3.03.00.047';
4292 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4293     $dbh->do("ALTER TABLE borrowers ADD `state` mediumtext AFTER city;");
4294     $dbh->do("ALTER TABLE borrowers ADD `B_state` mediumtext AFTER B_city;");
4295     $dbh->do("ALTER TABLE borrowers ADD `altcontactstate` mediumtext AFTER altcontactaddress3;");
4296     $dbh->do("ALTER TABLE deletedborrowers ADD `state` mediumtext AFTER city;");
4297     $dbh->do("ALTER TABLE deletedborrowers ADD `B_state` mediumtext AFTER B_city;");
4298     $dbh->do("ALTER TABLE deletedborrowers ADD `altcontactstate` mediumtext AFTER altcontactaddress3;");
4299     print "Upgrade to $DBversion done (Add state field to patron's addresses)\n";
4300 }
4301
4302 $DBversion = '3.03.00.048';
4303 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4304     $dbh->do("ALTER TABLE branches ADD `branchstate` mediumtext AFTER `branchcity`;");
4305     print "Upgrade to $DBversion done (Add state to branch address)\n";
4306     SetVersion ($DBversion);
4307 }
4308
4309 $DBversion = '3.03.00.049';
4310 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4311     $dbh->do("ALTER TABLE `accountlines` ADD `note` text NULL default NULL");
4312     $dbh->do("ALTER TABLE `accountlines` ADD `manager_id` int( 11 ) NULL ");
4313     print "Upgrade to $DBversion done (adding note and manager_id fields in accountlines table)\n";
4314     SetVersion($DBversion);
4315 }
4316
4317 $DBversion = "3.03.00.050";
4318 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4319     $dbh->do("
4320         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');
4321         ");
4322     print "Upgrade to $DBversion done (Adding OpacHiddenItems syspref)\n";
4323     SetVersion($DBversion);
4324 }
4325
4326 $DBversion = "3.03.00.051";
4327 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4328     print "Upgrade to $DBversion done (Remove spaces and dashes from message_attribute names)\n";
4329     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Due' WHERE message_name='Item Due'");
4330     $dbh->do("UPDATE message_attributes SET message_name = 'Advance_Notice' WHERE message_name='Advance Notice'");
4331     $dbh->do("UPDATE message_attributes SET message_name = 'Hold_Filled' WHERE message_name='Hold Filled'");
4332     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Check_in' WHERE message_name='Item Check-in'");
4333     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Checkout' WHERE message_name='Item Checkout'");
4334     SetVersion ($DBversion);
4335 }
4336
4337 $DBversion = "3.03.00.052";
4338 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4339     $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');");
4340     print "Upgrade to $DBversion done (Add syspref WaitingNotifyAtCheckin)\n";
4341     SetVersion ($DBversion);
4342 }
4343
4344 $DBversion = "3.04.00.000";
4345 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4346     print "Upgrade to $DBversion done Koha 3.4.0 release \n";
4347     SetVersion ($DBversion);
4348 }
4349
4350 $DBversion = "3.05.00.001";
4351 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4352     $dbh->do(qq{
4353     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');
4354     });
4355     print "Upgrade to $DBversion done (Adds New System preference numSearchRSSResults)\n";
4356     SetVersion($DBversion);
4357 }
4358
4359 $DBversion = '3.05.00.002';
4360 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4361     #follow up fix 5860: some installs already past 3.3.0.42
4362     stocknumber_checker();
4363     print "Upgrade to $DBversion done (Fix for stocknumber index)\n";
4364     SetVersion ($DBversion);
4365 }
4366
4367 $DBversion = "3.05.00.003";
4368 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4369     $dbh->do(qq{
4370     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');
4371     });
4372     print "Upgrade to $DBversion done (Adds New System preference OpacRenewalBranch)\n";
4373     SetVersion($DBversion);
4374 }
4375
4376 $DBversion = "3.05.00.004";
4377 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4378     $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');");
4379     print "Upgrade to $DBversion done (Add syspref ShowReviewerPhoto)\n";
4380     SetVersion($DBversion);
4381 }
4382
4383 $DBversion = "3.05.00.005";
4384 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4385     $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');");
4386     print "Upgrade to $DBversion done (Adds pref BasketConfirmations)\n";
4387     SetVersion($DBversion);
4388 }
4389
4390 $DBversion = "3.05.00.006";
4391 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4392     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('MARCAuthorityControlField008', '|| aca||aabn           | a|a     d', NULL, NULL, 'Textarea')");
4393     print "Upgrade to $DBversion done (Add syspref MARCAuthorityControlField008)\n";
4394     SetVersion ($DBversion);
4395 }
4396
4397 $DBversion = "3.05.00.007";
4398 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4399     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpenLibraryCovers',0,'If ON Openlibrary book covers will be show',NULL,'YesNo');");
4400     print "Upgrade to $DBversion done (Add syspref OpenLibraryCovers)\n";
4401     SetVersion($DBversion);
4402 }
4403
4404 $DBversion = "3.05.00.008";
4405 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4406     $dbh->do("ALTER TABLE `cities` ADD `city_state` VARCHAR( 100 ) NULL DEFAULT NULL AFTER  `city_name`;");
4407     $dbh->do("ALTER TABLE `cities` ADD `city_country` VARCHAR( 100 ) NULL DEFAULT NULL AFTER  `city_zipcode`;");
4408     print "Add state and country to cities table corresponding to new columns in borrowers\n";
4409     SetVersion($DBversion);
4410 }
4411
4412 $DBversion = "3.05.00.009";
4413 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4414     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4415               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE borrowernumber IS NULL");
4416     $dbh->do("DELETE FROM issues WHERE borrowernumber IS NULL");
4417
4418     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4419               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE itemnumber IS NULL");
4420     $dbh->do("DELETE FROM issues WHERE itemnumber IS NULL");
4421
4422     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4423               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowernumber = issues.borrowernumber)");
4424     $dbh->do("DELETE FROM issues WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowernumber = issues.borrowernumber)");
4425
4426     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4427               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE NOT EXISTS (SELECT * FROM items WHERE itemnumber = issues.itemnumber)");
4428     $dbh->do("DELETE FROM issues WHERE NOT EXISTS (SELECT * FROM items WHERE itemnumber = issues.itemnumber)");
4429
4430     $dbh->do("ALTER TABLE issues DROP FOREIGN KEY `issues_ibfk_1`");
4431     $dbh->do("ALTER TABLE issues DROP FOREIGN KEY `issues_ibfk_2`");
4432     $dbh->do("ALTER TABLE issues ALTER COLUMN borrowernumber DROP DEFAULT");
4433     $dbh->do("ALTER TABLE issues ALTER COLUMN itemnumber DROP DEFAULT");
4434     $dbh->do("ALTER TABLE issues MODIFY COLUMN borrowernumber int(11) NOT NULL");
4435     $dbh->do("ALTER TABLE issues MODIFY COLUMN itemnumber int(11) NOT NULL");
4436     $dbh->do("ALTER TABLE issues DROP KEY `issuesitemidx`");
4437     $dbh->do("ALTER TABLE issues ADD PRIMARY KEY (`itemnumber`)");
4438     $dbh->do("ALTER TABLE issues ADD CONSTRAINT `issues_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE RESTRICT ON UPDATE CASCADE");
4439     $dbh->do("ALTER TABLE issues ADD CONSTRAINT `issues_ibfk_2` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE RESTRICT ON UPDATE CASCADE");
4440
4441     print "Upgrade to $DBversion done (issues referential integrity)\n";
4442     SetVersion ($DBversion);
4443 }
4444
4445 $DBversion = "3.05.00.010";
4446 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4447     $dbh->do("CREATE INDEX priorityfoundidx ON reserves (priority,found)");
4448     print "Create an index on reserves to speed up holds awaiting pickup report bug 5866\n";
4449     SetVersion($DBversion);
4450 }
4451
4452
4453 $DBversion = "3.05.00.011";
4454 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4455     $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')");
4456     print "Upgrade to $DBversion done (add OPACResultsSidebar syspref (enh 6165))\n";
4457     SetVersion($DBversion);
4458 }
4459
4460 $DBversion = "3.05.00.012";
4461 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4462     $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')");
4463     print "Upgrade to $DBversion done (add RecordLocalUseOnReturn syspref (enh 6403))\n";
4464     SetVersion($DBversion);
4465 }
4466
4467 $DBversion = "3.05.00.013";
4468 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4469     $dbh->do(qq|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OpacKohaUrl','0',"Show 'Powered by Koha' text on OPAC footer.",NULL,NULL)|);
4470     print "Upgrade to $DBversion done (Add syspref 'OpacKohaUrl')\n";
4471     SetVersion($DBversion);
4472 }
4473
4474 $DBversion = "3.05.00.014";
4475 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4476     $dbh->do("ALTER TABLE `borrowers` MODIFY `userid` VARCHAR(75)");
4477     print "Modified userid column length into 75 in borrowers\n";
4478     SetVersion($DBversion);
4479 }
4480
4481 $DBversion = "3.05.00.015";
4482 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4483     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectEnabled',0,'Enable Novelist Select content.  Requires Novelist Profile and Password',NULL,'YesNo')");
4484     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectProfile',NULL,'Novelist Select user Password',NULL,'free')");
4485     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectPassword',NULL,'Enable Novelist user Profile',NULL,'free')");
4486     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectView','tab','Where to display Novelist Select content','tab|above|below|right','Choice')");
4487     print "Upgrade to $DBversion done (Add support for EBSCO's NoveList Select (enh 6902))\n";
4488     SetVersion($DBversion);
4489 }
4490
4491 $DBversion = '3.05.00.016';
4492 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4493     $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');");
4494     print "Upgrade to $DBversion done (Add EasyAnalyticalRecords syspref)\n";
4495     SetVersion ($DBversion);
4496 }
4497
4498 $DBversion = '3.05.00.017';
4499 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4500     if (C4::Context->preference("marcflavour") eq 'MARC21' ||
4501         C4::Context->preference("marcflavour") eq 'NORMARC'){
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', '0', 'Host Biblionumber', 'Host Biblionumber', 0, 0, NULL, 7, NULL, NULL, '', NULL, -6, '', '', '', NULL)");
4503         $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)");
4504         print "Upgrade to $DBversion done (Add 773 subfield 9 and 0 to default framework)\n";
4505         SetVersion ($DBversion);
4506     } elsif (C4::Context->preference("marcflavour") eq 'UNIMARC'){
4507         $dbh->do("INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`, `tab`, `authorised_value` , `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`) VALUES ('461', '9', 'Host Itemnumber', 'Host Itemnumber', 0, 0, NULL, 7, NULL, NULL, '', NULL, -6, '', '', '', NULL)");
4508         print "Upgrade to $DBversion done (Add 461 subfield 9 to default framework)\n";
4509         SetVersion ($DBversion);
4510     }
4511 }
4512
4513 $DBversion = "3.05.00.018";
4514 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4515     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacNavBottom','','Links after OpacNav links','70|10','Textarea')");
4516     print "Upgrade to $DBversion done (add OpacNavBottom syspref (enh 6825): if appropriate, you can split OpacNav into OpacNav and OpacNavBottom)\n";
4517     SetVersion($DBversion);
4518 }
4519
4520 $DBversion = "3.05.00.019";
4521 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4522     $dbh->do("UPDATE itemtypes SET imageurl = 'vokal/Book.png' WHERE imageurl = 'vokal/BOOK.png'");
4523     $dbh->do("UPDATE itemtypes SET imageurl = 'vokal/Book-32px.png' WHERE imageurl = 'vokal/BOOK-32px.png'");
4524     $dbh->do("UPDATE authorised_values SET imageurl = 'vokal/Book.png' WHERE imageurl = 'vokal/BOOK.png'");
4525     $dbh->do("UPDATE authorised_values SET imageurl = 'vokal/Book-32px.png' WHERE imageurl = 'vokal/BOOK-32px.png'");
4526     print "Upgrade to $DBversion done (remove duplicate VOKAL Book icons, bug 6862)\n";
4527     SetVersion($DBversion);
4528 }
4529
4530 $DBversion = "3.05.00.020";
4531 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4532     $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')");
4533     print "Upgrade to $DBversion done (Add syspref AcqViewBaskets)\n";
4534     SetVersion($DBversion);
4535 }
4536
4537 $DBversion = "3.05.00.021";
4538 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4539     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN display_checkout TINYINT(1) NOT NULL DEFAULT '0';");
4540     print "Upgrade to $DBversion done (Added a display_checkout field in borrower_attribute_types table)\n";
4541     SetVersion($DBversion);
4542 }
4543
4544 $DBversion = "3.05.00.022";
4545 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4546     $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");
4547     print "Upgrade to $DBversion done (6094: Fixing ModAuthority problems, add a need_merge_authorities table)\n";
4548     SetVersion($DBversion);
4549 }
4550
4551 $DBversion = "3.05.00.023";
4552 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4553     $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');");
4554     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";
4555     SetVersion($DBversion);
4556 }
4557
4558 $DBversion = "3.06.00.000";
4559 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4560     print "Upgrade to $DBversion done Koha 3.6.0 release \n";
4561     SetVersion ($DBversion);
4562 }
4563
4564 $DBversion = "3.07.00.001";
4565 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4566     my $borrowers = $dbh->selectcol_arrayref( "SELECT borrowernumber from borrowers where debarred =1;", { Columns => [1] } );
4567     $dbh->do("ALTER TABLE borrowers MODIFY debarred DATE DEFAULT NULL;");
4568     $dbh->do( "UPDATE borrowers set debarred='9999-12-31' where borrowernumber IN (" . join( ",", @$borrowers ) . ");" ) if ($borrowers and scalar(@$borrowers)>0);
4569     $dbh->do("ALTER TABLE borrowers ADD COLUMN debarredcomment VARCHAR(255) DEFAULT NULL AFTER debarred;");
4570     $dbh->do("ALTER TABLE deletedborrowers MODIFY debarred DATE DEFAULT NULL;");
4571     $dbh->do("ALTER TABLE deletedborrowers ADD COLUMN debarredcomment VARCHAR(255) DEFAULT NULL AFTER debarred;");
4572     print "Upgrade done (Change borrowers.debarred into Date )\n";
4573     SetVersion($DBversion);
4574 }
4575
4576 $DBversion = "3.07.00.002";
4577 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4578     $dbh->do("UPDATE borrowers SET debarred=NULL WHERE debarred='0000-00-00';");
4579     print "Setting NULL to debarred where 0000-00-00 is stored (bug 7272)\n";
4580     SetVersion($DBversion);
4581 }
4582
4583 $DBversion = "3.07.00.003";
4584 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4585     $dbh->do(" UPDATE `message_attributes` SET message_name='Item_Due' WHERE message_name='Item_DUE'");
4586     print "Updating message_name in message_attributes\n";
4587     SetVersion($DBversion);
4588 }
4589
4590 $DBversion = "3.07.00.004";
4591 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4592     $dbh->do("ALTER TABLE  `suggestions` ADD  `patronreason` TEXT NULL AFTER  `reason`");
4593     print "Upgrade to $DBversion done (Add column to suggestions table to store patrons' reasons for submitting a suggestion. )\n";
4594     SetVersion($DBversion);
4595 }
4596
4597 $DBversion = "3.07.00.005";
4598 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4599     $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')");
4600     print "Upgrade to $DBversion done (BorrowerUnwantedField syspref)\n";
4601     SetVersion ($DBversion);
4602 }
4603
4604 $DBversion = "3.07.00.006";
4605 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4606     $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');");
4607     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";
4608     SetVersion($DBversion);
4609 }
4610
4611 $DBversion = "3.07.00.007";
4612 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4613     $dbh->do("ALTER TABLE items MODIFY materials text;");
4614     print "Upgrade to $DBversion done alter items.material from varchar(10) to text \n";
4615     SetVersion($DBversion);
4616 }
4617
4618 $DBversion = '3.07.00.008';
4619 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4620     if (C4::Context->preference("marcflavour") eq 'MARC21') {
4621         if (C4::Context->preference("opaclanguages") eq "de") {
4622             $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, '');");
4623         } else {
4624             $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, '');");
4625         }
4626     }
4627     print "Upgrade to $DBversion done (add MARC21 field 545 to framework)\n";
4628     SetVersion ($DBversion);
4629 }
4630
4631 $DBversion = "3.07.00.009";
4632 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4633     $dbh->do("ALTER TABLE `aqorders` ADD COLUMN `claims_count` INT(11)  DEFAULT 0, ADD COLUMN `claimed_date` DATE  DEFAULT NULL AFTER `claims_count`");
4634     print "Upgrade to $DBversion done (Add claims_count and claimed_date fields in aqorders table)\n";
4635     SetVersion($DBversion);
4636 }
4637
4638 $DBversion = "3.07.00.010";
4639 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4640     $dbh->do(
4641         q|CREATE TABLE `biblioimages` (
4642           `imagenumber` int(11) NOT NULL AUTO_INCREMENT,
4643           `biblionumber` int(11) NOT NULL,
4644           `mimetype` varchar(15) NOT NULL,
4645           `imagefile` mediumblob NOT NULL,
4646           `thumbnail` mediumblob NOT NULL,
4647           PRIMARY KEY (`imagenumber`),
4648           CONSTRAINT `bibliocoverimage_fk1` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
4649           ) ENGINE=InnoDB DEFAULT CHARSET=utf8|
4650     );
4651     $dbh->do(
4652         q|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OPACLocalCoverImages','0','Display local cover images on OPAC search and details pages.','1','YesNo')|
4653         );
4654     $dbh->do(
4655         q|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('LocalCoverImages','0','Display local cover images on intranet search and details pages.','1','YesNo')|
4656         );
4657     $dbh->do(
4658         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')|
4659     );
4660     $dbh->do(
4661         q|INSERT INTO permissions (module_bit, code, description) VALUES (13, 'upload_local_cover_images', 'Upload local cover images')|
4662     );
4663     print "Upgrade to $DBversion done (Added support for local cover images)\n";
4664     SetVersion($DBversion);
4665 }
4666
4667 $DBversion = "3.07.00.011";
4668 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4669     $dbh->do(<<ENDOFRENEWAL);
4670     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');
4671 ENDOFRENEWAL
4672     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";
4673     SetVersion($DBversion);
4674 }
4675
4676 $DBversion = "3.07.00.012";
4677 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4678     $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')");
4679     print "Upgrade to $DBversion add 'AllowItemsOnHoldCheckout' syspref \n";
4680     SetVersion ($DBversion);
4681 }
4682
4683 $DBversion = "3.07.00.013";
4684 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4685     $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');");
4686     print "Upgrade to $DBversion done (Bug 7345: Add system preference OpacExportOptions.)\n";
4687     SetVersion ($DBversion);
4688 }
4689
4690 $DBversion = "3.07.00.014";
4691 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4692     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";
4693     SetVersion($DBversion);
4694 }
4695
4696 $DBversion = "3.07.00.015";
4697 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4698     my $sth = $dbh->prepare(q|
4699         SELECT COUNT(*) FROM marc_subfield_structure where kohafield="biblioitems.editionstatement"
4700         |);
4701     $sth->execute;
4702     my $already_exists = $sth->fetchrow;
4703     if ( not $already_exists ) {
4704         my $field = C4::Context->preference("marcflavour") eq "UNIMARC" ? "205" : "250";
4705         my $subfield = "a";
4706         my $sth = $dbh->prepare( q|
4707             UPDATE marc_subfield_structure SET kohafield = "biblioitems.editionstatement"
4708             WHERE tagfield = ? AND tagsubfield = ?
4709         |);
4710         $sth->execute( $field, $subfield );
4711         print "Upgrade to $DBversion done (Added a mapping for biblioitems.editionstatement.)\n";
4712     } else {
4713         print "Upgrade to $DBversion done (Added a mapping for biblioitems.editionstatement (already exists, nothing to do).)\n";
4714     }
4715     SetVersion($DBversion);
4716 }
4717
4718 $DBversion = "3.07.00.016";
4719 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4720     $dbh->do("ALTER TABLE items ADD KEY `itemcallnumber` (itemcallnumber)");
4721     print "Upgrade to $DBversion done (Added index on items.itemcallnumber)\n";
4722     SetVersion($DBversion);
4723 }
4724
4725 $DBversion = "3.07.00.017";
4726 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4727     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('TransferWhenCancelAllWaitingHolds','0','Transfer items when cancelling all waiting holds',NULL,'YesNo')");
4728     print "Upgrade to $DBversion done (Add sysprefs to control transfer when cancel all waiting holds)\n";
4729     SetVersion ($DBversion);
4730 }
4731
4732 $DBversion = "3.07.00.018";
4733 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4734     $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;");
4735     print "Upgrade to $DBversion done ( adding offline operations table )\n";
4736     SetVersion($DBversion);
4737 }
4738
4739 $DBversion = "3.07.00.019";
4740 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4741     $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");
4742     $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");
4743     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";
4744     SetVersion($DBversion);
4745 }
4746
4747 $DBversion = "3.07.00.020";
4748 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4749     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OPACpatronimages',0,'Enable patron images in the OPAC',NULL,'YesNo');");
4750     print "Upgrade to $DBversion done (Bug 3516: Add the option to show patron images in the OPAC.)\n";
4751     SetVersion($DBversion);
4752 }
4753
4754 $DBversion = "3.07.00.021";
4755 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4756     $dbh->do(
4757     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('LinkerModule','Default','Chooses which linker module to use (see documentation).','Default|FirstMatchLastMatch','Choice');"
4758     );
4759     $dbh->do(
4760     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('LinkerOptions','','A pipe-separated list of options for the linker.','','free');"
4761     );
4762     $dbh->do(
4763     "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');"
4764     );
4765     $dbh->do(
4766     "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');"
4767     );
4768     $dbh->do(
4769     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AutoCreateAuthorities',0,'Automatically create authorities that do not exist when cataloging records.',NULL,'YesNo');"
4770     );
4771     $dbh->do(
4772     "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');"
4773     );
4774     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";
4775     SetVersion($DBversion);
4776 }
4777
4778 $DBversion = "3.07.00.022";
4779 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4780     $dbh->do("DELETE FROM reviews WHERE biblionumber NOT IN (SELECT biblionumber from biblio)");
4781     $dbh->do("UPDATE reviews SET borrowernumber = NULL WHERE borrowernumber NOT IN (SELECT borrowernumber FROM borrowers)");
4782     $dbh->do("ALTER TABLE reviews ADD CONSTRAINT reviews_ibfk_2 FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE");
4783     $dbh->do("ALTER TABLE reviews ADD CONSTRAINT reviews_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber ) ON UPDATE CASCADE ON DELETE SET NULL");
4784     print "Upgrade to $DBversion done (Bug 7493 - Add constraint linking OPAC comment biblionumber to biblio, OPAC comment borrowernumber to borrowers.)\n";
4785     SetVersion($DBversion);
4786 }
4787
4788 $DBversion = "3.07.00.023";
4789 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4790     $dbh->do("ALTER TABLE `message_transports` DROP FOREIGN KEY `message_transports_ibfk_3`");
4791     $dbh->do("ALTER TABLE `letter` DROP PRIMARY KEY");
4792     $dbh->do("ALTER TABLE `letter` ADD `branchcode` varchar(10) default NULL AFTER `code`");
4793     $dbh->do("ALTER TABLE `letter` ADD PRIMARY KEY  (`module`,`code`, `branchcode`)");
4794     $dbh->do("ALTER TABLE `message_transports` ADD `branchcode` varchar(10) NOT NULL default ''");
4795     $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");
4796     $dbh->do("ALTER TABLE `letter` ADD `is_html` tinyint(1) default 0 AFTER `name`");
4797
4798     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4799               VALUES ('circulation','ISSUESLIP','Issue Slip','Issue Slip', '<h3><<branches.branchname>></h3>
4800 Checked out to <<borrowers.title>> <<borrowers.firstname>> <<borrowers.initials>> <<borrowers.surname>> <br />
4801 (<<borrowers.cardnumber>>) <br />
4802
4803 <<today>><br />
4804
4805 <h4>Checked Out</h4>
4806 <checkedout>
4807 <p>
4808 <<biblio.title>> <br />
4809 Barcode: <<items.barcode>><br />
4810 Date due: <<issues.date_due>><br />
4811 </p>
4812 </checkedout>
4813
4814 <h4>Overdues</h4>
4815 <overdue>
4816 <p>
4817 <<biblio.title>> <br />
4818 Barcode: <<items.barcode>><br />
4819 Date due: <<issues.date_due>><br />
4820 </p>
4821 </overdue>
4822
4823 <hr>
4824
4825 <h4 style=\"text-align: center; font-style:italic;\">News</h4>
4826 <news>
4827 <div class=\"newsitem\">
4828 <h5 style=\"margin-bottom: 1px; margin-top: 1px\"><b><<opac_news.title>></b></h5>
4829 <p style=\"margin-bottom: 1px; margin-top: 1px\"><<opac_news.new>></p>
4830 <p class=\"newsfooter\" style=\"font-size: 8pt; font-style:italic; margin-bottom: 1px; margin-top: 1px\">Posted on <<opac_news.timestamp>></p>
4831 <hr />
4832 </div>
4833 </news>', 1)");
4834     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4835               VALUES ('circulation','ISSUEQSLIP','Issue Quick Slip','Issue Quick Slip', '<h3><<branches.branchname>></h3>
4836 Checked out to <<borrowers.title>> <<borrowers.firstname>> <<borrowers.initials>> <<borrowers.surname>> <br />
4837 (<<borrowers.cardnumber>>) <br />
4838
4839 <<today>><br />
4840
4841 <h4>Checked Out Today</h4>
4842 <checkedout>
4843 <p>
4844 <<biblio.title>> <br />
4845 Barcode: <<items.barcode>><br />
4846 Date due: <<issues.date_due>><br />
4847 </p>
4848 </checkedout>', 1)");
4849     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4850               VALUES ('circulation','RESERVESLIP','Reserve Slip','Reserve Slip', '<h5>Date: <<today>></h5>
4851
4852 <h3> Transfer to/Hold in <<branches.branchname>></h3>
4853
4854 <h3><<borrowers.surname>>, <<borrowers.firstname>></h3>
4855
4856 <ul>
4857     <li><<borrowers.cardnumber>></li>
4858     <li><<borrowers.phone>></li>
4859     <li> <<borrowers.address>><br />
4860          <<borrowers.address2>><br />
4861          <<borrowers.city >>  <<borrowers.zipcode>>
4862     </li>
4863     <li><<borrowers.email>></li>
4864 </ul>
4865 <br />
4866 <h3>ITEM ON HOLD</h3>
4867 <h4><<biblio.title>></h4>
4868 <h5><<biblio.author>></h5>
4869 <ul>
4870    <li><<items.barcode>></li>
4871    <li><<items.itemcallnumber>></li>
4872    <li><<reserves.waitingdate>></li>
4873 </ul>
4874 <p>Notes:
4875 <pre><<reserves.reservenotes>></pre>
4876 </p>', 1)");
4877     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4878               VALUES ('circulation','TRANSFERSLIP','Transfer Slip','Transfer Slip', '<h5>Date: <<today>></h5>
4879 <h3>Transfer to <<branches.branchname>></h3>
4880
4881 <h3>ITEM</h3>
4882 <h4><<biblio.title>></h4>
4883 <h5><<biblio.author>></h5>
4884 <ul>
4885    <li><<items.barcode>></li>
4886    <li><<items.itemcallnumber>></li>
4887 </ul>', 1)");
4888
4889     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('NoticeCSS','','Notices CSS url.',NULL,'free')");
4890     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('SlipCSS','','Slips CSS url.',NULL,'free')");
4891
4892     $dbh->do("UPDATE `letter` SET content = replace(content, '<<title>>', '<<biblio.title>>') WHERE code = 'HOLDPLACED'");
4893
4894     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";
4895     SetVersion($DBversion);
4896 }
4897
4898 $DBversion = "3.07.00.024";
4899 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4900     $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')");
4901     $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')");
4902     print "Upgrade to $DBversion done (Added system preference ExpireReservesMaxPickUpDelay, system preference ExpireReservesMaxPickUpDelayCharge, add reseves.charge_if_expired)\n";
4903 }
4904
4905 $DBversion = "3.07.00.025";
4906 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4907     if (TableExists('bibliocoverimage')) {
4908         $dbh->do( q|DROP TABLE bibliocoverimage;| );
4909         $dbh->do(
4910             q|CREATE TABLE biblioimages (
4911               imagenumber int(11) NOT NULL AUTO_INCREMENT,
4912               biblionumber int(11) NOT NULL,
4913               mimetype varchar(15) NOT NULL,
4914               imagefile mediumblob NOT NULL,
4915               thumbnail mediumblob NOT NULL,
4916               PRIMARY KEY (imagenumber),
4917               CONSTRAINT bibliocoverimage_fk1 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
4918               ) ENGINE=InnoDB DEFAULT CHARSET=utf8;|
4919         );
4920     }
4921     print "Upgrade to $DBversion done (Correct table name for local cover images if needed. )\n";
4922     SetVersion($DBversion);
4923 }
4924
4925 $DBversion = "3.07.00.026";
4926 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4927     $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');");
4928     print "Upgrade to $DBversion done (Add syspref CalendarFirstDayOfWeek used to select the first day of week to use in the calendar. )\n";
4929     SetVersion($DBversion);
4930 }
4931
4932 $DBversion = "3.07.00.027";
4933 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4934     $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');});
4935     print "Upgrade to $DBversion done (Added system preference RoutingListNote for adding a general note to all routing lists.)\n";
4936     SetVersion($DBversion);
4937 }
4938
4939 $DBversion = "3.07.00.028";
4940 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4941     $dbh->do(qq{
4942     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');
4943     });
4944     print "Upgrade to $DBversion done (Bug 6296 New System preference AllowPKIAuth)\n";
4945 }
4946
4947 $DBversion = "3.07.00.029";
4948 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4949     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_descriptions`;});
4950     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_mappings`;});
4951     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_biblios`;});
4952     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets`;});
4953
4954     $dbh->do(q{
4955         CREATE TABLE `oai_sets` (
4956           `id` int(11) NOT NULL auto_increment,
4957           `spec` varchar(80) NOT NULL UNIQUE,
4958           `name` varchar(80) NOT NULL,
4959           PRIMARY KEY (`id`)
4960         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4961     });
4962
4963     $dbh->do(q{
4964         CREATE TABLE `oai_sets_descriptions` (
4965           `set_id` int(11) NOT NULL,
4966           `description` varchar(255) NOT NULL,
4967           CONSTRAINT `oai_sets_descriptions_ibfk_1` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4968         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4969     });
4970
4971     $dbh->do(q{
4972         CREATE TABLE `oai_sets_mappings` (
4973           `set_id` int(11) NOT NULL,
4974           `marcfield` char(3) NOT NULL,
4975           `marcsubfield` char(1) NOT NULL,
4976           `marcvalue` varchar(80) NOT NULL,
4977           CONSTRAINT `oai_sets_mappings_ibfk_1` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4978         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4979     });
4980
4981     $dbh->do(q{
4982         CREATE TABLE `oai_sets_biblios` (
4983           `biblionumber` int(11) NOT NULL,
4984           `set_id` int(11) NOT NULL,
4985           PRIMARY KEY (`biblionumber`, `set_id`),
4986           CONSTRAINT `oai_sets_biblios_ibfk_1` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
4987           CONSTRAINT `oai_sets_biblios_ibfk_2` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4988         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4989     });
4990
4991     $dbh->do(q{
4992         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');
4993     });
4994
4995     print "Upgrade to $DBversion done (Atomic update for OAI-PMH sets management)\n";
4996     SetVersion($DBversion);
4997 }
4998
4999 $DBversion = "3.07.00.030";
5000 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5001     $dbh->do("ALTER TABLE default_circ_rules ADD
5002             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5003     $dbh->do("ALTER TABLE branch_item_rules ADD
5004             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5005     $dbh->do("ALTER TABLE default_branch_circ_rules ADD
5006             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5007     $dbh->do("ALTER TABLE default_branch_item_rules ADD
5008             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5009     # set the default rule to the current value of HomeOrHoldingBranchReturn (default to 'homebranch' if need be)
5010     my $homeorholdingbranchreturn = C4::Context->prefernce('HomeOrHoldingBranchReturn') || 'homebranch';
5011     $dbh->do("UPDATE default_circ_rules SET returnbranch = '$homeorholdingbranchreturn'");
5012     print "Upgrade to $DBversion done (Atomic update for OAI-PMH sets management)\n";
5013     SetVersion($DBversion);
5014 }
5015
5016 $DBversion = "3.07.00.031";
5017 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5018     $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')");
5019     print "Upgrade to $DBversion done (Add syspref to tell Koha if ICU indexing is in use for Zebra or not.)\n";
5020     SetVersion ($DBversion);
5021 }
5022
5023 $DBversion = "3.07.00.032";
5024 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5025     $dbh->do("ALTER TABLE virtualshelves MODIFY COLUMN owner int"); #should have been int already (fk to borrowers)
5026     $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
5027     $dbh->do("DELETE FROM virtualshelves WHERE owner IS NULL and category=1"); #delete private lists without owner (cascades to shelfcontents)
5028     $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");
5029     $dbh->do("UPDATE virtualshelves SET allow_add=0, allow_delete_own=1, allow_delete_other=0 WHERE category=1");
5030     $dbh->do("UPDATE virtualshelves SET allow_add=0, allow_delete_own=1, allow_delete_other=0 WHERE category=2");
5031     $dbh->do("UPDATE virtualshelves SET allow_add=1, allow_delete_own=1, allow_delete_other=1 WHERE category=3");
5032     $dbh->do("UPDATE virtualshelves SET category=2 WHERE category=3");
5033
5034     $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");
5035     $dbh->do("UPDATE virtualshelfcontents co LEFT JOIN virtualshelves sh USING (shelfnumber) SET co.borrowernumber=sh.owner");
5036
5037     $dbh->do("CREATE TABLE virtualshelfshares
5038     (id int AUTO_INCREMENT PRIMARY KEY, shelfnumber int NOT NULL,
5039     borrowernumber int, invitekey varchar(10), sharedate datetime,
5040     CONSTRAINT `virtualshelfshares_ibfk_1` FOREIGN KEY (`shelfnumber`) REFERENCES `virtualshelves` (`shelfnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
5041         CONSTRAINT `virtualshelfshares_ibfk_2` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE SET NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8");
5042
5043     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacAllowPublicListCreation',1,'If set, allows opac users to create public lists',NULL,'YesNo');");
5044     $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');");
5045
5046     print "Upgrade to $DBversion done (BZ7310: Improving list permissions)\n";
5047     SetVersion($DBversion);
5048 }
5049
5050 $DBversion = "3.07.00.033";
5051 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5052     $dbh->do("ALTER TABLE branches ADD opac_info text;");
5053     print "Upgrade to $DBversion done add opac_info to branches \n";
5054     SetVersion($DBversion);
5055 }
5056
5057 $DBversion = "3.07.00.034";
5058 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5059     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN category_code VARCHAR(10) NULL DEFAULT NULL AFTER `display_checkout`");
5060     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN class VARCHAR(255)  NOT NULL DEFAULT '' AFTER `category_code`");
5061     $dbh->do("ALTER TABLE borrower_attribute_types ADD CONSTRAINT category_code_fk FOREIGN KEY (category_code) REFERENCES categories(categorycode)");
5062     print "Upgrade to $DBversion done (New fields category_code and class in borrower_attribute_types table)\n";
5063     SetVersion($DBversion);
5064 }
5065
5066 $DBversion = "3.07.00.035";
5067 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5068     $dbh->do("ALTER TABLE issues CHANGE date_due date_due datetime");
5069     $dbh->do("UPDATE issues SET date_due = CONCAT(SUBSTR(date_due,1,11),'23:59:00')");
5070     $dbh->do("ALTER TABLE issues CHANGE returndate returndate datetime");
5071     $dbh->do("ALTER TABLE issues CHANGE lastreneweddate lastreneweddate datetime");
5072     $dbh->do("ALTER TABLE issues CHANGE issuedate issuedate datetime");
5073     $dbh->do("ALTER TABLE old_issues CHANGE date_due date_due datetime");
5074     $dbh->do("ALTER TABLE old_issues CHANGE returndate returndate datetime");
5075     $dbh->do("ALTER TABLE old_issues CHANGE lastreneweddate lastreneweddate datetime");
5076     $dbh->do("ALTER TABLE old_issues CHANGE issuedate issuedate datetime");
5077     $dbh->do("UPDATE accountlines SET description = CONCAT(description,' 23:59') WHERE accounttype='F' OR accounttype='FU'"); #BUG-8253
5078     print "Upgrade to $DBversion done (Setting up issues and accountlines tables for hourly loans)\n";
5079     SetVersion($DBversion);
5080 }
5081
5082 $DBversion = "3.07.00.036";
5083 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5084     $dbh->do(qq{
5085        ALTER TABLE z3950servers ADD timeout INT( 11 ) NOT NULL DEFAULT '0' AFTER syntax;
5086     });
5087     print "Upgrade to $DBversion done (New timeout field in z3950servers)\n";
5088 }
5089
5090 $DBversion = "3.07.00.037";
5091 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5092     $dbh->do("
5093        ALTER TABLE  `marc_subfield_structure` ADD  `maxlength` INT( 4 ) NOT NULL DEFAULT  '9999';
5094        ");
5095        $dbh->do("
5096        UPDATE `marc_subfield_structure` SET maxlength=24 WHERE tagfield='000';
5097        ");
5098        $dbh->do("
5099        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='MARC21','40','9999') WHERE tagfield='008';
5100        ");
5101        $dbh->do("
5102        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='NORMARC','40','9999') WHERE tagfield='008';
5103        ");
5104        $dbh->do("
5105        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='UNIMARC','36','9999') WHERE tagfield='100';
5106        ");
5107     print "Upgrade to $DBversion done (Add new field maxlength to marc_subfield_structure)\n";
5108     SetVersion($DBversion);
5109 }
5110
5111 $DBversion = "3.07.00.038";
5112 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5113     $dbh->do(qq{
5114         INSERT INTO systempreferences(variable,value,explanation,options,type)
5115         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')
5116     });
5117     print "Upgrade to $DBversion done (Added system preference 'UniqueItemFields')\n";
5118     SetVersion($DBversion);
5119 }
5120
5121 $DBversion = "3.07.00.039";
5122 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5123     $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')} );
5124     $dbh->do( qq{CREATE TABLE IF NOT EXISTS social_data
5125       ( isbn VARCHAR(30),
5126         num_critics INT,
5127         num_critics_pro INT,
5128         num_quotations INT,
5129         num_videos INT,
5130         score_avg DECIMAL(5,2),
5131         num_scores INT,
5132         PRIMARY KEY  (isbn)
5133       ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5134     } );
5135     $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')} );
5136     print "Upgrade to $DBversion done (added syspref and table for babeltheque (Babeltheque_url_js, babeltheque))\n";
5137     SetVersion($DBversion);
5138 }
5139
5140 $DBversion = "3.07.00.040";
5141 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5142     $dbh->do( qq{INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('SocialNetworks','0','Enable/Disable social networks links in opac detail','','YesNo')} );
5143     print "Upgrade to $DBversion done (added syspref SocialNetworks, to display facebook/ggl+ and other buttons)\n";
5144     SetVersion($DBversion);
5145 }
5146
5147
5148
5149 $DBversion = "3.07.00.041";
5150 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5151     $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')");
5152     print "Upgrade to $DBversion done (Add system preference SubscriptionDuplicateDroppedInput)\n";
5153     SetVersion($DBversion);
5154 }
5155
5156 $DBversion = "3.07.00.042";
5157 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5158     $dbh->do("ALTER TABLE reserves ADD suspend BOOLEAN NOT NULL DEFAULT 0");
5159     $dbh->do("ALTER TABLE old_reserves ADD suspend BOOLEAN NOT NULL DEFAULT 0");
5160
5161     $dbh->do("ALTER TABLE reserves ADD suspend_until DATETIME NULL DEFAULT NULL");
5162     $dbh->do("ALTER TABLE old_reserves ADD suspend_until DATETIME NULL DEFAULT NULL");
5163
5164     $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')");
5165
5166     print "Upgrade to $DBversion done (Add suspend fields to reserves table, add syspref AutoResumeSuspendedHolds)\n";
5167     SetVersion ($DBversion);
5168 }
5169
5170 $DBversion = "3.07.00.043";
5171 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5172     my $countXSLTDetailsDisplay = 0;
5173     my $valueXSLTDetailsDisplay = "";
5174     my $valueXSLTResultsDisplay = "";
5175     my $valueOPACXSLTDetailsDisplay = "";
5176     my $valueOPACXSLTResultsDisplay = "";
5177     #the line below test if database comes from a BibLibre's branch
5178     $countXSLTDetailsDisplay = $dbh->do('SELECT 1 FROM systempreferences WHERE variable="IntranetXSLTDetailsDisplay"');
5179     if ($countXSLTDetailsDisplay > 0)
5180     {
5181         #the two lines below will only be used to update the databases from the BibLibre's branch. They will not affect the others
5182         $dbh->do(q|UPDATE systempreferences SET variable="XSLTDetailsDisplay" WHERE variable="IntranetXSLTDetailsDisplay"|);
5183         $dbh->do(q|UPDATE systempreferences SET variable="XSLTResultsDisplay" WHERE variable="IntranetXSLTResultsDisplay"|);
5184     }
5185     else
5186     {
5187         $valueXSLTDetailsDisplay = "default" if (C4::Context->preference("XSLTDetailsDisplay"));
5188         $valueXSLTResultsDisplay = "default" if (C4::Context->preference("XSLTResultsDisplay"));
5189         $valueOPACXSLTDetailsDisplay = "default" if (C4::Context->preference("OPACXSLTDetailsDisplay"));
5190         $valueOPACXSLTResultsDisplay = "default" if (C4::Context->preference("OPACXSLTResultsDisplay"));
5191         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueXSLTDetailsDisplay\" WHERE variable='XSLTDetailsDisplay'");
5192         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueXSLTResultsDisplay\" WHERE variable='XSLTResultsDisplay'");
5193         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueOPACXSLTDetailsDisplay\" WHERE variable='OPACXSLTDetailsDisplay'");
5194         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueOPACXSLTResultsDisplay\" WHERE variable='OPACXSLTResultsDisplay'");
5195     }
5196     print "Upgrade to $DBversion done (XSLT systempreference takes a path to file rather than YesNo)\n";
5197     SetVersion($DBversion);
5198 }
5199
5200 $DBversion = "3.07.00.044";
5201 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5202     $dbh->do("ALTER TABLE aqbooksellers ADD deliverytime INT DEFAULT NULL");
5203     print "Upgrade to $DBversion done (Add deliverytime field in aqbooksellers table)";
5204     SetVersion($DBversion);
5205 }
5206
5207 $DBversion = "3.07.00.045";
5208 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5209     $dbh->do("ALTER TABLE import_batches MODIFY COLUMN batch_type ENUM('batch','z3950','webservice') NOT NULL default 'batch'");
5210     print "Upgrade to $DBversion done (Add 'webservice' to batch_type enum)\n";
5211     SetVersion ($DBversion);
5212 }
5213
5214 $DBversion = "3.07.00.046";
5215 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5216     $dbh->do("ALTER TABLE issuingrules ADD COLUMN lengthunit varchar(10) DEFAULT 'days' AFTER issuelength");
5217     print "Upgrade to $DBversion done (Setting up issues tables for hourly loans (lengthunit fix))\n";
5218     SetVersion($DBversion);
5219 }
5220
5221 $DBversion = "3.07.00.047";
5222 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5223     $dbh->do("CREATE INDEX items_location ON items(location)");
5224     $dbh->do("CREATE INDEX items_ccode ON items(ccode)");
5225     print "Upgrade to $DBversion done (items_location and items_ccode indexes added for ShelfBrowser)\n";
5226     SetVersion($DBversion);
5227 }
5228
5229 $DBversion = "3.07.00.048";
5230 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5231     $dbh->do(
5232         q | CREATE TABLE ratings (
5233   borrowernumber int(11) NOT NULL,
5234   biblionumber int(11) NOT NULL,
5235   rating_value tinyint(1) NOT NULL,
5236   timestamp timestamp NOT NULL default CURRENT_TIMESTAMP,
5237   PRIMARY KEY  (borrowernumber,biblionumber),
5238   CONSTRAINT ratings_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE,
5239   CONSTRAINT ratings_ibfk_2 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
5240 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
5241     );
5242
5243     $dbh->do(
5244 q /INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OpacStarRatings','disable',NULL,'disable|all|details','Choice') /
5245     );
5246
5247     print
5248 "Upgrade to $DBversion done (Add 'ratings' table and 'OpacStarRatings' syspref)\n";
5249     SetVersion($DBversion);
5250 }
5251
5252 $DBversion = "3.07.00.049";
5253 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5254     $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')");
5255     print "Upgrade to $DBversion done (Add system preference OpacBrowseResults ))\n";
5256     SetVersion($DBversion);
5257 }
5258
5259 $DBversion = "3.08.00.000";
5260 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5261     print "Upgrade to $DBversion done\n";
5262     SetVersion($DBversion);
5263 }
5264
5265 $DBversion = "3.09.00.001";
5266 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5267     $dbh->do("ALTER TABLE borrower_attribute_types MODIFY category_code VARCHAR( 1 ) NULL DEFAULT NULL");
5268     print "Upgrade to $DBversion done. (Bug 8002: Update patron attribute types table to allow NULL category_code)\n";
5269     SetVersion($DBversion);
5270 }
5271
5272 $DBversion = "3.09.00.002";
5273 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5274     $dbh->do("ALTER TABLE saved_sql
5275         ADD (
5276             cache_expiry INT NOT NULL DEFAULT 300,
5277             public BOOLEAN NOT NULL DEFAULT FALSE
5278         );
5279     ");
5280     print "Upgrade to $DBversion done (Added cache_expiry and public fields in
5281 saved_reports table.)\n";
5282     SetVersion($DBversion);
5283 }
5284
5285 $DBversion = "3.09.00.003";
5286 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5287     $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');");
5288     print "Upgrade to $DBversion done (Added SvcMaxReportRows syspref)\n";
5289     SetVersion($DBversion);
5290 }
5291
5292 $DBversion = "3.09.00.004";
5293 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5294     $dbh->do("INSERT IGNORE INTO permissions (module_bit, code, description) VALUES('13', 'edit_patrons', 'Perform batch modifivation of patrons')");
5295     print "Upgrade to $DBversion done (Adds permissions flag for access to the patron modifications tool)\n";
5296     SetVersion($DBversion);
5297 }
5298
5299 $DBversion = "3.09.00.005";
5300 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5301     unless (TableExists('quotes')) {
5302         $dbh->do( qq{
5303             CREATE TABLE `quotes` (
5304               `id` int(11) NOT NULL AUTO_INCREMENT,
5305               `source` text DEFAULT NULL,
5306               `text` mediumtext NOT NULL,
5307               `timestamp` datetime NOT NULL,
5308               PRIMARY KEY (`id`)
5309             ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5310         });
5311     }
5312     $dbh->do( qq{
5313         INSERT IGNORE INTO permissions VALUES (13, "edit_quotes","Edit quotes for quote-of-the-day feature");
5314     });
5315     $dbh->do( qq{
5316         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');
5317     });
5318     print "Upgrade to $DBversion done (Adding Quote of the Day Option.)\n";
5319     SetVersion($DBversion);
5320 }
5321
5322 $DBversion = "3.09.00.006";
5323 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5324     $dbh->do("UPDATE systempreferences SET
5325                 variable = 'OPACShowHoldQueueDetails',
5326                 value = CASE value WHEN '1' THEN 'priority' ELSE 'none' END,
5327                 options = 'none|priority|holds|holds_priority',
5328                 explanation = 'Show holds details in OPAC',
5329                 type = 'Choice'
5330               WHERE variable = 'OPACDisplayRequestPriority'");
5331     print "Upgrade to $DBversion done (Changed system preference OPACDisplayRequestPriority -> OPACShowHoldQueueDetails)\n";
5332     SetVersion($DBversion);
5333 }
5334
5335 $DBversion = "3.09.00.007";
5336 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5337     unless(C4::Context->preference('ReservesControlBranch')){
5338         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('ReservesControlBranch','PatronLibrary','ItemHomeLibrary|PatronLibrary','Branch checked for members reservations rights.','Choice')");
5339     }
5340     print "Upgrade to $DBversion done (Insert ReservesControlBranch systempreference into systempreferences table )\n";
5341     SetVersion($DBversion);
5342 }
5343
5344 $DBversion = "3.09.00.008";
5345 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5346     $dbh->do("ALTER TABLE sessions ADD PRIMARY KEY (id);");
5347     $dbh->do("ALTER TABLE sessions DROP INDEX `id`;");
5348     print "Upgrade to $DBversion done (redefine the field id as PRIMARY KEY of sessions)\n";
5349     SetVersion($DBversion);
5350 }
5351
5352 $DBversion = "3.09.00.009";
5353 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5354     $dbh->do("ALTER TABLE branches ADD PRIMARY KEY (branchcode);");
5355     $dbh->do("ALTER TABLE branches DROP INDEX branchcode;");
5356     print "Upgrade to $DBversion done (redefine the field branchcode as PRIMARY KEY of branches)\n";
5357     SetVersion ($DBversion);
5358 }
5359
5360 $DBversion = "3.09.00.010";
5361 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5362     $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')");
5363     print "Upgrade to $DBversion done (Add system preference issuelostitem ))\n";
5364     SetVersion($DBversion);
5365 }
5366
5367 $DBversion = "3.09.00.011";
5368 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5369     $dbh->do("ALTER TABLE `biblioitems` ADD `ean` VARCHAR( 13 ) NULL AFTER issn");
5370     $dbh->do("CREATE INDEX `ean` ON biblioitems (`ean`) ");
5371     $dbh->do("ALTER TABLE `deletedbiblioitems` ADD `ean` VARCHAR( 13 ) NULL AFTER issn");
5372     if (C4::Context->preference("marcflavour") eq 'UNIMARC') {
5373          $dbh->do("UPDATE marc_subfield_structure SET kohafield='biblioitems.ean' WHERE tagfield='073' and tagsubfield='a'");
5374     }
5375     print "Upgrade to $DBversion done (Adding ean in biblioitems and deletedbiblioitems)\n";
5376     print "If you have records with ean, please run misc/batchRebuildBiblioTables.pl to populate bibliotems.ean\n" if (C4::Context->preference("marcflavour") eq 'UNIMARC');
5377     SetVersion($DBversion);
5378 }
5379
5380 $DBversion = "3.09.00.012";
5381 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5382     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('SuspendHoldsIntranet', '1', NULL , 'Allow holds to be suspended from the intranet.', 'YesNo')");
5383     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('SuspendHoldsOpac', '1', NULL , 'Allow holds to be suspended from the OPAC.', 'YesNo')");
5384     print "Upgrade to $DBversion done (Add system preference OpacBrowseResults ))\n";
5385     SetVersion($DBversion);
5386 }
5387
5388 $DBversion ="3.09.00.013";
5389 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5390     $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');");
5391     print "Upgrade to $DBversion done (Add system preference DefaultLanguageField008))\n";
5392     SetVersion($DBversion);
5393 }
5394
5395 $DBversion ="3.09.00.014";
5396 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5397     # add phone message transport type
5398     $dbh->do("INSERT INTO message_transport_types (message_transport_type) VALUES ('phone')");
5399
5400     # adds HOLD_PHONE and PREDUE_PHONE letters (as placeholders)
5401     $dbh->do("INSERT INTO letter (module, code, name, title, content) VALUES
5402               ('reserves', 'HOLD_PHONE', 'Item Available for Pick-up (phone notice)', 'Item Available for Pick-up (phone notice)', 'Your item is available for pickup'),
5403               ('circulation', 'PREDUE_PHONE', 'Advance Notice of Item Due (phone notice)', 'Advance Notice of Item Due (phone notice)', 'Your item is due soon'),
5404               ('circulation', 'OVERDUE_PHONE', 'Overdue Notice (phone notice)', 'Overdue Notice (phone notice)', 'Your item is overdue')
5405               ");
5406
5407     # add phone notifications to patron message preferences options
5408     $dbh->do("INSERT INTO message_transports
5409              (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) VALUES
5410              (4, 'phone', 0, 'reserves', 'HOLD_PHONE'),
5411              (2, 'phone', 0, 'circulation', 'PREDUE_PHONE')
5412              ");
5413
5414     # add TalkingTechItivaPhoneNotification syspref
5415     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('TalkingTechItivaPhoneNotification',0,'If ON, enables Talking Tech I-tiva phone notifications',NULL,'YesNo');");
5416
5417     print "Upgrade done (Support for Talking Tech i-tiva phone notification system)\n";
5418     SetVersion($DBversion);
5419 }
5420
5421 $DBversion = "3.09.00.015";
5422 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5423     $dbh->do(qq{
5424         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')
5425     });
5426     print "Upgrade to $DBversion done (Add System preference StatisticsFields)\n";
5427     SetVersion($DBversion);
5428 }
5429
5430 $DBversion = "3.09.00.016";
5431 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5432     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACShowBarcode','0','Show items barcode in holding tab','','YesNo')");
5433     print "Upgrade to $DBversion done (Add syspref OPACShowBarcode)\n";
5434     SetVersion ($DBversion);
5435 }
5436
5437 $DBversion = "3.09.00.017";
5438 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5439     $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');");
5440     print "Upgrade to $DBversion done (Add customizable OpacNavRight region to the OPAC main page)\n";
5441     SetVersion ($DBversion);
5442 }
5443
5444 $DBversion = "3.09.00.018";
5445 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5446     $dbh->do("DROP TABLE IF EXISTS aqbudgetborrowers");
5447     $dbh->do("
5448         CREATE TABLE aqbudgetborrowers (
5449           budget_id int(11) NOT NULL,
5450           borrowernumber int(11) NOT NULL,
5451           PRIMARY KEY (budget_id, borrowernumber),
5452           CONSTRAINT aqbudgetborrowers_ibfk_1 FOREIGN KEY (budget_id)
5453             REFERENCES aqbudgets (budget_id)
5454             ON DELETE CASCADE ON UPDATE CASCADE,
5455           CONSTRAINT aqbudgetborrowers_ibfk_2 FOREIGN KEY (borrowernumber)
5456             REFERENCES borrowers (borrowernumber)
5457             ON DELETE CASCADE ON UPDATE CASCADE
5458         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
5459     ");
5460     $dbh->do("
5461         INSERT INTO permissions (module_bit, code, description)
5462         VALUES (11, 'budget_manage_all', 'Manage all budgets')
5463     ");
5464     print "Upgrade to $DBversion done (Add aqbudgetborrowers table)\n";
5465     SetVersion($DBversion);
5466 }
5467
5468 $DBversion = "3.09.00.019";
5469 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5470     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('OPACShowUnusedAuthorities','1','','Show authorities that are not being used in the OPAC.','YesNo')");
5471     print "Upgrade to $DBversion done (Add OPACShowUnusedAuthorities system preference)\n";
5472     SetVersion ($DBversion);
5473 }
5474
5475 $DBversion = "3.09.00.020";
5476 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5477     $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')");
5478     $dbh->do("
5479 CREATE TABLE IF NOT EXISTS borrower_files (
5480   file_id int(11) NOT NULL AUTO_INCREMENT,
5481   borrowernumber int(11) NOT NULL,
5482   file_name varchar(255) NOT NULL,
5483   file_type varchar(255) NOT NULL,
5484   file_description varchar(255) DEFAULT NULL,
5485   file_content longblob NOT NULL,
5486   date_uploaded timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
5487   PRIMARY KEY (file_id),
5488   KEY borrowernumber (borrowernumber)
5489 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
5490     ");
5491     $dbh->do("ALTER TABLE borrower_files ADD CONSTRAINT borrower_files_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE");
5492
5493     print "Upgrade to $DBversion done (Added borrow_files table, EnableBorrowerFiles syspref)\n";
5494     SetVersion($DBversion);
5495 }
5496
5497 $DBversion = "3.09.00.021";
5498 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5499     $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');");
5500     print "Upgrade to $DBversion done (Add syspref UpdateTotalIssuesOnCirc)\n";
5501     SetVersion($DBversion);
5502 }
5503
5504 $DBversion = "3.09.00.022";
5505 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5506     $dbh->do("ALTER TABLE search_history MODIFY COLUMN query_cgi text NOT NULL");
5507     print "Upgrade to $DBversion done (Change search_history.query_cgi type to text. bug 5981)\n";
5508     SetVersion($DBversion);
5509 }
5510
5511 $DBversion = "3.09.00.023";
5512 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5513     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('SearchEngine','Zebra','Solr|Zebra','Search Engine','Choice')");
5514     print "Upgrade to $DBversion done (Add system preference SearchEngine )\n";
5515     SetVersion($DBversion);
5516 }
5517
5518 $DBversion ="3.09.00.024";
5519 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5520     $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')");
5521     print "Upgrade to $DBversion done (Add system preference IntranetSlipPrinterJS))\n";
5522     SetVersion($DBversion);
5523 }
5524
5525 $DBversion = "3.09.00.025";
5526 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5527     $dbh->do('START TRANSACTION');
5528     $dbh->do('CREATE TABLE tmp_reserves AS SELECT * FROM old_reserves LIMIT 0');
5529     $dbh->do('ALTER TABLE tmp_reserves ADD reserve_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
5530     $dbh->do("
5531         INSERT INTO tmp_reserves (
5532           borrowernumber, reservedate, biblionumber,
5533           constrainttype, branchcode, notificationdate,
5534           reminderdate, cancellationdate, reservenotes,
5535           priority, found, timestamp, itemnumber,
5536           waitingdate, expirationdate, lowestPriority,
5537           suspend, suspend_until
5538         ) SELECT
5539           borrowernumber, reservedate, biblionumber,
5540           constrainttype, branchcode, notificationdate,
5541           reminderdate, cancellationdate, reservenotes,
5542           priority, found, timestamp, itemnumber,
5543           waitingdate, expirationdate, lowestPriority,
5544           suspend, suspend_until
5545         FROM old_reserves ORDER BY reservedate
5546     ");
5547     $dbh->do('SET @ai = ( SELECT MAX( reserve_id ) FROM tmp_reserves )');
5548     $dbh->do('TRUNCATE old_reserves');
5549     $dbh->do('ALTER TABLE old_reserves ADD reserve_id INT( 11 ) NOT NULL PRIMARY KEY FIRST');
5550     $dbh->do('INSERT INTO old_reserves SELECT * FROM tmp_reserves WHERE reserve_id <= @ai');
5551     $dbh->do("
5552         INSERT INTO tmp_reserves (
5553           borrowernumber, reservedate, biblionumber,
5554           constrainttype, branchcode, notificationdate,
5555           reminderdate, cancellationdate, reservenotes,
5556           priority, found, timestamp, itemnumber,
5557           waitingdate, expirationdate, lowestPriority,
5558           suspend, suspend_until
5559         ) SELECT
5560           borrowernumber, reservedate, biblionumber,
5561           constrainttype, branchcode, notificationdate,
5562           reminderdate, cancellationdate, reservenotes,
5563           priority, found, timestamp, itemnumber,
5564           waitingdate, expirationdate, lowestPriority,
5565           suspend, suspend_until
5566         FROM reserves ORDER BY reservedate
5567     ");
5568     $dbh->do('TRUNCATE reserves');
5569     $dbh->do('ALTER TABLE reserves ADD reserve_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
5570     $dbh->do('INSERT INTO reserves SELECT * FROM tmp_reserves WHERE reserve_id > COALESCE(@ai, 0)');
5571     $dbh->do('DROP TABLE tmp_reserves');
5572     $dbh->do('COMMIT');
5573
5574     my $sth = $dbh->prepare("
5575         SELECT COUNT( * ) AS count
5576         FROM information_schema.COLUMNS
5577         WHERE COLUMN_NAME =  'reserve_id'
5578         AND (
5579           TABLE_NAME LIKE  'reserves'
5580           OR
5581           TABLE_NAME LIKE  'old_reserves'
5582         )
5583     ");
5584     $sth->execute();
5585     my $row = $sth->fetchrow_hashref();
5586     die("Failed to add reserve_id to reserves tables, please refresh the page to try again.") unless ( $row->{'count'} );
5587
5588     print "Upgrade to $DBversion done (add reserve_id to reserves & old_reserves tables)\n";
5589     SetVersion($DBversion);
5590 }
5591
5592 $DBversion = "3.09.00.026";
5593 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5594     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
5595         ( 3, 'parameters_remaining_permissions', 'Remaining system parameters permissions'),
5596         ( 3, 'manage_circ_rules', 'manage circulation rules')");
5597     $dbh->do("INSERT INTO user_permissions (borrowernumber, module_bit, code)
5598         SELECT borrowernumber, 3, 'parameters_remaining_permissions'
5599         FROM borrowers WHERE flags & (1 << 3)");
5600     # Give new subpermissions to all users that have 'parameters' permission flag (bit 3) set
5601     # see userflags table
5602     $dbh->do("INSERT INTO user_permissions (borrowernumber, module_bit, code)
5603         SELECT borrowernumber, 3, 'manage_circ_rules'
5604         FROM borrowers WHERE flags & (1 << 3)");
5605     print "Upgrade to $DBversion done (Added parameters subpermissions)\n";
5606     SetVersion($DBversion);
5607 }
5608
5609 $DBversion = '3.09.00.027';
5610 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5611     $dbh->do("ALTER TABLE issuingrules ADD overduefinescap decimal(28,6) DEFAULT NULL");
5612     my $maxfine = C4::Context->preference('MaxFine');
5613     if ($maxfine && $maxfine < 900) { # an arbitrary value that tells us it's not "some huge value"
5614       $dbh->do("UPDATE issuingrules SET overduefinescap=?",undef,$maxfine);
5615       $dbh->do("UPDATE systempreferences SET value = NULL WHERE variable = 'MaxFine'");
5616     }
5617     $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'");
5618     print "Upgrade to $DBversion done (Bug 7420 add overduefinescap to circulation matrix)\n";
5619     SetVersion ($DBversion);
5620 }
5621
5622 $DBversion = "3.09.00.028";
5623 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5624     unless ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) {
5625         my %referencetypes = (  '00' => 'PERSO_NAME',
5626                                 '10' => 'CORPO_NAME',
5627                                 '11' => 'MEETI_NAME',
5628                                 '30' => 'UNIF_TITLE',
5629                                 '48' => 'CHRON_TERM',
5630                                 '50' => 'TOPIC_TERM',
5631                                 '51' => 'GEOGR_NAME',
5632                                 '55' => 'GENRE/FORM'
5633                 );
5634         my $query = q{SELECT DISTINCT authtypecode, tagfield
5635                     FROM auth_subfield_structure
5636                     WHERE (tagfield BETWEEN '400' AND '455' OR
5637                     tagfield BETWEEN '500' and '555') AND tagsubfield='a' AND
5638                     frameworkcode = '' AND ROW(authtypecode, tagfield) NOT IN
5639                     (SELECT authtypecode, tagfield FROM auth_subfield_structure
5640                     WHERE tagsubfield ='9' )};
5641         $sth = $dbh->prepare($query);
5642         $sth->execute;
5643         my $sth2 = $dbh->prepare(q{INSERT INTO auth_subfield_structure
5644                 (authtypecode, tagfield, tagsubfield, liblibrarian, libopac,
5645                  repeatable, mandatory, tab, authorised_value, value_builder,
5646                  seealso, isurl, hidden, linkid, kohafield, frameworkcode)
5647                 VALUES (?, ?, '9', '9 (RLIN)', '9 (RLIN)', 0, 0, ?, NULL, NULL,
5648                     NULL, 0, 1, '', '', '')});
5649         my $sth3 = $dbh->prepare(q{UPDATE auth_subfield_structure SET
5650                                     frameworkcode = ? WHERE authtypecode = ? AND
5651                                     tagfield = ? AND tagsubfield = 'a'});
5652         while (my $row = $sth->fetchrow_arrayref()) {
5653             my ($authtypecode, $field) = @$row;
5654             $sth2->execute($authtypecode, $field, substr($field, 0, 1));
5655             my $authtypemarker = substr $field, 1, 2;
5656             if ($authtypemarker && $referencetypes{$authtypemarker}) {
5657                 $sth3->execute($referencetypes{$authtypemarker}, $authtypecode, $field);
5658             }
5659         }
5660     }
5661
5662     print "Upgrade to $DBversion done (Add thesaurus links for MARC21/NORMARC)\n";
5663     SetVersion($DBversion);
5664 }
5665
5666 $DBversion = "3.09.00.029"; # FIXME
5667 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5668     $dbh->do("UPDATE systempreferences SET options=concat(options,'|EAN13') WHERE variable='itemBarcodeInputFilter' AND options NOT LIKE '%EAN13%'");
5669     print "Upgrade to $DBversion done (Add itemBarcodeInputFilter choice EAN13)\n";
5670
5671     $dbh->do("UPDATE systempreferences SET options = concat(options,'|EAN13'), explanation = concat(explanation,'; EAN13 - incremental') WHERE variable = 'autoBarcode' AND options NOT LIKE '%EAN13%'");
5672     print "Upgrade to $DBversion done ( Added EAN13 barcode autogeneration sequence )\n";
5673     SetVersion($DBversion);
5674 }
5675
5676 $DBversion ="3.09.00.030";
5677 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5678     my $query = "SELECT value FROM systempreferences WHERE variable='opacstylesheet'";
5679     my $remote= $dbh->selectrow_arrayref($query);
5680     $dbh->do("DELETE from systempreferences WHERE variable='opacstylesheet'");
5681     if($remote && $remote->[0]) {
5682         $query="UPDATE systempreferences SET value=? WHERE variable='opaclayoutstylesheet'";
5683         $dbh->do($query,undef,$remote->[0]);
5684         print "NOTE: The URL of your remote opac css file has been moved to preference opaclayoutstylesheet.\n";
5685     }
5686     print "Upgrade to $DBversion done (BZ 8263: Make OPAC stylesheet preferences more consistent)\n";
5687     SetVersion($DBversion);
5688 }
5689
5690 $DBversion = "3.09.00.031";
5691 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5692     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonReviews'");
5693     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonSimilarItems'");
5694     $dbh->do("DELETE FROM systempreferences WHERE variable='AWSAccessKeyID'");
5695     $dbh->do("DELETE FROM systempreferences WHERE variable='AWSPrivateKey'");
5696     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonReviews'");
5697     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonSimilarItems'");
5698     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonEnabled'");
5699     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonEnabled'");
5700     print "Upgrade to $DBversion done ('Remove preferences controlling broken Amazon features (Bug 8679')\n";
5701     SetVersion ($DBversion);
5702 }
5703
5704 $DBversion = "3.09.00.032";
5705 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5706     $dbh->do("UPDATE systempreferences SET value = 'call_number' WHERE variable = 'defaultSortField' AND value = 'callnumber'");
5707     $dbh->do("UPDATE systempreferences SET value = 'call_number' WHERE variable = 'OPACdefaultSortField' AND value = 'callnumber'");
5708     print "Upgrade to $DBversion done (Bug 8657 - Default sort by call number does not work. Correcting system preference value.)\n";
5709     SetVersion ($DBversion);
5710 }
5711
5712
5713 $DBversion = '3.09.00.033';
5714 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5715    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacSuppressionByIPRange','','Restrict the suppression to IP adresses outside of the IP range','','free');");
5716    print "Upgrade to $DBversion done (Add OpacSuppressionByIPRange syspref)\n";
5717    SetVersion ($DBversion);
5718 }
5719
5720 $DBversion ="3.09.00.034";
5721 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5722     $dbh->do("UPDATE auth_subfield_structure SET frameworkcode = 'PERSO_NAME' WHERE frameworkcode = 'PERSO_CODE'");
5723     $dbh->do("UPDATE auth_subfield_structure SET frameworkcode = 'CORPO_NAME' WHERE frameworkcode = 'ORGO_CODE'");
5724     print "Upgrade to $DBversion done (Bug 8207: correct typo in authority types)\n";
5725     SetVersion ($DBversion);
5726 }
5727
5728 $DBversion = "3.09.00.035";
5729 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5730     $dbh->do("
5731     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');
5732     ");
5733     $dbh->do(
5734     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SubfieldsToUseWhenPrefill','','Define a list of subfields to use when prefilling items (separated by space)','','Free');
5735     ");
5736     print "Upgrade to $DBversion done (Adding PrefillItem and SubfieldsToUseWhenPrefill sysprefs)\n";
5737     SetVersion ($DBversion);
5738 }
5739
5740 $DBversion = "3.09.00.036";
5741 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5742     # biblioitems changes
5743     $dbh->do("ALTER TABLE biblioitems ADD COLUMN agerestriction VARCHAR(255) DEFAULT NULL AFTER cn_sort");
5744     $dbh->do("ALTER TABLE deletedbiblioitems ADD COLUMN agerestriction VARCHAR(255) DEFAULT NULL AFTER cn_sort");
5745     # preferences changes
5746     $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')");
5747     $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')");
5748
5749     print "Upgrade to $DBversion done (Add colum agerestriction to biblioitems and deletedbiblioitems, add system preferences AgeRestrictionMarker and AgeRestrictionOverride)\n";
5750    SetVersion ($DBversion);
5751 }
5752
5753 $DBversion = "3.09.00.037";
5754 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5755     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('UseTransportCostMatrix',0,'Use Transport Cost Matrix when filling holds','','YesNo')");
5756
5757  $dbh->do("CREATE TABLE `transport_cost` (
5758               `frombranch` varchar(10) NOT NULL,
5759               `tobranch` varchar(10) NOT NULL,
5760               `cost` decimal(6,2) NOT NULL,
5761               `disable_transfer` tinyint(1) NOT NULL DEFAULT 0,
5762               CHECK ( `frombranch` <> `tobranch` ), -- a dud check, mysql does not support that
5763               PRIMARY KEY (`frombranch`, `tobranch`),
5764               CONSTRAINT `transport_cost_ibfk_1` FOREIGN KEY (`frombranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
5765               CONSTRAINT `transport_cost_ibfk_2` FOREIGN KEY (`tobranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
5766           ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
5767
5768     print "Upgrade to $DBversion done (creating `transport_cost` table; adding UseTransportCostMatrix systempref, in circulation)\n";
5769     SetVersion($DBversion);
5770 }
5771
5772 $DBversion ="3.09.00.038";
5773 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5774     $dbh->do("ALTER TABLE borrower_attributes CHANGE  attribute  attribute VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
5775     print "Upgrade to $DBversion done (Increase the maximum size of a borrower attribute value)\n";
5776     SetVersion($DBversion);
5777 }
5778
5779 $DBversion ="3.09.00.039";
5780 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5781     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,type) VALUES('DidYouMeanFromAuthorities','0','Suggest searches based on authority file.','YesNo');");
5782     print "Upgrade to $DBversion done (Add system preference DidYouMeanFromAuthorities)\n";
5783     SetVersion($DBversion);
5784 }
5785
5786 $DBversion = "3.09.00.040";
5787 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5788     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('IncludeSeeFromInSearches','0','','Include see-from references in searches.','YesNo');");
5789     print "Upgrade to $DBversion done (Add IncludeSeeFromInSearches system preference)\n";
5790     SetVersion ($DBversion);
5791 }
5792
5793 $DBversion = "3.09.00.041";
5794 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5795     $dbh->do(qq{
5796         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ExportRemoveFields','','List of fields for non export in circulation.pl (separated by a space)','','');
5797     });
5798     print "Upgrade to $DBversion done (Add system preference ExportRemoveFields)\n";
5799     SetVersion($DBversion);
5800 }
5801
5802 $DBversion = "3.09.00.042";
5803 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5804     $dbh->do(qq{
5805         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ExportWithCsvProfile','','Set a profile name for CSV export','','');
5806     });
5807     print "Upgrade to $DBversion done (Adds New System preference ExportWithCsvProfile)\n";
5808     SetVersion($DBversion)
5809 }
5810
5811 $DBversion = "3.09.00.043";
5812 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5813     $dbh->do("
5814         ALTER TABLE aqorders
5815         ADD parent_ordernumber int(11) DEFAULT NULL
5816     ");
5817     $dbh->do("
5818         UPDATE aqorders
5819         SET parent_ordernumber = ordernumber;
5820     ");
5821     print "Upgrade to $DBversion done (Adding parent_ordernumber in aqorders)\n";
5822     SetVersion($DBversion);
5823 }
5824
5825 $DBversion = '3.09.00.044';
5826 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5827     $dbh->do("ALTER TABLE statistics ADD COLUMN ccode VARCHAR ( 10 ) NULL AFTER associatedborrower");
5828     $dbh->do("UPDATE statistics SET statistics.ccode = ( SELECT items.ccode FROM items WHERE statistics.itemnumber = items.itemnumber )");
5829     $dbh->do("UPDATE statistics SET statistics.ccode = (
5830               SELECT deleteditems.ccode FROM deleteditems
5831                   WHERE statistics.itemnumber = deleteditems.itemnumber
5832               ) WHERE statistics.ccode IS NULL");
5833     print "Upgrade done ( Added Collection Code to Statistics table. )\n";
5834     SetVersion ($DBversion);
5835 }
5836
5837 $DBversion = "3.09.00.045";
5838 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5839     $dbh->do("ALTER TABLE borrower_attribute_types MODIFY category_code VARCHAR( 10 ) NULL DEFAULT NULL");
5840     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.";
5841     SetVersion($DBversion);
5842 }
5843
5844 $DBversion = "3.09.00.046";
5845 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5846     $dbh->do("ALTER TABLE `accountlines` ADD `accountlines_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;");
5847     print "Upgrade to $DBversion done (adding accountlines_id field in accountlines table)\n";
5848     SetVersion($DBversion);
5849 }
5850
5851 $DBversion = "3.09.00.047";
5852 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5853     # to preserve default behaviour as best as possible, set this new preference differently depending on whether IndependantBranches is set or not
5854     my $prefvalue = 'anywhere';
5855     if (C4::Context->preference("IndependantBranches")) { $prefvalue = 'homeorholdingbranch';}
5856     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowReturnToBranch', '$prefvalue', 'Where an item may be returned', 'anywhere|homebranch|holdingbranch|homeorholdingbranch', 'Choice');");
5857
5858     print "Upgrade to $DBversion done: adding AllowReturnToBranch syspref (bug 6151)";
5859     SetVersion($DBversion);
5860 }
5861
5862 $DBversion = "3.09.00.048";
5863 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5864     $dbh->do("ALTER TABLE authorised_values MODIFY lib varchar(200)");
5865     $dbh->do("ALTER TABLE authorised_values MODIFY lib_opac varchar(200)");
5866
5867     print "Upgrade to $DBversion done (Raise the length of Authorised Values descriptions)\n";
5868     SetVersion($DBversion);
5869 }
5870
5871 $DBversion ="3.09.00.049";
5872 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5873     $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');");
5874     $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');");
5875     $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');");
5876     $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');");
5877     print "Upgrade to $DBversion done (Add OPACMobileUserCSS, OpacMainUserBlockMobile, OpacShowLibrariesPulldownMobile and OpacShowFiltersPulldownMobile sysprefs)\n";
5878     SetVersion($DBversion);
5879 }
5880
5881 $DBversion = "3.09.00.050";
5882 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5883     $dbh->do("ALTER TABLE authorised_values MODIFY category varchar(16) NOT NULL DEFAULT '';");
5884     $dbh->do("INSERT INTO authorised_values (category, authorised_value, lib) VALUES
5885               ('REPORT_GROUP', 'CIRC', 'Circulation'),
5886               ('REPORT_GROUP', 'CAT', 'Catalog'),
5887               ('REPORT_GROUP', 'PAT', 'Patrons'),
5888               ('REPORT_GROUP', 'ACQ', 'Acquisitions'),
5889               ('REPORT_GROUP', 'ACC', 'Accounts');");
5890
5891     $dbh->do("ALTER TABLE reports_dictionary ADD report_area varchar(6) DEFAULT NULL;");
5892     $dbh->do("UPDATE reports_dictionary SET report_area = CASE area
5893                   WHEN 1 THEN 'CIRC'
5894                   WHEN 2 THEN 'CAT'
5895                   WHEN 3 THEN 'PAT'
5896                   WHEN 4 THEN 'ACQ'
5897                   WHEN 5 THEN 'ACC'
5898                   END;");
5899     $dbh->do("ALTER TABLE reports_dictionary DROP area;");
5900     $dbh->do("ALTER TABLE reports_dictionary ADD KEY dictionary_area_idx (report_area);");
5901
5902     $dbh->do("ALTER TABLE saved_sql ADD report_area varchar(6) DEFAULT NULL;");
5903     $dbh->do("ALTER TABLE saved_sql ADD report_group varchar(80) DEFAULT NULL;");
5904     $dbh->do("ALTER TABLE saved_sql ADD report_subgroup varchar(80) DEFAULT NULL;");
5905     $dbh->do("ALTER TABLE saved_sql ADD KEY sql_area_group_idx (report_group, report_subgroup);");
5906
5907     print "Upgrade to $DBversion done saved_sql new fields report_group and report_area; authorised_values.category 16 char \n";
5908     SetVersion($DBversion);
5909 }
5910
5911 $DBversion = "3.09.00.051";
5912 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5913     $dbh->do("
5914         CREATE TABLE aqinvoices (
5915           invoiceid int(11) NOT NULL AUTO_INCREMENT,
5916           invoicenumber mediumtext NOT NULL,
5917           booksellerid int(11) NOT NULL,
5918           shipmentdate date default NULL,
5919           billingdate date default NULL,
5920           closedate date default NULL,
5921           shipmentcost decimal(28,6) default NULL,
5922           shipmentcost_budgetid int(11) default NULL,
5923           PRIMARY KEY (invoiceid),
5924           CONSTRAINT aqinvoices_fk_aqbooksellerid FOREIGN KEY (booksellerid) REFERENCES aqbooksellers (id) ON DELETE CASCADE ON UPDATE CASCADE,
5925           CONSTRAINT aqinvoices_fk_shipmentcost_budgetid FOREIGN KEY (shipmentcost_budgetid) REFERENCES aqbudgets (budget_id) ON DELETE SET NULL ON UPDATE CASCADE
5926         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5927     ");
5928
5929     # Fill this new table with existing invoices
5930     my $sth = $dbh->prepare("
5931         SELECT aqorders.booksellerinvoicenumber AS invoicenumber, aqbasket.booksellerid, aqorders.datereceived
5932         FROM aqorders
5933           LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
5934         WHERE aqorders.booksellerinvoicenumber IS NOT NULL
5935           AND aqorders.booksellerinvoicenumber != ''
5936         GROUP BY aqorders.booksellerinvoicenumber
5937     ");
5938     $sth->execute;
5939     my $results = $sth->fetchall_arrayref({});
5940     $sth = $dbh->prepare("
5941         INSERT INTO aqinvoices (invoicenumber, booksellerid, shipmentdate) VALUES (?,?,?)
5942     ");
5943     foreach(@$results) {
5944         $sth->execute($_->{invoicenumber}, $_->{booksellerid}, $_->{datereceived});
5945     }
5946
5947     # Add the column in aqorders, fill it with correct value
5948     # and then drop booksellerinvoicenumber column
5949     $dbh->do("
5950         ALTER TABLE aqorders
5951         ADD COLUMN invoiceid int(11) default NULL AFTER booksellerinvoicenumber,
5952         ADD CONSTRAINT aqorders_ibfk_3 FOREIGN KEY (invoiceid) REFERENCES aqinvoices (invoiceid) ON DELETE SET NULL ON UPDATE CASCADE
5953     ");
5954
5955     $dbh->do("
5956         UPDATE aqorders, aqinvoices
5957         SET aqorders.invoiceid = aqinvoices.invoiceid
5958         WHERE aqorders.booksellerinvoicenumber = aqinvoices.invoicenumber
5959     ");
5960
5961     $dbh->do("
5962         ALTER TABLE aqorders
5963         DROP COLUMN booksellerinvoicenumber
5964     ");
5965
5966     print "Upgrade to $DBversion done (Add aqinvoices table) \n";
5967     SetVersion ($DBversion);
5968 }
5969
5970 $DBversion = "3.09.00.052";
5971 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5972     $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');");
5973     $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');");
5974     $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');");
5975     print "Upgrade to $DBversion done (Add systempreferences to decrease loan length on high demand items decreaseLoanHighHolds, decreaseLoanHighHoldsValue and decreaseLoanHighHoldsDuration) \n";
5976     SetVersion ($DBversion);
5977 }
5978
5979 $DBversion = "3.09.00.053";
5980 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5981     $dbh->do(
5982     q|CREATE TABLE `import_auths` (
5983         import_record_id int(11) NOT NULL,
5984         matched_authid int(11) default NULL,
5985         control_number varchar(25) default NULL,
5986         authorized_heading varchar(128) default NULL,
5987         original_source varchar(25) default NULL,
5988         CONSTRAINT import_auths_ibfk_1 FOREIGN KEY (import_record_id)
5989         REFERENCES import_records (import_record_id) ON DELETE CASCADE ON UPDATE CASCADE,
5990         KEY matched_authid (matched_authid)
5991         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;|
5992     );
5993     $dbh->do("ALTER TABLE import_batches
5994                 CHANGE COLUMN num_biblios num_records int(11) NOT NULL default 0,
5995                 ADD COLUMN record_type enum('biblio', 'auth', 'holdings') NOT NULL default 'biblio'");
5996     $dbh->do("UPDATE import_batches SET record_type='auth' WHERE import_batch_id IN
5997                 (SELECT import_batch_id FROM import_records WHERE record_type='auth')");
5998
5999     print "Upgrade to $DBversion done (Added support for staging authorities)\n";
6000     SetVersion ($DBversion);
6001 }
6002
6003 $DBversion = "3.09.00.054";
6004 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6005     $dbh->do("ALTER TABLE aqorders CHANGE COLUMN gst gstrate DECIMAL(6,4)  DEFAULT NULL");
6006     print "Upgrade to $DBversion done (Change column name in aqorders gst --> gstrate)\n";
6007     SetVersion($DBversion);
6008 }
6009
6010 $DBversion = "3.09.00.055";
6011 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6012     $dbh->do("ALTER TABLE aqorders ADD discount float(6,4) DEFAULT NULL AFTER gstrate");
6013     print "Upgrade to $DBversion done (Add discount field in aqorders table)\n";
6014     SetVersion($DBversion);
6015 }
6016
6017 $DBversion ="3.09.00.056";
6018 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6019     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('AuthDisplayHierarchy','0','Display authority hierarchies','','YesNo')");
6020     print "Upgrade to $DBversion done (Add system preference AuthDisplayHierarchy)\n";
6021     SetVersion($DBversion);
6022 }
6023
6024 $DBversion = "3.09.00.057";
6025 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6026     $dbh->do("ALTER TABLE aqbasket ADD deliveryplace VARCHAR(10) default NULL AFTER basketgroupid;");
6027     $dbh->do("ALTER TABLE aqbasket ADD billingplace VARCHAR(10) default NULL AFTER deliveryplace;");
6028     print "Upgrade to $DBversion done (Bug 5356: Added billingplace, deliveryplace to the aqbasket table)\n";
6029     SetVersion($DBversion);
6030 }
6031
6032 $DBversion ="3.09.00.058";
6033 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6034     $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');");
6035     $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');");
6036     print "Upgrade to $DBversion done (Add Did You Mean? configuration)\n";
6037     SetVersion($DBversion);
6038 }
6039
6040 $DBversion ="3.09.00.059";
6041 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6042     $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');");
6043     print "Upgrade to $DBversion done (Add system preference BlockReturnOfWithdrawnItems)\n";
6044     SetVersion($DBversion);
6045 }
6046
6047 $DBversion = "3.09.00.060";
6048 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6049     $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')");
6050     print "Upgrade to $DBversion done (Added HoldsToPullStartDate syspref)\n";
6051     SetVersion($DBversion);
6052 }
6053
6054 $DBversion = "3.09.00.061";
6055 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6056     $dbh->do("UPDATE systempreferences set value=0 WHERE variable='OPACItemsResultsDisplay' AND value='statuses'");
6057     $dbh->do("UPDATE systempreferences set value=1 WHERE variable='OPACItemsResultsDisplay' AND value='itemdetails'");
6058     $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'");
6059     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";
6060     SetVersion ($DBversion);
6061 }
6062
6063 $DBversion = "3.09.00.062";
6064 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6065    $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='NoZebra'");
6066    $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='QueryRemoveStopwords'");
6067    print "Upgrade to $DBversion done (Disable obsolete NoZebra and QueryRemoveStopwords sysprefs)\n";
6068    SetVersion ($DBversion);
6069 }
6070
6071 $DBversion = "3.09.00.063";
6072 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6073     my $gst_booksellers = $dbh->selectcol_arrayref("SELECT DISTINCT(gstrate) FROM aqbooksellers");
6074     my $gist_syspref = C4::Context->preference("gist");
6075     # remove the undef values and construct and array with the syspref and the supplier values
6076     my @gstrates = map { defined $_ ? $_ : () } @$gst_booksellers;
6077     push @gstrates, split ('\|', $gist_syspref);
6078     # we want to compare integer (or float)
6079     $_ = $_ + 0 for @gstrates;
6080     use List::MoreUtils qw/uniq/;
6081     # remove duplicate values
6082     @gstrates = uniq sort @gstrates;
6083     my $new_syspref_value = join '|', @gstrates;
6084     # update the syspref with the new values
6085     my $sth = $dbh->prepare("UPDATE systempreferences set value=? WHERE variable='gist'");
6086     $sth->execute( $new_syspref_value );
6087
6088     print "Upgrade to $DBversion done (Bug 8832, Set the syspref gist with the existing values)\n";
6089     SetVersion ($DBversion);
6090 }
6091
6092 $DBversion = "3.09.00.064";
6093 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6094    $dbh->do('ALTER TABLE items ADD coded_location_qualifier varchar(10) default NULL AFTER itemcallnumber');
6095    print "Upgrade to $DBversion done (Bug 6428: Added coded_location_qualifier to the items table)\n";
6096    SetVersion ($DBversion);
6097 }
6098
6099 $DBversion = "3.09.00.065";
6100 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6101    $dbh->do('ALTER TABLE deleteditems ADD coded_location_qualifier varchar(10) default NULL AFTER itemcallnumber');
6102    print "Upgrade to $DBversion done (Bug 6428: Added coded_location_qualifier to the deleteditems table)\n";
6103    SetVersion ($DBversion);
6104 }
6105
6106 $DBversion = "3.09.00.066";
6107 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6108    $dbh->do("DELETE FROM systempreferences WHERE variable='DidYouMeanFromAuthorities'");
6109    print "Upgrade to $DBversion done (Bug 9107: remove DidYouMeanFromAuthorities syspref)\n";
6110    SetVersion ($DBversion);
6111 }
6112
6113 $DBversion = "3.09.00.067";
6114 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6115    $dbh->do("ALTER TABLE statistics CHANGE COLUMN ccode ccode varchar(10) NULL");
6116    print "Upgrade to $DBversion done (Bug 9064: statistics.ccode potentially wrongly defined)\n";
6117    SetVersion ($DBversion);
6118 }
6119
6120 $DBversion = "3.10.00.00";
6121 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6122    print "Upgrade to $DBversion done (release tag)\n";
6123    SetVersion ($DBversion);
6124 }
6125
6126 $DBversion = "3.11.00.001";
6127 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6128     $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')");
6129     print "Upgrade to $DBversion done (Bug 2832 - Add alphabet syspref)\n";
6130 }
6131
6132 $DBversion = "3.11.00.002";
6133 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6134     $dbh->do(q{
6135         DELETE from aqorders_items where ordernumber NOT IN (SELECT ordernumber FROM aqorders);
6136     });
6137     $dbh->do(q{
6138         ALTER TABLE aqorders_items
6139         ADD CONSTRAINT aqorders_items_ibfk_1 FOREIGN KEY (ordernumber) REFERENCES aqorders (ordernumber)
6140         ON DELETE CASCADE ON UPDATE CASCADE;
6141     });
6142     print "Upgrade to $DBversion done (Bug 9030: Add constraint on aqorders_items.ordernumber)\n";
6143     SetVersion ($DBversion);
6144 }
6145
6146 $DBversion = "3.11.00.003";
6147 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6148     $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')");
6149     print "Upgrade to $DBversion done (Bug 7189: Add system preference RefundLostItemFeeOnReturn)\n";
6150     SetVersion($DBversion);
6151 }
6152
6153 $DBversion = "3.11.00.004";
6154 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6155     $dbh->do(qq{
6156         ALTER TABLE subscription ADD COLUMN closed INT(1) NOT NULL DEFAULT 0 AFTER enddate;
6157     });
6158
6159     print "Upgrade to $DBversion done (Bug 8782: Add field subscription.closed)\n";
6160     SetVersion($DBversion);
6161 }
6162
6163 $DBversion = "3.11.00.005";
6164 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6165     $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;});
6166
6167     $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;});
6168
6169     $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;});
6170
6171     print "Upgrade to $DBversion done (Bug 7919: Display of values depending on the connexion library)\n";
6172     SetVersion($DBversion);
6173 }
6174
6175 $DBversion = "3.11.00.006";
6176 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6177     $dbh->do(q{
6178         UPDATE virtualshelves SET sortfield="copyrightdate" where sortfield="year";
6179     });
6180     print "Upgrade to $DBversion done (Bug 9167: Update the virtualshelves.sortfield column with 'copyrightdate' if needed)\n";
6181     SetVersion($DBversion);
6182 }
6183
6184 $DBversion = "3.11.00.007";
6185 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6186     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ar', 'language', 'de', 'Arabisch')");
6187     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hy', 'language', 'de', 'Armenisch')");
6188     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'bg', 'language', 'de', 'Bulgarisch')");
6189     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'zh', 'language', 'de', 'Chinesisch')");
6190     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'cs', 'language', 'de', 'Tschechisch')");
6191     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'da', 'language', 'de', 'Dänisch')");
6192     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nl', 'language', 'de', 'Niederländisch')");
6193     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'en', 'language', 'de', 'Englisch')");
6194     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fi', 'language', 'de', 'Finnisch')");
6195     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fr', 'language', 'de', 'Französisch')");
6196     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'lo', 'language', 'fr', 'Laotien')");
6197     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'lo', 'language', 'de', 'Laotisch')");
6198     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'el', 'language', 'de', 'Griechisch (Nach 1453)')");
6199     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'he', 'language', 'de', 'Hebräisch')");
6200     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hi', 'language', 'de', 'Hindi')");
6201     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hu', 'language', 'de', 'Ungarisch')");
6202     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'id', 'language', 'de', 'Indonesisch')");
6203     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'it', 'language', 'de', 'Italienisch')");
6204     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ja', 'language', 'de', 'Japanisch')");
6205     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ko', 'language', 'de', 'Koreanisch')");
6206     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'la', 'language', 'de', 'Latein')");
6207     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'gl', 'language', 'fr', 'Galicien')");
6208     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'gl', 'language', 'de', 'Galizisch')");
6209     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nb', 'language', 'de', 'Norwegisch bokm&#229;l')");
6210     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nn', 'language', 'de', 'Norwegisch nynorsk')");
6211     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fa', 'language', 'de', 'Persisch')");
6212     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'pl', 'language', 'de', 'Polnisch')");
6213     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'pt', 'language', 'de', 'Portugiesisch')");
6214     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ro', 'language', 'de', 'Rumänisch')");
6215     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ru', 'language', 'de', 'Russisch')");
6216     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sr', 'language', 'fr', 'Serbe')");
6217     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sr', 'language', 'de', 'Serbisch')");
6218     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'es', 'language', 'de', 'Spanisch')");
6219     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sv', 'language', 'de', 'Schwedisch')");
6220     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tet', 'language', 'fr', 'Tétoum')");
6221     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tet', 'language', 'de', 'Tetum')");
6222     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'th', 'language', 'de', 'Thailändisch')");
6223     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tr', 'language', 'de', 'Türkisch')");
6224     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'uk', 'language', 'de', 'Ukrainisch')");
6225     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ur', 'language', 'fr', 'Ourdou')");
6226     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ur', 'language', 'de', 'Urdu')");
6227     print "Upgrade to $DBversion done (Bug 9056: add German and a couple of French translations to language_descriptions)\n";
6228     SetVersion ($DBversion);
6229 }
6230
6231 $DBversion = "3.11.00.008";
6232 if (CheckVersion($DBversion)) {
6233     $dbh->do("
6234         CREATE TABLE IF NOT EXISTS `borrower_modifications` (
6235           `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6236           `verification_token` varchar(255) NOT NULL DEFAULT '',
6237           `borrowernumber` int(11) NOT NULL DEFAULT '0',
6238           `cardnumber` varchar(16) DEFAULT NULL,
6239           `surname` mediumtext,
6240           `firstname` text,
6241           `title` mediumtext,
6242           `othernames` mediumtext,
6243           `initials` text,
6244           `streetnumber` varchar(10) DEFAULT NULL,
6245           `streettype` varchar(50) DEFAULT NULL,
6246           `address` mediumtext,
6247           `address2` text,
6248           `city` mediumtext,
6249           `state` text,
6250           `zipcode` varchar(25) DEFAULT NULL,
6251           `country` text,
6252           `email` mediumtext,
6253           `phone` text,
6254           `mobile` varchar(50) DEFAULT NULL,
6255           `fax` mediumtext,
6256           `emailpro` text,
6257           `phonepro` text,
6258           `B_streetnumber` varchar(10) DEFAULT NULL,
6259           `B_streettype` varchar(50) DEFAULT NULL,
6260           `B_address` varchar(100) DEFAULT NULL,
6261           `B_address2` text,
6262           `B_city` mediumtext,
6263           `B_state` text,
6264           `B_zipcode` varchar(25) DEFAULT NULL,
6265           `B_country` text,
6266           `B_email` text,
6267           `B_phone` mediumtext,
6268           `dateofbirth` date DEFAULT NULL,
6269           `branchcode` varchar(10) DEFAULT NULL,
6270           `categorycode` varchar(10) DEFAULT NULL,
6271           `dateenrolled` date DEFAULT NULL,
6272           `dateexpiry` date DEFAULT NULL,
6273           `gonenoaddress` tinyint(1) DEFAULT NULL,
6274           `lost` tinyint(1) DEFAULT NULL,
6275           `debarred` date DEFAULT NULL,
6276           `debarredcomment` varchar(255) DEFAULT NULL,
6277           `contactname` mediumtext,
6278           `contactfirstname` text,
6279           `contacttitle` text,
6280           `guarantorid` int(11) DEFAULT NULL,
6281           `borrowernotes` mediumtext,
6282           `relationship` varchar(100) DEFAULT NULL,
6283           `ethnicity` varchar(50) DEFAULT NULL,
6284           `ethnotes` varchar(255) DEFAULT NULL,
6285           `sex` varchar(1) DEFAULT NULL,
6286           `password` varchar(30) DEFAULT NULL,
6287           `flags` int(11) DEFAULT NULL,
6288           `userid` varchar(75) DEFAULT NULL,
6289           `opacnote` mediumtext,
6290           `contactnote` varchar(255) DEFAULT NULL,
6291           `sort1` varchar(80) DEFAULT NULL,
6292           `sort2` varchar(80) DEFAULT NULL,
6293           `altcontactfirstname` varchar(255) DEFAULT NULL,
6294           `altcontactsurname` varchar(255) DEFAULT NULL,
6295           `altcontactaddress1` varchar(255) DEFAULT NULL,
6296           `altcontactaddress2` varchar(255) DEFAULT NULL,
6297           `altcontactaddress3` varchar(255) DEFAULT NULL,
6298           `altcontactstate` text,
6299           `altcontactzipcode` varchar(50) DEFAULT NULL,
6300           `altcontactcountry` text,
6301           `altcontactphone` varchar(50) DEFAULT NULL,
6302           `smsalertnumber` varchar(50) DEFAULT NULL,
6303           `privacy` int(11) DEFAULT NULL,
6304           PRIMARY KEY (`verification_token`,`borrowernumber`),
6305           KEY `verification_token` (`verification_token`),
6306           KEY `borrowernumber` (`borrowernumber`)
6307         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6308 ");
6309
6310     $dbh->do("
6311         INSERT INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES
6312         ('PatronSelfRegistration', '0', NULL, 'If enabled, patrons will be able to register themselves via the OPAC.', 'YesNo'),
6313         ('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'),
6314         ('PatronSelfRegistrationDefaultCategory', '', '', 'A patron registered via the OPAC will receive a borrower category code set in this system preference.', 'free'),
6315         ('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'),
6316         ('PatronSelfRegistrationBorrowerMandatoryField',  'surname|firstname', NULL ,  'Choose the mandatory fields for a patron''s account, when registering via the OPAC.',  'free'),
6317         ('PatronSelfRegistrationBorrowerUnwantedField',  '', NULL ,  'Name the fields you don''t want to display when registering a new patron via the OPAC.',  'free');
6318     ");
6319
6320     $dbh->do("
6321     INSERT INTO  letter ( `module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content` )
6322     VALUES ( 'members', 'OPAC_REG_VERIFY', '', 'Opac Self-Registration Verification Email', '1', 'Verify Your Account', 'Hello!
6323
6324     Your library account has been created. Please verify your email address by clicking this link to complete the signup process:
6325
6326     http://<<OPACBaseURL>>/cgi-bin/koha/opac-registration-verify.pl?token=<<borrower_modifications.verification_token>>
6327
6328     If you did not initiate this request, you may safely ignore this one-time message. The request will expire shortly.'
6329     )");
6330
6331     print "Upgrade to $DBversion done (Bug 7067: Add Patron Self Registration)\n";
6332     SetVersion ($DBversion);
6333 }
6334
6335 $DBversion = "3.11.00.009";
6336 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6337     $dbh->do("
6338         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
6339         ('SeparateHoldings', '0', 'Separate current branch holdings from other holdings', NULL, 'YesNo'),
6340         ('SeparateHoldingsBranch', 'homebranch', 'Branch used to separate holdings', 'homebranch|holdingbranch', 'Choice'),
6341         ('OpacSeparateHoldings', '0', 'Separate current branch holdings from other holdings (OPAC)', NULL, 'YesNo'),
6342         ('OpacSeparateHoldingsBranch', 'homebranch', 'Branch used to separate holdings (OPAC)', 'homebranch|holdingbranch', 'Choice')
6343     ");
6344
6345     print "Upgrade to $DBversion done (Bug 7674: Add systempreferences SeparateHoldings, SeparateHoldingsBranch, OpacSeparateHoldings and OpacSeparateHoldingsBranch) \n";
6346     SetVersion ($DBversion);
6347 }
6348
6349 $DBversion = "3.11.00.010";
6350 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6351     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('RenewalSendNotice', '0', '', NULL, 'YesNo')");
6352     $dbh->do(q{
6353         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
6354         ('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>>.');
6355     });
6356     print "Upgrade to $DBversion done (Bug 9151 - Renewal notice according to patron alert preferences)\n";
6357     SetVersion($DBversion);
6358 }
6359
6360 $DBversion = "3.11.00.011";
6361 if ( CheckVersion($DBversion) ) {
6362    $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');");
6363    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('HTML5MediaExtensions','webm|ogg|ogv|oga|vtt','Media file extensions','','free');");
6364    print "Upgrade to $DBversion done (Bug 8377: Add HTML5MediaEnabled and HTML5MediaExtensions sysprefs)\n";
6365    SetVersion ($DBversion);
6366 }
6367
6368 $DBversion = "3.11.00.012";
6369 if ( CheckVersion($DBversion) ) {
6370     $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')");
6371     print "Upgrade to $DBversion done (Bug 9206: Only allow place holds in records that the patron don't have in his possession)\n";
6372     SetVersion($DBversion);
6373 }
6374
6375 $DBversion = "3.11.00.013";
6376 if ( CheckVersion($DBversion) ) {
6377     $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')");
6378     print "Upgrade to $DBversion done (Bug 9162 - Add a system preference to set which notes fields appears on title notes/description separator)\n";
6379     SetVersion($DBversion);
6380 }
6381
6382 $DBversion = "3.11.00.014";
6383 if ( CheckVersion($DBversion) ) {
6384    $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' )");
6385    $dbh->do("INSERT INTO systempreferences ( variable, value, explanation, type ) VALUES ( 'SCOUserJS', '', 'Define custom javascript for inclusion in the SCO module', 'free' )");
6386    print "Upgrade to $DBversion done (Bug 9009: Add SCOUserCSS and SCOUserJS sysprefs)\n";
6387 }
6388
6389 $DBversion = "3.11.00.015";
6390 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6391     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('RentalsInNoissuesCharge', '1', 'Rental charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
6392     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('ManInvInNoissuesCharge', '1', 'MANUAL_INV charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
6393     print "Upgrade to $DBversion done (Add sysprefs RentalsInNoissuesCharge and ManInvInNoissuesCharge.)\n";
6394     SetVersion($DBversion);
6395 }
6396
6397 $DBversion = "3.11.00.016";
6398 if ( CheckVersion($DBversion) ) {
6399    $dbh->do(q{
6400         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";
6401         });
6402    $dbh->do(q{
6403         UPDATE userflags SET flagdesc="Edit Authorities" where flagdesc="Allow to edit authorities";
6404         });
6405    $dbh->do(q{
6406         UPDATE userflags SET flagdesc="Allow access to the reports module" where flagdesc="Allow to access to the reports module";
6407         });
6408    $dbh->do(q{
6409         UPDATE userflags SET flagdesc="Set library management parameters (deprecated)" where flagdesc="Set library management parameters";
6410         });
6411    $dbh->do(q{
6412         UPDATE userflags SET flagdesc="Manage serial subscriptions" where flagdesc="Allow to manage serials subscriptions";
6413         });
6414    $dbh->do(q{
6415         UPDATE userflags SET flagdesc="Manage patrons fines and fees" where flagdesc="Update borrower charges";
6416         });
6417    $dbh->do(q{
6418         UPDATE userflags SET flagdesc="Check out and check in items" where flagdesc="Circulate books";
6419         });
6420    $dbh->do(q{
6421         UPDATE userflags SET flagdesc="Manage Koha system settings (Administration panel)" where flagdesc="Set Koha system parameters";
6422         });
6423    $dbh->do(q{
6424         UPDATE userflags SET flagdesc="Add or modify patrons" where flagdesc="Add or modify borrowers";
6425         });
6426    $dbh->do(q{
6427         UPDATE userflags SET flagdesc="Use all tools (expand for granular tools permissions)" where flagdesc="Use tools (export, import, barcodes)";
6428         });
6429    $dbh->do(q{
6430         UPDATE userflags SET flagdesc="Allow staff members to modify permissions for other staff members" where flagdesc="Set user permissions";
6431         });
6432    $dbh->do(q{
6433         UPDATE permissions SET description="Perform batch modification of patrons" where description="Perform batch modifivation of patrons";
6434         });
6435
6436    print "Upgrade to $DBversion done (Bug 9382 (updated with bug 9745) - refresh permission descriptions to make more sense)\n";
6437    SetVersion ($DBversion);
6438 }
6439
6440 $DBversion ="3.11.00.017";
6441 if ( CheckVersion($DBversion) ) {
6442     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksReviews','0','Display book review snippets from IDreamBooks.com','','YesNo');");
6443     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksReadometer','0','Display Readometer from IDreamBooks.com','','YesNo');");
6444     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksResults','0','Display IDreamBooks.com rating in search results','','YesNo');");
6445     print "Upgrade to $DBversion done (Add IDreamBooks enhanced content)\n";
6446     SetVersion($DBversion);
6447 }
6448
6449 $DBversion = "3.11.00.018";
6450 if ( CheckVersion($DBversion) ) {
6451    $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')");
6452    $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')");
6453    print "Upgrade to $DBversion done (Bug 9395: Problem with callnumber and standard number search in OPAC and Staff Client)\n";
6454    SetVersion ($DBversion);
6455 }
6456
6457 $DBversion = "3.11.00.019";
6458 if ( CheckVersion($DBversion) ) {
6459     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('UNIMARCAuthorityField100', 'afrey50      ba0', NULL, NULL, 'Textarea')");
6460     print "Upgrade to $DBversion done (Bug 9145 - Add syspref UNIMARCAuthorityField100)\n";
6461     SetVersion ($DBversion);
6462 }
6463
6464 $DBversion = "3.11.00.020";
6465 if ( CheckVersion($DBversion) ) {
6466     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UNIMARCField100Language', 'fre','UNIMARC field 100 default language',NULL,'short')");
6467     print "Upgrade to $DBversion done (Bug 8347 - Koha forces UNIMARC 100 field code language to 'fre')\n";
6468     SetVersion($DBversion);
6469 }
6470
6471 $DBversion ="3.11.00.021";
6472 if ( CheckVersion($DBversion) ) {
6473     $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');");
6474     print "Upgrade to $DBversion done (Bug 5888 - Subject search pop-up for the OPAC)\n";
6475     SetVersion($DBversion);
6476 }
6477
6478 $DBversion = "3.11.00.022";
6479 if ( CheckVersion($DBversion) ) {
6480     $dbh->do(
6481 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('Persona',0,'Use Mozilla Persona for login','','YesNo')"
6482     );
6483     print "Upgrade to $DBversion done (Bug 9587 - Allow login via Persona)\n";
6484     SetVersion($DBversion);
6485 }
6486
6487 $DBversion = "3.11.00.023";
6488 if ( CheckVersion($DBversion) ) {
6489     $dbh->do("UPDATE z3950servers SET host = 'lx2.loc.gov', port = 210, db = 'LCDB', syntax = 'USMARC', encoding = 'utf8' WHERE name = 'LIBRARY OF CONGRESS'");
6490     print "Upgrade to $DBversion done (Bug 9520 - Update default LOC Z39.50 target)\n";
6491     SetVersion($DBversion);
6492 }
6493
6494 $DBversion = "3.11.00.024";
6495 if ( CheckVersion($DBversion) ) {
6496     $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');");
6497     print "Upgrade to $DBversion done (Bug 5079: Add OpacItemLocation syspref)\n";
6498     SetVersion ($DBversion);
6499 }
6500
6501 $DBversion = "3.11.00.025";
6502 if ( CheckVersion($DBversion) ) {
6503     $dbh->do(
6504         "CREATE TABLE linktracker (
6505   id int(11) NOT NULL AUTO_INCREMENT,
6506   biblionumber int(11) DEFAULT NULL,
6507   itemnumber int(11) DEFAULT NULL,
6508   borrowernumber int(11) DEFAULT NULL,
6509   url text,
6510   timeclicked datetime DEFAULT NULL,
6511   PRIMARY KEY (id),
6512   KEY bibidx (biblionumber),
6513   KEY itemidx (itemnumber),
6514   KEY borridx (borrowernumber),
6515   KEY dateidx (timeclicked)
6516     ) ENGINE=InnoDB DEFAULT CHARSET=utf8;"
6517     );
6518     $dbh->do( "
6519   INSERT INTO systempreferences (variable,value,explanation,options,type)
6520   VALUES('TrackClicks','0','Track links clicked',NULL,'Integer')" );
6521     print
6522 "Upgrade to $DBversion done (Adds feature Bug 8917, the ability to track links clicked)\n";
6523     SetVersion($DBversion);
6524 }
6525
6526 $DBversion = "3.11.00.026";
6527 if ( CheckVersion($DBversion) ) {
6528     $dbh->do(qq{
6529         ALTER TABLE import_records ADD INDEX batch_id_record_type ( import_batch_id, record_type );
6530     });
6531     print "Upgrade to $DBversion done (Bug 9207: Add new index batch_id_record_type to import_records)\n";
6532     SetVersion($DBversion);
6533 }
6534
6535 $DBversion = "3.11.00.027";
6536 if ( CheckVersion($DBversion) ) {
6537     $dbh->do(q{
6538         INSERT INTO permissions ( module_bit, code, description )
6539         VALUES  ( '1', 'overdues_report', 'Execute overdue items report' )
6540     });
6541     # add new permission for users with all report permissions and circulation remaining permission
6542     $dbh->do(q{
6543         INSERT INTO user_permissions (borrowernumber, module_bit, code)
6544         SELECT user_permissions.borrowernumber, 1, 'overdues_report'
6545         FROM user_permissions
6546         LEFT JOIN borrowers USING(borrowernumber)
6547         WHERE borrowers.flags & (1 << 16)
6548         AND user_permissions.code = 'circulate_remaining_permissions'
6549     });
6550     print "Upgrade to $DBversion done ( Add circ permission overdues_report )\n";
6551     SetVersion($DBversion);
6552 }
6553
6554 $DBversion = "3.11.00.028";
6555 if ( CheckVersion($DBversion) ) {
6556     $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'    );");
6557     print "Upgrade to $DBversion done (Bug 9756 - Patron self registration missing the system preference PatronSelfRegistrationAdditionalInstructions)\n";
6558     SetVersion($DBversion);
6559 }
6560
6561 $DBversion = "3.11.00.029";
6562 if (CheckVersion($DBversion)) {
6563     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UseQueryParser', '0', 'If enabled, try to use QueryParser for queries.', NULL, 'YesNo')");
6564     print "Upgrade to $DBversion done (Bug 9239: Make it possible for Koha to use QueryParser)\n";
6565     SetVersion ($DBversion);
6566 }
6567
6568 $DBversion = "3.11.00.030";
6569 if ( CheckVersion($DBversion) ) {
6570     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('FinesIncludeGracePeriod','1','If enabled, fines calculations will include the grace period.',NULL,'YesNo');");
6571     print "Upgrade to $DBversion done (Add system preference FinesIncludeGracePeriod)\n";
6572     SetVersion($DBversion);
6573 }
6574
6575 $DBversion = "3.11.00.100";
6576 if ( CheckVersion($DBversion) ) {
6577     print "Upgrade to $DBversion done (3.12-alpha release)\n";
6578     SetVersion ($DBversion);
6579 }
6580
6581 $DBversion = "3.11.00.101";
6582 if ( CheckVersion($DBversion) ) {
6583    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('UNIMARCAuthorsFacetsSeparator',', ', 'UNIMARC authors facets separator', NULL, 'short')");
6584    print "Upgrade to $DBversion done (Bug 9341: Problem with UNIMARC authors facets)\n";
6585    SetVersion ($DBversion);
6586 }
6587
6588 $DBversion = "3.11.00.102";
6589 if ( CheckVersion($DBversion) ) {
6590     $dbh->do(q{
6591         DELETE FROM systempreferences WHERE variable='NoZebra'
6592     });
6593     $dbh->do(q{
6594         DELETE FROM systempreferences WHERE variable='QueryRemoveStopwords'
6595     });
6596     print "Upgrade to $DBversion done (Remove deprecated NoZebra and QueryRemoveStopwords sysprefs)\n";
6597     SetVersion($DBversion);
6598 }
6599
6600 $DBversion = "3.11.00.103";
6601 if ( CheckVersion($DBversion) ) {
6602     $dbh->do("DELETE FROM systempreferences WHERE variable = 'insecure';");
6603     print "Upgrade to $DBversion done (Bug 9827 - Remove 'insecure' system preference)\n";
6604     SetVersion($DBversion);
6605 }
6606
6607 $DBversion = "3.11.00.104";
6608 if ( CheckVersion($DBversion) ) {
6609     print "Upgrade to $DBversion done (3.12-alpha2 release)\n";
6610     SetVersion ($DBversion);
6611 }
6612
6613 $DBversion = "3.11.00.105";
6614 if ( CheckVersion($DBversion) ) {
6615     if ( C4::Context->preference("marcflavour") eq 'MARC21' ) {
6616         $sth = $dbh->prepare(
6617 "SELECT frameworkcode FROM marc_tag_structure WHERE tagfield = '029'"
6618         );
6619         $sth->execute;
6620         my $frameworkcodes = $sth->fetchall_hashref('frameworkcode');
6621
6622         for my $frameworkcode ( keys %$frameworkcodes ) {
6623             $dbh->do( "
6624     INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian,
6625     libopac, repeatable, mandatory, kohafield, tab, authorised_value, authtypecode,
6626     value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
6627     ('029', 'a', 'OCLC library identifier', 'OCLC library identifier', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6628     ('029', 'b', 'System control number', 'System control number', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6629     ('029', 'c', 'OAI set name', 'OAI set name', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6630     ('029', 't', 'Content type identifier', 'Content type identifier', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL)
6631    " );
6632         }
6633
6634         for my $tag ( '863', '864', '865' ) {
6635             $sth = $dbh->prepare(
6636 "SELECT frameworkcode FROM marc_tag_structure WHERE tagfield = '$tag'"
6637             );
6638             $sth->execute;
6639             my $frameworkcodes = $sth->fetchall_hashref('frameworkcode');
6640
6641             for my $frameworkcode ( keys %$frameworkcodes ) {
6642                 $dbh->do( "
6643      INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian,
6644      libopac, repeatable, mandatory, kohafield, tab, authorised_value, authtypecode,
6645      value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
6646      ('$tag', '6', 'Linkage', 'Linkage', 0, 0, '', 8, '', '', '', NULL, 5, '$frameworkcode', '', '', NULL),
6647      ('$tag', '8', 'Field link and sequence number', 'Field link and sequence number', 0, 0, '', 8, '', '', '', NULL, 5, '$frameworkcode', '', '', NULL),
6648      ('$tag', 'a', 'First level of enumeration', 'First level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6649      ('$tag', 'b', 'Second level of enumeration', 'Second level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6650      ('$tag', 'c', 'Third level of enumeration', 'Third level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6651      ('$tag', 'd', 'Fourth level of enumeration', 'Fourth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6652      ('$tag', 'e', 'Fifth level of enumeration', 'Fifth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6653      ('$tag', 'f', 'Sixth level of enumeration', 'Sixth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6654      ('$tag', 'g', 'Alternative numbering scheme, first level of enumeration', 'Alternative numbering scheme, first level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6655      ('$tag', 'h', 'Alternative numbering scheme, second level of enumeration', 'Alternative numbering scheme, second level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6656      ('$tag', 'i', 'First level of chronology', 'First level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6657      ('$tag', 'j', 'Second level of chronology', 'Second level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6658      ('$tag', 'k', 'Third level of chronology', 'Third level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6659      ('$tag', 'l', 'Fourth level of chronology', 'Fourth level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6660      ('$tag', 'm', 'Alternative numbering scheme, chronology', 'Alternative numbering scheme, chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6661      ('$tag', 'n', 'Converted Gregorian year', 'Converted Gregorian year', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6662      ('$tag', 'o', 'Type of unit', 'Type of unit', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6663      ('$tag', 'p', 'Piece designation', 'Piece designation', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6664      ('$tag', 'q', 'Piece physical condition', 'Piece physical condition', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6665      ('$tag', 's', 'Copyright article-fee code', 'Copyright article-fee code', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6666      ('$tag', 't', 'Copy number', 'Copy number', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6667      ('$tag', 'v', 'Issuing date', 'Issuing date', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6668      ('$tag', 'w', 'Break indicator', 'Break indicator', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6669      ('$tag', 'x', 'Nonpublic note', 'Nonpublic note', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6670      ('$tag', 'z', 'Public note', 'Public note', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL)
6671     " );
6672             }
6673         }
6674     }
6675     print "Upgrade to $DBversion done (Bug 9353: Missing subfields on MARC21 frameworks)\n";
6676     SetVersion($DBversion);
6677 }
6678
6679
6680 $DBversion = "3.11.00.106";
6681 if ( CheckVersion($DBversion) ) {
6682     $dbh->do("INSERT INTO userflags (bit, flag, flagdesc, defaulton) VALUES ('19', 'plugins', 'Koha plugins', '0')");
6683     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
6684               ('19', 'manage', 'Manage plugins ( install / uninstall )'),
6685               ('19', 'tool', 'Use tool plugins'),
6686               ('19', 'report', 'Use report plugins'),
6687               ('19', 'configure', 'Configure plugins')
6688             ");
6689     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UseKohaPlugins','0','Enable or disable the ability to use Koha Plugins.','','YesNo')");
6690
6691     $dbh->do("
6692         CREATE TABLE IF NOT EXISTS plugin_data (
6693             plugin_class varchar(255) NOT NULL,
6694             plugin_key varchar(255) NOT NULL,
6695             plugin_value text,
6696             PRIMARY KEY (plugin_class,plugin_key)
6697         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6698     ");
6699
6700     print "Upgrade to $DBversion done (Bug 7804: Added plugin system.)\n";
6701     SetVersion($DBversion);
6702 }
6703
6704 $DBversion = "3.11.00.107";
6705 if ( CheckVersion($DBversion) ) {
6706    $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('TimeFormat','24hr','12hr|24hr','Defines the global time format for visual output.','Choice')");
6707    print "Upgrade to $DBversion done (Bug 9014: Add syspref TimeFormat)\n";
6708    SetVersion ($DBversion);
6709 }
6710
6711 $DBversion = "3.11.00.108";
6712 if ( CheckVersion($DBversion) ) {
6713     $dbh->do("ALTER TABLE action_logs CHANGE timestamp timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;");
6714     $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');");
6715     $dbh->do("ALTER TABLE action_logs CHANGE timestamp timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;");
6716     print "Upgrade to $DBversion done (Bug 7241: Fix on circulation logs)\n";
6717     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";
6718     SetVersion($DBversion);
6719 }
6720
6721 $DBversion = "3.11.00.109";
6722 if ( CheckVersion($DBversion) ) {
6723    $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');");
6724    print "Upgrade to $DBversion done (Bug 9403: Add DisplayIconsXSLT)\n";
6725    SetVersion ($DBversion);
6726 }
6727
6728 $DBversion = "3.11.00.110";
6729 if ( CheckVersion($DBversion) ) {
6730     $dbh->do("ALTER TABLE pending_offline_operations CHANGE barcode barcode VARCHAR( 20 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
6731     $dbh->do("ALTER TABLE pending_offline_operations ADD amount DECIMAL( 28, 6 ) NULL DEFAULT NULL");
6732     print "Upgrade to $DBversion done (Bug 8220 - Allow koc uploads to go to process queue)\n";
6733     SetVersion ($DBversion);
6734 }
6735
6736 $DBversion = "3.11.00.111";
6737 if ( CheckVersion($DBversion) ) {
6738     my $sth = $dbh->prepare("
6739         SELECT module, code, branchcode, content
6740         FROM letter
6741         WHERE content LIKE '%<fine>%'
6742     ");
6743     $sth->execute;
6744     my $sth_update = $dbh->prepare("UPDATE letter SET content = ? WHERE module = ? AND code = ? AND branchcode = ?");
6745     while(my $row = $sth->fetchrow_hashref){
6746         $row->{content} =~ s/<fine>\w+<\/fine>/<<items.fine>>/;
6747         $sth_update->execute($row->{content}, $row->{module}, $row->{code}, $row->{branchcode});
6748     }
6749     print "Upgrade to $DBversion done (use new <<items.fine>> syntax in notices)\n";
6750     SetVersion($DBversion);
6751 }
6752
6753 $DBversion = "3.11.00.112";
6754 if ( CheckVersion($DBversion) ) {
6755     $dbh->do(qq{
6756         ALTER TABLE issuingrules ADD COLUMN renewalperiod int(4) DEFAULT NULL AFTER renewalsallowed
6757     });
6758     $dbh->do(qq{
6759         UPDATE issuingrules SET renewalperiod = issuelength
6760     });
6761     print "Upgrade to $DBversion done (Bug 8365: Add colum issuingrules.renewalperiod)\n";
6762     SetVersion ($DBversion);
6763 }
6764
6765 $DBversion = "3.11.00.113";
6766 if ( CheckVersion($DBversion) ) {
6767     $dbh->do(q{
6768         ALTER TABLE branchcategories ADD show_in_pulldown BOOLEAN NOT NULL DEFAULT '0',
6769         ADD INDEX ( show_in_pulldown )
6770     });
6771     print "Upgrade to $DBversion done (Bug 9257 - Add groups to normal search pulldown)\n";
6772     SetVersion ($DBversion);
6773 }
6774
6775 $DBversion = "3.11.00.115";
6776 if ( CheckVersion($DBversion) ) {
6777     $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')");
6778     $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')");
6779     print "Upgrade to $DBversion done (Bug 7740: Add syspref HighlightOwnItemsOnOPAC)\n";
6780     SetVersion ($DBversion);
6781 }
6782
6783 $DBversion = "3.11.00.116";
6784 if ( CheckVersion($DBversion) ) {
6785     $dbh->do(q{ALTER TABLE aqorders DROP COLUMN serialid;});
6786     $dbh->do(q{ALTER TABLE aqorders DROP COLUMN subscription;});
6787     $dbh->do(q{ALTER TABLE aqorders ADD COLUMN subscriptionid INT(11) DEFAULT NULL;});
6788     $dbh->do(q{ALTER TABLE aqorders ADD CONSTRAINT aqorders_subscriptionid FOREIGN KEY (subscriptionid) REFERENCES subscription (subscriptionid) ON DELETE CASCADE ON UPDATE CASCADE;});
6789     $dbh->do(q{ALTER TABLE subscription ADD COLUMN reneweddate DATE DEFAULT NULL;});
6790     print "Upgrade to $DBversion done (Bug 5343: table aqorders: DROP serialid and subscription fields and ADD subscriptionid, table subscription: ADD reneweddate)\n";
6791     SetVersion ($DBversion);
6792 }
6793
6794 $DBversion = "3.11.00.200";
6795 if ( CheckVersion($DBversion) ) {
6796     print "Upgrade to $DBversion done (3.12-beta1 release)\n";
6797     SetVersion ($DBversion);
6798 }
6799
6800 $DBversion = "3.11.00.201";
6801 if ( CheckVersion($DBversion) ) {
6802     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'BIBSYS' AND host LIKE 'z3950.bibsys.no'");
6803     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'NORBOK' AND host LIKE 'z3950.nb.no'");
6804     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'SAMBOK' AND host LIKE 'z3950.nb.no'");
6805     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'DEICHMAN' AND host like 'z3950.deich.folkebibl.no'");
6806     print "Upgrade to $DBversion done (Bug 9498 - Update encoding for Norwegian sample Z39.50 servers)\n";
6807     SetVersion($DBversion);
6808 }
6809
6810 $DBversion = "3.11.00.202";
6811 if ( CheckVersion($DBversion) ) {
6812    $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ca', 'language', 'Catalan','2013-01-12' )");
6813    $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'ca','cat')");
6814    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'es', 'Catalán')");
6815    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'en', 'Catalan')");
6816    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'fr', 'Catalan')");
6817    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'ca', 'Català')");
6818    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'de', 'Katalanisch')");
6819    print "Upgrade to $DBversion done (Bug 9381: Add Catalan laguage)\n";
6820    SetVersion ($DBversion);
6821 }
6822
6823 $DBversion = "3.11.00.203";
6824 if ( CheckVersion($DBversion) ) {
6825     $dbh->do(q{ALTER TABLE suggestions CHANGE COLUMN title title VARCHAR(255) DEFAULT NULL;});
6826     print "Upgrade to $DBversion done (Bug 2046 - increasing title column length for suggestions)\n";
6827     SetVersion ($DBversion);
6828 }
6829
6830 $DBversion = "3.11.00.300";
6831 if ( CheckVersion($DBversion) ) {
6832     print "Upgrade to $DBversion done (3.12-beta3 release)\n";
6833     SetVersion ($DBversion);
6834 }
6835
6836 $DBversion = "3.11.00.301";
6837 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6838     #issues
6839     $dbh->do(q{
6840         ALTER TABLE `issues`
6841             ADD KEY `itemnumber_idx` (`itemnumber`),
6842             ADD KEY `branchcode_idx` (`branchcode`),
6843             ADD KEY `issuingbranch_idx` (`issuingbranch`)
6844     });
6845     $dbh->do(q{
6846         ALTER TABLE `old_issues`
6847             ADD KEY `branchcode_idx` (`branchcode`),
6848             ADD KEY `issuingbranch_idx` (`issuingbranch`)
6849     });
6850     #items
6851     $dbh->do(q{
6852         ALTER TABLE `items` ADD KEY `itype_idx` (`itype`)
6853     });
6854     $dbh->do(q{
6855         ALTER TABLE `deleteditems` ADD KEY `itype_idx` (`itype`)
6856     });
6857     # biblioitems
6858     $dbh->do(q{
6859         ALTER TABLE `biblioitems` ADD KEY `itemtype_idx` (`itemtype`)
6860     });
6861     $dbh->do(q{
6862         ALTER TABLE `deletedbiblioitems` ADD KEY `itemtype_idx` (`itemtype`)
6863     });
6864     # statistics
6865     $dbh->do(q{
6866         ALTER TABLE `statistics`
6867             ADD KEY `branch_idx` (`branch`),
6868             ADD KEY `proccode_idx` (`proccode`),
6869             ADD KEY `type_idx` (`type`),
6870             ADD KEY `usercode_idx` (`usercode`),
6871             ADD KEY `itemnumber_idx` (`itemnumber`),
6872             ADD KEY `itemtype_idx` (`itemtype`),
6873             ADD KEY `borrowernumber_idx` (`borrowernumber`),
6874             ADD KEY `associatedborrower_idx` (`associatedborrower`),
6875             ADD KEY `ccode_idx` (`ccode`)
6876     });
6877
6878     print "Upgrade to $DBversion done (Bug 9681: Add some database indexes)\n";
6879     SetVersion($DBversion);
6880 }
6881
6882 $DBversion = "3.12.00.000";
6883 if ( CheckVersion($DBversion) ) {
6884     print "Upgrade to $DBversion done (3.12.0 release)\n";
6885     SetVersion ($DBversion);
6886 }
6887
6888 $DBversion = '3.13.00.000';
6889 if ( CheckVersion($DBversion) ) {
6890     print "Upgrade to $DBversion done (start the journey to Koha Pi)\n";
6891     SetVersion ($DBversion);
6892 }
6893
6894 $DBversion = "3.13.00.001";
6895 if ( CheckVersion($DBversion) ) {
6896     $dbh->do("INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('UseCourseReserves', '0', NULL, 'Enable the course reserves feature.', 'YesNo')");
6897     $dbh->do("INSERT INTO userflags (bit,flag,flagdesc,defaulton) VALUES ('18','coursereserves','Course Reserves','0')");
6898     $dbh->do("
6899 CREATE TABLE `courses` (
6900   `course_id` int(11) NOT NULL AUTO_INCREMENT,
6901   `department` varchar(20) DEFAULT NULL,
6902   `course_number` varchar(255) DEFAULT NULL,
6903   `section` varchar(255) DEFAULT NULL,
6904   `course_name` varchar(255) DEFAULT NULL,
6905   `term` varchar(20) DEFAULT NULL,
6906   `staff_note` mediumtext,
6907   `public_note` mediumtext,
6908   `students_count` varchar(20) DEFAULT NULL,
6909   `enabled` enum('yes','no') NOT NULL DEFAULT 'yes',
6910   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6911    PRIMARY KEY (`course_id`)
6912 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6913     ");
6914
6915     $dbh->do("
6916 CREATE TABLE `course_instructors` (
6917   `course_id` int(11) NOT NULL,
6918   `borrowernumber` int(11) NOT NULL,
6919   PRIMARY KEY (`course_id`,`borrowernumber`),
6920   KEY `borrowernumber` (`borrowernumber`)
6921 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6922     ");
6923
6924     $dbh->do("
6925 ALTER TABLE `course_instructors`
6926   ADD CONSTRAINT `course_instructors_ibfk_2` FOREIGN KEY (`course_id`) REFERENCES `courses` (`course_id`),
6927   ADD CONSTRAINT `course_instructors_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE;
6928     ");
6929
6930     $dbh->do("
6931 CREATE TABLE `course_items` (
6932   `ci_id` int(11) NOT NULL AUTO_INCREMENT,
6933   `itemnumber` int(11) NOT NULL,
6934   `itype` varchar(10) DEFAULT NULL,
6935   `ccode` varchar(10) DEFAULT NULL,
6936   `holdingbranch` varchar(10) DEFAULT NULL,
6937   `location` varchar(80) DEFAULT NULL,
6938   `enabled` enum('yes','no') NOT NULL DEFAULT 'no',
6939   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6940    PRIMARY KEY (`ci_id`),
6941    UNIQUE KEY `itemnumber` (`itemnumber`),
6942    KEY `holdingbranch` (`holdingbranch`)
6943 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6944     ");
6945
6946     $dbh->do("
6947 ALTER TABLE `course_items`
6948   ADD CONSTRAINT `course_items_ibfk_2` FOREIGN KEY (`holdingbranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
6949   ADD CONSTRAINT `course_items_ibfk_1` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE;
6950 ");
6951
6952     $dbh->do("
6953 CREATE TABLE `course_reserves` (
6954   `cr_id` int(11) NOT NULL AUTO_INCREMENT,
6955   `course_id` int(11) NOT NULL,
6956   `ci_id` int(11) NOT NULL,
6957   `staff_note` mediumtext,
6958   `public_note` mediumtext,
6959   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6960    PRIMARY KEY (`cr_id`),
6961    UNIQUE KEY `pseudo_key` (`course_id`,`ci_id`),
6962    KEY `course_id` (`course_id`)
6963 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6964 ");
6965
6966     $dbh->do("
6967 ALTER TABLE `course_reserves`
6968   ADD CONSTRAINT `course_reserves_ibfk_1` FOREIGN KEY (`course_id`) REFERENCES `courses` (`course_id`);
6969     ");
6970
6971     $dbh->do("
6972 INSERT INTO permissions (module_bit, code, description) VALUES
6973   (18, 'manage_courses', 'Add, edit and delete courses'),
6974   (18, 'add_reserves', 'Add course reserves'),
6975   (18, 'delete_reserves', 'Remove course reserves')
6976 ;
6977     ");
6978
6979
6980     print "Upgrade to $DBversion done (Add Course Reserves ( system preference UseCourseReserves ))\n";
6981     SetVersion($DBversion);
6982 }
6983
6984 $DBversion = "3.13.00.002";
6985 if ( CheckVersion($DBversion) ) {
6986    $dbh->do("UPDATE systempreferences SET variable = 'IndependentBranches' WHERE variable = 'IndependantBranches'");
6987    print "Upgrade to $DBversion done (Bug 10080 - Change system pref IndependantBranches to IndependentBranches)\n";
6988    SetVersion ($DBversion);
6989 }
6990
6991 $DBversion = '3.13.00.003';
6992 if ( CheckVersion($DBversion) ) {
6993     $dbh->do("ALTER TABLE serial DROP itemnumber");
6994     print "Upgrade to $DBversion done (Bug 7718 - Remove itemnumber column from serials table)\n";
6995     SetVersion($DBversion);
6996 }
6997
6998 $DBversion = "3.13.00.004";
6999 if(CheckVersion($DBversion)) {
7000     $dbh->do(
7001 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacShowHoldNotes',0,'Show hold notes on OPAC','','YesNo')"
7002     );
7003     print "Upgrade to $DBversion done (Bug 9722: Allow users to add notes when placing a hold in OPAC)\n";
7004     SetVersion($DBversion);
7005 }
7006
7007 $DBversion = "3.13.00.005";
7008 if(CheckVersion($DBversion)) {
7009     my $intra= C4::Context->preference("intranetstylesheet");
7010     #if this pref is not blank or starting with http, https or / [root], then
7011     #add an additional / to the front
7012     if($intra && $intra !~ /^(\/|https?)/) {
7013         $dbh->do("UPDATE systempreferences SET value=? WHERE variable=?",
7014             undef,('/'.$intra,"intranetstylesheet"));
7015         print "WARNING: Your system preference intranetstylesheet has been prefixed with a slash to make it an absolute path.\n";
7016     }
7017     print "Upgrade to $DBversion done (Bug 10052: Make intranetstylesheet and intranetcolorstylesheet behave exactly like their opac counterparts)\n";
7018     SetVersion ($DBversion);
7019 }
7020
7021 $DBversion = "3.13.00.006";
7022 if ( CheckVersion($DBversion) ) {
7023     $dbh->do(
7024         q{
7025 INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('CalculateFinesOnReturn','1','Switch to control if overdue fines are calculated on return or not', '', 'YesNo');
7026 }
7027     );
7028     print
7029 "Upgrade to $DBversion done (Bug 10120 - Fines on item return controlled by a systempreference)\n";
7030     SetVersion($DBversion);
7031 }
7032
7033 $DBversion = "3.13.00.007";
7034 if ( CheckVersion($DBversion) ) {
7035     $dbh->do("UPDATE systempreferences SET variable='OpacHoldNotes' WHERE variable='OpacShowHoldNotes'");
7036     print "Upgrade to $DBversion done (Bug 10343: Rename OpacShowHoldNotes to OpacHoldNotes)\n";
7037     SetVersion($DBversion);
7038 }
7039
7040 $DBversion = "3.13.00.008";
7041 if ( CheckVersion($DBversion) ) {
7042     $dbh->do("
7043 CREATE TABLE IF NOT EXISTS borrower_files (
7044   file_id int(11) NOT NULL AUTO_INCREMENT,
7045   borrowernumber int(11) NOT NULL,
7046   file_name varchar(255) NOT NULL,
7047   file_type varchar(255) NOT NULL,
7048   file_description varchar(255) DEFAULT NULL,
7049   file_content longblob NOT NULL,
7050   date_uploaded timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
7051   PRIMARY KEY (file_id),
7052   KEY borrowernumber (borrowernumber),
7053   CONSTRAINT borrower_files_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
7054 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7055     ");
7056     print "Upgrade to $DBversion done (Bug 10443: make sure borrower_files table exists)\n";
7057     SetVersion($DBversion);
7058 }
7059
7060 $DBversion = "3.13.00.009";
7061 if ( CheckVersion($DBversion) ) {
7062     $dbh->do("ALTER TABLE aqorders DROP COLUMN biblioitemnumber");
7063     print "Upgrade to $DBversion done (Bug 9987 - Drop column aqorders.biblioitemnumber)\n";
7064     SetVersion($DBversion);
7065 }
7066
7067 $DBversion = "3.13.00.010";
7068 if ( CheckVersion($DBversion) ) {
7069     $dbh->do(
7070         q{
7071 INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AcqWarnOnDuplicateInvoice','0','Warn librarians when they try to create a duplicate invoice', '', 'YesNo');
7072 }
7073     );
7074     print
7075 "Upgrade to $DBversion done (Bug 10366 - Add system preference to enabling warning librarian when invoice is duplicated)\n";
7076     SetVersion($DBversion);
7077 }
7078
7079 $DBversion = "3.13.00.011";
7080 if ( CheckVersion($DBversion) ) {
7081     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='ita' WHERE rfc4646_subtag='it'");
7082     print "Upgrade to $DBversion done (Bug 9519: Wrong language code for Italian in the advanced search language limitations)\n";
7083     SetVersion($DBversion);
7084 }
7085
7086 $DBversion = "3.13.00.012";
7087 if ( CheckVersion($DBversion) ) {
7088     $dbh->do("ALTER TABLE issuingrules MODIFY COLUMN overduefinescap decimal(28,6) DEFAULT NULL;");
7089     print "Upgrade to $DBversion done (Bug 10490: Correct datatype for overduefinescap in issuingrules)\n";
7090     SetVersion($DBversion);
7091 }
7092
7093 $DBversion ="3.13.00.013";
7094 if ( CheckVersion($DBversion) ) {
7095     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('AllowTooManyOverride', '1', 'If on, allow staff to override and check out items when the patron has reached the maximum number of allowed checkouts', '', 'YesNo');");
7096     print "Upgrade to $DBversion done (Bug 9576: add AllowTooManyOverride syspref to enable or disable issue limit confirmation)\n";
7097     SetVersion($DBversion);
7098 }
7099
7100 $DBversion = "3.13.00.014";
7101 if ( CheckVersion($DBversion) ) {
7102     $dbh->do("ALTER TABLE courses MODIFY COLUMN department varchar(80) DEFAULT NULL;");
7103     $dbh->do("ALTER TABLE courses MODIFY COLUMN term       varchar(80) DEFAULT NULL;");
7104     print "Upgrade to $DBversion done (Bug 10604: correct width of courses.department and courses.term)\n";
7105     SetVersion($DBversion);
7106 }
7107
7108 $DBversion = "3.13.00.015";
7109 if ( CheckVersion($DBversion) ) {
7110     $dbh->do(
7111 "INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('itemBarcodeFallbackSearch','','If set, enables the automatic use of a keyword catalog search if the phrase entered as a barcode on the checkout page does not turn up any results during an item barcode search',NULL,'YesNo')"
7112     );
7113     print "Upgrade to $DBversion done (Bug 7494: Add itemBarcodeFallbackSearch syspref)\n";
7114     SetVersion($DBversion);
7115 }
7116
7117 $DBversion = "3.13.00.016";
7118 if ( CheckVersion($DBversion) ) {
7119     $dbh->do(q{
7120         ALTER TABLE items CHANGE wthdrawn withdrawn TINYINT( 1 ) NOT NULL DEFAULT  '0'
7121     });
7122
7123     $dbh->do(q{
7124         ALTER TABLE deleteditems CHANGE wthdrawn withdrawn TINYINT( 1 ) NOT NULL DEFAULT  '0'
7125     });
7126
7127     $dbh->do(q{
7128         UPDATE saved_sql SET savedsql = REPLACE(savedsql, 'wthdrawn', 'withdrawn')
7129     });
7130
7131     $dbh->do(q{
7132         UPDATE marc_subfield_structure SET kohafield = 'items.withdrawn' WHERE kohafield = 'items.wthdrawn'
7133     });
7134
7135     print "Upgrade to $DBversion done (Bug 10550 - Fix database typo wthdrawn)\n";
7136     SetVersion($DBversion);
7137 }
7138
7139 $DBversion = "3.13.00.017";
7140 if ( CheckVersion($DBversion) ) {
7141     $dbh->do(
7142 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveClientKey','','Client key for OverDrive integration','30','Free')"
7143     );
7144     $dbh->do(
7145 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveClientSecret','','Client key for OverDrive integration','30','YesNo')"
7146     );
7147     $dbh->do(
7148 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveLibraryID','','Library ID for OverDrive integration','','Integer')"
7149     );
7150     print "Upgrade to $DBversion done (Bug 10320 - Show results from library's OverDrive collection in OPAC search)\n";
7151     SetVersion($DBversion);
7152 }
7153
7154 $DBversion = "3.13.00.018";
7155 if ( CheckVersion($DBversion) ) {
7156     $dbh->do(qq{DROP TABLE IF EXISTS aqorders_transfers;});
7157     $dbh->do(qq{
7158         CREATE TABLE aqorders_transfers (
7159           ordernumber_from int(11) NULL,
7160           ordernumber_to int(11) NULL,
7161           timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
7162           UNIQUE KEY ordernumber_from (ordernumber_from),
7163           UNIQUE KEY ordernumber_to (ordernumber_to),
7164           CONSTRAINT aqorders_transfers_ordernumber_from FOREIGN KEY (ordernumber_from) REFERENCES aqorders (ordernumber) ON DELETE SET NULL ON UPDATE CASCADE,
7165           CONSTRAINT aqorders_transfers_ordernumber_to FOREIGN KEY (ordernumber_to) REFERENCES aqorders (ordernumber) ON DELETE SET NULL ON UPDATE CASCADE
7166         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7167     });
7168     print "Upgrade to $DBversion done (Bug 5349: Add aqorders_transfers table)\n";
7169     SetVersion($DBversion);
7170 }
7171
7172 $DBversion = "3.13.00.019";
7173 if ( CheckVersion($DBversion) ) {
7174     $dbh->do("ALTER TABLE itemtypes ADD COLUMN checkinmsg VARCHAR(255) AFTER summary;");
7175     $dbh->do("ALTER TABLE itemtypes ADD COLUMN checkinmsgtype CHAR(16) DEFAULT 'message' NOT NULL AFTER checkinmsg;");
7176     print "Upgrade to $DBversion done (Bug 10513 - Light up a warning/message when returning a chosen item type)\n";
7177     SetVersion($DBversion);
7178 }
7179
7180 $DBversion = "3.13.00.020";
7181 if ( CheckVersion($DBversion) ) {
7182     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('WhenLostForgiveFine','0',NULL,'If ON, Forgives the fines on an item when it is lost.','YesNo')");
7183     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('WhenLostChargeReplacementFee','1',NULL,'If ON, Charge the replacement price when a patron loses an item.','YesNo')");
7184     print "Upgrade to $DBversion done (Bug 7639: system preferences to forgive fines on lost items)\n";
7185     SetVersion($DBversion);
7186 }
7187
7188 $DBversion ="3.13.00.021";
7189 if ( CheckVersion($DBversion) ) {
7190     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ConfirmFutureHolds','0','Number of days for confirming future holds','','Integer');");
7191     print "Upgrade to $DBversion done (Bug 9761: Add ConfirmFutureHolds pref)\n";
7192     SetVersion($DBversion);
7193 }
7194
7195 $DBversion = "3.13.00.022";
7196 if ( CheckVersion($DBversion) ) {
7197     $dbh->do("DELETE from auth_tag_structure WHERE tagfield IN ('68a','68b')");
7198     $dbh->do("DELETE from auth_subfield_structure WHERE tagfield IN ('68a','68b')");
7199     print "Upgrade to $DBversion done (Bug 10687 - Delete erroneous tags 68a and 68b on default MARC21 auth framework)\n";
7200     SetVersion($DBversion);
7201 }
7202
7203 $DBversion = "3.13.00.023";
7204 if ( CheckVersion($DBversion) ) {
7205     $dbh->do("ALTER TABLE borrowers CHANGE password password VARCHAR(60);");
7206     print "Upgrade to $DBversion done (Bug 9611 upgrading password storage system)\n";
7207     SetVersion($DBversion);
7208 }
7209
7210 $DBversion = "3.13.00.024";
7211 if ( CheckVersion($DBversion) ) {
7212     $dbh->do(q{ALTER TABLE z3950servers ADD COLUMN recordtype VARCHAR(45) NOT NULL DEFAULT 'biblio' AFTER description;});
7213     print "Upgrade to $DBversion done (Bug 10096 - Add a Z39.50 interface for authority searching)\n";
7214 }
7215
7216 $DBversion = "3.13.00.025";
7217 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
7218    $dbh->do("ALTER TABLE oai_sets_mappings ADD COLUMN operator varchar(8) NOT NULL default 'equal' AFTER marcsubfield;");
7219    print "Upgrade to $DBversion done (Bug 9295: OAI notequal: add operator column to OAI mappings table)\n";
7220    SetVersion ($DBversion);
7221 }
7222
7223 $DBversion = "3.13.00.026";
7224 if ( CheckVersion($DBversion) ) {
7225     $dbh->do(q|
7226         ALTER TABLE auth_subfield_structure ADD COLUMN defaultvalue TEXT DEFAULT NULL AFTER frameworkcode
7227     |);
7228     print "Upgrade to $DBversion done (Bug 10602: Add the column auth_subfield_structure.defaultvalue)\n";
7229     SetVersion($DBversion);
7230 }
7231
7232 $DBversion = "3.13.00.027";
7233 if ( CheckVersion($DBversion) ) {
7234     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('AllowOfflineCirculation','0','','If on, enables HTML5 offline circulation functionality.','YesNo')");
7235     print "Upgrade to $DBversion done (Bug 10240: Add syspref AllowOfflineCirculation)\n";
7236     SetVersion ($DBversion);
7237 }
7238
7239 $DBversion = "3.13.00.028";
7240 if ( CheckVersion($DBversion) ) {
7241     $dbh->do(q{
7242         ALTER TABLE export_format ADD type VARCHAR(255) DEFAULT 'marc' AFTER encoding
7243     });
7244     $dbh->do(q{
7245         ALTER TABLE export_format CHANGE marcfields content mediumtext NOT NULL
7246     });
7247     print "Upgrade to $DBversion done (Bug 10853: Add new field export_format.type and rename export_format.marcfields with export_format.content)\n";
7248     SetVersion($DBversion);
7249 }
7250
7251 $DBversion = "3.13.00.029";
7252 if ( CheckVersion($DBversion) ) {
7253     $dbh->do(q{
7254         INSERT IGNORE INTO export_format( profile, description, content, csv_separator, type )
7255         VALUES ( "issues to claim", "Default CSV export for serial issue claims",
7256                 "SUPPLIER=aqbooksellers.name|TITLE=subscription.title|ISSUE NUMBER=serial.serialseq|LATE SINCE=serial.planneddate",
7257                 ",", "sql" )
7258     });
7259     print "Upgrade to $DBversion done (Bug 10854: Add the default CSV profile for claiming issues)\n";
7260     SetVersion($DBversion);
7261 }
7262
7263 $DBversion = "3.13.00.030";
7264 if ( CheckVersion($DBversion) ) {
7265     $dbh->do(qq{
7266         DELETE FROM patronimage WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowers.cardnumber = patronimage.cardnumber)
7267     });
7268
7269     $dbh->do(qq{
7270         ALTER TABLE patronimage ADD borrowernumber INT( 11 ) NULL FIRST
7271     });
7272
7273     $dbh->{AutoCommit} = 0;
7274     $dbh->{RaiseError} = 1;
7275
7276     eval {
7277         $dbh->do(qq{
7278             UPDATE patronimage LEFT JOIN borrowers USING ( cardnumber ) SET patronimage.borrowernumber = borrowers.borrowernumber
7279         });
7280         $dbh->commit();
7281     };
7282
7283     if ($@) {
7284         print "Upgrade to $DBversion done (Bug 10636 - patronimage should have borrowernumber as PK, not cardnumber) failed! Transaction aborted because $@\n";
7285         eval { $dbh->rollback };
7286     }
7287     else {
7288         $dbh->do(qq{
7289             ALTER TABLE patronimage DROP FOREIGN KEY patronimage_fk1
7290         });
7291         $dbh->do(qq{
7292             ALTER TABLE patronimage DROP PRIMARY KEY, ADD PRIMARY KEY( borrowernumber )
7293         });
7294         $dbh->do(qq{
7295             ALTER TABLE patronimage DROP cardnumber
7296         });
7297         $dbh->do(qq{
7298             ALTER TABLE patronimage ADD FOREIGN KEY ( borrowernumber ) REFERENCES borrowers ( borrowernumber ) ON DELETE CASCADE ON UPDATE CASCADE
7299         });
7300
7301         print "Upgrade to $DBversion done (Bug 10636 - patronimage should have borrowernumber as PK, not cardnumber)\n";
7302         SetVersion($DBversion);
7303     }
7304
7305     $dbh->{AutoCommit} = 1;
7306     $dbh->{RaiseError} = 0;
7307 }
7308
7309 $DBversion = "3.13.00.031";
7310 if ( CheckVersion($DBversion) ) {
7311
7312     $dbh->do(q{
7313         CREATE TABLE IF NOT EXISTS `patron_lists` (
7314           patron_list_id int(11) NOT NULL AUTO_INCREMENT,
7315           name varchar(255) CHARACTER SET utf8 NOT NULL,
7316           owner int(11) NOT NULL,
7317           PRIMARY KEY (patron_list_id),
7318           KEY owner (owner)
7319         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7320     });
7321
7322     $dbh->do(q{
7323         ALTER TABLE `patron_lists`
7324           ADD CONSTRAINT patron_lists_ibfk_1 FOREIGN KEY (`owner`) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE;
7325     });
7326
7327     $dbh->do(q{
7328         CREATE TABLE patron_list_patrons (
7329           patron_list_patron_id int(11) NOT NULL AUTO_INCREMENT,
7330           patron_list_id int(11) NOT NULL,
7331           borrowernumber int(11) NOT NULL,
7332           PRIMARY KEY (patron_list_patron_id),
7333           KEY patron_list_id (patron_list_id),
7334           KEY borrowernumber (borrowernumber)
7335         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7336     });
7337
7338     $dbh->do(q{
7339         ALTER TABLE `patron_list_patrons`
7340           ADD CONSTRAINT patron_list_patrons_ibfk_1 FOREIGN KEY (patron_list_id) REFERENCES patron_lists (patron_list_id) ON DELETE CASCADE ON UPDATE CASCADE,
7341           ADD CONSTRAINT patron_list_patrons_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE;
7342     });
7343
7344     $dbh->do(q{
7345         INSERT INTO permissions (module_bit, code, description) VALUES
7346         (13, 'manage_patron_lists', 'Add, edit and delete patron lists and their contents')
7347     });
7348
7349     print "Upgrade to $DBversion done (Bug 10565 - Add a 'Patron List' feature for storing and manipulating collections of patrons)\n";
7350     SetVersion($DBversion);
7351 }
7352
7353 $DBversion = "3.13.00.032";
7354 if ( CheckVersion($DBversion) ) {
7355     $dbh->do("ALTER TABLE aqorders ADD COLUMN orderstatus varchar(16) DEFAULT 'new' AFTER parent_ordernumber");
7356     $dbh->do("UPDATE aqorders SET orderstatus='ordered' WHERE basketno IN (SELECT basketno FROM aqbasket WHERE closedate IS NOT NULL)");
7357     $dbh->do(q{
7358         UPDATE aqorders SET orderstatus='partial'
7359         WHERE quantity > quantityreceived
7360         AND quantityreceived > 0
7361         AND ordernumber IN (
7362             SELECT parent_ordernumber
7363             FROM (
7364                 SELECT DISTINCT(parent_ordernumber)
7365                 FROM aqorders
7366                 WHERE ordernumber != parent_ordernumber
7367             ) AS aq
7368         )
7369         AND basketno IN (SELECT basketno FROM aqbasket WHERE closedate IS NOT NULL)
7370     });
7371     $dbh->do("UPDATE aqorders SET orderstatus='complete' WHERE quantity=quantityreceived");
7372     $dbh->do("UPDATE aqorders SET orderstatus='cancelled' WHERE datecancellationprinted IS NOT NULL");
7373     print "Upgrade to $DBversion done (Bug 5336: Add the new column aqorders.orderstatus)\n";
7374     SetVersion($DBversion);
7375 }
7376
7377 $DBversion = "3.13.00.033";
7378 if ( CheckVersion($DBversion) ) {
7379     $dbh->do(qq|
7380         DROP TABLE IF EXISTS subscription_frequencies
7381     |);
7382     $dbh->do(qq|
7383         CREATE TABLE subscription_frequencies (
7384             id INTEGER NOT NULL AUTO_INCREMENT,
7385             description TEXT NOT NULL,
7386             displayorder INT DEFAULT NULL,
7387             unit ENUM('day','week','month','year') DEFAULT NULL,
7388             unitsperissue INTEGER NOT NULL DEFAULT '1',
7389             issuesperunit INTEGER NOT NULL DEFAULT '1',
7390             PRIMARY KEY (id)
7391         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
7392     |);
7393
7394     $dbh->do(qq|
7395         DROP TABLE IF EXISTS subscription_numberpatterns
7396     |);
7397     $dbh->do(qq|
7398         CREATE TABLE subscription_numberpatterns (
7399             id INTEGER NOT NULL AUTO_INCREMENT,
7400             label VARCHAR(255) NOT NULL,
7401             displayorder INTEGER DEFAULT NULL,
7402             description TEXT NOT NULL,
7403             numberingmethod VARCHAR(255) NOT NULL,
7404             label1 VARCHAR(255) DEFAULT NULL,
7405             add1 INTEGER DEFAULT NULL,
7406             every1 INTEGER DEFAULT NULL,
7407             whenmorethan1 INTEGER DEFAULT NULL,
7408             setto1 INTEGER DEFAULT NULL,
7409             numbering1 VARCHAR(255) DEFAULT NULL,
7410             label2 VARCHAR(255) DEFAULT NULL,
7411             add2 INTEGER DEFAULT NULL,
7412             every2 INTEGER DEFAULT NULL,
7413             whenmorethan2 INTEGER DEFAULT NULL,
7414             setto2 INTEGER DEFAULT NULL,
7415             numbering2 VARCHAR(255) DEFAULT NULL,
7416             label3 VARCHAR(255) DEFAULT NULL,
7417             add3 INTEGER DEFAULT NULL,
7418             every3 INTEGER DEFAULT NULL,
7419             whenmorethan3 INTEGER DEFAULT NULL,
7420             setto3 INTEGER DEFAULT NULL,
7421             numbering3 VARCHAR(255) DEFAULT NULL,
7422             PRIMARY KEY (id)
7423         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
7424     |);
7425
7426     $dbh->do(qq|
7427         INSERT INTO subscription_frequencies (description, unit, unitsperissue, issuesperunit, displayorder)
7428         VALUES
7429             ('2/day', 'day', 1, 2, 1),
7430             ('1/day', 'day', 1, 1, 2),
7431             ('3/week', 'week', 1, 3, 3),
7432             ('1/week', 'week', 1, 1, 4),
7433             ('1/2 weeks', 'week', 2, 1, 5),
7434             ('1/3 weeks', 'week', 3, 1, 6),
7435             ('1/month', 'month', 1, 1, 7),
7436             ('1/2 months', 'month', 2, 1, 8),
7437             ('1/3 months', 'month', 3, 1, 9),
7438             ('2/year', 'month', 6, 1, 10),
7439             ('1/year', 'year', 1, 1, 11),
7440             ('1/2 year', 'year', 2, 1, 12),
7441             ('Irregular', NULL, 1, 1, 13)
7442     |);
7443
7444     # Used to link existing subscription to newly created frequencies
7445     my $frequencies_mapping = {     # keys are old frequency numbers, values are the new ones
7446         1 => 2,     # daily (n/week)
7447         2 => 4,     # 1/week
7448         3 => 5,     # 1/2 weeks
7449         4 => 6,     # 1/3 weeks
7450         5 => 7,     # 1/month
7451         6 => 8,     # 1/2 months (6/year)
7452         7 => 9,     # 1/3 months (1/quarter)
7453         8 => 9,    # 1/quarter (seasonal)
7454         9 => 10,    # 2/year
7455         10 => 11,   # 1/year
7456         11 => 12,   # 1/2 years
7457         12 => 1,    # 2/day
7458         16 => 13,   # Without periodicity
7459         32 => 13,   # Irregular
7460         48 => 13    # Unknown
7461     };
7462
7463     $dbh->do(qq|
7464         INSERT INTO subscription_numberpatterns
7465             (label, displayorder, description, numberingmethod,
7466             label1, add1, every1, whenmorethan1, setto1, numbering1,
7467             label2, add2, every2, whenmorethan2, setto2, numbering2,
7468             label3, add3, every3, whenmorethan3, setto3, numbering3)
7469         VALUES
7470             ('Number', 1, 'Simple Numbering method', 'No.{X}',
7471             'Number', 1, 1, 99999, 1, NULL,
7472             NULL, NULL, NULL, NULL, NULL, NULL,
7473             NULL, NULL, NULL, NULL, NULL, NULL),
7474
7475             ('Volume, Number, Issue', 2, 'Volume Number Issue 1', 'Vol.{X}, Number {Y}, Issue {Z}',
7476             'Volume', 1, 48, 99999, 1, NULL,
7477             'Number', 1, 4, 12, 1, NULL,
7478             'Issue', 1, 1, 4, 1, NULL),
7479
7480             ('Volume, Number', 3, 'Volume Number 1', 'Vol {X}, No {Y}',
7481             'Volume', 1, 12, 99999, 1, NULL,
7482             'Number', 1, 1, 12, 1, NULL,
7483             NULL, NULL, NULL, NULL, NULL, NULL),
7484
7485             ('Seasonal', 4, 'Season Year', '{X} {Y}',
7486             'Season', 1, 1, 3, 0, 'season',
7487             'Year', 1, 4, 99999, 1, NULL,
7488             NULL, NULL, NULL, NULL, NULL, NULL)
7489     |);
7490
7491     $dbh->do(qq|
7492         ALTER TABLE subscription
7493         MODIFY COLUMN numberpattern INTEGER DEFAULT NULL,
7494         MODIFY COLUMN periodicity INTEGER DEFAULT NULL
7495     |);
7496
7497     # Update existing subscriptions
7498
7499     my $query = qq|
7500         SELECT subscriptionid, periodicity, numberingmethod,
7501             add1, every1, whenmorethan1, setto1,
7502             add2, every2, whenmorethan2, setto2,
7503             add3, every3, whenmorethan3, setto3
7504         FROM subscription
7505         ORDER BY subscriptionid
7506     |;
7507     my $sth = $dbh->prepare($query);
7508     $sth->execute;
7509     my $insert_numberpatterns_sth = $dbh->prepare(qq|
7510         INSERT INTO subscription_numberpatterns
7511              (label, displayorder, description, numberingmethod,
7512             label1, add1, every1, whenmorethan1, setto1, numbering1,
7513             label2, add2, every2, whenmorethan2, setto2, numbering2,
7514             label3, add3, every3, whenmorethan3, setto3, numbering3)
7515         VALUES
7516             (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
7517     |);
7518     my $check_numberpatterns_sth = $dbh->prepare(qq|
7519         SELECT * FROM subscription_numberpatterns
7520         WHERE (add1 = ? OR (add1 IS NULL AND ? IS NULL)) AND (add2 = ? OR (add2 IS NULL AND ? IS NULL))
7521         AND (add3 = ? OR (add3 IS NULL AND ? IS NULL)) AND (every1 = ? OR (every1 IS NULL AND ? IS NULL))
7522         AND (every2 = ? OR (every2 IS NULL AND ? IS NULL)) AND (every3 = ? OR (every3 IS NULL AND ? IS NULL))
7523         AND (whenmorethan1 = ? OR (whenmorethan1 IS NULL AND ? IS NULL)) AND (whenmorethan2 = ? OR (whenmorethan2 IS NULL AND ? IS NULL))
7524         AND (whenmorethan3 = ? OR (whenmorethan3 IS NULL AND ? IS NULL)) AND (setto1 = ? OR (setto1 IS NULL AND ? IS NULL))
7525         AND (setto2 = ? OR (setto2 IS NULL AND ? IS NULL)) AND (setto3 = ? OR (setto3 IS NULL AND ? IS NULL))
7526         AND (numberingmethod = ? OR (numberingmethod IS NULL AND ? IS NULL))
7527         LIMIT 1
7528     |);
7529     my $update_subscription_sth = $dbh->prepare(qq|
7530         UPDATE subscription
7531         SET numberpattern = ?,
7532             periodicity = ?
7533         WHERE subscriptionid = ?
7534     |);
7535
7536     my $i = 1;
7537     while(my $sub = $sth->fetchrow_hashref) {
7538         $check_numberpatterns_sth->execute(
7539             $sub->{add1}, $sub->{add1}, $sub->{add2}, $sub->{add2}, $sub->{add3}, $sub->{add3},
7540             $sub->{every1}, $sub->{every1}, $sub->{every2}, $sub->{every2}, $sub->{every3}, $sub->{every3},
7541             $sub->{whenmorethan1}, $sub->{whenmorethan1}, $sub->{whenmorethan2}, $sub->{whenmorethan2},
7542             $sub->{whenmorethan3}, $sub->{whenmorethan3}, $sub->{setto1}, $sub->{setto1}, $sub->{setto2},
7543             $sub->{setto2}, $sub->{setto3}, $sub->{setto3}, $sub->{numberingmethod}, $sub->{numberingmethod}
7544         );
7545         my $p = $check_numberpatterns_sth->fetchrow_hashref;
7546         if (defined $p) {
7547             # Pattern already exists, link to it
7548             $update_subscription_sth->execute($p->{id},
7549                 $frequencies_mapping->{$sub->{periodicity}},
7550                 $sub->{subscriptionid});
7551         } else {
7552             # Create a new numbering pattern for this subscription
7553             my $ok = $insert_numberpatterns_sth->execute(
7554                 "Backup pattern $i", 4+$i, "Automatically created pattern by updatedatabase", $sub->{numberingmethod},
7555                 "X", $sub->{add1}, $sub->{every1}, $sub->{whenmorethan1}, $sub->{setto1}, undef,
7556                 "Y", $sub->{add2}, $sub->{every2}, $sub->{whenmorethan2}, $sub->{setto2}, undef,
7557                 "Z", $sub->{add3}, $sub->{every3}, $sub->{whenmorethan3}, $sub->{setto3}, undef
7558             );
7559             if($ok) {
7560                 my $id = $dbh->last_insert_id(undef, undef, 'subscription_numberpatterns', undef);
7561                 # Link to subscription_numberpatterns and subscription_frequencies
7562                 $update_subscription_sth->execute($id,
7563                     $frequencies_mapping->{$sub->{periodicity}},
7564                     $sub->{subscriptionid});
7565             }
7566             $i++;
7567         }
7568     }
7569
7570     # Remove now useless columns
7571     $dbh->do(qq|
7572         ALTER TABLE subscription
7573         DROP COLUMN numberingmethod,
7574         DROP COLUMN add1,
7575         DROP COLUMN every1,
7576         DROP COLUMN whenmorethan1,
7577         DROP COLUMN setto1,
7578         DROP COLUMN add2,
7579         DROP COLUMN every2,
7580         DROP COLUMN whenmorethan2,
7581         DROP COLUMN setto2,
7582         DROP COLUMN add3,
7583         DROP COLUMN every3,
7584         DROP COLUMN whenmorethan3,
7585         DROP COLUMN setto3,
7586         DROP COLUMN dow,
7587         DROP COLUMN issuesatonce,
7588         DROP COLUMN hemisphere,
7589         ADD COLUMN countissuesperunit INTEGER NOT NULL DEFAULT 1 AFTER periodicity,
7590         ADD COLUMN skip_serialseq BOOLEAN NOT NULL DEFAULT 0 AFTER irregularity,
7591         ADD COLUMN locale VARCHAR(80) DEFAULT NULL AFTER numberpattern,
7592         ADD CONSTRAINT subscription_ibfk_1 FOREIGN KEY (periodicity) REFERENCES subscription_frequencies (id) ON DELETE SET NULL ON UPDATE CASCADE,
7593         ADD CONSTRAINT subscription_ibfk_2 FOREIGN KEY (numberpattern) REFERENCES subscription_numberpatterns (id) ON DELETE SET NULL ON UPDATE CASCADE
7594     |);
7595
7596     # Set firstacquidate if not already set (firstacquidate is now mandatory)
7597     my $get_first_planneddate_sth = $dbh->prepare(qq|
7598         SELECT planneddate
7599         FROM serial
7600         WHERE subscriptionid = ?
7601         ORDER BY serialid
7602         LIMIT 1
7603     |);
7604     my $update_firstacquidate_sth = $dbh->prepare(qq|
7605         UPDATE subscription
7606         SET firstacquidate = ?
7607         WHERE subscriptionid = ?
7608     |);
7609     my $get_subscriptions_sth = $dbh->prepare(qq|
7610         SELECT subscriptionid, startdate
7611         FROM subscription
7612         WHERE firstacquidate IS NULL
7613           OR firstacquidate = '0000-00-00'
7614     |);
7615     $get_subscriptions_sth->execute;
7616     while ( my ($subscriptionid, $startdate) = $get_subscriptions_sth->fetchrow ) {
7617         # Try to get the planned date of the first serial
7618         $get_first_planneddate_sth->execute($subscriptionid);
7619         my ($first_planneddate) = $get_first_planneddate_sth->fetchrow;
7620         if ($first_planneddate and $first_planneddate =~ /^\d{4}-\d{2}-\d{2}$/) {
7621             $update_firstacquidate_sth->execute($first_planneddate, $subscriptionid);
7622         } else {
7623             # Defaults to subscription start date
7624             $update_firstacquidate_sth->execute($startdate, $subscriptionid);
7625         }
7626     }
7627
7628     print "Upgrade to $DBversion done (Bug 7688: add subscription_frequencies and subscription_numberpatterns tables)\n";
7629     SetVersion($DBversion);
7630 }
7631
7632 $DBversion = "3.13.00.034";
7633 if ( CheckVersion($DBversion) ) {
7634     $dbh->do("
7635         ALTER TABLE `import_batches`
7636         CHANGE `item_action` `item_action`
7637           ENUM( 'always_add', 'add_only_for_matches', 'add_only_for_new', 'ignore', 'replace' )
7638           NOT NULL DEFAULT 'always_add'
7639     ");
7640     print "Upgrade to $DBversion done (Bug 7131 - way to overlay items in in marc import)\n";
7641     SetVersion($DBversion);
7642 }
7643
7644 $DBversion ="3.13.00.035";
7645 if ( CheckVersion($DBversion) ) {
7646     $dbh->do(q{
7647 CREATE TABLE borrower_debarments (
7648   borrower_debarment_id int(11) NOT NULL AUTO_INCREMENT,
7649   borrowernumber int(11) NOT NULL,
7650   expiration date DEFAULT NULL,
7651   `type` enum('SUSPENSION','OVERDUES','MANUAL') NOT NULL DEFAULT 'MANUAL',
7652   `comment` text,
7653   manager_id int(11) DEFAULT NULL,
7654   created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
7655   updated timestamp NULL DEFAULT NULL,
7656   PRIMARY KEY (borrower_debarment_id),
7657   KEY borrowernumber (borrowernumber) ,
7658   CONSTRAINT `borrower_debarments_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
7659     ON DELETE CASCADE ON UPDATE CASCADE
7660 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7661     });
7662
7663     # debarments with end date
7664     $dbh->do(q{
7665 INSERT INTO borrower_debarments ( borrowernumber, expiration, comment ) SELECT borrowernumber, debarred, debarredcomment FROM borrowers WHERE debarred IS NOT NULL AND debarred <> '9999-12-31'
7666     });
7667     # debarments with no end date
7668     $dbh->do(q{
7669 INSERT INTO borrower_debarments ( borrowernumber, comment ) SELECT borrowernumber, debarredcomment FROM borrowers WHERE debarred = '9999-12-31'
7670     });
7671
7672     $dbh->do(q{
7673 INSERT IGNORE INTO systempreferences (variable,value,explanation,type) VALUES
7674 ('AutoRemoveOverduesRestrictions','0','Defines whether an OVERDUES debarment should be lifted automatically if all overdue items are returned by the patron.','YesNo')
7675     });
7676
7677     print "Upgrade to $DBversion done (Bug 2720 - Overdues which debar automatically should undebar automatically when returned)\n";
7678     SetVersion($DBversion);
7679 }
7680
7681 $DBversion = "3.13.00.036";
7682 if ( CheckVersion($DBversion) ) {
7683     $dbh->do(qq{
7684         INSERT INTO systempreferences (variable, value, explanation, options, type)
7685         VALUES ('StaffDetailItemSelection', '1', 'Enable item selection in record detail page', NULL, 'YesNo')
7686     });
7687     print "Upgrade to $DBversion done (Add system preference StaffDetailItemSelection)\n";
7688     SetVersion($DBversion);
7689 }
7690
7691 $DBversion = "3.13.00.037";
7692 if ( CheckVersion($DBversion) ) {
7693     #add phone if it is not there already (explains the ignore option)
7694     $dbh->do("
7695 INSERT IGNORE INTO message_transport_types (message_transport_type) values ('phone');
7696     ");
7697     print "Upgrade to $DBversion done (Bug 10572: Add phone to message_transport_types table for new installs)\n";
7698     SetVersion($DBversion);
7699 }
7700
7701 $DBversion = "3.13.00.038";
7702 if ( CheckVersion($DBversion) ) {
7703     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES(15, 'superserials', 'Manage subscriptions from any branch (only applies when IndependentBranches is used)')");
7704     print "Upgrade to $DBversion done (Bug 8435: Add superserials permission)\n";
7705     SetVersion($DBversion);
7706 }
7707
7708 $DBversion = "3.13.00.039";
7709 if ( CheckVersion($DBversion) ) {
7710     $dbh->do("
7711         ALTER TABLE aqbasket ADD branch varchar(10) default NULL
7712     ");
7713     $dbh->do("
7714         ALTER TABLE aqbasket
7715         ADD CONSTRAINT aqbasket_ibfk_4 FOREIGN KEY (branch)
7716             REFERENCES branches (branchcode)
7717             ON UPDATE CASCADE ON DELETE SET NULL
7718     ");
7719     $dbh->do("
7720         DROP TABLE IF EXISTS aqbasketusers
7721     ");
7722     $dbh->do("
7723         CREATE TABLE aqbasketusers (
7724             basketno int(11) NOT NULL,
7725             borrowernumber int(11) NOT NULL,
7726             PRIMARY KEY (basketno,borrowernumber),
7727             CONSTRAINT aqbasketusers_ibfk_1 FOREIGN KEY (basketno) REFERENCES aqbasket (basketno) ON DELETE CASCADE ON UPDATE CASCADE,
7728             CONSTRAINT aqbasketusers_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
7729         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7730     ");
7731     $dbh->do("
7732         INSERT INTO permissions (module_bit, code, description)
7733         VALUES (11, 'order_manage_all', 'Manage all orders and baskets, regardless of restrictions on them')
7734     ");
7735
7736     print "Upgrade to $DBversion done (Add branch and users list to baskets. "
7737         . "New permission order_manage_all)\n";
7738     SetVersion($DBversion);
7739 }
7740
7741 $DBversion = "3.13.00.040";
7742 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
7743     $dbh->do("CREATE TABLE IF NOT EXISTS marc_modification_templates (
7744               template_id int(11) NOT NULL auto_increment,
7745               name text NOT NULL,
7746               PRIMARY KEY  (template_id)
7747               ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;"
7748     );
7749
7750     $dbh->do("
7751       CREATE TABLE IF NOT EXISTS marc_modification_template_actions (
7752       mmta_id int(11) NOT NULL auto_increment,
7753       template_id int(11) NOT NULL,
7754       ordering int(3) NOT NULL,
7755       action enum('delete_field','update_field','move_field','copy_field') NOT NULL,
7756       field_number smallint(6) NOT NULL default '0',
7757       from_field varchar(3) NOT NULL,
7758       from_subfield varchar(1) NULL,
7759       field_value varchar(100) default NULL,
7760       to_field varchar(3) default NULL,
7761       to_subfield varchar(1) default NULL,
7762       to_regex_search text,
7763       to_regex_replace text,
7764       to_regex_modifiers varchar(8) default '',
7765       conditional enum('if','unless') default NULL,
7766       conditional_field varchar(3) default NULL,
7767       conditional_subfield varchar(1) default NULL,
7768       conditional_comparison enum('exists','not_exists','equals','not_equals') default NULL,
7769       conditional_value text,
7770       conditional_regex tinyint(1) NOT NULL default '0',
7771       description text,
7772       PRIMARY KEY  (mmta_id),
7773       CONSTRAINT `mmta_ibfk_1` FOREIGN KEY (`template_id`) REFERENCES `marc_modification_templates` (`template_id`) ON DELETE CASCADE ON UPDATE CASCADE
7774       ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7775     ");
7776
7777     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('13', 'marc_modification_templates', 'Manage marc modification templates')");
7778
7779     print "Upgrade to $DBversion done ( Bug 8015: Added tables for MARC Modification Framework )\n";
7780     SetVersion($DBversion);
7781 }
7782
7783 $DBversion = "3.13.00.041";
7784 if(CheckVersion($DBversion)) {
7785     $dbh->do(q{
7786         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');
7787     });
7788     print "Upgrade to $DBversion done (Bug 10986: Added AcqItemSetSubfieldsWhenReceived syspref)\n";
7789     SetVersion($DBversion);
7790 }
7791
7792 $DBversion = "3.13.00.042";
7793 if(CheckVersion($DBversion)) {
7794     print "Upgrade to $DBversion done (Koha 3.14 beta)\n";
7795     SetVersion($DBversion);
7796 }
7797
7798 $DBversion = "3.13.00.043";
7799 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
7800     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('SearchEngine','Zebra','Solr|Zebra','Search Engine','Choice')");
7801     print "Upgrade to $DBversion done (Bug 11196: Add system preference SearchEngine if missing )\n";
7802     SetVersion($DBversion);
7803 }
7804
7805 $DBversion = "3.14.00.000";
7806 if ( CheckVersion($DBversion) ) {
7807     print "Upgrade to $DBversion done (3.14.0 release)\n";
7808     SetVersion ($DBversion);
7809 }
7810
7811 $DBversion = '3.15.00.000';
7812 if ( CheckVersion($DBversion) ) {
7813     print "Upgrade to $DBversion done (the road goes ever on)\n";
7814     SetVersion ($DBversion);
7815 }
7816
7817 $DBversion = "3.15.00.001";
7818 if ( CheckVersion($DBversion) ) {
7819     $dbh->do("UPDATE systempreferences SET value='clear' where variable = 'CircAutoPrintQuickSlip' and value = '0'");
7820     $dbh->do("UPDATE systempreferences SET value='qslip' where variable = 'CircAutoPrintQuickSlip' and value = '1'");
7821     $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'");
7822     print "Upgrade to $DBversion done (Bug 11040: Add option to print full slip when checking out a null barcode)\n";
7823     SetVersion($DBversion);
7824 }
7825
7826 $DBversion = "3.15.00.002";
7827 if(CheckVersion($DBversion)) {
7828     $dbh->do("ALTER TABLE deleteditems MODIFY materials text;");
7829     print "Upgrade to $DBversion done (Bug 11275: alter deleteditems.materials from varchar(10) to text)\n";
7830     SetVersion($DBversion);
7831 }
7832
7833 $DBversion = "3.15.00.003";
7834 if ( CheckVersion($DBversion) ) {
7835     $dbh->do(q{
7836         UPDATE accountlines
7837         SET description = ''
7838         WHERE description IN (
7839             ' New Card',
7840             ' Fine',
7841             ' Sundry',
7842             'Writeoff',
7843             ' Account Management fee',
7844             'Payment,thanks', 'Payment,thanks - ',
7845             ' Lost Item'
7846         )
7847     });
7848     print "Upgrade to $DBversion done (Bug 2546: Update fine descriptions)\n";
7849     SetVersion($DBversion);
7850 }
7851
7852 $DBversion = "3.15.00.004";
7853 if ( CheckVersion($DBversion) ) {
7854     if ( C4::Context->preference("marcflavour") eq 'MARC21' ) {
7855         $dbh->do(qq{
7856             INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian, libopac, repeatable, mandatory,
7857             kohafield, tab, authorised_value, authtypecode, value_builder, isurl, hidden, frameworkcode, seealso, link,
7858             defaultvalue) VALUES
7859             ('015', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7860             ('020', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7861             ('024', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7862             ('027', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7863             ('800', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7864             ('810', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7865             ('811', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7866             ('830', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL);
7867         });
7868         $dbh->do(qq{
7869             INSERT IGNORE INTO auth_subfield_structure (authtypecode, tagfield, tagsubfield, liblibrarian, libopac, repeatable,
7870             mandatory, tab, authorised_value, value_builder, seealso, isurl, hidden, linkid, kohafield, frameworkcode) VALUES
7871             ('', '020', 'q', 'Qualifying information', 'Qualifying information', 1, 0, 0, NULL, NULL, NULL, 0, 0, '', '', ''),
7872             ('', '024', 'q', 'Qualifying information', 'Qualifying information', 1, 0, 0, NULL, NULL, NULL, 0, 0, '', '', '');
7873         });
7874     }
7875     print "Upgrade to $DBversion done (Bug 10970 - Update MARC21 frameworks to Update Nr. 17 - DB update)\n";
7876     SetVersion($DBversion);
7877 }
7878
7879 $DBversion = "3.15.00.005";
7880 if ( CheckVersion($DBversion) ) {
7881    $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('AcquisitionDetails', '1', '', 'Hide/Show acquisition details on the biblio detail page.', 'YesNo');");
7882    print "Upgrade to $DBversion done (Bug 8230: Add AcquisitionDetails system preference)\n";
7883    SetVersion ($DBversion);
7884 }
7885
7886 $DBversion = "3.15.00.006";
7887 if(CheckVersion($DBversion)) {
7888     $dbh->do(q{
7889         ALTER TABLE `borrowers`
7890         ADD KEY `surname_idx` (`surname`(255)),
7891         ADD KEY `firstname_idx` (`firstname`(255)),
7892         ADD KEY `othernames_idx` (`othernames`(255))
7893     });
7894     print "Upgrade to $DBversion done (Bug 11249 - Add DB indexes on borrower names)\n";
7895     SetVersion($DBversion);
7896 }
7897
7898 $DBversion = "3.15.00.007";
7899 if ( CheckVersion($DBversion) ) {
7900    $dbh->do("ALTER TABLE items ADD itemlost_on DATETIME NULL AFTER itemlost");
7901    $dbh->do("ALTER TABLE items ADD withdrawn_on DATETIME NULL AFTER withdrawn");
7902    $dbh->do("ALTER TABLE deleteditems ADD itemlost_on DATETIME NULL AFTER itemlost");
7903    $dbh->do("ALTER TABLE deleteditems ADD withdrawn_on DATETIME NULL AFTER withdrawn");
7904    print "Upgrade to $DBversion done (Bug 9673 - Track when items are marked as lost or withdrawn)\n";
7905    SetVersion ($DBversion);
7906 }
7907
7908 $DBversion = "3.15.00.008";
7909 if ( CheckVersion($DBversion) ) {
7910     $dbh->do(q{
7911         ALTER TABLE collections_tracking CHANGE ctId collections_tracking_id integer(11) NOT NULL auto_increment;
7912     });
7913     print "Upgrade to $DBversion done (Bug 11384) - change name of collections_tracker.ctId column)\n";
7914    SetVersion ($DBversion);
7915 }
7916
7917 $DBversion = "3.15.00.009";
7918 if ( CheckVersion($DBversion) ) {
7919     $dbh->do(q{
7920         ALTER TABLE suggestions MODIFY suggesteddate DATE NOT NULL
7921     });
7922     print "Upgrade to $DBversion done (Bug 11391) - drop default value on suggestions.suggesteddate column)\n";
7923    SetVersion ($DBversion);
7924 }
7925
7926 $DBversion = "3.15.00.010";
7927 if(CheckVersion($DBversion)) {
7928     $dbh->do("ALTER TABLE deleteditems DROP COLUMN marc");
7929     print "Upgrade to $DBversion done (Bug 6331: remove obsolete column in deleteditems.marc)\n";
7930     SetVersion ($DBversion);
7931 }
7932
7933 $DBversion = "3.15.00.011";
7934 if(CheckVersion($DBversion)) {
7935     $dbh->do("UPDATE marc_subfield_structure SET maxlength=9999 WHERE maxlength IS NULL OR maxlength=0;");
7936     print "Upgrade to $DBversion done (Bug 8018: set 9999 as default max length for subfields)\n";
7937     SetVersion ($DBversion);
7938 }
7939
7940 $DBversion = "3.15.00.012";
7941 if ( CheckVersion($DBversion) ) {
7942     $dbh->do(q{
7943         INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'force_checkout', 'Force checkout if a limitation exists')
7944     });
7945     $dbh->do(q{
7946         INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'manage_restrictions', 'Manage restrictions for accounts')
7947     });
7948     $dbh->do(q{
7949         INSERT INTO user_permissions (borrowernumber, module_bit, code)
7950             SELECT user_permissions.borrowernumber, 1, 'force_checkout'
7951             FROM user_permissions
7952             LEFT JOIN borrowers USING(borrowernumber)
7953             WHERE borrowers.flags & (1 << 1)
7954     });
7955     $dbh->do(q{
7956         INSERT INTO user_permissions (borrowernumber, module_bit, code)
7957             SELECT user_permissions.borrowernumber, 1, 'manage_restrictions'
7958             FROM user_permissions
7959             LEFT JOIN borrowers USING(borrowernumber)
7960             WHERE borrowers.flags & (1 << 1)
7961     });
7962
7963     print "Upgrade to $DBversion done (Bug 10863 - Add permissions force_checkout and manage_restrictions)\n";
7964     SetVersion($DBversion);
7965 }
7966
7967 $DBversion = "3.15.00.013";
7968 if(CheckVersion($DBversion)) {
7969     $dbh->do(q{
7970         UPDATE systempreferences
7971         SET explanation = 'Upon receiving items, update their subfields if they were created when placing an order (e.g. o=5|a="foo bar")'
7972         WHERE variable = "AcqItemSetSubfieldsWhenReceived"
7973     });
7974
7975     $dbh->do(q{
7976         UPDATE systempreferences
7977         SET value = ''
7978         WHERE variable = "AcqItemSetSubfieldsWhenReceived"
7979             AND value = "0"
7980     });
7981     print "Upgrade to $DBversion done (Bug 11237: Update explanation and default value for AcqItemSetSubfieldsWhenReceived syspref)\n";
7982     SetVersion($DBversion);
7983 }
7984
7985 $DBversion = "3.15.00.014";
7986 if (CheckVersion($DBversion)) {
7987     $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');");
7988     print "Upgrade to $DBversion done (Bug 11415: add system preference for automatic self checkout receipt printing)\n";
7989     SetVersion($DBversion);
7990 }
7991
7992 $DBversion = "3.15.00.015";
7993 if (CheckVersion($DBversion)) {
7994     $dbh->do("INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
7995         ('OpacSuggestionManagedBy',1,'','Show the name of the staff member who managed a suggestion in OPAC','YesNo');");
7996     print "Upgrade to $DBversion done (Bug 10907: Add OpacSuggestionManagedBy system preference)\n";
7997     SetVersion($DBversion);
7998 }
7999
8000 $DBversion = "3.15.00.016";
8001 if (CheckVersion($DBversion)) {
8002     $dbh->do("ALTER TABLE biblioitems CHANGE url url TEXT NULL DEFAULT NULL");
8003     $dbh->do("ALTER TABLE deletedbiblioitems CHANGE url url TEXT NULL DEFAULT NULL");
8004     print "Upgrade to $DBversion done (Bug 11268 - Biblioitems URL field is too small for some URLs)\n";
8005     SetVersion($DBversion);
8006 }
8007
8008 $DBversion = "3.15.00.017";
8009 if(CheckVersion($DBversion)) {
8010     $dbh->do(q{
8011         UPDATE systempreferences
8012         SET explanation = 'Define the contents of UNIMARC authority control field 100 position 08-35'
8013         WHERE variable = "UNIMARCAuthorityField100"
8014     });
8015     $dbh->do(q{
8016         UPDATE systempreferences
8017         SET explanation = 'Define the contents of MARC21 authority control field 008 position 06-39'
8018         WHERE variable = "MARCAuthorityControlField008"
8019     });
8020     $dbh->do(q{
8021         UPDATE systempreferences
8022         SET explanation = 'Define MARC Organization Code for MARC21 records - http://www.loc.gov/marc/organizations/orgshome.html'
8023         WHERE variable = "MARCOrgCode"
8024     });
8025     print "Upgrade to $DBversion done (Bug 11611 - fix possible confusion between UNIMARC and MARC21 in some sysprefs)\n";
8026     SetVersion($DBversion);
8027 }
8028
8029 $DBversion = "3.15.00.018";
8030 if ( CheckVersion($DBversion) ) {
8031     $dbh->{AutoCommit} = 0;
8032     $dbh->{RaiseError} = 1;
8033
8034     eval {
8035         $dbh->selectcol_arrayref(q|SELECT COUNT(*) FROM roadtype|);
8036     };
8037     unless ( $@ ) {
8038         my $av_added = $dbh->do(q|
8039             INSERT INTO authorised_values(category, authorised_value, lib, lib_opac)
8040                 SELECT 'ROADTYPE', roadtypeid, road_type, road_type
8041                 FROM roadtype;
8042         |);
8043
8044         my $rt_deleted = $dbh->do(q|
8045             DELETE FROM roadtype
8046         |);
8047
8048         if ( $av_added == $rt_deleted or $rt_deleted eq "0E0" ) {
8049             $dbh->do(q|
8050                 DROP TABLE roadtype;
8051             |);
8052             $dbh->commit;
8053             print "Upgrade to $DBversion done (Bug 7372: Move road types from the roadtype table to the ROADTYPE authorised values)\n";
8054             SetVersion($DBversion);
8055         } else {
8056             print "Upgrade to $DBversion failed (Bug 7372: Move road types from the roadtype table to the ROADTYPE authorised values.\nTransaction aborted because $@\n)";
8057             $dbh->rollback;
8058         }
8059     }
8060     $dbh->{AutoCommit} = 1;
8061     $dbh->{RaiseError} = 0;
8062 }
8063
8064 $DBversion = "3.15.00.019";
8065 if ( CheckVersion($DBversion) ) {
8066     $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')");
8067     print "Upgrade to $DBversion done (Bug 11256: Add system preference OpacMaxItemsToDisplay)\n";
8068     SetVersion($DBversion);
8069 }
8070
8071 $DBversion = "3.15.00.020";
8072 if ( CheckVersion($DBversion) ) {
8073     $dbh->do(q|
8074         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')
8075     |);
8076     print "Upgrade to $DBversion done (Bug 11343: Add system preference MaxItemsForBatch )\n";
8077     SetVersion($DBversion);
8078 }
8079
8080 $DBversion = "3.15.00.021";
8081 if(CheckVersion($DBversion)) {
8082     $dbh->do(q{
8083         ALTER TABLE `action_logs`
8084             DROP KEY timestamp,
8085             ADD KEY `timestamp_idx` (`timestamp`),
8086             ADD KEY `user_idx` (`user`),
8087             ADD KEY `module_idx` (`module`(255)),
8088             ADD KEY `action_idx` (`action`(255)),
8089             ADD KEY `object_idx` (`object`),
8090             ADD KEY `info_idx` (`info`(255))
8091     });
8092     print "Upgrade to $DBversion done (Bug 3445: Add indexes to action_logs table)\n";
8093     SetVersion($DBversion);
8094 }
8095
8096 $DBversion = "3.15.00.022";
8097 if (CheckVersion($DBversion)) {
8098     $dbh->do(q|
8099         DELETE FROM systempreferences WHERE variable= "memberofinstitution"
8100     |);
8101     print "Upgrade to $DBversion done (Bug 11751: Remove memberofinstitytion system preference)\n";
8102     SetVersion($DBversion);
8103 }
8104
8105 $DBversion = "3.15.00.023";
8106 if ( CheckVersion($DBversion) ) {
8107    $dbh->do("
8108        INSERT INTO systempreferences (variable,value,options,explanation,type)
8109        VALUES('CardnumberLength', '', '', 'Set a length for card numbers.', 'Free');
8110     ");
8111    print "Upgrade to $DBversion done (Bug 10861: Add CardnumberLength syspref)\n";
8112    SetVersion ($DBversion);
8113 }
8114
8115 $DBversion = "3.15.00.024";
8116 if ( CheckVersion($DBversion) ) {
8117     $dbh->do(q{
8118         DELETE FROM systempreferences WHERE variable = 'NoZebraIndexes'
8119     });
8120     print "Upgrade to $DBversion done (Bug 10012 - remove last vestiges of NoZebra)\n";
8121     SetVersion($DBversion);
8122 }
8123
8124 $DBversion = "3.15.00.025";
8125 if ( CheckVersion($DBversion) ) {
8126     $dbh->do(q{
8127         DROP TABLE aqorderdelivery;
8128     });
8129     print "Upgrade to $DBversion done (Bug 11928 - remove unused table)\n";
8130     SetVersion($DBversion);
8131 }
8132
8133 $DBversion = "3.15.00.026";
8134 if ( CheckVersion($DBversion) ) {
8135     $dbh->do(q{
8136         UPDATE language_descriptions SET description = 'Հայերեն' WHERE subtag = 'hy' AND lang = 'hy';
8137     });
8138     print "Upgrade to $DBversion done (Bug 11973 - Fix Armenian language description)\n";
8139     SetVersion($DBversion);
8140 }
8141
8142 $DBversion = "3.15.00.027";
8143 if (CheckVersion($DBversion)) {
8144     $dbh->do(q{
8145         ALTER TABLE opac_news ADD branchcode varchar(10) DEFAULT NULL
8146                                   AFTER idnew,
8147                               ADD CONSTRAINT opac_news_branchcode_ibfk
8148                                   FOREIGN KEY (branchcode)
8149                                   REFERENCES branches (branchcode)
8150                                   ON DELETE CASCADE ON UPDATE CASCADE;
8151     });
8152     print "Upgrade to $DBversion done (Bug 7567: Add branchcode to opac_news)\n";
8153     SetVersion($DBversion);
8154 }
8155
8156 $DBversion = "3.15.00.028";
8157 if(CheckVersion($DBversion)) {
8158     $dbh->do(q{
8159         ALTER TABLE issuingrules ADD norenewalbefore int(4) default NULL AFTER renewalperiod
8160     });
8161     print "Upgrade to $DBversion done (Bug 7413: Allow OPAC renewal x days before due date)\n";
8162     SetVersion($DBversion);
8163 }
8164
8165 $DBversion = "3.15.00.029";
8166 if ( CheckVersion($DBversion) ) {
8167     $dbh->do(q{
8168         UPDATE borrower_debarments SET expiration = NULL WHERE expiration = '9999-12-31'
8169     });
8170     print "Upgrade to $DBversion done (Bug 11846 - correct borrower_debarments with expiration 9999-12-31)\n";
8171     SetVersion($DBversion);
8172 }
8173
8174 $DBversion = "3.15.00.030";
8175 if(CheckVersion($DBversion)) {
8176     $dbh->do(q|
8177         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')
8178     |);
8179     print "Upgrade to $DBversion done (Bug 12052: Add OPACMySummaryNote syspref)\n";
8180     SetVersion($DBversion);
8181 }
8182
8183 $DBversion = "3.15.00.031";
8184 if ( CheckVersion($DBversion) ) {
8185    $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('10', 'writeoff', 'Write off fines and fees')");
8186    $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('10', 'remaining_permissions', 'Remaining permissions for managing fines and fees')");
8187    print "Upgrade to $DBversion done (Bug 9448 - Add separate permission for writing off fees)\n";
8188    SetVersion ($DBversion);
8189 }
8190
8191 $DBversion = "3.15.00.032";
8192 if ( CheckVersion($DBversion) ) {
8193     $dbh->do("ALTER TABLE aqorders CHANGE notes order_internalnote MEDIUMTEXT;");
8194     $dbh->do("ALTER TABLE aqorders ADD COLUMN order_vendornote MEDIUMTEXT AFTER order_internalnote;");
8195     print "Upgrade to $DBversion done (Bug 9416 - In each order, add a new note made for the vendor)\n";
8196    SetVersion ($DBversion);
8197 }
8198
8199 $DBversion = "3.15.00.033";
8200 if ( CheckVersion($DBversion) ) {
8201     $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')");
8202     print "Upgrade to $DBversion done (Bug 10951: Add NoLoginInstructions pref)\n";
8203     SetVersion($DBversion);
8204 }
8205
8206 $DBversion = "3.15.00.034";
8207 if ( CheckVersion($DBversion) ) {
8208     $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')");
8209     print "Upgrade to $DBversion done (Bug 10986: system preferences to limit languages in advanced search )\n";
8210     SetVersion ($DBversion);
8211 }
8212
8213 $DBversion = "3.15.00.035";
8214 if ( CheckVersion($DBversion) ) {
8215     #insert a notice for sharing a list and accepting a share
8216     $dbh->do("
8217 INSERT INTO letter (module, code, branchcode, name, is_html, title, content)
8218 VALUES ( 'members', 'SHARE_INVITE', '', 'Invitation for sharing a list', '0', 'Share list <<listname>>', 'Dear patron,
8219
8220 One of our patrons, <<borrowers.firstname>> <<borrowers.surname>>, invites you to share a list <<listname>> in our library catalog.
8221
8222 To access this shared list, please click on the following URL or copy-and-paste it into your browser address bar.
8223
8224 <<shareurl>>
8225
8226 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.
8227
8228 Thank you.
8229
8230 Your library.'
8231     )");
8232     $dbh->do("
8233 INSERT INTO letter (module, code, branchcode, name, is_html, title, content)
8234 VALUES ( 'members', 'SHARE_ACCEPT', '', 'Notification about an accepted share', '0', 'Share on list <<listname>> accepted', 'Dear patron,
8235
8236 We want to inform you that <<borrowers.firstname>> <<borrowers.surname>> accepted your invitation to share your list <<listname>> in our library catalog.
8237
8238 Thank you.
8239
8240 Your library.'
8241     )");
8242     print "Upgrade to $DBversion done (Bug 9032: Share a list)\n";
8243     SetVersion($DBversion);
8244 }
8245
8246 $DBversion = "3.15.00.036";
8247 if ( CheckVersion($DBversion) ) {
8248     $dbh->do(q{
8249         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
8250         VALUES('AllowMultipleIssuesOnABiblio',1,'Allow/Don\'t allow patrons to check out multiple items from one biblio','','YesNo')
8251     });
8252
8253     print "Upgrade to $DBversion done (Bug 10859 - Add system preference AllowMultipleIssuesOnABiblio)\n";
8254     SetVersion($DBversion);
8255 }
8256
8257 $DBversion = "3.15.00.037";
8258 if(CheckVersion($DBversion)) {
8259     $dbh->do(q{
8260         ALTER TABLE itemtypes ADD sip_media_type VARCHAR( 3 ) DEFAULT NULL AFTER checkinmsgtype
8261     });
8262     $dbh->do(q{
8263         INSERT INTO authorised_values (category, authorised_value, lib) VALUES
8264          ('SIP_MEDIA_TYPE', '000', 'Other'),
8265          ('SIP_MEDIA_TYPE', '001', 'Book'),
8266          ('SIP_MEDIA_TYPE', '002', 'Magazine'),
8267          ('SIP_MEDIA_TYPE', '003', 'Bound journal'),
8268          ('SIP_MEDIA_TYPE', '004', 'Audio tape'),
8269          ('SIP_MEDIA_TYPE', '005', 'Video tape'),
8270          ('SIP_MEDIA_TYPE', '006', 'CD/CDROM'),
8271          ('SIP_MEDIA_TYPE', '007', 'Diskette'),
8272          ('SIP_MEDIA_TYPE', '008', 'Book with diskette'),
8273          ('SIP_MEDIA_TYPE', '009', 'Book with CD'),
8274          ('SIP_MEDIA_TYPE', '010', 'Book with audio tape')
8275     });
8276     print "Upgrade to $DBversion done (Bug 11351 - Add support for SIP2 media type)\n";
8277     SetVersion($DBversion);
8278 }
8279
8280 $DBversion = '3.15.00.038';
8281 if ( CheckVersion($DBversion) ) {
8282     $dbh->do(q{
8283         INSERT INTO  systempreferences (
8284             variable,
8285             value,
8286             options,
8287             explanation,
8288             type
8289             )
8290         VALUES (
8291             'DisplayLibraryFacets',  'holding',  'home|holding|both',  'Defines which library facets to display.',  'Choice'
8292         );
8293     });
8294     print "Upgrade to $DBversion done (Bug 11334 - Add facet for home library)\n";
8295     SetVersion ($DBversion);
8296 }
8297
8298 $DBversion = "3.15.00.039";
8299 if ( CheckVersion($DBversion) ) {
8300
8301     $dbh->do( q{
8302         ALTER TABLE letter ADD COLUMN message_transport_type VARCHAR(20) NOT NULL DEFAULT 'email' AFTER content
8303     } );
8304
8305     $dbh->do( q{
8306         ALTER TABLE letter ADD CONSTRAINT message_transport_type_fk FOREIGN KEY (message_transport_type) REFERENCES message_transport_types(message_transport_type);
8307     } );
8308
8309     $dbh->do( q{
8310         ALTER TABLE letter DROP PRIMARY KEY, ADD PRIMARY KEY (`module`,`code`,`branchcode`, message_transport_type);
8311     } );
8312
8313     $dbh->do( q{
8314         CREATE TABLE overduerules_transport_types(
8315             id INT(11) NOT NULL AUTO_INCREMENT,
8316             branchcode varchar(10) NOT NULL DEFAULT '',
8317             categorycode VARCHAR(10) NOT NULL DEFAULT '',
8318             letternumber INT(1) NOT NULL DEFAULT 1,
8319             message_transport_type VARCHAR(20) NOT NULL DEFAULT 'email',
8320             PRIMARY KEY (id),
8321             CONSTRAINT overduerules_fk FOREIGN KEY (branchcode, categorycode) REFERENCES overduerules (branchcode, categorycode) ON DELETE CASCADE ON UPDATE CASCADE,
8322             CONSTRAINT mtt_fk FOREIGN KEY (message_transport_type) REFERENCES message_transport_types (message_transport_type) ON DELETE CASCADE ON UPDATE CASCADE
8323         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
8324     } );
8325
8326     my $sth = $dbh->prepare( q{
8327         SELECT * FROM overduerules;
8328     } );
8329
8330     $sth->execute;
8331     my $sth_insert_mtt = $dbh->prepare( q{
8332         INSERT INTO overduerules_transport_types (branchcode, categorycode, letternumber, message_transport_type) VALUES ( ?, ?, ?, ? )
8333     } );
8334     while ( my $row = $sth->fetchrow_hashref ) {
8335         my $branchcode = $row->{branchcode};
8336         my $categorycode = $row->{categorycode};
8337         for my $letternumber ( 1 .. 3 ) {
8338             next unless $row->{"letter$letternumber"};
8339             $sth_insert_mtt->execute(
8340                 $branchcode, $categorycode, $letternumber, 'email'
8341             );
8342         }
8343     }
8344
8345     print "Upgrade done (Bug 9016: Adds multi transport types management for notices)\n";
8346     SetVersion($DBversion);
8347 }
8348
8349 $DBversion = "3.15.00.040";
8350 if ( CheckVersion($DBversion) ) {
8351     $dbh->do(q|
8352         UPDATE message_transports SET letter_code='HOLD' WHERE letter_code='HOLD_PHONE' OR letter_code='HOLD_PRINT'
8353     |);
8354     $dbh->do(q|
8355         UPDATE letter SET code='HOLD', message_transport_type='print' WHERE code='HOLD_PRINT'
8356     |);
8357     $dbh->do(q|
8358         UPDATE letter SET code='HOLD', message_transport_type='phone' WHERE code='HOLD_PHONE'
8359     |);
8360     print "Upgrade to $DBversion done (Bug 10845: Multi transport types for holds)\n";
8361     SetVersion($DBversion);
8362 }
8363
8364 $DBversion = "3.15.00.041";
8365 if ( CheckVersion($DBversion) ) {
8366     my $name = $dbh->selectcol_arrayref(q|
8367         SELECT name FROM letter WHERE code="HOLD"
8368     |);
8369     $name = $name->[0];
8370     $dbh->do(q|
8371         UPDATE letter
8372         SET code="HOLD",
8373             message_transport_type="phone",
8374             name= ?
8375         WHERE code="HOLD_PHONE"
8376     |, {}, $name);
8377
8378     $dbh->do(q|
8379         UPDATE letter
8380         SET code="PREDUE",
8381             message_transport_type="phone",
8382             name= ?
8383         WHERE code="PREDUE_PHONE"
8384     |, {}, $name);
8385
8386     $dbh->do(q|
8387         UPDATE letter
8388         SET code="OVERDUE",
8389             message_transport_type="phone",
8390             name= ?
8391         WHERE code="OVERDUE_PHONE"
8392     |, {}, $name);
8393
8394     print "Upgrade to $DBversion done (Bug 11867: Update letters *_PHONE)\n";
8395     SetVersion($DBversion);
8396 }
8397
8398 $DBversion = "3.15.00.042";
8399 if ( CheckVersion($DBversion) ) {
8400     $dbh->do(q{
8401         INSERT INTO systempreferences
8402             (variable,value,explanation,options,type)
8403         VALUES
8404             ('SpecifyReturnDate',0,'Define whether to display \"Specify Return Date\" form in Circulation','','YesNo')
8405     });
8406     print "Upgrade to $DBversion done (Bug 10694 - Allow arbitrary backdating of returns)\n";
8407     SetVersion($DBversion);
8408 }
8409
8410 $DBversion = "3.15.00.043";
8411 if ( CheckVersion($DBversion) ) {
8412     $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')");
8413    print "Upgrade to $DBversion done (Bug 7180: Added MarcFieldsToOrder syspref)\n";
8414    SetVersion ($DBversion);
8415 }
8416
8417 $DBversion = "3.15.00.044";
8418 if ( CheckVersion($DBversion) ) {
8419     $dbh->do("ALTER TABLE currency ADD isocode VARCHAR(5) default NULL AFTER symbol;");
8420     print "Upgrade to $DBversion done (Added isocode to the currency table)\n";
8421     SetVersion($DBversion);
8422 }
8423
8424 $DBversion = "3.15.00.045";
8425 if ( CheckVersion($DBversion) ) {
8426     $dbh->do("
8427         INSERT INTO systempreferences (variable,value,explanation,options,type)
8428         VALUES (
8429             'BlockExpiredPatronOpacActions',
8430             '0',
8431             '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',
8432             NULL,
8433             'YesNo'
8434         )
8435     ");
8436     $dbh->do("ALTER TABLE `categories` ADD COLUMN `BlockExpiredPatronOpacActions` TINYINT(1) DEFAULT -1 NOT NULL AFTER category_type");
8437     print "Upgraded to $DBversion done (Bug 6739 - expired patrons not blocked from opac actions)\n";
8438     SetVersion ($DBversion);
8439 }
8440
8441 $DBversion = "3.15.00.046";
8442 if ( CheckVersion($DBversion) ) {
8443     $dbh->do(q|
8444         ALTER TABLE search_history ADD COLUMN type VARCHAR(16) NOT NULL DEFAULT 'biblio' AFTER query_cgi
8445     |);
8446     print "Upgrade to $DBversion done (Bug 10807 - Add db field search_history.type)\n";
8447     SetVersion($DBversion);
8448 }
8449
8450 $DBversion = "3.15.00.047";
8451 if ( CheckVersion($DBversion) ) {
8452     $dbh->do(q|
8453         INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('EnableSearchHistory','0','','Enable or disable search history','YesNo')
8454     |);
8455     print "Upgrade to $DBversion done (Bug 10862: Add EnableSearchHistory syspref)\n";
8456     SetVersion($DBversion);
8457 }
8458
8459 $DBversion = "3.15.00.048";
8460 if ( CheckVersion($DBversion) ) {
8461     $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')");
8462     $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')");
8463     print "Upgrade to $DBversion done (Bug 10195: Records hidden with OpacSuppression can still be accessed)\n";
8464     SetVersion($DBversion);
8465 }
8466
8467 $DBversion = "3.15.00.049";
8468 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
8469     $dbh->do("ALTER TABLE biblioitems DROP INDEX isbn");
8470     $dbh->do("ALTER TABLE biblioitems DROP INDEX issn");
8471     $dbh->do("ALTER TABLE biblioitems
8472               CHANGE isbn isbn MEDIUMTEXT NULL DEFAULT NULL,
8473               CHANGE issn issn MEDIUMTEXT NULL DEFAULT NULL
8474     ");
8475     $dbh->do("ALTER TABLE biblioitems
8476               ADD INDEX isbn ( isbn ( 255 ) ),
8477               ADD INDEX issn ( issn ( 255 ) )
8478     ");
8479
8480     $dbh->do("ALTER TABLE deletedbiblioitems DROP INDEX isbn");
8481     $dbh->do("ALTER TABLE deletedbiblioitems
8482               CHANGE isbn isbn MEDIUMTEXT NULL DEFAULT NULL,
8483               CHANGE issn issn MEDIUMTEXT NULL DEFAULT NULL
8484     ");
8485     $dbh->do("ALTER TABLE deletedbiblioitems
8486               ADD INDEX isbn ( isbn ( 255 ) )
8487     ");
8488
8489     print "Upgrade to $DBversion done (Bug 5377 - Biblioitems isbn and issn fields too small for multiple ISBN and ISSN)\n";
8490     SetVersion($DBversion);
8491 }
8492
8493 $DBversion = "3.15.00.050";
8494 if ( CheckVersion($DBversion) ) {
8495     $dbh->do("
8496         INSERT INTO systempreferences (
8497             variable,
8498             value,
8499             explanation,
8500             type
8501         ) VALUES (
8502             'AggressiveMatchOnISBN',
8503             '0',
8504             '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',
8505             'YesNo'
8506         )
8507     ");
8508
8509     print "Upgrade to $DBversion done (Bug 10500 - Improve isbn matching when importing records)\n";
8510     SetVersion($DBversion);
8511 }
8512
8513 $DBversion = "3.15.00.051";
8514 if ( CheckVersion($DBversion) ) {
8515     print "Upgrade to $DBversion done (Koha 3.16 beta)\n";
8516     SetVersion($DBversion);
8517 }
8518
8519 $DBversion = "3.15.00.052";
8520 if ( CheckVersion($DBversion) ) {
8521     print "Upgrade to $DBversion done (Koha 3.16 RC)\n";
8522     SetVersion($DBversion);
8523 }
8524
8525 $DBversion = "3.16.00.000";
8526 if ( CheckVersion($DBversion) ) {
8527     print "Upgrade to $DBversion done (3.16.0 release)\n";
8528     SetVersion ($DBversion);
8529 }
8530
8531 $DBversion = '3.17.00.000';
8532 if ( CheckVersion($DBversion) ) {
8533     print "Upgrade to $DBversion done (there is no time to rest on our laurels)\n";
8534     SetVersion ($DBversion);
8535 }
8536
8537 $DBversion = '3.17.00.001';
8538 if ( CheckVersion($DBversion) ) {
8539    $dbh->do("UPDATE systempreferences SET variable = 'AuthoritySeparator' WHERE variable = 'authoritysep'");
8540    print "Upgrade to $DBversion done (Bug 10330 - Rename system preference authoritysep to AuthoritySeparator)\n";
8541    SetVersion ($DBversion);
8542 }
8543
8544 $DBversion = "3.17.00.002";
8545 if (CheckVersion($DBversion)) {
8546     $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')");
8547     $dbh->do("
8548 CREATE TABLE IF NOT EXISTS `misc_files` (
8549   `file_id` int(11) NOT NULL AUTO_INCREMENT,
8550   `table_tag` varchar(255) NOT NULL,
8551   `record_id` int(11) NOT NULL,
8552   `file_name` varchar(255) NOT NULL,
8553   `file_type` varchar(255) NOT NULL,
8554   `file_description` varchar(255) DEFAULT NULL,
8555   `file_content` longblob NOT NULL, -- file content
8556   `date_uploaded` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
8557   PRIMARY KEY (`file_id`),
8558   KEY `table_tag` (`table_tag`),
8559   KEY `record_id` (`record_id`)
8560 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
8561     ");
8562     print "Upgrade to $DBversion done (Bug 3050 - Add an option to upload scanned invoices)\n";
8563     SetVersion($DBversion);
8564 }
8565
8566 $DBversion = "3.17.00.003";
8567 if (CheckVersion($DBversion)) {
8568     $dbh->do("UPDATE systempreferences SET type = 'Choice', options = '0|1|force' WHERE variable = 'OPACItemHolds'");
8569     print "Upgrade to $DBversion done (Bug 7825 - Changed OPACItemHolds syspref to Choice)\n";
8570     SetVersion($DBversion);
8571 }
8572
8573 $DBversion = "3.17.00.004";
8574 if (CheckVersion($DBversion)) {
8575     $dbh->do("ALTER TABLE categories ADD default_privacy ENUM( 'default', 'never', 'forever' ) NOT NULL DEFAULT 'default' AFTER category_type");
8576     print "Upgrade to $DBversion done (Bug 6254 - can't set patron privacy by default)\n";
8577     SetVersion($DBversion);
8578 }
8579
8580 $DBversion = "3.17.00.005";
8581 if (CheckVersion($DBversion)) {
8582     $dbh->do(q|
8583         ALTER TABLE issuingrules
8584         ADD maxsuspensiondays INT(11) DEFAULT NULL AFTER finedays;
8585     |);
8586     print "Upgrade to $DBversion done (Bug 12230: Add new issuing rule maxsuspensiondays)\n";
8587     SetVersion($DBversion);
8588 }
8589
8590 $DBversion = "3.17.00.006";
8591 if ( CheckVersion($DBversion) ) {
8592     $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')");
8593     $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')");
8594     print "Upgrade to $DBversion done (Bug 7720 - Ambiguity in OPAC Details location.)\n";
8595     SetVersion($DBversion);
8596 }
8597
8598 $DBversion = "3.17.00.007";
8599 if (CheckVersion($DBversion)) {
8600     $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');");
8601     print "Upgrade to $DBversion done (Bug 11629 - Add ability to update not for loan status on checkin)\n";
8602     SetVersion($DBversion);
8603 }
8604
8605 $DBversion = "3.17.00.008";
8606 if ( CheckVersion($DBversion) ) {
8607     $dbh->do(q|
8608         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('OPACAcquisitionDetails','0', '','Show the acquisition details at the OPAC','YesNo')
8609     |);
8610     print "Upgrade to $DBversion done (Bug 11169 - Add OPACAcquisitionDetails syspref)\n";
8611     SetVersion($DBversion);
8612 }
8613
8614 $DBversion = "3.17.00.009";
8615 if ( CheckVersion($DBversion) ) {
8616     $dbh->do(q{
8617         DELETE FROM systempreferences WHERE variable = 'UseTablesortForCirc'
8618     });
8619
8620     print "Upgrade to $DBversion done (Bug 11703 - Remove UseTablesortForCirc syspref)\n";
8621     SetVersion($DBversion);
8622 }
8623
8624 $DBversion = "3.17.00.010";
8625 if ( CheckVersion($DBversion) ) {
8626     $dbh->do("DELETE FROM systempreferences WHERE variable='opacsmallimage'");
8627     print "Upgrade to $DBversion done (Bug 11347 - PROG/CCSR deprecation: Remove opacsmallimage system preference)\n";
8628     SetVersion($DBversion);
8629 }
8630
8631 $DBversion = "3.17.00.011";
8632 if ( CheckVersion($DBversion) ) {
8633     $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'hr', 'language', 'Croatian','2014-07-24' )");
8634     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'hr','hrv')");
8635     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'hr', 'Hrvatski')");
8636     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'en', 'Croatian')");
8637     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'fr', 'Croate')");
8638     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'de', 'Kroatisch')");
8639     print "Upgrade to $DBversion done (Bug 12649: Add Croatian language)\n";
8640     SetVersion ($DBversion);
8641 }
8642
8643 $DBversion = "3.17.00.012";
8644 if ( CheckVersion($DBversion) ) {
8645     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacShowFiltersPulldownMobile'");
8646     print "Upgrade to $DBversion done ( Bug 12512 - PROG/CCSR deprecation: Remove OpacShowFiltersPulldownMobile system preference )\n";
8647     SetVersion ($DBversion);
8648 }
8649
8650 $DBversion = "3.17.00.013";
8651 if ( CheckVersion($DBversion) ) {
8652     $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')");
8653     print "Upgrade to $DBversion done (Re-add system preference maxreserves)\n";
8654     SetVersion ($DBversion);
8655 }
8656
8657 $DBversion = '3.17.00.014';
8658 if ( CheckVersion($DBversion) ) {
8659     $dbh->do("
8660         INSERT INTO systempreferences (variable,value,explanation,type) VALUES
8661         ('OverdueNoticeCalendar',0,'Take calendar into consideration when working out sending overdue notices','YesNo')
8662     ");
8663     print "Upgrade to $DBversion done (Bug 12529 - Adding a syspref to allow the overdue notices to consider the calendar when generating notices)\n";
8664     SetVersion($DBversion);
8665 }
8666
8667 $DBversion = "3.17.00.015";
8668 if ( CheckVersion($DBversion) ) {
8669     $dbh->do(q{
8670         CREATE TABLE IF NOT EXISTS columns_settings (
8671             module varchar(255) NOT NULL,
8672             page varchar(255) NOT NULL,
8673             tablename varchar(255) NOT NULL,
8674             columnname varchar(255) NOT NULL,
8675             cannot_be_toggled int(1) NOT NULL DEFAULT 0,
8676             is_hidden int(1) NOT NULL DEFAULT 0,
8677             PRIMARY KEY(module, page, tablename, columnname)
8678         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
8679     });
8680     print "Upgrade to $DBversion done (Bug 10212 - Create new table columns_settings)\n";
8681     SetVersion ($DBversion);
8682 }
8683
8684 $DBversion = "3.17.00.016";
8685 if ( CheckVersion($DBversion) ) {
8686     $dbh->do("CREATE TABLE aqcontacts (
8687         id int(11) NOT NULL auto_increment,
8688         name varchar(100) default NULL,
8689         position varchar(100) default NULL,
8690         phone varchar(100) default NULL,
8691         altphone varchar(100) default NULL,
8692         fax varchar(100) default NULL,
8693         email varchar(100) default NULL,
8694         notes mediumtext,
8695         claimacquisition BOOLEAN NOT NULL DEFAULT 0,
8696         claimissues BOOLEAN NOT NULL DEFAULT 0,
8697         acqprimary BOOLEAN NOT NULL DEFAULT 0,
8698         serialsprimary BOOLEAN NOT NULL DEFAULT 0,
8699         booksellerid int(11) not NULL,
8700         PRIMARY KEY  (id),
8701         CONSTRAINT booksellerid_aqcontacts_fk FOREIGN KEY (booksellerid)
8702             REFERENCES aqbooksellers (id) ON DELETE CASCADE ON UPDATE CASCADE
8703         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;");
8704     $dbh->do("INSERT INTO aqcontacts (name, position, phone, altphone, fax,
8705             email, notes, booksellerid, claimacquisition, claimissues, acqprimary, serialsprimary)
8706         SELECT contact, contpos, contphone, contaltphone, contfax, contemail,
8707             contnotes, id, 1, 1, 1, 1 FROM aqbooksellers;");
8708     $dbh->do("ALTER TABLE aqbooksellers DROP COLUMN contact,
8709         DROP COLUMN contpos, DROP COLUMN contphone,
8710         DROP COLUMN contaltphone, DROP COLUMN contfax,
8711         DROP COLUMN contemail, DROP COLUMN contnotes;");
8712     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contact>>', '<<aqcontacts.name>>')");
8713     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contpos>>', '<<aqcontacts.position>>')");
8714     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contphone>>', '<<aqcontacts.phone>>')");
8715     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contaltphone>>', '<<aqcontacts.altphone>>')");
8716     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contfax>>', '<<aqcontacts.contfax>>')");
8717     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contemail>>', '<<aqcontacts.contemail>>')");
8718     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contnotes>>', '<<aqcontacts.contnotes>>')");
8719     print "Upgrade to $DBversion done (Bug 10402: Move bookseller contacts to separate table)\n";
8720     SetVersion($DBversion);
8721 }
8722
8723 $DBversion = "3.17.00.017";
8724 if ( CheckVersion($DBversion) ) {
8725     # Correct invalid recordtypes (should be very exceptional)
8726     $dbh->do(q{
8727         UPDATE z3950servers set recordtype='biblio' WHERE recordtype NOT IN ('authority','biblio')
8728     });
8729     # Correct invalid server types (should also be very exceptional)
8730     $dbh->do(q{
8731         UPDATE z3950servers set type='zed' WHERE type <> 'zed'
8732     });
8733     # Adjust table
8734     $dbh->do(q{
8735         ALTER TABLE z3950servers
8736         DROP COLUMN icon,
8737         DROP COLUMN description,
8738         DROP COLUMN position,
8739         MODIFY COLUMN id int NOT NULL AUTO_INCREMENT FIRST,
8740         MODIFY COLUMN recordtype enum('authority','biblio') NOT NULL DEFAULT 'biblio',
8741         CHANGE COLUMN name servername mediumtext NOT NULL,
8742         CHANGE COLUMN type servertype enum('zed','sru') NOT NULL DEFAULT 'zed',
8743         ADD COLUMN sru_options varchar(255) default NULL,
8744         ADD COLUMN sru_fields mediumtext default NULL,
8745         ADD COLUMN add_xslt mediumtext default NULL
8746     });
8747     print "Upgrade to $DBversion done (Bug 6536: Z3950 improvements)\n";
8748     SetVersion ($DBversion);
8749 }
8750
8751 $DBversion = "3.17.00.018";
8752 if ( CheckVersion($DBversion) ) {
8753     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('HoldsInNoissuesCharge', '0', 'Hold charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
8754     print "Upgrade to $DBversion done (Bug 12205: Add HoldsInNoissuesCharge systempreference)\n";
8755     SetVersion($DBversion);
8756 }
8757
8758 $DBversion = "3.17.00.019";
8759 if ( CheckVersion($DBversion) ) {
8760     $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')"
8761     );
8762     print "Upgrade to $DBversion done (Bug 6149: Operator highlighted in search results)\n";
8763     SetVersion($DBversion);
8764 }
8765
8766 $DBversion = "3.17.00.020";
8767 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
8768     $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')");
8769     print "Upgrade to $DBversion done (Bug 8735 - Expire holds waiting only on days the library is open)\n";
8770     SetVersion ($DBversion);
8771 }
8772
8773 $DBversion = "3.17.00.021";
8774 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
8775     my $pref = C4::Context->preference('HomeOrHoldingBranch');
8776     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
8777        VALUES ('StaffSearchResultsDisplayBranch', ?,'homebranch|holdingbranch','Controls the display of the home or holding branch for staff search results','choice')", undef, $pref);
8778     print "Upgrade to $DBversion done (Bug 12582 - Control of branch displayed in search results linked to HomeOrHoldingBranch)\n";
8779     SetVersion ($DBversion);
8780 }
8781
8782 $DBversion = '3.17.00.022';
8783 if ( CheckVersion($DBversion) ) {
8784     my @temp= $dbh->selectrow_array(qq|
8785         SELECT count(*)
8786         FROM marc_subfield_structure
8787         WHERE kohafield='permanent_location' OR kohafield='items.permanent_location'
8788     |);
8789     print "Upgrade to $DBversion done (Bug 7817: Check for permanent_location)\n";
8790     if( $temp[0] ) {
8791         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";
8792     }
8793     SetVersion($DBversion);
8794 }
8795
8796 $DBversion = "3.17.00.023";
8797 if ( CheckVersion($DBversion) ) {
8798     $dbh->do(q{
8799         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')
8800     });
8801     print "Upgrade to $DBversion done (Bug 11169 - Add AcqItemSetSubfieldsWhenReceiptIsCancelled syspref)\n";
8802     SetVersion($DBversion);
8803 }
8804
8805 $DBversion = "3.17.00.024";
8806 if(CheckVersion($DBversion)) {
8807     $dbh->do(q{
8808         ALTER TABLE issues ADD auto_renew BOOLEAN default FALSE AFTER renewals
8809     });
8810     $dbh->do(q{
8811         ALTER TABLE old_issues ADD auto_renew BOOLEAN default FALSE AFTER renewals
8812     });
8813     $dbh->do(q{
8814         ALTER TABLE issuingrules ADD auto_renew BOOLEAN default FALSE AFTER norenewalbefore
8815     });
8816     print "Upgrade to $DBversion done (Bug 11577: [ENH] Automatic renewal feature)\n";
8817     SetVersion($DBversion);
8818 }
8819
8820 $DBversion = '3.17.00.025';
8821 if ( CheckVersion($DBversion) ) {
8822     $dbh->do(qq{
8823         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')
8824     });
8825     print "Upgrade to $DBversion done (Bug 12728: Checked syspref StatisticsFields)\n";
8826 }
8827
8828 $DBversion = "3.17.00.026";
8829 if ( CheckVersion($DBversion) ) {
8830     if ( C4::Context->preference('marcflavour') eq 'MARC21' ) {
8831         $dbh->do("UPDATE marc_subfield_structure SET liblibrarian = 'Encoded bitrate', libopac = 'Encoded bitrate' WHERE tagfield = '347' AND tagsubfield = 'f'");
8832         $dbh->do("UPDATE marc_subfield_structure SET repeatable = 1 WHERE tagfield IN ('110','111','610','611','710','711','810','811') AND tagsubfield = 'c'");
8833         $dbh->do("UPDATE auth_subfield_structure SET repeatable = 1 WHERE tagfield IN ('110','111','410','411','510','511','710','711') AND tagsubfield = 'c'");
8834         print "Upgrade to $DBversion done (Bug 12435 - Update MARC21 frameworks to Update No. 18 (April 2014))\n";
8835     }
8836     SetVersion($DBversion);
8837 }
8838
8839 $DBversion = "3.17.00.027";
8840 if ( CheckVersion($DBversion) ) {
8841     $dbh->do(q{
8842         DELETE FROM systempreferences WHERE variable = 'SearchEngine'
8843     });
8844     print "Upgrade to $DBversion done (Bug 12538 - Remove SearchEngine syspref)\n";
8845     SetVersion($DBversion);
8846 }
8847
8848 $DBversion = "3.17.00.028";
8849 if ( CheckVersion($DBversion) ) {
8850     $dbh->do(q{
8851         INSERT INTO systempreferences (variable,value) VALUES('OpacCustomSearch','');
8852     });
8853     print "Upgrade to $DBversion done (Bug 12296 - search box replaceable with a system preference)\n";
8854     SetVersion($DBversion);
8855 }
8856
8857 $DBversion = "3.17.00.029";
8858 if ( CheckVersion($DBversion) ) {
8859     $dbh->do("ALTER TABLE  `items` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8860     $dbh->do("ALTER TABLE  `deleteditems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8861     $dbh->do("ALTER TABLE  `biblioitems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8862     $dbh->do("ALTER TABLE  `deletedbiblioitems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8863     print "Upgrade to $DBversion done (Bug 12424 - ddc sorting of call numbers truncates long Cutter parts)\n";
8864     SetVersion ($DBversion);
8865 }
8866
8867 $DBversion = "3.17.00.030";
8868 if ( CheckVersion($DBversion) ) {
8869     $dbh->do(
8870         q{
8871        INSERT INTO systempreferences (variable, value, options, explanation, type )
8872        VALUES
8873         ('UsageStatsCountry', '', NULL, 'The country where your library is located, to be shown on the Hea Koha community website', 'YesNo'),
8874         ('UsageStatsID', '', NULL, 'This preference is part of Koha but it should not be deleted or updated manually.',  'Free'),
8875         ('UsageStatsLastUpdateTime', '', NULL, 'This preference is part of Koha but it should not be deleted or updated manually.', 'Free'),
8876         ('UsageStatsLibraryName', '', NULL, 'The library name to be shown on Hea Koha community website', 'Free'),
8877         ('UsageStatsLibraryType', 'public', 'public|university', 'The library type to be shown on the Hea Koha community website', 'Choice'),
8878         ('UsageStatsLibraryUrl', '', NULL, 'The library URL to be shown on Hea Koha community website', 'Free'),
8879         ('UsageStats', 0, NULL, 'Share anonymous usage data on the Hea Koha community website.', 'YesNo')
8880     });
8881     print "Upgrade to $DBversion done (Bug 11926: Add UsageStats systempreferences (HEA))\n";
8882     SetVersion ($DBversion);
8883 }
8884
8885 $DBversion = "3.17.00.031";
8886 if ( CheckVersion($DBversion) ) {
8887    $dbh->do("ALTER TABLE saved_sql CHANGE report_name report_name VARCHAR( 255 ) NOT NULL DEFAULT '' ");
8888    print "Upgrade to $DBversion done (Bug 2969: Report Name should be mandatory for saved reports)\n";
8889    SetVersion ($DBversion);
8890 }
8891
8892 $DBversion = "3.17.00.032";
8893 if ( CheckVersion($DBversion) ) {
8894     $dbh->do(
8895 "INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('ReplytoDefault',  '',  NULL,  'The default email address to be set as replyto.',  'Free')"
8896     );
8897     $dbh->do(
8898 "INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('ReturnpathDefault',  '',  NULL,  'The default email address to be set as return-path',  'Free')"
8899     );
8900     $dbh->do("ALTER TABLE branches ADD branchreplyto mediumtext AFTER branchemail");
8901     $dbh->do("ALTER TABLE branches ADD branchreturnpath mediumtext AFTER branchreplyto");
8902     print "Upgrade to $DBversion done (Bug 9530: Adding replyto and returnpath addresses.)\n";
8903     SetVersion($DBversion);
8904 }
8905
8906 $DBversion = "3.17.00.033";
8907 if ( CheckVersion($DBversion) ) {
8908     $dbh->do(q{
8909         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
8910         VALUES('FacetMaxCount', '20','Specify the max facet count for each category',NULL,'Integer')
8911     });
8912     print "Upgrade to $DBversion done (Bug 13088 - Allow the user to specify a max amount of facets to show)\n";
8913     SetVersion($DBversion);
8914 }
8915
8916 $DBversion = "3.17.00.034";
8917 if ( CheckVersion($DBversion) ) {
8918     $dbh->do(q|
8919         ALTER TABLE aqorders DROP COLUMN cancelledby;
8920     |);
8921
8922     print "Upgrade to $DBversion done (Bug 11007 - DROP column aqorders.cancelledby)\n";
8923     SetVersion($DBversion);
8924 }
8925
8926 $DBversion = "3.17.00.035";
8927 if ( CheckVersion($DBversion) ) {
8928     $dbh->do(q|
8929         ALTER TABLE serial ADD COLUMN claims_count INT(11) DEFAULT 0 after claimdate
8930     |);
8931     $dbh->do(q|
8932         UPDATE serial
8933         SET claims_count = 1
8934         WHERE claimdate IS NOT NULL
8935     |);
8936     print "Upgrade to $DBversion done (Bug 5342: Add claims_count field in serial table)\n";
8937     SetVersion($DBversion);
8938 }
8939
8940 $DBversion = "3.17.00.036";
8941 if ( CheckVersion($DBversion) ) {
8942     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacShowLibrariesPulldownMobile'");
8943     print "Upgrade to $DBversion done ( Bug 12513 - PROG/CCSR deprecation: Remove OpacShowLibrariesPulldownMobile system preference )\n";
8944     SetVersion ($DBversion);
8945 }
8946
8947 $DBversion = "3.17.00.037";
8948 if ( CheckVersion($DBversion) ) {
8949     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacMainUserBlockMobile'");
8950     print "Upgrade to $DBversion done ( Bug 12246 - PROG/CCSR deprecation: Remove OpacMainUserBlockMobile system preference )\n";
8951     SetVersion ($DBversion);
8952 }
8953
8954 $DBversion = "3.17.00.038";
8955 if ( CheckVersion($DBversion) ) {
8956     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACMobileUserCSS'");
8957     print "Upgrade to $DBversion done ( Bug 12245 - PROG/CCSR deprecation: Remove OPACMobileUserCSS system preference )\n";
8958     SetVersion ($DBversion);
8959 }
8960
8961 $DBversion = "3.17.00.039";
8962 if ( CheckVersion($DBversion) ) {
8963     $dbh->do("INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES
8964     ('OPACFallback', 'prog', 'bootstrap|prog', 'Define the fallback theme for the OPAC interface.', 'Themes')");
8965     print "Upgrade to $DBversion done (Bug 12539 - PROG/CCSR deprecation: Remove hardcoded theme from C4/Templates.pm)\n";
8966     SetVersion ($DBversion);
8967 }
8968
8969 $DBversion = "3.17.00.040";
8970 if ( CheckVersion($DBversion) ) {
8971     my $opac_theme = C4::Context->preference( 'opacthemes' );
8972     if ( !defined $opac_theme || $opac_theme eq 'prog' || $opac_theme eq 'ccsr' ) {
8973         $dbh->do("UPDATE systempreferences SET value='bootstrap' WHERE variable='opacthemes'");
8974     }
8975     print "Upgrade to $DBversion done (Bug 12223: 'prog' and 'ccsr' themes removed)\n";
8976     SetVersion($DBversion);
8977 }
8978
8979 $DBversion = "3.17.00.041";
8980 if ( CheckVersion($DBversion) ) {
8981     print "Upgrade to $DBversion done (Bug 11346: Deprecate the 'prog' and 'CCSR' themes)\n";
8982     SetVersion($DBversion);
8983 }
8984
8985 $DBversion = "3.17.00.042";
8986 if ( CheckVersion($DBversion) ) {
8987     $dbh->do("DELETE FROM systempreferences WHERE variable='yuipath'");
8988     print "Upgrade to $DBversion done (Bug 12494: Remove yuipath system preference)\n";
8989     SetVersion ($DBversion);
8990 }
8991
8992 $DBversion = "3.17.00.043";
8993 if ( CheckVersion($DBversion) ) {
8994     $dbh->do("
8995         ALTER TABLE aqorders
8996         ADD COLUMN cancellationreason TEXT DEFAULT NULL AFTER datecancellationprinted
8997     ");
8998     print "Upgrade to $DBversion done (Bug 7162: Add aqorders.cancellationreason)\n";
8999     SetVersion ($DBversion);
9000 }
9001
9002 $DBversion = "3.17.00.044";
9003 if ( CheckVersion($DBversion) ) {
9004     $dbh->do(q{
9005         INSERT IGNORE INTO systempreferences
9006             (variable,value,explanation,options,type)
9007             VALUES('OnSiteCheckouts','0','Enable/Disable the on-site checkouts feature','','YesNo');
9008     });
9009     $dbh->do(q{
9010         INSERT IGNORE INTO systempreferences
9011             (variable,value,explanation,options,type)
9012             VALUES('OnSiteCheckoutsForce','0','Enable/Disable the on-site for all cases (Even if a user is debarred, etc.)','','YesNo');
9013     });
9014     $dbh->do(q{
9015         ALTER TABLE issues ADD COLUMN onsite_checkout INT(1) NOT NULL DEFAULT 0 AFTER issuedate;
9016     });
9017     $dbh->do(q{
9018         ALTER TABLE old_issues ADD COLUMN onsite_checkout INT(1) NOT NULL DEFAULT 0 AFTER issuedate;
9019     });
9020     print "Upgrade to $DBversion done (Bug 10860: Add new system preference OnSiteCheckouts + fields [old_]issues.onsite_checkout)\n";
9021     SetVersion($DBversion);
9022 }
9023
9024 $DBversion = "3.17.00.045";
9025 if ( CheckVersion($DBversion) ) {
9026     $dbh->do(q{
9027         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
9028         ('LocalHoldsPriority',  '0', NULL,  'Enables the LocalHoldsPriority feature',  'YesNo'),
9029         ('LocalHoldsPriorityItemControl',  'holdingbranch',  'holdingbranch|homebranch',  'decides if the feature operates using the item''s home or holding library.',  'Choice'),
9030         ('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')
9031     });
9032     print "Upgrade to $DBversion done (Bug 11126 - Make the holds system optionally give precedence to local holds)\n";
9033     SetVersion($DBversion);
9034 }
9035
9036 $DBversion = "3.17.00.046";
9037 if ( CheckVersion($DBversion) ) {
9038     $dbh->do(q{
9039         CREATE TABLE IF NOT EXISTS items_search_fields (
9040           name VARCHAR(255) NOT NULL,
9041           label VARCHAR(255) NOT NULL,
9042           tagfield CHAR(3) NOT NULL,
9043           tagsubfield CHAR(1) NULL DEFAULT NULL,
9044           authorised_values_category VARCHAR(16) NULL DEFAULT NULL,
9045           PRIMARY KEY(name),
9046           CONSTRAINT items_search_fields_authorised_values_category
9047             FOREIGN KEY (authorised_values_category) REFERENCES authorised_values (category)
9048             ON DELETE SET NULL ON UPDATE CASCADE
9049         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
9050     });
9051     print "Upgrade to $DBversion done (Bug 11425: Add items_search_fields table)\n";
9052     SetVersion($DBversion);
9053 }
9054
9055 $DBversion = "3.17.00.047";
9056 if ( CheckVersion($DBversion) ) {
9057     $dbh->do(q{
9058         ALTER TABLE collections
9059             CHANGE colBranchcode colBranchcode VARCHAR( 10 ) NULL DEFAULT NULL,
9060             ADD INDEX ( colBranchcode ),
9061             ADD CONSTRAINT collections_ibfk_1 FOREIGN KEY (colBranchcode) REFERENCES branches (branchcode) ON DELETE CASCADE ON UPDATE CASCADE
9062     });
9063     print "Upgrade to $DBversion done (Bug 8836 - Resurrect Rotating Collections)\n";
9064     SetVersion($DBversion);
9065 }
9066
9067 $DBversion = "3.17.00.048";
9068 if ( CheckVersion($DBversion) ) {
9069     $dbh->do(q|
9070         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')
9071     |);
9072     print "Upgrade to $DBversion done (Bug 12448 - Add RentalFeesCheckoutConfirmation syspref)\n";
9073     SetVersion($DBversion);
9074 }
9075
9076 $DBversion = "3.17.00.049";
9077 if ( CheckVersion($DBversion) ) {
9078     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'am', 'language', 'Amharic','2014-10-29')");
9079     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'am','amh')");
9080     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'am', 'language', 'am', 'አማርኛ')");
9081     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'am', 'language', 'en', 'Amharic')");
9082
9083     $dbh->do("UPDATE language_descriptions SET description = 'لعربية' WHERE subtag = 'ar' AND type = 'language' AND lang = 'ar'");
9084
9085     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'az', 'language', 'Azerbaijani','2014-10-30')");
9086     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'az','aze')");
9087     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'az', 'language', 'az', 'Azərbaycan dili')");
9088     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'az', 'language', 'en', 'Azerbaijani')");
9089
9090     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'be', 'language', 'Byelorussian','2014-10-30')");
9091     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'be','bel')");
9092     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'be', 'language', 'be', 'Беларуская мова')");
9093     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'be', 'language', 'en', 'Byelorussian')");
9094
9095     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'bn', 'language', 'Bengali','2014-10-30')");
9096     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'bn','ben')");
9097     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'bn', 'language', 'bn', 'বাংলা')");
9098     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'bn', 'language', 'en', 'Bengali')");
9099
9100     $dbh->do("UPDATE language_descriptions SET description = 'Български' WHERE subtag = 'bg' AND type = 'language' AND lang = 'bg'");
9101     $dbh->do("UPDATE language_descriptions SET description = 'Ceština' WHERE subtag = 'cs' AND type = 'language' AND lang = 'cs'");
9102     $dbh->do("UPDATE language_descriptions SET description = 'Ελληνικά' WHERE subtag = 'el' AND type = 'language' AND lang = 'el'");
9103     $dbh->do("UPDATE language_descriptions SET description = 'Español' WHERE subtag = 'es' AND type = 'language' AND lang = 'es'");
9104
9105     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'eu', 'language', 'Basque','2014-10-30')");
9106     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'eu','eus')");
9107     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'eu', 'language', 'eu', 'Euskera')");
9108     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'eu', 'language', 'en', 'Basque')");
9109
9110     $dbh->do("UPDATE language_descriptions SET description = 'فارسى' WHERE subtag = 'fa' AND type = 'language' AND lang = 'fa'");
9111     $dbh->do("UPDATE language_descriptions SET description = 'Suomi' WHERE subtag = 'fi' AND type = 'language' AND lang = 'fi'");
9112
9113     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'fo', 'language', 'Faroese','2014-10-30')");
9114     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'fo','fao')");
9115     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'fo', 'language', 'fo', 'Føroyskt')");
9116     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'fo', 'language', 'en', 'Faroese')");
9117
9118     $dbh->do("UPDATE language_descriptions SET description = 'Français' WHERE subtag = 'fr' AND type = 'language' AND lang = 'fr'");
9119     $dbh->do("UPDATE language_descriptions SET description = 'עִבְרִית' WHERE subtag = 'he' AND type = 'language' AND lang = 'he'");
9120     $dbh->do("UPDATE language_descriptions SET description = 'हिन्दी' WHERE subtag = 'hi' AND type = 'language' AND lang = 'hi'");
9121
9122     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'is', 'language', 'Icelandic','2014-10-30')");
9123     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'is','ice')");
9124     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'is', 'language', 'is', 'Íslenska')");
9125     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'is', 'language', 'en', 'Icelandic')");
9126
9127     $dbh->do("UPDATE language_descriptions SET description = '日本語' WHERE subtag = 'ja' AND type = 'language' AND lang = 'ja'");
9128
9129     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ka', 'language', 'Kannada','2014-10-30')");
9130     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ka','kan')");
9131     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'ka', 'ಕನ್ನಡ')");
9132     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'en', 'Kannada')");
9133
9134     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'km', 'language', 'Khmer','2014-10-30')");
9135     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'km','khm')");
9136     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'km', 'language', 'km', 'ភាសាខ្មែរ')");
9137     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'km', 'language', 'en', 'Khmer')");
9138
9139     $dbh->do("UPDATE language_descriptions SET description = '한국어' WHERE subtag = 'ko' AND type = 'language' AND lang = 'ko'");
9140
9141     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ku', 'language', 'Kurdish','2014-05-13')");
9142     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ku','kur')");
9143     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'ku', 'کوردی')");
9144     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'en', 'Kurdish')");
9145     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'fr', 'Kurde')");
9146     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'de', 'Kurdisch')");
9147     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'es', 'Kurdo')");
9148
9149     $dbh->do("UPDATE language_descriptions SET description = 'ພາສາລາວ' WHERE subtag = 'lo' AND type = 'language' AND lang = 'lo'");
9150
9151     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mi', 'language', 'Maori','2014-10-30')");
9152     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mi','mri')");
9153     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mi', 'language', 'mi', 'Te Reo Māori')");
9154     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mi', 'language', 'en', 'Maori')");
9155
9156     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mn', 'language', 'Mongolian','2014-10-30')");
9157     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mn','mon')");
9158     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mn', 'language', 'mn', 'Mонгол')");
9159     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mn', 'language', 'en', 'Mongolian')");
9160
9161     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mr', 'language', 'Marathi','2014-10-30')");
9162     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mr','mar')");
9163     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mr', 'language', 'mr', 'मराठी')");
9164     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mr', 'language', 'en', 'Marathi')");
9165
9166     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ms', 'language', 'Malay','2014-10-30')");
9167     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ms','may')");
9168     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ms', 'language', 'ms', 'Bahasa melayu')");
9169     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ms', 'language', 'en', 'Malay')");
9170
9171     $dbh->do("UPDATE language_descriptions SET description = 'Norsk bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'nb'");
9172     $dbh->do("UPDATE language_descriptions SET description = 'Norwegian bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'en'");
9173     $dbh->do("UPDATE language_descriptions SET description = 'Norvégien bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'fr'");
9174     $dbh->do("UPDATE language_descriptions SET description = 'Norwegisch bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'de'");
9175
9176     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ne', 'language', 'Nepali','2014-10-30')");
9177     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ne','nep')");
9178     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)VALUES ( 'ne', 'language', 'ne', 'नेपाली')");
9179     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ne', 'language', 'en', 'Nepali')");
9180
9181     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'pbr', 'language', 'Pangwa','2014-10-30')");
9182     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'pbr','pbr')");
9183     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'pbr', 'language', 'pbr', 'Ekipangwa')");
9184     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'pbr', 'language', 'en', 'Pangwa')");
9185
9186     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'prs', 'language', 'Dari','2014-10-30')");
9187     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'prs','prs')");
9188     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'prs', 'language', 'prs', 'درى')");
9189     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'prs', 'language', 'en', 'Dari')");
9190
9191     $dbh->do("UPDATE language_descriptions SET description = 'Português' WHERE subtag = 'pt' AND type = 'language' AND lang = 'pt'");
9192     $dbh->do("UPDATE language_descriptions SET description = 'Român' WHERE subtag = 'ro' AND type = 'language' AND lang = 'ro'");
9193     $dbh->do("UPDATE language_descriptions SET description = 'Русский' WHERE subtag = 'ru' AND type = 'language' AND lang = 'ru'");
9194
9195     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'rw', 'language', 'Kinyarwanda','2014-10-30')");
9196     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'rw','kin')");
9197     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'rw', 'language', 'rw', 'Ikinyarwanda')");
9198     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'rw', 'language', 'en', 'Kinyarwanda')");
9199
9200     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sd', 'language', 'Sindhi','2014-10-30')");
9201     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sd','snd')");
9202     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sd', 'language', 'sd', 'سنڌي')");
9203     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sd', 'language', 'en', 'Sindhi')");
9204
9205     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sk', 'language', 'Slovak','2014-10-30')");
9206     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sk','slk')");
9207     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sk', 'language', 'sk', 'Slovenčina')");
9208     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sk', 'language', 'en', 'Slovak')");
9209
9210     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sl', 'language', 'Slovene','2014-10-30')");
9211     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sl','slv')");
9212     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sl', 'language', 'sl', 'Slovenščina')");
9213     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sl', 'language', 'en', 'Slovene')");
9214
9215     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sq', 'language', 'Albanian','2014-10-30')");
9216     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sq','sqi')");
9217     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sq', 'language', 'sq', 'Shqip')");
9218     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sq', 'language', 'en', 'Albanian')");
9219
9220     $dbh->do("UPDATE language_descriptions SET description = 'Cрпски' WHERE subtag = 'sr' AND type = 'language' AND lang = 'sr'");
9221
9222     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sw', 'language', 'Swahili','2014-10-30')");
9223     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sw','swa')");
9224     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sw', 'language', 'sw', 'Kiswahili')");
9225     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sw', 'language', 'en', 'Swahili')");
9226
9227     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ta', 'language', 'Tamil','2014-10-30')");
9228     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ta','tam')");
9229     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ta', 'language', 'ta', 'தமிழ்')");
9230     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ta', 'language', 'en', 'Tamil')");
9231
9232     $dbh->do("UPDATE language_descriptions SET description = 'Tetun' WHERE subtag = 'tet' AND type = 'language' AND lang = 'tet'");
9233     $dbh->do("UPDATE language_descriptions SET description = 'ภาษาไทย' WHERE subtag = 'th' AND type = 'language' AND lang = 'th'");
9234
9235     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'tl', 'language', 'Tagalog','2014-10-30')");
9236     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'tl','tgl')");
9237     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'tl', 'language', 'tl', 'Tagalog')");
9238     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'tl', 'language', 'en', 'Tagalog')");
9239
9240     $dbh->do("UPDATE language_descriptions SET description = 'Türkçe' WHERE subtag = 'tr' AND type = 'language' AND lang = 'tr'");
9241     $dbh->do("UPDATE language_descriptions SET description = 'Українська' WHERE subtag = 'uk' AND type = 'language' AND lang = 'uk'");
9242     $dbh->do("UPDATE language_descriptions SET description = 'اردو' WHERE subtag = 'ur' AND type = 'language' AND lang = 'ur'");
9243
9244     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'vi', 'language', 'Vietnamese','2014-10-30')");
9245     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'vi','vie')");
9246     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'vi', 'language', 'vi', '㗂越')");
9247     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'vi', 'language', 'en', 'Vietnamese')");
9248
9249     $dbh->do("UPDATE language_descriptions SET description = '中文' WHERE subtag = 'zh' AND type = 'language' AND lang = 'zh'");
9250     $dbh->do("UPDATE language_descriptions SET description = '' WHERE subtag = 'Arab,script' AND type = 'Arab' AND lang = 'العربية'");
9251
9252     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Armn', 'script', 'Armenian','2014-10-30')");
9253     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Armn', 'script', 'Armn', 'Հայոց այբուբեն')");
9254     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Armn', 'script', 'en', 'Armenian')");
9255
9256     $dbh->do("UPDATE language_descriptions SET description = 'Кирилица' WHERE subtag = 'Cyrl' AND type = 'script' AND lang = 'Cyrl'");
9257
9258     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Ethi', 'script', 'Ethiopic','2014-10-30')");
9259     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Ethi', 'script', 'Ethi', 'ግዕዝ')");
9260     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Ethi', 'script', 'en', 'Ethiopic')");
9261
9262     $dbh->do("UPDATE language_descriptions SET description = 'Ελληνικό αλφάβητο' WHERE subtag = 'Grek' AND type = 'script' AND lang = 'Grek'");
9263     $dbh->do("UPDATE language_descriptions SET description = '简体字' WHERE subtag = 'Hans' AND type = 'script' AND lang = 'Hans'");
9264     $dbh->do("UPDATE language_descriptions SET description = '繁體字' WHERE subtag = 'Hant' AND type = 'script' AND lang = 'Hant'");
9265     $dbh->do("UPDATE language_descriptions SET description = 'אָלֶף־בֵּית עִבְרִי' WHERE subtag = 'Hebr' AND type = 'script' AND lang = 'Hebr'");
9266
9267     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Jpan', 'script', 'Japanese','2014-10-30')");
9268     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Jpan', 'script', 'Jpan', '漢字')");
9269     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Jpan', 'script', 'en', 'Japanese')");
9270
9271     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Knda', 'script', 'Kannada','2014-10-30')");
9272     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Knda', 'script', 'Knda', 'ಕನ್ನಡ ಲಿಪಿ')");
9273     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Knda', 'script', 'en', 'Kannada')");
9274
9275     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Kore', 'script', 'Korean','2014-10-30')");
9276     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Kore', 'script', 'Kore', '한글')");
9277     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Kore', 'script', 'en', 'Korean')");
9278
9279     $dbh->do("UPDATE language_descriptions SET description = 'ອັກສອນລາວ' WHERE subtag = 'Laoo' AND type = 'script' AND lang = 'Laoo'");
9280
9281     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'AL', 'region', 'Albania','2014-10-30')");
9282     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AL', 'region', 'en', 'Albania')");
9283     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AL', 'region', 'sq', 'Shqipërisë')");
9284
9285     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'AZ', 'region', 'Azerbaijan','2014-10-30')");
9286     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AZ', 'region', 'en', 'Azerbaijan')");
9287     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AZ', 'region', 'az', 'Azərbaycan')");
9288
9289     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BE', 'region', 'Belgium','2014-10-30')");
9290     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BE', 'region', 'en', 'Belgium')");
9291     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BE', 'region', 'nl', 'België')");
9292
9293     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BR', 'region', 'Brazil','2014-10-30')");
9294     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BR', 'region', 'en', 'Brazil')");
9295     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BR', 'region', 'pt', 'Brasil')");
9296
9297     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BY', 'region', 'Belarus','2014-10-30')");
9298     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BY', 'region', 'en', 'Belarus')");
9299     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BY', 'region', 'be', 'Беларусь')");
9300
9301     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CA', 'region', 'fr', 'Canada')");
9302
9303     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CH', 'region', 'Switzerland','2014-10-30')");
9304     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CH', 'region', 'en', 'Switzerland')");
9305     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CH', 'region', 'de', 'Schweiz')");
9306
9307     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CN', 'region', 'China','2014-10-30')");
9308     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CN', 'region', 'en', 'China')");
9309     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CN', 'region', 'zh', '中国')");
9310
9311     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CZ', 'region', 'Czech Republic','2014-10-30')");
9312     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CZ', 'region', 'en', 'Czech Republic')");
9313     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CZ', 'region', 'cs', 'Česká republika')");
9314
9315     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'DE', 'region', 'Germany','2014-10-30')");
9316     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DE', 'region', 'en', 'Germany')");
9317     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DE', 'region', 'de', 'Deutschland')");
9318
9319     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DK', 'region', 'en', 'Denmark')");
9320
9321     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ES', 'region', 'Spain','2014-10-30')");
9322     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ES', 'region', 'en', 'Spain')");
9323     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ES', 'region', 'es', 'España')");
9324
9325     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'FI', 'region', 'Finland','2014-10-30')");
9326     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FI', 'region', 'en', 'Finland')");
9327     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FI', 'region', 'fi', 'Suomi')");
9328
9329     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'FO', 'region', 'Faroe Islands','2014-10-30')");
9330     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FO', 'region', 'en', 'Faroe Islands')");
9331     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FO', 'region', 'fo', 'Føroyar')");
9332
9333     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'GR', 'region', 'Greece','2014-10-30')");
9334     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'GR', 'region', 'en', 'Greece')");
9335     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'GR', 'region', 'el', 'Ελλάδα')");
9336
9337     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'HR', 'region', 'Croatia','2014-10-30')");
9338     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HR', 'region', 'en', 'Croatia')");
9339     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HR', 'region', 'hr', 'Hrvatska')");
9340
9341     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'HU', 'region', 'Hungary','2014-10-30')");
9342     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HU', 'region', 'en', 'Hungary')");
9343     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HU', 'region', 'hu', 'Magyarország')");
9344
9345     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ID', 'region', 'Indonesia','2014-10-30')");
9346     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ID', 'region', 'en', 'Indonesia')");
9347     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ID', 'region', 'id', 'Indonesia')");
9348
9349     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'IS', 'region', 'Iceland','2014-10-30')");
9350     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IS', 'region', 'en', 'Iceland')");
9351     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IS', 'region', 'is', 'Ísland')");
9352
9353     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'IT', 'region', 'Italy','2014-10-30')");
9354     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IT', 'region', 'en', 'Italy')");
9355     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IT', 'region', 'it', 'Italia')");
9356
9357     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'JP', 'region', 'Japan','2014-10-30')");
9358     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'JP', 'region', 'en', 'Japan')");
9359     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'JP', 'region', 'ja', '日本')");
9360
9361     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KE', 'region', 'Kenya','2014-10-30')");
9362     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KE', 'region', 'en', 'Kenya')");
9363     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KE', 'region', 'rw', 'Kenya')");
9364
9365     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KH', 'region', 'Cambodia','2014-10-30')");
9366     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KH', 'region', 'en', 'Cambodia')");
9367     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KH', 'region', 'km', 'កម្ពុជា')");
9368
9369     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KP', 'region', 'North Korea','2014-10-30')");
9370     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KP', 'region', 'en', 'North Korea')");
9371     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KP', 'region', 'ko', '조선민주주의인민공화국')");
9372
9373     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'LK', 'region', 'Sri Lanka','2014-10-30')");
9374     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'LK', 'region', 'en', 'Sri Lanka')");
9375     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'LK', 'region', 'ta', 'இலங்கை')");
9376
9377     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'MY', 'region', 'Malaysia','2014-10-30')");
9378     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'MY', 'region', 'en', 'Malaysia')");
9379     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'MY', 'region', 'ms', 'Malaysia')");
9380
9381     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NE', 'region', 'Niger','2014-10-30')");
9382     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NE', 'region', 'en', 'Niger')");
9383     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NE', 'region', 'ne', 'Niger')");
9384
9385     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NL', 'region', 'Netherlands','2014-10-30')");
9386     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NL', 'region', 'en', 'Netherlands')");
9387     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NL', 'region', 'nl', 'Nederland')");
9388
9389     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NO', 'region', 'Norway','2014-10-30')");
9390     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'en', 'Norway')");
9391     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'ne', 'Noreg')");
9392     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'nn', 'Noreg')");
9393
9394     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PH', 'region', 'Philippines','2014-10-30')");
9395     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PH', 'region', 'en', 'Philippines')");
9396     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PH', 'region', 'tl', 'Pilipinas')");
9397
9398     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PK', 'region', 'Pakistan','2014-10-30')");
9399     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PK', 'region', 'en', 'Pakistan')");
9400     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PK', 'region', 'sd', 'پاكستان')");
9401
9402     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PL', 'region', 'Poland','2014-10-30')");
9403     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PL', 'region', 'en', 'Poland')");
9404     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PL', 'region', 'pl', 'Polska')");
9405
9406     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PT', 'region', 'Portugal','2014-10-30')");
9407     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PT', 'region', 'en', 'Portugal')");
9408     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PT', 'region', 'pt', 'Portugal')");
9409
9410     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RO', 'region', 'Romania','2014-10-30')");
9411     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RO', 'region', 'en', 'Romania')");
9412     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RO', 'region', 'ro', 'România')");
9413
9414     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RU', 'region', 'Russia','2014-10-30')");
9415     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RU', 'region', 'en', 'Russia')");
9416     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RU', 'region', 'ru', 'Россия')");
9417
9418     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RW', 'region', 'Rwanda','2014-10-30')");
9419     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RW', 'region', 'en', 'Rwanda')");
9420     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RW', 'region', 'rw', 'Rwanda')");
9421
9422     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SE', 'region', 'Sweden','2014-10-30')");
9423     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SE', 'region', 'en', 'Sweden')");
9424     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SE', 'region', 'sv', 'Sverige')");
9425
9426     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SI', 'region', 'Slovenia','2014-10-30')");
9427     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SI', 'region', 'en', 'Slovenia')");
9428     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SI', 'region', 'sl', 'Slovenija')");
9429
9430     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SK', 'region', 'Slovakia','2014-10-30')");
9431     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SK', 'region', 'en', 'Slovakia')");
9432     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SK', 'region', 'sk', 'Slovensko')");
9433
9434     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TH', 'region', 'Thailand','2014-10-30')");
9435     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TH', 'region', 'en', 'Thailand')");
9436     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TH', 'region', 'th', 'ประเทศไทย')");
9437
9438     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TR', 'region', 'Turkey','2014-10-30')");
9439     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TR', 'region', 'en', 'Turkey')");
9440     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TR', 'region', 'tr', 'Türkiye')");
9441
9442     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TW', 'region', 'Taiwan','2014-10-30')");
9443     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TW', 'region', 'en', 'Taiwan')");
9444     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TW', 'region', 'zh', '台灣')");
9445
9446     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'UA', 'region', 'Ukraine','2014-10-30')");
9447     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'UA', 'region', 'en', 'Ukraine')");
9448     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'UA', 'region', 'uk', 'Україна')");
9449
9450     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'VN', 'region', 'Vietnam','2014-10-30')");
9451     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'VN', 'region', 'en', 'Vietnam')");
9452     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'VN', 'region', 'vi', 'Việt Nam')");
9453
9454     print "Upgrade to $DBversion done (Bug 12250: Update descriptions for languages, scripts and regions)\n";
9455     SetVersion($DBversion);
9456 }
9457
9458 $DBversion = "3.17.00.050";
9459 if ( CheckVersion($DBversion) ) {
9460     $dbh->do(q|
9461         INSERT INTO permissions (module_bit, code, description) VALUES
9462           (13, 'records_batchdel', 'Perform batch deletion of records (bibliographic or authority)')
9463     |);
9464     print "Upgrade to $DBversion done (Bug 12403: Add permission tools_records_batchdelitem)\n";
9465     SetVersion($DBversion);
9466 }
9467
9468 $DBversion = "3.17.00.051";
9469 if ( CheckVersion($DBversion) ) {
9470     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('GoogleIndicTransliteration','0','','GoogleIndicTransliteration on the OPAC.','YesNo')");
9471     print "Upgrade to $DBversion done (Bug 13211: Added system preferences GoogleIndicTransliteration on the OPAC)\n";
9472     SetVersion($DBversion);
9473 }
9474
9475 $DBversion = "3.17.00.052";
9476 if ( CheckVersion($DBversion) ) {
9477     $dbh->do(q{
9478         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');
9479     });
9480
9481     $dbh->do(q{
9482         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');
9483    });
9484    print "Upgrade to $DBversion done (Bug 9043: Add system preference OpacAdvSearchOptions and OpacAdvSearchMoreOptions)\n";
9485    SetVersion ($DBversion);
9486 }
9487
9488 $DBversion = "3.17.00.053";
9489 if ( CheckVersion($DBversion) ) {
9490     $dbh->do(q{
9491         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)');
9492     });
9493
9494     $dbh->do(q{
9495         INSERT INTO permissions (module_bit, code, description) VALUES ('9', 'delete_all_items', 'Delete all items at once');
9496     });
9497
9498     $dbh->do(q{
9499         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)');
9500     });
9501
9502     # The delete_all_items permission should be added to users having the edit_items permission.
9503     $dbh->do(q{
9504         INSERT INTO user_permissions (borrowernumber, module_bit, code) SELECT borrowernumber, module_bit, "delete_all_items" FROM user_permissions WHERE code="edit_items";
9505     });
9506
9507     # Add 2 new prefs
9508     $dbh->do(q{
9509         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');
9510     });
9511
9512     $dbh->do(q{
9513         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');
9514     });
9515
9516     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";
9517     SetVersion($DBversion);
9518 }
9519
9520 $DBversion = "3.17.00.054";
9521 if (CheckVersion($DBversion)) {
9522     $dbh->do(q{
9523         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
9524         ('AllowRenewalIfOtherItemsAvailable','0',NULL,'If enabled, allow a patron to renew an item with unfilled holds if other available items can fill that hold.','YesNo')
9525     });
9526     print "Upgrade to $DBversion done (Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds)\n";
9527     SetVersion($DBversion);
9528 }
9529
9530 $DBversion = "3.17.00.055";
9531 if ( CheckVersion($DBversion) ) {
9532     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBEnable', '0', NULL, 'Enable communication with the Norwegian national patron database.', 'YesNo')");
9533     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBEndpoint', '', NULL, 'Which NL endpoint to use.', 'Free')");
9534     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBUsername', '', NULL, 'Username for communication with the Norwegian national patron database.', 'Free')");
9535     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBPassword', '', NULL, 'Password for communication with the Norwegian national patron database.', 'Free')");
9536     $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')");
9537     $dbh->do("
9538 CREATE TABLE borrower_sync (
9539     borrowersyncid int(11) NOT NULL AUTO_INCREMENT,
9540     borrowernumber int(11) NOT NULL,
9541     synctype varchar(32) NOT NULL,
9542     sync tinyint(1) NOT NULL DEFAULT '0',
9543     syncstatus varchar(10) DEFAULT NULL,
9544     lastsync varchar(50) DEFAULT NULL,
9545     hashed_pin varchar(64) DEFAULT NULL,
9546     PRIMARY KEY (borrowersyncid),
9547     KEY borrowernumber (borrowernumber),
9548     CONSTRAINT borrower_sync_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
9549 ) ENGINE=InnoDB DEFAULT CHARSET=utf8"
9550 );
9551     print "Upgrade to $DBversion done (Bug 11401 - Add support for Norwegian national library card)\n";
9552     SetVersion($DBversion);
9553 }
9554
9555 $DBversion = "3.17.00.056";
9556 if ( CheckVersion($DBversion) ) {
9557     $dbh->do(q{
9558         UPDATE systempreferences SET value = 'pubdate,itemtype,language,sorting,location' WHERE variable='OpacAdvSearchOptions'
9559     });
9560
9561     $dbh->do(q{
9562         UPDATE systempreferences SET value = 'pubdate,itemtype,language,subtype,sorting,location' WHERE variable='OpacAdvSearchMoreOptions'
9563     });
9564
9565     print "Upgrade to $DBversion done (Bug 9043 - Update the values for OpacAdvSearchOptions and OpacAdvSearchOptions)\n";
9566     SetVersion($DBversion);
9567 }
9568
9569 $DBversion = "3.17.00.057";
9570 if ( CheckVersion($DBversion) ) {
9571     print "Upgrade to $DBversion done (Koha 3.18 beta)\n";
9572     SetVersion ($DBversion);
9573 }
9574
9575 $DBversion = "3.17.00.058";
9576 if( CheckVersion($DBversion) ){
9577     $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')");
9578     $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')");
9579     $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')");
9580     print "Upgrade to $DBversion done (Bug 8337: System preferences for longoverdue cron)\n";
9581     SetVersion($DBversion);
9582 }
9583
9584 $DBversion = "3.17.00.059";
9585 if ( CheckVersion($DBversion) ) {
9586     $dbh->do(q{
9587         UPDATE permissions SET description = "Add and delete budgets (but can't modifiy budgets)" WHERE description = "Add and delete budgets (but cant modify budgets)";
9588     });
9589     print "Upgrade to $DBversion done (Bug 10749: Fix typo in budget_add_del permission description)\n";
9590     SetVersion ($DBversion);
9591 }
9592
9593 $DBversion = "3.17.00.060";
9594 if ( CheckVersion($DBversion) ) {
9595     my $count_l = $dbh->selectcol_arrayref(q|
9596         SELECT COUNT(*) FROM letter WHERE message_transport_type='feed'
9597     |);
9598     my $count_mq = $dbh->selectcol_arrayref(q|
9599         SELECT COUNT(*) FROM message_queue WHERE message_transport_type='feed'
9600     |);
9601     my $count_ott = $dbh->selectcol_arrayref(q|
9602         SELECT COUNT(*) FROM overduerules_transport_types WHERE message_transport_type='feed'
9603     |);
9604     my $count_mt = $dbh->selectcol_arrayref(q|
9605         SELECT COUNT(*) FROM message_transports WHERE message_transport_type='feed'
9606     |);
9607     my $count_bmtp = $dbh->selectcol_arrayref(q|
9608         SELECT COUNT(*) FROM borrower_message_transport_preferences WHERE message_transport_type='feed'
9609     |);
9610
9611     my $deleted = 0;
9612     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 ) {
9613         $deleted = $dbh->do(q|
9614             DELETE FROM message_transport_types where message_transport_type='feed'
9615         |);
9616         $deleted = $deleted ne '0E0' ? 1 : 0;
9617     }
9618
9619     print "Upgrade to $DBversion done (Bug 12298: Delete the 'feed' message transport type " . ($deleted ? '(deleted!)' : '(not deleted)') . ")\n";
9620     SetVersion($DBversion);
9621 }
9622
9623 $DBversion = "3.18.00.000";
9624 if ( CheckVersion($DBversion) ) {
9625     print "Upgrade to $DBversion done (3.18.0 release)\n";
9626     SetVersion($DBversion);
9627 }
9628
9629 $DBversion = "3.19.00.000";
9630 if ( CheckVersion($DBversion) ) {
9631     print "Upgrade to $DBversion done (there's life after 3.18)\n";
9632     SetVersion ($DBversion);
9633 }
9634
9635 $DBversion = "3.19.00.001";
9636 if ( CheckVersion($DBversion) ) {
9637     $dbh->do("
9638         UPDATE systempreferences
9639         SET options = 'public|school|academic|research|private|societyAssociation|corporate|government|religiousOrg|subscription'
9640         WHERE variable = 'UsageStatsLibraryType'
9641     ");
9642     if ( C4::Context->preference("UsageStatsLibraryType") eq "university" ) {
9643         C4::Context->set_preference("UsageStatsLibraryType", "academic")
9644     }
9645     print "Upgrade to $DBversion done (Bug 13436: Add more options to UsageStatsLibraryType)\n";
9646     SetVersion ($DBversion);
9647 }
9648
9649 $DBversion = "3.19.00.002";
9650 if ( CheckVersion($DBversion) ) {
9651     $dbh->do(q|
9652         UPDATE suggestions SET branchcode="" WHERE branchcode="__ANY__"
9653     |);
9654     print "upgrade to $DBversion done (Bug 10753: replace __ANY__ with empty string in suggestions.branchcode)\n";
9655     SetVersion ($DBversion);
9656 }
9657
9658 $DBversion = "3.19.00.003";
9659 if ( CheckVersion($DBversion) ) {
9660     my ($count) = $dbh->selectrow_array("SELECT COUNT(*) FROM borrowers GROUP BY userid HAVING COUNT(userid) > 1");
9661
9662     if ( $count ) {
9663         print "Upgrade to $DBversion done (Bug 1861 - Unique patrons logins not (totally) enforced) FAILED!\n";
9664         print "Your database has users with duplicate user logins. Please have your administrator deduplicate your user logins.\n";
9665         print "Afterward, your Koha administrator should execute the following database query: ALTER TABLE borrowers DROP INDEX userid, ADD UNIQUE userid (userid)";
9666     } else {
9667         $dbh->do(q{
9668             ALTER TABLE borrowers
9669                 DROP INDEX userid ,
9670                 ADD UNIQUE userid (userid)
9671         });
9672         print "Upgrade to $DBversion done (Bug 1861: Unique patrons logins not (totally) enforced)\n";
9673     }
9674
9675     SetVersion($DBversion);
9676 }
9677
9678 $DBversion = "3.19.00.004";
9679 if ( CheckVersion($DBversion) ) {
9680     my $pref_value = C4::Context->preference('OpacExportOptions');
9681     $pref_value =~ s/\|/,/g; # multiple is separated by ,
9682     $dbh->do(q{
9683         UPDATE systempreferences
9684             SET value = ?,
9685                 type = 'multiple'
9686         WHERE variable = 'OpacExportOptions'
9687     }, {}, $pref_value );
9688     print "Upgrade to $DBversion done (Bug 13346: OpacExportOptions is now multiple)\n";
9689     SetVersion ($DBversion);
9690 }
9691
9692 $DBversion = "3.19.00.005";
9693 if(CheckVersion($DBversion)) {
9694     $dbh->do(q{
9695         ALTER TABLE authorised_values MODIFY COLUMN category VARCHAR(32) NOT NULL DEFAULT ''
9696     });
9697
9698     $dbh->do(q{
9699         ALTER TABLE borrower_attribute_types MODIFY COLUMN authorised_value_category VARCHAR(32) DEFAULT NULL
9700     });
9701
9702     print "Upgrade to $DBversion done (Bug 13379: Modify authorised_values.category to varchar(32))\n";
9703     SetVersion($DBversion);
9704 }
9705
9706 $DBversion = "3.19.00.006";
9707 if ( CheckVersion($DBversion) ) {
9708     $dbh->do(q|SET foreign_key_checks = 0|);
9709     my $sth = $dbh->table_info( '','','','TABLE' );
9710     my ( $cat, $schema, $name, $type, $remarks );
9711     while ( ( $cat, $schema, $name, $type, $remarks ) = $sth->fetchrow_array ) {
9712         my $table_sth = $dbh->prepare(qq|SHOW CREATE TABLE $name|);
9713         $table_sth->execute;
9714         my @table = $table_sth->fetchrow_array;
9715         unless ( $table[1] =~ /COLLATE=utf8mb4_unicode_ci/ ) { #catches utf8mb4 collated tables
9716             if ( $name eq 'marc_subfield_structure' ) {
9717                 $dbh->do(q|
9718                     ALTER TABLE marc_subfield_structure
9719                     MODIFY COLUMN tagfield varchar(3) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9720                     MODIFY COLUMN tagsubfield varchar(1) COLLATE utf8_bin NOT NULL DEFAULT '',
9721                     MODIFY COLUMN liblibrarian varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9722                     MODIFY COLUMN libopac varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9723                     MODIFY COLUMN kohafield varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
9724                     MODIFY COLUMN authorised_value varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
9725                     MODIFY COLUMN authtypecode varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
9726                     MODIFY COLUMN value_builder varchar(80) COLLATE utf8_unicode_ci DEFAULT NULL,
9727                     MODIFY COLUMN frameworkcode varchar(4) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9728                     MODIFY COLUMN seealso varchar(1100) COLLATE utf8_unicode_ci DEFAULT NULL,
9729                     MODIFY COLUMN link varchar(80) COLLATE utf8_unicode_ci DEFAULT NULL
9730                 |);
9731             }
9732             else {
9733                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci|);
9734             }
9735         }
9736     }
9737     $dbh->do(q|SET foreign_key_checks = 1|);;
9738
9739     print "Upgrade to $DBversion done (Bug 11944: Convert DB tables to utf8_unicode_ci)\n";
9740     SetVersion($DBversion);
9741 }
9742
9743 $DBversion = "3.19.00.007";
9744 if ( CheckVersion($DBversion) ) {
9745     my $orphan_budgets = $dbh->selectall_arrayref(q|
9746         SELECT budget_id, budget_name, budget_code
9747         FROM aqbudgets
9748         WHERE   budget_parent_id IS NOT NULL
9749             AND budget_parent_id NOT IN (
9750                 SELECT DISTINCT budget_id FROM aqbudgets
9751             )
9752     |, { Slice => {} } );
9753
9754     if ( @$orphan_budgets ) {
9755         for my $b ( @$orphan_budgets ) {
9756             print "Fund $b->{budget_name} (code:$b->{budget_code}, id:$b->{budget_id}) does not have a parent, it may cause problem\n";
9757         }
9758         print "Upgrade to $DBversion done (Bug 12905: Check budget integrity: FAIL)\n";
9759     } else {
9760         print "Upgrade to $DBversion done (Bug 12905: Check budget integrity: OK)\n";
9761     }
9762     SetVersion($DBversion);
9763 }
9764
9765 $DBversion = "3.19.00.008";
9766 if ( CheckVersion($DBversion) ) {
9767     my $number_of_orders_not_linked = $dbh->selectcol_arrayref(q|
9768         SELECT COUNT(*)
9769         FROM aqorders o
9770         WHERE NOT EXISTS (
9771             SELECT NULL
9772             FROM aqbudgets b
9773             WHERE b.budget_id = o.budget_id
9774         );
9775     |);
9776
9777     if ( $number_of_orders_not_linked->[0] > 0 ) {
9778         $dbh->do(q|
9779             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)
9780         |);
9781         my $budget_period_id = $dbh->last_insert_id( undef, undef, 'aqbudgetperiods', undef );
9782         $dbh->do(qq|
9783             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 );
9784         |);
9785         my $budget_id = $dbh->last_insert_id( undef, undef, 'aqbudgets', undef );
9786         $dbh->do(qq|
9787             UPDATE aqorders o
9788             SET budget_id = $budget_id
9789             WHERE NOT EXISTS (
9790                 SELECT NULL
9791                 FROM aqbudgets b
9792                 WHERE b.budget_id = o.budget_id
9793             )
9794         |);
9795     }
9796
9797     $dbh->do(q|
9798         ALTER TABLE aqorders
9799         ADD CONSTRAINT aqorders_budget_id_fk FOREIGN KEY (budget_id) REFERENCES aqbudgets(budget_id) ON DELETE CASCADE ON UPDATE CASCADE
9800     |);
9801
9802     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";
9803     SetVersion($DBversion);
9804 }
9805
9806 $DBversion = "3.19.00.009";
9807 if ( CheckVersion($DBversion) ) {
9808     $dbh->do(q|
9809         UPDATE suggestions s SET s.budgetid = NULL
9810         WHERE NOT EXISTS (
9811             SELECT NULL
9812             FROM aqbudgets b
9813             WHERE b.budget_id = s.budgetid
9814         );
9815     |);
9816
9817     $dbh->do(q|
9818         ALTER TABLE suggestions
9819         ADD CONSTRAINT suggestions_budget_id_fk FOREIGN KEY (budgetid) REFERENCES aqbudgets(budget_id) ON DELETE SET NULL ON UPDATE CASCADE
9820     |);
9821
9822     print "Upgrade to $DBversion done (Bug 13007: Add new foreign key suggestions.budgetid)\n";
9823     SetVersion($DBversion);
9824 }
9825
9826 $DBversion = "3.19.00.010";
9827 if ( CheckVersion($DBversion) ) {
9828     $dbh->do(q|
9829         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
9830         VALUES('SessionRestrictionByIP','1','Check for Change in  Remote IP address for Session Security. Disable when remote ip address changes frequently.','','YesNo')
9831     |);
9832     print "Upgrade to $DBversion done (Bug 5511: SessionRestrictionByIP)\n";
9833     SetVersion ($DBversion);
9834 }
9835
9836 $DBversion = "3.19.00.011";
9837 if ( CheckVersion($DBversion) ) {
9838     $dbh->do(q|
9839         INSERT INTO userflags (bit, flag, flagdesc, defaulton) VALUES
9840         (20, 'lists', 'Lists', 0)
9841     |);
9842     $dbh->do(q|
9843         INSERT INTO permissions (module_bit, code, description) VALUES
9844         (20, 'delete_public_lists', 'Delete public lists')
9845     |);
9846     print "Upgrade to $DBversion done (Bug 13417: Add permission to delete public lists)\n";
9847     SetVersion ($DBversion);
9848 }
9849
9850 $DBversion = "3.19.00.012";
9851 if(CheckVersion($DBversion)) {
9852     $dbh->do(q{
9853         ALTER TABLE biblioitems MODIFY COLUMN marcxml longtext
9854     });
9855
9856     $dbh->do(q{
9857         ALTER TABLE deletedbiblioitems MODIFY COLUMN marcxml longtext
9858     });
9859
9860     print "Upgrade to $DBversion done (Bug 13523 Remove NOT NULL restriction on field marcxml due to mysql STRICT_TRANS_TABLES)\n";
9861     SetVersion ($DBversion);
9862 }
9863
9864 $DBversion = "3.19.00.013";
9865 if ( CheckVersion($DBversion) ) {
9866     $dbh->do(q|
9867         INSERT INTO permissions (module_bit, code, description) VALUES
9868           (13, 'records_batchmod', 'Perform batch modification of records (biblios or authorities)')
9869     |);
9870     print "Upgrade to $DBversion done (Bug 11395: Add permission tools_records_batchmod)\n";
9871     SetVersion($DBversion);
9872 }
9873
9874 $DBversion = "3.19.00.014";
9875 if ( CheckVersion($DBversion) ) {
9876     $dbh->do(q|
9877         CREATE TABLE aqorder_users (
9878             ordernumber int(11) NOT NULL,
9879             borrowernumber int(11) NOT NULL,
9880             PRIMARY KEY (ordernumber, borrowernumber),
9881             CONSTRAINT aqorder_users_ibfk_1 FOREIGN KEY (ordernumber) REFERENCES aqorders (ordernumber) ON DELETE CASCADE ON UPDATE CASCADE,
9882             CONSTRAINT aqorder_users_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
9883         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
9884     |);
9885
9886     $dbh->do(q|
9887         INSERT INTO letter(module, code, branchcode, name, title, content, message_transport_type)
9888         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')
9889     |);
9890     print "Upgrade to $DBversion done (Bug 12648: Add letter ACQ_NOTIF_ON_RECEIV )\n";
9891     SetVersion ($DBversion);
9892 }
9893
9894 $DBversion = "3.19.00.015";
9895 if ( CheckVersion($DBversion) ) {
9896     $dbh->do(q|
9897         ALTER TABLE search_history ADD COLUMN id INT(11) NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY(id);
9898     |);
9899     print "Upgrade to $DBversion done (Bug 11430: Add primary key for search_history)\n";
9900     SetVersion($DBversion);
9901 }
9902
9903 $DBversion = "3.19.00.016";
9904 if(CheckVersion($DBversion)) {
9905     my @order_cancellation_reason = $dbh->selectrow_array("SELECT count(*) FROM authorised_values WHERE category='ORDER_CANCELLATION_REASON'");
9906     if ($order_cancellation_reason[0] == 0) {
9907         $dbh->do(q{
9908             INSERT INTO authorised_values (category, authorised_value, lib) VALUES
9909              ('ORDER_CANCELLATION_REASON', 0, 'No reason provided'),
9910              ('ORDER_CANCELLATION_REASON', 1, 'Out of stock'),
9911              ('ORDER_CANCELLATION_REASON', 2, 'Restocking')
9912         });
9913
9914         my $already_existing_reasons = $dbh->selectcol_arrayref(q{
9915             SELECT DISTINCT( cancellationreason )
9916             FROM aqorders;
9917         }, { Slice => {} });
9918
9919         my $update_orders_sth = $dbh->prepare(q{
9920             UPDATE aqorders
9921             SET cancellationreason = ?
9922             WHERE cancellationreason = ?
9923         });
9924
9925         my $insert_av_sth = $dbh->prepare(q{
9926             INSERT INTO authorised_values (category, authorised_value, lib) VALUES
9927              ('ORDER_CANCELLATION_REASON', ?, ?)
9928         });
9929         my $i = 3;
9930         for my $reason ( @$already_existing_reasons ) {
9931             next unless $reason;
9932             $insert_av_sth->execute( $i, $reason );
9933             $update_orders_sth->execute( $i, $reason );
9934             $i++;
9935         }
9936         print "Upgrade to $DBversion done (Bug 13380: Add the ORDER_CANCELLATION_REASON authorised value)\n";
9937     }
9938     else {
9939         print "Upgrade to $DBversion done (Bug 13380: ORDER_CANCELLATION_REASON authorised value already existed from earlier update!)\n";
9940     }
9941
9942     SetVersion($DBversion);
9943 }
9944
9945 $DBversion = '3.19.00.017';
9946 if ( CheckVersion($DBversion) ) {
9947     # First create the column
9948     $dbh->do("ALTER TABLE issuingrules ADD onshelfholds tinyint(1) default 0 NOT NULL");
9949     # Now update the column
9950     if (C4::Context->preference("AllowOnShelfHolds")){
9951         # Pref is on, set allow for all rules
9952         $dbh->do("UPDATE issuingrules SET onshelfholds=1");
9953     } else {
9954         # If the preference is not set, leave off
9955         $dbh->do("UPDATE issuingrules SET onshelfholds=0");
9956     }
9957     # Remove from the systempreferences table
9958     $dbh->do("DELETE FROM systempreferences WHERE variable = 'AllowOnShelfHolds'");
9959
9960     # First create the column
9961     $dbh->do("ALTER TABLE issuingrules ADD opacitemholds char(1) DEFAULT 'N' NOT NULL");
9962     # Now update the column
9963     my $opacitemholds = C4::Context->preference("OPACItemHolds") || '';
9964     if (lc ($opacitemholds) eq 'force') {
9965         $opacitemholds = 'F';
9966     }
9967     else {
9968         $opacitemholds = $opacitemholds ? 'Y' : 'N';
9969     }
9970     # Set allow for all rules
9971     $dbh->do("UPDATE issuingrules SET opacitemholds='$opacitemholds'");
9972
9973     # Remove from the systempreferences table
9974     $dbh->do("DELETE FROM systempreferences WHERE variable = 'OPACItemHolds'");
9975
9976     print "Upgrade to $DBversion done (Bug 5786: Move AllowOnShelfHolds to circulation matrix; Move OPACItemHolds system preference to circulation matrix)\n";
9977     SetVersion ($DBversion);
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 # DEVELOPER PROCESS, search for anything to execute in the db_update directory
10405 # SEE bug 13068
10406 # if there is anything in the atomicupdate, read and execute it.
10407
10408 my $update_dir = C4::Context->config('intranetdir') . '/installer/data/mysql/atomicupdate/';
10409 opendir( my $dirh, $update_dir );
10410 foreach my $file ( sort readdir $dirh ) {
10411     next if $file !~ /\.(sql|perl)$/;  #skip other files
10412     print "DEV atomic update: $file\n";
10413     if ( $file =~ /\.sql$/ ) {
10414         my $installer = C4::Installer->new();
10415         my $rv = $installer->load_sql( $update_dir . $file ) ? 0 : 1;
10416     } elsif ( $file =~ /\.perl$/ ) {
10417         do $update_dir . $file;
10418     }
10419 }
10420
10421 =head1 FUNCTIONS
10422
10423 =head2 TableExists($table)
10424
10425 =cut
10426
10427 sub TableExists {
10428     my $table = shift;
10429     eval {
10430                 local $dbh->{PrintError} = 0;
10431                 local $dbh->{RaiseError} = 1;
10432                 $dbh->do(qq{SELECT * FROM $table WHERE 1 = 0 });
10433             };
10434     return 1 unless $@;
10435     return 0;
10436 }
10437
10438 =head2 DropAllForeignKeys($table)
10439
10440 Drop all foreign keys of the table $table
10441
10442 =cut
10443
10444 sub DropAllForeignKeys {
10445     my ($table) = @_;
10446     # get the table description
10447     my $sth = $dbh->prepare("SHOW CREATE TABLE $table");
10448     $sth->execute;
10449     my $vsc_structure = $sth->fetchrow;
10450     # split on CONSTRAINT keyword
10451     my @fks = split /CONSTRAINT /,$vsc_structure;
10452     # parse each entry
10453     foreach (@fks) {
10454         # isolate what is before FOREIGN KEY, if there is something, it's a foreign key to drop
10455         $_ = /(.*) FOREIGN KEY.*/;
10456         my $id = $1;
10457         if ($id) {
10458             # we have found 1 foreign, drop it
10459             $dbh->do("ALTER TABLE $table DROP FOREIGN KEY $id");
10460             $id="";
10461         }
10462     }
10463 }
10464
10465
10466 =head2 TransformToNum
10467
10468 Transform the Koha version from a 4 parts string
10469 to a number, with just 1 .
10470
10471 =cut
10472
10473 sub TransformToNum {
10474     my $version = shift;
10475     # remove the 3 last . to have a Perl number
10476     $version =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
10477     # three X's at the end indicate that you are testing patch with dbrev
10478     # change it into 999
10479     # prevents error on a < comparison between strings (should be: lt)
10480     $version =~ s/XXX$/999/;
10481     return $version;
10482 }
10483
10484 =head2 SetVersion
10485
10486 set the DBversion in the systempreferences
10487
10488 =cut
10489
10490 sub SetVersion {
10491     return if $_[0]=~ /XXX$/;
10492       #you are testing a patch with a db revision; do not change version
10493     my $kohaversion = TransformToNum($_[0]);
10494     if (C4::Context->preference('Version')) {
10495       my $finish=$dbh->prepare("UPDATE systempreferences SET value=? WHERE variable='Version'");
10496       $finish->execute($kohaversion);
10497     } else {
10498       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')");
10499       $finish->execute($kohaversion);
10500     }
10501     C4::Context::clear_syspref_cache(); # invalidate cached preferences
10502 }
10503
10504 =head2 CheckVersion
10505
10506 Check whether a given update should be run when passed the proposed version
10507 number. The update will always be run if the proposed version is greater
10508 than the current database version and less than or equal to the version in
10509 kohaversion.pl. The update is also run if the version contains XXX, though
10510 this behavior will be changed following the adoption of non-linear updates
10511 as implemented in bug 7167.
10512
10513 =cut
10514
10515 sub CheckVersion {
10516     my ($proposed_version) = @_;
10517     my $version_number = TransformToNum($proposed_version);
10518
10519     # The following line should be deleted when bug 7167 is pushed
10520     return 1 if ( $proposed_version =~ m/XXX/ );
10521
10522     if ( C4::Context->preference("Version") < $version_number
10523         && $version_number <= TransformToNum( $Koha::VERSION ) )
10524     {
10525         return 1;
10526     }
10527     else {
10528         return 0;
10529     }
10530 }
10531
10532 exit;