Bug 14069: Drop existing primary key on items if exists
[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 MARC::Record;
43 use MARC::File::XML ( BinaryEncoding => 'utf8' );
44
45 # FIXME - The user might be installing a new database, so can't rely
46 # on /etc/koha.conf anyway.
47
48 my $debug = 0;
49
50 my (
51     $sth, $sti,
52     $query,
53     %existingtables,    # tables already in database
54     %types,
55     $table,
56     $column,
57     $type, $null, $key, $default, $extra,
58     $prefitem,          # preference item in systempreferences table
59 );
60
61 my $schema = Koha::Database->new()->schema();
62
63 my $silent;
64 GetOptions(
65     's' =>\$silent
66     );
67 my $dbh = C4::Context->dbh;
68 $|=1; # flushes output
69
70 local $dbh->{RaiseError} = 0;
71
72 # Record the version we are coming from
73
74 my $original_version = C4::Context->preference("Version");
75
76 # Deal with virtualshelves
77 my $DBversion = "3.00.00.001";
78 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
79     # update virtualshelves table to
80     #
81     $dbh->do("ALTER TABLE `bookshelf` RENAME `virtualshelves`");
82     $dbh->do("ALTER TABLE `shelfcontents` RENAME `virtualshelfcontents`");
83     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD `biblionumber` INT( 11 ) NOT NULL default '0' AFTER shelfnumber");
84     $dbh->do("UPDATE `virtualshelfcontents` SET biblionumber=(SELECT biblionumber FROM items WHERE items.itemnumber=virtualshelfcontents.itemnumber)");
85     # drop all foreign keys : otherwise, we can't drop itemnumber field.
86     DropAllForeignKeys('virtualshelfcontents');
87     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD KEY biblionumber (biblionumber)");
88     # create the new foreign keys (on biblionumber)
89     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD CONSTRAINT `virtualshelfcontents_ibfk_1` FOREIGN KEY (`shelfnumber`) REFERENCES `virtualshelves` (`shelfnumber`) ON DELETE CASCADE ON UPDATE CASCADE");
90     # re-create the foreign key on virtualshelf
91     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD CONSTRAINT `shelfcontents_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE");
92     $dbh->do("ALTER TABLE `virtualshelfcontents` DROP `itemnumber`");
93     print "Upgrade to $DBversion done (virtualshelves)\n";
94     SetVersion ($DBversion);
95 }
96
97
98 $DBversion = "3.00.00.002";
99 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
100     $dbh->do("DROP TABLE sessions");
101     $dbh->do("CREATE TABLE `sessions` (
102   `id` varchar(32) NOT NULL,
103   `a_session` text NOT NULL,
104   UNIQUE KEY `id` (`id`)
105 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
106     print "Upgrade to $DBversion done (sessions uses CGI::session, new table structure for sessions)\n";
107     SetVersion ($DBversion);
108 }
109
110
111 $DBversion = "3.00.00.003";
112 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
113     if (C4::Context->preference("opaclanguages") eq "fr") {
114         $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')");
115     } else {
116         $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')");
117     }
118     print "Upgrade to $DBversion done (adding ReservesNeedReturns systempref, in circulation)\n";
119     SetVersion ($DBversion);
120 }
121
122
123 $DBversion = "3.00.00.004";
124 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
125     $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')");
126     print "Upgrade to $DBversion done (adding DebugLevel systempref, in 'Admin' tab)\n";
127     SetVersion ($DBversion);
128 }
129
130 $DBversion = "3.00.00.005";
131 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
132     $dbh->do("CREATE TABLE `tags` (
133                     `entry` varchar(255) NOT NULL default '',
134                     `weight` bigint(20) NOT NULL default 0,
135                     PRIMARY KEY  (`entry`)
136                     ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
137                 ");
138         $dbh->do("CREATE TABLE `nozebra` (
139                 `server` varchar(20)     NOT NULL,
140                 `indexname` varchar(40)  NOT NULL,
141                 `value` varchar(250)     NOT NULL,
142                 `biblionumbers` longtext NOT NULL,
143                 KEY `indexname` (`server`,`indexname`),
144                 KEY `value` (`server`,`value`))
145                 ENGINE=InnoDB DEFAULT CHARSET=utf8;
146                 ");
147     print "Upgrade to $DBversion done (adding tags and nozebra tables )\n";
148     SetVersion ($DBversion);
149 }
150
151 $DBversion = "3.00.00.006";
152 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
153     $dbh->do("UPDATE issues SET issuedate=timestamp WHERE issuedate='0000-00-00'");
154     print "Upgrade to $DBversion done (filled issues.issuedate with timestamp)\n";
155     SetVersion ($DBversion);
156 }
157
158 $DBversion = "3.00.00.007";
159 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
160     $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')");
161     print "Upgrade to $DBversion done (set SessionStorage variable)\n";
162     SetVersion ($DBversion);
163 }
164
165 $DBversion = "3.00.00.008";
166 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
167     $dbh->do("ALTER TABLE `biblio` ADD `datecreated` DATE NOT NULL AFTER `timestamp` ;");
168     $dbh->do("UPDATE biblio SET datecreated=timestamp");
169     print "Upgrade to $DBversion done (biblio creation date)\n";
170     SetVersion ($DBversion);
171 }
172
173 $DBversion = "3.00.00.009";
174 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
175
176     # Create backups of call number columns
177     # in case default migration needs to be customized
178     #
179     # UPGRADE NOTE: temp_upg_biblioitems_call_num should be dropped
180     #               after call numbers have been transformed to the new structure
181     #
182     # Not bothering to do the same with deletedbiblioitems -- assume
183     # default is good enough.
184     $dbh->do("CREATE TABLE `temp_upg_biblioitems_call_num` AS
185               SELECT `biblioitemnumber`, `biblionumber`,
186                      `classification`, `dewey`, `subclass`,
187                      `lcsort`, `ccode`
188               FROM `biblioitems`");
189
190     # biblioitems changes
191     $dbh->do("ALTER TABLE `biblioitems` CHANGE COLUMN `volumeddesc` `volumedesc` TEXT,
192                                     ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
193                                     ADD `cn_class` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
194                                     ADD `cn_item` VARCHAR(10) DEFAULT NULL AFTER `cn_class`,
195                                     ADD `cn_suffix` VARCHAR(10) DEFAULT NULL AFTER `cn_item`,
196                                     ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_suffix`,
197                                     ADD `totalissues` INT(10) AFTER `cn_sort`");
198
199     # default mapping of call number columns:
200     #   cn_class = concatentation of classification + dewey,
201     #              trimmed to fit -- assumes that most users do not
202     #              populate both classification and dewey in a single record
203     #   cn_item  = subclass
204     #   cn_source = left null
205     #   cn_sort = lcsort
206     #
207     # After upgrade, cn_sort will have to be set based on whatever
208     # default call number scheme user sets as a preference.  Misc
209     # script will be added at some point to do that.
210     #
211     $dbh->do("UPDATE `biblioitems`
212               SET cn_class = SUBSTR(TRIM(CONCAT_WS(' ', `classification`, `dewey`)), 1, 30),
213                     cn_item = subclass,
214                     `cn_sort` = `lcsort`
215             ");
216
217     # Now drop the old call number columns
218     $dbh->do("ALTER TABLE `biblioitems` DROP COLUMN `classification`,
219                                         DROP COLUMN `dewey`,
220                                         DROP COLUMN `subclass`,
221                                         DROP COLUMN `lcsort`,
222                                         DROP COLUMN `ccode`");
223
224     # deletedbiblio changes
225     $dbh->do("ALTER TABLE `deletedbiblio` ALTER COLUMN `frameworkcode` SET DEFAULT '',
226                                         DROP COLUMN `marc`,
227                                         ADD `datecreated` DATE NOT NULL AFTER `timestamp`");
228     $dbh->do("UPDATE deletedbiblio SET datecreated = timestamp");
229
230     # deletedbiblioitems changes
231     $dbh->do("ALTER TABLE `deletedbiblioitems`
232                         MODIFY `publicationyear` TEXT,
233                         CHANGE `volumeddesc` `volumedesc` TEXT,
234                         MODIFY `collectiontitle` MEDIUMTEXT DEFAULT NULL AFTER `volumedesc`,
235                         MODIFY `collectionissn` TEXT DEFAULT NULL AFTER `collectiontitle`,
236                         MODIFY `collectionvolume` MEDIUMTEXT DEFAULT NULL AFTER `collectionissn`,
237                         MODIFY `editionstatement` TEXT DEFAULT NULL AFTER `collectionvolume`,
238                         MODIFY `editionresponsibility` TEXT DEFAULT NULL AFTER `editionstatement`,
239                         MODIFY `place` VARCHAR(255) DEFAULT NULL AFTER `size`,
240                         MODIFY `marc` LONGBLOB,
241                         ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `url`,
242                         ADD `cn_class` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
243                         ADD `cn_item` VARCHAR(10) DEFAULT NULL AFTER `cn_class`,
244                         ADD `cn_suffix` VARCHAR(10) DEFAULT NULL AFTER `cn_item`,
245                         ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_suffix`,
246                         ADD `totalissues` INT(10) AFTER `cn_sort`,
247                         ADD `marcxml` LONGTEXT NOT NULL AFTER `totalissues`,
248                         ADD KEY `isbn` (`isbn`),
249                         ADD KEY `publishercode` (`publishercode`)
250                     ");
251
252     $dbh->do("UPDATE `deletedbiblioitems`
253                 SET `cn_class` = SUBSTR(TRIM(CONCAT_WS(' ', `classification`, `dewey`)), 1, 30),
254                `cn_item` = `subclass`,
255                 `cn_sort` = `lcsort`
256             ");
257     $dbh->do("ALTER TABLE `deletedbiblioitems`
258                         DROP COLUMN `classification`,
259                         DROP COLUMN `dewey`,
260                         DROP COLUMN `subclass`,
261                         DROP COLUMN `lcsort`,
262                         DROP COLUMN `ccode`
263             ");
264
265     # deleteditems changes
266     $dbh->do("ALTER TABLE `deleteditems`
267                         MODIFY `barcode` VARCHAR(20) DEFAULT NULL,
268                         MODIFY `price` DECIMAL(8,2) DEFAULT NULL,
269                         MODIFY `replacementprice` DECIMAL(8,2) DEFAULT NULL,
270                         DROP `bulk`,
271                         MODIFY `itemcallnumber` VARCHAR(30) DEFAULT NULL AFTER `wthdrawn`,
272                         MODIFY `holdingbranch` VARCHAR(10) DEFAULT NULL,
273                         DROP `interim`,
274                         MODIFY `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP AFTER `paidfor`,
275                         DROP `cutterextra`,
276                         ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `onloan`,
277                         ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
278                         ADD `ccode` VARCHAR(10) DEFAULT NULL AFTER `cn_sort`,
279                         ADD `materials` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
280                         ADD `uri` VARCHAR(255) DEFAULT NULL AFTER `materials`,
281                         MODIFY `marc` LONGBLOB AFTER `uri`,
282                         DROP KEY `barcode`,
283                         DROP KEY `itembarcodeidx`,
284                         DROP KEY `itembinoidx`,
285                         DROP KEY `itembibnoidx`,
286                         ADD UNIQUE KEY `delitembarcodeidx` (`barcode`),
287                         ADD KEY `delitembinoidx` (`biblioitemnumber`),
288                         ADD KEY `delitembibnoidx` (`biblionumber`),
289                         ADD KEY `delhomebranch` (`homebranch`),
290                         ADD KEY `delholdingbranch` (`holdingbranch`)");
291     $dbh->do("UPDATE deleteditems SET `ccode` = `itype`");
292     $dbh->do("ALTER TABLE deleteditems DROP `itype`");
293     $dbh->do("UPDATE `deleteditems` SET `cn_sort` = `itemcallnumber`");
294
295     # items changes
296     $dbh->do("ALTER TABLE `items` ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `onloan`,
297                                 ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
298                                 ADD `ccode` VARCHAR(10) DEFAULT NULL AFTER `cn_sort`,
299                                 ADD `materials` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
300                                 ADD `uri` VARCHAR(255) DEFAULT NULL AFTER `materials`
301             ");
302     $dbh->do("ALTER TABLE `items`
303                         DROP KEY `itembarcodeidx`,
304                         ADD UNIQUE KEY `itembarcodeidx` (`barcode`)");
305
306     # map items.itype to items.ccode and
307     # set cn_sort to itemcallnumber -- as with biblioitems.cn_sort,
308     # will have to be subsequently updated per user's default
309     # classification scheme
310     $dbh->do("UPDATE `items` SET `cn_sort` = `itemcallnumber`,
311                             `ccode` = `itype`");
312
313     $dbh->do("ALTER TABLE `items` DROP `cutterextra`,
314                                 DROP `itype`");
315
316     print "Upgrade to $DBversion done (major changes to biblio, biblioitems, items, and deleted* versions of same\n";
317     SetVersion ($DBversion);
318 }
319
320 $DBversion = "3.00.00.010";
321 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
322     $dbh->do("CREATE INDEX `userid` ON borrowers (`userid`) ");
323     print "Upgrade to $DBversion done (userid index added)\n";
324     SetVersion ($DBversion);
325 }
326
327 $DBversion = "3.00.00.011";
328 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
329     $dbh->do("ALTER TABLE `branchcategories` CHANGE `categorycode` `categorycode` varchar(10) ");
330     $dbh->do("ALTER TABLE `branchcategories` CHANGE `categoryname` `categoryname` varchar(32) ");
331     $dbh->do("ALTER TABLE `branchcategories` ADD COLUMN `categorytype` varchar(16) ");
332     $dbh->do("UPDATE `branchcategories` SET `categorytype` = 'properties'");
333     $dbh->do("ALTER TABLE `branchrelations` CHANGE `categorycode` `categorycode` varchar(10) ");
334     print "Upgrade to $DBversion done (added branchcategory type)\n";
335     SetVersion ($DBversion);
336 }
337
338 $DBversion = "3.00.00.012";
339 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
340     $dbh->do("CREATE TABLE `class_sort_rules` (
341                                `class_sort_rule` varchar(10) NOT NULL default '',
342                                `description` mediumtext,
343                                `sort_routine` varchar(30) NOT NULL default '',
344                                PRIMARY KEY (`class_sort_rule`),
345                                UNIQUE KEY `class_sort_rule_idx` (`class_sort_rule`)
346                              ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
347     $dbh->do("CREATE TABLE `class_sources` (
348                                `cn_source` varchar(10) NOT NULL default '',
349                                `description` mediumtext,
350                                `used` tinyint(4) NOT NULL default 0,
351                                `class_sort_rule` varchar(10) NOT NULL default '',
352                                PRIMARY KEY (`cn_source`),
353                                UNIQUE KEY `cn_source_idx` (`cn_source`),
354                                KEY `used_idx` (`used`),
355                                CONSTRAINT `class_source_ibfk_1` FOREIGN KEY (`class_sort_rule`)
356                                           REFERENCES `class_sort_rules` (`class_sort_rule`)
357                              ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
358     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type)
359               VALUES('DefaultClassificationSource','ddc',
360                      'Default classification scheme used by the collection. E.g., Dewey, LCC, etc.', NULL,'free')");
361     $dbh->do("INSERT INTO `class_sort_rules` (`class_sort_rule`, `description`, `sort_routine`) VALUES
362                                ('dewey', 'Default filing rules for DDC', 'Dewey'),
363                                ('lcc', 'Default filing rules for LCC', 'LCC'),
364                                ('generic', 'Generic call number filing rules', 'Generic')");
365     $dbh->do("INSERT INTO `class_sources` (`cn_source`, `description`, `used`, `class_sort_rule`) VALUES
366                             ('ddc', 'Dewey Decimal Classification', 1, 'dewey'),
367                             ('lcc', 'Library of Congress Classification', 1, 'lcc'),
368                             ('udc', 'Universal Decimal Classification', 0, 'generic'),
369                             ('sudocs', 'SuDoc Classification (U.S. GPO)', 0, 'generic'),
370                             ('z', 'Other/Generic Classification Scheme', 0, 'generic')");
371     print "Upgrade to $DBversion done (classification sources added)\n";
372     SetVersion ($DBversion);
373 }
374
375 $DBversion = "3.00.00.013";
376 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
377     $dbh->do("CREATE TABLE `import_batches` (
378               `import_batch_id` int(11) NOT NULL auto_increment,
379               `template_id` int(11) default NULL,
380               `branchcode` varchar(10) default NULL,
381               `num_biblios` int(11) NOT NULL default 0,
382               `num_items` int(11) NOT NULL default 0,
383               `upload_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
384               `overlay_action` enum('replace', 'create_new', 'use_template') NOT NULL default 'create_new',
385               `import_status` enum('staging', 'staged', 'importing', 'imported', 'reverting', 'reverted', 'cleaned') NOT NULL default 'staging',
386               `batch_type` enum('batch', 'z3950') NOT NULL default 'batch',
387               `file_name` varchar(100),
388               `comments` mediumtext,
389               PRIMARY KEY (`import_batch_id`),
390               KEY `branchcode` (`branchcode`)
391               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
392     $dbh->do("CREATE TABLE `import_records` (
393               `import_record_id` int(11) NOT NULL auto_increment,
394               `import_batch_id` int(11) NOT NULL,
395               `branchcode` varchar(10) default NULL,
396               `record_sequence` int(11) NOT NULL default 0,
397               `upload_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
398               `import_date` DATE default NULL,
399               `marc` longblob NOT NULL,
400               `marcxml` longtext NOT NULL,
401               `marcxml_old` longtext NOT NULL,
402               `record_type` enum('biblio', 'auth', 'holdings') NOT NULL default 'biblio',
403               `overlay_status` enum('no_match', 'auto_match', 'manual_match', 'match_applied') NOT NULL default 'no_match',
404               `status` enum('error', 'staged', 'imported', 'reverted', 'items_reverted') NOT NULL default 'staged',
405               `import_error` mediumtext,
406               `encoding` varchar(40) NOT NULL default '',
407               `z3950random` varchar(40) default NULL,
408               PRIMARY KEY (`import_record_id`),
409               CONSTRAINT `import_records_ifbk_1` FOREIGN KEY (`import_batch_id`)
410                           REFERENCES `import_batches` (`import_batch_id`) ON DELETE CASCADE ON UPDATE CASCADE,
411               KEY `branchcode` (`branchcode`),
412               KEY `batch_sequence` (`import_batch_id`, `record_sequence`)
413               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
414     $dbh->do("CREATE TABLE `import_record_matches` (
415               `import_record_id` int(11) NOT NULL,
416               `candidate_match_id` int(11) NOT NULL,
417               `score` int(11) NOT NULL default 0,
418               CONSTRAINT `import_record_matches_ibfk_1` FOREIGN KEY (`import_record_id`)
419                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
420               KEY `record_score` (`import_record_id`, `score`)
421               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
422     $dbh->do("CREATE TABLE `import_biblios` (
423               `import_record_id` int(11) NOT NULL,
424               `matched_biblionumber` int(11) default NULL,
425               `control_number` varchar(25) default NULL,
426               `original_source` varchar(25) default NULL,
427               `title` varchar(128) default NULL,
428               `author` varchar(80) default NULL,
429               `isbn` varchar(14) default NULL,
430               `issn` varchar(9) default NULL,
431               `has_items` tinyint(1) NOT NULL default 0,
432               CONSTRAINT `import_biblios_ibfk_1` FOREIGN KEY (`import_record_id`)
433                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
434               KEY `matched_biblionumber` (`matched_biblionumber`),
435               KEY `title` (`title`),
436               KEY `isbn` (`isbn`)
437               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
438     $dbh->do("CREATE TABLE `import_items` (
439               `import_items_id` int(11) NOT NULL auto_increment,
440               `import_record_id` int(11) NOT NULL,
441               `itemnumber` int(11) default NULL,
442               `branchcode` varchar(10) default NULL,
443               `status` enum('error', 'staged', 'imported', 'reverted') NOT NULL default 'staged',
444               `marcxml` longtext NOT NULL,
445               `import_error` mediumtext,
446               PRIMARY KEY (`import_items_id`),
447               CONSTRAINT `import_items_ibfk_1` FOREIGN KEY (`import_record_id`)
448                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
449               KEY `itemnumber` (`itemnumber`),
450               KEY `branchcode` (`branchcode`)
451               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
452
453     $dbh->do("INSERT INTO `import_batches`
454                 (`overlay_action`, `import_status`, `batch_type`, `file_name`)
455               SELECT distinct 'create_new', 'staged', 'z3950', `file`
456               FROM   `marc_breeding`");
457
458     $dbh->do("INSERT INTO `import_records`
459                 (`import_batch_id`, `import_record_id`, `record_sequence`, `marc`, `record_type`, `status`,
460                 `encoding`, `z3950random`, `marcxml`, `marcxml_old`)
461               SELECT `import_batch_id`, `id`, 1, `marc`, 'biblio', 'staged', `encoding`, `z3950random`, '', ''
462               FROM `marc_breeding`
463               JOIN `import_batches` ON (`file_name` = `file`)");
464
465     $dbh->do("INSERT INTO `import_biblios`
466                 (`import_record_id`, `title`, `author`, `isbn`)
467               SELECT `import_record_id`, `title`, `author`, `isbn`
468               FROM   `marc_breeding`
469               JOIN   `import_records` ON (`import_record_id` = `id`)");
470
471     $dbh->do("UPDATE `import_batches`
472               SET `num_biblios` = (
473               SELECT COUNT(*)
474               FROM `import_records`
475               WHERE `import_batch_id` = `import_batches`.`import_batch_id`
476               )");
477
478     $dbh->do("DROP TABLE `marc_breeding`");
479
480     print "Upgrade to $DBversion done (import_batches et al. added)\n";
481     SetVersion ($DBversion);
482 }
483
484 $DBversion = "3.00.00.014";
485 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
486     $dbh->do("ALTER TABLE subscription ADD lastbranch VARCHAR(4)");
487     print "Upgrade to $DBversion done (userid index added)\n";
488     SetVersion ($DBversion);
489 }
490
491 $DBversion = "3.00.00.015";
492 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
493     $dbh->do("CREATE TABLE `saved_sql` (
494            `id` int(11) NOT NULL auto_increment,
495            `borrowernumber` int(11) default NULL,
496            `date_created` datetime default NULL,
497            `last_modified` datetime default NULL,
498            `savedsql` text,
499            `last_run` datetime default NULL,
500            `report_name` varchar(255) default NULL,
501            `type` varchar(255) default NULL,
502            `notes` text,
503            PRIMARY KEY  (`id`),
504            KEY boridx (`borrowernumber`)
505         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
506     $dbh->do("CREATE TABLE `saved_reports` (
507            `id` int(11) NOT NULL auto_increment,
508            `report_id` int(11) default NULL,
509            `report` longtext,
510            `date_run` datetime default NULL,
511            PRIMARY KEY  (`id`)
512         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
513     print "Upgrade to $DBversion done (saved_sql and saved_reports added)\n";
514     SetVersion ($DBversion);
515 }
516
517 $DBversion = "3.00.00.016";
518 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
519     $dbh->do(" CREATE TABLE reports_dictionary (
520           id int(11) NOT NULL auto_increment,
521           name varchar(255) default NULL,
522           description text,
523           date_created datetime default NULL,
524           date_modified datetime default NULL,
525           saved_sql text,
526           area int(11) default NULL,
527           PRIMARY KEY  (id)
528         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
529     print "Upgrade to $DBversion done (reports_dictionary) added)\n";
530     SetVersion ($DBversion);
531 }
532
533 $DBversion = "3.00.00.017";
534 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
535     $dbh->do("ALTER TABLE action_logs DROP PRIMARY KEY");
536     $dbh->do("ALTER TABLE action_logs ADD KEY  timestamp (timestamp,user)");
537     $dbh->do("ALTER TABLE action_logs ADD action_id INT(11) NOT NULL FIRST");
538     $dbh->do("UPDATE action_logs SET action_id = if (\@a, \@a:=\@a+1, \@a:=1)");
539     $dbh->do("ALTER TABLE action_logs MODIFY action_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY");
540     print "Upgrade to $DBversion done (added column to action_logs)\n";
541     SetVersion ($DBversion);
542 }
543
544 $DBversion = "3.00.00.018";
545 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
546     $dbh->do("ALTER TABLE `zebraqueue`
547                     ADD `done` INT NOT NULL DEFAULT '0',
548                     ADD `time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ;
549             ");
550     print "Upgrade to $DBversion done (adding timestamp and done columns to zebraque table to improve problem tracking) added)\n";
551     SetVersion ($DBversion);
552 }
553
554 $DBversion = "3.00.00.019";
555 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
556     $dbh->do("ALTER TABLE biblio MODIFY biblionumber INT(11) NOT NULL AUTO_INCREMENT");
557     $dbh->do("ALTER TABLE biblioitems MODIFY biblioitemnumber INT(11) NOT NULL AUTO_INCREMENT");
558     $dbh->do("ALTER TABLE items MODIFY itemnumber INT(11) NOT NULL AUTO_INCREMENT");
559     print "Upgrade to $DBversion done (made bib/item PKs auto_increment)\n";
560     SetVersion ($DBversion);
561 }
562
563 $DBversion = "3.00.00.020";
564 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
565     $dbh->do("ALTER TABLE deleteditems
566               DROP KEY `delitembarcodeidx`,
567               ADD KEY `delitembarcodeidx` (`barcode`)");
568     print "Upgrade to $DBversion done (dropped uniqueness of key on deleteditems.barcode)\n";
569     SetVersion ($DBversion);
570 }
571
572 $DBversion = "3.00.00.021";
573 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
574     $dbh->do("ALTER TABLE items CHANGE homebranch homebranch VARCHAR(10)");
575     $dbh->do("ALTER TABLE deleteditems CHANGE homebranch homebranch VARCHAR(10)");
576     $dbh->do("ALTER TABLE statistics CHANGE branch branch VARCHAR(10)");
577     $dbh->do("ALTER TABLE subscription CHANGE lastbranch lastbranch VARCHAR(10)");
578     print "Upgrade to $DBversion done (extended missed branchcode columns to 10 chars)\n";
579     SetVersion ($DBversion);
580 }
581
582 $DBversion = "3.00.00.022";
583 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
584     $dbh->do("ALTER TABLE items
585                 ADD `damaged` tinyint(1) default NULL AFTER notforloan");
586     $dbh->do("ALTER TABLE deleteditems
587                 ADD `damaged` tinyint(1) default NULL AFTER notforloan");
588     print "Upgrade to $DBversion done (adding damaged column to items table)\n";
589     SetVersion ($DBversion);
590 }
591
592 $DBversion = "3.00.00.023";
593 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
594      $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
595          VALUES ('yuipath','http://yui.yahooapis.com/2.3.1/build','Insert the path to YUI libraries','','free')");
596     print "Upgrade to $DBversion done (adding new system preference for controlling YUI path)\n";
597     SetVersion ($DBversion);
598 }
599 $DBversion = "3.00.00.024";
600 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
601     $dbh->do("ALTER TABLE biblioitems CHANGE  itemtype itemtype VARCHAR(10)");
602     print "Upgrade to $DBversion done (changing itemtype to (10))\n";
603     SetVersion ($DBversion);
604 }
605
606 $DBversion = "3.00.00.025";
607 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
608     $dbh->do("ALTER TABLE items ADD COLUMN itype VARCHAR(10)");
609     $dbh->do("ALTER TABLE deleteditems ADD COLUMN itype VARCHAR(10) AFTER uri");
610     if(C4::Context->preference('item-level_itypes')){
611         $dbh->do('update items,biblioitems set items.itype=biblioitems.itemtype where items.biblionumber=biblioitems.biblionumber and itype is null');
612     }
613     print "Upgrade to $DBversion done (reintroduce items.itype - fill from itemtype)\n ";
614     SetVersion ($DBversion);
615 }
616
617 $DBversion = "3.00.00.026";
618 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
619     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
620        VALUES ('HomeOrHoldingBranch','homebranch','homebranch|holdingbranch','With independent branches turned on this decides whether to check the items holdingbranch or homebranch at circulatilon','choice')");
621     print "Upgrade to $DBversion done (adding new system preference for choosing whether homebranch or holdingbranch is checked in circulation)\n";
622     SetVersion ($DBversion);
623 }
624
625 $DBversion = "3.00.00.027";
626 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
627     $dbh->do("CREATE TABLE `marc_matchers` (
628                 `matcher_id` int(11) NOT NULL auto_increment,
629                 `code` varchar(10) NOT NULL default '',
630                 `description` varchar(255) NOT NULL default '',
631                 `record_type` varchar(10) NOT NULL default 'biblio',
632                 `threshold` int(11) NOT NULL default 0,
633                 PRIMARY KEY (`matcher_id`),
634                 KEY `code` (`code`),
635                 KEY `record_type` (`record_type`)
636               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
637     $dbh->do("CREATE TABLE `matchpoints` (
638                 `matcher_id` int(11) NOT NULL,
639                 `matchpoint_id` int(11) NOT NULL auto_increment,
640                 `search_index` varchar(30) NOT NULL default '',
641                 `score` int(11) NOT NULL default 0,
642                 PRIMARY KEY (`matchpoint_id`),
643                 CONSTRAINT `matchpoints_ifbk_1` FOREIGN KEY (`matcher_id`)
644                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE
645               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
646     $dbh->do("CREATE TABLE `matchpoint_components` (
647                 `matchpoint_id` int(11) NOT NULL,
648                 `matchpoint_component_id` int(11) NOT NULL auto_increment,
649                 sequence int(11) NOT NULL default 0,
650                 tag varchar(3) NOT NULL default '',
651                 subfields varchar(40) NOT NULL default '',
652                 offset int(4) NOT NULL default 0,
653                 length int(4) NOT NULL default 0,
654                 PRIMARY KEY (`matchpoint_component_id`),
655                 KEY `by_sequence` (`matchpoint_id`, `sequence`),
656                 CONSTRAINT `matchpoint_components_ifbk_1` FOREIGN KEY (`matchpoint_id`)
657                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
658               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
659     $dbh->do("CREATE TABLE `matchpoint_component_norms` (
660                 `matchpoint_component_id` int(11) NOT NULL,
661                 `sequence`  int(11) NOT NULL default 0,
662                 `norm_routine` varchar(50) NOT NULL default '',
663                 KEY `matchpoint_component_norms` (`matchpoint_component_id`, `sequence`),
664                 CONSTRAINT `matchpoint_component_norms_ifbk_1` FOREIGN KEY (`matchpoint_component_id`)
665                            REFERENCES `matchpoint_components` (`matchpoint_component_id`) ON DELETE CASCADE ON UPDATE CASCADE
666               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
667     $dbh->do("CREATE TABLE `matcher_matchpoints` (
668                 `matcher_id` int(11) NOT NULL,
669                 `matchpoint_id` int(11) NOT NULL,
670                 CONSTRAINT `matcher_matchpoints_ifbk_1` FOREIGN KEY (`matcher_id`)
671                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE,
672                 CONSTRAINT `matcher_matchpoints_ifbk_2` FOREIGN KEY (`matchpoint_id`)
673                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
674               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
675     $dbh->do("CREATE TABLE `matchchecks` (
676                 `matcher_id` int(11) NOT NULL,
677                 `matchcheck_id` int(11) NOT NULL auto_increment,
678                 `source_matchpoint_id` int(11) NOT NULL,
679                 `target_matchpoint_id` int(11) NOT NULL,
680                 PRIMARY KEY (`matchcheck_id`),
681                 CONSTRAINT `matcher_matchchecks_ifbk_1` FOREIGN KEY (`matcher_id`)
682                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE,
683                 CONSTRAINT `matcher_matchchecks_ifbk_2` FOREIGN KEY (`source_matchpoint_id`)
684                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE,
685                 CONSTRAINT `matcher_matchchecks_ifbk_3` FOREIGN KEY (`target_matchpoint_id`)
686                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
687               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
688     print "Upgrade to $DBversion done (added C4::Matcher serialization tables)\n ";
689     SetVersion ($DBversion);
690 }
691
692 $DBversion = "3.00.00.028";
693 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
694     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
695        VALUES ('canreservefromotherbranches','1','','With Independent branches on, can a user from one library reserve an item from another library','YesNo')");
696     print "Upgrade to $DBversion done (adding new system preference for changing reserve/holds behaviour with independent branches)\n";
697     SetVersion ($DBversion);
698 }
699
700
701 $DBversion = "3.00.00.029";
702 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
703     $dbh->do("ALTER TABLE `import_batches` ADD `matcher_id` int(11) NULL AFTER `import_batch_id`");
704     print "Upgrade to $DBversion done (adding matcher_id to import_batches)\n";
705     SetVersion ($DBversion);
706 }
707
708 $DBversion = "3.00.00.030";
709 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
710     $dbh->do("
711 CREATE TABLE services_throttle (
712   service_type varchar(10) NOT NULL default '',
713   service_count varchar(45) default NULL,
714   PRIMARY KEY  (service_type)
715 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
716 ");
717     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
718        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')");
719  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
720        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')");
721  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
722        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')");
723  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
724        VALUES ('XISBNDailyLimit',499,'','The xISBN Web service is free for non-commercial use when usage does not exceed 500 requests per day','free')");
725  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
726        VALUES ('PINESISBN',0,'','Use with FRBRizeEditions. If ON, Koha will use PINES OISBN web service in the Editions tab on the detail pages.','YesNo')");
727  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
728        VALUES ('ThingISBN',0,'','Use with FRBRizeEditions. If ON, Koha will use the ThingISBN web service in the Editions tab on the detail pages.','YesNo')");
729     print "Upgrade to $DBversion done (adding services throttle table and sysprefs for xISBN)\n";
730     SetVersion ($DBversion);
731 }
732
733 $DBversion = "3.00.00.031";
734 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
735
736 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryStemming',1,'If ON, enables query stemming',NULL,'YesNo')");
737 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryFuzzy',1,'If ON, enables fuzzy option for searches',NULL,'YesNo')");
738 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryWeightFields',1,'If ON, enables field weighting',NULL,'YesNo')");
739 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('WebBasedSelfCheck',0,'If ON, enables the web-based self-check system',NULL,'YesNo')");
740 $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')");
741 $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')");
742 $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')");
743 $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')");
744 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('defaultSortOrder',NULL,'Specify the default sort order','asc|dsc|az|za','Choice')");
745 $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')");
746 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACdefaultSortOrder',NULL,'Specify the default sort order','asc|dsc|za|az','Choice')");
747 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('staffClientBaseURL','','Specify the base URL of the staff client',NULL,'free')");
748 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('minPasswordLength',3,'Specify the minimum length of a patron/staff password',NULL,'free')");
749 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('noItemTypeImages',0,'If ON, disables item-type images',NULL,'YesNo')");
750 $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')");
751 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('holdCancelLength','','Specify how many days before a hold is canceled',NULL,'free')");
752 $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')");
753 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('finesMode','test','Choose the fines mode, test or production','test|production','Choice')");
754 $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')");
755 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('itemBarcodeInputFilter','','If set, allows specification of a item barcode input filter','cuecat','Choice')");
756 $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')");
757 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('URLLinkText','','Text to display as the link anchor in the OPAC',NULL,'free')");
758 $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')");
759 $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')");
760 $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')");
761 $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')");
762 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACUserCSS',0,'Add CSS to be included in the OPAC',NULL,'free')");
763
764     print "Upgrade to $DBversion done (adding additional system preference)\n";
765     SetVersion ($DBversion);
766 }
767
768 $DBversion = "3.00.00.032";
769 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
770     $dbh->do("UPDATE `marc_subfield_structure` SET `kohafield` = 'items.wthdrawn' WHERE `kohafield` = 'items.withdrawn'");
771     print "Upgrade to $DBversion done (fixed MARC framework references to items.withdrawn)\n";
772     SetVersion ($DBversion);
773 }
774
775 $DBversion = "3.00.00.033";
776 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
777     $dbh->do("INSERT INTO `userflags` VALUES(17,'staffaccess','Modify login / permissions for staff users',0)");
778     print "Upgrade to $DBversion done (Adding permissions flag for staff member access modification.  )\n";
779     SetVersion ($DBversion);
780 }
781
782 $DBversion = "3.00.00.034";
783 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
784     $dbh->do("ALTER TABLE `virtualshelves` ADD COLUMN `sortfield` VARCHAR(16) ");
785     print "Upgrade to $DBversion done (Adding sortfield for Virtual Shelves.  )\n";
786     SetVersion ($DBversion);
787 }
788
789 $DBversion = "3.00.00.035";
790 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
791     $dbh->do("UPDATE marc_subfield_structure
792               SET authorised_value = 'cn_source'
793               WHERE kohafield IN ('items.cn_source', 'biblioitems.cn_source')
794               AND (authorised_value is NULL OR authorised_value = '')");
795     print "Upgrade to $DBversion done (MARC frameworks: make classification source a drop-down)\n";
796     SetVersion ($DBversion);
797 }
798
799 $DBversion = "3.00.00.036";
800 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
801     $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');");
802     print "Upgrade to $DBversion done (OPACItemsResultsDisplay systempreference added)\n";
803     SetVersion ($DBversion);
804 }
805
806 $DBversion = "3.00.00.037";
807 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
808     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactfirstname` varchar(255)");
809     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactsurname` varchar(255)");
810     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress1` varchar(255)");
811     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress2` varchar(255)");
812     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress3` varchar(255)");
813     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactzipcode` varchar(50)");
814     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactphone` varchar(50)");
815     print "Upgrade to $DBversion done (Adding Alternative Contact Person information to borrowers table)\n";
816     SetVersion ($DBversion);
817 }
818
819 $DBversion = "3.00.00.038";
820 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
821     $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'");
822     $dbh->do("DELETE FROM `systempreferences` WHERE variable='hideBiblioNumber'");
823     print "Upgrade to $DBversion done ('alter finesMode systempreference, remove superfluous syspref.')\n";
824     SetVersion ($DBversion);
825 }
826
827 $DBversion = "3.00.00.039";
828 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
829     $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')");
830     $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')");
831     $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')");
832     # $dbh->do("DELETE FROM `systempreferences` WHERE variable='HomeOrHoldingBranch'"); # Bug #2752
833     print "Upgrade to $DBversion done ('add circ sysprefs CircControl, finesCalendar, and uppercasesurnames, and delete HomeOrHoldingBranch.')\n";
834     SetVersion ($DBversion);
835 }
836
837 $DBversion = "3.00.00.040";
838 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
839         $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')");
840         $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')");
841         print "Upgrade to $DBversion done ('add circ sysprefs todaysIssuesDefaultSortOrder and previousIssuesDefaultSortOrder.')\n";
842     SetVersion ($DBversion);
843 }
844
845
846 $DBversion = "3.00.00.041";
847 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
848     # Strictly speaking it is not necessary to explicitly change
849     # NULL values to 0, because the ALTER TABLE statement will do that.
850     # However, setting them first avoids a warning.
851     $dbh->do("UPDATE items SET notforloan = 0 WHERE notforloan IS NULL");
852     $dbh->do("UPDATE items SET damaged = 0 WHERE damaged IS NULL");
853     $dbh->do("UPDATE items SET itemlost = 0 WHERE itemlost IS NULL");
854     $dbh->do("UPDATE items SET wthdrawn = 0 WHERE wthdrawn IS NULL");
855     $dbh->do("ALTER TABLE items
856                 MODIFY notforloan tinyint(1) NOT NULL default 0,
857                 MODIFY damaged    tinyint(1) NOT NULL default 0,
858                 MODIFY itemlost   tinyint(1) NOT NULL default 0,
859                 MODIFY wthdrawn   tinyint(1) NOT NULL default 0");
860     $dbh->do("UPDATE deleteditems SET notforloan = 0 WHERE notforloan IS NULL");
861     $dbh->do("UPDATE deleteditems SET damaged = 0 WHERE damaged IS NULL");
862     $dbh->do("UPDATE deleteditems SET itemlost = 0 WHERE itemlost IS NULL");
863     $dbh->do("UPDATE deleteditems SET wthdrawn = 0 WHERE wthdrawn IS NULL");
864     $dbh->do("ALTER TABLE deleteditems
865                 MODIFY notforloan tinyint(1) NOT NULL default 0,
866                 MODIFY damaged    tinyint(1) NOT NULL default 0,
867                 MODIFY itemlost   tinyint(1) NOT NULL default 0,
868                 MODIFY wthdrawn   tinyint(1) NOT NULL default 0");
869         print "Upgrade to $DBversion done (disallow NULL in several item status columns)\n";
870     SetVersion ($DBversion);
871 }
872
873 $DBversion = "3.00.00.04";
874 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
875     $dbh->do("ALTER TABLE aqbooksellers CHANGE name name mediumtext NOT NULL");
876         print "Upgrade to $DBversion done (disallow NULL in aqbooksellers.name; part of fix for bug 1251)\n";
877     SetVersion ($DBversion);
878 }
879
880 $DBversion = "3.00.00.043";
881 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
882     $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");
883         print "Upgrade to $DBversion done (currency table: add symbol and timestamp columns)\n";
884     SetVersion ($DBversion);
885 }
886
887 $DBversion = "3.00.00.044";
888 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
889     $dbh->do("ALTER TABLE deletedborrowers
890   ADD `altcontactfirstname` varchar(255) default NULL,
891   ADD `altcontactsurname` varchar(255) default NULL,
892   ADD `altcontactaddress1` varchar(255) default NULL,
893   ADD `altcontactaddress2` varchar(255) default NULL,
894   ADD `altcontactaddress3` varchar(255) default NULL,
895   ADD `altcontactzipcode` varchar(50) default NULL,
896   ADD `altcontactphone` varchar(50) default NULL
897   ");
898   $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES
899 ('OPACBaseURL',NULL,'Specify the Base URL of the OPAC, e.g., opac.mylibrary.com, the http:// will be added automatically by Koha.',NULL,'Free'),
900 ('language','en','Set the default language in the staff client.',NULL,'Languages'),
901 ('QueryAutoTruncate',1,'If ON, query truncation is enabled by default',NULL,'YesNo'),
902 ('QueryRemoveStopwords',0,'If ON, stopwords listed in the Administration area will be removed from queries',NULL,'YesNo')
903   ");
904         print "Upgrade to $DBversion done (syncing deletedborrowers table with borrowers table)\n";
905     SetVersion ($DBversion);
906 }
907
908 #-- http://www.w3.org/International/articles/language-tags/
909
910 #-- RFC4646
911 $DBversion = "3.00.00.045";
912 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
913     $dbh->do("
914 CREATE TABLE language_subtag_registry (
915         subtag varchar(25),
916         type varchar(25), -- language-script-region-variant-extension-privateuse
917         description varchar(25), -- only one of the possible descriptions for ease of reference, see language_descriptions for the complete list
918         added date,
919         KEY `subtag` (`subtag`)
920 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
921
922 #-- TODO: add suppress_scripts
923 #-- this maps three letter codes defined in iso639.2 back to their
924 #-- two letter equivilents in rfc4646 (LOC maintains iso639+)
925  $dbh->do("CREATE TABLE language_rfc4646_to_iso639 (
926         rfc4646_subtag varchar(25),
927         iso639_2_code varchar(25),
928         KEY `rfc4646_subtag` (`rfc4646_subtag`)
929 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
930
931  $dbh->do("CREATE TABLE language_descriptions (
932         subtag varchar(25),
933         type varchar(25),
934         lang varchar(25),
935         description varchar(255),
936         KEY `lang` (`lang`)
937 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
938
939 #-- bi-directional support, keyed by script subcode
940  $dbh->do("CREATE TABLE language_script_bidi (
941         rfc4646_subtag varchar(25), -- script subtag, Arab, Hebr, etc.
942         bidi varchar(3), -- rtl ltr
943         KEY `rfc4646_subtag` (`rfc4646_subtag`)
944 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
945
946 #-- BIDI Stuff, Arabic and Hebrew
947  $dbh->do("INSERT INTO language_script_bidi(rfc4646_subtag,bidi)
948 VALUES( 'Arab', 'rtl')");
949  $dbh->do("INSERT INTO language_script_bidi(rfc4646_subtag,bidi)
950 VALUES( 'Hebr', 'rtl')");
951
952 #-- TODO: need to map language subtags to script subtags for detection
953 #-- of bidi when script is not specified (like ar, he)
954  $dbh->do("CREATE TABLE language_script_mapping (
955         language_subtag varchar(25),
956         script_subtag varchar(25),
957         KEY `language_subtag` (`language_subtag`)
958 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
959
960 #-- Default mappings between script and language subcodes
961  $dbh->do("INSERT INTO language_script_mapping(language_subtag,script_subtag)
962 VALUES( 'ar', 'Arab')");
963  $dbh->do("INSERT INTO language_script_mapping(language_subtag,script_subtag)
964 VALUES( 'he', 'Hebr')");
965
966         print "Upgrade to $DBversion done (adding language subtag registry and basic BiDi support NOTE: You should import the subtag registry SQL)\n";
967     SetVersion ($DBversion);
968 }
969
970 $DBversion = "3.00.00.046";
971 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
972     $dbh->do("ALTER TABLE `subscription` CHANGE `numberlength` `numberlength` int(11) default '0' ,
973                  CHANGE `weeklength` `weeklength` int(11) default '0'");
974     $dbh->do("CREATE TABLE `serialitems` (`serialid` int(11) NOT NULL, `itemnumber` int(11) NOT NULL, UNIQUE KEY `serialididx` (`serialid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
975     $dbh->do("INSERT INTO `serialitems` SELECT `serialid`,`itemnumber` from serial where NOT ISNULL(itemnumber) && itemnumber <> '' && itemnumber NOT LIKE '%,%'");
976         print "Upgrade to $DBversion done (Add serialitems table to link serial issues to items. )\n";
977     SetVersion ($DBversion);
978 }
979
980 $DBversion = "3.00.00.047";
981 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
982     $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');");
983         print "Upgrade to $DBversion done ( Added OpacRenewalAllowed syspref )\n";
984     SetVersion ($DBversion);
985 }
986
987 $DBversion = "3.00.00.048";
988 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
989     $dbh->do("ALTER TABLE `items` ADD `more_subfields_xml` longtext default NULL AFTER `itype`");
990         print "Upgrade to $DBversion done (added items.more_subfields_xml)\n";
991     SetVersion ($DBversion);
992 }
993
994 $DBversion = "3.00.00.049";
995 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
996         $dbh->do("ALTER TABLE `z3950servers` ADD `encoding` text default NULL AFTER type ");
997         print "Upgrade to $DBversion done ( Added encoding field to z3950servers table )\n";
998     SetVersion ($DBversion);
999 }
1000
1001 $DBversion = "3.00.00.050";
1002 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1003     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacHighlightedWords','0','If Set, query matched terms are highlighted in OPAC',NULL,'YesNo');");
1004         print "Upgrade to $DBversion done ( Added OpacHighlightedWords syspref )\n";
1005     SetVersion ($DBversion);
1006 }
1007
1008 $DBversion = "3.00.00.051";
1009 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1010     $dbh->do("UPDATE systempreferences SET explanation = 'Define the current theme for the OPAC interface.' WHERE variable = 'opacthemes';");
1011         print "Upgrade to $DBversion done ( Corrected opacthemes explanation. )\n";
1012     SetVersion ($DBversion);
1013 }
1014
1015 $DBversion = "3.00.00.052";
1016 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1017     $dbh->do("ALTER TABLE `deleteditems` ADD `more_subfields_xml` LONGTEXT DEFAULT NULL AFTER `itype`");
1018         print "Upgrade to $DBversion done ( Adding missing column to deleteditems table. )\n";
1019     SetVersion ($DBversion);
1020 }
1021
1022 $DBversion = "3.00.00.053";
1023 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1024     $dbh->do("CREATE TABLE `printers_profile` (
1025             `prof_id` int(4) NOT NULL auto_increment,
1026             `printername` varchar(40) NOT NULL,
1027             `tmpl_id` int(4) NOT NULL,
1028             `paper_bin` varchar(20) NOT NULL,
1029             `offset_horz` float default NULL,
1030             `offset_vert` float default NULL,
1031             `creep_horz` float default NULL,
1032             `creep_vert` float default NULL,
1033             `unit` char(20) NOT NULL default 'POINT',
1034             PRIMARY KEY  (`prof_id`),
1035             UNIQUE KEY `printername` (`printername`,`tmpl_id`,`paper_bin`),
1036             CONSTRAINT `printers_profile_pnfk_1` FOREIGN KEY (`tmpl_id`) REFERENCES `labels_templates` (`tmpl_id`) ON DELETE CASCADE ON UPDATE CASCADE
1037             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1038     $dbh->do("CREATE TABLE `labels_profile` (
1039             `tmpl_id` int(4) NOT NULL,
1040             `prof_id` int(4) NOT NULL,
1041             UNIQUE KEY `tmpl_id` (`tmpl_id`),
1042             UNIQUE KEY `prof_id` (`prof_id`)
1043             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1044     print "Upgrade to $DBversion done ( Printer Profile tables added )\n";
1045     SetVersion ($DBversion);
1046 }
1047
1048 $DBversion = "3.00.00.054";
1049 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1050     $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';");
1051         print "Upgrade to $DBversion done ( Added another barcode autogeneration sequence to barcode.pl. )\n";
1052     SetVersion ($DBversion);
1053 }
1054
1055 $DBversion = "3.00.00.055";
1056 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1057     $dbh->do("ALTER TABLE `zebraqueue` ADD KEY `zebraqueue_lookup` (`server`, `biblio_auth_number`, `operation`, `done`)");
1058         print "Upgrade to $DBversion done ( Added index on zebraqueue. )\n";
1059     SetVersion ($DBversion);
1060 }
1061 $DBversion = "3.00.00.056";
1062 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1063     if (C4::Context->preference("marcflavour") eq 'UNIMARC') {
1064         $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) ");
1065     } else {
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 ('952', 'h', 'Serial Enumeration / chronology','Serial Enumeration / chronology', 0, 0, 'items.enumchron', 10, '', '', '', 0, 0, '', '', '', NULL) ");
1067     }
1068     $dbh->do("ALTER TABLE `items` ADD `enumchron` VARCHAR(80) DEFAULT NULL;");
1069     print "Upgrade to $DBversion done ( Added item.enumchron column, and framework map to 952h )\n";
1070     SetVersion ($DBversion);
1071 }
1072
1073 $DBversion = "3.00.00.057";
1074 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1075     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH','0','if ON, OAI-PMH server is enabled',NULL,'YesNo');");
1076     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH:archiveID','KOHA-OAI-TEST','OAI-PMH archive identification',NULL,'Free');");
1077     $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');");
1078     $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');");
1079     $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');");
1080     SetVersion ($DBversion);
1081 }
1082
1083 $DBversion = "3.00.00.058";
1084 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1085     $dbh->do("ALTER TABLE `opac_news`
1086                 CHANGE `lang` `lang` VARCHAR( 25 )
1087                 CHARACTER SET utf8
1088                 COLLATE utf8_general_ci
1089                 NOT NULL default ''");
1090         print "Upgrade to $DBversion done ( lang field in opac_news made longer )\n";
1091     SetVersion ($DBversion);
1092 }
1093
1094 $DBversion = "3.00.00.059";
1095 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1096
1097     $dbh->do("CREATE TABLE IF NOT EXISTS `labels_templates` (
1098             `tmpl_id` int(4) NOT NULL auto_increment,
1099             `tmpl_code` char(100)  default '',
1100             `tmpl_desc` char(100) default '',
1101             `page_width` float default '0',
1102             `page_height` float default '0',
1103             `label_width` float default '0',
1104             `label_height` float default '0',
1105             `topmargin` float default '0',
1106             `leftmargin` float default '0',
1107             `cols` int(2) default '0',
1108             `rows` int(2) default '0',
1109             `colgap` float default '0',
1110             `rowgap` float default '0',
1111             `active` int(1) default NULL,
1112             `units` char(20)  default 'PX',
1113             `fontsize` int(4) NOT NULL default '3',
1114             PRIMARY KEY  (`tmpl_id`)
1115             ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1116     $dbh->do("CREATE TABLE  IF NOT EXISTS `printers_profile` (
1117             `prof_id` int(4) NOT NULL auto_increment,
1118             `printername` varchar(40) NOT NULL,
1119             `tmpl_id` int(4) NOT NULL,
1120             `paper_bin` varchar(20) NOT NULL,
1121             `offset_horz` float default NULL,
1122             `offset_vert` float default NULL,
1123             `creep_horz` float default NULL,
1124             `creep_vert` float default NULL,
1125             `unit` char(20) NOT NULL default 'POINT',
1126             PRIMARY KEY  (`prof_id`),
1127             UNIQUE KEY `printername` (`printername`,`tmpl_id`,`paper_bin`),
1128             CONSTRAINT `printers_profile_pnfk_1` FOREIGN KEY (`tmpl_id`) REFERENCES `labels_templates` (`tmpl_id`) ON DELETE CASCADE ON UPDATE CASCADE
1129             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1130     print "Upgrade to $DBversion done ( Added labels_templates table if it did not exist. )\n";
1131     SetVersion ($DBversion);
1132 }
1133
1134 $DBversion = "3.00.00.060";
1135 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1136     $dbh->do("CREATE TABLE IF NOT EXISTS `patronimage` (
1137             `cardnumber` varchar(16) NOT NULL,
1138             `mimetype` varchar(15) NOT NULL,
1139             `imagefile` mediumblob NOT NULL,
1140             PRIMARY KEY  (`cardnumber`),
1141             CONSTRAINT `patronimage_fk1` FOREIGN KEY (`cardnumber`) REFERENCES `borrowers` (`cardnumber`) ON DELETE CASCADE ON UPDATE CASCADE
1142             ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1143         print "Upgrade to $DBversion done ( Added patronimage table. )\n";
1144     SetVersion ($DBversion);
1145 }
1146
1147 $DBversion = "3.00.00.061";
1148 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1149     $dbh->do("ALTER TABLE labels_templates ADD COLUMN font char(10) NOT NULL DEFAULT 'TR';");
1150         print "Upgrade to $DBversion done ( Added font column to labels_templates )\n";
1151     SetVersion ($DBversion);
1152 }
1153
1154 $DBversion = "3.00.00.062";
1155 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1156     $dbh->do("CREATE TABLE `old_issues` (
1157                 `borrowernumber` int(11) default NULL,
1158                 `itemnumber` int(11) default NULL,
1159                 `date_due` date default NULL,
1160                 `branchcode` varchar(10) default NULL,
1161                 `issuingbranch` varchar(18) default NULL,
1162                 `returndate` date default NULL,
1163                 `lastreneweddate` date default NULL,
1164                 `return` varchar(4) default NULL,
1165                 `renewals` tinyint(4) default NULL,
1166                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1167                 `issuedate` date default NULL,
1168                 KEY `old_issuesborridx` (`borrowernumber`),
1169                 KEY `old_issuesitemidx` (`itemnumber`),
1170                 KEY `old_bordate` (`borrowernumber`,`timestamp`),
1171                 CONSTRAINT `old_issues_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1172                     ON DELETE SET NULL ON UPDATE SET NULL,
1173                 CONSTRAINT `old_issues_ibfk_2` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`)
1174                     ON DELETE SET NULL ON UPDATE SET NULL
1175                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1176     $dbh->do("CREATE TABLE `old_reserves` (
1177                 `borrowernumber` int(11) default NULL,
1178                 `reservedate` date default NULL,
1179                 `biblionumber` int(11) default NULL,
1180                 `constrainttype` varchar(1) default NULL,
1181                 `branchcode` varchar(10) default NULL,
1182                 `notificationdate` date default NULL,
1183                 `reminderdate` date default NULL,
1184                 `cancellationdate` date default NULL,
1185                 `reservenotes` mediumtext,
1186                 `priority` smallint(6) default NULL,
1187                 `found` varchar(1) default NULL,
1188                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1189                 `itemnumber` int(11) default NULL,
1190                 `waitingdate` date default NULL,
1191                 KEY `old_reserves_borrowernumber` (`borrowernumber`),
1192                 KEY `old_reserves_biblionumber` (`biblionumber`),
1193                 KEY `old_reserves_itemnumber` (`itemnumber`),
1194                 KEY `old_reserves_branchcode` (`branchcode`),
1195                 CONSTRAINT `old_reserves_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1196                     ON DELETE SET NULL ON UPDATE SET NULL,
1197                 CONSTRAINT `old_reserves_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`)
1198                     ON DELETE SET NULL ON UPDATE SET NULL,
1199                 CONSTRAINT `old_reserves_ibfk_3` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`)
1200                     ON DELETE SET NULL ON UPDATE SET NULL
1201                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1202
1203     # move closed transactions to old_* tables
1204     $dbh->do("INSERT INTO old_issues SELECT * FROM issues WHERE returndate IS NOT NULL");
1205     $dbh->do("DELETE FROM issues WHERE returndate IS NOT NULL");
1206     $dbh->do("INSERT INTO old_reserves SELECT * FROM reserves WHERE cancellationdate IS NOT NULL OR found = 'F'");
1207     $dbh->do("DELETE FROM reserves WHERE cancellationdate IS NOT NULL OR found = 'F'");
1208
1209         print "Upgrade to $DBversion done ( Added old_issues and old_reserves tables )\n";
1210     SetVersion ($DBversion);
1211 }
1212
1213 $DBversion = "3.00.00.063";
1214 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1215     $dbh->do("ALTER TABLE deleteditems
1216                 CHANGE COLUMN booksellerid booksellerid MEDIUMTEXT DEFAULT NULL,
1217                 ADD COLUMN enumchron VARCHAR(80) DEFAULT NULL AFTER more_subfields_xml,
1218                 ADD COLUMN copynumber SMALLINT(6) DEFAULT NULL AFTER enumchron;");
1219     $dbh->do("ALTER TABLE items
1220                 CHANGE COLUMN booksellerid booksellerid MEDIUMTEXT,
1221                 ADD COLUMN copynumber SMALLINT(6) DEFAULT NULL AFTER enumchron;");
1222         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";
1223     SetVersion ($DBversion);
1224 }
1225
1226 $DBversion = "3.00.00.064";
1227 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1228     $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');");
1229     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AWSAccessKeyID','','See:  http://aws.amazon.com','','free');");
1230     $dbh->do("DELETE FROM `systempreferences` WHERE variable='AmazonDevKey';");
1231     $dbh->do("DELETE FROM `systempreferences` WHERE variable='XISBNAmazonSimilarItems';");
1232     $dbh->do("DELETE FROM `systempreferences` WHERE variable='OPACXISBNAmazonSimilarItems';");
1233     print "Upgrade to $DBversion done (IMPORTANT: Upgrading to Amazon.com Associates Web Service 4.0 ) \n";
1234     SetVersion ($DBversion);
1235 }
1236
1237 $DBversion = "3.00.00.065";
1238 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1239     $dbh->do("CREATE TABLE `patroncards` (
1240                 `cardid` int(11) NOT NULL auto_increment,
1241                 `batch_id` varchar(10) NOT NULL default '1',
1242                 `borrowernumber` int(11) NOT NULL,
1243                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1244                 PRIMARY KEY  (`cardid`),
1245                 KEY `patroncards_ibfk_1` (`borrowernumber`),
1246                 CONSTRAINT `patroncards_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE
1247                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1248     print "Upgrade to $DBversion done (Adding patroncards table for patroncards generation feature. ) \n";
1249     SetVersion ($DBversion);
1250 }
1251
1252 $DBversion = "3.00.00.066";
1253 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1254     $dbh->do("ALTER TABLE `virtualshelfcontents` MODIFY `dateadded` timestamp NOT NULL
1255 DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP;
1256 ");
1257     print "Upgrade to $DBversion done (fix for bug 1873: virtualshelfcontents dateadded column empty. ) \n";
1258     SetVersion ($DBversion);
1259 }
1260
1261 $DBversion = "3.00.00.067";
1262 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1263     $dbh->do("UPDATE systempreferences SET explanation = 'Enable patron images for the Staff Client', type = 'YesNo' WHERE variable = 'patronimages'");
1264     print "Upgrade to $DBversion done (Updating patronimages syspref to reflect current kohastructure.sql. ) \n";
1265     SetVersion ($DBversion);
1266 }
1267
1268 $DBversion = "3.00.00.068";
1269 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1270     $dbh->do("CREATE TABLE `permissions` (
1271                 `module_bit` int(11) NOT NULL DEFAULT 0,
1272                 `code` varchar(30) DEFAULT NULL,
1273                 `description` varchar(255) DEFAULT NULL,
1274                 PRIMARY KEY  (`module_bit`, `code`),
1275                 CONSTRAINT `permissions_ibfk_1` FOREIGN KEY (`module_bit`) REFERENCES `userflags` (`bit`)
1276                     ON DELETE CASCADE ON UPDATE CASCADE
1277               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1278     $dbh->do("CREATE TABLE `user_permissions` (
1279                 `borrowernumber` int(11) NOT NULL DEFAULT 0,
1280                 `module_bit` int(11) NOT NULL DEFAULT 0,
1281                 `code` varchar(30) DEFAULT NULL,
1282                 CONSTRAINT `user_permissions_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1283                     ON DELETE CASCADE ON UPDATE CASCADE,
1284                 CONSTRAINT `user_permissions_ibfk_2` FOREIGN KEY (`module_bit`, `code`)
1285                     REFERENCES `permissions` (`module_bit`, `code`)
1286                     ON DELETE CASCADE ON UPDATE CASCADE
1287               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1288
1289     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
1290     (13, 'edit_news', 'Write news for the OPAC and staff interfaces'),
1291     (13, 'label_creator', 'Create printable labels and barcodes from catalog and patron data'),
1292     (13, 'edit_calendar', 'Define days when the library is closed'),
1293     (13, 'moderate_comments', 'Moderate patron comments'),
1294     (13, 'edit_notices', 'Define notices'),
1295     (13, 'edit_notice_status_triggers', 'Set notice/status triggers for overdue items'),
1296     (13, 'view_system_logs', 'Browse the system logs'),
1297     (13, 'inventory', 'Perform inventory (stocktaking) of your catalogue'),
1298     (13, 'stage_marc_import', 'Stage MARC records into the reservoir'),
1299     (13, 'manage_staged_marc', 'Managed staged MARC records, including completing and reversing imports'),
1300     (13, 'export_catalog', 'Export bibliographic and holdings data'),
1301     (13, 'import_patrons', 'Import patron data'),
1302     (13, 'delete_anonymize_patrons', 'Delete old borrowers and anonymize circulation history (deletes borrower reading history)'),
1303     (13, 'batch_upload_patron_images', 'Upload patron images in batch or one at a time'),
1304     (13, 'schedule_tasks', 'Schedule tasks to run')");
1305
1306     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('GranularPermissions','0','Use detailed staff user permissions',NULL,'YesNo')");
1307
1308     print "Upgrade to $DBversion done (adding permissions and user_permissions tables and GranularPermissions syspref) \n";
1309     SetVersion ($DBversion);
1310 }
1311 $DBversion = "3.00.00.069";
1312 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1313     $dbh->do("ALTER TABLE labels_conf CHANGE COLUMN class classification int(1) DEFAULT NULL;");
1314         print "Upgrade to $DBversion done ( Correcting columname in labels_conf )\n";
1315     SetVersion ($DBversion);
1316 }
1317
1318 $DBversion = "3.00.00.070";
1319 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1320     $sth = $dbh->prepare("SELECT value FROM systempreferences WHERE variable='yuipath'");
1321     $sth->execute;
1322     my ($value) = $sth->fetchrow;
1323     $value =~ s/2.3.1/2.5.1/;
1324     $dbh->do("UPDATE systempreferences SET value='$value' WHERE variable='yuipath';");
1325         print "Update yuipath syspref to 2.5.1 if necessary\n";
1326     SetVersion ($DBversion);
1327 }
1328
1329 $DBversion = "3.00.00.071";
1330 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1331     $dbh->do(" ALTER TABLE `subscription` ADD `serialsadditems` TINYINT( 1 ) NOT NULL DEFAULT '0';");
1332     # fill the new field with the previous systempreference value, then drop the syspref
1333     my $sth = $dbh->prepare("SELECT value FROM systempreferences WHERE variable='serialsadditems'");
1334     $sth->execute;
1335     my ($serialsadditems) = $sth->fetchrow();
1336     $dbh->do("UPDATE subscription SET serialsadditems=$serialsadditems");
1337     $dbh->do("DELETE FROM systempreferences WHERE variable='serialsadditems'");
1338     print "Upgrade to $DBversion done ( moving serialsadditems from syspref to subscription )\n";
1339     SetVersion ($DBversion);
1340 }
1341
1342 $DBversion = "3.00.00.072";
1343 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1344     $dbh->do("ALTER TABLE labels_conf ADD COLUMN formatstring mediumtext DEFAULT NULL AFTER printingtype");
1345         print "Upgrade to $DBversion done ( Adding format string to labels generator. )\n";
1346     SetVersion ($DBversion);
1347 }
1348
1349 $DBversion = "3.00.00.073";
1350 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1351         $dbh->do("DROP TABLE IF EXISTS `tags_all`;");
1352         $dbh->do(q#
1353         CREATE TABLE `tags_all` (
1354           `tag_id`         int(11) NOT NULL auto_increment,
1355           `borrowernumber` int(11) NOT NULL,
1356           `biblionumber`   int(11) NOT NULL,
1357           `term`      varchar(255) NOT NULL,
1358           `language`       int(4) default NULL,
1359           `date_created` datetime  NOT NULL,
1360           PRIMARY KEY  (`tag_id`),
1361           KEY `tags_borrowers_fk_1` (`borrowernumber`),
1362           KEY `tags_biblionumber_fk_1` (`biblionumber`),
1363           CONSTRAINT `tags_borrowers_fk_1` FOREIGN KEY (`borrowernumber`)
1364                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1365           CONSTRAINT `tags_biblionumber_fk_1` FOREIGN KEY (`biblionumber`)
1366                 REFERENCES `biblio`     (`biblionumber`)  ON DELETE CASCADE ON UPDATE CASCADE
1367         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1368         #);
1369         $dbh->do("DROP TABLE IF EXISTS `tags_approval`;");
1370         $dbh->do(q#
1371         CREATE TABLE `tags_approval` (
1372           `term`   varchar(255) NOT NULL,
1373           `approved`     int(1) NOT NULL default '0',
1374           `date_approved` datetime       default NULL,
1375           `approved_by` int(11)          default NULL,
1376           `weight_total` int(9) NOT NULL default '1',
1377           PRIMARY KEY  (`term`),
1378           KEY `tags_approval_borrowers_fk_1` (`approved_by`),
1379           CONSTRAINT `tags_approval_borrowers_fk_1` FOREIGN KEY (`approved_by`)
1380                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE
1381         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1382         #);
1383         $dbh->do("DROP TABLE IF EXISTS `tags_index`;");
1384         $dbh->do(q#
1385         CREATE TABLE `tags_index` (
1386           `term`    varchar(255) NOT NULL,
1387           `biblionumber` int(11) NOT NULL,
1388           `weight`        int(9) NOT NULL default '1',
1389           PRIMARY KEY  (`term`,`biblionumber`),
1390           KEY `tags_index_biblionumber_fk_1` (`biblionumber`),
1391           CONSTRAINT `tags_index_term_fk_1` FOREIGN KEY (`term`)
1392                 REFERENCES `tags_approval` (`term`)  ON DELETE CASCADE ON UPDATE CASCADE,
1393           CONSTRAINT `tags_index_biblionumber_fk_1` FOREIGN KEY (`biblionumber`)
1394                 REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
1395         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1396         #);
1397         $dbh->do(q#
1398         INSERT INTO `systempreferences` VALUES
1399                 ('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=',''),
1400                 ('BakerTaylorEnabled','0','','Enable or disable all Baker & Taylor features.','YesNo'),
1401                 ('BakerTaylorPassword','','','Baker & Taylor Password for Content Cafe (external content)','Textarea'),
1402                 ('BakerTaylorUsername','','','Baker & Taylor Username for Content Cafe (external content)','Textarea'),
1403                 ('TagsEnabled','1','','Enables or disables all tagging features.  This is the main switch for tags.','YesNo'),
1404                 ('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.',''),
1405                 ('TagsInputOnDetail','1','','Allow users to input tags from the detail page.',         'YesNo'),
1406                 ('TagsInputOnList',  '0','','Allow users to input tags from the search results list.', 'YesNo'),
1407                 ('TagsModeration',  NULL,'','Require tags from patrons to be approved before becoming visible.','YesNo'),
1408                 ('TagsShowOnDetail','10','','Number of tags to display on detail page.  0 is off.',        'Integer'),
1409                 ('TagsShowOnList',   '6','','Number of tags to display on search results list.  0 is off.','Integer')
1410         #);
1411         print "Upgrade to $DBversion done (Baker/Taylor,Tags: sysprefs and tables (tags_all, tags_index, tags_approval)) \n";
1412         SetVersion ($DBversion);
1413 }
1414
1415 $DBversion = "3.00.00.074";
1416 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1417     $dbh->do( q(update itemtypes set imageurl = concat( 'npl/', imageurl )
1418                   where imageurl not like 'http%'
1419                     and imageurl is not NULL
1420                     and imageurl != '') );
1421     print "Upgrade to $DBversion done (updating imagetype.imageurls to reflect new icon locations.)\n";
1422     SetVersion ($DBversion);
1423 }
1424
1425 $DBversion = "3.00.00.075";
1426 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1427     $dbh->do( q(alter table authorised_values add imageurl varchar(200) default NULL) );
1428     print "Upgrade to $DBversion done (adding imageurl field to authorised_values table)\n";
1429     SetVersion ($DBversion);
1430 }
1431
1432 $DBversion = "3.00.00.076";
1433 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1434     $dbh->do("ALTER TABLE import_batches
1435               ADD COLUMN nomatch_action enum('create_new', 'ignore') NOT NULL default 'create_new' AFTER overlay_action");
1436     $dbh->do("ALTER TABLE import_batches
1437               ADD COLUMN item_action enum('always_add', 'add_only_for_matches', 'add_only_for_new', 'ignore')
1438                   NOT NULL default 'always_add' AFTER nomatch_action");
1439     $dbh->do("ALTER TABLE import_batches
1440               MODIFY overlay_action  enum('replace', 'create_new', 'use_template', 'ignore')
1441                   NOT NULL default 'create_new'");
1442     $dbh->do("ALTER TABLE import_records
1443               MODIFY status  enum('error', 'staged', 'imported', 'reverted', 'items_reverted',
1444                                   'ignored') NOT NULL default 'staged'");
1445     $dbh->do("ALTER TABLE import_items
1446               MODIFY status enum('error', 'staged', 'imported', 'reverted', 'ignored') NOT NULL default 'staged'");
1447
1448         print "Upgrade to $DBversion done (changes to import_batches and import_records)\n";
1449         SetVersion ($DBversion);
1450 }
1451
1452 $DBversion = "3.00.00.077";
1453 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1454     # drop these tables only if they exist and none of them are empty
1455     # these tables are not defined in the packaged 2.2.9, but since it is believed
1456     # that at least one library may be using them in a post-2.2.9 but pre-3.0 Koha,
1457     # some care is taken.
1458     my ($print_error) = $dbh->{PrintError};
1459     $dbh->{PrintError} = 0;
1460     my ($raise_error) = $dbh->{RaiseError};
1461     $dbh->{RaiseError} = 1;
1462
1463     my $count = 0;
1464     my $do_drop = 1;
1465     eval { $count = $dbh->do("SELECT 1 FROM categorytable"); };
1466     if ($count > 0) {
1467         $do_drop = 0;
1468     }
1469     eval { $count = $dbh->do("SELECT 1 FROM mediatypetable"); };
1470     if ($count > 0) {
1471         $do_drop = 0;
1472     }
1473     eval { $count = $dbh->do("SELECT 1 FROM subcategorytable"); };
1474     if ($count > 0) {
1475         $do_drop = 0;
1476     }
1477
1478     if ($do_drop) {
1479         $dbh->do("DROP TABLE IF EXISTS `categorytable`");
1480         $dbh->do("DROP TABLE IF EXISTS `mediatypetable`");
1481         $dbh->do("DROP TABLE IF EXISTS `subcategorytable`");
1482     }
1483
1484     $dbh->{PrintError} = $print_error;
1485     $dbh->{RaiseError} = $raise_error;
1486         print "Upgrade to $DBversion done (drop categorytable, subcategorytable, and mediatypetable)\n";
1487         SetVersion ($DBversion);
1488 }
1489
1490 $DBversion = "3.00.00.078";
1491 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1492     my ($print_error) = $dbh->{PrintError};
1493     $dbh->{PrintError} = 0;
1494
1495     unless ($dbh->do("SELECT 1 FROM browser")) {
1496         $dbh->{PrintError} = $print_error;
1497         $dbh->do("CREATE TABLE `browser` (
1498                     `level` int(11) NOT NULL,
1499                     `classification` varchar(20) NOT NULL,
1500                     `description` varchar(255) NOT NULL,
1501                     `number` bigint(20) NOT NULL,
1502                     `endnode` tinyint(4) NOT NULL
1503                   ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1504     }
1505     $dbh->{PrintError} = $print_error;
1506         print "Upgrade to $DBversion done (add browser table if not already present)\n";
1507         SetVersion ($DBversion);
1508 }
1509
1510 $DBversion = "3.00.00.079";
1511 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1512  my ($print_error) = $dbh->{PrintError};
1513     $dbh->{PrintError} = 0;
1514
1515     $dbh->do("INSERT INTO `systempreferences` (variable, value,options,type, explanation)VALUES
1516         ('AddPatronLists','categorycode','categorycode|category_type','Choice','Allow user to choose what list to pick up from when adding patrons')");
1517     print "Upgrade to $DBversion done (add browser table if not already present)\n";
1518         SetVersion ($DBversion);
1519 }
1520
1521 $DBversion = "3.00.00.080";
1522 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1523     $dbh->do("ALTER TABLE subscription CHANGE monthlength monthlength int(11) default '0'");
1524     $dbh->do("ALTER TABLE deleteditems MODIFY marc LONGBLOB AFTER copynumber");
1525     $dbh->do("ALTER TABLE aqbooksellers CHANGE name name mediumtext NOT NULL");
1526         print "Upgrade to $DBversion done (catch up on DB schema changes since alpha and beta)\n";
1527         SetVersion ($DBversion);
1528 }
1529
1530 $DBversion = "3.00.00.081";
1531 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1532     $dbh->do("CREATE TABLE `borrower_attribute_types` (
1533                 `code` varchar(10) NOT NULL,
1534                 `description` varchar(255) NOT NULL,
1535                 `repeatable` tinyint(1) NOT NULL default 0,
1536                 `unique_id` tinyint(1) NOT NULL default 0,
1537                 `opac_display` tinyint(1) NOT NULL default 0,
1538                 `password_allowed` tinyint(1) NOT NULL default 0,
1539                 `staff_searchable` tinyint(1) NOT NULL default 0,
1540                 `authorised_value_category` varchar(10) default NULL,
1541                 PRIMARY KEY  (`code`)
1542               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1543     $dbh->do("CREATE TABLE `borrower_attributes` (
1544                 `borrowernumber` int(11) NOT NULL,
1545                 `code` varchar(10) NOT NULL,
1546                 `attribute` varchar(30) default NULL,
1547                 `password` varchar(30) default NULL,
1548                 KEY `borrowernumber` (`borrowernumber`),
1549                 KEY `code_attribute` (`code`, `attribute`),
1550                 CONSTRAINT `borrower_attributes_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1551                     ON DELETE CASCADE ON UPDATE CASCADE,
1552                 CONSTRAINT `borrower_attributes_ibfk_2` FOREIGN KEY (`code`) REFERENCES `borrower_attribute_types` (`code`)
1553                     ON DELETE CASCADE ON UPDATE CASCADE
1554             ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1555     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('ExtendedPatronAttributes','0','Use extended patron IDs and attributes',NULL,'YesNo')");
1556     print "Upgrade to $DBversion done (added borrower_attributes and  borrower_attribute_types)\n";
1557  SetVersion ($DBversion);
1558 }
1559
1560 $DBversion = "3.00.00.082";
1561 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1562     $dbh->do( q(alter table accountlines add column lastincrement decimal(28,6) default NULL) );
1563     print "Upgrade to $DBversion done (adding lastincrement column to accountlines table)\n";
1564     SetVersion ($DBversion);
1565 }
1566
1567 $DBversion = "3.00.00.083";
1568 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1569     $dbh->do( qq(UPDATE systempreferences SET value='local' where variable='yuipath' and value like "%/intranet-tmpl/prog/%"));
1570     print "Upgrade to $DBversion done (Changing yuipath behaviour in managing a local value)\n";
1571     SetVersion ($DBversion);
1572 }
1573 $DBversion = "3.00.00.084";
1574     if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1575     $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')");
1576     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('GoogleJackets','0','if ON, displays jacket covers from Google Books API',NULL,'YesNo')");
1577     print "Upgrade to $DBversion done (add new sysprefs)\n";
1578     SetVersion ($DBversion);
1579 }
1580
1581 $DBversion = "3.00.00.085";
1582 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1583     if (C4::Context->preference("marcflavour") eq 'MARC21') {
1584         $dbh->do("UPDATE marc_subfield_structure SET tab = 0 WHERE tab =  9 AND tagfield = '037'");
1585         $dbh->do("UPDATE marc_subfield_structure SET tab = 1 WHERE tab =  6 AND tagfield in ('100', '110', '111', '130')");
1586         $dbh->do("UPDATE marc_subfield_structure SET tab = 2 WHERE tab =  6 AND tagfield in ('240', '243')");
1587         $dbh->do("UPDATE marc_subfield_structure SET tab = 4 WHERE tab =  6 AND tagfield in ('400', '410', '411', '440')");
1588         $dbh->do("UPDATE marc_subfield_structure SET tab = 5 WHERE tab =  9 AND tagfield = '584'");
1589         $dbh->do("UPDATE marc_subfield_structure SET tab = 7 WHERE tab = -6 AND tagfield = '760'");
1590     }
1591     print "Upgrade to $DBversion done (move editing tab of various MARC21 subfields)\n";
1592     SetVersion ($DBversion);
1593 }
1594
1595 $DBversion = "3.00.00.086";
1596 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1597         $dbh->do(
1598         "CREATE TABLE `tmp_holdsqueue` (
1599         `biblionumber` int(11) default NULL,
1600         `itemnumber` int(11) default NULL,
1601         `barcode` varchar(20) default NULL,
1602         `surname` mediumtext NOT NULL,
1603         `firstname` text,
1604         `phone` text,
1605         `borrowernumber` int(11) NOT NULL,
1606         `cardnumber` varchar(16) default NULL,
1607         `reservedate` date default NULL,
1608         `title` mediumtext,
1609         `itemcallnumber` varchar(30) default NULL,
1610         `holdingbranch` varchar(10) default NULL,
1611         `pickbranch` varchar(10) default NULL,
1612         `notes` text
1613         ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1614
1615         $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')");
1616         $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')");
1617
1618         print "Upgrade to $DBversion done (Table structure for table `tmp_holdsqueue`)\n";
1619         SetVersion ($DBversion);
1620 }
1621
1622 $DBversion = "3.00.00.087";
1623 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1624     $dbh->do("INSERT INTO `systempreferences` VALUES ('AutoEmailOpacUser','0','','Sends notification emails containing new account details to patrons - when account is created.','YesNo')" );
1625     $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')");
1626     print "Upgrade to $DBversion done (added 2 new 'AutoEmailOpacUser' sysprefs)\n";
1627     SetVersion ($DBversion);
1628 }
1629
1630 $DBversion = "3.00.00.088";
1631 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1632         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('OPACShelfBrowser','1','','Enable/disable Shelf Browser on item details page','YesNo')");
1633         $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')");
1634         $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')");
1635         $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')");
1636         print "Upgrade to $DBversion done (added 2 new 'AutoEmailOpacUser' sysprefs)\n";
1637     SetVersion ($DBversion);
1638 }
1639
1640 $DBversion = "3.00.00.089";
1641 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1642         $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')");
1643         print "Upgrade to $DBversion done (added new AdvancedSearchTypes syspref)\n";
1644     SetVersion ($DBversion);
1645 }
1646
1647 $DBversion = "3.00.00.090";
1648 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1649     $dbh->do("
1650         CREATE TABLE `branch_borrower_circ_rules` (
1651           `branchcode` VARCHAR(10) NOT NULL,
1652           `categorycode` VARCHAR(10) NOT NULL,
1653           `maxissueqty` int(4) default NULL,
1654           PRIMARY KEY (`categorycode`, `branchcode`),
1655           CONSTRAINT `branch_borrower_circ_rules_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
1656             ON DELETE CASCADE ON UPDATE CASCADE,
1657           CONSTRAINT `branch_borrower_circ_rules_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`)
1658             ON DELETE CASCADE ON UPDATE CASCADE
1659         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1660     ");
1661     $dbh->do("
1662         CREATE TABLE `default_borrower_circ_rules` (
1663           `categorycode` VARCHAR(10) NOT NULL,
1664           `maxissueqty` int(4) default NULL,
1665           PRIMARY KEY (`categorycode`),
1666           CONSTRAINT `borrower_borrower_circ_rules_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
1667             ON DELETE CASCADE ON UPDATE CASCADE
1668         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1669     ");
1670     $dbh->do("
1671         CREATE TABLE `default_branch_circ_rules` (
1672           `branchcode` VARCHAR(10) NOT NULL,
1673           `maxissueqty` int(4) default NULL,
1674           PRIMARY KEY (`branchcode`),
1675           CONSTRAINT `default_branch_circ_rules_ibfk_1` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`)
1676             ON DELETE CASCADE ON UPDATE CASCADE
1677         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1678     ");
1679     $dbh->do("
1680         CREATE TABLE `default_circ_rules` (
1681             `singleton` enum('singleton') NOT NULL default 'singleton',
1682             `maxissueqty` int(4) default NULL,
1683             PRIMARY KEY (`singleton`)
1684         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1685     ");
1686     print "Upgrade to $DBversion done (added several circ rules tables)\n";
1687     SetVersion ($DBversion);
1688 }
1689
1690
1691 $DBversion = "3.00.00.091";
1692 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1693     $dbh->do(<<'END_SQL');
1694 ALTER TABLE borrowers
1695 ADD `smsalertnumber` varchar(50) default NULL
1696 END_SQL
1697
1698     $dbh->do(<<'END_SQL');
1699 CREATE TABLE `message_attributes` (
1700   `message_attribute_id` int(11) NOT NULL auto_increment,
1701   `message_name` varchar(20) NOT NULL default '',
1702   `takes_days` tinyint(1) NOT NULL default '0',
1703   PRIMARY KEY  (`message_attribute_id`),
1704   UNIQUE KEY `message_name` (`message_name`)
1705 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1706 END_SQL
1707
1708     $dbh->do(<<'END_SQL');
1709 CREATE TABLE `message_transport_types` (
1710   `message_transport_type` varchar(20) NOT NULL,
1711   PRIMARY KEY  (`message_transport_type`)
1712 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1713 END_SQL
1714
1715     $dbh->do(<<'END_SQL');
1716 CREATE TABLE `message_transports` (
1717   `message_attribute_id` int(11) NOT NULL,
1718   `message_transport_type` varchar(20) NOT NULL,
1719   `is_digest` tinyint(1) NOT NULL default '0',
1720   `letter_module` varchar(20) NOT NULL default '',
1721   `letter_code` varchar(20) NOT NULL default '',
1722   PRIMARY KEY  (`message_attribute_id`,`message_transport_type`,`is_digest`),
1723   KEY `message_transport_type` (`message_transport_type`),
1724   KEY `letter_module` (`letter_module`,`letter_code`),
1725   CONSTRAINT `message_transports_ibfk_1` FOREIGN KEY (`message_attribute_id`) REFERENCES `message_attributes` (`message_attribute_id`) ON DELETE CASCADE ON UPDATE CASCADE,
1726   CONSTRAINT `message_transports_ibfk_2` FOREIGN KEY (`message_transport_type`) REFERENCES `message_transport_types` (`message_transport_type`) ON DELETE CASCADE ON UPDATE CASCADE,
1727   CONSTRAINT `message_transports_ibfk_3` FOREIGN KEY (`letter_module`, `letter_code`) REFERENCES `letter` (`module`, `code`) ON DELETE CASCADE ON UPDATE CASCADE
1728 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1729 END_SQL
1730
1731     $dbh->do(<<'END_SQL');
1732 CREATE TABLE `borrower_message_preferences` (
1733   `borrower_message_preference_id` int(11) NOT NULL auto_increment,
1734   `borrowernumber` int(11) NOT NULL default '0',
1735   `message_attribute_id` int(11) default '0',
1736   `days_in_advance` int(11) default '0',
1737   `wants_digets` tinyint(1) NOT NULL default '0',
1738   PRIMARY KEY  (`borrower_message_preference_id`),
1739   KEY `borrowernumber` (`borrowernumber`),
1740   KEY `message_attribute_id` (`message_attribute_id`),
1741   CONSTRAINT `borrower_message_preferences_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1742   CONSTRAINT `borrower_message_preferences_ibfk_2` FOREIGN KEY (`message_attribute_id`) REFERENCES `message_attributes` (`message_attribute_id`) ON DELETE CASCADE ON UPDATE CASCADE
1743 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1744 END_SQL
1745
1746     $dbh->do(<<'END_SQL');
1747 CREATE TABLE `borrower_message_transport_preferences` (
1748   `borrower_message_preference_id` int(11) NOT NULL default '0',
1749   `message_transport_type` varchar(20) NOT NULL default '0',
1750   PRIMARY KEY  (`borrower_message_preference_id`,`message_transport_type`),
1751   KEY `message_transport_type` (`message_transport_type`),
1752   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,
1753   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
1754 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1755 END_SQL
1756
1757     $dbh->do(<<'END_SQL');
1758 CREATE TABLE `message_queue` (
1759   `message_id` int(11) NOT NULL auto_increment,
1760   `borrowernumber` int(11) NOT NULL,
1761   `subject` text,
1762   `content` text,
1763   `message_transport_type` varchar(20) NOT NULL,
1764   `status` enum('sent','pending','failed','deleted') NOT NULL default 'pending',
1765   `time_queued` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1766   KEY `message_id` (`message_id`),
1767   KEY `borrowernumber` (`borrowernumber`),
1768   KEY `message_transport_type` (`message_transport_type`),
1769   CONSTRAINT `messageq_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1770   CONSTRAINT `messageq_ibfk_2` FOREIGN KEY (`message_transport_type`) REFERENCES `message_transport_types` (`message_transport_type`) ON DELETE RESTRICT ON UPDATE CASCADE
1771 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1772 END_SQL
1773
1774     $dbh->do(<<'END_SQL');
1775 INSERT INTO `systempreferences`
1776   (variable,value,explanation,options,type)
1777 VALUES
1778 ('EnhancedMessagingPreferences',0,'If ON, allows patrons to select to receive additional messages about items due or nearly due.','','YesNo')
1779 END_SQL
1780
1781     $dbh->do( <<'END_SQL');
1782 INSERT INTO `letter`
1783 (module, code, name, title, content)
1784 VALUES
1785 ('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>>'),
1786 ('circulation','DUEDGST','Item Due Reminder (Digest)','Item Due Reminder','You have <<count>> items due'),
1787 ('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>>'),
1788 ('circulation','PREDUEDGST','Advance Notice of Item Due (Digest)','Advance Notice of Item Due','You have <<count>> items due soon'),
1789 ('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.');
1790 END_SQL
1791
1792     my @sql_scripts = (
1793         'installer/data/mysql/en/mandatory/message_transport_types.sql',
1794         'installer/data/mysql/en/optional/sample_notices_message_attributes.sql',
1795         'installer/data/mysql/en/optional/sample_notices_message_transports.sql',
1796     );
1797
1798     my $installer = C4::Installer->new();
1799     foreach my $script ( @sql_scripts ) {
1800         my $full_path = $installer->get_file_path_from_name($script);
1801         my $error = $installer->load_sql($full_path);
1802         warn $error if $error;
1803     }
1804
1805     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";
1806     SetVersion ($DBversion);
1807 }
1808
1809 $DBversion = "3.00.00.092";
1810 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1811     $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')");
1812     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES('AllowHoldsOnDamagedItems', '1', '', 'Allow hold requests to be placed on damaged items', 'YesNo')");
1813         print "Upgrade to $DBversion done (added new AllowOnShelfHolds syspref)\n";
1814     SetVersion ($DBversion);
1815 }
1816
1817 $DBversion = "3.00.00.093";
1818 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1819     $dbh->do("ALTER TABLE `items` MODIFY COLUMN `copynumber` VARCHAR(32) DEFAULT NULL");
1820     $dbh->do("ALTER TABLE `deleteditems` MODIFY COLUMN `copynumber` VARCHAR(32) DEFAULT NULL");
1821         print "Upgrade to $DBversion done (Change data type of items.copynumber to allow free text)\n";
1822     SetVersion ($DBversion);
1823 }
1824
1825 $DBversion = "3.00.00.094";
1826 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1827     $dbh->do("ALTER TABLE `marc_subfield_structure` MODIFY `tagsubfield` VARCHAR(1) NOT NULL DEFAULT '' COLLATE utf8_bin");
1828         print "Upgrade to $DBversion done (Change Collation of marc_subfield_structure to allow mixed case in subfield labels.)\n";
1829     SetVersion ($DBversion);
1830 }
1831
1832 $DBversion = "3.00.00.095";
1833 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1834     if (C4::Context->preference("marcflavour") eq 'MARC21') {
1835         $dbh->do("UPDATE marc_subfield_structure SET authtypecode = 'MEETI_NAME' WHERE authtypecode = 'Meeting Name'");
1836         $dbh->do("UPDATE marc_subfield_structure SET authtypecode = 'CORPO_NAME' WHERE authtypecode = 'CORP0_NAME'");
1837     }
1838         print "Upgrade to $DBversion done (fix invalid authority types in MARC21 frameworks [bug 2254])\n";
1839     SetVersion ($DBversion);
1840 }
1841
1842 $DBversion = "3.00.00.096";
1843 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1844     $sth = $dbh->prepare("SHOW COLUMNS FROM borrower_message_preferences LIKE 'wants_digets'");
1845     $sth->execute();
1846     if (my $row = $sth->fetchrow_hashref) {
1847         $dbh->do("ALTER TABLE borrower_message_preferences CHANGE wants_digets wants_digest tinyint(1) NOT NULL default 0");
1848     }
1849         print "Upgrade to $DBversion done (fix name borrower_message_preferences.wants_digest)\n";
1850     SetVersion ($DBversion);
1851 }
1852
1853 $DBversion = '3.00.00.097';
1854 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1855
1856     $dbh->do('ALTER TABLE message_queue ADD to_address   mediumtext default NULL');
1857     $dbh->do('ALTER TABLE message_queue ADD from_address mediumtext default NULL');
1858     $dbh->do('ALTER TABLE message_queue ADD content_type text');
1859     $dbh->do('ALTER TABLE message_queue CHANGE borrowernumber borrowernumber int(11) default NULL');
1860
1861     print "Upgrade to $DBversion done (updating 4 fields in message_queue table)\n";
1862     SetVersion($DBversion);
1863 }
1864
1865 $DBversion = '3.00.00.098';
1866 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1867
1868     $dbh->do(q(DELETE FROM message_transport_types WHERE message_transport_type = 'rss'));
1869     $dbh->do(q(DELETE FROM message_transports WHERE message_transport_type = 'rss'));
1870
1871     print "Upgrade to $DBversion done (removing unused RSS message_transport_type)\n";
1872     SetVersion($DBversion);
1873 }
1874
1875 $DBversion = '3.00.00.099';
1876 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1877     $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')");
1878     print "Upgrade to $DBversion done (Adding OpacSuppression syspref)\n";
1879     SetVersion($DBversion);
1880 }
1881
1882 $DBversion = '3.00.00.100';
1883 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1884         $dbh->do('ALTER TABLE virtualshelves ADD COLUMN lastmodified timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP');
1885     print "Upgrade to $DBversion done (Adding lastmodified column to virtualshelves)\n";
1886     SetVersion($DBversion);
1887 }
1888
1889 $DBversion = '3.00.00.101';
1890 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1891         $dbh->do('ALTER TABLE `overduerules` CHANGE `categorycode` `categorycode` VARCHAR(10) NOT NULL');
1892         $dbh->do('ALTER TABLE `deletedborrowers` CHANGE `categorycode` `categorycode` VARCHAR(10) NOT NULL');
1893     print "Upgrade to $DBversion done (Updating columnd definitions for patron category codes in notice/statsu triggers and deletedborrowers tables.)\n";
1894     SetVersion($DBversion);
1895 }
1896
1897 $DBversion = '3.00.00.102';
1898 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1899         $dbh->do('ALTER TABLE serialitems MODIFY `serialid` int(11) NOT NULL AFTER itemnumber' );
1900         $dbh->do('ALTER TABLE serialitems DROP KEY serialididx' );
1901         $dbh->do('ALTER TABLE serialitems ADD CONSTRAINT UNIQUE KEY serialitemsidx (itemnumber)' );
1902         # before setting constraint, delete any unvalid data
1903         $dbh->do('DELETE from serialitems WHERE serialid not in (SELECT serial.serialid FROM serial)');
1904         $dbh->do('ALTER TABLE serialitems ADD CONSTRAINT serialitems_sfk_1 FOREIGN KEY (serialid) REFERENCES serial (serialid) ON DELETE CASCADE ON UPDATE CASCADE' );
1905     print "Upgrade to $DBversion done (Updating serialitems table to allow for multiple items per serial fixing kohabug 2380)\n";
1906     SetVersion($DBversion);
1907 }
1908
1909 $DBversion = "3.00.00.103";
1910 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1911     $dbh->do("DELETE FROM systempreferences WHERE variable='serialsadditems'");
1912     print "Upgrade to $DBversion done ( Verifying the removal of serialsadditems from syspref fixing kohabug 2219)\n";
1913     SetVersion ($DBversion);
1914 }
1915
1916 $DBversion = "3.00.00.104";
1917 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1918     $dbh->do("DELETE FROM systempreferences WHERE variable='noOPACHolds'");
1919     print "Upgrade to $DBversion done (remove superseded 'noOPACHolds' system preference per bug 2413)\n";
1920     SetVersion ($DBversion);
1921 }
1922
1923 $DBversion = '3.00.00.105';
1924 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
1925
1926     # it is possible that this syspref is already defined since the feature was added some time ago.
1927     unless ( $dbh->do(q(SELECT variable FROM systempreferences WHERE variable = 'SMSSendDriver')) ) {
1928         $dbh->do(<<'END_SQL');
1929 INSERT INTO `systempreferences`
1930   (variable,value,explanation,options,type)
1931 VALUES
1932 ('SMSSendDriver','','Sets which SMS::Send driver is used to send SMS messages.','','free')
1933 END_SQL
1934     }
1935     print "Upgrade to $DBversion done (added SMSSendDriver system preference)\n";
1936     SetVersion($DBversion);
1937 }
1938
1939 $DBversion = "3.00.00.106";
1940 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1941     $dbh->do("DELETE FROM systempreferences WHERE variable='noOPACHolds'");
1942
1943 # db revision 105 didn't apply correctly, so we're rolling this into 106
1944         $dbh->do("INSERT INTO `systempreferences`
1945    (variable,value,explanation,options,type)
1946         VALUES
1947         ('SMSSendDriver','','Sets which SMS::Send driver is used to send SMS messages.','','free')");
1948
1949     print "Upgrade to $DBversion done (remove default '0000-00-00' in subscriptionhistory.enddate field)\n";
1950     $dbh->do("ALTER TABLE `subscriptionhistory` CHANGE `enddate` `enddate` DATE NULL DEFAULT NULL ");
1951     $dbh->do("UPDATE subscriptionhistory SET enddate=NULL WHERE enddate='0000-00-00'");
1952     SetVersion ($DBversion);
1953 }
1954
1955 $DBversion = '3.00.00.107';
1956 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1957     $dbh->do(<<'END_SQL');
1958 UPDATE systempreferences
1959   SET explanation = CONCAT( explanation, '. WARNING: this feature is very resource consuming on collections with large numbers of items.' )
1960   WHERE variable = 'OPACShelfBrowser'
1961     AND explanation NOT LIKE '%WARNING%'
1962 END_SQL
1963     $dbh->do(<<'END_SQL');
1964 UPDATE systempreferences
1965   SET explanation = CONCAT( explanation, '. WARNING: this feature is very resource consuming.' )
1966   WHERE variable = 'CataloguingLog'
1967     AND explanation NOT LIKE '%WARNING%'
1968 END_SQL
1969     $dbh->do(<<'END_SQL');
1970 UPDATE systempreferences
1971   SET explanation = CONCAT( explanation, '. WARNING: using NoZebra on even modest sized collections is very slow.' )
1972   WHERE variable = 'NoZebra'
1973     AND explanation NOT LIKE '%WARNING%'
1974 END_SQL
1975     print "Upgrade to $DBversion done (warning added to OPACShelfBrowser system preference)\n";
1976     SetVersion ($DBversion);
1977 }
1978
1979 $DBversion = '3.01.00.000';
1980 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1981     print "Upgrade to $DBversion done (start of 3.1)\n";
1982     SetVersion ($DBversion);
1983 }
1984
1985 $DBversion = '3.01.00.001';
1986 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1987     $dbh->do("
1988         CREATE TABLE hold_fill_targets (
1989             `borrowernumber` int(11) NOT NULL,
1990             `biblionumber` int(11) NOT NULL,
1991             `itemnumber` int(11) NOT NULL,
1992             `source_branchcode`  varchar(10) default NULL,
1993             `item_level_request` tinyint(4) NOT NULL default 0,
1994             PRIMARY KEY `itemnumber` (`itemnumber`),
1995             KEY `bib_branch` (`biblionumber`, `source_branchcode`),
1996             CONSTRAINT `hold_fill_targets_ibfk_1` FOREIGN KEY (`borrowernumber`)
1997                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1998             CONSTRAINT `hold_fill_targets_ibfk_2` FOREIGN KEY (`biblionumber`)
1999                 REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
2000             CONSTRAINT `hold_fill_targets_ibfk_3` FOREIGN KEY (`itemnumber`)
2001                 REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
2002             CONSTRAINT `hold_fill_targets_ibfk_4` FOREIGN KEY (`source_branchcode`)
2003                 REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
2004         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2005     ");
2006     $dbh->do("
2007         ALTER TABLE tmp_holdsqueue
2008             ADD item_level_request tinyint(4) NOT NULL default 0
2009     ");
2010
2011     print "Upgrade to $DBversion done (add hold_fill_targets table and a column to tmp_holdsqueue)\n";
2012     SetVersion($DBversion);
2013 }
2014
2015 $DBversion = '3.01.00.002';
2016 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2017     # use statistics where available
2018     $dbh->do("
2019         ALTER TABLE statistics ADD KEY  tmp_stats (type, itemnumber, borrowernumber)
2020     ");
2021     $dbh->do("
2022         UPDATE issues iss
2023         SET issuedate = (
2024             SELECT max(datetime)
2025             FROM statistics
2026             WHERE type = 'issue'
2027             AND itemnumber = iss.itemnumber
2028             AND borrowernumber = iss.borrowernumber
2029         )
2030         WHERE issuedate IS NULL;
2031     ");
2032     $dbh->do("ALTER TABLE statistics DROP KEY tmp_stats");
2033
2034     # default to last renewal date
2035     $dbh->do("
2036         UPDATE issues
2037         SET issuedate = lastreneweddate
2038         WHERE issuedate IS NULL
2039         and lastreneweddate IS NOT NULL
2040     ");
2041
2042     my $num_bad_issuedates = $dbh->selectrow_array("SELECT COUNT(*) FROM issues WHERE issuedate IS NULL");
2043     if ($num_bad_issuedates > 0) {
2044         print STDERR "After the upgrade to $DBversion, there are still $num_bad_issuedates loan(s) with a NULL (blank) loan date. ",
2045                      "Please check the issues table in your database.";
2046     }
2047     print "Upgrade to $DBversion done (bug 2582: set null issues.issuedate to lastreneweddate)\n";
2048     SetVersion($DBversion);
2049 }
2050
2051 $DBversion = "3.01.00.003";
2052 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2053     $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')");
2054     print "Upgrade to $DBversion done (add new syspref)\n";
2055     SetVersion ($DBversion);
2056 }
2057
2058 $DBversion = '3.01.00.004';
2059 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2060     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACDisplayRequestPriority','0','Show patrons the priority level on holds in the OPAC','','YesNo')");
2061     print "Upgrade to $DBversion done (added OPACDisplayRequestPriority system preference)\n";
2062     SetVersion ($DBversion);
2063 }
2064
2065 $DBversion = '3.01.00.005';
2066 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2067     $dbh->do("
2068         INSERT INTO `letter` (module, code, name, title, content)
2069         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>>')
2070     ");
2071     $dbh->do("INSERT INTO `message_attributes` (message_attribute_id, message_name, takes_days) values(4, 'Hold Filled', 0)");
2072     $dbh->do("INSERT INTO `message_transports` (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) values(4, 'sms', 0, 'reserves', 'HOLD')");
2073     $dbh->do("INSERT INTO `message_transports` (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) values(4, 'email', 0, 'reserves', 'HOLD')");
2074     print "Upgrade to $DBversion done (Add letter for holds notifications)\n";
2075     SetVersion ($DBversion);
2076 }
2077
2078 $DBversion = '3.01.00.006';
2079 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2080     $dbh->do("ALTER TABLE `biblioitems` ADD KEY issn (issn)");
2081     print "Upgrade to $DBversion done (add index on biblioitems.issn)\n";
2082     SetVersion ($DBversion);
2083 }
2084
2085 $DBversion = "3.01.00.007";
2086 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2087     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='intranetmainUserblock'");
2088     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='intranetuserjs'");
2089     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='opacheader'");
2090     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='OpacMainUserBlock'");
2091     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='OpacNav'");
2092     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='opacuserjs'");
2093     $dbh->do("UPDATE `systempreferences` SET options='30|10', type='Textarea' WHERE variable='OAI-PMH:Set'");
2094     $dbh->do("UPDATE `systempreferences` SET options='50' WHERE variable='intranetstylesheet'");
2095     $dbh->do("UPDATE `systempreferences` SET options='50' WHERE variable='intranetcolorstylesheet'");
2096     $dbh->do("UPDATE `systempreferences` SET options='10' WHERE variable='globalDueDate'");
2097     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='numSearchResults'");
2098     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='OPACnumSearchResults'");
2099     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='ReservesMaxPickupDelay'");
2100     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='TransfersMaxDaysWarning'");
2101     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='StaticHoldsQueueWeight'");
2102     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='holdCancelLength'");
2103     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='XISBNDailyLimit'");
2104     $dbh->do("UPDATE `systempreferences` SET type='Float' WHERE variable='gist'");
2105     $dbh->do("UPDATE `systempreferences` SET type='Free' WHERE variable='BakerTaylorUsername'");
2106     $dbh->do("UPDATE `systempreferences` SET type='Free' WHERE variable='BakerTaylorPassword'");
2107     $dbh->do("UPDATE `systempreferences` SET type='Textarea', options='70|10' WHERE variable='ISBD'");
2108     $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'");
2109     print "Upgrade to $DBversion done (fix display of many sysprefs)\n";
2110     SetVersion ($DBversion);
2111 }
2112
2113 $DBversion = '3.01.00.008';
2114 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2115
2116     $dbh->do("CREATE TABLE branch_transfer_limits (
2117                           limitId int(8) NOT NULL auto_increment,
2118                           toBranch varchar(4) NOT NULL,
2119                           fromBranch varchar(4) NOT NULL,
2120                           itemtype varchar(4) NOT NULL,
2121                           PRIMARY KEY  (limitId)
2122                           ) ENGINE=InnoDB DEFAULT CHARSET=utf8"
2123                         );
2124
2125     $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')");
2126
2127     print "Upgrade to $DBversion done (added branch_transfer_limits table and UseBranchTransferLimits system preference)\n";
2128     SetVersion ($DBversion);
2129 }
2130
2131 $DBversion = "3.01.00.009";
2132 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2133     $dbh->do("ALTER TABLE permissions MODIFY `code` varchar(64) DEFAULT NULL");
2134     $dbh->do("ALTER TABLE user_permissions MODIFY `code` varchar(64) DEFAULT NULL");
2135     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'circulate_remaining_permissions', 'Remaining circulation permissions')");
2136     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'override_renewals', 'Override blocked renewals')");
2137     print "Upgrade to $DBversion done (added subpermissions for circulate permission)\n";
2138 }
2139
2140 $DBversion = '3.01.00.010';
2141 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2142     $dbh->do("ALTER TABLE `borrower_attributes` MODIFY COLUMN `attribute` VARCHAR(64) DEFAULT NULL");
2143     $dbh->do("ALTER TABLE `borrower_attributes` MODIFY COLUMN `password` VARCHAR(64) DEFAULT NULL");
2144     print "Upgrade to $DBversion done (bug 2687: increase length of borrower attribute fields)\n";
2145     SetVersion ($DBversion);
2146 }
2147
2148 $DBversion = '3.01.00.011';
2149 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2150
2151     # Yes, the old value was ^M terminated.
2152     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);";
2153
2154     my $intranetuserjs = C4::Context->preference('intranetuserjs');
2155     if ($intranetuserjs  and  $intranetuserjs eq $bad_value) {
2156         my $sql = <<'END_SQL';
2157 UPDATE systempreferences
2158 SET value = ''
2159 WHERE variable = 'intranetuserjs'
2160 END_SQL
2161         $dbh->do($sql);
2162     }
2163     print "Upgrade to $DBversion done (removed bogus intranetuserjs syspref)\n";
2164     SetVersion($DBversion);
2165 }
2166
2167 $DBversion = "3.01.00.012";
2168 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2169     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowHoldPolicyOverride', '0', 'Allow staff to override hold policies when placing holds',NULL,'YesNo')");
2170     $dbh->do("
2171         CREATE TABLE `branch_item_rules` (
2172           `branchcode` varchar(10) NOT NULL,
2173           `itemtype` varchar(10) NOT NULL,
2174           `holdallowed` tinyint(1) default NULL,
2175           PRIMARY KEY  (`itemtype`,`branchcode`),
2176           KEY `branch_item_rules_ibfk_2` (`branchcode`),
2177           CONSTRAINT `branch_item_rules_ibfk_1` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE,
2178           CONSTRAINT `branch_item_rules_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
2179         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2180     ");
2181     $dbh->do("
2182         CREATE TABLE `default_branch_item_rules` (
2183           `itemtype` varchar(10) NOT NULL,
2184           `holdallowed` tinyint(1) default NULL,
2185           PRIMARY KEY  (`itemtype`),
2186           CONSTRAINT `default_branch_item_rules_ibfk_1` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE
2187         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2188     ");
2189     $dbh->do("
2190         ALTER TABLE default_branch_circ_rules
2191             ADD COLUMN holdallowed tinyint(1) NULL
2192     ");
2193     $dbh->do("
2194         ALTER TABLE default_circ_rules
2195             ADD COLUMN holdallowed tinyint(1) NULL
2196     ");
2197     print "Upgrade to $DBversion done (Add tables and system preferences for holds policies)\n";
2198     SetVersion ($DBversion);
2199 }
2200
2201 $DBversion = '3.01.00.013';
2202 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2203     $dbh->do("
2204         CREATE TABLE item_circulation_alert_preferences (
2205             id           int(11) AUTO_INCREMENT,
2206             branchcode   varchar(10) NOT NULL,
2207             categorycode varchar(10) NOT NULL,
2208             item_type    varchar(10) NOT NULL,
2209             notification varchar(16) NOT NULL,
2210             PRIMARY KEY (id),
2211             KEY (branchcode, categorycode, item_type, notification)
2212         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2213     ");
2214
2215     $dbh->do(q{ ALTER TABLE `message_queue` ADD metadata text DEFAULT NULL           AFTER content;  });
2216     $dbh->do(q{ ALTER TABLE `message_queue` ADD letter_code varchar(64) DEFAULT NULL AFTER metadata; });
2217
2218     $dbh->do(q{
2219         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
2220         ('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.');
2221     });
2222     $dbh->do(q{
2223         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
2224         ('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>>.');
2225     });
2226
2227     $dbh->do(q{INSERT INTO message_attributes (message_attribute_id, message_name, takes_days) VALUES (5, 'Item Check-in', 0);});
2228     $dbh->do(q{INSERT INTO message_attributes (message_attribute_id, message_name, takes_days) VALUES (6, 'Item Checkout', 0);});
2229
2230     $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');});
2231     $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');});
2232     $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');});
2233     $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');});
2234
2235     print "Upgrade to $DBversion done (data for Email Checkout Slips project)\n";
2236          SetVersion ($DBversion);
2237 }
2238
2239 $DBversion = "3.01.00.014";
2240 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2241     $dbh->do("ALTER TABLE `branch_transfer_limits` CHANGE `itemtype` `itemtype` VARCHAR( 4 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL");
2242     $dbh->do("ALTER TABLE `branch_transfer_limits` ADD `ccode` VARCHAR( 10 ) NULL ;");
2243     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2244     VALUES (
2245     'BranchTransferLimitsType', 'ccode', 'itemtype|ccode', 'When using branch transfer limits, choose whether to limit by itemtype or collection code.', 'Choice'
2246     );");
2247
2248     print "Upgrade to $DBversion done ( Updated table for Branch Transfer Limits)\n";
2249     SetVersion ($DBversion);
2250 }
2251
2252 $DBversion = '3.01.00.015';
2253 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2254     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsClientCode', '0', 'Client Code for using Syndetics Solutions content','','free')");
2255
2256     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsEnabled', '0', 'Turn on Syndetics Enhanced Content','','YesNo')");
2257
2258     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsCoverImages', '0', 'Display Cover Images from Syndetics','','YesNo')");
2259
2260     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsTOC', '0', 'Display Table of Content information from Syndetics','','YesNo')");
2261
2262     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsSummary', '0', 'Display Summary Information from Syndetics','','YesNo')");
2263
2264     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsEditions', '0', 'Display Editions from Syndetics','','YesNo')");
2265
2266     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsExcerpt', '0', 'Display Excerpts and first chapters on OPAC from Syndetics','','YesNo')");
2267
2268     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsReviews', '0', 'Display Reviews on OPAC from Syndetics','','YesNo')");
2269
2270     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsAuthorNotes', '0', 'Display Notes about the Author on OPAC from Syndetics','','YesNo')");
2271
2272     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsAwards', '0', 'Display Awards on OPAC from Syndetics','','YesNo')");
2273
2274     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsSeries', '0', 'Display Series information on OPAC from Syndetics','','YesNo')");
2275
2276     $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')");
2277
2278     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAmazonCoverImages', '0', 'Display cover images on OPAC from Amazon Web Services','','YesNo')");
2279
2280     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AmazonCoverImages', '0', 'Display Cover Images in Staff Client from Amazon Web Services','','YesNo')");
2281
2282     $dbh->do("UPDATE systempreferences SET variable='AmazonEnabled' WHERE variable = 'AmazonContent'");
2283
2284     $dbh->do("UPDATE systempreferences SET variable='OPACAmazonEnabled' WHERE variable = 'OPACAmazonContent'");
2285
2286     print "Upgrade to $DBversion done (added Syndetics Enhanced Content system preferences)\n";
2287     SetVersion ($DBversion);
2288 }
2289
2290 $DBversion = "3.01.00.016";
2291 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2292     $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')");
2293     print "Upgrade to $DBversion done (Added Babeltheque syspref)\n";
2294     SetVersion ($DBversion);
2295 }
2296
2297 $DBversion = "3.01.00.017";
2298 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2299     $dbh->do("ALTER TABLE `subscription` ADD `staffdisplaycount` VARCHAR(10) NULL;");
2300     $dbh->do("ALTER TABLE `subscription` ADD `opacdisplaycount` VARCHAR(10) NULL;");
2301     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2302     VALUES (
2303     'StaffSerialIssueDisplayCount', '3', '', 'Number of serial issues to display per subscription in the Staff client', 'Integer'
2304     );");
2305         $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2306     VALUES (
2307     'OPACSerialIssueDisplayCount', '3', '', 'Number of serial issues to display per subscription in the OPAC', 'Integer'
2308     );");
2309
2310     print "Upgrade to $DBversion done ( Updated table for Serials Display)\n";
2311     SetVersion ($DBversion);
2312 }
2313
2314 $DBversion = "3.01.00.018";
2315 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2316     $dbh->do("ALTER TABLE deletedborrowers ADD `smsalertnumber` varchar(50) default NULL");
2317     print "Upgrade to $DBversion done (added deletedborrowers.smsalertnumber, missed in 3.00.00.091)\n";
2318     SetVersion ($DBversion);
2319 }
2320
2321 $DBversion = "3.01.00.019";
2322 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2323         $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')");
2324     print "Upgrade to $DBversion done (adding OPACShowCheckoutName systempref)\n";
2325     SetVersion ($DBversion);
2326 }
2327
2328 $DBversion = "3.01.00.020";
2329 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2330     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesID','','See:http://librarything.com/forlibraries/','','free')");
2331     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesEnabled','0','Enable or Disable Library Thing for Libraries Features','','YesNo')");
2332     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesTabbedView','0','Put LibraryThingForLibraries Content in Tabs.','','YesNo')");
2333     print "Upgrade to $DBversion done (adding LibraryThing for Libraries sysprefs)\n";
2334     SetVersion ($DBversion);
2335 }
2336
2337 $DBversion = "3.01.00.021";
2338 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2339     my $enable_reviews = C4::Context->preference('OPACAmazonEnabled') ? '1' : '0';
2340     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAmazonReviews', '$enable_reviews', 'Display Amazon readers reviews on OPAC','','YesNo')");
2341     print "Upgrade to $DBversion done (adding OPACAmazonReviews syspref)\n";
2342     SetVersion ($DBversion);
2343 }
2344
2345 $DBversion = '3.01.00.022';
2346 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2347     $dbh->do("ALTER TABLE `labels_conf` MODIFY COLUMN `formatstring` mediumtext DEFAULT NULL");
2348     print "Upgrade to $DBversion done (bug 2945: increase size of labels_conf.formatstring)\n";
2349     SetVersion ($DBversion);
2350 }
2351
2352 $DBversion = '3.01.00.023';
2353 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2354     $dbh->do("ALTER TABLE biblioitems        MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2355     $dbh->do("ALTER TABLE deletedbiblioitems MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2356     $dbh->do("ALTER TABLE import_biblios     MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2357     $dbh->do("ALTER TABLE suggestions        MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2358     print "Upgrade to $DBversion done (bug 2765: increase width of isbn column in several tables)\n";
2359     SetVersion ($DBversion);
2360 }
2361
2362 $DBversion = "3.01.00.024";
2363 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2364     $dbh->do("ALTER TABLE labels MODIFY COLUMN batch_id int(10) NOT NULL default 1;");
2365     print "Upgrade to $DBversion done (change labels.batch_id from varchar to int)\n";
2366     SetVersion ($DBversion);
2367 }
2368
2369 $DBversion = '3.01.00.025';
2370 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2371     $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')");
2372
2373     print "Upgrade to $DBversion done (added ceilingDueDate system preference)\n";
2374     SetVersion ($DBversion);
2375 }
2376
2377 $DBversion = '3.01.00.026';
2378 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2379     $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')");
2380
2381     print "Upgrade to $DBversion done (added numReturnedItemsToShow system preference)\n";
2382     SetVersion ($DBversion);
2383 }
2384
2385 $DBversion = '3.01.00.027';
2386 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2387     $dbh->do("ALTER TABLE zebraqueue CHANGE `biblio_auth_number` `biblio_auth_number` bigint(20) unsigned NOT NULL default 0");
2388     print "Upgrade to $DBversion done (Increased size of zebraqueue biblio_auth_number to address bug 3148.)\n";
2389     SetVersion ($DBversion);
2390 }
2391
2392 $DBversion = '3.01.00.028';
2393 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2394     my $enable_reviews = C4::Context->preference('AmazonEnabled') ? '1' : '0';
2395     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AmazonReviews', '$enable_reviews', 'Display Amazon reviews on staff interface','','YesNo')");
2396     print "Upgrade to $DBversion done (added AmazonReviews)\n";
2397     SetVersion ($DBversion);
2398 }
2399
2400 $DBversion = '3.01.00.029';
2401 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2402     $dbh->do(q( UPDATE language_rfc4646_to_iso639
2403                 SET iso639_2_code = 'spa'
2404                 WHERE rfc4646_subtag = 'es'
2405                 AND   iso639_2_code = 'rus' )
2406             );
2407     print "Upgrade to $DBversion done (fixed bug 2599: using Spanish search limit retrieves Russian results)\n";
2408     SetVersion ($DBversion);
2409 }
2410
2411 $DBversion = "3.01.00.030";
2412 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2413     $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')");
2414     print "Upgrade to $DBversion done (added AllowNotForLoanOverride system preference)\n";
2415     SetVersion ($DBversion);
2416 }
2417
2418 $DBversion = "3.01.00.031";
2419 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2420     $dbh->do("ALTER TABLE branch_transfer_limits
2421               MODIFY toBranch   varchar(10) NOT NULL,
2422               MODIFY fromBranch varchar(10) NOT NULL,
2423               MODIFY itemtype   varchar(10) NULL");
2424     print "Upgrade to $DBversion done (fix column widths in branch_transfer_limits)\n";
2425     SetVersion ($DBversion);
2426 }
2427
2428 $DBversion = "3.01.00.032";
2429 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2430     $dbh->do(<<ENDOFRENEWAL);
2431 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');
2432 ENDOFRENEWAL
2433     print "Upgrade to $DBversion done (Change the field)\n";
2434     SetVersion ($DBversion);
2435 }
2436
2437 $DBversion = "3.01.00.033";
2438 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2439     $dbh->do(q/
2440         ALTER TABLE borrower_message_preferences
2441         MODIFY borrowernumber int(11) default NULL,
2442         ADD    categorycode varchar(10) default NULL AFTER borrowernumber,
2443         ADD KEY `categorycode` (`categorycode`),
2444         ADD CONSTRAINT `borrower_message_preferences_ibfk_3`
2445                        FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
2446                        ON DELETE CASCADE ON UPDATE CASCADE
2447     /);
2448     print "Upgrade to $DBversion done (DB changes to allow patron category defaults for messaging preferences)\n";
2449     SetVersion ($DBversion);
2450 }
2451
2452 $DBversion = "3.01.00.034";
2453 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2454     $dbh->do("ALTER TABLE `subscription` ADD COLUMN `graceperiod` INT(11) NOT NULL default '0';");
2455     print "Upgrade to $DBversion done (Adding graceperiod column to subscription table)\n";
2456     SetVersion ($DBversion);
2457 }
2458
2459 $DBversion = '3.01.00.035';
2460 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2461     $dbh->do(q{ ALTER TABLE `subscription` ADD location varchar(80) NULL DEFAULT '' AFTER callnumber; });
2462    print "Upgrade to $DBversion done (Adding location to subscription table)\n";
2463     SetVersion ($DBversion);
2464 }
2465
2466 $DBversion = '3.01.00.036';
2467 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2468     $dbh->do("UPDATE systempreferences SET explanation = 'Choose the default detail view in the staff interface; choose between normal, labeled_marc, marc or isbd'
2469               WHERE variable = 'IntranetBiblioDefaultView'
2470               AND   explanation = 'IntranetBiblioDefaultView'");
2471     $dbh->do("UPDATE systempreferences SET type = 'Choice', options = 'normal|marc|isbd|labeled_marc'
2472               WHERE variable = 'IntranetBiblioDefaultView'");
2473     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewISBD','1','Allow display of ISBD view of bibiographic records','','YesNo')");
2474     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewLabeledMARC','0','Allow display of labeled MARC view of bibiographic records','','YesNo')");
2475     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewMARC','1','Allow display of MARC view of bibiographic records','','YesNo')");
2476     print "Upgrade to $DBversion done (new viewISBD, viewLabeledMARC, viewMARC sysprefs and tweak IntranetBiblioDefaultView)\n";
2477     SetVersion ($DBversion);
2478 }
2479
2480 $DBversion = '3.01.00.037';
2481 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2482     $dbh->do('ALTER TABLE authorised_values ADD KEY `lib` (`lib`)');
2483     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('FilterBeforeOverdueReport','0','Do not run overdue report until filter selected','','YesNo')");
2484     SetVersion ($DBversion);
2485     print "Upgrade to $DBversion done (added FilterBeforeOverdueReport syspref and new index on authorised_values)\n";
2486 }
2487
2488 $DBversion = "3.01.00.038";
2489 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2490     # update branches table
2491     #
2492     $dbh->do("ALTER TABLE branches ADD `branchzip` varchar(25) default NULL AFTER `branchaddress3`");
2493     $dbh->do("ALTER TABLE branches ADD `branchcity` mediumtext AFTER `branchzip`");
2494     $dbh->do("ALTER TABLE branches ADD `branchcountry` text AFTER `branchcity`");
2495     $dbh->do("ALTER TABLE branches ADD `branchurl` mediumtext AFTER `branchemail`");
2496     $dbh->do("ALTER TABLE branches ADD `branchnotes` mediumtext AFTER `branchprinter`");
2497     print "Upgrade to $DBversion done (add ZIP, city, country, URL, and notes column to branches)\n";
2498     SetVersion ($DBversion);
2499 }
2500
2501 $DBversion = '3.01.00.039';
2502 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2503     $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')");
2504     $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')");
2505     SetVersion ($DBversion);
2506     print "Upgrade to $DBversion done (added SpineLabelFormat and SpineLabelAutoPrint sysprefs)\n";
2507 }
2508
2509 $DBversion = '3.01.00.040';
2510 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2511     $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')");
2512     $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')");
2513     SetVersion ($DBversion);
2514     print "Upgrade to $DBversion done (AllowHoldDateInFuture and OPACAllowHoldDateInFuture sysprefs)\n";
2515 }
2516
2517 $DBversion = '3.01.00.041';
2518 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2519     $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')");
2520     SetVersion ($DBversion);
2521     print "Upgrade to $DBversion done (added AWSPrivateKey syspref - note that if you use enhanced content from Amazon, this should be set right away.)\n";
2522 }
2523
2524 $DBversion = '3.01.00.042';
2525 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2526     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACFineNoRenewals','99999','Fine Limit above which user canmot renew books via OPAC','','Integer')");
2527     SetVersion ($DBversion);
2528     print "Upgrade to $DBversion done (added OPACFineNoRenewals syspref)\n";
2529 }
2530
2531 $DBversion = '3.01.00.043';
2532 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2533     $dbh->do('ALTER TABLE items ADD COLUMN permanent_location VARCHAR(80) DEFAULT NULL AFTER location');
2534     $dbh->do('UPDATE items SET permanent_location = location');
2535     $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 )', '')");
2536     $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')");
2537     $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')");
2538     SetVersion ($DBversion);
2539     print "Upgrade to $DBversion done (amended Item added NewItemsDefaultLocation, InProcessingToShelvingCart, ReturnToShelvingCart sysprefs)\n";
2540 }
2541
2542 $DBversion = '3.01.00.044';
2543 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2544     $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')");
2545     SetVersion ($DBversion);
2546     print "Upgrade to $DBversion done (added DisplayClearScreenButton system preference)\n";
2547 }
2548
2549 $DBversion = '3.01.00.045';
2550 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2551     $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')");
2552     SetVersion ($DBversion);
2553     print "Upgrade to $DBversion done (added a preference to hide the patrons name in the staff catalog)\n";
2554 }
2555
2556 $DBversion = "3.01.00.046";
2557 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2558     # update borrowers table
2559     #
2560     $dbh->do("ALTER TABLE borrowers ADD `country` text AFTER zipcode");
2561     $dbh->do("ALTER TABLE borrowers ADD `B_country` text AFTER B_zipcode");
2562     $dbh->do("ALTER TABLE deletedborrowers ADD `country` text AFTER zipcode");
2563     $dbh->do("ALTER TABLE deletedborrowers ADD `B_country` text AFTER B_zipcode");
2564     print "Upgrade to $DBversion done (add country and B_country to borrowers)\n";
2565     SetVersion ($DBversion);
2566 }
2567
2568 $DBversion = '3.01.00.047';
2569 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2570     $dbh->do("ALTER TABLE items MODIFY itemcallnumber varchar(255);");
2571     $dbh->do("ALTER TABLE deleteditems MODIFY itemcallnumber varchar(255);");
2572     $dbh->do("ALTER TABLE tmp_holdsqueue MODIFY itemcallnumber varchar(255);");
2573     SetVersion ($DBversion);
2574     print " Upgrade to $DBversion done (bug 2761: change max length of itemcallnumber to 255 from 30)\n";
2575 }
2576
2577 $DBversion = '3.01.00.048';
2578 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2579     $dbh->do("UPDATE userflags SET flagdesc='View Catalog (Librarian Interface)' WHERE bit=2;");
2580     $dbh->do("UPDATE userflags SET flagdesc='Edit Catalog (Modify bibliographic/holdings data)' WHERE bit=9;");
2581     $dbh->do("UPDATE userflags SET flagdesc='Allow to edit authorities' WHERE bit=14;");
2582     $dbh->do("UPDATE userflags SET flagdesc='Allow to access to the reports module' WHERE bit=16;");
2583     $dbh->do("UPDATE userflags SET flagdesc='Allow to manage serials subscriptions' WHERE bit=15;");
2584     SetVersion ($DBversion);
2585     print " Upgrade to $DBversion done (bug 2611: fix spelling/capitalization in permission flag descriptions)\n";
2586 }
2587
2588 $DBversion = '3.01.00.049';
2589 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2590     $dbh->do("UPDATE permissions SET description = 'Perform inventory (stocktaking) of your catalog' WHERE code = 'inventory';");
2591      SetVersion ($DBversion);
2592     print "Upgrade to $DBversion done (bug 2611: changed catalogue to catalog per the standard)\n";
2593 }
2594
2595 $DBversion = '3.01.00.050';
2596 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2597     $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');");
2598     SetVersion ($DBversion);
2599     print "Upgrade to $DBversion done (bug 1934: Add OPACSearchForTitleIn syspref)\n";
2600 }
2601
2602 $DBversion = '3.01.00.051';
2603 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2604     $dbh->do("UPDATE systempreferences SET explanation='Fine limit above which user cannot renew books via OPAC' WHERE variable='OPACFineNoRenewals';");
2605     $dbh->do("UPDATE systempreferences SET explanation='If set to ON, a clear screen button will appear on the circulation page.' WHERE variable='DisplayClearScreenButton';");
2606     SetVersion ($DBversion);
2607     print "Upgrade to $DBversion done (fixed typos in new sysprefs)\n";
2608 }
2609
2610 $DBversion = '3.01.00.052';
2611 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2612     $dbh->do('ALTER TABLE deleteditems ADD COLUMN permanent_location VARCHAR(80) DEFAULT NULL AFTER location');
2613     SetVersion ($DBversion);
2614     print "Upgrade to $DBversion done (bug 3481: add permanent_location column to deleteditems)\n";
2615 }
2616
2617 $DBversion = '3.01.00.053';
2618 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2619     my $upgrade_script = C4::Context->config("intranetdir") . "/installer/data/mysql/labels_upgrade.pl";
2620     system("perl $upgrade_script");
2621     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";
2622     SetVersion ($DBversion);
2623 }
2624
2625 $DBversion = '3.01.00.054';
2626 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2627     $dbh->do("ALTER TABLE borrowers ADD `B_address2` text AFTER B_address");
2628     $dbh->do("ALTER TABLE borrowers ADD `altcontactcountry` text AFTER altcontactzipcode");
2629     $dbh->do("ALTER TABLE deletedborrowers ADD `B_address2` text AFTER B_address");
2630     $dbh->do("ALTER TABLE deletedborrowers ADD `altcontactcountry` text AFTER altcontactzipcode");
2631     SetVersion ($DBversion);
2632     print "Upgrade to $DBversion done (bug 1600, bug 3454: add altcontactcountry and B_address2 to borrowers and deletedborrowers)\n";
2633 }
2634
2635 $DBversion = '3.01.00.055';
2636 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2637     $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'|);
2638     SetVersion ($DBversion);
2639     print "Upgrade to $DBversion done (changed OPACSearchForTitleIn per requests in bug 1934)\n";
2640 }
2641
2642 $DBversion = '3.01.00.056';
2643 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2644     $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');");
2645     SetVersion ($DBversion);
2646     print "Upgrade to $DBversion done (Bug 1172 : Add OPACPatronDetails syspref)\n";
2647 }
2648
2649 $DBversion = '3.01.00.057';
2650 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2651     $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');");
2652     SetVersion ($DBversion);
2653     print "Upgrade to $DBversion done (Bug 2576 : Add OPACFinesTab syspref)\n";
2654 }
2655
2656 $DBversion = '3.01.00.058';
2657 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2658     $dbh->do("ALTER TABLE `language_subtag_registry` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2659     $dbh->do("ALTER TABLE `language_rfc4646_to_iso639` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2660     $dbh->do("ALTER TABLE `language_descriptions` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2661     SetVersion ($DBversion);
2662     print "Upgrade to $DBversion done (Added primary keys to language tables)\n";
2663 }
2664
2665 $DBversion = '3.01.00.059';
2666 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2667     $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')");
2668     SetVersion ($DBversion);
2669     print "Upgrade to $DBversion done (added DisplayOPACiconsXSLT sysprefs)\n";
2670 }
2671
2672 $DBversion = '3.01.00.060';
2673 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2674     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowAllMessageDeletion','0','Allow any Library to delete any message','','YesNo');");
2675     $dbh->do('DROP TABLE IF EXISTS messages');
2676     $dbh->do("CREATE TABLE messages ( `message_id` int(11) NOT NULL auto_increment,
2677         `borrowernumber` int(11) NOT NULL,
2678         `branchcode` varchar(4) default NULL,
2679         `message_type` varchar(1) NOT NULL,
2680         `message` text NOT NULL,
2681         `message_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
2682         PRIMARY KEY (`message_id`)
2683         ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
2684
2685         print "Upgrade to $DBversion done ( Added AllowAllMessageDeletion syspref and messages table )\n";
2686     SetVersion ($DBversion);
2687 }
2688
2689 $DBversion = '3.01.00.061';
2690 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2691     $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')");
2692         print "Upgrade to $DBversion done ( Added ShowPatronImageInWebBasedSelfCheck system preference )\n";
2693     SetVersion ($DBversion);
2694 }
2695
2696 $DBversion = "3.01.00.062";
2697 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2698     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'manage_csv_profiles', 'Manage CSV export profiles')");
2699     $dbh->do(q/
2700         CREATE TABLE `export_format` (
2701           `export_format_id` int(11) NOT NULL auto_increment,
2702           `profile` varchar(255) NOT NULL,
2703           `description` mediumtext NOT NULL,
2704           `marcfields` mediumtext NOT NULL,
2705           PRIMARY KEY  (`export_format_id`)
2706         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Used for CSV export';
2707     /);
2708     print "Upgrade to $DBversion done (added csv export profiles)\n";
2709 }
2710
2711 $DBversion = "3.01.00.063";
2712 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2713     $dbh->do("
2714         CREATE TABLE `fieldmapping` (
2715           `id` int(11) NOT NULL auto_increment,
2716           `field` varchar(255) NOT NULL,
2717           `frameworkcode` char(4) NOT NULL default '',
2718           `fieldcode` char(3) NOT NULL,
2719           `subfieldcode` char(1) NOT NULL,
2720           PRIMARY KEY  (`id`)
2721         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2722              ");
2723     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";
2724 }
2725
2726 $DBversion = '3.01.00.065';
2727 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2728     $dbh->do('ALTER TABLE issuingrules ADD COLUMN `renewalsallowed` smallint(6) NOT NULL default "0" AFTER `issuelength`;');
2729     $sth = $dbh->prepare("SELECT itemtype, renewalsallowed FROM itemtypes");
2730     $sth->execute();
2731
2732     my $sthupd = $dbh->prepare("UPDATE issuingrules SET renewalsallowed = ? WHERE itemtype = ?");
2733
2734     while(my $row = $sth->fetchrow_hashref){
2735         $sthupd->execute($row->{renewalsallowed}, $row->{itemtype});
2736     }
2737
2738     $dbh->do('ALTER TABLE itemtypes DROP COLUMN `renewalsallowed`;');
2739
2740     SetVersion ($DBversion);
2741     print "Upgrade to $DBversion done (Moving allowed renewals from itemtypes to issuingrule)\n";
2742 }
2743
2744 $DBversion = '3.01.00.066';
2745 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2746     $dbh->do('ALTER TABLE issuingrules ADD COLUMN `reservesallowed` smallint(6) NOT NULL default "0" AFTER `renewalsallowed`;');
2747
2748     my $maxreserves = C4::Context->preference('maxreserves');
2749     $sth = $dbh->prepare('UPDATE issuingrules SET reservesallowed = ?;');
2750     $sth->execute($maxreserves);
2751
2752     $dbh->do('DELETE FROM systempreferences WHERE variable = "maxreserves";');
2753
2754     $dbh->do("INSERT INTO systempreferences (variable,value, options, explanation, type) VALUES('ReservesControlBranch','PatronLibrary','ItemHomeLibrary|PatronLibrary','Branch checked for members reservations rights','Choice')");
2755
2756     SetVersion ($DBversion);
2757     print "Upgrade to $DBversion done (Moving max allowed reserves from system preference to issuingrule)\n";
2758 }
2759
2760 $DBversion = "3.01.00.067";
2761 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2762     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'batchmod', 'Perform batch modification of items')");
2763     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'batchdel', 'Perform batch deletion of items')");
2764     print "Upgrade to $DBversion done (added permissions for batch modification and deletion)\n";
2765     SetVersion ($DBversion);
2766 }
2767
2768 $DBversion = "3.01.00.068";
2769 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2770         $dbh->do("ALTER TABLE issuingrules ADD COLUMN `finedays` int(11) default NULL AFTER `fine` ");
2771         print "Upgrade to $DBversion done (Adding finedays in issuingrules table)\n";
2772     SetVersion ($DBversion);
2773 }
2774
2775
2776 $DBversion = "3.01.00.069";
2777 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2778         $dbh->do("INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('EnableOpacSearchHistory', '1', '', 'Enable or disable opac search history', 'YesNo')");
2779
2780         my $create = <<SEARCHHIST;
2781 CREATE TABLE IF NOT EXISTS `search_history` (
2782   `userid` int(11) NOT NULL,
2783   `sessionid` varchar(32) NOT NULL,
2784   `query_desc` varchar(255) NOT NULL,
2785   `query_cgi` varchar(255) NOT NULL,
2786   `total` int(11) NOT NULL,
2787   `time` timestamp NOT NULL default CURRENT_TIMESTAMP,
2788   KEY `userid` (`userid`),
2789   KEY `sessionid` (`sessionid`)
2790 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Opac search history results';
2791 SEARCHHIST
2792         $dbh->do($create);
2793
2794         print "Upgrade to $DBversion done (added OPAC search history preference and table)\n";
2795 }
2796
2797 $DBversion = "3.01.00.070";
2798 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2799         $dbh->do("ALTER TABLE authorised_values ADD COLUMN `lib_opac` VARCHAR(80) default NULL AFTER `lib`");
2800         print "Upgrade to $DBversion done (Added a lib_opac field in authorised_values table)\n";
2801 }
2802
2803 $DBversion = "3.01.00.071";
2804 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2805         $dbh->do("ALTER TABLE `subscription` ADD `enddate` date default NULL");
2806         $dbh->do("ALTER TABLE subscriptionhistory CHANGE enddate histenddate DATE default NULL");
2807         print "Upgrade to $DBversion done ( Adding enddate to subscription)\n";
2808 }
2809
2810 # Acquisitions update
2811
2812 $DBversion = "3.01.00.072";
2813 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2814     $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')");
2815     # create a new syspref for the 'Mr anonymous' patron
2816     $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,'')");
2817     # fill AnonymousPatron with AnonymousSuggestion value (copy)
2818     my $sth=$dbh->prepare("SELECT value FROM systempreferences WHERE variable='AnonSuggestions'");
2819     $sth->execute;
2820     my ($value) = $sth->fetchrow() || 0;
2821     $dbh->do("UPDATE systempreferences SET value='$value' WHERE variable='AnonymousPatron'");
2822     # set AnonymousSuggestion do YesNo
2823     # 1st, set the value (1/True if it had a borrowernumber)
2824     $dbh->do("UPDATE systempreferences SET value=1 WHERE variable='AnonSuggestions' AND value>0");
2825     # 2nd, change the type to Choice
2826     $dbh->do("UPDATE systempreferences SET type='YesNo' WHERE variable='AnonSuggestions'");
2827         # borrower reading record privacy : 0 : forever, 1 : laws, 2 : don't keep at all
2828     $dbh->do("ALTER TABLE `borrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
2829     print "Upgrade to $DBversion done (add new syspref and column in borrowers)\n";
2830     SetVersion ($DBversion);
2831 }
2832
2833 $DBversion = '3.01.00.073';
2834 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2835     $dbh->do('SET FOREIGN_KEY_CHECKS=0 ');
2836     $dbh->do(<<'END_SQL');
2837 CREATE TABLE IF NOT EXISTS `aqcontract` (
2838   `contractnumber` int(11) NOT NULL auto_increment,
2839   `contractstartdate` date default NULL,
2840   `contractenddate` date default NULL,
2841   `contractname` varchar(50) default NULL,
2842   `contractdescription` mediumtext,
2843   `booksellerid` int(11) not NULL,
2844     PRIMARY KEY  (`contractnumber`),
2845         CONSTRAINT `booksellerid_fk1` FOREIGN KEY (`booksellerid`)
2846         REFERENCES `aqbooksellers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
2847 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
2848 END_SQL
2849     $dbh->do('SET FOREIGN_KEY_CHECKS=1 ');
2850     print "Upgrade to $DBversion done (adding aqcontract table)\n";
2851     SetVersion ($DBversion);
2852 }
2853
2854 $DBversion = '3.01.00.074';
2855 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2856     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `basketname` varchar(50) default NULL AFTER `basketno`");
2857     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `note` mediumtext AFTER `basketname`");
2858     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `booksellernote` mediumtext AFTER `note`");
2859     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `contractnumber` int(11) AFTER `booksellernote`");
2860     $dbh->do("ALTER TABLE `aqbasket` ADD FOREIGN KEY (`contractnumber`) REFERENCES `aqcontract` (`contractnumber`)");
2861     print "Upgrade to $DBversion done (edit aqbasket table done)\n";
2862     SetVersion ($DBversion);
2863 }
2864
2865 $DBversion = '3.01.00.075';
2866 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2867     $dbh->do("ALTER TABLE `aqorders` ADD COLUMN `uncertainprice` tinyint(1)");
2868
2869     print "Upgrade to $DBversion done (adding uncertainprices)\n";
2870     SetVersion ($DBversion);
2871 }
2872
2873 $DBversion = '3.01.00.076';
2874 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2875     $dbh->do('SET FOREIGN_KEY_CHECKS=0 ');
2876     $dbh->do("CREATE TABLE IF NOT EXISTS `aqbasketgroups` (
2877                          `id` int(11) NOT NULL auto_increment,
2878                          `name` varchar(50) default NULL,
2879                          `closed` tinyint(1) default NULL,
2880                          `booksellerid` int(11) NOT NULL,
2881                          PRIMARY KEY (`id`),
2882                          KEY `booksellerid` (`booksellerid`),
2883                          CONSTRAINT `aqbasketgroups_ibfk_1` FOREIGN KEY (`booksellerid`) REFERENCES `aqbooksellers` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
2884                          ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
2885     $dbh->do("ALTER TABLE aqbasket ADD COLUMN `basketgroupid` int(11)");
2886     $dbh->do("ALTER TABLE aqbasket ADD FOREIGN KEY (`basketgroupid`) REFERENCES `aqbasketgroups` (`id`) ON UPDATE CASCADE ON DELETE SET NULL");
2887     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('pdfformat','pdfformat::layout2pages','Controls what script is used for printing (basketgroups)','','free')");
2888     $dbh->do('SET FOREIGN_KEY_CHECKS=1 ');
2889     print "Upgrade to $DBversion done (adding basketgroups)\n";
2890     SetVersion ($DBversion);
2891 }
2892 $DBversion = '3.01.00.077';
2893 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2894
2895     $dbh->do("SET FOREIGN_KEY_CHECKS=0 ");
2896     # create a mapping table holding the info we need to match orders to budgets
2897     $dbh->do('DROP TABLE IF EXISTS fundmapping');
2898     $dbh->do(
2899         q|CREATE TABLE fundmapping AS
2900         SELECT aqorderbreakdown.ordernumber, branchcode, bookfundid, budgetdate, entrydate
2901         FROM aqorderbreakdown JOIN aqorders ON aqorderbreakdown.ordernumber = aqorders.ordernumber|);
2902     # match the new type of the corresponding field
2903     $dbh->do('ALTER TABLE fundmapping modify column bookfundid varchar(30)');
2904     # System did not ensure budgetdate was valid historically
2905     $dbh->do(q|UPDATE fundmapping SET budgetdate = entrydate WHERE budgetdate = '0000-00-00' OR budgetdate IS NULL|);
2906     # We save the map in fundmapping in case you need later processing
2907     $dbh->do(q|ALTER TABLE fundmapping add column aqbudgetid integer|);
2908     # these can speed processing up
2909     $dbh->do(q|CREATE INDEX fundmaporder ON fundmapping (ordernumber)|);
2910     $dbh->do(q|CREATE INDEX fundmapid ON fundmapping (bookfundid)|);
2911
2912     $dbh->do("DROP TABLE IF EXISTS `aqbudgetperiods` ");
2913
2914     $dbh->do(qq|
2915                     CREATE TABLE `aqbudgetperiods` (
2916                     `budget_period_id` int(11) NOT NULL auto_increment,
2917                     `budget_period_startdate` date NOT NULL,
2918                     `budget_period_enddate` date NOT NULL,
2919                     `budget_period_active` tinyint(1) default '0',
2920                     `budget_period_description` mediumtext,
2921                     `budget_period_locked` tinyint(1) default NULL,
2922                     `sort1_authcat` varchar(10) default NULL,
2923                     `sort2_authcat` varchar(10) default NULL,
2924                     PRIMARY KEY  (`budget_period_id`)
2925                     ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 |);
2926
2927    $dbh->do(<<ADDPERIODS);
2928 INSERT INTO aqbudgetperiods (budget_period_startdate,budget_period_enddate,budget_period_active,budget_period_description,budget_period_locked)
2929 SELECT DISTINCT startdate, enddate, NOW() BETWEEN startdate and enddate, concat(startdate," ",enddate),NOT NOW() BETWEEN startdate AND enddate from aqbudget
2930 ADDPERIODS
2931 # SORRY , NO AQBUDGET/AQBOOKFUND -> AQBUDGETS IMPORT JUST YET,
2932 # BUT A NEW CLEAN AQBUDGETS TABLE CREATE FOR NOW..
2933 # DROP TABLE IF EXISTS `aqbudget`;
2934 #CREATE TABLE `aqbudget` (
2935 #  `bookfundid` varchar(10) NOT NULL default ',
2936 #    `startdate` date NOT NULL default 0,
2937 #         `enddate` date default NULL,
2938 #           `budgetamount` decimal(13,2) default NULL,
2939 #                 `aqbudgetid` tinyint(4) NOT NULL auto_increment,
2940 #                   `branchcode` varchar(10) default NULL,
2941     DropAllForeignKeys('aqbudget');
2942   #$dbh->do("drop table aqbudget;");
2943
2944
2945     my $maxbudgetid = $dbh->selectcol_arrayref(<<IDsBUDGET);
2946 SELECT MAX(aqbudgetid) from aqbudget
2947 IDsBUDGET
2948
2949 $$maxbudgetid[0] = 0 if !$$maxbudgetid[0];
2950
2951     $dbh->do(<<BUDGETAUTOINCREMENT);
2952 ALTER TABLE aqbudget AUTO_INCREMENT=$$maxbudgetid[0]
2953 BUDGETAUTOINCREMENT
2954
2955     $dbh->do(<<BUDGETNAME);
2956 ALTER TABLE aqbudget RENAME `aqbudgets`
2957 BUDGETNAME
2958
2959     $dbh->do(<<BUDGETS);
2960 ALTER TABLE `aqbudgets`
2961    CHANGE  COLUMN aqbudgetid `budget_id` int(11) NOT NULL AUTO_INCREMENT,
2962    CHANGE  COLUMN branchcode `budget_branchcode` varchar(10) default NULL,
2963    CHANGE  COLUMN budgetamount `budget_amount` decimal(28,6) NOT NULL default '0.00',
2964    CHANGE  COLUMN bookfundid   `budget_code` varchar(30) default NULL,
2965    ADD     COLUMN `budget_parent_id` int(11) default NULL,
2966    ADD     COLUMN `budget_name` varchar(80) default NULL,
2967    ADD     COLUMN `budget_encumb` decimal(28,6) default '0.00',
2968    ADD     COLUMN `budget_expend` decimal(28,6) default '0.00',
2969    ADD     COLUMN `budget_notes` mediumtext,
2970    ADD     COLUMN `budget_description` mediumtext,
2971    ADD     COLUMN `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
2972    ADD     COLUMN `budget_amount_sublevel`  decimal(28,6) AFTER `budget_amount`,
2973    ADD     COLUMN `budget_period_id` int(11) default NULL,
2974    ADD     COLUMN `sort1_authcat` varchar(80) default NULL,
2975    ADD     COLUMN `sort2_authcat` varchar(80) default NULL,
2976    ADD     COLUMN `budget_owner_id` int(11) default NULL,
2977    ADD     COLUMN `budget_permission` int(1) default '0';
2978 BUDGETS
2979
2980     $dbh->do(<<BUDGETCONSTRAINTS);
2981 ALTER TABLE `aqbudgets`
2982    ADD CONSTRAINT `aqbudgets_ifbk_1` FOREIGN KEY (`budget_period_id`) REFERENCES `aqbudgetperiods` (`budget_period_id`) ON DELETE CASCADE ON UPDATE CASCADE
2983 BUDGETCONSTRAINTS
2984 #    $dbh->do(<<BUDGETPKDROP);
2985 #ALTER TABLE `aqbudgets`
2986 #   DROP PRIMARY KEY
2987 #BUDGETPKDROP
2988 #    $dbh->do(<<BUDGETPKADD);
2989 #ALTER TABLE `aqbudgets`
2990 #   ADD PRIMARY KEY budget_id
2991 #BUDGETPKADD
2992
2993
2994         my $query_period= $dbh->prepare(qq|SELECT budget_period_id from aqbudgetperiods where budget_period_startdate=? and budget_period_enddate=?|);
2995         my $query_bookfund= $dbh->prepare(qq|SELECT * from aqbookfund where bookfundid=?|);
2996         my $selectbudgets=$dbh->prepare(qq|SELECT * from aqbudgets|);
2997         my $updatebudgets=$dbh->prepare(qq|UPDATE aqbudgets SET budget_period_id= ? , budget_name=?, budget_branchcode=? where budget_id=?|);
2998         $selectbudgets->execute;
2999         while (my $databudget=$selectbudgets->fetchrow_hashref){
3000                 $query_period->execute ($$databudget{startdate},$$databudget{enddate});
3001                 my ($budgetperiodid)=$query_period->fetchrow;
3002                 $query_bookfund->execute ($$databudget{budget_code});
3003                 my $databf=$query_bookfund->fetchrow_hashref;
3004                 my $branchcode=$$databudget{budget_branchcode}||$$databf{branchcode};
3005                 $updatebudgets->execute($budgetperiodid,$$databf{bookfundname},$branchcode,$$databudget{budget_id});
3006         }
3007     $dbh->do(<<BUDGETDROPDATES);
3008 ALTER TABLE `aqbudgets`
3009    DROP startdate,
3010    DROP enddate
3011 BUDGETDROPDATES
3012
3013
3014     $dbh->do("DROP TABLE IF EXISTS `aqbudgets_planning` ");
3015     $dbh->do("CREATE TABLE  `aqbudgets_planning` (
3016                     `plan_id` int(11) NOT NULL auto_increment,
3017                     `budget_id` int(11) NOT NULL,
3018                     `budget_period_id` int(11) NOT NULL,
3019                     `estimated_amount` decimal(28,6) default NULL,
3020                     `authcat` varchar(30) NOT NULL,
3021                     `authvalue` varchar(30) NOT NULL,
3022                                         `display` tinyint(1) DEFAULT 1,
3023                         PRIMARY KEY  (`plan_id`),
3024                         CONSTRAINT `aqbudgets_planning_ifbk_1` FOREIGN KEY (`budget_id`) REFERENCES `aqbudgets` (`budget_id`) ON DELETE CASCADE ON UPDATE CASCADE
3025                         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
3026
3027     $dbh->do("ALTER TABLE `aqorders`
3028                     ADD COLUMN `budget_id` tinyint(4) NOT NULL,
3029                     ADD COLUMN `budgetgroup_id` int(11) NOT NULL,
3030                     ADD COLUMN  `sort1_authcat` varchar(10) default NULL,
3031                     ADD COLUMN  `sort2_authcat` varchar(10) default NULL" );
3032                 # We need to map the orders to the budgets
3033                 # For Historic reasons this is more complex than it should be on occasions
3034                 my $budg_arr = $dbh->selectall_arrayref(
3035                     q|SELECT aqbudgets.budget_id, aqbudgets.budget_code, aqbudgetperiods.budget_period_startdate,
3036                     aqbudgetperiods.budget_period_enddate
3037                     FROM aqbudgets JOIN aqbudgetperiods ON aqbudgets.budget_period_id = aqbudgetperiods.budget_period_id
3038                     ORDER BY budget_code, budget_period_startdate|, { Slice => {} });
3039                 # We arbitarily order on start date, this means if you have overlapping periods the order will be
3040                 # linked to the latest matching budget YMMV
3041                 my $b_sth = $dbh->prepare(
3042                     'UPDATE fundmapping set aqbudgetid = ? where bookfundid =? AND budgetdate >= ? AND budgetdate <= ?');
3043                 for my $b ( @{$budg_arr}) {
3044                     $b_sth->execute($b->{budget_id}, $b->{budget_code}, $b->{budget_period_startdate}, $b->{budget_period_enddate});
3045                 }
3046                 # move the budgetids to aqorders
3047                 $dbh->do(q|UPDATE aqorders, fundmapping SET aqorders.budget_id = fundmapping.aqbudgetid
3048                     WHERE aqorders.ordernumber = fundmapping.ordernumber AND fundmapping.aqbudgetid IS NOT NULL|);
3049                 # NB fundmapping is left as an accontants trail also if you have budgetids that werent set
3050                 # you can decide what to do with them
3051
3052      $dbh->do(
3053          q|UPDATE aqorders, aqbudgets SET aqorders.budgetgroup_id = aqbudgets.budget_period_id
3054          WHERE aqorders.budget_id = aqbudgets.budget_id|);
3055                 # cannot do until aqorderbreakdown removed
3056 #    $dbh->do("DROP TABLE aqbookfund ");
3057 #    $dbh->do("ALTER TABLE aqorders  ADD FOREIGN KEY (`budget_id`) REFERENCES `aqbudgets` (`budget_id`) ON UPDATE CASCADE  " ); ????
3058     $dbh->do("SET FOREIGN_KEY_CHECKS=1 ");
3059
3060     print "Upgrade to $DBversion done (Adding new aqbudgetperiods, aqbudgets and aqbudget_planning tables  )\n";
3061     SetVersion ($DBversion);
3062 }
3063
3064
3065
3066 $DBversion = '3.01.00.078';
3067 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3068     $dbh->do("ALTER TABLE aqbudgetperiods ADD COLUMN budget_period_total decimal(28,6)");
3069     print "Upgrade to $DBversion done (adds 'budget_period_total' column to aqbudgetperiods table)\n";
3070     SetVersion($DBversion);
3071 }
3072
3073
3074 $DBversion = '3.01.00.079';
3075 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3076     $dbh->do("ALTER TABLE currency ADD COLUMN active  tinyint(1)");
3077
3078     print "Upgrade to $DBversion done (adds 'active' column to currencies table)\n";
3079     SetVersion($DBversion);
3080 }
3081
3082 $DBversion = '3.01.00.080';
3083 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3084     $dbh->do(<<BUDG_PERM );
3085 INSERT INTO permissions (module_bit, code, description) VALUES
3086             (11, 'vendors_manage', 'Manage vendors'),
3087             (11, 'contracts_manage', 'Manage contracts'),
3088             (11, 'period_manage', 'Manage periods'),
3089             (11, 'budget_manage', 'Manage budgets'),
3090             (11, 'budget_modify', "Modify budget (can't create lines but can modify existing ones)"),
3091             (11, 'planning_manage', 'Manage budget plannings'),
3092             (11, 'order_manage', 'Manage orders & basket'),
3093             (11, 'group_manage', 'Manage orders & basketgroups'),
3094             (11, 'order_receive', 'Manage orders & basket'),
3095             (11, 'budget_add_del', "Add and delete budgets (but can't modify budgets)");
3096 BUDG_PERM
3097
3098     print "Upgrade to $DBversion done (adds permissions for the acquisitions module)\n";
3099     SetVersion($DBversion);
3100 }
3101
3102
3103 $DBversion = '3.01.00.081';
3104 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3105     $dbh->do("ALTER TABLE aqbooksellers ADD COLUMN `gstrate` decimal(6,4) default NULL");
3106     if (my $gist=C4::Context->preference("gist")){
3107                 my $sql=$dbh->prepare("UPDATE aqbooksellers set `gstrate`=? ");
3108         $sql->execute($gist) ;
3109         }
3110     print "Upgrade to $DBversion done (added per-supplier gstrate setting)\n";
3111     SetVersion($DBversion);
3112 }
3113
3114 $DBversion = "3.01.00.082";
3115 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3116     if (C4::Context->preference("opaclanguages") eq "fr") {
3117         $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')#);
3118     } else {
3119         $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')");
3120     }
3121     print "Upgrade to $DBversion done (adding ReservesNeedReturns systempref, in circulation)\n";
3122     SetVersion ($DBversion);
3123 }
3124
3125 $DBversion = "3.01.00.083";
3126 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3127     $dbh->do(qq|
3128  CREATE TABLE `aqorders_items` (
3129   `ordernumber` int(11) NOT NULL,
3130   `itemnumber` int(11) NOT NULL,
3131   `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
3132   PRIMARY KEY  (`itemnumber`),
3133   KEY `ordernumber` (`ordernumber`)
3134 ) ENGINE=InnoDB DEFAULT CHARSET=utf8   |
3135     );
3136
3137     $dbh->do(qq| DROP TABLE aqorderbreakdown |);
3138     $dbh->do('DROP TABLE aqbookfund');
3139     print "Upgrade to $DBversion done (New aqorders_items table for acqui)\n";
3140     SetVersion ($DBversion);
3141 }
3142
3143 $DBversion = "3.01.00.084";
3144 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3145     $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')  #);
3146
3147     print "Upgrade to $DBversion done (CurrencyFormat syspref added)\n";
3148     SetVersion ($DBversion);
3149 }
3150
3151 $DBversion = "3.01.00.085";
3152 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3153     $dbh->do("ALTER table aqorders drop column title");
3154     $dbh->do("ALTER TABLE `aqorders` CHANGE `budget_id` `budget_id` INT( 11 ) NOT NULL");
3155     print "Upgrade to $DBversion done update budget_id size that should not be a tinyint\n";
3156     SetVersion ($DBversion);
3157 }
3158
3159 $DBversion = "3.01.00.086";
3160 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3161     $dbh->do(<<SUGGESTIONS);
3162 ALTER table suggestions
3163     ADD budgetid INT(11),
3164     ADD branchcode VARCHAR(10) default NULL,
3165     ADD acceptedby INT(11) default NULL,
3166     ADD accepteddate date default NULL,
3167     ADD suggesteddate date default NULL,
3168     ADD manageddate date default NULL,
3169     ADD rejectedby INT(11) default NULL,
3170     ADD rejecteddate date default NULL,
3171     ADD collectiontitle text default NULL,
3172     ADD itemtype VARCHAR(30) default NULL
3173     ;
3174 SUGGESTIONS
3175     print "Upgrade to $DBversion done (Suggestions)\n";
3176     SetVersion ($DBversion);
3177 }
3178
3179 $DBversion = "3.01.00.087";
3180 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3181     $dbh->do("ALTER table aqbudgets drop column budget_amount_sublevel;");
3182     print "Upgrade to $DBversion done (Drop column budget_amount_sublevel from aqbudgets)\n";
3183     SetVersion ($DBversion);
3184 }
3185
3186 $DBversion = "3.01.00.088";
3187 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3188     $dbh->do(  qq# INSERT INTO `systempreferences` VALUES ('intranetbookbag','1','','If ON, enables display of Cart feature in the intranet','YesNo')  #);
3189
3190     print "Upgrade to $DBversion done (intranetbookbag syspref added)\n";
3191     SetVersion ($DBversion);
3192 }
3193
3194 $DBversion = "3.01.00.090";
3195 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3196 $dbh->do("
3197        INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3198                 (16, 'execute_reports', 'Execute SQL reports'),
3199                 (16, 'create_reports', 'Create SQL Reports')
3200         ");
3201
3202     print "Upgrade to $DBversion done (granular permissions for guided reports added)\n";
3203     SetVersion ($DBversion);
3204 }
3205
3206 $DBversion = "3.01.00.091";
3207 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3208 $dbh->do("
3209         UPDATE `systempreferences` SET `options` = 'holdings|serialcollection|subscriptions'
3210         WHERE `systempreferences`.`variable` = 'opacSerialDefaultTab' LIMIT 1
3211         ");
3212
3213     print "Upgrade to $DBversion done (opac-detail default tag updated)\n";
3214     SetVersion ($DBversion);
3215 }
3216
3217 $DBversion = "3.01.00.092";
3218 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3219     if (C4::Context->preference("opaclanguages") =~ /fr/) {
3220         $dbh->do(qq{
3221 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');
3222         });
3223         }else{
3224         $dbh->do(qq{
3225 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');
3226         });
3227         }
3228     print "Upgrade to $DBversion done (Added RoutingListAddReserves syspref)\n";
3229     SetVersion ($DBversion);
3230 }
3231
3232 $DBversion = "3.01.00.093";
3233 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3234         $dbh->do(qq{
3235         ALTER TABLE biblioitems ADD INDEX issn_idx (issn);
3236         });
3237     print "Upgrade to $DBversion done (added index to ISSN)\n";
3238     SetVersion ($DBversion);
3239 }
3240
3241 $DBversion = "3.01.00.094";
3242 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3243         $dbh->do(qq{
3244         ALTER TABLE aqbasketgroups ADD deliveryplace VARCHAR(10) default NULL, ADD deliverycomment VARCHAR(255) default NULL;
3245         });
3246
3247     print "Upgrade to $DBversion done (adding deliveryplace deliverycomment to basketgroups)\n";
3248     SetVersion ($DBversion);
3249 }
3250
3251 $DBversion = "3.01.00.095";
3252 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3253         $dbh->do(qq{
3254         ALTER TABLE items ADD stocknumber VARCHAR(32) DEFAULT NULL COMMENT "stores the inventory number";
3255         });
3256         $dbh->do(qq{
3257         ALTER TABLE items ADD UNIQUE INDEX itemsstocknumberidx (stocknumber);
3258         });
3259         $dbh->do(qq{
3260         ALTER TABLE deleteditems ADD stocknumber VARCHAR(32) DEFAULT NULL COMMENT "stores the inventory number of deleted items";
3261         });
3262         $dbh->do(qq{
3263         ALTER TABLE deleteditems ADD UNIQUE INDEX deleteditemsstocknumberidx (stocknumber);
3264         });
3265         if (C4::Context->preference('marcflavour') eq 'UNIMARC'){
3266                 $dbh->do(qq{
3267         INSERT IGNORE INTO marc_subfield_structure (frameworkcode,tagfield, tagsubfield, tab, repeatable, mandatory,kohafield)
3268         SELECT DISTINCT (frameworkcode),995,"j",10,0,0,"items.stocknumber" from biblio_framework ;
3269                 });
3270                 #Previously, copynumber was used as stocknumber
3271                 $dbh->do(qq{
3272         UPDATE items set stocknumber=copynumber;
3273                 });
3274                 $dbh->do(qq{
3275         UPDATE items set copynumber=NULL;
3276                 });
3277         }
3278     print "Upgrade to $DBversion done (stocknumber field added)\n";
3279     SetVersion ($DBversion);
3280 }
3281
3282 $DBversion = "3.01.00.096";
3283 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3284     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OrderPdfTemplate','','Uploads a PDF template to use for printing baskets','NULL','Upload')");
3285     $dbh->do("UPDATE systempreferences SET variable='OrderPdfFormat' WHERE variable='pdfformat'");
3286     print "Upgrade to $DBversion done (PDF orders system preferences added and updated)\n";
3287     SetVersion ($DBversion);
3288 }
3289
3290 $DBversion = "3.01.00.097";
3291 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3292         $dbh->do(qq{
3293         ALTER TABLE aqbasketgroups ADD billingplace VARCHAR(10) NOT NULL AFTER deliverycomment;
3294         });
3295
3296     print "Upgrade to $DBversion done (Adding billingplace to aqbasketgroups)\n";
3297     SetVersion ($DBversion);
3298 }
3299
3300 $DBversion = "3.01.00.098";
3301 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3302         $dbh->do(qq{
3303         ALTER TABLE auth_subfield_structure MODIFY frameworkcode VARCHAR(10) NULL;
3304         });
3305
3306     print "Upgrade to $DBversion done (changing frameworkcode length in auth_subfield_structure)\n";
3307     SetVersion ($DBversion);
3308 }
3309
3310 $DBversion = "3.01.00.099";
3311 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3312         $dbh->do(qq{
3313                 INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3314                 (9, 'edit_catalogue', 'Edit catalogue'),
3315                 (9, 'fast_cataloging', 'Fast cataloging')
3316         });
3317
3318     print "Upgrade to $DBversion done (granular permissions for cataloging added)\n";
3319     SetVersion ($DBversion);
3320 }
3321
3322 $DBversion = "3.01.00.100";
3323 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3324         $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')");
3325         print "Upgrade to $DBversion done (added CAS authentication system preferences)\n";
3326     SetVersion ($DBversion);
3327 }
3328
3329 $DBversion = "3.01.00.101";
3330 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3331         $dbh->do(
3332         "INSERT INTO systempreferences
3333            (variable, value, options, explanation, type)
3334          VALUES (
3335             'OverdueNoticeBcc', '', '',
3336             'Email address to Bcc outgoing notices sent by email',
3337             'free')
3338          ");
3339         print "Upgrade to $DBversion done (added OverdueNoticeBcc system preferences)\n";
3340     SetVersion ($DBversion);
3341 }
3342 $DBversion = "3.01.00.102";
3343 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3344     $dbh->do(
3345     "UPDATE permissions set description = 'Edit catalog (Modify bibliographic/holdings data)' where module_bit = 9 and code = 'edit_catalogue'"
3346     );
3347         print "Upgrade to $DBversion done (fixed spelling error in edit_catalogue permission)\n";
3348     SetVersion ($DBversion);
3349 }
3350
3351 $DBversion = "3.01.00.103";
3352 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3353         $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES (13, 'moderate_tags', 'Moderate patron tags')");
3354         print "Upgrade to $DBversion done (adding patron permissions for tags tool)\n";
3355     SetVersion ($DBversion);
3356 }
3357
3358 $DBversion = "3.01.00.104";
3359 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3360
3361     my ($maninv_count, $borrnotes_count);
3362     eval { $maninv_count = $dbh->do("SELECT 1 FROM authorised_values WHERE category='MANUAL_INV'"); };
3363     if ($maninv_count == 0) {
3364         $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('MANUAL_INV','Copier Fees','.25')");
3365     }
3366     eval { $borrnotes_count = $dbh->do("SELECT 1 FROM authorised_values WHERE category='BOR_NOTES'"); };
3367     if ($borrnotes_count == 0) {
3368         $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('BOR_NOTES','ADDR','Address Notes')");
3369     }
3370
3371     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('LOC','CART','Book Cart')");
3372     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('LOC','PROC','Processing Center')");
3373
3374         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";
3375         SetVersion ($DBversion);
3376 }
3377
3378
3379 $DBversion = "3.01.00.105";
3380 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3381     $dbh->do("
3382       CREATE TABLE `collections` (
3383         `colId` int(11) NOT NULL auto_increment,
3384         `colTitle` varchar(100) NOT NULL default '',
3385         `colDesc` text NOT NULL,
3386         `colBranchcode` varchar(4) default NULL COMMENT 'branchcode for branch where item should be held.',
3387         PRIMARY KEY  (`colId`)
3388       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3389     ");
3390
3391     $dbh->do("
3392       CREATE TABLE `collections_tracking` (
3393         `ctId` int(11) NOT NULL auto_increment,
3394         `colId` int(11) NOT NULL default '0' COMMENT 'collections.colId',
3395         `itemnumber` int(11) NOT NULL default '0' COMMENT 'items.itemnumber',
3396         PRIMARY KEY  (`ctId`)
3397       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3398     ");
3399     $dbh->do("
3400         INSERT INTO permissions (module_bit, code, description)
3401         VALUES ( 13, 'rotating_collections', 'Manage Rotating collections')" );
3402         print "Upgrade to $DBversion done (added collection and collection_tracking tables for rotating collections functionality)\n";
3403     SetVersion ($DBversion);
3404 }
3405 $DBversion = "3.01.00.106";
3406 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3407         $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' )");
3408         print "Upgrade to $DBversion done (added OpacAddMastheadLibraryPulldown system preferences)\n";
3409     SetVersion ($DBversion);
3410 }
3411
3412 $DBversion = '3.01.00.107';
3413 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3414     my $upgrade_script = C4::Context->config("intranetdir") . "/installer/data/mysql/patroncards_upgrade.pl";
3415     system("perl $upgrade_script");
3416     print "Upgrade to $DBversion done (Migrated labels and patroncards tables and data to new schema.)\n";
3417     SetVersion ($DBversion);
3418 }
3419
3420 $DBversion = '3.01.00.108';
3421 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3422         $dbh->do(qq{
3423     ALTER TABLE `export_format` ADD `csv_separator` VARCHAR( 2 ) NOT NULL AFTER `marcfields` ,
3424     ADD `field_separator` VARCHAR( 2 ) NOT NULL AFTER `csv_separator` ,
3425     ADD `subfield_separator` VARCHAR( 2 ) NOT NULL AFTER `field_separator`
3426     });
3427         print "Upgrade to $DBversion done (added separators for csv export)\n";
3428     SetVersion ($DBversion);
3429 }
3430
3431 $DBversion = "3.01.00.109";
3432 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3433         $dbh->do(qq{
3434         ALTER TABLE `export_format` ADD `encoding` VARCHAR(255) NOT NULL AFTER `subfield_separator`
3435         });
3436         print "Upgrade to $DBversion done (added encoding for csv export)\n";
3437     SetVersion ($DBversion);
3438 }
3439
3440 $DBversion = '3.01.00.110';
3441 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3442     $dbh->do('ALTER TABLE `categories` ADD COLUMN `enrolmentperioddate` DATE NULL DEFAULT NULL AFTER `enrolmentperiod`');
3443     print "Upgrade to $DBversion done (Add enrolment period date support)\n";
3444     SetVersion ($DBversion);
3445 }
3446
3447 $DBversion = '3.01.00.111';
3448 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3449     print "Upgrade to $DBversion done (mark DBrev for 3.2-alpha release)\n";
3450     SetVersion ($DBversion);
3451 }
3452
3453 $DBversion = '3.01.00.112';
3454 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3455         $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');");
3456         print "Upgrade to $DBversion done ( added Show Spine Label Printer on Bib Items Details preferences )\n";
3457     SetVersion ($DBversion);
3458 }
3459
3460 $DBversion = '3.01.00.113';
3461 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3462     my $value = C4::Context->preference("XSLTResultsDisplay");
3463     $dbh->do(
3464         "INSERT INTO systempreferences (variable,value,type)
3465          VALUES('OPACXSLTResultsDisplay',?,'YesNo')", {}, $value ? 1 : 0);
3466     $value = C4::Context->preference("XSLTDetailsDisplay");
3467     $dbh->do(
3468         "INSERT INTO systempreferences (variable,value,type)
3469          VALUES('OPACXSLTDetailsDisplay',?,'YesNo')", {}, $value ? 1 : 0);
3470     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";
3471     SetVersion ($DBversion);
3472 }
3473
3474 $DBversion = '3.01.00.114';
3475 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3476     $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')");
3477     $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')");
3478     $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')");
3479         print "Upgrade to $DBversion done ( Added AutoSelfCheckAllowed, AutoSelfCheckID, and AutoShelfCheckPass system preference )\n";
3480     SetVersion ($DBversion);
3481 }
3482
3483 $DBversion = '3.01.00.115';
3484 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3485     $dbh->do('UPDATE aqorders SET quantityreceived = 0 WHERE quantityreceived IS NULL');
3486     $dbh->do('ALTER TABLE aqorders MODIFY COLUMN quantityreceived smallint(6) NOT NULL DEFAULT 0');
3487         print "Upgrade to $DBversion done ( Default aqorders.quantityreceived to 0 )\n";
3488     SetVersion ($DBversion);
3489 }
3490
3491 $DBversion = '3.01.00.116';
3492 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3493         if (C4::Context->preference('OrderPdfFormat') eq 'pdfformat::example'){
3494                 $dbh->do("UPDATE `systempreferences` set value='pdfformat::layout2pages' WHERE variable='OrderPdfFormat'");
3495         }
3496         print "Upgrade to $DBversion done (corrected default OrderPdfFormat value if still set wrong )\n";
3497     SetVersion ($DBversion);
3498 }
3499
3500 $DBversion = '3.01.00.117';
3501 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3502     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'por' WHERE rfc4646_subtag='pt' ");
3503     print "Upgrade to $DBversion done (corrected ISO 639-2 language code for Portuguese)\n";
3504     SetVersion ($DBversion);
3505 }
3506
3507 $DBversion = '3.01.00.118';
3508 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3509     my ($count) = $dbh->selectrow_array("SELECT count(*) FROM information_schema.columns
3510                                          WHERE table_name = 'aqbudgets_planning'
3511                                          AND column_name = 'display'");
3512     if ($count < 1) {
3513         $dbh->do("ALTER TABLE aqbudgets_planning ADD COLUMN display tinyint(1) DEFAULT 1");
3514     }
3515     print "Upgrade to $DBversion done (bug 4203: add display column to aqbudgets_planning if missing)\n";
3516     SetVersion ($DBversion);
3517 }
3518
3519 $DBversion = '3.01.00.119';
3520 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3521     eval{require Locale::Currency::Format};
3522     if (!$@) {
3523         print "Upgrade to $DBversion done (Locale::Currency::Format installed.)\n";
3524         SetVersion ($DBversion);
3525     }
3526     else {
3527         print "Upgrade to $DBversion done.\n";
3528         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";
3529         SetVersion ($DBversion);
3530     }
3531 }
3532
3533 $DBversion = '3.01.00.120';
3534 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3535     $dbh->do(q{
3536 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');
3537 });
3538     print "Upgrade to $DBversion done (bug 1080: add soundon system preference for circulation sounds)\n";
3539     SetVersion ($DBversion);
3540 }
3541
3542 $DBversion = '3.01.00.121';
3543 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3544     $dbh->do("ALTER TABLE `reserves` ADD `expirationdate` DATE DEFAULT NULL");
3545     $dbh->do("ALTER TABLE `reserves` ADD `lowestPriority` tinyint(1) NOT NULL");
3546     $dbh->do("ALTER TABLE `old_reserves` ADD `expirationdate` DATE DEFAULT NULL");
3547     $dbh->do("ALTER TABLE `old_reserves` ADD `lowestPriority` tinyint(1) NOT NULL");
3548     print "Upgrade to $DBversion done ( Added Additional Fields to Reserves tables )\n";
3549     SetVersion ($DBversion);
3550 }
3551
3552 $DBversion = '3.01.00.122';
3553 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3554     $dbh->do(q{
3555       INSERT INTO systempreferences (variable,value,explanation,options,type)
3556       VALUES ('OAI-PMH:ConfFile', '', 'If empty, Koha OAI Server operates in normal mode, otherwise it operates in extended mode.','','File');
3557 });
3558     print "Upgrade to $DBversion done. — Add a new system preference OAI-PMF:ConfFile\n";
3559     SetVersion ($DBversion);
3560 }
3561
3562 $DBversion = "3.01.00.123";
3563 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3564     $dbh->do("INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3565         (6, 'place_holds', 'Place holds for patrons')");
3566     $dbh->do("INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3567         (6, 'modify_holds_priority', 'Modify holds priority')");
3568     $dbh->do("UPDATE `userflags` SET `flagdesc` = 'Place and modify holds for patrons' WHERE `flag` = 'reserveforothers'");
3569     print "Upgrade to $DBversion done (Add granular permission for holds modification and update description of reserveforothers permission)\n";
3570     SetVersion ($DBversion);
3571 }
3572
3573 $DBversion = '3.01.00.124';
3574 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3575     $dbh->do("
3576         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>>).');
3577     ");
3578     print "Upgrade to $DBversion done (bug 3242: add HOLDPLACED letter template, which is used when emailLibrarianWhenHoldIsPlaced is enabled)\n";
3579     SetVersion ($DBversion);
3580 }
3581
3582 $DBversion = '3.01.00.125';
3583 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3584     $dbh->do("
3585         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' );
3586     ");
3587     $dbh->do("
3588         INSERT INTO message_transport_types (message_transport_type) values ('print');
3589     ");
3590     print "Upgrade to $DBversion done (bug 3482: Printable hold and overdue notices)\n";
3591     SetVersion ($DBversion);
3592 }
3593
3594 $DBversion = "3.01.00.126";
3595 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3596         $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')");
3597         $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')");
3598
3599     print "Upgrade to $DBversion done (Adding ILS-DI updates and ILS-DI:AuthorizedIPs)\n";
3600     SetVersion ($DBversion);
3601 }
3602
3603 $DBversion = '3.01.00.127';
3604 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3605     $dbh->do("ALTER TABLE messages CHANGE branchcode branchcode varchar(10);");
3606     print "Upgrade to $DBversion done (bug 4190: messages in patron account did not work with branchcodes > 4)\n";
3607     SetVersion ($DBversion);
3608 }
3609
3610 $DBversion = '3.01.00.128';
3611 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3612     $dbh->do('CREATE INDEX budget_id ON aqorders (budget_id );');
3613     print "Upgrade to $DBversion done (bug 4331: index orders by budget_id)\n";
3614     SetVersion ($DBversion);
3615 }
3616
3617 $DBversion = "3.01.00.129";
3618 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3619         $dbh->do("UPDATE `permissions` SET `code` = 'items_batchdel' WHERE `permissions`.`module_bit` =13 AND `permissions`.`code` = 'batchdel' LIMIT 1 ;");
3620         $dbh->do("UPDATE `permissions` SET `code` = 'items_batchmod' WHERE `permissions`.`module_bit` =13 AND `permissions`.`code` = 'batchmod' LIMIT 1 ;");
3621         print "Upgrade to $DBversion done (Change permissions names for item batch modification / deletion)\n";
3622
3623     SetVersion ($DBversion);
3624 }
3625
3626 $DBversion = "3.01.00.130";
3627 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3628     $dbh->do("UPDATE reserves SET expirationdate = NULL WHERE expirationdate = '0000-00-00'");
3629     print "Upgrade to $DBversion done (change reserves.expirationdate values of 0000-00-00 to NULL (bug 1532)\n";
3630     SetVersion ($DBversion);
3631 }
3632
3633 $DBversion = "3.01.00.131";
3634 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3635         $dbh->do(q{
3636 INSERT IGNORE INTO message_transport_types (message_transport_type) VALUES ('print'),('feed');
3637     });
3638     print "Upgrade to $DBversion done (adding print and feed message transport types)\n";
3639     SetVersion ($DBversion);
3640 }
3641
3642 $DBversion = "3.01.00.132";
3643 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3644         $dbh->do(q{
3645     ALTER TABLE language_descriptions ADD INDEX subtag_type_lang (subtag, type, lang);
3646     });
3647     print "Upgrade to $DBversion done (Adding index to language_descriptions table)\n";
3648     SetVersion ($DBversion);
3649 }
3650
3651 $DBversion = '3.01.00.133';
3652 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3653     $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')");
3654     print "Upgrade to $DBversion done (bug 4405: added OverduesBlockCirc syspref to control whether circulation is blocked if a borrower has overdues)\n";
3655     SetVersion ($DBversion);
3656 }
3657
3658 $DBversion = '3.01.00.134';
3659 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3660     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('DisplayMultiPlaceHold','1','Display the ability to place multiple holds or not','','YesNo')");
3661     print "Upgrade to $DBversion done (adding syspref DisplayMultiPlaceHold to control whether multiple holds can be placed from the search results page)\n";
3662     SetVersion ($DBversion);
3663 }
3664
3665 $DBversion = '3.01.00.135';
3666 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3667     $dbh->do("
3668         INSERT INTO `letter` (module, code, name, title, content) VALUES
3669 ('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')
3670 ");
3671     print "Upgrade to $DBversion done (bug 4377: added HOLD_PRINT message template)\n";
3672     SetVersion ($DBversion);
3673 }
3674
3675 $DBversion = '3.01.00.136';
3676 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3677     $dbh->do(qq{
3678 INSERT INTO permissions (module_bit, code, description) VALUES
3679    ( 9, 'edit_items', 'Edit Items');});
3680     print "Upgrade to $DBversion done (Adding a new permission to edit items)\n";
3681     SetVersion ($DBversion);
3682 }
3683
3684 $DBversion = "3.01.00.137";
3685 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3686         $dbh->do("
3687           INSERT INTO permissions (module_bit, code, description) VALUES
3688           (15, 'check_expiration', 'Check the expiration of a serial'),
3689           (15, 'claim_serials', 'Claim missing serials'),
3690           (15, 'create_subscription', 'Create a new subscription'),
3691           (15, 'delete_subscription', 'Delete an existing subscription'),
3692           (15, 'edit_subscription', 'Edit an existing subscription'),
3693           (15, 'receive_serials', 'Serials receiving'),
3694           (15, 'renew_subscription', 'Renew a subscription'),
3695           (15, 'routing', 'Routing');
3696                  ");
3697     print "Upgrade to $DBversion done (adding granular permissions for serials)\n";
3698     SetVersion ($DBversion);
3699 }
3700
3701 $DBversion = "3.01.00.138";
3702 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3703     $dbh->do("DELETE FROM systempreferences WHERE variable = 'GranularPermissions'");
3704     print "Upgrade to $DBversion done (bug 4896: removing GranularPermissions syspref; use of granular permissions is now the default)\n";
3705     SetVersion ($DBversion);
3706 }
3707
3708 $DBversion = '3.01.00.139';
3709 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3710     $dbh->do("ALTER TABLE message_attributes CHANGE message_name message_name varchar(40);");
3711     print "Upgrade to $DBversion done (bug 3682: change message_name from varchar(20) to varchar(40))\n";
3712     SetVersion ($DBversion);
3713 }
3714
3715 $DBversion = '3.01.00.140';
3716 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3717     $dbh->do("UPDATE systempreferences SET value = '0' WHERE variable = 'TagsModeration' AND value is NULL");
3718     print "Upgrade to $DBversion done (bug 4312 TagsModeration changed from NULL to 0)\n";
3719     SetVersion ($DBversion);
3720 }
3721
3722 $DBversion = '3.01.00.141';
3723 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3724     $dbh->do(qq{DELETE FROM message_attributes WHERE message_attribute_id=3;});
3725     $dbh->do(qq{DELETE FROM letter WHERE code='EVENT' AND title='Upcoming Library Event';});
3726     print "Upgrade to $DBversion done Remove upcoming events messaging option (bug 2434)\n";
3727     SetVersion ($DBversion);
3728 }
3729
3730 $DBversion = '3.01.00.142';
3731 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3732     $dbh->do(qq{DELETE FROM message_transports WHERE message_attribute_id=3;});
3733     print "Upgrade to $DBversion done (Remove upcoming events messaging option part 2 (bug 2434))\n";
3734     SetVersion ($DBversion);
3735 }
3736
3737 $DBversion = '3.01.00.143';
3738 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3739     $dbh->do(qq{CREATE INDEX auth_value_idx ON authorised_values (authorised_value)});
3740     $dbh->do(qq{CREATE INDEX auth_val_cat_idx ON borrower_attribute_types (authorised_value_category)});
3741     print "Upgrade to $DBversion done (Create index on authorised_values and borrower_attribute_types (bug 4139))\n";
3742     SetVersion ($DBversion);
3743 }
3744
3745 $DBversion = '3.01.00.144';
3746 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3747     $dbh->do(qq{UPDATE systempreferences SET value='normal' where value='default' and variable='IntranetBiblioDefaultView'});
3748     print "Upgrade to $DBversion done (Update the 'default' to 'normal' for the IntranetBiblioDefaultView syspref (bug 5007))\n";
3749     SetVersion ($DBversion);
3750 }
3751
3752 $DBversion = "3.01.00.145";
3753 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3754     $dbh->do("ALTER TABLE borrowers ADD KEY `guarantorid` (guarantorid);");
3755     print "Upgrade to $DBversion done (Add index on guarantorid)\n";
3756     SetVersion ($DBversion);
3757 }
3758
3759 $DBversion = '3.01.00.999';
3760 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3761     print "Upgrade to $DBversion done (3.2.0 release candidate)\n";
3762     SetVersion ($DBversion);
3763 }
3764
3765 $DBversion = "3.02.00.000";
3766 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3767     my $value = $dbh->selectrow_array("SELECT value FROM systempreferences WHERE variable = 'HomeOrHoldingBranch'");
3768     $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');");
3769     print "Upgrade to $DBversion done (Add HomeOrHoldingBranchReturn system preference)\n";
3770     SetVersion ($DBversion);
3771 }
3772
3773 $DBversion = "3.02.00.001";
3774 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3775     $dbh->do(q{DELETE FROM systempreferences WHERE variable IN (
3776                 'holdCancelLength',
3777                 'PINESISBN',
3778                 'sortbynonfiling',
3779                 'TemplateEncoding',
3780                 'OPACSubscriptionDisplay',
3781                 'OPACDisplayExtendedSubInfo',
3782                 'OAI-PMH:Set',
3783                 'OAI-PMH:Subset',
3784                 'libraryAddress',
3785                 'kohaspsuggest',
3786                 'OrderPdfTemplate',
3787                 'marc',
3788                 'acquisitions',
3789                 'MIME')
3790                }
3791     );
3792     print "Upgrade to $DBversion done (bug 3756: remove disused system preferences)\n";
3793     SetVersion ($DBversion);
3794 }
3795
3796 $DBversion = "3.02.00.002";
3797 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3798     $dbh->do(q{DELETE FROM systempreferences WHERE variable = 'OpacPrivacy'});
3799     print "Upgrade to $DBversion done (bug 3881: remove unused OpacPrivacy system preference)\n";
3800     SetVersion ($DBversion);
3801 }
3802
3803 $DBversion = "3.02.00.003";
3804 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3805     $dbh->do(q{UPDATE systempreferences SET variable = 'ILS-DI:AuthorizedIPs' WHERE variable = 'ILS-DI:Authorized_IPs'});
3806     print "Upgrade to $DBversion done (correct ILS-DI:AuthorizedIPs)\n";
3807     SetVersion ($DBversion);
3808 }
3809
3810 $DBversion = "3.02.00.004";
3811 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3812     print "Upgrade to $DBversion done (3.2.0 general release)\n";
3813     SetVersion ($DBversion);
3814 }
3815 # This is the point where 3.2.x and master diverged, we can use $original_version to make sure we don't
3816
3817 # apply updates that have already been done
3818
3819 $DBversion = "3.03.00.001";
3820 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.005")) {
3821     $dbh->do("DELETE FROM subscriptionroutinglist WHERE borrowernumber IS NULL;");
3822     $dbh->do("ALTER TABLE subscriptionroutinglist MODIFY COLUMN `borrowernumber` int(11) NOT NULL;");
3823     $dbh->do("DELETE FROM subscriptionroutinglist WHERE subscriptionid IS NULL;");
3824     $dbh->do("ALTER TABLE subscriptionroutinglist MODIFY COLUMN `subscriptionid` int(11) NOT NULL;");
3825     $dbh->do("CREATE TEMPORARY TABLE del_subscriptionroutinglist
3826               SELECT s1.routingid FROM subscriptionroutinglist s1
3827               WHERE EXISTS (SELECT * FROM subscriptionroutinglist s2
3828                             WHERE s2.borrowernumber = s1.borrowernumber
3829                             AND   s2.subscriptionid = s1.subscriptionid
3830                             AND   s2.routingid < s1.routingid);");
3831     $dbh->do("DELETE FROM subscriptionroutinglist
3832               WHERE routingid IN (SELECT routingid FROM del_subscriptionroutinglist);");
3833     $dbh->do("ALTER TABLE subscriptionroutinglist ADD UNIQUE (subscriptionid, borrowernumber);");
3834     $dbh->do("ALTER TABLE subscriptionroutinglist
3835                 ADD CONSTRAINT `subscriptionroutinglist_ibfk_1` FOREIGN KEY (`borrowernumber`)
3836                 REFERENCES `borrowers` (`borrowernumber`)
3837                 ON DELETE CASCADE ON UPDATE CASCADE");
3838     $dbh->do("ALTER TABLE subscriptionroutinglist
3839                 ADD CONSTRAINT `subscriptionroutinglist_ibfk_2` FOREIGN KEY (`subscriptionid`)
3840                 REFERENCES `subscription` (`subscriptionid`)
3841                 ON DELETE CASCADE ON UPDATE CASCADE");
3842     print "Upgrade to $DBversion done (Make subscriptionroutinglist more strict)\n";
3843     SetVersion ($DBversion);
3844 }
3845
3846 $DBversion = '3.03.00.002';
3847 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.006")) {
3848     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='arm' WHERE rfc4646_subtag='hy';");
3849     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='eng' WHERE rfc4646_subtag='en';");
3850     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'fi','fin');");
3851     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='fre' WHERE rfc4646_subtag='fr';");
3852     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'lo','lao');");
3853     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='ita' WHERE rfc4646_subtag='it';");
3854     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'sr','srp');");
3855     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'tet','tet');");
3856     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'ur','urd');");
3857
3858     print "Upgrade to $DBversion done (Correct language mappings)\n";
3859     SetVersion ($DBversion);
3860 }
3861
3862 $DBversion = '3.03.00.003';
3863 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.007")) {
3864     $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');");
3865     print "Upgrade to $DBversion done (Add UseTablesortForCirc syspref)\n";
3866     SetVersion ($DBversion);
3867 }
3868
3869 $DBversion = '3.03.00.004';
3870 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.001")) {
3871     my $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'ACCEPTED');
3872     $dbh->do(q/
3873 INSERT INTO `letter`
3874 (module, code, name, title, content)
3875 VALUES
3876 ('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>>')
3877 /) unless $count > 0;
3878     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'AVAILABLE');
3879     $dbh->do(q/
3880 INSERT INTO `letter`
3881 (module, code, name, title, content)
3882 VALUES
3883 ('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>>')
3884 /) unless $count > 0;
3885     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'ORDERED');
3886     $dbh->do(q/
3887 INSERT INTO `letter`
3888 (module, code, name, title, content)
3889 VALUES
3890 ('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>>')
3891 /) unless $count > 0;
3892     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'REJECTED');
3893     $dbh->do(q/
3894 INSERT INTO `letter`
3895 (module, code, name, title, content)
3896 VALUES
3897 ('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>>')
3898 /) unless $count > 0;
3899     print "Upgrade to $DBversion done (bug 5127: add default templates for suggestion status change notifications)\n";
3900     SetVersion ($DBversion);
3901 };
3902
3903 $DBversion = '3.03.00.005';
3904 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3905     $dbh->do("update `systempreferences` set options='whitespace|T-prefix|cuecat|libsuite8' where variable='itemBarcodeInputFilter'");
3906     print "Upgrade to $DBversion done (Add itemBarcodeInputFilter choice libsuite8)\n";
3907 }
3908
3909 $DBversion = '3.03.00.006';
3910 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.002")) {
3911     $dbh->do("ALTER TABLE deletedborrowers ADD `privacy` int(11) AFTER smsalertnumber;");
3912     $dbh->do("ALTER TABLE deletedborrowers CHANGE `cardnumber` `cardnumber` varchar(16);");
3913     print "Upgrade to $DBversion done (Fix differences between borrowers and deletedborrowers)\n";
3914     SetVersion ($DBversion);
3915 }
3916
3917 $DBversion = '3.03.00.007';
3918 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3919     $dbh->do("ALTER table suggestions ADD quantity SMALLINT(6) default NULL,
3920                 ADD currency VARCHAR(3) default NULL,
3921                 ADD price DECIMAL(28,6) default NULL,
3922                 ADD total DECIMAL(28,6) default NULL;
3923                 ");
3924     print "Upgrade to $DBversion done (Added acq related columns to suggestions)\n";
3925     SetVersion ($DBversion);
3926 }
3927
3928 $DBversion = '3.03.00.008';
3929 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3930     $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')");
3931     print "Upgrade to $DBversion done (adding syspref OPACNoResultsFound to control what displays when no results are found for a search in the OPAC.)\n";
3932     SetVersion ($DBversion);
3933 }
3934
3935 $DBversion = '3.03.00.009';
3936 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.003")) {
3937     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('IntranetUserCSS','','Add CSS to be included in the Intranet',NULL,'free')");
3938     print "Upgrade to $DBversion done (Add IntranetUserCSS syspref)\n";
3939     SetVersion ($DBversion);
3940 }
3941
3942 $DBversion = "3.03.00.010";
3943 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.02.001")) {
3944     $dbh->do("UPDATE `marc_subfield_structure` SET liblibrarian = 'Distance from earth' WHERE liblibrarian = 'Distrance from earth' AND tagfield = '034' AND tagsubfield = 'r';");
3945     $dbh->do("UPDATE `marc_subfield_structure` SET libopac = 'Distance from earth' WHERE libopac = 'Distrance from earth' AND tagfield = '034' AND tagsubfield = 'r';");
3946     print "Upgrade to $DBversion done (Fix misspelled 034r subfield in MARC21 Frameworks)\n";
3947     SetVersion ($DBversion);
3948 }
3949
3950 $DBversion = "3.03.00.011";
3951 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3952     $dbh->do("UPDATE aqbooksellers SET gstrate=NULL WHERE gstrate=0.0");
3953     print "Upgrade to $DBversion done (Bug 5186: allow GST rate to be set to 0)\n";
3954     SetVersion ($DBversion);
3955 }
3956
3957 $DBversion = "3.03.00.012";
3958 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3959    $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')");
3960    print "Upgrade to $DBversion done (Bug 2142: maxItemsInSearchResults syspref resurrected)\n";
3961    SetVersion ($DBversion);
3962 }
3963
3964 $DBversion = "3.03.00.013";
3965 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3966     $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')");
3967     print "Upgrade to $DBversion done (added 'OpacPublic' syspref)\n";
3968    SetVersion ($DBversion);
3969 }
3970
3971 $DBversion = "3.03.00.014";
3972 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3973     $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')");
3974     $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')");
3975     $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')");
3976     print "Upgrade to $DBversion done (Add flexible shelf browser constraints)\n";
3977     SetVersion ($DBversion);
3978 }
3979
3980 $DBversion = "3.03.00.015";
3981 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3982     if ( C4::Context->preference("marcflavour") eq "MARC21" ) {
3983         my $sth = $dbh->prepare(
3984 "INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`,
3985                              `tab`, `authorised_value`, `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`)
3986                              VALUES ( ?, '9', '9 (RLIN)', '9 (RLIN)', 0, 0, '', 6, '', '', '', 0, -5, '', '', '', NULL)"
3987         );
3988         $sth->execute('648');
3989         $sth->execute('654');
3990         $sth->execute('655');
3991         $sth->execute('656');
3992         $sth->execute('657');
3993         $sth->execute('658');
3994         $sth->execute('662');
3995         $sth->finish;
3996         print
3997 "Upgrade to $DBversion done (Bug 5619: Add subfield 9 to marc21 648,654,655,656,657,658,662)\n";
3998     }
3999     SetVersion($DBversion);
4000 }
4001
4002 $DBversion = '3.03.00.016';
4003 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4004     # reimplement OpacPrivacy system preference
4005     $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')");
4006     $dbh->do("ALTER TABLE `borrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
4007     $dbh->do("ALTER TABLE `deletedborrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
4008     print "Upgrade to $DBversion done (OpacPrivacy reimplementation)\n";
4009     SetVersion($DBversion);
4010 };
4011
4012 $DBversion = '3.03.00.017';
4013 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.001")) {
4014     $dbh->do("ALTER TABLE  `currency` CHANGE `rate` `rate` FLOAT( 15, 5 ) NULL DEFAULT NULL;");
4015     print "Upgrade to $DBversion done (Enable currency rates >= 100)\n";
4016     SetVersion ($DBversion);
4017 }
4018
4019 $DBversion = '3.03.00.018';
4020 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.002")) {
4021     $dbh->do( q|update language_descriptions set description = 'Nederlands' where lang = 'nl' and subtag = 'nl'|);
4022     $dbh->do( q|update language_descriptions set description = 'Dansk' where lang = 'da' and subtag = 'da'|);
4023     print "Upgrade to $DBversion done (Correct language descriptions)\n";
4024     SetVersion ($DBversion);
4025 }
4026
4027 $DBversion = '3.03.00.019';
4028 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.003")) {
4029     # Fix bokmål
4030     $dbh->do("UPDATE language_subtag_registry SET description = 'Norwegian bokm&#229;l' WHERE subtag = 'nb';");
4031     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'nb','nob');");
4032     $dbh->do("UPDATE language_descriptions SET description = 'Norsk bokm&#229;l' WHERE subtag = 'nb' AND lang = 'nb';");
4033     $dbh->do("UPDATE language_descriptions SET description = 'Norwegian bokm&#229;l' WHERE subtag = 'nb' AND lang = 'en';");
4034     $dbh->do("UPDATE language_descriptions SET description = 'Norvégien bokm&#229;l' WHERE subtag = 'nb' AND lang = 'fr';");
4035     # Add nynorsk
4036     $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'nn', 'language', 'Norwegian nynorsk','2011-02-14' )");
4037     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'nn','nno')");
4038     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'nb', 'Norsk nynorsk')");
4039     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'nn', 'Norsk nynorsk')");
4040     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'en', 'Norwegian nynorsk')");
4041     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'fr', 'Norvégien nynorsk')");
4042     print "Upgrade to $DBversion done (Correct language descriptions for Norwegian)\n";
4043     SetVersion ($DBversion);
4044 }
4045
4046 $DBversion = '3.03.00.020';
4047 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4048     $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')");
4049     $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')");
4050     print "Upgrade to $DBversion done (Bug 5811: Add sysprefs controlling overriding fines)\n";
4051     SetVersion($DBversion);
4052 };
4053
4054 $DBversion = '3.03.00.021';
4055 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.001")) {
4056     $dbh->do("ALTER TABLE items MODIFY enumchron TEXT");
4057     $dbh->do("ALTER TABLE deleteditems MODIFY enumchron TEXT");
4058     print "Upgrade to $DBversion done (bug 5642: longer serial enumeration)\n";
4059     SetVersion ($DBversion);
4060 }
4061
4062 $DBversion = '3.03.00.022';
4063 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4064     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('AuthoritiesLog','0','If ON, log edit/create/delete actions on authorities.','','YesNo');");
4065     print "Upgrade to $DBversion done (Add AuthoritiesLog syspref)\n";
4066     SetVersion ($DBversion);
4067 }
4068
4069 # due to a mismatch in kohastructure.sql some koha will have missing columns in aqbasketgroup
4070 # this attempts to fix that
4071 $DBversion = '3.03.00.023';
4072 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.002")) {
4073     my $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'billingplace'");
4074     $sth->execute;
4075     $dbh->do("ALTER TABLE aqbasketgroups ADD billingplace VARCHAR(10)") if ! $sth->fetchrow_hashref;
4076     $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'deliveryplace'");
4077     $sth->execute;
4078     $dbh->do("ALTER TABLE aqbasketgroups ADD deliveryplace VARCHAR(10)") if ! $sth->fetchrow_hashref;
4079     $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'deliverycomment'");
4080     $sth->execute;
4081     $dbh->do("ALTER TABLE aqbasketgroups ADD deliverycomment VARCHAR(255)") if ! $sth->fetchrow_hashref;
4082     print "Upgrade to $DBversion done (Reconcile aqbasketgroups)\n";
4083     SetVersion ($DBversion);
4084 }
4085
4086 $DBversion = '3.03.00.024';
4087 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4088     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('TraceCompleteSubfields','0','Force subject tracings to only match complete subfields.','0','YesNo')");
4089     $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')");
4090     print "Upgrade to $DBversion done (Add syspref to force whole-subfield matching on subject tracings)\n";
4091     SetVersion($DBversion);
4092 };
4093
4094 $DBversion = "3.03.00.025";
4095 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4096     $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')");
4097     print "Upgrade to $DBversion done (Add syspref to control if user can choose pickup branch for holds)\n";
4098     SetVersion ($DBversion);
4099 }
4100
4101 $DBversion = '3.03.00.026';
4102 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.003")) {
4103     $dbh->do("UPDATE `message_attributes` SET message_name='Item Due' WHERE message_attribute_id=1 AND message_name LIKE 'Item DUE'");
4104         print "Upgrade to $DBversion done ( fix capitalization in message type )\n";
4105     SetVersion ($DBversion);
4106 }
4107
4108 $DBversion = '3.03.00.027';
4109 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4110     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('displayFacetCount', '0', NULL, NULL, 'YesNo')");
4111     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('maxRecordsForFacets', '20', NULL, NULL, 'Integer')");
4112     print "Upgrade to $DBversion done (Preferences for facet count)\n";
4113     SetVersion ($DBversion);
4114 }
4115
4116 $DBversion = "3.03.00.028";
4117 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4118     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('FacetLabelTruncationLength', 20, 'Truncate facets length to','','free')");
4119     print "Upgrade to $DBversion done (Add FacetLabelTruncationLength syspref to control facets displayed length)\n";
4120     SetVersion ($DBversion);
4121 }
4122
4123 $DBversion = "3.03.00.029";
4124 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4125     $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')");
4126     print "Upgrade to $DBversion done (Add syspref to control if user can choose branch when making purchase suggestion)\n";
4127     SetVersion ($DBversion);
4128 }
4129
4130 $DBversion = "3.03.00.030";
4131 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4132     $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')");
4133     $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')");
4134     print "Upgrade to $DBversion done (Add sysprefs to control custom favicons)\n";
4135     SetVersion ($DBversion);
4136 }
4137
4138 $DBversion = "3.03.00.031";
4139 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4140     $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');");
4141     print "Upgrade to $DBversion done (Add syspref FineNotifyAtCheckin)\n";
4142     SetVersion ($DBversion);
4143 }
4144
4145 $DBversion = '3.03.00.032';
4146 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4147     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('TraceSubjectSubdivisions', 1, 'Create searches on all subdivisions for subject tracings.','1','YesNo')");
4148     print "Upgrade to $DBversion done ( include subdivisions when generating subject tracing searches )\n";
4149 }
4150
4151
4152 $DBversion = '3.03.00.033';
4153 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4154     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('StaffAuthorisedValueImages', '1', '', NULL, 'YesNo')");
4155     print "Upgrade to $DBversion done (System pref StaffAuthorisedValueImages)\n";
4156     SetVersion ($DBversion);
4157 }
4158
4159 $DBversion = '3.03.00.034';
4160 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4161     $dbh->do("ALTER TABLE `categories` ADD `hidelostitems` tinyint(1) NOT NULL default '0' AFTER `reservefee`");
4162     print "Upgrade to $DBversion done (Add hidelostitems preference to borrower categories)\n";
4163     SetVersion ($DBversion);
4164 }
4165
4166 $DBversion = '3.03.00.035';
4167 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4168     $dbh->do("ALTER TABLE `issuingrules` ADD hardduedate date default NULL AFTER issuelength");
4169     $dbh->do("ALTER TABLE `issuingrules` ADD hardduedatecompare tinyint NOT NULL default 0 AFTER hardduedate");
4170     my $duedate;
4171     if (C4::Context->preference("globalDueDate")) {
4172       $duedate = C4::Dates::format_date_in_iso(C4::Context->preference("globalDueDate"));
4173       $dbh->do("UPDATE `issuingrules` SET hardduedate = '$duedate', hardduedatecompare = 0");
4174     } elsif (C4::Context->preference("ceilingDueDate")) {
4175       $duedate = C4::Dates::format_date_in_iso(C4::Context->preference("ceilingDueDate"));
4176       $dbh->do("UPDATE `issuingrules` SET hardduedate = '$duedate', hardduedatecompare = -1");
4177     }
4178     $dbh->do("DELETE FROM `systempreferences` WHERE variable = 'globalDueDate' OR variable = 'ceilingDueDate'");
4179     print "Upgrade to $DBversion done (Move global and ceiling due dates to Circ Rules level)\n";
4180     SetVersion ($DBversion);
4181 }
4182
4183 $DBversion = '3.03.00.036';
4184 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4185     $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')");
4186     print "Upgrade to $DBversion done ( Make COinS optional in OPAC search results )\n";
4187     SetVersion ($DBversion);
4188 }
4189
4190 $DBversion = '3.03.00.037';
4191 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4192     $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')");
4193     $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')");
4194     print "Upgrade to $DBversion done (Add 'Display856uAsImage' and 'OPACDisplay856uAsImage' syspref)\n";
4195     SetVersion ($DBversion);
4196 }
4197
4198 $DBversion = '3.03.00.038';
4199 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4200     $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')");
4201     $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')");
4202     $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')");
4203     print "Upgrade to $DBversion done ( Add Self-checkout by Login system preferences )\n";
4204 }
4205
4206 $DBversion = "3.03.00.039";
4207 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4208     $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');");
4209     print "Upgrade to $DBversion done (Add syspref ShowReviewer)\n";
4210 }
4211
4212 $DBversion = "3.03.00.040";
4213 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4214     $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');");
4215     print "Upgrade to $DBversion done (Add syspref UseControlNumber)\n";
4216 }
4217
4218 $DBversion = "3.03.00.041";
4219 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4220     $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')");
4221     $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')");
4222     print "Upgrade to $DBversion done (Add sysprefs to control alternate holdings information display)\n";
4223     SetVersion ($DBversion);
4224 }
4225
4226 $DBversion = '3.03.00.042';
4227 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4228     stocknumber_checker();
4229     print "Upgrade to $DBversion done (5860 Index itemstocknumber)\n";
4230     SetVersion ($DBversion);
4231 }
4232
4233 sub stocknumber_checker { #code reused later on
4234   my @row;
4235   #drop the obsolete itemSStocknumber idx if it exists
4236   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemsstocknumberidx'");
4237   $dbh->do("ALTER TABLE `items` DROP INDEX `itemsstocknumberidx`;") if @row;
4238
4239   #check itemstocknumber idx; remove it if it is unique
4240   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemstocknumberidx' AND non_unique=0");
4241   $dbh->do("ALTER TABLE `items` DROP INDEX `itemstocknumberidx`;") if @row;
4242
4243   #add itemstocknumber index non-unique IF it still not exists
4244   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemstocknumberidx'");
4245   $dbh->do("ALTER TABLE items ADD INDEX itemstocknumberidx (stocknumber);") unless @row;
4246 }
4247
4248 $DBversion = "3.03.00.043";
4249 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4250
4251     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib,lib_opac) VALUES ('YES_NO','0','No','No')");
4252     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib,lib_opac) VALUES ('YES_NO','1','Yes','Yes')");
4253
4254         print "Upgrade to $DBversion done ( add generic boolean YES_NO authorised_values pair )\n";
4255         SetVersion ($DBversion);
4256 }
4257
4258 $DBversion = '3.03.00.044';
4259 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4260     $dbh->do("ALTER TABLE `aqbasketgroups` ADD `freedeliveryplace` TEXT NULL AFTER `deliveryplace`;");
4261     print "Upgrade to $DBversion done (adding freedeliveryplace to basketgroups)\n";
4262 }
4263
4264 $DBversion = '3.03.00.045';
4265 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4266     #Remove obsolete columns from aqbooksellers if needed
4267     my $a = $dbh->selectall_hashref('SHOW columns from aqbooksellers','Field');
4268     my $sqldrop="ALTER TABLE aqbooksellers DROP COLUMN ";
4269     foreach(qw/deliverydays followupdays followupscancel invoicedisc nocalc specialty/) {
4270       $dbh->do($sqldrop.$_) if exists $a->{$_};
4271     }
4272     #Remove obsolete column from aqbudgets if needed
4273     #The correct column is budget_notes
4274     $a = $dbh->selectall_hashref('SHOW columns from aqbudgets','Field');
4275     if(exists $a->{budget_description}) {
4276       $dbh->do("ALTER TABLE aqbudgets DROP COLUMN budget_description");
4277     }
4278     print "Upgrade to $DBversion done (Remove obsolete columns from aqbooksellers and aqbudgets if needed)\n";
4279     SetVersion ($DBversion);
4280 }
4281
4282 $DBversion = "3.03.00.046";
4283 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4284     $dbh->do("ALTER TABLE overduerules ALTER delay1 SET DEFAULT NULL, ALTER delay2 SET DEFAULT NULL, ALTER delay3 SET DEFAULT NULL");
4285     print "Upgrade to $DBversion done (Setting NULL default value for delayn columns in table overduerules)\n";
4286     SetVersion($DBversion);
4287 }
4288
4289 $DBversion = '3.03.00.047';
4290 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4291     $dbh->do("ALTER TABLE borrowers ADD `state` mediumtext AFTER city;");
4292     $dbh->do("ALTER TABLE borrowers ADD `B_state` mediumtext AFTER B_city;");
4293     $dbh->do("ALTER TABLE borrowers ADD `altcontactstate` mediumtext AFTER altcontactaddress3;");
4294     $dbh->do("ALTER TABLE deletedborrowers ADD `state` mediumtext AFTER city;");
4295     $dbh->do("ALTER TABLE deletedborrowers ADD `B_state` mediumtext AFTER B_city;");
4296     $dbh->do("ALTER TABLE deletedborrowers ADD `altcontactstate` mediumtext AFTER altcontactaddress3;");
4297     print "Upgrade to $DBversion done (Add state field to patron's addresses)\n";
4298 }
4299
4300 $DBversion = '3.03.00.048';
4301 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4302     $dbh->do("ALTER TABLE branches ADD `branchstate` mediumtext AFTER `branchcity`;");
4303     print "Upgrade to $DBversion done (Add state to branch address)\n";
4304     SetVersion ($DBversion);
4305 }
4306
4307 $DBversion = '3.03.00.049';
4308 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4309     $dbh->do("ALTER TABLE `accountlines` ADD `note` text NULL default NULL");
4310     $dbh->do("ALTER TABLE `accountlines` ADD `manager_id` int( 11 ) NULL ");
4311     print "Upgrade to $DBversion done (adding note and manager_id fields in accountlines table)\n";
4312     SetVersion($DBversion);
4313 }
4314
4315 $DBversion = "3.03.00.050";
4316 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4317     $dbh->do("
4318         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');
4319         ");
4320     print "Upgrade to $DBversion done (Adding OpacHiddenItems syspref)\n";
4321     SetVersion($DBversion);
4322 }
4323
4324 $DBversion = "3.03.00.051";
4325 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4326     print "Upgrade to $DBversion done (Remove spaces and dashes from message_attribute names)\n";
4327     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Due' WHERE message_name='Item Due'");
4328     $dbh->do("UPDATE message_attributes SET message_name = 'Advance_Notice' WHERE message_name='Advance Notice'");
4329     $dbh->do("UPDATE message_attributes SET message_name = 'Hold_Filled' WHERE message_name='Hold Filled'");
4330     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Check_in' WHERE message_name='Item Check-in'");
4331     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Checkout' WHERE message_name='Item Checkout'");
4332     SetVersion ($DBversion);
4333 }
4334
4335 $DBversion = "3.03.00.052";
4336 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4337     $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');");
4338     print "Upgrade to $DBversion done (Add syspref WaitingNotifyAtCheckin)\n";
4339     SetVersion ($DBversion);
4340 }
4341
4342 $DBversion = "3.04.00.000";
4343 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4344     print "Upgrade to $DBversion done Koha 3.4.0 release \n";
4345     SetVersion ($DBversion);
4346 }
4347
4348 $DBversion = "3.05.00.001";
4349 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4350     $dbh->do(qq{
4351     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');
4352     });
4353     print "Upgrade to $DBversion done (Adds New System preference numSearchRSSResults)\n";
4354     SetVersion($DBversion);
4355 }
4356
4357 $DBversion = '3.05.00.002';
4358 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4359     #follow up fix 5860: some installs already past 3.3.0.42
4360     stocknumber_checker();
4361     print "Upgrade to $DBversion done (Fix for stocknumber index)\n";
4362     SetVersion ($DBversion);
4363 }
4364
4365 $DBversion = "3.05.00.003";
4366 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4367     $dbh->do(qq{
4368     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');
4369     });
4370     print "Upgrade to $DBversion done (Adds New System preference OpacRenewalBranch)\n";
4371     SetVersion($DBversion);
4372 }
4373
4374 $DBversion = "3.05.00.004";
4375 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4376     $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');");
4377     print "Upgrade to $DBversion done (Add syspref ShowReviewerPhoto)\n";
4378     SetVersion($DBversion);
4379 }
4380
4381 $DBversion = "3.05.00.005";
4382 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4383     $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');");
4384     print "Upgrade to $DBversion done (Adds pref BasketConfirmations)\n";
4385     SetVersion($DBversion);
4386 }
4387
4388 $DBversion = "3.05.00.006";
4389 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4390     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('MARCAuthorityControlField008', '|| aca||aabn           | a|a     d', NULL, NULL, 'Textarea')");
4391     print "Upgrade to $DBversion done (Add syspref MARCAuthorityControlField008)\n";
4392     SetVersion ($DBversion);
4393 }
4394
4395 $DBversion = "3.05.00.007";
4396 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4397     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpenLibraryCovers',0,'If ON Openlibrary book covers will be show',NULL,'YesNo');");
4398     print "Upgrade to $DBversion done (Add syspref OpenLibraryCovers)\n";
4399     SetVersion($DBversion);
4400 }
4401
4402 $DBversion = "3.05.00.008";
4403 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4404     $dbh->do("ALTER TABLE `cities` ADD `city_state` VARCHAR( 100 ) NULL DEFAULT NULL AFTER  `city_name`;");
4405     $dbh->do("ALTER TABLE `cities` ADD `city_country` VARCHAR( 100 ) NULL DEFAULT NULL AFTER  `city_zipcode`;");
4406     print "Add state and country to cities table corresponding to new columns in borrowers\n";
4407     SetVersion($DBversion);
4408 }
4409
4410 $DBversion = "3.05.00.009";
4411 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4412     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4413               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE borrowernumber IS NULL");
4414     $dbh->do("DELETE FROM issues WHERE borrowernumber IS NULL");
4415
4416     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4417               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE itemnumber IS NULL");
4418     $dbh->do("DELETE FROM issues WHERE itemnumber IS NULL");
4419
4420     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4421               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)");
4422     $dbh->do("DELETE FROM issues WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowernumber = issues.borrowernumber)");
4423
4424     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4425               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)");
4426     $dbh->do("DELETE FROM issues WHERE NOT EXISTS (SELECT * FROM items WHERE itemnumber = issues.itemnumber)");
4427
4428     $dbh->do("ALTER TABLE issues DROP FOREIGN KEY `issues_ibfk_1`");
4429     $dbh->do("ALTER TABLE issues DROP FOREIGN KEY `issues_ibfk_2`");
4430     $dbh->do("ALTER TABLE issues ALTER COLUMN borrowernumber DROP DEFAULT");
4431     $dbh->do("ALTER TABLE issues ALTER COLUMN itemnumber DROP DEFAULT");
4432     $dbh->do("ALTER TABLE issues MODIFY COLUMN borrowernumber int(11) NOT NULL");
4433     $dbh->do("ALTER TABLE issues MODIFY COLUMN itemnumber int(11) NOT NULL");
4434     $dbh->do("ALTER TABLE issues DROP KEY `issuesitemidx`");
4435     $dbh->do("ALTER TABLE issues ADD PRIMARY KEY (`itemnumber`)");
4436     $dbh->do("ALTER TABLE issues ADD CONSTRAINT `issues_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE RESTRICT ON UPDATE CASCADE");
4437     $dbh->do("ALTER TABLE issues ADD CONSTRAINT `issues_ibfk_2` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE RESTRICT ON UPDATE CASCADE");
4438
4439     print "Upgrade to $DBversion done (issues referential integrity)\n";
4440     SetVersion ($DBversion);
4441 }
4442
4443 $DBversion = "3.05.00.010";
4444 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4445     $dbh->do("CREATE INDEX priorityfoundidx ON reserves (priority,found)");
4446     print "Create an index on reserves to speed up holds awaiting pickup report bug 5866\n";
4447     SetVersion($DBversion);
4448 }
4449
4450
4451 $DBversion = "3.05.00.011";
4452 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4453     $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')");
4454     print "Upgrade to $DBversion done (add OPACResultsSidebar syspref (enh 6165))\n";
4455     SetVersion($DBversion);
4456 }
4457
4458 $DBversion = "3.05.00.012";
4459 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4460     $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')");
4461     print "Upgrade to $DBversion done (add RecordLocalUseOnReturn syspref (enh 6403))\n";
4462     SetVersion($DBversion);
4463 }
4464
4465 $DBversion = "3.05.00.013";
4466 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4467     $dbh->do(qq|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OpacKohaUrl','0',"Show 'Powered by Koha' text on OPAC footer.",NULL,NULL)|);
4468     print "Upgrade to $DBversion done (Add syspref 'OpacKohaUrl')\n";
4469     SetVersion($DBversion);
4470 }
4471
4472 $DBversion = "3.05.00.014";
4473 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4474     $dbh->do("ALTER TABLE `borrowers` MODIFY `userid` VARCHAR(75)");
4475     print "Modified userid column length into 75 in borrowers\n";
4476     SetVersion($DBversion);
4477 }
4478
4479 $DBversion = "3.05.00.015";
4480 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4481     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectEnabled',0,'Enable Novelist Select content.  Requires Novelist Profile and Password',NULL,'YesNo')");
4482     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectProfile',NULL,'Novelist Select user Password',NULL,'free')");
4483     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectPassword',NULL,'Enable Novelist user Profile',NULL,'free')");
4484     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectView','tab','Where to display Novelist Select content','tab|above|below|right','Choice')");
4485     print "Upgrade to $DBversion done (Add support for EBSCO's NoveList Select (enh 6902))\n";
4486     SetVersion($DBversion);
4487 }
4488
4489 $DBversion = '3.05.00.016';
4490 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4491     $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');");
4492     print "Upgrade to $DBversion done (Add EasyAnalyticalRecords syspref)\n";
4493     SetVersion ($DBversion);
4494 }
4495
4496 $DBversion = '3.05.00.017';
4497 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4498     if (C4::Context->preference("marcflavour") eq 'MARC21' ||
4499         C4::Context->preference("marcflavour") eq 'NORMARC'){
4500         $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)");
4501         $dbh->do("INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`, `tab`, `authorised_value` , `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`) VALUES ('773', '9', 'Host Itemnumber', 'Host Itemnumber', 0, 0, NULL, 7, NULL, NULL, '', NULL, -6, '', '', '', NULL)");
4502         print "Upgrade to $DBversion done (Add 773 subfield 9 and 0 to default framework)\n";
4503         SetVersion ($DBversion);
4504     } elsif (C4::Context->preference("marcflavour") eq 'UNIMARC'){
4505         $dbh->do("INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`, `tab`, `authorised_value` , `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`) VALUES ('461', '9', 'Host Itemnumber', 'Host Itemnumber', 0, 0, NULL, 7, NULL, NULL, '', NULL, -6, '', '', '', NULL)");
4506         print "Upgrade to $DBversion done (Add 461 subfield 9 to default framework)\n";
4507         SetVersion ($DBversion);
4508     }
4509 }
4510
4511 $DBversion = "3.05.00.018";
4512 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4513     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacNavBottom','','Links after OpacNav links','70|10','Textarea')");
4514     print "Upgrade to $DBversion done (add OpacNavBottom syspref (enh 6825): if appropriate, you can split OpacNav into OpacNav and OpacNavBottom)\n";
4515     SetVersion($DBversion);
4516 }
4517
4518 $DBversion = "3.05.00.019";
4519 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4520     $dbh->do("UPDATE itemtypes SET imageurl = 'vokal/Book.png' WHERE imageurl = 'vokal/BOOK.png'");
4521     $dbh->do("UPDATE itemtypes SET imageurl = 'vokal/Book-32px.png' WHERE imageurl = 'vokal/BOOK-32px.png'");
4522     $dbh->do("UPDATE authorised_values SET imageurl = 'vokal/Book.png' WHERE imageurl = 'vokal/BOOK.png'");
4523     $dbh->do("UPDATE authorised_values SET imageurl = 'vokal/Book-32px.png' WHERE imageurl = 'vokal/BOOK-32px.png'");
4524     print "Upgrade to $DBversion done (remove duplicate VOKAL Book icons, bug 6862)\n";
4525     SetVersion($DBversion);
4526 }
4527
4528 $DBversion = "3.05.00.020";
4529 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4530     $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')");
4531     print "Upgrade to $DBversion done (Add syspref AcqViewBaskets)\n";
4532     SetVersion($DBversion);
4533 }
4534
4535 $DBversion = "3.05.00.021";
4536 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4537     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN display_checkout TINYINT(1) NOT NULL DEFAULT '0';");
4538     print "Upgrade to $DBversion done (Added a display_checkout field in borrower_attribute_types table)\n";
4539     SetVersion($DBversion);
4540 }
4541
4542 $DBversion = "3.05.00.022";
4543 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4544     $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");
4545     print "Upgrade to $DBversion done (6094: Fixing ModAuthority problems, add a need_merge_authorities table)\n";
4546     SetVersion($DBversion);
4547 }
4548
4549 $DBversion = "3.05.00.023";
4550 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4551     $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');");
4552     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";
4553     SetVersion($DBversion);
4554 }
4555
4556 $DBversion = "3.06.00.000";
4557 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4558     print "Upgrade to $DBversion done Koha 3.6.0 release \n";
4559     SetVersion ($DBversion);
4560 }
4561
4562 $DBversion = "3.07.00.001";
4563 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4564     my $borrowers = $dbh->selectcol_arrayref( "SELECT borrowernumber from borrowers where debarred =1;", { Columns => [1] } );
4565     $dbh->do("ALTER TABLE borrowers MODIFY debarred DATE DEFAULT NULL;");
4566     $dbh->do( "UPDATE borrowers set debarred='9999-12-31' where borrowernumber IN (" . join( ",", @$borrowers ) . ");" ) if ($borrowers and scalar(@$borrowers)>0);
4567     $dbh->do("ALTER TABLE borrowers ADD COLUMN debarredcomment VARCHAR(255) DEFAULT NULL AFTER debarred;");
4568     $dbh->do("ALTER TABLE deletedborrowers MODIFY debarred DATE DEFAULT NULL;");
4569     $dbh->do("ALTER TABLE deletedborrowers ADD COLUMN debarredcomment VARCHAR(255) DEFAULT NULL AFTER debarred;");
4570     print "Upgrade done (Change borrowers.debarred into Date )\n";
4571     SetVersion($DBversion);
4572 }
4573
4574 $DBversion = "3.07.00.002";
4575 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4576     $dbh->do("UPDATE borrowers SET debarred=NULL WHERE debarred='0000-00-00';");
4577     print "Setting NULL to debarred where 0000-00-00 is stored (bug 7272)\n";
4578     SetVersion($DBversion);
4579 }
4580
4581 $DBversion = "3.07.00.003";
4582 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4583     $dbh->do(" UPDATE `message_attributes` SET message_name='Item_Due' WHERE message_name='Item_DUE'");
4584     print "Updating message_name in message_attributes\n";
4585     SetVersion($DBversion);
4586 }
4587
4588 $DBversion = "3.07.00.004";
4589 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4590     $dbh->do("ALTER TABLE  `suggestions` ADD  `patronreason` TEXT NULL AFTER  `reason`");
4591     print "Upgrade to $DBversion done (Add column to suggestions table to store patrons' reasons for submitting a suggestion. )\n";
4592     SetVersion($DBversion);
4593 }
4594
4595 $DBversion = "3.07.00.005";
4596 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4597     $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')");
4598     print "Upgrade to $DBversion done (BorrowerUnwantedField syspref)\n";
4599     SetVersion ($DBversion);
4600 }
4601
4602 $DBversion = "3.07.00.006";
4603 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4604     $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');");
4605     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";
4606     SetVersion($DBversion);
4607 }
4608
4609 $DBversion = "3.07.00.007";
4610 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4611     $dbh->do("ALTER TABLE items MODIFY materials text;");
4612     print "Upgrade to $DBversion done alter items.material from varchar(10) to text \n";
4613     SetVersion($DBversion);
4614 }
4615
4616 $DBversion = '3.07.00.008';
4617 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4618     if (C4::Context->preference("marcflavour") eq 'MARC21') {
4619         if (C4::Context->preference("opaclanguages") eq "de") {
4620             $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, '');");
4621         } else {
4622             $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, '');");
4623         }
4624     }
4625     print "Upgrade to $DBversion done (add MARC21 field 545 to framework)\n";
4626     SetVersion ($DBversion);
4627 }
4628
4629 $DBversion = "3.07.00.009";
4630 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4631     $dbh->do("ALTER TABLE `aqorders` ADD COLUMN `claims_count` INT(11)  DEFAULT 0, ADD COLUMN `claimed_date` DATE  DEFAULT NULL AFTER `claims_count`");
4632     print "Upgrade to $DBversion done (Add claims_count and claimed_date fields in aqorders table)\n";
4633     SetVersion($DBversion);
4634 }
4635
4636 $DBversion = "3.07.00.010";
4637 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4638     $dbh->do(
4639         q|CREATE TABLE `biblioimages` (
4640           `imagenumber` int(11) NOT NULL AUTO_INCREMENT,
4641           `biblionumber` int(11) NOT NULL,
4642           `mimetype` varchar(15) NOT NULL,
4643           `imagefile` mediumblob NOT NULL,
4644           `thumbnail` mediumblob NOT NULL,
4645           PRIMARY KEY (`imagenumber`),
4646           CONSTRAINT `bibliocoverimage_fk1` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
4647           ) ENGINE=InnoDB DEFAULT CHARSET=utf8|
4648     );
4649     $dbh->do(
4650         q|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OPACLocalCoverImages','0','Display local cover images on OPAC search and details pages.','1','YesNo')|
4651         );
4652     $dbh->do(
4653         q|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('LocalCoverImages','0','Display local cover images on intranet search and details pages.','1','YesNo')|
4654         );
4655     $dbh->do(
4656         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')|
4657     );
4658     $dbh->do(
4659         q|INSERT INTO permissions (module_bit, code, description) VALUES (13, 'upload_local_cover_images', 'Upload local cover images')|
4660     );
4661     print "Upgrade to $DBversion done (Added support for local cover images)\n";
4662     SetVersion($DBversion);
4663 }
4664
4665 $DBversion = "3.07.00.011";
4666 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4667     $dbh->do(<<ENDOFRENEWAL);
4668     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');
4669 ENDOFRENEWAL
4670     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";
4671     SetVersion($DBversion);
4672 }
4673
4674 $DBversion = "3.07.00.012";
4675 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4676     $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')");
4677     print "Upgrade to $DBversion add 'AllowItemsOnHoldCheckout' syspref \n";
4678     SetVersion ($DBversion);
4679 }
4680
4681 $DBversion = "3.07.00.013";
4682 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4683     $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');");
4684     print "Upgrade to $DBversion done (Bug 7345: Add system preference OpacExportOptions.)\n";
4685     SetVersion ($DBversion);
4686 }
4687
4688 $DBversion = "3.07.00.014";
4689 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4690     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";
4691     SetVersion($DBversion);
4692 }
4693
4694 $DBversion = "3.07.00.015";
4695 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4696     my $sth = $dbh->prepare(q|
4697         SELECT COUNT(*) FROM marc_subfield_structure where kohafield="biblioitems.editionstatement"
4698         |);
4699     $sth->execute;
4700     my $already_exists = $sth->fetchrow;
4701     if ( not $already_exists ) {
4702         my $field = C4::Context->preference("marcflavour") eq "UNIMARC" ? "205" : "250";
4703         my $subfield = "a";
4704         my $sth = $dbh->prepare( q|
4705             UPDATE marc_subfield_structure SET kohafield = "biblioitems.editionstatement"
4706             WHERE tagfield = ? AND tagsubfield = ?
4707         |);
4708         $sth->execute( $field, $subfield );
4709         print "Upgrade to $DBversion done (Added a mapping for biblioitems.editionstatement.)\n";
4710     } else {
4711         print "Upgrade to $DBversion done (Added a mapping for biblioitems.editionstatement (already exists, nothing to do).)\n";
4712     }
4713     SetVersion($DBversion);
4714 }
4715
4716 $DBversion = "3.07.00.016";
4717 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4718     $dbh->do("ALTER TABLE items ADD KEY `itemcallnumber` (itemcallnumber)");
4719     print "Upgrade to $DBversion done (Added index on items.itemcallnumber)\n";
4720     SetVersion($DBversion);
4721 }
4722
4723 $DBversion = "3.07.00.017";
4724 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4725     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('TransferWhenCancelAllWaitingHolds','0','Transfer items when cancelling all waiting holds',NULL,'YesNo')");
4726     print "Upgrade to $DBversion done (Add sysprefs to control transfer when cancel all waiting holds)\n";
4727     SetVersion ($DBversion);
4728 }
4729
4730 $DBversion = "3.07.00.018";
4731 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4732     $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;");
4733     print "Upgrade to $DBversion done ( adding offline operations table )\n";
4734     SetVersion($DBversion);
4735 }
4736
4737 $DBversion = "3.07.00.019";
4738 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4739     $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");
4740     $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");
4741     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";
4742     SetVersion($DBversion);
4743 }
4744
4745 $DBversion = "3.07.00.020";
4746 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4747     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OPACpatronimages',0,'Enable patron images in the OPAC',NULL,'YesNo');");
4748     print "Upgrade to $DBversion done (Bug 3516: Add the option to show patron images in the OPAC.)\n";
4749     SetVersion($DBversion);
4750 }
4751
4752 $DBversion = "3.07.00.021";
4753 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4754     $dbh->do(
4755     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('LinkerModule','Default','Chooses which linker module to use (see documentation).','Default|FirstMatchLastMatch','Choice');"
4756     );
4757     $dbh->do(
4758     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('LinkerOptions','','A pipe-separated list of options for the linker.','','free');"
4759     );
4760     $dbh->do(
4761     "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');"
4762     );
4763     $dbh->do(
4764     "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');"
4765     );
4766     $dbh->do(
4767     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AutoCreateAuthorities',0,'Automatically create authorities that do not exist when cataloging records.',NULL,'YesNo');"
4768     );
4769     $dbh->do(
4770     "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');"
4771     );
4772     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";
4773     SetVersion($DBversion);
4774 }
4775
4776 $DBversion = "3.07.00.022";
4777 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4778     $dbh->do("DELETE FROM reviews WHERE biblionumber NOT IN (SELECT biblionumber from biblio)");
4779     $dbh->do("UPDATE reviews SET borrowernumber = NULL WHERE borrowernumber NOT IN (SELECT borrowernumber FROM borrowers)");
4780     $dbh->do("ALTER TABLE reviews ADD CONSTRAINT reviews_ibfk_2 FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE");
4781     $dbh->do("ALTER TABLE reviews ADD CONSTRAINT reviews_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber ) ON UPDATE CASCADE ON DELETE SET NULL");
4782     print "Upgrade to $DBversion done (Bug 7493 - Add constraint linking OPAC comment biblionumber to biblio, OPAC comment borrowernumber to borrowers.)\n";
4783     SetVersion($DBversion);
4784 }
4785
4786 $DBversion = "3.07.00.023";
4787 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4788     $dbh->do("ALTER TABLE `message_transports` DROP FOREIGN KEY `message_transports_ibfk_3`");
4789     $dbh->do("ALTER TABLE `letter` DROP PRIMARY KEY");
4790     $dbh->do("ALTER TABLE `letter` ADD `branchcode` varchar(10) default NULL AFTER `code`");
4791     $dbh->do("ALTER TABLE `letter` ADD PRIMARY KEY  (`module`,`code`, `branchcode`)");
4792     $dbh->do("ALTER TABLE `message_transports` ADD `branchcode` varchar(10) NOT NULL default ''");
4793     $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");
4794     $dbh->do("ALTER TABLE `letter` ADD `is_html` tinyint(1) default 0 AFTER `name`");
4795
4796     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4797               VALUES ('circulation','ISSUESLIP','Issue Slip','Issue Slip', '<h3><<branches.branchname>></h3>
4798 Checked out to <<borrowers.title>> <<borrowers.firstname>> <<borrowers.initials>> <<borrowers.surname>> <br />
4799 (<<borrowers.cardnumber>>) <br />
4800
4801 <<today>><br />
4802
4803 <h4>Checked Out</h4>
4804 <checkedout>
4805 <p>
4806 <<biblio.title>> <br />
4807 Barcode: <<items.barcode>><br />
4808 Date due: <<issues.date_due>><br />
4809 </p>
4810 </checkedout>
4811
4812 <h4>Overdues</h4>
4813 <overdue>
4814 <p>
4815 <<biblio.title>> <br />
4816 Barcode: <<items.barcode>><br />
4817 Date due: <<issues.date_due>><br />
4818 </p>
4819 </overdue>
4820
4821 <hr>
4822
4823 <h4 style=\"text-align: center; font-style:italic;\">News</h4>
4824 <news>
4825 <div class=\"newsitem\">
4826 <h5 style=\"margin-bottom: 1px; margin-top: 1px\"><b><<opac_news.title>></b></h5>
4827 <p style=\"margin-bottom: 1px; margin-top: 1px\"><<opac_news.new>></p>
4828 <p class=\"newsfooter\" style=\"font-size: 8pt; font-style:italic; margin-bottom: 1px; margin-top: 1px\">Posted on <<opac_news.timestamp>></p>
4829 <hr />
4830 </div>
4831 </news>', 1)");
4832     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4833               VALUES ('circulation','ISSUEQSLIP','Issue Quick Slip','Issue Quick Slip', '<h3><<branches.branchname>></h3>
4834 Checked out to <<borrowers.title>> <<borrowers.firstname>> <<borrowers.initials>> <<borrowers.surname>> <br />
4835 (<<borrowers.cardnumber>>) <br />
4836
4837 <<today>><br />
4838
4839 <h4>Checked Out Today</h4>
4840 <checkedout>
4841 <p>
4842 <<biblio.title>> <br />
4843 Barcode: <<items.barcode>><br />
4844 Date due: <<issues.date_due>><br />
4845 </p>
4846 </checkedout>', 1)");
4847     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4848               VALUES ('circulation','RESERVESLIP','Reserve Slip','Reserve Slip', '<h5>Date: <<today>></h5>
4849
4850 <h3> Transfer to/Hold in <<branches.branchname>></h3>
4851
4852 <h3><<borrowers.surname>>, <<borrowers.firstname>></h3>
4853
4854 <ul>
4855     <li><<borrowers.cardnumber>></li>
4856     <li><<borrowers.phone>></li>
4857     <li> <<borrowers.address>><br />
4858          <<borrowers.address2>><br />
4859          <<borrowers.city >>  <<borrowers.zipcode>>
4860     </li>
4861     <li><<borrowers.email>></li>
4862 </ul>
4863 <br />
4864 <h3>ITEM ON HOLD</h3>
4865 <h4><<biblio.title>></h4>
4866 <h5><<biblio.author>></h5>
4867 <ul>
4868    <li><<items.barcode>></li>
4869    <li><<items.itemcallnumber>></li>
4870    <li><<reserves.waitingdate>></li>
4871 </ul>
4872 <p>Notes:
4873 <pre><<reserves.reservenotes>></pre>
4874 </p>', 1)");
4875     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4876               VALUES ('circulation','TRANSFERSLIP','Transfer Slip','Transfer Slip', '<h5>Date: <<today>></h5>
4877 <h3>Transfer to <<branches.branchname>></h3>
4878
4879 <h3>ITEM</h3>
4880 <h4><<biblio.title>></h4>
4881 <h5><<biblio.author>></h5>
4882 <ul>
4883    <li><<items.barcode>></li>
4884    <li><<items.itemcallnumber>></li>
4885 </ul>', 1)");
4886
4887     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('NoticeCSS','','Notices CSS url.',NULL,'free')");
4888     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('SlipCSS','','Slips CSS url.',NULL,'free')");
4889
4890     $dbh->do("UPDATE `letter` SET content = replace(content, '<<title>>', '<<biblio.title>>') WHERE code = 'HOLDPLACED'");
4891
4892     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";
4893     SetVersion($DBversion);
4894 }
4895
4896 $DBversion = "3.07.00.024";
4897 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4898     $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')");
4899     $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')");
4900     print "Upgrade to $DBversion done (Added system preference ExpireReservesMaxPickUpDelay, system preference ExpireReservesMaxPickUpDelayCharge, add reseves.charge_if_expired)\n";
4901 }
4902
4903 $DBversion = "3.07.00.025";
4904 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4905     if (TableExists('bibliocoverimage')) {
4906         $dbh->do( q|DROP TABLE bibliocoverimage;| );
4907         $dbh->do(
4908             q|CREATE TABLE biblioimages (
4909               imagenumber int(11) NOT NULL AUTO_INCREMENT,
4910               biblionumber int(11) NOT NULL,
4911               mimetype varchar(15) NOT NULL,
4912               imagefile mediumblob NOT NULL,
4913               thumbnail mediumblob NOT NULL,
4914               PRIMARY KEY (imagenumber),
4915               CONSTRAINT bibliocoverimage_fk1 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
4916               ) ENGINE=InnoDB DEFAULT CHARSET=utf8;|
4917         );
4918     }
4919     print "Upgrade to $DBversion done (Correct table name for local cover images if needed. )\n";
4920     SetVersion($DBversion);
4921 }
4922
4923 $DBversion = "3.07.00.026";
4924 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4925     $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');");
4926     print "Upgrade to $DBversion done (Add syspref CalendarFirstDayOfWeek used to select the first day of week to use in the calendar. )\n";
4927     SetVersion($DBversion);
4928 }
4929
4930 $DBversion = "3.07.00.027";
4931 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4932     $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');});
4933     print "Upgrade to $DBversion done (Added system preference RoutingListNote for adding a general note to all routing lists.)\n";
4934     SetVersion($DBversion);
4935 }
4936
4937 $DBversion = "3.07.00.028";
4938 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4939     $dbh->do(qq{
4940     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');
4941     });
4942     print "Upgrade to $DBversion done (Bug 6296 New System preference AllowPKIAuth)\n";
4943 }
4944
4945 $DBversion = "3.07.00.029";
4946 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4947     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_descriptions`;});
4948     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_mappings`;});
4949     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_biblios`;});
4950     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets`;});
4951
4952     $dbh->do(q{
4953         CREATE TABLE `oai_sets` (
4954           `id` int(11) NOT NULL auto_increment,
4955           `spec` varchar(80) NOT NULL UNIQUE,
4956           `name` varchar(80) NOT NULL,
4957           PRIMARY KEY (`id`)
4958         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4959     });
4960
4961     $dbh->do(q{
4962         CREATE TABLE `oai_sets_descriptions` (
4963           `set_id` int(11) NOT NULL,
4964           `description` varchar(255) NOT NULL,
4965           CONSTRAINT `oai_sets_descriptions_ibfk_1` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4966         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4967     });
4968
4969     $dbh->do(q{
4970         CREATE TABLE `oai_sets_mappings` (
4971           `set_id` int(11) NOT NULL,
4972           `marcfield` char(3) NOT NULL,
4973           `marcsubfield` char(1) NOT NULL,
4974           `marcvalue` varchar(80) NOT NULL,
4975           CONSTRAINT `oai_sets_mappings_ibfk_1` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4976         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4977     });
4978
4979     $dbh->do(q{
4980         CREATE TABLE `oai_sets_biblios` (
4981           `biblionumber` int(11) NOT NULL,
4982           `set_id` int(11) NOT NULL,
4983           PRIMARY KEY (`biblionumber`, `set_id`),
4984           CONSTRAINT `oai_sets_biblios_ibfk_1` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
4985           CONSTRAINT `oai_sets_biblios_ibfk_2` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4986         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4987     });
4988
4989     $dbh->do(q{
4990         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');
4991     });
4992
4993     print "Upgrade to $DBversion done (Atomic update for OAI-PMH sets management)\n";
4994     SetVersion($DBversion);
4995 }
4996
4997 $DBversion = "3.07.00.030";
4998 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4999     $dbh->do("ALTER TABLE default_circ_rules ADD
5000             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5001     $dbh->do("ALTER TABLE branch_item_rules ADD
5002             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5003     $dbh->do("ALTER TABLE default_branch_circ_rules ADD
5004             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5005     $dbh->do("ALTER TABLE default_branch_item_rules ADD
5006             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5007     # set the default rule to the current value of HomeOrHoldingBranchReturn (default to 'homebranch' if need be)
5008     my $homeorholdingbranchreturn = C4::Context->prefernce('HomeOrHoldingBranchReturn') || 'homebranch';
5009     $dbh->do("UPDATE default_circ_rules SET returnbranch = '$homeorholdingbranchreturn'");
5010     print "Upgrade to $DBversion done (Atomic update for OAI-PMH sets management)\n";
5011     SetVersion($DBversion);
5012 }
5013
5014 $DBversion = "3.07.00.031";
5015 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5016     $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')");
5017     print "Upgrade to $DBversion done (Add syspref to tell Koha if ICU indexing is in use for Zebra or not.)\n";
5018     SetVersion ($DBversion);
5019 }
5020
5021 $DBversion = "3.07.00.032";
5022 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5023     $dbh->do("ALTER TABLE virtualshelves MODIFY COLUMN owner int"); #should have been int already (fk to borrowers)
5024     $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
5025     $dbh->do("DELETE FROM virtualshelves WHERE owner IS NULL and category=1"); #delete private lists without owner (cascades to shelfcontents)
5026     $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");
5027     $dbh->do("UPDATE virtualshelves SET allow_add=0, allow_delete_own=1, allow_delete_other=0 WHERE category=1");
5028     $dbh->do("UPDATE virtualshelves SET allow_add=0, allow_delete_own=1, allow_delete_other=0 WHERE category=2");
5029     $dbh->do("UPDATE virtualshelves SET allow_add=1, allow_delete_own=1, allow_delete_other=1 WHERE category=3");
5030     $dbh->do("UPDATE virtualshelves SET category=2 WHERE category=3");
5031
5032     $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");
5033     $dbh->do("UPDATE virtualshelfcontents co LEFT JOIN virtualshelves sh USING (shelfnumber) SET co.borrowernumber=sh.owner");
5034
5035     $dbh->do("CREATE TABLE virtualshelfshares
5036     (id int AUTO_INCREMENT PRIMARY KEY, shelfnumber int NOT NULL,
5037     borrowernumber int, invitekey varchar(10), sharedate datetime,
5038     CONSTRAINT `virtualshelfshares_ibfk_1` FOREIGN KEY (`shelfnumber`) REFERENCES `virtualshelves` (`shelfnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
5039         CONSTRAINT `virtualshelfshares_ibfk_2` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE SET NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8");
5040
5041     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacAllowPublicListCreation',1,'If set, allows opac users to create public lists',NULL,'YesNo');");
5042     $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');");
5043
5044     print "Upgrade to $DBversion done (BZ7310: Improving list permissions)\n";
5045     SetVersion($DBversion);
5046 }
5047
5048 $DBversion = "3.07.00.033";
5049 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5050     $dbh->do("ALTER TABLE branches ADD opac_info text;");
5051     print "Upgrade to $DBversion done add opac_info to branches \n";
5052     SetVersion($DBversion);
5053 }
5054
5055 $DBversion = "3.07.00.034";
5056 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5057     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN category_code VARCHAR(10) NULL DEFAULT NULL AFTER `display_checkout`");
5058     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN class VARCHAR(255)  NOT NULL DEFAULT '' AFTER `category_code`");
5059     $dbh->do("ALTER TABLE borrower_attribute_types ADD CONSTRAINT category_code_fk FOREIGN KEY (category_code) REFERENCES categories(categorycode)");
5060     print "Upgrade to $DBversion done (New fields category_code and class in borrower_attribute_types table)\n";
5061     SetVersion($DBversion);
5062 }
5063
5064 $DBversion = "3.07.00.035";
5065 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5066     $dbh->do("ALTER TABLE issues CHANGE date_due date_due datetime");
5067     $dbh->do("UPDATE issues SET date_due = CONCAT(SUBSTR(date_due,1,11),'23:59:00')");
5068     $dbh->do("ALTER TABLE issues CHANGE returndate returndate datetime");
5069     $dbh->do("ALTER TABLE issues CHANGE lastreneweddate lastreneweddate datetime");
5070     $dbh->do("ALTER TABLE issues CHANGE issuedate issuedate datetime");
5071     $dbh->do("ALTER TABLE old_issues CHANGE date_due date_due datetime");
5072     $dbh->do("ALTER TABLE old_issues CHANGE returndate returndate datetime");
5073     $dbh->do("ALTER TABLE old_issues CHANGE lastreneweddate lastreneweddate datetime");
5074     $dbh->do("ALTER TABLE old_issues CHANGE issuedate issuedate datetime");
5075     $dbh->do("UPDATE accountlines SET description = CONCAT(description,' 23:59') WHERE accounttype='F' OR accounttype='FU'"); #BUG-8253
5076     print "Upgrade to $DBversion done (Setting up issues and accountlines tables for hourly loans)\n";
5077     SetVersion($DBversion);
5078 }
5079
5080 $DBversion = "3.07.00.036";
5081 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5082     $dbh->do(qq{
5083        ALTER TABLE z3950servers ADD timeout INT( 11 ) NOT NULL DEFAULT '0' AFTER syntax;
5084     });
5085     print "Upgrade to $DBversion done (New timeout field in z3950servers)\n";
5086 }
5087
5088 $DBversion = "3.07.00.037";
5089 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5090     $dbh->do("
5091        ALTER TABLE  `marc_subfield_structure` ADD  `maxlength` INT( 4 ) NOT NULL DEFAULT  '9999';
5092        ");
5093        $dbh->do("
5094        UPDATE `marc_subfield_structure` SET maxlength=24 WHERE tagfield='000';
5095        ");
5096        $dbh->do("
5097        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='MARC21','40','9999') WHERE tagfield='008';
5098        ");
5099        $dbh->do("
5100        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='NORMARC','40','9999') WHERE tagfield='008';
5101        ");
5102        $dbh->do("
5103        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='UNIMARC','36','9999') WHERE tagfield='100';
5104        ");
5105     print "Upgrade to $DBversion done (Add new field maxlength to marc_subfield_structure)\n";
5106     SetVersion($DBversion);
5107 }
5108
5109 $DBversion = "3.07.00.038";
5110 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5111     $dbh->do(qq{
5112         INSERT INTO systempreferences(variable,value,explanation,options,type)
5113         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')
5114     });
5115     print "Upgrade to $DBversion done (Added system preference 'UniqueItemFields')\n";
5116     SetVersion($DBversion);
5117 }
5118
5119 $DBversion = "3.07.00.039";
5120 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5121     $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')} );
5122     $dbh->do( qq{CREATE TABLE IF NOT EXISTS social_data
5123       ( isbn VARCHAR(30),
5124         num_critics INT,
5125         num_critics_pro INT,
5126         num_quotations INT,
5127         num_videos INT,
5128         score_avg DECIMAL(5,2),
5129         num_scores INT,
5130         PRIMARY KEY  (isbn)
5131       ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5132     } );
5133     $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')} );
5134     print "Upgrade to $DBversion done (added syspref and table for babeltheque (Babeltheque_url_js, babeltheque))\n";
5135     SetVersion($DBversion);
5136 }
5137
5138 $DBversion = "3.07.00.040";
5139 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5140     $dbh->do( qq{INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('SocialNetworks','0','Enable/Disable social networks links in opac detail','','YesNo')} );
5141     print "Upgrade to $DBversion done (added syspref SocialNetworks, to display facebook/ggl+ and other buttons)\n";
5142     SetVersion($DBversion);
5143 }
5144
5145
5146
5147 $DBversion = "3.07.00.041";
5148 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5149     $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')");
5150     print "Upgrade to $DBversion done (Add system preference SubscriptionDuplicateDroppedInput)\n";
5151     SetVersion($DBversion);
5152 }
5153
5154 $DBversion = "3.07.00.042";
5155 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5156     $dbh->do("ALTER TABLE reserves ADD suspend BOOLEAN NOT NULL DEFAULT 0");
5157     $dbh->do("ALTER TABLE old_reserves ADD suspend BOOLEAN NOT NULL DEFAULT 0");
5158
5159     $dbh->do("ALTER TABLE reserves ADD suspend_until DATETIME NULL DEFAULT NULL");
5160     $dbh->do("ALTER TABLE old_reserves ADD suspend_until DATETIME NULL DEFAULT NULL");
5161
5162     $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')");
5163
5164     print "Upgrade to $DBversion done (Add suspend fields to reserves table, add syspref AutoResumeSuspendedHolds)\n";
5165     SetVersion ($DBversion);
5166 }
5167
5168 $DBversion = "3.07.00.043";
5169 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5170     my $countXSLTDetailsDisplay = 0;
5171     my $valueXSLTDetailsDisplay = "";
5172     my $valueXSLTResultsDisplay = "";
5173     my $valueOPACXSLTDetailsDisplay = "";
5174     my $valueOPACXSLTResultsDisplay = "";
5175     #the line below test if database comes from a BibLibre's branch
5176     $countXSLTDetailsDisplay = $dbh->do('SELECT 1 FROM systempreferences WHERE variable="IntranetXSLTDetailsDisplay"');
5177     if ($countXSLTDetailsDisplay > 0)
5178     {
5179         #the two lines below will only be used to update the databases from the BibLibre's branch. They will not affect the others
5180         $dbh->do(q|UPDATE systempreferences SET variable="XSLTDetailsDisplay" WHERE variable="IntranetXSLTDetailsDisplay"|);
5181         $dbh->do(q|UPDATE systempreferences SET variable="XSLTResultsDisplay" WHERE variable="IntranetXSLTResultsDisplay"|);
5182     }
5183     else
5184     {
5185         $valueXSLTDetailsDisplay = "default" if (C4::Context->preference("XSLTDetailsDisplay"));
5186         $valueXSLTResultsDisplay = "default" if (C4::Context->preference("XSLTResultsDisplay"));
5187         $valueOPACXSLTDetailsDisplay = "default" if (C4::Context->preference("OPACXSLTDetailsDisplay"));
5188         $valueOPACXSLTResultsDisplay = "default" if (C4::Context->preference("OPACXSLTResultsDisplay"));
5189         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueXSLTDetailsDisplay\" WHERE variable='XSLTDetailsDisplay'");
5190         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueXSLTResultsDisplay\" WHERE variable='XSLTResultsDisplay'");
5191         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueOPACXSLTDetailsDisplay\" WHERE variable='OPACXSLTDetailsDisplay'");
5192         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueOPACXSLTResultsDisplay\" WHERE variable='OPACXSLTResultsDisplay'");
5193     }
5194     print "Upgrade to $DBversion done (XSLT systempreference takes a path to file rather than YesNo)\n";
5195     SetVersion($DBversion);
5196 }
5197
5198 $DBversion = "3.07.00.044";
5199 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5200     $dbh->do("ALTER TABLE aqbooksellers ADD deliverytime INT DEFAULT NULL");
5201     print "Upgrade to $DBversion done (Add deliverytime field in aqbooksellers table)";
5202     SetVersion($DBversion);
5203 }
5204
5205 $DBversion = "3.07.00.045";
5206 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5207     $dbh->do("ALTER TABLE import_batches MODIFY COLUMN batch_type ENUM('batch','z3950','webservice') NOT NULL default 'batch'");
5208     print "Upgrade to $DBversion done (Add 'webservice' to batch_type enum)\n";
5209     SetVersion ($DBversion);
5210 }
5211
5212 $DBversion = "3.07.00.046";
5213 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5214     $dbh->do("ALTER TABLE issuingrules ADD COLUMN lengthunit varchar(10) DEFAULT 'days' AFTER issuelength");
5215     print "Upgrade to $DBversion done (Setting up issues tables for hourly loans (lengthunit fix))\n";
5216     SetVersion($DBversion);
5217 }
5218
5219 $DBversion = "3.07.00.047";
5220 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5221     $dbh->do("CREATE INDEX items_location ON items(location)");
5222     $dbh->do("CREATE INDEX items_ccode ON items(ccode)");
5223     print "Upgrade to $DBversion done (items_location and items_ccode indexes added for ShelfBrowser)\n";
5224     SetVersion($DBversion);
5225 }
5226
5227 $DBversion = "3.07.00.048";
5228 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5229     $dbh->do(
5230         q | CREATE TABLE ratings (
5231   borrowernumber int(11) NOT NULL,
5232   biblionumber int(11) NOT NULL,
5233   rating_value tinyint(1) NOT NULL,
5234   timestamp timestamp NOT NULL default CURRENT_TIMESTAMP,
5235   PRIMARY KEY  (borrowernumber,biblionumber),
5236   CONSTRAINT ratings_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE,
5237   CONSTRAINT ratings_ibfk_2 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
5238 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
5239     );
5240
5241     $dbh->do(
5242 q /INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OpacStarRatings','disable',NULL,'disable|all|details','Choice') /
5243     );
5244
5245     print
5246 "Upgrade to $DBversion done (Add 'ratings' table and 'OpacStarRatings' syspref)\n";
5247     SetVersion($DBversion);
5248 }
5249
5250 $DBversion = "3.07.00.049";
5251 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5252     $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')");
5253     print "Upgrade to $DBversion done (Add system preference OpacBrowseResults ))\n";
5254     SetVersion($DBversion);
5255 }
5256
5257 $DBversion = "3.08.00.000";
5258 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5259     print "Upgrade to $DBversion done\n";
5260     SetVersion($DBversion);
5261 }
5262
5263 $DBversion = "3.09.00.001";
5264 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5265     $dbh->do("ALTER TABLE borrower_attribute_types MODIFY category_code VARCHAR( 1 ) NULL DEFAULT NULL");
5266     print "Upgrade to $DBversion done. (Bug 8002: Update patron attribute types table to allow NULL category_code)\n";
5267     SetVersion($DBversion);
5268 }
5269
5270 $DBversion = "3.09.00.002";
5271 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5272     $dbh->do("ALTER TABLE saved_sql
5273         ADD (
5274             cache_expiry INT NOT NULL DEFAULT 300,
5275             public BOOLEAN NOT NULL DEFAULT FALSE
5276         );
5277     ");
5278     print "Upgrade to $DBversion done (Added cache_expiry and public fields in
5279 saved_reports table.)\n";
5280     SetVersion($DBversion);
5281 }
5282
5283 $DBversion = "3.09.00.003";
5284 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5285     $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');");
5286     print "Upgrade to $DBversion done (Added SvcMaxReportRows syspref)\n";
5287     SetVersion($DBversion);
5288 }
5289
5290 $DBversion = "3.09.00.004";
5291 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5292     $dbh->do("INSERT IGNORE INTO permissions (module_bit, code, description) VALUES('13', 'edit_patrons', 'Perform batch modifivation of patrons')");
5293     print "Upgrade to $DBversion done (Adds permissions flag for access to the patron modifications tool)\n";
5294     SetVersion($DBversion);
5295 }
5296
5297 $DBversion = "3.09.00.005";
5298 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5299     unless (TableExists('quotes')) {
5300         $dbh->do( qq{
5301             CREATE TABLE `quotes` (
5302               `id` int(11) NOT NULL AUTO_INCREMENT,
5303               `source` text DEFAULT NULL,
5304               `text` mediumtext NOT NULL,
5305               `timestamp` datetime NOT NULL,
5306               PRIMARY KEY (`id`)
5307             ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5308         });
5309     }
5310     $dbh->do( qq{
5311         INSERT IGNORE INTO permissions VALUES (13, "edit_quotes","Edit quotes for quote-of-the-day feature");
5312     });
5313     $dbh->do( qq{
5314         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');
5315     });
5316     print "Upgrade to $DBversion done (Adding Quote of the Day Option.)\n";
5317     SetVersion($DBversion);
5318 }
5319
5320 $DBversion = "3.09.00.006";
5321 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5322     $dbh->do("UPDATE systempreferences SET
5323                 variable = 'OPACShowHoldQueueDetails',
5324                 value = CASE value WHEN '1' THEN 'priority' ELSE 'none' END,
5325                 options = 'none|priority|holds|holds_priority',
5326                 explanation = 'Show holds details in OPAC',
5327                 type = 'Choice'
5328               WHERE variable = 'OPACDisplayRequestPriority'");
5329     print "Upgrade to $DBversion done (Changed system preference OPACDisplayRequestPriority -> OPACShowHoldQueueDetails)\n";
5330     SetVersion($DBversion);
5331 }
5332
5333 $DBversion = "3.09.00.007";
5334 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5335     unless(C4::Context->preference('ReservesControlBranch')){
5336         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('ReservesControlBranch','PatronLibrary','ItemHomeLibrary|PatronLibrary','Branch checked for members reservations rights.','Choice')");
5337     }
5338     print "Upgrade to $DBversion done (Insert ReservesControlBranch systempreference into systempreferences table )\n";
5339     SetVersion($DBversion);
5340 }
5341
5342 $DBversion = "3.09.00.008";
5343 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5344     $dbh->do("ALTER TABLE sessions ADD PRIMARY KEY (id);");
5345     $dbh->do("ALTER TABLE sessions DROP INDEX `id`;");
5346     print "Upgrade to $DBversion done (redefine the field id as PRIMARY KEY of sessions)\n";
5347     SetVersion($DBversion);
5348 }
5349
5350 $DBversion = "3.09.00.009";
5351 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5352     $dbh->do("ALTER TABLE branches ADD PRIMARY KEY (branchcode);");
5353     $dbh->do("ALTER TABLE branches DROP INDEX branchcode;");
5354     print "Upgrade to $DBversion done (redefine the field branchcode as PRIMARY KEY of branches)\n";
5355     SetVersion ($DBversion);
5356 }
5357
5358 $DBversion = "3.09.00.010";
5359 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5360     $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')");
5361     print "Upgrade to $DBversion done (Add system preference issuelostitem ))\n";
5362     SetVersion($DBversion);
5363 }
5364
5365 $DBversion = "3.09.00.011";
5366 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5367     $dbh->do("ALTER TABLE `biblioitems` ADD `ean` VARCHAR( 13 ) NULL AFTER issn");
5368     $dbh->do("CREATE INDEX `ean` ON biblioitems (`ean`) ");
5369     $dbh->do("ALTER TABLE `deletedbiblioitems` ADD `ean` VARCHAR( 13 ) NULL AFTER issn");
5370     if (C4::Context->preference("marcflavour") eq 'UNIMARC') {
5371          $dbh->do("UPDATE marc_subfield_structure SET kohafield='biblioitems.ean' WHERE tagfield='073' and tagsubfield='a'");
5372     }
5373     print "Upgrade to $DBversion done (Adding ean in biblioitems and deletedbiblioitems)\n";
5374     print "If you have records with ean, please run misc/batchRebuildBiblioTables.pl to populate bibliotems.ean\n" if (C4::Context->preference("marcflavour") eq 'UNIMARC');
5375     SetVersion($DBversion);
5376 }
5377
5378 $DBversion = "3.09.00.012";
5379 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5380     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('SuspendHoldsIntranet', '1', NULL , 'Allow holds to be suspended from the intranet.', 'YesNo')");
5381     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('SuspendHoldsOpac', '1', NULL , 'Allow holds to be suspended from the OPAC.', 'YesNo')");
5382     print "Upgrade to $DBversion done (Add system preference OpacBrowseResults ))\n";
5383     SetVersion($DBversion);
5384 }
5385
5386 $DBversion ="3.09.00.013";
5387 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5388     $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');");
5389     print "Upgrade to $DBversion done (Add system preference DefaultLanguageField008))\n";
5390     SetVersion($DBversion);
5391 }
5392
5393 $DBversion ="3.09.00.014";
5394 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5395     # add phone message transport type
5396     $dbh->do("INSERT INTO message_transport_types (message_transport_type) VALUES ('phone')");
5397
5398     # adds HOLD_PHONE and PREDUE_PHONE letters (as placeholders)
5399     $dbh->do("INSERT INTO letter (module, code, name, title, content) VALUES
5400               ('reserves', 'HOLD_PHONE', 'Item Available for Pick-up (phone notice)', 'Item Available for Pick-up (phone notice)', 'Your item is available for pickup'),
5401               ('circulation', 'PREDUE_PHONE', 'Advance Notice of Item Due (phone notice)', 'Advance Notice of Item Due (phone notice)', 'Your item is due soon'),
5402               ('circulation', 'OVERDUE_PHONE', 'Overdue Notice (phone notice)', 'Overdue Notice (phone notice)', 'Your item is overdue')
5403               ");
5404
5405     # add phone notifications to patron message preferences options
5406     $dbh->do("INSERT INTO message_transports
5407              (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) VALUES
5408              (4, 'phone', 0, 'reserves', 'HOLD_PHONE'),
5409              (2, 'phone', 0, 'circulation', 'PREDUE_PHONE')
5410              ");
5411
5412     # add TalkingTechItivaPhoneNotification syspref
5413     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('TalkingTechItivaPhoneNotification',0,'If ON, enables Talking Tech I-tiva phone notifications',NULL,'YesNo');");
5414
5415     print "Upgrade done (Support for Talking Tech i-tiva phone notification system)\n";
5416     SetVersion($DBversion);
5417 }
5418
5419 $DBversion = "3.09.00.015";
5420 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5421     $dbh->do(qq{
5422         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')
5423     });
5424     print "Upgrade to $DBversion done (Add System preference StatisticsFields)\n";
5425     SetVersion($DBversion);
5426 }
5427
5428 $DBversion = "3.09.00.016";
5429 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5430     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACShowBarcode','0','Show items barcode in holding tab','','YesNo')");
5431     print "Upgrade to $DBversion done (Add syspref OPACShowBarcode)\n";
5432     SetVersion ($DBversion);
5433 }
5434
5435 $DBversion = "3.09.00.017";
5436 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5437     $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');");
5438     print "Upgrade to $DBversion done (Add customizable OpacNavRight region to the OPAC main page)\n";
5439     SetVersion ($DBversion);
5440 }
5441
5442 $DBversion = "3.09.00.018";
5443 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5444     $dbh->do("DROP TABLE IF EXISTS aqbudgetborrowers");
5445     $dbh->do("
5446         CREATE TABLE aqbudgetborrowers (
5447           budget_id int(11) NOT NULL,
5448           borrowernumber int(11) NOT NULL,
5449           PRIMARY KEY (budget_id, borrowernumber),
5450           CONSTRAINT aqbudgetborrowers_ibfk_1 FOREIGN KEY (budget_id)
5451             REFERENCES aqbudgets (budget_id)
5452             ON DELETE CASCADE ON UPDATE CASCADE,
5453           CONSTRAINT aqbudgetborrowers_ibfk_2 FOREIGN KEY (borrowernumber)
5454             REFERENCES borrowers (borrowernumber)
5455             ON DELETE CASCADE ON UPDATE CASCADE
5456         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
5457     ");
5458     $dbh->do("
5459         INSERT INTO permissions (module_bit, code, description)
5460         VALUES (11, 'budget_manage_all', 'Manage all budgets')
5461     ");
5462     print "Upgrade to $DBversion done (Add aqbudgetborrowers table)\n";
5463     SetVersion($DBversion);
5464 }
5465
5466 $DBversion = "3.09.00.019";
5467 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5468     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('OPACShowUnusedAuthorities','1','','Show authorities that are not being used in the OPAC.','YesNo')");
5469     print "Upgrade to $DBversion done (Add OPACShowUnusedAuthorities system preference)\n";
5470     SetVersion ($DBversion);
5471 }
5472
5473 $DBversion = "3.09.00.020";
5474 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5475     $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')");
5476     $dbh->do("
5477 CREATE TABLE IF NOT EXISTS borrower_files (
5478   file_id int(11) NOT NULL AUTO_INCREMENT,
5479   borrowernumber int(11) NOT NULL,
5480   file_name varchar(255) NOT NULL,
5481   file_type varchar(255) NOT NULL,
5482   file_description varchar(255) DEFAULT NULL,
5483   file_content longblob NOT NULL,
5484   date_uploaded timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
5485   PRIMARY KEY (file_id),
5486   KEY borrowernumber (borrowernumber)
5487 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
5488     ");
5489     $dbh->do("ALTER TABLE borrower_files ADD CONSTRAINT borrower_files_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE");
5490
5491     print "Upgrade to $DBversion done (Added borrow_files table, EnableBorrowerFiles syspref)\n";
5492     SetVersion($DBversion);
5493 }
5494
5495 $DBversion = "3.09.00.021";
5496 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5497     $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');");
5498     print "Upgrade to $DBversion done (Add syspref UpdateTotalIssuesOnCirc)\n";
5499     SetVersion($DBversion);
5500 }
5501
5502 $DBversion = "3.09.00.022";
5503 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5504     $dbh->do("ALTER TABLE search_history MODIFY COLUMN query_cgi text NOT NULL");
5505     print "Upgrade to $DBversion done (Change search_history.query_cgi type to text. bug 5981)\n";
5506     SetVersion($DBversion);
5507 }
5508
5509 $DBversion = "3.09.00.023";
5510 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5511     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('SearchEngine','Zebra','Solr|Zebra','Search Engine','Choice')");
5512     print "Upgrade to $DBversion done (Add system preference SearchEngine )\n";
5513     SetVersion($DBversion);
5514 }
5515
5516 $DBversion ="3.09.00.024";
5517 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5518     $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')");
5519     print "Upgrade to $DBversion done (Add system preference IntranetSlipPrinterJS))\n";
5520     SetVersion($DBversion);
5521 }
5522
5523 $DBversion = "3.09.00.025";
5524 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5525     $dbh->do('START TRANSACTION');
5526     $dbh->do('CREATE TABLE tmp_reserves AS SELECT * FROM old_reserves LIMIT 0');
5527     $dbh->do('ALTER TABLE tmp_reserves ADD reserve_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
5528     $dbh->do("
5529         INSERT INTO tmp_reserves (
5530           borrowernumber, reservedate, biblionumber,
5531           constrainttype, branchcode, notificationdate,
5532           reminderdate, cancellationdate, reservenotes,
5533           priority, found, timestamp, itemnumber,
5534           waitingdate, expirationdate, lowestPriority,
5535           suspend, suspend_until
5536         ) SELECT
5537           borrowernumber, reservedate, biblionumber,
5538           constrainttype, branchcode, notificationdate,
5539           reminderdate, cancellationdate, reservenotes,
5540           priority, found, timestamp, itemnumber,
5541           waitingdate, expirationdate, lowestPriority,
5542           suspend, suspend_until
5543         FROM old_reserves ORDER BY reservedate
5544     ");
5545     $dbh->do('SET @ai = ( SELECT MAX( reserve_id ) FROM tmp_reserves )');
5546     $dbh->do('TRUNCATE old_reserves');
5547     $dbh->do('ALTER TABLE old_reserves ADD reserve_id INT( 11 ) NOT NULL PRIMARY KEY FIRST');
5548     $dbh->do('INSERT INTO old_reserves SELECT * FROM tmp_reserves WHERE reserve_id <= @ai');
5549     $dbh->do("
5550         INSERT INTO tmp_reserves (
5551           borrowernumber, reservedate, biblionumber,
5552           constrainttype, branchcode, notificationdate,
5553           reminderdate, cancellationdate, reservenotes,
5554           priority, found, timestamp, itemnumber,
5555           waitingdate, expirationdate, lowestPriority,
5556           suspend, suspend_until
5557         ) SELECT
5558           borrowernumber, reservedate, biblionumber,
5559           constrainttype, branchcode, notificationdate,
5560           reminderdate, cancellationdate, reservenotes,
5561           priority, found, timestamp, itemnumber,
5562           waitingdate, expirationdate, lowestPriority,
5563           suspend, suspend_until
5564         FROM reserves ORDER BY reservedate
5565     ");
5566     $dbh->do('TRUNCATE reserves');
5567     $dbh->do('ALTER TABLE reserves ADD reserve_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
5568     $dbh->do('INSERT INTO reserves SELECT * FROM tmp_reserves WHERE reserve_id > COALESCE(@ai, 0)');
5569     $dbh->do('DROP TABLE tmp_reserves');
5570     $dbh->do('COMMIT');
5571
5572     my $sth = $dbh->prepare("
5573         SELECT COUNT( * ) AS count
5574         FROM information_schema.COLUMNS
5575         WHERE COLUMN_NAME =  'reserve_id'
5576         AND (
5577           TABLE_NAME LIKE  'reserves'
5578           OR
5579           TABLE_NAME LIKE  'old_reserves'
5580         )
5581     ");
5582     $sth->execute();
5583     my $row = $sth->fetchrow_hashref();
5584     die("Failed to add reserve_id to reserves tables, please refresh the page to try again.") unless ( $row->{'count'} );
5585
5586     print "Upgrade to $DBversion done (add reserve_id to reserves & old_reserves tables)\n";
5587     SetVersion($DBversion);
5588 }
5589
5590 $DBversion = "3.09.00.026";
5591 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5592     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
5593         ( 3, 'parameters_remaining_permissions', 'Remaining system parameters permissions'),
5594         ( 3, 'manage_circ_rules', 'manage circulation rules')");
5595     $dbh->do("INSERT INTO user_permissions (borrowernumber, module_bit, code)
5596         SELECT borrowernumber, 3, 'parameters_remaining_permissions'
5597         FROM borrowers WHERE flags & (1 << 3)");
5598     # Give new subpermissions to all users that have 'parameters' permission flag (bit 3) set
5599     # see userflags table
5600     $dbh->do("INSERT INTO user_permissions (borrowernumber, module_bit, code)
5601         SELECT borrowernumber, 3, 'manage_circ_rules'
5602         FROM borrowers WHERE flags & (1 << 3)");
5603     print "Upgrade to $DBversion done (Added parameters subpermissions)\n";
5604     SetVersion($DBversion);
5605 }
5606
5607 $DBversion = '3.09.00.027';
5608 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5609     $dbh->do("ALTER TABLE issuingrules ADD overduefinescap decimal(28,6) DEFAULT NULL");
5610     my $maxfine = C4::Context->preference('MaxFine');
5611     if ($maxfine && $maxfine < 900) { # an arbitrary value that tells us it's not "some huge value"
5612       $dbh->do("UPDATE issuingrules SET overduefinescap=?",undef,$maxfine);
5613       $dbh->do("UPDATE systempreferences SET value = NULL WHERE variable = 'MaxFine'");
5614     }
5615     $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'");
5616     print "Upgrade to $DBversion done (Bug 7420 add overduefinescap to circulation matrix)\n";
5617     SetVersion ($DBversion);
5618 }
5619
5620 $DBversion = "3.09.00.028";
5621 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5622     unless ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) {
5623         my %referencetypes = (  '00' => 'PERSO_NAME',
5624                                 '10' => 'CORPO_NAME',
5625                                 '11' => 'MEETI_NAME',
5626                                 '30' => 'UNIF_TITLE',
5627                                 '48' => 'CHRON_TERM',
5628                                 '50' => 'TOPIC_TERM',
5629                                 '51' => 'GEOGR_NAME',
5630                                 '55' => 'GENRE/FORM'
5631                 );
5632         my $query = q{SELECT DISTINCT authtypecode, tagfield
5633                     FROM auth_subfield_structure
5634                     WHERE (tagfield BETWEEN '400' AND '455' OR
5635                     tagfield BETWEEN '500' and '555') AND tagsubfield='a' AND
5636                     frameworkcode = '' AND ROW(authtypecode, tagfield) NOT IN
5637                     (SELECT authtypecode, tagfield FROM auth_subfield_structure
5638                     WHERE tagsubfield ='9' )};
5639         $sth = $dbh->prepare($query);
5640         $sth->execute;
5641         my $sth2 = $dbh->prepare(q{INSERT INTO auth_subfield_structure
5642                 (authtypecode, tagfield, tagsubfield, liblibrarian, libopac,
5643                  repeatable, mandatory, tab, authorised_value, value_builder,
5644                  seealso, isurl, hidden, linkid, kohafield, frameworkcode)
5645                 VALUES (?, ?, '9', '9 (RLIN)', '9 (RLIN)', 0, 0, ?, NULL, NULL,
5646                     NULL, 0, 1, '', '', '')});
5647         my $sth3 = $dbh->prepare(q{UPDATE auth_subfield_structure SET
5648                                     frameworkcode = ? WHERE authtypecode = ? AND
5649                                     tagfield = ? AND tagsubfield = 'a'});
5650         while (my $row = $sth->fetchrow_arrayref()) {
5651             my ($authtypecode, $field) = @$row;
5652             $sth2->execute($authtypecode, $field, substr($field, 0, 1));
5653             my $authtypemarker = substr $field, 1, 2;
5654             if ($authtypemarker && $referencetypes{$authtypemarker}) {
5655                 $sth3->execute($referencetypes{$authtypemarker}, $authtypecode, $field);
5656             }
5657         }
5658     }
5659
5660     print "Upgrade to $DBversion done (Add thesaurus links for MARC21/NORMARC)\n";
5661     SetVersion($DBversion);
5662 }
5663
5664 $DBversion = "3.09.00.029"; # FIXME
5665 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5666     $dbh->do("UPDATE systempreferences SET options=concat(options,'|EAN13') WHERE variable='itemBarcodeInputFilter' AND options NOT LIKE '%EAN13%'");
5667     print "Upgrade to $DBversion done (Add itemBarcodeInputFilter choice EAN13)\n";
5668
5669     $dbh->do("UPDATE systempreferences SET options = concat(options,'|EAN13'), explanation = concat(explanation,'; EAN13 - incremental') WHERE variable = 'autoBarcode' AND options NOT LIKE '%EAN13%'");
5670     print "Upgrade to $DBversion done ( Added EAN13 barcode autogeneration sequence )\n";
5671     SetVersion($DBversion);
5672 }
5673
5674 $DBversion ="3.09.00.030";
5675 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5676     my $query = "SELECT value FROM systempreferences WHERE variable='opacstylesheet'";
5677     my $remote= $dbh->selectrow_arrayref($query);
5678     $dbh->do("DELETE from systempreferences WHERE variable='opacstylesheet'");
5679     if($remote && $remote->[0]) {
5680         $query="UPDATE systempreferences SET value=? WHERE variable='opaclayoutstylesheet'";
5681         $dbh->do($query,undef,$remote->[0]);
5682         print "NOTE: The URL of your remote opac css file has been moved to preference opaclayoutstylesheet.\n";
5683     }
5684     print "Upgrade to $DBversion done (BZ 8263: Make OPAC stylesheet preferences more consistent)\n";
5685     SetVersion($DBversion);
5686 }
5687
5688 $DBversion = "3.09.00.031";
5689 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5690     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonReviews'");
5691     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonSimilarItems'");
5692     $dbh->do("DELETE FROM systempreferences WHERE variable='AWSAccessKeyID'");
5693     $dbh->do("DELETE FROM systempreferences WHERE variable='AWSPrivateKey'");
5694     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonReviews'");
5695     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonSimilarItems'");
5696     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonEnabled'");
5697     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonEnabled'");
5698     print "Upgrade to $DBversion done ('Remove preferences controlling broken Amazon features (Bug 8679')\n";
5699     SetVersion ($DBversion);
5700 }
5701
5702 $DBversion = "3.09.00.032";
5703 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5704     $dbh->do("UPDATE systempreferences SET value = 'call_number' WHERE variable = 'defaultSortField' AND value = 'callnumber'");
5705     $dbh->do("UPDATE systempreferences SET value = 'call_number' WHERE variable = 'OPACdefaultSortField' AND value = 'callnumber'");
5706     print "Upgrade to $DBversion done (Bug 8657 - Default sort by call number does not work. Correcting system preference value.)\n";
5707     SetVersion ($DBversion);
5708 }
5709
5710
5711 $DBversion = '3.09.00.033';
5712 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5713    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacSuppressionByIPRange','','Restrict the suppression to IP adresses outside of the IP range','','free');");
5714    print "Upgrade to $DBversion done (Add OpacSuppressionByIPRange syspref)\n";
5715    SetVersion ($DBversion);
5716 }
5717
5718 $DBversion ="3.09.00.034";
5719 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5720     $dbh->do("UPDATE auth_subfield_structure SET frameworkcode = 'PERSO_NAME' WHERE frameworkcode = 'PERSO_CODE'");
5721     $dbh->do("UPDATE auth_subfield_structure SET frameworkcode = 'CORPO_NAME' WHERE frameworkcode = 'ORGO_CODE'");
5722     print "Upgrade to $DBversion done (Bug 8207: correct typo in authority types)\n";
5723     SetVersion ($DBversion);
5724 }
5725
5726 $DBversion = "3.09.00.035";
5727 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5728     $dbh->do("
5729     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');
5730     ");
5731     $dbh->do(
5732     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SubfieldsToUseWhenPrefill','','Define a list of subfields to use when prefilling items (separated by space)','','Free');
5733     ");
5734     print "Upgrade to $DBversion done (Adding PrefillItem and SubfieldsToUseWhenPrefill sysprefs)\n";
5735     SetVersion ($DBversion);
5736 }
5737
5738 $DBversion = "3.09.00.036";
5739 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5740     # biblioitems changes
5741     $dbh->do("ALTER TABLE biblioitems ADD COLUMN agerestriction VARCHAR(255) DEFAULT NULL AFTER cn_sort");
5742     $dbh->do("ALTER TABLE deletedbiblioitems ADD COLUMN agerestriction VARCHAR(255) DEFAULT NULL AFTER cn_sort");
5743     # preferences changes
5744     $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')");
5745     $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')");
5746
5747     print "Upgrade to $DBversion done (Add colum agerestriction to biblioitems and deletedbiblioitems, add system preferences AgeRestrictionMarker and AgeRestrictionOverride)\n";
5748    SetVersion ($DBversion);
5749 }
5750
5751 $DBversion = "3.09.00.037";
5752 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5753     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('UseTransportCostMatrix',0,'Use Transport Cost Matrix when filling holds','','YesNo')");
5754
5755  $dbh->do("CREATE TABLE `transport_cost` (
5756               `frombranch` varchar(10) NOT NULL,
5757               `tobranch` varchar(10) NOT NULL,
5758               `cost` decimal(6,2) NOT NULL,
5759               `disable_transfer` tinyint(1) NOT NULL DEFAULT 0,
5760               CHECK ( `frombranch` <> `tobranch` ), -- a dud check, mysql does not support that
5761               PRIMARY KEY (`frombranch`, `tobranch`),
5762               CONSTRAINT `transport_cost_ibfk_1` FOREIGN KEY (`frombranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
5763               CONSTRAINT `transport_cost_ibfk_2` FOREIGN KEY (`tobranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
5764           ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
5765
5766     print "Upgrade to $DBversion done (creating `transport_cost` table; adding UseTransportCostMatrix systempref, in circulation)\n";
5767     SetVersion($DBversion);
5768 }
5769
5770 $DBversion ="3.09.00.038";
5771 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5772     $dbh->do("ALTER TABLE borrower_attributes CHANGE  attribute  attribute VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
5773     print "Upgrade to $DBversion done (Increase the maximum size of a borrower attribute value)\n";
5774     SetVersion($DBversion);
5775 }
5776
5777 $DBversion ="3.09.00.039";
5778 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5779     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,type) VALUES('DidYouMeanFromAuthorities','0','Suggest searches based on authority file.','YesNo');");
5780     print "Upgrade to $DBversion done (Add system preference DidYouMeanFromAuthorities)\n";
5781     SetVersion($DBversion);
5782 }
5783
5784 $DBversion = "3.09.00.040";
5785 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5786     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('IncludeSeeFromInSearches','0','','Include see-from references in searches.','YesNo');");
5787     print "Upgrade to $DBversion done (Add IncludeSeeFromInSearches system preference)\n";
5788     SetVersion ($DBversion);
5789 }
5790
5791 $DBversion = "3.09.00.041";
5792 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5793     $dbh->do(qq{
5794         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ExportRemoveFields','','List of fields for non export in circulation.pl (separated by a space)','','');
5795     });
5796     print "Upgrade to $DBversion done (Add system preference ExportRemoveFields)\n";
5797     SetVersion($DBversion);
5798 }
5799
5800 $DBversion = "3.09.00.042";
5801 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5802     $dbh->do(qq{
5803         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ExportWithCsvProfile','','Set a profile name for CSV export','','');
5804     });
5805     print "Upgrade to $DBversion done (Adds New System preference ExportWithCsvProfile)\n";
5806     SetVersion($DBversion)
5807 }
5808
5809 $DBversion = "3.09.00.043";
5810 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5811     $dbh->do("
5812         ALTER TABLE aqorders
5813         ADD parent_ordernumber int(11) DEFAULT NULL
5814     ");
5815     $dbh->do("
5816         UPDATE aqorders
5817         SET parent_ordernumber = ordernumber;
5818     ");
5819     print "Upgrade to $DBversion done (Adding parent_ordernumber in aqorders)\n";
5820     SetVersion($DBversion);
5821 }
5822
5823 $DBversion = '3.09.00.044';
5824 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5825     $dbh->do("ALTER TABLE statistics ADD COLUMN ccode VARCHAR ( 10 ) NULL AFTER associatedborrower");
5826     $dbh->do("UPDATE statistics SET statistics.ccode = ( SELECT items.ccode FROM items WHERE statistics.itemnumber = items.itemnumber )");
5827     $dbh->do("UPDATE statistics SET statistics.ccode = (
5828               SELECT deleteditems.ccode FROM deleteditems
5829                   WHERE statistics.itemnumber = deleteditems.itemnumber
5830               ) WHERE statistics.ccode IS NULL");
5831     print "Upgrade done ( Added Collection Code to Statistics table. )\n";
5832     SetVersion ($DBversion);
5833 }
5834
5835 $DBversion = "3.09.00.045";
5836 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5837     $dbh->do("ALTER TABLE borrower_attribute_types MODIFY category_code VARCHAR( 10 ) NULL DEFAULT NULL");
5838     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.";
5839     SetVersion($DBversion);
5840 }
5841
5842 $DBversion = "3.09.00.046";
5843 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5844     $dbh->do("ALTER TABLE `accountlines` ADD `accountlines_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;");
5845     print "Upgrade to $DBversion done (adding accountlines_id field in accountlines table)\n";
5846     SetVersion($DBversion);
5847 }
5848
5849 $DBversion = "3.09.00.047";
5850 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5851     # to preserve default behaviour as best as possible, set this new preference differently depending on whether IndependantBranches is set or not
5852     my $prefvalue = 'anywhere';
5853     if (C4::Context->preference("IndependantBranches")) { $prefvalue = 'homeorholdingbranch';}
5854     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowReturnToBranch', '$prefvalue', 'Where an item may be returned', 'anywhere|homebranch|holdingbranch|homeorholdingbranch', 'Choice');");
5855
5856     print "Upgrade to $DBversion done: adding AllowReturnToBranch syspref (bug 6151)";
5857     SetVersion($DBversion);
5858 }
5859
5860 $DBversion = "3.09.00.048";
5861 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5862     $dbh->do("ALTER TABLE authorised_values MODIFY lib varchar(200)");
5863     $dbh->do("ALTER TABLE authorised_values MODIFY lib_opac varchar(200)");
5864
5865     print "Upgrade to $DBversion done (Raise the length of Authorised Values descriptions)\n";
5866     SetVersion($DBversion);
5867 }
5868
5869 $DBversion ="3.09.00.049";
5870 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5871     $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');");
5872     $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');");
5873     $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');");
5874     $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');");
5875     print "Upgrade to $DBversion done (Add OPACMobileUserCSS, OpacMainUserBlockMobile, OpacShowLibrariesPulldownMobile and OpacShowFiltersPulldownMobile sysprefs)\n";
5876     SetVersion($DBversion);
5877 }
5878
5879 $DBversion = "3.09.00.050";
5880 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5881     $dbh->do("ALTER TABLE authorised_values MODIFY category varchar(16) NOT NULL DEFAULT '';");
5882     $dbh->do("INSERT INTO authorised_values (category, authorised_value, lib) VALUES
5883               ('REPORT_GROUP', 'CIRC', 'Circulation'),
5884               ('REPORT_GROUP', 'CAT', 'Catalog'),
5885               ('REPORT_GROUP', 'PAT', 'Patrons'),
5886               ('REPORT_GROUP', 'ACQ', 'Acquisitions'),
5887               ('REPORT_GROUP', 'ACC', 'Accounts');");
5888
5889     $dbh->do("ALTER TABLE reports_dictionary ADD report_area varchar(6) DEFAULT NULL;");
5890     $dbh->do("UPDATE reports_dictionary SET report_area = CASE area
5891                   WHEN 1 THEN 'CIRC'
5892                   WHEN 2 THEN 'CAT'
5893                   WHEN 3 THEN 'PAT'
5894                   WHEN 4 THEN 'ACQ'
5895                   WHEN 5 THEN 'ACC'
5896                   END;");
5897     $dbh->do("ALTER TABLE reports_dictionary DROP area;");
5898     $dbh->do("ALTER TABLE reports_dictionary ADD KEY dictionary_area_idx (report_area);");
5899
5900     $dbh->do("ALTER TABLE saved_sql ADD report_area varchar(6) DEFAULT NULL;");
5901     $dbh->do("ALTER TABLE saved_sql ADD report_group varchar(80) DEFAULT NULL;");
5902     $dbh->do("ALTER TABLE saved_sql ADD report_subgroup varchar(80) DEFAULT NULL;");
5903     $dbh->do("ALTER TABLE saved_sql ADD KEY sql_area_group_idx (report_group, report_subgroup);");
5904
5905     print "Upgrade to $DBversion done saved_sql new fields report_group and report_area; authorised_values.category 16 char \n";
5906     SetVersion($DBversion);
5907 }
5908
5909 $DBversion = "3.09.00.051";
5910 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5911     $dbh->do("
5912         CREATE TABLE aqinvoices (
5913           invoiceid int(11) NOT NULL AUTO_INCREMENT,
5914           invoicenumber mediumtext NOT NULL,
5915           booksellerid int(11) NOT NULL,
5916           shipmentdate date default NULL,
5917           billingdate date default NULL,
5918           closedate date default NULL,
5919           shipmentcost decimal(28,6) default NULL,
5920           shipmentcost_budgetid int(11) default NULL,
5921           PRIMARY KEY (invoiceid),
5922           CONSTRAINT aqinvoices_fk_aqbooksellerid FOREIGN KEY (booksellerid) REFERENCES aqbooksellers (id) ON DELETE CASCADE ON UPDATE CASCADE,
5923           CONSTRAINT aqinvoices_fk_shipmentcost_budgetid FOREIGN KEY (shipmentcost_budgetid) REFERENCES aqbudgets (budget_id) ON DELETE SET NULL ON UPDATE CASCADE
5924         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5925     ");
5926
5927     # Fill this new table with existing invoices
5928     my $sth = $dbh->prepare("
5929         SELECT aqorders.booksellerinvoicenumber AS invoicenumber, aqbasket.booksellerid, aqorders.datereceived
5930         FROM aqorders
5931           LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
5932         WHERE aqorders.booksellerinvoicenumber IS NOT NULL
5933           AND aqorders.booksellerinvoicenumber != ''
5934         GROUP BY aqorders.booksellerinvoicenumber
5935     ");
5936     $sth->execute;
5937     my $results = $sth->fetchall_arrayref({});
5938     $sth = $dbh->prepare("
5939         INSERT INTO aqinvoices (invoicenumber, booksellerid, shipmentdate) VALUES (?,?,?)
5940     ");
5941     foreach(@$results) {
5942         $sth->execute($_->{invoicenumber}, $_->{booksellerid}, $_->{datereceived});
5943     }
5944
5945     # Add the column in aqorders, fill it with correct value
5946     # and then drop booksellerinvoicenumber column
5947     $dbh->do("
5948         ALTER TABLE aqorders
5949         ADD COLUMN invoiceid int(11) default NULL AFTER booksellerinvoicenumber,
5950         ADD CONSTRAINT aqorders_ibfk_3 FOREIGN KEY (invoiceid) REFERENCES aqinvoices (invoiceid) ON DELETE SET NULL ON UPDATE CASCADE
5951     ");
5952
5953     $dbh->do("
5954         UPDATE aqorders, aqinvoices
5955         SET aqorders.invoiceid = aqinvoices.invoiceid
5956         WHERE aqorders.booksellerinvoicenumber = aqinvoices.invoicenumber
5957     ");
5958
5959     $dbh->do("
5960         ALTER TABLE aqorders
5961         DROP COLUMN booksellerinvoicenumber
5962     ");
5963
5964     print "Upgrade to $DBversion done (Add aqinvoices table) \n";
5965     SetVersion ($DBversion);
5966 }
5967
5968 $DBversion = "3.09.00.052";
5969 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5970     $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');");
5971     $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');");
5972     $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');");
5973     print "Upgrade to $DBversion done (Add systempreferences to decrease loan length on high demand items decreaseLoanHighHolds, decreaseLoanHighHoldsValue and decreaseLoanHighHoldsDuration) \n";
5974     SetVersion ($DBversion);
5975 }
5976
5977 $DBversion = "3.09.00.053";
5978 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5979     $dbh->do(
5980     q|CREATE TABLE `import_auths` (
5981         import_record_id int(11) NOT NULL,
5982         matched_authid int(11) default NULL,
5983         control_number varchar(25) default NULL,
5984         authorized_heading varchar(128) default NULL,
5985         original_source varchar(25) default NULL,
5986         CONSTRAINT import_auths_ibfk_1 FOREIGN KEY (import_record_id)
5987         REFERENCES import_records (import_record_id) ON DELETE CASCADE ON UPDATE CASCADE,
5988         KEY matched_authid (matched_authid)
5989         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;|
5990     );
5991     $dbh->do("ALTER TABLE import_batches
5992                 CHANGE COLUMN num_biblios num_records int(11) NOT NULL default 0,
5993                 ADD COLUMN record_type enum('biblio', 'auth', 'holdings') NOT NULL default 'biblio'");
5994     $dbh->do("UPDATE import_batches SET record_type='auth' WHERE import_batch_id IN
5995                 (SELECT import_batch_id FROM import_records WHERE record_type='auth')");
5996
5997     print "Upgrade to $DBversion done (Added support for staging authorities)\n";
5998     SetVersion ($DBversion);
5999 }
6000
6001 $DBversion = "3.09.00.054";
6002 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6003     $dbh->do("ALTER TABLE aqorders CHANGE COLUMN gst gstrate DECIMAL(6,4)  DEFAULT NULL");
6004     print "Upgrade to $DBversion done (Change column name in aqorders gst --> gstrate)\n";
6005     SetVersion($DBversion);
6006 }
6007
6008 $DBversion = "3.09.00.055";
6009 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6010     $dbh->do("ALTER TABLE aqorders ADD discount float(6,4) DEFAULT NULL AFTER gstrate");
6011     print "Upgrade to $DBversion done (Add discount field in aqorders table)\n";
6012     SetVersion($DBversion);
6013 }
6014
6015 $DBversion ="3.09.00.056";
6016 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6017     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('AuthDisplayHierarchy','0','Display authority hierarchies','','YesNo')");
6018     print "Upgrade to $DBversion done (Add system preference AuthDisplayHierarchy)\n";
6019     SetVersion($DBversion);
6020 }
6021
6022 $DBversion = "3.09.00.057";
6023 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6024     $dbh->do("ALTER TABLE aqbasket ADD deliveryplace VARCHAR(10) default NULL AFTER basketgroupid;");
6025     $dbh->do("ALTER TABLE aqbasket ADD billingplace VARCHAR(10) default NULL AFTER deliveryplace;");
6026     print "Upgrade to $DBversion done (Bug 5356: Added billingplace, deliveryplace to the aqbasket table)\n";
6027     SetVersion($DBversion);
6028 }
6029
6030 $DBversion ="3.09.00.058";
6031 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6032     $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');");
6033     $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');");
6034     print "Upgrade to $DBversion done (Add Did You Mean? configuration)\n";
6035     SetVersion($DBversion);
6036 }
6037
6038 $DBversion ="3.09.00.059";
6039 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6040     $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');");
6041     print "Upgrade to $DBversion done (Add system preference BlockReturnOfWithdrawnItems)\n";
6042     SetVersion($DBversion);
6043 }
6044
6045 $DBversion = "3.09.00.060";
6046 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6047     $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')");
6048     print "Upgrade to $DBversion done (Added HoldsToPullStartDate syspref)\n";
6049     SetVersion($DBversion);
6050 }
6051
6052 $DBversion = "3.09.00.061";
6053 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6054     $dbh->do("UPDATE systempreferences set value=0 WHERE variable='OPACItemsResultsDisplay' AND value='statuses'");
6055     $dbh->do("UPDATE systempreferences set value=1 WHERE variable='OPACItemsResultsDisplay' AND value='itemdetails'");
6056     $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'");
6057     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";
6058     SetVersion ($DBversion);
6059 }
6060
6061 $DBversion = "3.09.00.062";
6062 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6063    $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='NoZebra'");
6064    $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='QueryRemoveStopwords'");
6065    print "Upgrade to $DBversion done (Disable obsolete NoZebra and QueryRemoveStopwords sysprefs)\n";
6066    SetVersion ($DBversion);
6067 }
6068
6069 $DBversion = "3.09.00.063";
6070 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6071     my $gst_booksellers = $dbh->selectcol_arrayref("SELECT DISTINCT(gstrate) FROM aqbooksellers");
6072     my $gist_syspref = C4::Context->preference("gist");
6073     # remove the undef values and construct and array with the syspref and the supplier values
6074     my @gstrates = map { defined $_ ? $_ : () } @$gst_booksellers;
6075     push @gstrates, split ('\|', $gist_syspref);
6076     # we want to compare integer (or float)
6077     $_ = $_ + 0 for @gstrates;
6078     use List::MoreUtils qw/uniq/;
6079     # remove duplicate values
6080     @gstrates = uniq sort @gstrates;
6081     my $new_syspref_value = join '|', @gstrates;
6082     # update the syspref with the new values
6083     my $sth = $dbh->prepare("UPDATE systempreferences set value=? WHERE variable='gist'");
6084     $sth->execute( $new_syspref_value );
6085
6086     print "Upgrade to $DBversion done (Bug 8832, Set the syspref gist with the existing values)\n";
6087     SetVersion ($DBversion);
6088 }
6089
6090 $DBversion = "3.09.00.064";
6091 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6092    $dbh->do('ALTER TABLE items ADD coded_location_qualifier varchar(10) default NULL AFTER itemcallnumber');
6093    print "Upgrade to $DBversion done (Bug 6428: Added coded_location_qualifier to the items table)\n";
6094    SetVersion ($DBversion);
6095 }
6096
6097 $DBversion = "3.09.00.065";
6098 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6099    $dbh->do('ALTER TABLE deleteditems ADD coded_location_qualifier varchar(10) default NULL AFTER itemcallnumber');
6100    print "Upgrade to $DBversion done (Bug 6428: Added coded_location_qualifier to the deleteditems table)\n";
6101    SetVersion ($DBversion);
6102 }
6103
6104 $DBversion = "3.09.00.066";
6105 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6106    $dbh->do("DELETE FROM systempreferences WHERE variable='DidYouMeanFromAuthorities'");
6107    print "Upgrade to $DBversion done (Bug 9107: remove DidYouMeanFromAuthorities syspref)\n";
6108    SetVersion ($DBversion);
6109 }
6110
6111 $DBversion = "3.09.00.067";
6112 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6113    $dbh->do("ALTER TABLE statistics CHANGE COLUMN ccode ccode varchar(10) NULL");
6114    print "Upgrade to $DBversion done (Bug 9064: statistics.ccode potentially wrongly defined)\n";
6115    SetVersion ($DBversion);
6116 }
6117
6118 $DBversion = "3.10.00.00";
6119 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6120    print "Upgrade to $DBversion done (release tag)\n";
6121    SetVersion ($DBversion);
6122 }
6123
6124 $DBversion = "3.11.00.001";
6125 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6126     $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')");
6127     print "Upgrade to $DBversion done (Bug 2832 - Add alphabet syspref)\n";
6128 }
6129
6130 $DBversion = "3.11.00.002";
6131 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6132     $dbh->do(q{
6133         DELETE from aqorders_items where ordernumber NOT IN (SELECT ordernumber FROM aqorders);
6134     });
6135     $dbh->do(q{
6136         ALTER TABLE aqorders_items
6137         ADD CONSTRAINT aqorders_items_ibfk_1 FOREIGN KEY (ordernumber) REFERENCES aqorders (ordernumber)
6138         ON DELETE CASCADE ON UPDATE CASCADE;
6139     });
6140     print "Upgrade to $DBversion done (Bug 9030: Add constraint on aqorders_items.ordernumber)\n";
6141     SetVersion ($DBversion);
6142 }
6143
6144 $DBversion = "3.11.00.003";
6145 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6146     $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')");
6147     print "Upgrade to $DBversion done (Bug 7189: Add system preference RefundLostItemFeeOnReturn)\n";
6148     SetVersion($DBversion);
6149 }
6150
6151 $DBversion = "3.11.00.004";
6152 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6153     $dbh->do(qq{
6154         ALTER TABLE subscription ADD COLUMN closed INT(1) NOT NULL DEFAULT 0 AFTER enddate;
6155     });
6156
6157     print "Upgrade to $DBversion done (Bug 8782: Add field subscription.closed)\n";
6158     SetVersion($DBversion);
6159 }
6160
6161 $DBversion = "3.11.00.005";
6162 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6163     $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;});
6164
6165     $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;});
6166
6167     $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;});
6168
6169     print "Upgrade to $DBversion done (Bug 7919: Display of values depending on the connexion library)\n";
6170     SetVersion($DBversion);
6171 }
6172
6173 $DBversion = "3.11.00.006";
6174 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6175     $dbh->do(q{
6176         UPDATE virtualshelves SET sortfield="copyrightdate" where sortfield="year";
6177     });
6178     print "Upgrade to $DBversion done (Bug 9167: Update the virtualshelves.sortfield column with 'copyrightdate' if needed)\n";
6179     SetVersion($DBversion);
6180 }
6181
6182 $DBversion = "3.11.00.007";
6183 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6184     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ar', 'language', 'de', 'Arabisch')");
6185     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hy', 'language', 'de', 'Armenisch')");
6186     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'bg', 'language', 'de', 'Bulgarisch')");
6187     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'zh', 'language', 'de', 'Chinesisch')");
6188     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'cs', 'language', 'de', 'Tschechisch')");
6189     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'da', 'language', 'de', 'Dänisch')");
6190     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nl', 'language', 'de', 'Niederländisch')");
6191     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'en', 'language', 'de', 'Englisch')");
6192     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fi', 'language', 'de', 'Finnisch')");
6193     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fr', 'language', 'de', 'Französisch')");
6194     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'lo', 'language', 'fr', 'Laotien')");
6195     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'lo', 'language', 'de', 'Laotisch')");
6196     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'el', 'language', 'de', 'Griechisch (Nach 1453)')");
6197     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'he', 'language', 'de', 'Hebräisch')");
6198     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hi', 'language', 'de', 'Hindi')");
6199     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hu', 'language', 'de', 'Ungarisch')");
6200     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'id', 'language', 'de', 'Indonesisch')");
6201     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'it', 'language', 'de', 'Italienisch')");
6202     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ja', 'language', 'de', 'Japanisch')");
6203     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ko', 'language', 'de', 'Koreanisch')");
6204     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'la', 'language', 'de', 'Latein')");
6205     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'gl', 'language', 'fr', 'Galicien')");
6206     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'gl', 'language', 'de', 'Galizisch')");
6207     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nb', 'language', 'de', 'Norwegisch bokm&#229;l')");
6208     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nn', 'language', 'de', 'Norwegisch nynorsk')");
6209     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fa', 'language', 'de', 'Persisch')");
6210     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'pl', 'language', 'de', 'Polnisch')");
6211     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'pt', 'language', 'de', 'Portugiesisch')");
6212     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ro', 'language', 'de', 'Rumänisch')");
6213     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ru', 'language', 'de', 'Russisch')");
6214     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sr', 'language', 'fr', 'Serbe')");
6215     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sr', 'language', 'de', 'Serbisch')");
6216     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'es', 'language', 'de', 'Spanisch')");
6217     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sv', 'language', 'de', 'Schwedisch')");
6218     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tet', 'language', 'fr', 'Tétoum')");
6219     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tet', 'language', 'de', 'Tetum')");
6220     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'th', 'language', 'de', 'Thailändisch')");
6221     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tr', 'language', 'de', 'Türkisch')");
6222     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'uk', 'language', 'de', 'Ukrainisch')");
6223     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ur', 'language', 'fr', 'Ourdou')");
6224     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ur', 'language', 'de', 'Urdu')");
6225     print "Upgrade to $DBversion done (Bug 9056: add German and a couple of French translations to language_descriptions)\n";
6226     SetVersion ($DBversion);
6227 }
6228
6229 $DBversion = "3.11.00.008";
6230 if (CheckVersion($DBversion)) {
6231     $dbh->do("
6232         CREATE TABLE IF NOT EXISTS `borrower_modifications` (
6233           `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6234           `verification_token` varchar(255) NOT NULL DEFAULT '',
6235           `borrowernumber` int(11) NOT NULL DEFAULT '0',
6236           `cardnumber` varchar(16) DEFAULT NULL,
6237           `surname` mediumtext,
6238           `firstname` text,
6239           `title` mediumtext,
6240           `othernames` mediumtext,
6241           `initials` text,
6242           `streetnumber` varchar(10) DEFAULT NULL,
6243           `streettype` varchar(50) DEFAULT NULL,
6244           `address` mediumtext,
6245           `address2` text,
6246           `city` mediumtext,
6247           `state` text,
6248           `zipcode` varchar(25) DEFAULT NULL,
6249           `country` text,
6250           `email` mediumtext,
6251           `phone` text,
6252           `mobile` varchar(50) DEFAULT NULL,
6253           `fax` mediumtext,
6254           `emailpro` text,
6255           `phonepro` text,
6256           `B_streetnumber` varchar(10) DEFAULT NULL,
6257           `B_streettype` varchar(50) DEFAULT NULL,
6258           `B_address` varchar(100) DEFAULT NULL,
6259           `B_address2` text,
6260           `B_city` mediumtext,
6261           `B_state` text,
6262           `B_zipcode` varchar(25) DEFAULT NULL,
6263           `B_country` text,
6264           `B_email` text,
6265           `B_phone` mediumtext,
6266           `dateofbirth` date DEFAULT NULL,
6267           `branchcode` varchar(10) DEFAULT NULL,
6268           `categorycode` varchar(10) DEFAULT NULL,
6269           `dateenrolled` date DEFAULT NULL,
6270           `dateexpiry` date DEFAULT NULL,
6271           `gonenoaddress` tinyint(1) DEFAULT NULL,
6272           `lost` tinyint(1) DEFAULT NULL,
6273           `debarred` date DEFAULT NULL,
6274           `debarredcomment` varchar(255) DEFAULT NULL,
6275           `contactname` mediumtext,
6276           `contactfirstname` text,
6277           `contacttitle` text,
6278           `guarantorid` int(11) DEFAULT NULL,
6279           `borrowernotes` mediumtext,
6280           `relationship` varchar(100) DEFAULT NULL,
6281           `ethnicity` varchar(50) DEFAULT NULL,
6282           `ethnotes` varchar(255) DEFAULT NULL,
6283           `sex` varchar(1) DEFAULT NULL,
6284           `password` varchar(30) DEFAULT NULL,
6285           `flags` int(11) DEFAULT NULL,
6286           `userid` varchar(75) DEFAULT NULL,
6287           `opacnote` mediumtext,
6288           `contactnote` varchar(255) DEFAULT NULL,
6289           `sort1` varchar(80) DEFAULT NULL,
6290           `sort2` varchar(80) DEFAULT NULL,
6291           `altcontactfirstname` varchar(255) DEFAULT NULL,
6292           `altcontactsurname` varchar(255) DEFAULT NULL,
6293           `altcontactaddress1` varchar(255) DEFAULT NULL,
6294           `altcontactaddress2` varchar(255) DEFAULT NULL,
6295           `altcontactaddress3` varchar(255) DEFAULT NULL,
6296           `altcontactstate` text,
6297           `altcontactzipcode` varchar(50) DEFAULT NULL,
6298           `altcontactcountry` text,
6299           `altcontactphone` varchar(50) DEFAULT NULL,
6300           `smsalertnumber` varchar(50) DEFAULT NULL,
6301           `privacy` int(11) DEFAULT NULL,
6302           PRIMARY KEY (`verification_token`,`borrowernumber`),
6303           KEY `verification_token` (`verification_token`),
6304           KEY `borrowernumber` (`borrowernumber`)
6305         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6306 ");
6307
6308     $dbh->do("
6309         INSERT INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES
6310         ('PatronSelfRegistration', '0', NULL, 'If enabled, patrons will be able to register themselves via the OPAC.', 'YesNo'),
6311         ('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'),
6312         ('PatronSelfRegistrationDefaultCategory', '', '', 'A patron registered via the OPAC will receive a borrower category code set in this system preference.', 'free'),
6313         ('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'),
6314         ('PatronSelfRegistrationBorrowerMandatoryField',  'surname|firstname', NULL ,  'Choose the mandatory fields for a patron''s account, when registering via the OPAC.',  'free'),
6315         ('PatronSelfRegistrationBorrowerUnwantedField',  '', NULL ,  'Name the fields you don''t want to display when registering a new patron via the OPAC.',  'free');
6316     ");
6317
6318     $dbh->do("
6319     INSERT INTO  letter ( `module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content` )
6320     VALUES ( 'members', 'OPAC_REG_VERIFY', '', 'Opac Self-Registration Verification Email', '1', 'Verify Your Account', 'Hello!
6321
6322     Your library account has been created. Please verify your email address by clicking this link to complete the signup process:
6323
6324     http://<<OPACBaseURL>>/cgi-bin/koha/opac-registration-verify.pl?token=<<borrower_modifications.verification_token>>
6325
6326     If you did not initiate this request, you may safely ignore this one-time message. The request will expire shortly.'
6327     )");
6328
6329     print "Upgrade to $DBversion done (Bug 7067: Add Patron Self Registration)\n";
6330     SetVersion ($DBversion);
6331 }
6332
6333 $DBversion = "3.11.00.009";
6334 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6335     $dbh->do("
6336         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
6337         ('SeparateHoldings', '0', 'Separate current branch holdings from other holdings', NULL, 'YesNo'),
6338         ('SeparateHoldingsBranch', 'homebranch', 'Branch used to separate holdings', 'homebranch|holdingbranch', 'Choice'),
6339         ('OpacSeparateHoldings', '0', 'Separate current branch holdings from other holdings (OPAC)', NULL, 'YesNo'),
6340         ('OpacSeparateHoldingsBranch', 'homebranch', 'Branch used to separate holdings (OPAC)', 'homebranch|holdingbranch', 'Choice')
6341     ");
6342
6343     print "Upgrade to $DBversion done (Bug 7674: Add systempreferences SeparateHoldings, SeparateHoldingsBranch, OpacSeparateHoldings and OpacSeparateHoldingsBranch) \n";
6344     SetVersion ($DBversion);
6345 }
6346
6347 $DBversion = "3.11.00.010";
6348 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6349     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('RenewalSendNotice', '0', '', NULL, 'YesNo')");
6350     $dbh->do(q{
6351         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
6352         ('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>>.');
6353     });
6354     print "Upgrade to $DBversion done (Bug 9151 - Renewal notice according to patron alert preferences)\n";
6355     SetVersion($DBversion);
6356 }
6357
6358 $DBversion = "3.11.00.011";
6359 if ( CheckVersion($DBversion) ) {
6360    $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');");
6361    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('HTML5MediaExtensions','webm|ogg|ogv|oga|vtt','Media file extensions','','free');");
6362    print "Upgrade to $DBversion done (Bug 8377: Add HTML5MediaEnabled and HTML5MediaExtensions sysprefs)\n";
6363    SetVersion ($DBversion);
6364 }
6365
6366 $DBversion = "3.11.00.012";
6367 if ( CheckVersion($DBversion) ) {
6368     $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')");
6369     print "Upgrade to $DBversion done (Bug 9206: Only allow place holds in records that the patron don't have in his possession)\n";
6370     SetVersion($DBversion);
6371 }
6372
6373 $DBversion = "3.11.00.013";
6374 if ( CheckVersion($DBversion) ) {
6375     $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')");
6376     print "Upgrade to $DBversion done (Bug 9162 - Add a system preference to set which notes fields appears on title notes/description separator)\n";
6377     SetVersion($DBversion);
6378 }
6379
6380 $DBversion = "3.11.00.014";
6381 if ( CheckVersion($DBversion) ) {
6382    $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' )");
6383    $dbh->do("INSERT INTO systempreferences ( variable, value, explanation, type ) VALUES ( 'SCOUserJS', '', 'Define custom javascript for inclusion in the SCO module', 'free' )");
6384    print "Upgrade to $DBversion done (Bug 9009: Add SCOUserCSS and SCOUserJS sysprefs)\n";
6385 }
6386
6387 $DBversion = "3.11.00.015";
6388 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6389     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('RentalsInNoissuesCharge', '1', 'Rental charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
6390     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('ManInvInNoissuesCharge', '1', 'MANUAL_INV charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
6391     print "Upgrade to $DBversion done (Add sysprefs RentalsInNoissuesCharge and ManInvInNoissuesCharge.)\n";
6392     SetVersion($DBversion);
6393 }
6394
6395 $DBversion = "3.11.00.016";
6396 if ( CheckVersion($DBversion) ) {
6397    $dbh->do(q{
6398         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";
6399         });
6400    $dbh->do(q{
6401         UPDATE userflags SET flagdesc="Edit Authorities" where flagdesc="Allow to edit authorities";
6402         });
6403    $dbh->do(q{
6404         UPDATE userflags SET flagdesc="Allow access to the reports module" where flagdesc="Allow to access to the reports module";
6405         });
6406    $dbh->do(q{
6407         UPDATE userflags SET flagdesc="Set library management parameters (deprecated)" where flagdesc="Set library management parameters";
6408         });
6409    $dbh->do(q{
6410         UPDATE userflags SET flagdesc="Manage serial subscriptions" where flagdesc="Allow to manage serials subscriptions";
6411         });
6412    $dbh->do(q{
6413         UPDATE userflags SET flagdesc="Manage patrons fines and fees" where flagdesc="Update borrower charges";
6414         });
6415    $dbh->do(q{
6416         UPDATE userflags SET flagdesc="Check out and check in items" where flagdesc="Circulate books";
6417         });
6418    $dbh->do(q{
6419         UPDATE userflags SET flagdesc="Manage Koha system settings (Administration panel)" where flagdesc="Set Koha system parameters";
6420         });
6421    $dbh->do(q{
6422         UPDATE userflags SET flagdesc="Add or modify patrons" where flagdesc="Add or modify borrowers";
6423         });
6424    $dbh->do(q{
6425         UPDATE userflags SET flagdesc="Use all tools (expand for granular tools permissions)" where flagdesc="Use tools (export, import, barcodes)";
6426         });
6427    $dbh->do(q{
6428         UPDATE userflags SET flagdesc="Allow staff members to modify permissions for other staff members" where flagdesc="Set user permissions";
6429         });
6430    $dbh->do(q{
6431         UPDATE permissions SET description="Perform batch modification of patrons" where description="Perform batch modifivation of patrons";
6432         });
6433
6434    print "Upgrade to $DBversion done (Bug 9382 (updated with bug 9745) - refresh permission descriptions to make more sense)\n";
6435    SetVersion ($DBversion);
6436 }
6437
6438 $DBversion ="3.11.00.017";
6439 if ( CheckVersion($DBversion) ) {
6440     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksReviews','0','Display book review snippets from IDreamBooks.com','','YesNo');");
6441     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksReadometer','0','Display Readometer from IDreamBooks.com','','YesNo');");
6442     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksResults','0','Display IDreamBooks.com rating in search results','','YesNo');");
6443     print "Upgrade to $DBversion done (Add IDreamBooks enhanced content)\n";
6444     SetVersion($DBversion);
6445 }
6446
6447 $DBversion = "3.11.00.018";
6448 if ( CheckVersion($DBversion) ) {
6449    $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')");
6450    $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')");
6451    print "Upgrade to $DBversion done (Bug 9395: Problem with callnumber and standard number search in OPAC and Staff Client)\n";
6452    SetVersion ($DBversion);
6453 }
6454
6455 $DBversion = "3.11.00.019";
6456 if ( CheckVersion($DBversion) ) {
6457     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('UNIMARCAuthorityField100', 'afrey50      ba0', NULL, NULL, 'Textarea')");
6458     print "Upgrade to $DBversion done (Bug 9145 - Add syspref UNIMARCAuthorityField100)\n";
6459     SetVersion ($DBversion);
6460 }
6461
6462 $DBversion = "3.11.00.020";
6463 if ( CheckVersion($DBversion) ) {
6464     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UNIMARCField100Language', 'fre','UNIMARC field 100 default language',NULL,'short')");
6465     print "Upgrade to $DBversion done (Bug 8347 - Koha forces UNIMARC 100 field code language to 'fre')\n";
6466     SetVersion($DBversion);
6467 }
6468
6469 $DBversion ="3.11.00.021";
6470 if ( CheckVersion($DBversion) ) {
6471     $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');");
6472     print "Upgrade to $DBversion done (Bug 5888 - Subject search pop-up for the OPAC)\n";
6473     SetVersion($DBversion);
6474 }
6475
6476 $DBversion = "3.11.00.022";
6477 if ( CheckVersion($DBversion) ) {
6478     $dbh->do(
6479 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('Persona',0,'Use Mozilla Persona for login','','YesNo')"
6480     );
6481     print "Upgrade to $DBversion done (Bug 9587 - Allow login via Persona)\n";
6482     SetVersion($DBversion);
6483 }
6484
6485 $DBversion = "3.11.00.023";
6486 if ( CheckVersion($DBversion) ) {
6487     $dbh->do("UPDATE z3950servers SET host = 'lx2.loc.gov', port = 210, db = 'LCDB', syntax = 'USMARC', encoding = 'utf8' WHERE name = 'LIBRARY OF CONGRESS'");
6488     print "Upgrade to $DBversion done (Bug 9520 - Update default LOC Z39.50 target)\n";
6489     SetVersion($DBversion);
6490 }
6491
6492 $DBversion = "3.11.00.024";
6493 if ( CheckVersion($DBversion) ) {
6494     $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');");
6495     print "Upgrade to $DBversion done (Bug 5079: Add OpacItemLocation syspref)\n";
6496     SetVersion ($DBversion);
6497 }
6498
6499 $DBversion = "3.11.00.025";
6500 if ( CheckVersion($DBversion) ) {
6501     $dbh->do(
6502         "CREATE TABLE linktracker (
6503   id int(11) NOT NULL AUTO_INCREMENT,
6504   biblionumber int(11) DEFAULT NULL,
6505   itemnumber int(11) DEFAULT NULL,
6506   borrowernumber int(11) DEFAULT NULL,
6507   url text,
6508   timeclicked datetime DEFAULT NULL,
6509   PRIMARY KEY (id),
6510   KEY bibidx (biblionumber),
6511   KEY itemidx (itemnumber),
6512   KEY borridx (borrowernumber),
6513   KEY dateidx (timeclicked)
6514     ) ENGINE=InnoDB DEFAULT CHARSET=utf8;"
6515     );
6516     $dbh->do( "
6517   INSERT INTO systempreferences (variable,value,explanation,options,type)
6518   VALUES('TrackClicks','0','Track links clicked',NULL,'Integer')" );
6519     print
6520 "Upgrade to $DBversion done (Adds feature Bug 8917, the ability to track links clicked)\n";
6521     SetVersion($DBversion);
6522 }
6523
6524 $DBversion = "3.11.00.026";
6525 if ( CheckVersion($DBversion) ) {
6526     $dbh->do(qq{
6527         ALTER TABLE import_records ADD INDEX batch_id_record_type ( import_batch_id, record_type );
6528     });
6529     print "Upgrade to $DBversion done (Bug 9207: Add new index batch_id_record_type to import_records)\n";
6530     SetVersion($DBversion);
6531 }
6532
6533 $DBversion = "3.11.00.027";
6534 if ( CheckVersion($DBversion) ) {
6535     $dbh->do(q{
6536         INSERT INTO permissions ( module_bit, code, description )
6537         VALUES  ( '1', 'overdues_report', 'Execute overdue items report' )
6538     });
6539     # add new permission for users with all report permissions and circulation remaining permission
6540     $dbh->do(q{
6541         INSERT INTO user_permissions (borrowernumber, module_bit, code)
6542         SELECT user_permissions.borrowernumber, 1, 'overdues_report'
6543         FROM user_permissions
6544         LEFT JOIN borrowers USING(borrowernumber)
6545         WHERE borrowers.flags & (1 << 16)
6546         AND user_permissions.code = 'circulate_remaining_permissions'
6547     });
6548     print "Upgrade to $DBversion done ( Add circ permission overdues_report )\n";
6549     SetVersion($DBversion);
6550 }
6551
6552 $DBversion = "3.11.00.028";
6553 if ( CheckVersion($DBversion) ) {
6554     $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'    );");
6555     print "Upgrade to $DBversion done (Bug 9756 - Patron self registration missing the system preference PatronSelfRegistrationAdditionalInstructions)\n";
6556     SetVersion($DBversion);
6557 }
6558
6559 $DBversion = "3.11.00.029";
6560 if (CheckVersion($DBversion)) {
6561     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UseQueryParser', '0', 'If enabled, try to use QueryParser for queries.', NULL, 'YesNo')");
6562     print "Upgrade to $DBversion done (Bug 9239: Make it possible for Koha to use QueryParser)\n";
6563     SetVersion ($DBversion);
6564 }
6565
6566 $DBversion = "3.11.00.030";
6567 if ( CheckVersion($DBversion) ) {
6568     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('FinesIncludeGracePeriod','1','If enabled, fines calculations will include the grace period.',NULL,'YesNo');");
6569     print "Upgrade to $DBversion done (Add system preference FinesIncludeGracePeriod)\n";
6570     SetVersion($DBversion);
6571 }
6572
6573 $DBversion = "3.11.00.100";
6574 if ( CheckVersion($DBversion) ) {
6575     print "Upgrade to $DBversion done (3.12-alpha release)\n";
6576     SetVersion ($DBversion);
6577 }
6578
6579 $DBversion = "3.11.00.101";
6580 if ( CheckVersion($DBversion) ) {
6581    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('UNIMARCAuthorsFacetsSeparator',', ', 'UNIMARC authors facets separator', NULL, 'short')");
6582    print "Upgrade to $DBversion done (Bug 9341: Problem with UNIMARC authors facets)\n";
6583    SetVersion ($DBversion);
6584 }
6585
6586 $DBversion = "3.11.00.102";
6587 if ( CheckVersion($DBversion) ) {
6588     $dbh->do(q{
6589         DELETE FROM systempreferences WHERE variable='NoZebra'
6590     });
6591     $dbh->do(q{
6592         DELETE FROM systempreferences WHERE variable='QueryRemoveStopwords'
6593     });
6594     print "Upgrade to $DBversion done (Remove deprecated NoZebra and QueryRemoveStopwords sysprefs)\n";
6595     SetVersion($DBversion);
6596 }
6597
6598 $DBversion = "3.11.00.103";
6599 if ( CheckVersion($DBversion) ) {
6600     $dbh->do("DELETE FROM systempreferences WHERE variable = 'insecure';");
6601     print "Upgrade to $DBversion done (Bug 9827 - Remove 'insecure' system preference)\n";
6602     SetVersion($DBversion);
6603 }
6604
6605 $DBversion = "3.11.00.104";
6606 if ( CheckVersion($DBversion) ) {
6607     print "Upgrade to $DBversion done (3.12-alpha2 release)\n";
6608     SetVersion ($DBversion);
6609 }
6610
6611 $DBversion = "3.11.00.105";
6612 if ( CheckVersion($DBversion) ) {
6613     if ( C4::Context->preference("marcflavour") eq 'MARC21' ) {
6614         $sth = $dbh->prepare(
6615 "SELECT frameworkcode FROM marc_tag_structure WHERE tagfield = '029'"
6616         );
6617         $sth->execute;
6618         my $frameworkcodes = $sth->fetchall_hashref('frameworkcode');
6619
6620         for my $frameworkcode ( keys %$frameworkcodes ) {
6621             $dbh->do( "
6622     INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian,
6623     libopac, repeatable, mandatory, kohafield, tab, authorised_value, authtypecode,
6624     value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
6625     ('029', 'a', 'OCLC library identifier', 'OCLC library identifier', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6626     ('029', 'b', 'System control number', 'System control number', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6627     ('029', 'c', 'OAI set name', 'OAI set name', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6628     ('029', 't', 'Content type identifier', 'Content type identifier', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL)
6629    " );
6630         }
6631
6632         for my $tag ( '863', '864', '865' ) {
6633             $sth = $dbh->prepare(
6634 "SELECT frameworkcode FROM marc_tag_structure WHERE tagfield = '$tag'"
6635             );
6636             $sth->execute;
6637             my $frameworkcodes = $sth->fetchall_hashref('frameworkcode');
6638
6639             for my $frameworkcode ( keys %$frameworkcodes ) {
6640                 $dbh->do( "
6641      INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian,
6642      libopac, repeatable, mandatory, kohafield, tab, authorised_value, authtypecode,
6643      value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
6644      ('$tag', '6', 'Linkage', 'Linkage', 0, 0, '', 8, '', '', '', NULL, 5, '$frameworkcode', '', '', NULL),
6645      ('$tag', '8', 'Field link and sequence number', 'Field link and sequence number', 0, 0, '', 8, '', '', '', NULL, 5, '$frameworkcode', '', '', NULL),
6646      ('$tag', 'a', 'First level of enumeration', 'First level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6647      ('$tag', 'b', 'Second level of enumeration', 'Second level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6648      ('$tag', 'c', 'Third level of enumeration', 'Third level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6649      ('$tag', 'd', 'Fourth level of enumeration', 'Fourth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6650      ('$tag', 'e', 'Fifth level of enumeration', 'Fifth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6651      ('$tag', 'f', 'Sixth level of enumeration', 'Sixth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6652      ('$tag', 'g', 'Alternative numbering scheme, first level of enumeration', 'Alternative numbering scheme, first level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6653      ('$tag', 'h', 'Alternative numbering scheme, second level of enumeration', 'Alternative numbering scheme, second level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6654      ('$tag', 'i', 'First level of chronology', 'First level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6655      ('$tag', 'j', 'Second level of chronology', 'Second level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6656      ('$tag', 'k', 'Third level of chronology', 'Third level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6657      ('$tag', 'l', 'Fourth level of chronology', 'Fourth level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6658      ('$tag', 'm', 'Alternative numbering scheme, chronology', 'Alternative numbering scheme, chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6659      ('$tag', 'n', 'Converted Gregorian year', 'Converted Gregorian year', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6660      ('$tag', 'o', 'Type of unit', 'Type of unit', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6661      ('$tag', 'p', 'Piece designation', 'Piece designation', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6662      ('$tag', 'q', 'Piece physical condition', 'Piece physical condition', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6663      ('$tag', 's', 'Copyright article-fee code', 'Copyright article-fee code', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6664      ('$tag', 't', 'Copy number', 'Copy number', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6665      ('$tag', 'v', 'Issuing date', 'Issuing date', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6666      ('$tag', 'w', 'Break indicator', 'Break indicator', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6667      ('$tag', 'x', 'Nonpublic note', 'Nonpublic note', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6668      ('$tag', 'z', 'Public note', 'Public note', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL)
6669     " );
6670             }
6671         }
6672     }
6673     print "Upgrade to $DBversion done (Bug 9353: Missing subfields on MARC21 frameworks)\n";
6674     SetVersion($DBversion);
6675 }
6676
6677
6678 $DBversion = "3.11.00.106";
6679 if ( CheckVersion($DBversion) ) {
6680     $dbh->do("INSERT INTO userflags (bit, flag, flagdesc, defaulton) VALUES ('19', 'plugins', 'Koha plugins', '0')");
6681     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
6682               ('19', 'manage', 'Manage plugins ( install / uninstall )'),
6683               ('19', 'tool', 'Use tool plugins'),
6684               ('19', 'report', 'Use report plugins'),
6685               ('19', 'configure', 'Configure plugins')
6686             ");
6687     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UseKohaPlugins','0','Enable or disable the ability to use Koha Plugins.','','YesNo')");
6688
6689     $dbh->do("
6690         CREATE TABLE IF NOT EXISTS plugin_data (
6691             plugin_class varchar(255) NOT NULL,
6692             plugin_key varchar(255) NOT NULL,
6693             plugin_value text,
6694             PRIMARY KEY (plugin_class,plugin_key)
6695         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6696     ");
6697
6698     print "Upgrade to $DBversion done (Bug 7804: Added plugin system.)\n";
6699     SetVersion($DBversion);
6700 }
6701
6702 $DBversion = "3.11.00.107";
6703 if ( CheckVersion($DBversion) ) {
6704    $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('TimeFormat','24hr','12hr|24hr','Defines the global time format for visual output.','Choice')");
6705    print "Upgrade to $DBversion done (Bug 9014: Add syspref TimeFormat)\n";
6706    SetVersion ($DBversion);
6707 }
6708
6709 $DBversion = "3.11.00.108";
6710 if ( CheckVersion($DBversion) ) {
6711     $dbh->do("ALTER TABLE action_logs CHANGE timestamp timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;");
6712     $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');");
6713     $dbh->do("ALTER TABLE action_logs CHANGE timestamp timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;");
6714     print "Upgrade to $DBversion done (Bug 7241: Fix on circulation logs)\n";
6715     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";
6716     SetVersion($DBversion);
6717 }
6718
6719 $DBversion = "3.11.00.109";
6720 if ( CheckVersion($DBversion) ) {
6721    $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');");
6722    print "Upgrade to $DBversion done (Bug 9403: Add DisplayIconsXSLT)\n";
6723    SetVersion ($DBversion);
6724 }
6725
6726 $DBversion = "3.11.00.110";
6727 if ( CheckVersion($DBversion) ) {
6728     $dbh->do("ALTER TABLE pending_offline_operations CHANGE barcode barcode VARCHAR( 20 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
6729     $dbh->do("ALTER TABLE pending_offline_operations ADD amount DECIMAL( 28, 6 ) NULL DEFAULT NULL");
6730     print "Upgrade to $DBversion done (Bug 8220 - Allow koc uploads to go to process queue)\n";
6731     SetVersion ($DBversion);
6732 }
6733
6734 $DBversion = "3.11.00.111";
6735 if ( CheckVersion($DBversion) ) {
6736     my $sth = $dbh->prepare("
6737         SELECT module, code, branchcode, content
6738         FROM letter
6739         WHERE content LIKE '%<fine>%'
6740     ");
6741     $sth->execute;
6742     my $sth_update = $dbh->prepare("UPDATE letter SET content = ? WHERE module = ? AND code = ? AND branchcode = ?");
6743     while(my $row = $sth->fetchrow_hashref){
6744         $row->{content} =~ s/<fine>\w+<\/fine>/<<items.fine>>/;
6745         $sth_update->execute($row->{content}, $row->{module}, $row->{code}, $row->{branchcode});
6746     }
6747     print "Upgrade to $DBversion done (use new <<items.fine>> syntax in notices)\n";
6748     SetVersion($DBversion);
6749 }
6750
6751 $DBversion = "3.11.00.112";
6752 if ( CheckVersion($DBversion) ) {
6753     $dbh->do(qq{
6754         ALTER TABLE issuingrules ADD COLUMN renewalperiod int(4) DEFAULT NULL AFTER renewalsallowed
6755     });
6756     $dbh->do(qq{
6757         UPDATE issuingrules SET renewalperiod = issuelength
6758     });
6759     print "Upgrade to $DBversion done (Bug 8365: Add colum issuingrules.renewalperiod)\n";
6760     SetVersion ($DBversion);
6761 }
6762
6763 $DBversion = "3.11.00.113";
6764 if ( CheckVersion($DBversion) ) {
6765     $dbh->do(q{
6766         ALTER TABLE branchcategories ADD show_in_pulldown BOOLEAN NOT NULL DEFAULT '0',
6767         ADD INDEX ( show_in_pulldown )
6768     });
6769     print "Upgrade to $DBversion done (Bug 9257 - Add groups to normal search pulldown)\n";
6770     SetVersion ($DBversion);
6771 }
6772
6773 $DBversion = "3.11.00.115";
6774 if ( CheckVersion($DBversion) ) {
6775     $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')");
6776     $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')");
6777     print "Upgrade to $DBversion done (Bug 7740: Add syspref HighlightOwnItemsOnOPAC)\n";
6778     SetVersion ($DBversion);
6779 }
6780
6781 $DBversion = "3.11.00.116";
6782 if ( CheckVersion($DBversion) ) {
6783     $dbh->do(q{ALTER TABLE aqorders DROP COLUMN serialid;});
6784     $dbh->do(q{ALTER TABLE aqorders DROP COLUMN subscription;});
6785     $dbh->do(q{ALTER TABLE aqorders ADD COLUMN subscriptionid INT(11) DEFAULT NULL;});
6786     $dbh->do(q{ALTER TABLE aqorders ADD CONSTRAINT aqorders_subscriptionid FOREIGN KEY (subscriptionid) REFERENCES subscription (subscriptionid) ON DELETE CASCADE ON UPDATE CASCADE;});
6787     $dbh->do(q{ALTER TABLE subscription ADD COLUMN reneweddate DATE DEFAULT NULL;});
6788     print "Upgrade to $DBversion done (Bug 5343: table aqorders: DROP serialid and subscription fields and ADD subscriptionid, table subscription: ADD reneweddate)\n";
6789     SetVersion ($DBversion);
6790 }
6791
6792 $DBversion = "3.11.00.200";
6793 if ( CheckVersion($DBversion) ) {
6794     print "Upgrade to $DBversion done (3.12-beta1 release)\n";
6795     SetVersion ($DBversion);
6796 }
6797
6798 $DBversion = "3.11.00.201";
6799 if ( CheckVersion($DBversion) ) {
6800     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'BIBSYS' AND host LIKE 'z3950.bibsys.no'");
6801     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'NORBOK' AND host LIKE 'z3950.nb.no'");
6802     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'SAMBOK' AND host LIKE 'z3950.nb.no'");
6803     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'DEICHMAN' AND host like 'z3950.deich.folkebibl.no'");
6804     print "Upgrade to $DBversion done (Bug 9498 - Update encoding for Norwegian sample Z39.50 servers)\n";
6805     SetVersion($DBversion);
6806 }
6807
6808 $DBversion = "3.11.00.202";
6809 if ( CheckVersion($DBversion) ) {
6810    $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ca', 'language', 'Catalan','2013-01-12' )");
6811    $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'ca','cat')");
6812    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'es', 'Catalán')");
6813    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'en', 'Catalan')");
6814    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'fr', 'Catalan')");
6815    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'ca', 'Català')");
6816    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'de', 'Katalanisch')");
6817    print "Upgrade to $DBversion done (Bug 9381: Add Catalan laguage)\n";
6818    SetVersion ($DBversion);
6819 }
6820
6821 $DBversion = "3.11.00.203";
6822 if ( CheckVersion($DBversion) ) {
6823     $dbh->do(q{ALTER TABLE suggestions CHANGE COLUMN title title VARCHAR(255) DEFAULT NULL;});
6824     print "Upgrade to $DBversion done (Bug 2046 - increasing title column length for suggestions)\n";
6825     SetVersion ($DBversion);
6826 }
6827
6828 $DBversion = "3.11.00.300";
6829 if ( CheckVersion($DBversion) ) {
6830     print "Upgrade to $DBversion done (3.12-beta3 release)\n";
6831     SetVersion ($DBversion);
6832 }
6833
6834 $DBversion = "3.11.00.301";
6835 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6836     #issues
6837     $dbh->do(q{
6838         ALTER TABLE `issues`
6839             ADD KEY `itemnumber_idx` (`itemnumber`),
6840             ADD KEY `branchcode_idx` (`branchcode`),
6841             ADD KEY `issuingbranch_idx` (`issuingbranch`)
6842     });
6843     $dbh->do(q{
6844         ALTER TABLE `old_issues`
6845             ADD KEY `branchcode_idx` (`branchcode`),
6846             ADD KEY `issuingbranch_idx` (`issuingbranch`)
6847     });
6848     #items
6849     $dbh->do(q{
6850         ALTER TABLE `items` ADD KEY `itype_idx` (`itype`)
6851     });
6852     $dbh->do(q{
6853         ALTER TABLE `deleteditems` ADD KEY `itype_idx` (`itype`)
6854     });
6855     # biblioitems
6856     $dbh->do(q{
6857         ALTER TABLE `biblioitems` ADD KEY `itemtype_idx` (`itemtype`)
6858     });
6859     $dbh->do(q{
6860         ALTER TABLE `deletedbiblioitems` ADD KEY `itemtype_idx` (`itemtype`)
6861     });
6862     # statistics
6863     $dbh->do(q{
6864         ALTER TABLE `statistics`
6865             ADD KEY `branch_idx` (`branch`),
6866             ADD KEY `proccode_idx` (`proccode`),
6867             ADD KEY `type_idx` (`type`),
6868             ADD KEY `usercode_idx` (`usercode`),
6869             ADD KEY `itemnumber_idx` (`itemnumber`),
6870             ADD KEY `itemtype_idx` (`itemtype`),
6871             ADD KEY `borrowernumber_idx` (`borrowernumber`),
6872             ADD KEY `associatedborrower_idx` (`associatedborrower`),
6873             ADD KEY `ccode_idx` (`ccode`)
6874     });
6875
6876     print "Upgrade to $DBversion done (Bug 9681: Add some database indexes)\n";
6877     SetVersion($DBversion);
6878 }
6879
6880 $DBversion = "3.12.00.000";
6881 if ( CheckVersion($DBversion) ) {
6882     print "Upgrade to $DBversion done (3.12.0 release)\n";
6883     SetVersion ($DBversion);
6884 }
6885
6886 $DBversion = '3.13.00.000';
6887 if ( CheckVersion($DBversion) ) {
6888     print "Upgrade to $DBversion done (start the journey to Koha Pi)\n";
6889     SetVersion ($DBversion);
6890 }
6891
6892 $DBversion = "3.13.00.001";
6893 if ( CheckVersion($DBversion) ) {
6894     $dbh->do("INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('UseCourseReserves', '0', NULL, 'Enable the course reserves feature.', 'YesNo')");
6895     $dbh->do("INSERT INTO userflags (bit,flag,flagdesc,defaulton) VALUES ('18','coursereserves','Course Reserves','0')");
6896     $dbh->do("
6897 CREATE TABLE `courses` (
6898   `course_id` int(11) NOT NULL AUTO_INCREMENT,
6899   `department` varchar(20) DEFAULT NULL,
6900   `course_number` varchar(255) DEFAULT NULL,
6901   `section` varchar(255) DEFAULT NULL,
6902   `course_name` varchar(255) DEFAULT NULL,
6903   `term` varchar(20) DEFAULT NULL,
6904   `staff_note` mediumtext,
6905   `public_note` mediumtext,
6906   `students_count` varchar(20) DEFAULT NULL,
6907   `enabled` enum('yes','no') NOT NULL DEFAULT 'yes',
6908   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6909    PRIMARY KEY (`course_id`)
6910 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6911     ");
6912
6913     $dbh->do("
6914 CREATE TABLE `course_instructors` (
6915   `course_id` int(11) NOT NULL,
6916   `borrowernumber` int(11) NOT NULL,
6917   PRIMARY KEY (`course_id`,`borrowernumber`),
6918   KEY `borrowernumber` (`borrowernumber`)
6919 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6920     ");
6921
6922     $dbh->do("
6923 ALTER TABLE `course_instructors`
6924   ADD CONSTRAINT `course_instructors_ibfk_2` FOREIGN KEY (`course_id`) REFERENCES `courses` (`course_id`),
6925   ADD CONSTRAINT `course_instructors_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE;
6926     ");
6927
6928     $dbh->do("
6929 CREATE TABLE `course_items` (
6930   `ci_id` int(11) NOT NULL AUTO_INCREMENT,
6931   `itemnumber` int(11) NOT NULL,
6932   `itype` varchar(10) DEFAULT NULL,
6933   `ccode` varchar(10) DEFAULT NULL,
6934   `holdingbranch` varchar(10) DEFAULT NULL,
6935   `location` varchar(80) DEFAULT NULL,
6936   `enabled` enum('yes','no') NOT NULL DEFAULT 'no',
6937   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6938    PRIMARY KEY (`ci_id`),
6939    UNIQUE KEY `itemnumber` (`itemnumber`),
6940    KEY `holdingbranch` (`holdingbranch`)
6941 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6942     ");
6943
6944     $dbh->do("
6945 ALTER TABLE `course_items`
6946   ADD CONSTRAINT `course_items_ibfk_2` FOREIGN KEY (`holdingbranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
6947   ADD CONSTRAINT `course_items_ibfk_1` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE;
6948 ");
6949
6950     $dbh->do("
6951 CREATE TABLE `course_reserves` (
6952   `cr_id` int(11) NOT NULL AUTO_INCREMENT,
6953   `course_id` int(11) NOT NULL,
6954   `ci_id` int(11) NOT NULL,
6955   `staff_note` mediumtext,
6956   `public_note` mediumtext,
6957   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6958    PRIMARY KEY (`cr_id`),
6959    UNIQUE KEY `pseudo_key` (`course_id`,`ci_id`),
6960    KEY `course_id` (`course_id`)
6961 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6962 ");
6963
6964     $dbh->do("
6965 ALTER TABLE `course_reserves`
6966   ADD CONSTRAINT `course_reserves_ibfk_1` FOREIGN KEY (`course_id`) REFERENCES `courses` (`course_id`);
6967     ");
6968
6969     $dbh->do("
6970 INSERT INTO permissions (module_bit, code, description) VALUES
6971   (18, 'manage_courses', 'Add, edit and delete courses'),
6972   (18, 'add_reserves', 'Add course reserves'),
6973   (18, 'delete_reserves', 'Remove course reserves')
6974 ;
6975     ");
6976
6977
6978     print "Upgrade to $DBversion done (Add Course Reserves ( system preference UseCourseReserves ))\n";
6979     SetVersion($DBversion);
6980 }
6981
6982 $DBversion = "3.13.00.002";
6983 if ( CheckVersion($DBversion) ) {
6984    $dbh->do("UPDATE systempreferences SET variable = 'IndependentBranches' WHERE variable = 'IndependantBranches'");
6985    print "Upgrade to $DBversion done (Bug 10080 - Change system pref IndependantBranches to IndependentBranches)\n";
6986    SetVersion ($DBversion);
6987 }
6988
6989 $DBversion = '3.13.00.003';
6990 if ( CheckVersion($DBversion) ) {
6991     $dbh->do("ALTER TABLE serial DROP itemnumber");
6992     print "Upgrade to $DBversion done (Bug 7718 - Remove itemnumber column from serials table)\n";
6993     SetVersion($DBversion);
6994 }
6995
6996 $DBversion = "3.13.00.004";
6997 if(CheckVersion($DBversion)) {
6998     $dbh->do(
6999 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacShowHoldNotes',0,'Show hold notes on OPAC','','YesNo')"
7000     );
7001     print "Upgrade to $DBversion done (Bug 9722: Allow users to add notes when placing a hold in OPAC)\n";
7002     SetVersion($DBversion);
7003 }
7004
7005 $DBversion = "3.13.00.005";
7006 if(CheckVersion($DBversion)) {
7007     my $intra= C4::Context->preference("intranetstylesheet");
7008     #if this pref is not blank or starting with http, https or / [root], then
7009     #add an additional / to the front
7010     if($intra && $intra !~ /^(\/|https?)/) {
7011         $dbh->do("UPDATE systempreferences SET value=? WHERE variable=?",
7012             undef,('/'.$intra,"intranetstylesheet"));
7013         print "WARNING: Your system preference intranetstylesheet has been prefixed with a slash to make it an absolute path.\n";
7014     }
7015     print "Upgrade to $DBversion done (Bug 10052: Make intranetstylesheet and intranetcolorstylesheet behave exactly like their opac counterparts)\n";
7016     SetVersion ($DBversion);
7017 }
7018
7019 $DBversion = "3.13.00.006";
7020 if ( CheckVersion($DBversion) ) {
7021     $dbh->do(
7022         q{
7023 INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('CalculateFinesOnReturn','1','Switch to control if overdue fines are calculated on return or not', '', 'YesNo');
7024 }
7025     );
7026     print
7027 "Upgrade to $DBversion done (Bug 10120 - Fines on item return controlled by a systempreference)\n";
7028     SetVersion($DBversion);
7029 }
7030
7031 $DBversion = "3.13.00.007";
7032 if ( CheckVersion($DBversion) ) {
7033     $dbh->do("UPDATE systempreferences SET variable='OpacHoldNotes' WHERE variable='OpacShowHoldNotes'");
7034     print "Upgrade to $DBversion done (Bug 10343: Rename OpacShowHoldNotes to OpacHoldNotes)\n";
7035     SetVersion($DBversion);
7036 }
7037
7038 $DBversion = "3.13.00.008";
7039 if ( CheckVersion($DBversion) ) {
7040     $dbh->do("
7041 CREATE TABLE IF NOT EXISTS borrower_files (
7042   file_id int(11) NOT NULL AUTO_INCREMENT,
7043   borrowernumber int(11) NOT NULL,
7044   file_name varchar(255) NOT NULL,
7045   file_type varchar(255) NOT NULL,
7046   file_description varchar(255) DEFAULT NULL,
7047   file_content longblob NOT NULL,
7048   date_uploaded timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
7049   PRIMARY KEY (file_id),
7050   KEY borrowernumber (borrowernumber),
7051   CONSTRAINT borrower_files_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
7052 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7053     ");
7054     print "Upgrade to $DBversion done (Bug 10443: make sure borrower_files table exists)\n";
7055     SetVersion($DBversion);
7056 }
7057
7058 $DBversion = "3.13.00.009";
7059 if ( CheckVersion($DBversion) ) {
7060     $dbh->do("ALTER TABLE aqorders DROP COLUMN biblioitemnumber");
7061     print "Upgrade to $DBversion done (Bug 9987 - Drop column aqorders.biblioitemnumber)\n";
7062     SetVersion($DBversion);
7063 }
7064
7065 $DBversion = "3.13.00.010";
7066 if ( CheckVersion($DBversion) ) {
7067     $dbh->do(
7068         q{
7069 INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AcqWarnOnDuplicateInvoice','0','Warn librarians when they try to create a duplicate invoice', '', 'YesNo');
7070 }
7071     );
7072     print
7073 "Upgrade to $DBversion done (Bug 10366 - Add system preference to enabling warning librarian when invoice is duplicated)\n";
7074     SetVersion($DBversion);
7075 }
7076
7077 $DBversion = "3.13.00.011";
7078 if ( CheckVersion($DBversion) ) {
7079     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='ita' WHERE rfc4646_subtag='it'");
7080     print "Upgrade to $DBversion done (Bug 9519: Wrong language code for Italian in the advanced search language limitations)\n";
7081     SetVersion($DBversion);
7082 }
7083
7084 $DBversion = "3.13.00.012";
7085 if ( CheckVersion($DBversion) ) {
7086     $dbh->do("ALTER TABLE issuingrules MODIFY COLUMN overduefinescap decimal(28,6) DEFAULT NULL;");
7087     print "Upgrade to $DBversion done (Bug 10490: Correct datatype for overduefinescap in issuingrules)\n";
7088     SetVersion($DBversion);
7089 }
7090
7091 $DBversion ="3.13.00.013";
7092 if ( CheckVersion($DBversion) ) {
7093     $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');");
7094     print "Upgrade to $DBversion done (Bug 9576: add AllowTooManyOverride syspref to enable or disable issue limit confirmation)\n";
7095     SetVersion($DBversion);
7096 }
7097
7098 $DBversion = "3.13.00.014";
7099 if ( CheckVersion($DBversion) ) {
7100     $dbh->do("ALTER TABLE courses MODIFY COLUMN department varchar(80) DEFAULT NULL;");
7101     $dbh->do("ALTER TABLE courses MODIFY COLUMN term       varchar(80) DEFAULT NULL;");
7102     print "Upgrade to $DBversion done (Bug 10604: correct width of courses.department and courses.term)\n";
7103     SetVersion($DBversion);
7104 }
7105
7106 $DBversion = "3.13.00.015";
7107 if ( CheckVersion($DBversion) ) {
7108     $dbh->do(
7109 "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')"
7110     );
7111     print "Upgrade to $DBversion done (Bug 7494: Add itemBarcodeFallbackSearch syspref)\n";
7112     SetVersion($DBversion);
7113 }
7114
7115 $DBversion = "3.13.00.016";
7116 if ( CheckVersion($DBversion) ) {
7117     $dbh->do(q{
7118         ALTER TABLE items CHANGE wthdrawn withdrawn TINYINT( 1 ) NOT NULL DEFAULT  '0'
7119     });
7120
7121     $dbh->do(q{
7122         ALTER TABLE deleteditems CHANGE wthdrawn withdrawn TINYINT( 1 ) NOT NULL DEFAULT  '0'
7123     });
7124
7125     $dbh->do(q{
7126         UPDATE saved_sql SET savedsql = REPLACE(savedsql, 'wthdrawn', 'withdrawn')
7127     });
7128
7129     $dbh->do(q{
7130         UPDATE marc_subfield_structure SET kohafield = 'items.withdrawn' WHERE kohafield = 'items.wthdrawn'
7131     });
7132
7133     print "Upgrade to $DBversion done (Bug 10550 - Fix database typo wthdrawn)\n";
7134     SetVersion($DBversion);
7135 }
7136
7137 $DBversion = "3.13.00.017";
7138 if ( CheckVersion($DBversion) ) {
7139     $dbh->do(
7140 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveClientKey','','Client key for OverDrive integration','30','Free')"
7141     );
7142     $dbh->do(
7143 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveClientSecret','','Client key for OverDrive integration','30','YesNo')"
7144     );
7145     $dbh->do(
7146 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveLibraryID','','Library ID for OverDrive integration','','Integer')"
7147     );
7148     print "Upgrade to $DBversion done (Bug 10320 - Show results from library's OverDrive collection in OPAC search)\n";
7149     SetVersion($DBversion);
7150 }
7151
7152 $DBversion = "3.13.00.018";
7153 if ( CheckVersion($DBversion) ) {
7154     $dbh->do(qq{DROP TABLE IF EXISTS aqorders_transfers;});
7155     $dbh->do(qq{
7156         CREATE TABLE aqorders_transfers (
7157           ordernumber_from int(11) NULL,
7158           ordernumber_to int(11) NULL,
7159           timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
7160           UNIQUE KEY ordernumber_from (ordernumber_from),
7161           UNIQUE KEY ordernumber_to (ordernumber_to),
7162           CONSTRAINT aqorders_transfers_ordernumber_from FOREIGN KEY (ordernumber_from) REFERENCES aqorders (ordernumber) ON DELETE SET NULL ON UPDATE CASCADE,
7163           CONSTRAINT aqorders_transfers_ordernumber_to FOREIGN KEY (ordernumber_to) REFERENCES aqorders (ordernumber) ON DELETE SET NULL ON UPDATE CASCADE
7164         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7165     });
7166     print "Upgrade to $DBversion done (Bug 5349: Add aqorders_transfers table)\n";
7167     SetVersion($DBversion);
7168 }
7169
7170 $DBversion = "3.13.00.019";
7171 if ( CheckVersion($DBversion) ) {
7172     $dbh->do("ALTER TABLE itemtypes ADD COLUMN checkinmsg VARCHAR(255) AFTER summary;");
7173     $dbh->do("ALTER TABLE itemtypes ADD COLUMN checkinmsgtype CHAR(16) DEFAULT 'message' NOT NULL AFTER checkinmsg;");
7174     print "Upgrade to $DBversion done (Bug 10513 - Light up a warning/message when returning a chosen item type)\n";
7175     SetVersion($DBversion);
7176 }
7177
7178 $DBversion = "3.13.00.020";
7179 if ( CheckVersion($DBversion) ) {
7180     $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')");
7181     $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')");
7182     print "Upgrade to $DBversion done (Bug 7639: system preferences to forgive fines on lost items)\n";
7183     SetVersion($DBversion);
7184 }
7185
7186 $DBversion ="3.13.00.021";
7187 if ( CheckVersion($DBversion) ) {
7188     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ConfirmFutureHolds','0','Number of days for confirming future holds','','Integer');");
7189     print "Upgrade to $DBversion done (Bug 9761: Add ConfirmFutureHolds pref)\n";
7190     SetVersion($DBversion);
7191 }
7192
7193 $DBversion = "3.13.00.022";
7194 if ( CheckVersion($DBversion) ) {
7195     $dbh->do("DELETE from auth_tag_structure WHERE tagfield IN ('68a','68b')");
7196     $dbh->do("DELETE from auth_subfield_structure WHERE tagfield IN ('68a','68b')");
7197     print "Upgrade to $DBversion done (Bug 10687 - Delete erroneous tags 68a and 68b on default MARC21 auth framework)\n";
7198     SetVersion($DBversion);
7199 }
7200
7201 $DBversion = "3.13.00.023";
7202 if ( CheckVersion($DBversion) ) {
7203     $dbh->do("ALTER TABLE borrowers CHANGE password password VARCHAR(60);");
7204     print "Upgrade to $DBversion done (Bug 9611 upgrading password storage system)\n";
7205     SetVersion($DBversion);
7206 }
7207
7208 $DBversion = "3.13.00.024";
7209 if ( CheckVersion($DBversion) ) {
7210     $dbh->do(q{ALTER TABLE z3950servers ADD COLUMN recordtype VARCHAR(45) NOT NULL DEFAULT 'biblio' AFTER description;});
7211     print "Upgrade to $DBversion done (Bug 10096 - Add a Z39.50 interface for authority searching)\n";
7212 }
7213
7214 $DBversion = "3.13.00.025";
7215 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
7216    $dbh->do("ALTER TABLE oai_sets_mappings ADD COLUMN operator varchar(8) NOT NULL default 'equal' AFTER marcsubfield;");
7217    print "Upgrade to $DBversion done (Bug 9295: OAI notequal: add operator column to OAI mappings table)\n";
7218    SetVersion ($DBversion);
7219 }
7220
7221 $DBversion = "3.13.00.026";
7222 if ( CheckVersion($DBversion) ) {
7223     $dbh->do(q|
7224         ALTER TABLE auth_subfield_structure ADD COLUMN defaultvalue TEXT DEFAULT NULL AFTER frameworkcode
7225     |);
7226     print "Upgrade to $DBversion done (Bug 10602: Add the column auth_subfield_structure.defaultvalue)\n";
7227     SetVersion($DBversion);
7228 }
7229
7230 $DBversion = "3.13.00.027";
7231 if ( CheckVersion($DBversion) ) {
7232     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('AllowOfflineCirculation','0','','If on, enables HTML5 offline circulation functionality.','YesNo')");
7233     print "Upgrade to $DBversion done (Bug 10240: Add syspref AllowOfflineCirculation)\n";
7234     SetVersion ($DBversion);
7235 }
7236
7237 $DBversion = "3.13.00.028";
7238 if ( CheckVersion($DBversion) ) {
7239     $dbh->do(q{
7240         ALTER TABLE export_format ADD type VARCHAR(255) DEFAULT 'marc' AFTER encoding
7241     });
7242     $dbh->do(q{
7243         ALTER TABLE export_format CHANGE marcfields content mediumtext NOT NULL
7244     });
7245     print "Upgrade to $DBversion done (Bug 10853: Add new field export_format.type and rename export_format.marcfields with export_format.content)\n";
7246     SetVersion($DBversion);
7247 }
7248
7249 $DBversion = "3.13.00.029";
7250 if ( CheckVersion($DBversion) ) {
7251     $dbh->do(q{
7252         INSERT IGNORE INTO export_format( profile, description, content, csv_separator, type )
7253         VALUES ( "issues to claim", "Default CSV export for serial issue claims",
7254                 "SUPPLIER=aqbooksellers.name|TITLE=subscription.title|ISSUE NUMBER=serial.serialseq|LATE SINCE=serial.planneddate",
7255                 ",", "sql" )
7256     });
7257     print "Upgrade to $DBversion done (Bug 10854: Add the default CSV profile for claiming issues)\n";
7258     SetVersion($DBversion);
7259 }
7260
7261 $DBversion = "3.13.00.030";
7262 if ( CheckVersion($DBversion) ) {
7263     $dbh->do(qq{
7264         DELETE FROM patronimage WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowers.cardnumber = patronimage.cardnumber)
7265     });
7266
7267     $dbh->do(qq{
7268         ALTER TABLE patronimage ADD borrowernumber INT( 11 ) NULL FIRST
7269     });
7270
7271     $dbh->{AutoCommit} = 0;
7272     $dbh->{RaiseError} = 1;
7273
7274     eval {
7275         $dbh->do(qq{
7276             UPDATE patronimage LEFT JOIN borrowers USING ( cardnumber ) SET patronimage.borrowernumber = borrowers.borrowernumber
7277         });
7278         $dbh->commit();
7279     };
7280
7281     if ($@) {
7282         print "Upgrade to $DBversion done (Bug 10636 - patronimage should have borrowernumber as PK, not cardnumber) failed! Transaction aborted because $@\n";
7283         eval { $dbh->rollback };
7284     }
7285     else {
7286         $dbh->do(qq{
7287             ALTER TABLE patronimage DROP FOREIGN KEY patronimage_fk1
7288         });
7289         $dbh->do(qq{
7290             ALTER TABLE patronimage DROP PRIMARY KEY, ADD PRIMARY KEY( borrowernumber )
7291         });
7292         $dbh->do(qq{
7293             ALTER TABLE patronimage DROP cardnumber
7294         });
7295         $dbh->do(qq{
7296             ALTER TABLE patronimage ADD FOREIGN KEY ( borrowernumber ) REFERENCES borrowers ( borrowernumber ) ON DELETE CASCADE ON UPDATE CASCADE
7297         });
7298
7299         print "Upgrade to $DBversion done (Bug 10636 - patronimage should have borrowernumber as PK, not cardnumber)\n";
7300         SetVersion($DBversion);
7301     }
7302
7303     $dbh->{AutoCommit} = 1;
7304     $dbh->{RaiseError} = 0;
7305 }
7306
7307 $DBversion = "3.13.00.031";
7308 if ( CheckVersion($DBversion) ) {
7309
7310     $dbh->do(q{
7311         CREATE TABLE IF NOT EXISTS `patron_lists` (
7312           patron_list_id int(11) NOT NULL AUTO_INCREMENT,
7313           name varchar(255) CHARACTER SET utf8 NOT NULL,
7314           owner int(11) NOT NULL,
7315           PRIMARY KEY (patron_list_id),
7316           KEY owner (owner)
7317         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7318     });
7319
7320     $dbh->do(q{
7321         ALTER TABLE `patron_lists`
7322           ADD CONSTRAINT patron_lists_ibfk_1 FOREIGN KEY (`owner`) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE;
7323     });
7324
7325     $dbh->do(q{
7326         CREATE TABLE patron_list_patrons (
7327           patron_list_patron_id int(11) NOT NULL AUTO_INCREMENT,
7328           patron_list_id int(11) NOT NULL,
7329           borrowernumber int(11) NOT NULL,
7330           PRIMARY KEY (patron_list_patron_id),
7331           KEY patron_list_id (patron_list_id),
7332           KEY borrowernumber (borrowernumber)
7333         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7334     });
7335
7336     $dbh->do(q{
7337         ALTER TABLE `patron_list_patrons`
7338           ADD CONSTRAINT patron_list_patrons_ibfk_1 FOREIGN KEY (patron_list_id) REFERENCES patron_lists (patron_list_id) ON DELETE CASCADE ON UPDATE CASCADE,
7339           ADD CONSTRAINT patron_list_patrons_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE;
7340     });
7341
7342     $dbh->do(q{
7343         INSERT INTO permissions (module_bit, code, description) VALUES
7344         (13, 'manage_patron_lists', 'Add, edit and delete patron lists and their contents')
7345     });
7346
7347     print "Upgrade to $DBversion done (Bug 10565 - Add a 'Patron List' feature for storing and manipulating collections of patrons)\n";
7348     SetVersion($DBversion);
7349 }
7350
7351 $DBversion = "3.13.00.032";
7352 if ( CheckVersion($DBversion) ) {
7353     $dbh->do("ALTER TABLE aqorders ADD COLUMN orderstatus varchar(16) DEFAULT 'new' AFTER parent_ordernumber");
7354     $dbh->do("UPDATE aqorders SET orderstatus='ordered' WHERE basketno IN (SELECT basketno FROM aqbasket WHERE closedate IS NOT NULL)");
7355     $dbh->do(q{
7356         UPDATE aqorders SET orderstatus='partial'
7357         WHERE quantity > quantityreceived
7358         AND quantityreceived > 0
7359         AND ordernumber IN (
7360             SELECT parent_ordernumber
7361             FROM (
7362                 SELECT DISTINCT(parent_ordernumber)
7363                 FROM aqorders
7364                 WHERE ordernumber != parent_ordernumber
7365             ) AS aq
7366         )
7367         AND basketno IN (SELECT basketno FROM aqbasket WHERE closedate IS NOT NULL)
7368     });
7369     $dbh->do("UPDATE aqorders SET orderstatus='complete' WHERE quantity=quantityreceived");
7370     $dbh->do("UPDATE aqorders SET orderstatus='cancelled' WHERE datecancellationprinted IS NOT NULL");
7371     print "Upgrade to $DBversion done (Bug 5336: Add the new column aqorders.orderstatus)\n";
7372     SetVersion($DBversion);
7373 }
7374
7375 $DBversion = "3.13.00.033";
7376 if ( CheckVersion($DBversion) ) {
7377     $dbh->do(qq|
7378         DROP TABLE IF EXISTS subscription_frequencies
7379     |);
7380     $dbh->do(qq|
7381         CREATE TABLE subscription_frequencies (
7382             id INTEGER NOT NULL AUTO_INCREMENT,
7383             description TEXT NOT NULL,
7384             displayorder INT DEFAULT NULL,
7385             unit ENUM('day','week','month','year') DEFAULT NULL,
7386             unitsperissue INTEGER NOT NULL DEFAULT '1',
7387             issuesperunit INTEGER NOT NULL DEFAULT '1',
7388             PRIMARY KEY (id)
7389         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
7390     |);
7391
7392     $dbh->do(qq|
7393         DROP TABLE IF EXISTS subscription_numberpatterns
7394     |);
7395     $dbh->do(qq|
7396         CREATE TABLE subscription_numberpatterns (
7397             id INTEGER NOT NULL AUTO_INCREMENT,
7398             label VARCHAR(255) NOT NULL,
7399             displayorder INTEGER DEFAULT NULL,
7400             description TEXT NOT NULL,
7401             numberingmethod VARCHAR(255) NOT NULL,
7402             label1 VARCHAR(255) DEFAULT NULL,
7403             add1 INTEGER DEFAULT NULL,
7404             every1 INTEGER DEFAULT NULL,
7405             whenmorethan1 INTEGER DEFAULT NULL,
7406             setto1 INTEGER DEFAULT NULL,
7407             numbering1 VARCHAR(255) DEFAULT NULL,
7408             label2 VARCHAR(255) DEFAULT NULL,
7409             add2 INTEGER DEFAULT NULL,
7410             every2 INTEGER DEFAULT NULL,
7411             whenmorethan2 INTEGER DEFAULT NULL,
7412             setto2 INTEGER DEFAULT NULL,
7413             numbering2 VARCHAR(255) DEFAULT NULL,
7414             label3 VARCHAR(255) DEFAULT NULL,
7415             add3 INTEGER DEFAULT NULL,
7416             every3 INTEGER DEFAULT NULL,
7417             whenmorethan3 INTEGER DEFAULT NULL,
7418             setto3 INTEGER DEFAULT NULL,
7419             numbering3 VARCHAR(255) DEFAULT NULL,
7420             PRIMARY KEY (id)
7421         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
7422     |);
7423
7424     $dbh->do(qq|
7425         INSERT INTO subscription_frequencies (description, unit, unitsperissue, issuesperunit, displayorder)
7426         VALUES
7427             ('2/day', 'day', 1, 2, 1),
7428             ('1/day', 'day', 1, 1, 2),
7429             ('3/week', 'week', 1, 3, 3),
7430             ('1/week', 'week', 1, 1, 4),
7431             ('1/2 weeks', 'week', 2, 1, 5),
7432             ('1/3 weeks', 'week', 3, 1, 6),
7433             ('1/month', 'month', 1, 1, 7),
7434             ('1/2 months', 'month', 2, 1, 8),
7435             ('1/3 months', 'month', 3, 1, 9),
7436             ('2/year', 'month', 6, 1, 10),
7437             ('1/year', 'year', 1, 1, 11),
7438             ('1/2 year', 'year', 2, 1, 12),
7439             ('Irregular', NULL, 1, 1, 13)
7440     |);
7441
7442     # Used to link existing subscription to newly created frequencies
7443     my $frequencies_mapping = {     # keys are old frequency numbers, values are the new ones
7444         1 => 2,     # daily (n/week)
7445         2 => 4,     # 1/week
7446         3 => 5,     # 1/2 weeks
7447         4 => 6,     # 1/3 weeks
7448         5 => 7,     # 1/month
7449         6 => 8,     # 1/2 months (6/year)
7450         7 => 9,     # 1/3 months (1/quarter)
7451         8 => 9,    # 1/quarter (seasonal)
7452         9 => 10,    # 2/year
7453         10 => 11,   # 1/year
7454         11 => 12,   # 1/2 years
7455         12 => 1,    # 2/day
7456         16 => 13,   # Without periodicity
7457         32 => 13,   # Irregular
7458         48 => 13    # Unknown
7459     };
7460
7461     $dbh->do(qq|
7462         INSERT INTO subscription_numberpatterns
7463             (label, displayorder, description, numberingmethod,
7464             label1, add1, every1, whenmorethan1, setto1, numbering1,
7465             label2, add2, every2, whenmorethan2, setto2, numbering2,
7466             label3, add3, every3, whenmorethan3, setto3, numbering3)
7467         VALUES
7468             ('Number', 1, 'Simple Numbering method', 'No.{X}',
7469             'Number', 1, 1, 99999, 1, NULL,
7470             NULL, NULL, NULL, NULL, NULL, NULL,
7471             NULL, NULL, NULL, NULL, NULL, NULL),
7472
7473             ('Volume, Number, Issue', 2, 'Volume Number Issue 1', 'Vol.{X}, Number {Y}, Issue {Z}',
7474             'Volume', 1, 48, 99999, 1, NULL,
7475             'Number', 1, 4, 12, 1, NULL,
7476             'Issue', 1, 1, 4, 1, NULL),
7477
7478             ('Volume, Number', 3, 'Volume Number 1', 'Vol {X}, No {Y}',
7479             'Volume', 1, 12, 99999, 1, NULL,
7480             'Number', 1, 1, 12, 1, NULL,
7481             NULL, NULL, NULL, NULL, NULL, NULL),
7482
7483             ('Seasonal', 4, 'Season Year', '{X} {Y}',
7484             'Season', 1, 1, 3, 0, 'season',
7485             'Year', 1, 4, 99999, 1, NULL,
7486             NULL, NULL, NULL, NULL, NULL, NULL)
7487     |);
7488
7489     $dbh->do(qq|
7490         ALTER TABLE subscription
7491         MODIFY COLUMN numberpattern INTEGER DEFAULT NULL,
7492         MODIFY COLUMN periodicity INTEGER DEFAULT NULL
7493     |);
7494
7495     # Update existing subscriptions
7496
7497     my $query = qq|
7498         SELECT subscriptionid, periodicity, numberingmethod,
7499             add1, every1, whenmorethan1, setto1,
7500             add2, every2, whenmorethan2, setto2,
7501             add3, every3, whenmorethan3, setto3
7502         FROM subscription
7503         ORDER BY subscriptionid
7504     |;
7505     my $sth = $dbh->prepare($query);
7506     $sth->execute;
7507     my $insert_numberpatterns_sth = $dbh->prepare(qq|
7508         INSERT INTO subscription_numberpatterns
7509              (label, displayorder, description, numberingmethod,
7510             label1, add1, every1, whenmorethan1, setto1, numbering1,
7511             label2, add2, every2, whenmorethan2, setto2, numbering2,
7512             label3, add3, every3, whenmorethan3, setto3, numbering3)
7513         VALUES
7514             (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
7515     |);
7516     my $check_numberpatterns_sth = $dbh->prepare(qq|
7517         SELECT * FROM subscription_numberpatterns
7518         WHERE (add1 = ? OR (add1 IS NULL AND ? IS NULL)) AND (add2 = ? OR (add2 IS NULL AND ? IS NULL))
7519         AND (add3 = ? OR (add3 IS NULL AND ? IS NULL)) AND (every1 = ? OR (every1 IS NULL AND ? IS NULL))
7520         AND (every2 = ? OR (every2 IS NULL AND ? IS NULL)) AND (every3 = ? OR (every3 IS NULL AND ? IS NULL))
7521         AND (whenmorethan1 = ? OR (whenmorethan1 IS NULL AND ? IS NULL)) AND (whenmorethan2 = ? OR (whenmorethan2 IS NULL AND ? IS NULL))
7522         AND (whenmorethan3 = ? OR (whenmorethan3 IS NULL AND ? IS NULL)) AND (setto1 = ? OR (setto1 IS NULL AND ? IS NULL))
7523         AND (setto2 = ? OR (setto2 IS NULL AND ? IS NULL)) AND (setto3 = ? OR (setto3 IS NULL AND ? IS NULL))
7524         AND (numberingmethod = ? OR (numberingmethod IS NULL AND ? IS NULL))
7525         LIMIT 1
7526     |);
7527     my $update_subscription_sth = $dbh->prepare(qq|
7528         UPDATE subscription
7529         SET numberpattern = ?,
7530             periodicity = ?
7531         WHERE subscriptionid = ?
7532     |);
7533
7534     my $i = 1;
7535     while(my $sub = $sth->fetchrow_hashref) {
7536         $check_numberpatterns_sth->execute(
7537             $sub->{add1}, $sub->{add1}, $sub->{add2}, $sub->{add2}, $sub->{add3}, $sub->{add3},
7538             $sub->{every1}, $sub->{every1}, $sub->{every2}, $sub->{every2}, $sub->{every3}, $sub->{every3},
7539             $sub->{whenmorethan1}, $sub->{whenmorethan1}, $sub->{whenmorethan2}, $sub->{whenmorethan2},
7540             $sub->{whenmorethan3}, $sub->{whenmorethan3}, $sub->{setto1}, $sub->{setto1}, $sub->{setto2},
7541             $sub->{setto2}, $sub->{setto3}, $sub->{setto3}, $sub->{numberingmethod}, $sub->{numberingmethod}
7542         );
7543         my $p = $check_numberpatterns_sth->fetchrow_hashref;
7544         if (defined $p) {
7545             # Pattern already exists, link to it
7546             $update_subscription_sth->execute($p->{id},
7547                 $frequencies_mapping->{$sub->{periodicity}},
7548                 $sub->{subscriptionid});
7549         } else {
7550             # Create a new numbering pattern for this subscription
7551             my $ok = $insert_numberpatterns_sth->execute(
7552                 "Backup pattern $i", 4+$i, "Automatically created pattern by updatedatabase", $sub->{numberingmethod},
7553                 "X", $sub->{add1}, $sub->{every1}, $sub->{whenmorethan1}, $sub->{setto1}, undef,
7554                 "Y", $sub->{add2}, $sub->{every2}, $sub->{whenmorethan2}, $sub->{setto2}, undef,
7555                 "Z", $sub->{add3}, $sub->{every3}, $sub->{whenmorethan3}, $sub->{setto3}, undef
7556             );
7557             if($ok) {
7558                 my $id = $dbh->last_insert_id(undef, undef, 'subscription_numberpatterns', undef);
7559                 # Link to subscription_numberpatterns and subscription_frequencies
7560                 $update_subscription_sth->execute($id,
7561                     $frequencies_mapping->{$sub->{periodicity}},
7562                     $sub->{subscriptionid});
7563             }
7564             $i++;
7565         }
7566     }
7567
7568     # Remove now useless columns
7569     $dbh->do(qq|
7570         ALTER TABLE subscription
7571         DROP COLUMN numberingmethod,
7572         DROP COLUMN add1,
7573         DROP COLUMN every1,
7574         DROP COLUMN whenmorethan1,
7575         DROP COLUMN setto1,
7576         DROP COLUMN add2,
7577         DROP COLUMN every2,
7578         DROP COLUMN whenmorethan2,
7579         DROP COLUMN setto2,
7580         DROP COLUMN add3,
7581         DROP COLUMN every3,
7582         DROP COLUMN whenmorethan3,
7583         DROP COLUMN setto3,
7584         DROP COLUMN dow,
7585         DROP COLUMN issuesatonce,
7586         DROP COLUMN hemisphere,
7587         ADD COLUMN countissuesperunit INTEGER NOT NULL DEFAULT 1 AFTER periodicity,
7588         ADD COLUMN skip_serialseq BOOLEAN NOT NULL DEFAULT 0 AFTER irregularity,
7589         ADD COLUMN locale VARCHAR(80) DEFAULT NULL AFTER numberpattern,
7590         ADD CONSTRAINT subscription_ibfk_1 FOREIGN KEY (periodicity) REFERENCES subscription_frequencies (id) ON DELETE SET NULL ON UPDATE CASCADE,
7591         ADD CONSTRAINT subscription_ibfk_2 FOREIGN KEY (numberpattern) REFERENCES subscription_numberpatterns (id) ON DELETE SET NULL ON UPDATE CASCADE
7592     |);
7593
7594     # Set firstacquidate if not already set (firstacquidate is now mandatory)
7595     my $get_first_planneddate_sth = $dbh->prepare(qq|
7596         SELECT planneddate
7597         FROM serial
7598         WHERE subscriptionid = ?
7599         ORDER BY serialid
7600         LIMIT 1
7601     |);
7602     my $update_firstacquidate_sth = $dbh->prepare(qq|
7603         UPDATE subscription
7604         SET firstacquidate = ?
7605         WHERE subscriptionid = ?
7606     |);
7607     my $get_subscriptions_sth = $dbh->prepare(qq|
7608         SELECT subscriptionid, startdate
7609         FROM subscription
7610         WHERE firstacquidate IS NULL
7611           OR firstacquidate = '0000-00-00'
7612     |);
7613     $get_subscriptions_sth->execute;
7614     while ( my ($subscriptionid, $startdate) = $get_subscriptions_sth->fetchrow ) {
7615         # Try to get the planned date of the first serial
7616         $get_first_planneddate_sth->execute($subscriptionid);
7617         my ($first_planneddate) = $get_first_planneddate_sth->fetchrow;
7618         if ($first_planneddate and $first_planneddate =~ /^\d{4}-\d{2}-\d{2}$/) {
7619             $update_firstacquidate_sth->execute($first_planneddate, $subscriptionid);
7620         } else {
7621             # Defaults to subscription start date
7622             $update_firstacquidate_sth->execute($startdate, $subscriptionid);
7623         }
7624     }
7625
7626     print "Upgrade to $DBversion done (Bug 7688: add subscription_frequencies and subscription_numberpatterns tables)\n";
7627     SetVersion($DBversion);
7628 }
7629
7630 $DBversion = "3.13.00.034";
7631 if ( CheckVersion($DBversion) ) {
7632     $dbh->do("
7633         ALTER TABLE `import_batches`
7634         CHANGE `item_action` `item_action`
7635           ENUM( 'always_add', 'add_only_for_matches', 'add_only_for_new', 'ignore', 'replace' )
7636           NOT NULL DEFAULT 'always_add'
7637     ");
7638     print "Upgrade to $DBversion done (Bug 7131 - way to overlay items in in marc import)\n";
7639     SetVersion($DBversion);
7640 }
7641
7642 $DBversion ="3.13.00.035";
7643 if ( CheckVersion($DBversion) ) {
7644     $dbh->do(q{
7645 CREATE TABLE borrower_debarments (
7646   borrower_debarment_id int(11) NOT NULL AUTO_INCREMENT,
7647   borrowernumber int(11) NOT NULL,
7648   expiration date DEFAULT NULL,
7649   `type` enum('SUSPENSION','OVERDUES','MANUAL') NOT NULL DEFAULT 'MANUAL',
7650   `comment` text,
7651   manager_id int(11) DEFAULT NULL,
7652   created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
7653   updated timestamp NULL DEFAULT NULL,
7654   PRIMARY KEY (borrower_debarment_id),
7655   KEY borrowernumber (borrowernumber) ,
7656   CONSTRAINT `borrower_debarments_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
7657     ON DELETE CASCADE ON UPDATE CASCADE
7658 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7659     });
7660
7661     # debarments with end date
7662     $dbh->do(q{
7663 INSERT INTO borrower_debarments ( borrowernumber, expiration, comment ) SELECT borrowernumber, debarred, debarredcomment FROM borrowers WHERE debarred IS NOT NULL AND debarred <> '9999-12-31'
7664     });
7665     # debarments with no end date
7666     $dbh->do(q{
7667 INSERT INTO borrower_debarments ( borrowernumber, comment ) SELECT borrowernumber, debarredcomment FROM borrowers WHERE debarred = '9999-12-31'
7668     });
7669
7670     $dbh->do(q{
7671 INSERT IGNORE INTO systempreferences (variable,value,explanation,type) VALUES
7672 ('AutoRemoveOverduesRestrictions','0','Defines whether an OVERDUES debarment should be lifted automatically if all overdue items are returned by the patron.','YesNo')
7673     });
7674
7675     print "Upgrade to $DBversion done (Bug 2720 - Overdues which debar automatically should undebar automatically when returned)\n";
7676     SetVersion($DBversion);
7677 }
7678
7679 $DBversion = "3.13.00.036";
7680 if ( CheckVersion($DBversion) ) {
7681     $dbh->do(qq{
7682         INSERT INTO systempreferences (variable, value, explanation, options, type)
7683         VALUES ('StaffDetailItemSelection', '1', 'Enable item selection in record detail page', NULL, 'YesNo')
7684     });
7685     print "Upgrade to $DBversion done (Add system preference StaffDetailItemSelection)\n";
7686     SetVersion($DBversion);
7687 }
7688
7689 $DBversion = "3.13.00.037";
7690 if ( CheckVersion($DBversion) ) {
7691     #add phone if it is not there already (explains the ignore option)
7692     $dbh->do("
7693 INSERT IGNORE INTO message_transport_types (message_transport_type) values ('phone');
7694     ");
7695     print "Upgrade to $DBversion done (Bug 10572: Add phone to message_transport_types table for new installs)\n";
7696     SetVersion($DBversion);
7697 }
7698
7699 $DBversion = "3.13.00.038";
7700 if ( CheckVersion($DBversion) ) {
7701     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES(15, 'superserials', 'Manage subscriptions from any branch (only applies when IndependentBranches is used)')");
7702     print "Upgrade to $DBversion done (Bug 8435: Add superserials permission)\n";
7703     SetVersion($DBversion);
7704 }
7705
7706 $DBversion = "3.13.00.039";
7707 if ( CheckVersion($DBversion) ) {
7708     $dbh->do("
7709         ALTER TABLE aqbasket ADD branch varchar(10) default NULL
7710     ");
7711     $dbh->do("
7712         ALTER TABLE aqbasket
7713         ADD CONSTRAINT aqbasket_ibfk_4 FOREIGN KEY (branch)
7714             REFERENCES branches (branchcode)
7715             ON UPDATE CASCADE ON DELETE SET NULL
7716     ");
7717     $dbh->do("
7718         DROP TABLE IF EXISTS aqbasketusers
7719     ");
7720     $dbh->do("
7721         CREATE TABLE aqbasketusers (
7722             basketno int(11) NOT NULL,
7723             borrowernumber int(11) NOT NULL,
7724             PRIMARY KEY (basketno,borrowernumber),
7725             CONSTRAINT aqbasketusers_ibfk_1 FOREIGN KEY (basketno) REFERENCES aqbasket (basketno) ON DELETE CASCADE ON UPDATE CASCADE,
7726             CONSTRAINT aqbasketusers_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
7727         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7728     ");
7729     $dbh->do("
7730         INSERT INTO permissions (module_bit, code, description)
7731         VALUES (11, 'order_manage_all', 'Manage all orders and baskets, regardless of restrictions on them')
7732     ");
7733
7734     print "Upgrade to $DBversion done (Add branch and users list to baskets. "
7735         . "New permission order_manage_all)\n";
7736     SetVersion($DBversion);
7737 }
7738
7739 $DBversion = "3.13.00.040";
7740 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
7741     $dbh->do("CREATE TABLE IF NOT EXISTS marc_modification_templates (
7742               template_id int(11) NOT NULL auto_increment,
7743               name text NOT NULL,
7744               PRIMARY KEY  (template_id)
7745               ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;"
7746     );
7747
7748     $dbh->do("
7749       CREATE TABLE IF NOT EXISTS marc_modification_template_actions (
7750       mmta_id int(11) NOT NULL auto_increment,
7751       template_id int(11) NOT NULL,
7752       ordering int(3) NOT NULL,
7753       action enum('delete_field','update_field','move_field','copy_field') NOT NULL,
7754       field_number smallint(6) NOT NULL default '0',
7755       from_field varchar(3) NOT NULL,
7756       from_subfield varchar(1) NULL,
7757       field_value varchar(100) default NULL,
7758       to_field varchar(3) default NULL,
7759       to_subfield varchar(1) default NULL,
7760       to_regex_search text,
7761       to_regex_replace text,
7762       to_regex_modifiers varchar(8) default '',
7763       conditional enum('if','unless') default NULL,
7764       conditional_field varchar(3) default NULL,
7765       conditional_subfield varchar(1) default NULL,
7766       conditional_comparison enum('exists','not_exists','equals','not_equals') default NULL,
7767       conditional_value text,
7768       conditional_regex tinyint(1) NOT NULL default '0',
7769       description text,
7770       PRIMARY KEY  (mmta_id),
7771       CONSTRAINT `mmta_ibfk_1` FOREIGN KEY (`template_id`) REFERENCES `marc_modification_templates` (`template_id`) ON DELETE CASCADE ON UPDATE CASCADE
7772       ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7773     ");
7774
7775     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('13', 'marc_modification_templates', 'Manage marc modification templates')");
7776
7777     print "Upgrade to $DBversion done ( Bug 8015: Added tables for MARC Modification Framework )\n";
7778     SetVersion($DBversion);
7779 }
7780
7781 $DBversion = "3.13.00.041";
7782 if(CheckVersion($DBversion)) {
7783     $dbh->do(q{
7784         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');
7785     });
7786     print "Upgrade to $DBversion done (Bug 10986: Added AcqItemSetSubfieldsWhenReceived syspref)\n";
7787     SetVersion($DBversion);
7788 }
7789
7790 $DBversion = "3.13.00.042";
7791 if(CheckVersion($DBversion)) {
7792     print "Upgrade to $DBversion done (Koha 3.14 beta)\n";
7793     SetVersion($DBversion);
7794 }
7795
7796 $DBversion = "3.13.00.043";
7797 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
7798     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('SearchEngine','Zebra','Solr|Zebra','Search Engine','Choice')");
7799     print "Upgrade to $DBversion done (Bug 11196: Add system preference SearchEngine if missing )\n";
7800     SetVersion($DBversion);
7801 }
7802
7803 $DBversion = "3.14.00.000";
7804 if ( CheckVersion($DBversion) ) {
7805     print "Upgrade to $DBversion done (3.14.0 release)\n";
7806     SetVersion ($DBversion);
7807 }
7808
7809 $DBversion = '3.15.00.000';
7810 if ( CheckVersion($DBversion) ) {
7811     print "Upgrade to $DBversion done (the road goes ever on)\n";
7812     SetVersion ($DBversion);
7813 }
7814
7815 $DBversion = "3.15.00.001";
7816 if ( CheckVersion($DBversion) ) {
7817     $dbh->do("UPDATE systempreferences SET value='clear' where variable = 'CircAutoPrintQuickSlip' and value = '0'");
7818     $dbh->do("UPDATE systempreferences SET value='qslip' where variable = 'CircAutoPrintQuickSlip' and value = '1'");
7819     $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'");
7820     print "Upgrade to $DBversion done (Bug 11040: Add option to print full slip when checking out a null barcode)\n";
7821     SetVersion($DBversion);
7822 }
7823
7824 $DBversion = "3.15.00.002";
7825 if(CheckVersion($DBversion)) {
7826     $dbh->do("ALTER TABLE deleteditems MODIFY materials text;");
7827     print "Upgrade to $DBversion done (Bug 11275: alter deleteditems.materials from varchar(10) to text)\n";
7828     SetVersion($DBversion);
7829 }
7830
7831 $DBversion = "3.15.00.003";
7832 if ( CheckVersion($DBversion) ) {
7833     $dbh->do(q{
7834         UPDATE accountlines
7835         SET description = ''
7836         WHERE description IN (
7837             ' New Card',
7838             ' Fine',
7839             ' Sundry',
7840             'Writeoff',
7841             ' Account Management fee',
7842             'Payment,thanks', 'Payment,thanks - ',
7843             ' Lost Item'
7844         )
7845     });
7846     print "Upgrade to $DBversion done (Bug 2546: Update fine descriptions)\n";
7847     SetVersion($DBversion);
7848 }
7849
7850 $DBversion = "3.15.00.004";
7851 if ( CheckVersion($DBversion) ) {
7852     if ( C4::Context->preference("marcflavour") eq 'MARC21' ) {
7853         $dbh->do(qq{
7854             INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian, libopac, repeatable, mandatory,
7855             kohafield, tab, authorised_value, authtypecode, value_builder, isurl, hidden, frameworkcode, seealso, link,
7856             defaultvalue) VALUES
7857             ('015', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7858             ('020', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7859             ('024', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7860             ('027', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7861             ('800', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7862             ('810', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7863             ('811', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7864             ('830', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL);
7865         });
7866         $dbh->do(qq{
7867             INSERT IGNORE INTO auth_subfield_structure (authtypecode, tagfield, tagsubfield, liblibrarian, libopac, repeatable,
7868             mandatory, tab, authorised_value, value_builder, seealso, isurl, hidden, linkid, kohafield, frameworkcode) VALUES
7869             ('', '020', 'q', 'Qualifying information', 'Qualifying information', 1, 0, 0, NULL, NULL, NULL, 0, 0, '', '', ''),
7870             ('', '024', 'q', 'Qualifying information', 'Qualifying information', 1, 0, 0, NULL, NULL, NULL, 0, 0, '', '', '');
7871         });
7872     }
7873     print "Upgrade to $DBversion done (Bug 10970 - Update MARC21 frameworks to Update Nr. 17 - DB update)\n";
7874     SetVersion($DBversion);
7875 }
7876
7877 $DBversion = "3.15.00.005";
7878 if ( CheckVersion($DBversion) ) {
7879    $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('AcquisitionDetails', '1', '', 'Hide/Show acquisition details on the biblio detail page.', 'YesNo');");
7880    print "Upgrade to $DBversion done (Bug 8230: Add AcquisitionDetails system preference)\n";
7881    SetVersion ($DBversion);
7882 }
7883
7884 $DBversion = "3.15.00.006";
7885 if(CheckVersion($DBversion)) {
7886     $dbh->do(q{
7887         ALTER TABLE `borrowers`
7888         ADD KEY `surname_idx` (`surname`(255)),
7889         ADD KEY `firstname_idx` (`firstname`(255)),
7890         ADD KEY `othernames_idx` (`othernames`(255))
7891     });
7892     print "Upgrade to $DBversion done (Bug 11249 - Add DB indexes on borrower names)\n";
7893     SetVersion($DBversion);
7894 }
7895
7896 $DBversion = "3.15.00.007";
7897 if ( CheckVersion($DBversion) ) {
7898    $dbh->do("ALTER TABLE items ADD itemlost_on DATETIME NULL AFTER itemlost");
7899    $dbh->do("ALTER TABLE items ADD withdrawn_on DATETIME NULL AFTER withdrawn");
7900    $dbh->do("ALTER TABLE deleteditems ADD itemlost_on DATETIME NULL AFTER itemlost");
7901    $dbh->do("ALTER TABLE deleteditems ADD withdrawn_on DATETIME NULL AFTER withdrawn");
7902    print "Upgrade to $DBversion done (Bug 9673 - Track when items are marked as lost or withdrawn)\n";
7903    SetVersion ($DBversion);
7904 }
7905
7906 $DBversion = "3.15.00.008";
7907 if ( CheckVersion($DBversion) ) {
7908     $dbh->do(q{
7909         ALTER TABLE collections_tracking CHANGE ctId collections_tracking_id integer(11) NOT NULL auto_increment;
7910     });
7911     print "Upgrade to $DBversion done (Bug 11384) - change name of collections_tracker.ctId column)\n";
7912    SetVersion ($DBversion);
7913 }
7914
7915 $DBversion = "3.15.00.009";
7916 if ( CheckVersion($DBversion) ) {
7917     $dbh->do(q{
7918         ALTER TABLE suggestions MODIFY suggesteddate DATE NOT NULL
7919     });
7920     print "Upgrade to $DBversion done (Bug 11391) - drop default value on suggestions.suggesteddate column)\n";
7921    SetVersion ($DBversion);
7922 }
7923
7924 $DBversion = "3.15.00.010";
7925 if(CheckVersion($DBversion)) {
7926     $dbh->do("ALTER TABLE deleteditems DROP COLUMN marc");
7927     print "Upgrade to $DBversion done (Bug 6331: remove obsolete column in deleteditems.marc)\n";
7928     SetVersion ($DBversion);
7929 }
7930
7931 $DBversion = "3.15.00.011";
7932 if(CheckVersion($DBversion)) {
7933     $dbh->do("UPDATE marc_subfield_structure SET maxlength=9999 WHERE maxlength IS NULL OR maxlength=0;");
7934     print "Upgrade to $DBversion done (Bug 8018: set 9999 as default max length for subfields)\n";
7935     SetVersion ($DBversion);
7936 }
7937
7938 $DBversion = "3.15.00.012";
7939 if ( CheckVersion($DBversion) ) {
7940     $dbh->do(q{
7941         INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'force_checkout', 'Force checkout if a limitation exists')
7942     });
7943     $dbh->do(q{
7944         INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'manage_restrictions', 'Manage restrictions for accounts')
7945     });
7946     $dbh->do(q{
7947         INSERT INTO user_permissions (borrowernumber, module_bit, code)
7948             SELECT user_permissions.borrowernumber, 1, 'force_checkout'
7949             FROM user_permissions
7950             LEFT JOIN borrowers USING(borrowernumber)
7951             WHERE borrowers.flags & (1 << 1)
7952     });
7953     $dbh->do(q{
7954         INSERT INTO user_permissions (borrowernumber, module_bit, code)
7955             SELECT user_permissions.borrowernumber, 1, 'manage_restrictions'
7956             FROM user_permissions
7957             LEFT JOIN borrowers USING(borrowernumber)
7958             WHERE borrowers.flags & (1 << 1)
7959     });
7960
7961     print "Upgrade to $DBversion done (Bug 10863 - Add permissions force_checkout and manage_restrictions)\n";
7962     SetVersion($DBversion);
7963 }
7964
7965 $DBversion = "3.15.00.013";
7966 if(CheckVersion($DBversion)) {
7967     $dbh->do(q{
7968         UPDATE systempreferences
7969         SET explanation = 'Upon receiving items, update their subfields if they were created when placing an order (e.g. o=5|a="foo bar")'
7970         WHERE variable = "AcqItemSetSubfieldsWhenReceived"
7971     });
7972
7973     $dbh->do(q{
7974         UPDATE systempreferences
7975         SET value = ''
7976         WHERE variable = "AcqItemSetSubfieldsWhenReceived"
7977             AND value = "0"
7978     });
7979     print "Upgrade to $DBversion done (Bug 11237: Update explanation and default value for AcqItemSetSubfieldsWhenReceived syspref)\n";
7980     SetVersion($DBversion);
7981 }
7982
7983 $DBversion = "3.15.00.014";
7984 if (CheckVersion($DBversion)) {
7985     $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');");
7986     print "Upgrade to $DBversion done (Bug 11415: add system preference for automatic self checkout receipt printing)\n";
7987     SetVersion($DBversion);
7988 }
7989
7990 $DBversion = "3.15.00.015";
7991 if (CheckVersion($DBversion)) {
7992     $dbh->do("INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
7993         ('OpacSuggestionManagedBy',1,'','Show the name of the staff member who managed a suggestion in OPAC','YesNo');");
7994     print "Upgrade to $DBversion done (Bug 10907: Add OpacSuggestionManagedBy system preference)\n";
7995     SetVersion($DBversion);
7996 }
7997
7998 $DBversion = "3.15.00.016";
7999 if (CheckVersion($DBversion)) {
8000     $dbh->do("ALTER TABLE biblioitems CHANGE url url TEXT NULL DEFAULT NULL");
8001     $dbh->do("ALTER TABLE deletedbiblioitems CHANGE url url TEXT NULL DEFAULT NULL");
8002     print "Upgrade to $DBversion done (Bug 11268 - Biblioitems URL field is too small for some URLs)\n";
8003     SetVersion($DBversion);
8004 }
8005
8006 $DBversion = "3.15.00.017";
8007 if(CheckVersion($DBversion)) {
8008     $dbh->do(q{
8009         UPDATE systempreferences
8010         SET explanation = 'Define the contents of UNIMARC authority control field 100 position 08-35'
8011         WHERE variable = "UNIMARCAuthorityField100"
8012     });
8013     $dbh->do(q{
8014         UPDATE systempreferences
8015         SET explanation = 'Define the contents of MARC21 authority control field 008 position 06-39'
8016         WHERE variable = "MARCAuthorityControlField008"
8017     });
8018     $dbh->do(q{
8019         UPDATE systempreferences
8020         SET explanation = 'Define MARC Organization Code for MARC21 records - http://www.loc.gov/marc/organizations/orgshome.html'
8021         WHERE variable = "MARCOrgCode"
8022     });
8023     print "Upgrade to $DBversion done (Bug 11611 - fix possible confusion between UNIMARC and MARC21 in some sysprefs)\n";
8024     SetVersion($DBversion);
8025 }
8026
8027 $DBversion = "3.15.00.018";
8028 if ( CheckVersion($DBversion) ) {
8029     $dbh->{AutoCommit} = 0;
8030     $dbh->{RaiseError} = 1;
8031
8032     eval {
8033         $dbh->selectcol_arrayref(q|SELECT COUNT(*) FROM roadtype|);
8034     };
8035     unless ( $@ ) {
8036         my $av_added = $dbh->do(q|
8037             INSERT INTO authorised_values(category, authorised_value, lib, lib_opac)
8038                 SELECT 'ROADTYPE', roadtypeid, road_type, road_type
8039                 FROM roadtype;
8040         |);
8041
8042         my $rt_deleted = $dbh->do(q|
8043             DELETE FROM roadtype
8044         |);
8045
8046         if ( $av_added == $rt_deleted or $rt_deleted eq "0E0" ) {
8047             $dbh->do(q|
8048                 DROP TABLE roadtype;
8049             |);
8050             $dbh->commit;
8051             print "Upgrade to $DBversion done (Bug 7372: Move road types from the roadtype table to the ROADTYPE authorised values)\n";
8052             SetVersion($DBversion);
8053         } else {
8054             print "Upgrade to $DBversion failed (Bug 7372: Move road types from the roadtype table to the ROADTYPE authorised values.\nTransaction aborted because $@\n)";
8055             $dbh->rollback;
8056         }
8057     }
8058     $dbh->{AutoCommit} = 1;
8059     $dbh->{RaiseError} = 0;
8060 }
8061
8062 $DBversion = "3.15.00.019";
8063 if ( CheckVersion($DBversion) ) {
8064     $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')");
8065     print "Upgrade to $DBversion done (Bug 11256: Add system preference OpacMaxItemsToDisplay)\n";
8066     SetVersion($DBversion);
8067 }
8068
8069 $DBversion = "3.15.00.020";
8070 if ( CheckVersion($DBversion) ) {
8071     $dbh->do(q|
8072         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')
8073     |);
8074     print "Upgrade to $DBversion done (Bug 11343: Add system preference MaxItemsForBatch )\n";
8075     SetVersion($DBversion);
8076 }
8077
8078 $DBversion = "3.15.00.021";
8079 if(CheckVersion($DBversion)) {
8080     $dbh->do(q{
8081         ALTER TABLE `action_logs`
8082             DROP KEY timestamp,
8083             ADD KEY `timestamp_idx` (`timestamp`),
8084             ADD KEY `user_idx` (`user`),
8085             ADD KEY `module_idx` (`module`(255)),
8086             ADD KEY `action_idx` (`action`(255)),
8087             ADD KEY `object_idx` (`object`),
8088             ADD KEY `info_idx` (`info`(255))
8089     });
8090     print "Upgrade to $DBversion done (Bug 3445: Add indexes to action_logs table)\n";
8091     SetVersion($DBversion);
8092 }
8093
8094 $DBversion = "3.15.00.022";
8095 if (CheckVersion($DBversion)) {
8096     $dbh->do(q|
8097         DELETE FROM systempreferences WHERE variable= "memberofinstitution"
8098     |);
8099     print "Upgrade to $DBversion done (Bug 11751: Remove memberofinstitytion system preference)\n";
8100     SetVersion($DBversion);
8101 }
8102
8103 $DBversion = "3.15.00.023";
8104 if ( CheckVersion($DBversion) ) {
8105    $dbh->do("
8106        INSERT INTO systempreferences (variable,value,options,explanation,type)
8107        VALUES('CardnumberLength', '', '', 'Set a length for card numbers.', 'Free');
8108     ");
8109    print "Upgrade to $DBversion done (Bug 10861: Add CardnumberLength syspref)\n";
8110    SetVersion ($DBversion);
8111 }
8112
8113 $DBversion = "3.15.00.024";
8114 if ( CheckVersion($DBversion) ) {
8115     $dbh->do(q{
8116         DELETE FROM systempreferences WHERE variable = 'NoZebraIndexes'
8117     });
8118     print "Upgrade to $DBversion done (Bug 10012 - remove last vestiges of NoZebra)\n";
8119     SetVersion($DBversion);
8120 }
8121
8122 $DBversion = "3.15.00.025";
8123 if ( CheckVersion($DBversion) ) {
8124     $dbh->do(q{
8125         DROP TABLE aqorderdelivery;
8126     });
8127     print "Upgrade to $DBversion done (Bug 11928 - remove unused table)\n";
8128     SetVersion($DBversion);
8129 }
8130
8131 $DBversion = "3.15.00.026";
8132 if ( CheckVersion($DBversion) ) {
8133     $dbh->do(q{
8134         UPDATE language_descriptions SET description = 'Հայերեն' WHERE subtag = 'hy' AND lang = 'hy';
8135     });
8136     print "Upgrade to $DBversion done (Bug 11973 - Fix Armenian language description)\n";
8137     SetVersion($DBversion);
8138 }
8139
8140 $DBversion = "3.15.00.027";
8141 if (CheckVersion($DBversion)) {
8142     $dbh->do(q{
8143         ALTER TABLE opac_news ADD branchcode varchar(10) DEFAULT NULL
8144                                   AFTER idnew,
8145                               ADD CONSTRAINT opac_news_branchcode_ibfk
8146                                   FOREIGN KEY (branchcode)
8147                                   REFERENCES branches (branchcode)
8148                                   ON DELETE CASCADE ON UPDATE CASCADE;
8149     });
8150     print "Upgrade to $DBversion done (Bug 7567: Add branchcode to opac_news)\n";
8151     SetVersion($DBversion);
8152 }
8153
8154 $DBversion = "3.15.00.028";
8155 if(CheckVersion($DBversion)) {
8156     $dbh->do(q{
8157         ALTER TABLE issuingrules ADD norenewalbefore int(4) default NULL AFTER renewalperiod
8158     });
8159     print "Upgrade to $DBversion done (Bug 7413: Allow OPAC renewal x days before due date)\n";
8160     SetVersion($DBversion);
8161 }
8162
8163 $DBversion = "3.15.00.029";
8164 if ( CheckVersion($DBversion) ) {
8165     $dbh->do(q{
8166         UPDATE borrower_debarments SET expiration = NULL WHERE expiration = '9999-12-31'
8167     });
8168     print "Upgrade to $DBversion done (Bug 11846 - correct borrower_debarments with expiration 9999-12-31)\n";
8169     SetVersion($DBversion);
8170 }
8171
8172 $DBversion = "3.15.00.030";
8173 if(CheckVersion($DBversion)) {
8174     $dbh->do(q|
8175         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')
8176     |);
8177     print "Upgrade to $DBversion done (Bug 12052: Add OPACMySummaryNote syspref)\n";
8178     SetVersion($DBversion);
8179 }
8180
8181 $DBversion = "3.15.00.031";
8182 if ( CheckVersion($DBversion) ) {
8183    $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('10', 'writeoff', 'Write off fines and fees')");
8184    $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('10', 'remaining_permissions', 'Remaining permissions for managing fines and fees')");
8185    print "Upgrade to $DBversion done (Bug 9448 - Add separate permission for writing off fees)\n";
8186    SetVersion ($DBversion);
8187 }
8188
8189 $DBversion = "3.15.00.032";
8190 if ( CheckVersion($DBversion) ) {
8191     $dbh->do("ALTER TABLE aqorders CHANGE notes order_internalnote MEDIUMTEXT;");
8192     $dbh->do("ALTER TABLE aqorders ADD COLUMN order_vendornote MEDIUMTEXT AFTER order_internalnote;");
8193     print "Upgrade to $DBversion done (Bug 9416 - In each order, add a new note made for the vendor)\n";
8194    SetVersion ($DBversion);
8195 }
8196
8197 $DBversion = "3.15.00.033";
8198 if ( CheckVersion($DBversion) ) {
8199     $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')");
8200     print "Upgrade to $DBversion done (Bug 10951: Add NoLoginInstructions pref)\n";
8201     SetVersion($DBversion);
8202 }
8203
8204 $DBversion = "3.15.00.034";
8205 if ( CheckVersion($DBversion) ) {
8206     $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')");
8207     print "Upgrade to $DBversion done (Bug 10986: system preferences to limit languages in advanced search )\n";
8208     SetVersion ($DBversion);
8209 }
8210
8211 $DBversion = "3.15.00.035";
8212 if ( CheckVersion($DBversion) ) {
8213     #insert a notice for sharing a list and accepting a share
8214     $dbh->do("
8215 INSERT INTO letter (module, code, branchcode, name, is_html, title, content)
8216 VALUES ( 'members', 'SHARE_INVITE', '', 'Invitation for sharing a list', '0', 'Share list <<listname>>', 'Dear patron,
8217
8218 One of our patrons, <<borrowers.firstname>> <<borrowers.surname>>, invites you to share a list <<listname>> in our library catalog.
8219
8220 To access this shared list, please click on the following URL or copy-and-paste it into your browser address bar.
8221
8222 <<shareurl>>
8223
8224 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.
8225
8226 Thank you.
8227
8228 Your library.'
8229     )");
8230     $dbh->do("
8231 INSERT INTO letter (module, code, branchcode, name, is_html, title, content)
8232 VALUES ( 'members', 'SHARE_ACCEPT', '', 'Notification about an accepted share', '0', 'Share on list <<listname>> accepted', 'Dear patron,
8233
8234 We want to inform you that <<borrowers.firstname>> <<borrowers.surname>> accepted your invitation to share your list <<listname>> in our library catalog.
8235
8236 Thank you.
8237
8238 Your library.'
8239     )");
8240     print "Upgrade to $DBversion done (Bug 9032: Share a list)\n";
8241     SetVersion($DBversion);
8242 }
8243
8244 $DBversion = "3.15.00.036";
8245 if ( CheckVersion($DBversion) ) {
8246     $dbh->do(q{
8247         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
8248         VALUES('AllowMultipleIssuesOnABiblio',1,'Allow/Don\'t allow patrons to check out multiple items from one biblio','','YesNo')
8249     });
8250
8251     print "Upgrade to $DBversion done (Bug 10859 - Add system preference AllowMultipleIssuesOnABiblio)\n";
8252     SetVersion($DBversion);
8253 }
8254
8255 $DBversion = "3.15.00.037";
8256 if(CheckVersion($DBversion)) {
8257     $dbh->do(q{
8258         ALTER TABLE itemtypes ADD sip_media_type VARCHAR( 3 ) DEFAULT NULL AFTER checkinmsgtype
8259     });
8260     $dbh->do(q{
8261         INSERT INTO authorised_values (category, authorised_value, lib) VALUES
8262          ('SIP_MEDIA_TYPE', '000', 'Other'),
8263          ('SIP_MEDIA_TYPE', '001', 'Book'),
8264          ('SIP_MEDIA_TYPE', '002', 'Magazine'),
8265          ('SIP_MEDIA_TYPE', '003', 'Bound journal'),
8266          ('SIP_MEDIA_TYPE', '004', 'Audio tape'),
8267          ('SIP_MEDIA_TYPE', '005', 'Video tape'),
8268          ('SIP_MEDIA_TYPE', '006', 'CD/CDROM'),
8269          ('SIP_MEDIA_TYPE', '007', 'Diskette'),
8270          ('SIP_MEDIA_TYPE', '008', 'Book with diskette'),
8271          ('SIP_MEDIA_TYPE', '009', 'Book with CD'),
8272          ('SIP_MEDIA_TYPE', '010', 'Book with audio tape')
8273     });
8274     print "Upgrade to $DBversion done (Bug 11351 - Add support for SIP2 media type)\n";
8275     SetVersion($DBversion);
8276 }
8277
8278 $DBversion = '3.15.00.038';
8279 if ( CheckVersion($DBversion) ) {
8280     $dbh->do(q{
8281         INSERT INTO  systempreferences (
8282             variable,
8283             value,
8284             options,
8285             explanation,
8286             type
8287             )
8288         VALUES (
8289             'DisplayLibraryFacets',  'holding',  'home|holding|both',  'Defines which library facets to display.',  'Choice'
8290         );
8291     });
8292     print "Upgrade to $DBversion done (Bug 11334 - Add facet for home library)\n";
8293     SetVersion ($DBversion);
8294 }
8295
8296 $DBversion = "3.15.00.039";
8297 if ( CheckVersion($DBversion) ) {
8298
8299     $dbh->do( q{
8300         ALTER TABLE letter ADD COLUMN message_transport_type VARCHAR(20) NOT NULL DEFAULT 'email' AFTER content
8301     } );
8302
8303     $dbh->do( q{
8304         ALTER TABLE letter ADD CONSTRAINT message_transport_type_fk FOREIGN KEY (message_transport_type) REFERENCES message_transport_types(message_transport_type);
8305     } );
8306
8307     $dbh->do( q{
8308         ALTER TABLE letter DROP PRIMARY KEY, ADD PRIMARY KEY (`module`,`code`,`branchcode`, message_transport_type);
8309     } );
8310
8311     $dbh->do( q{
8312         CREATE TABLE overduerules_transport_types(
8313             id INT(11) NOT NULL AUTO_INCREMENT,
8314             branchcode varchar(10) NOT NULL DEFAULT '',
8315             categorycode VARCHAR(10) NOT NULL DEFAULT '',
8316             letternumber INT(1) NOT NULL DEFAULT 1,
8317             message_transport_type VARCHAR(20) NOT NULL DEFAULT 'email',
8318             PRIMARY KEY (id),
8319             CONSTRAINT overduerules_fk FOREIGN KEY (branchcode, categorycode) REFERENCES overduerules (branchcode, categorycode) ON DELETE CASCADE ON UPDATE CASCADE,
8320             CONSTRAINT mtt_fk FOREIGN KEY (message_transport_type) REFERENCES message_transport_types (message_transport_type) ON DELETE CASCADE ON UPDATE CASCADE
8321         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
8322     } );
8323
8324     my $sth = $dbh->prepare( q{
8325         SELECT * FROM overduerules;
8326     } );
8327
8328     $sth->execute;
8329     my $sth_insert_mtt = $dbh->prepare( q{
8330         INSERT INTO overduerules_transport_types (branchcode, categorycode, letternumber, message_transport_type) VALUES ( ?, ?, ?, ? )
8331     } );
8332     while ( my $row = $sth->fetchrow_hashref ) {
8333         my $branchcode = $row->{branchcode};
8334         my $categorycode = $row->{categorycode};
8335         for my $letternumber ( 1 .. 3 ) {
8336             next unless $row->{"letter$letternumber"};
8337             $sth_insert_mtt->execute(
8338                 $branchcode, $categorycode, $letternumber, 'email'
8339             );
8340         }
8341     }
8342
8343     print "Upgrade done (Bug 9016: Adds multi transport types management for notices)\n";
8344     SetVersion($DBversion);
8345 }
8346
8347 $DBversion = "3.15.00.040";
8348 if ( CheckVersion($DBversion) ) {
8349     $dbh->do(q|
8350         UPDATE message_transports SET letter_code='HOLD' WHERE letter_code='HOLD_PHONE' OR letter_code='HOLD_PRINT'
8351     |);
8352     $dbh->do(q|
8353         UPDATE letter SET code='HOLD', message_transport_type='print' WHERE code='HOLD_PRINT'
8354     |);
8355     $dbh->do(q|
8356         UPDATE letter SET code='HOLD', message_transport_type='phone' WHERE code='HOLD_PHONE'
8357     |);
8358     print "Upgrade to $DBversion done (Bug 10845: Multi transport types for holds)\n";
8359     SetVersion($DBversion);
8360 }
8361
8362 $DBversion = "3.15.00.041";
8363 if ( CheckVersion($DBversion) ) {
8364     my $name = $dbh->selectcol_arrayref(q|
8365         SELECT name FROM letter WHERE code="HOLD"
8366     |);
8367     $name = $name->[0];
8368     $dbh->do(q|
8369         UPDATE letter
8370         SET code="HOLD",
8371             message_transport_type="phone",
8372             name= ?
8373         WHERE code="HOLD_PHONE"
8374     |, {}, $name);
8375
8376     $dbh->do(q|
8377         UPDATE letter
8378         SET code="PREDUE",
8379             message_transport_type="phone",
8380             name= ?
8381         WHERE code="PREDUE_PHONE"
8382     |, {}, $name);
8383
8384     $dbh->do(q|
8385         UPDATE letter
8386         SET code="OVERDUE",
8387             message_transport_type="phone",
8388             name= ?
8389         WHERE code="OVERDUE_PHONE"
8390     |, {}, $name);
8391
8392     print "Upgrade to $DBversion done (Bug 11867: Update letters *_PHONE)\n";
8393     SetVersion($DBversion);
8394 }
8395
8396 $DBversion = "3.15.00.042";
8397 if ( CheckVersion($DBversion) ) {
8398     $dbh->do(q{
8399         INSERT INTO systempreferences
8400             (variable,value,explanation,options,type)
8401         VALUES
8402             ('SpecifyReturnDate',0,'Define whether to display \"Specify Return Date\" form in Circulation','','YesNo')
8403     });
8404     print "Upgrade to $DBversion done (Bug 10694 - Allow arbitrary backdating of returns)\n";
8405     SetVersion($DBversion);
8406 }
8407
8408 $DBversion = "3.15.00.043";
8409 if ( CheckVersion($DBversion) ) {
8410     $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')");
8411    print "Upgrade to $DBversion done (Bug 7180: Added MarcFieldsToOrder syspref)\n";
8412    SetVersion ($DBversion);
8413 }
8414
8415 $DBversion = "3.15.00.044";
8416 if ( CheckVersion($DBversion) ) {
8417     $dbh->do("ALTER TABLE currency ADD isocode VARCHAR(5) default NULL AFTER symbol;");
8418     print "Upgrade to $DBversion done (Added isocode to the currency table)\n";
8419     SetVersion($DBversion);
8420 }
8421
8422 $DBversion = "3.15.00.045";
8423 if ( CheckVersion($DBversion) ) {
8424     $dbh->do("
8425         INSERT INTO systempreferences (variable,value,explanation,options,type)
8426         VALUES (
8427             'BlockExpiredPatronOpacActions',
8428             '0',
8429             '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',
8430             NULL,
8431             'YesNo'
8432         )
8433     ");
8434     $dbh->do("ALTER TABLE `categories` ADD COLUMN `BlockExpiredPatronOpacActions` TINYINT(1) DEFAULT -1 NOT NULL AFTER category_type");
8435     print "Upgraded to $DBversion done (Bug 6739 - expired patrons not blocked from opac actions)\n";
8436     SetVersion ($DBversion);
8437 }
8438
8439 $DBversion = "3.15.00.046";
8440 if ( CheckVersion($DBversion) ) {
8441     $dbh->do(q|
8442         ALTER TABLE search_history ADD COLUMN type VARCHAR(16) NOT NULL DEFAULT 'biblio' AFTER query_cgi
8443     |);
8444     print "Upgrade to $DBversion done (Bug 10807 - Add db field search_history.type)\n";
8445     SetVersion($DBversion);
8446 }
8447
8448 $DBversion = "3.15.00.047";
8449 if ( CheckVersion($DBversion) ) {
8450     $dbh->do(q|
8451         INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('EnableSearchHistory','0','','Enable or disable search history','YesNo')
8452     |);
8453     print "Upgrade to $DBversion done (Bug 10862: Add EnableSearchHistory syspref)\n";
8454     SetVersion($DBversion);
8455 }
8456
8457 $DBversion = "3.15.00.048";
8458 if ( CheckVersion($DBversion) ) {
8459     $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')");
8460     $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')");
8461     print "Upgrade to $DBversion done (Bug 10195: Records hidden with OpacSuppression can still be accessed)\n";
8462     SetVersion($DBversion);
8463 }
8464
8465 $DBversion = "3.15.00.049";
8466 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
8467     $dbh->do("ALTER TABLE biblioitems DROP INDEX isbn");
8468     $dbh->do("ALTER TABLE biblioitems DROP INDEX issn");
8469     $dbh->do("ALTER TABLE biblioitems
8470               CHANGE isbn isbn MEDIUMTEXT NULL DEFAULT NULL,
8471               CHANGE issn issn MEDIUMTEXT NULL DEFAULT NULL
8472     ");
8473     $dbh->do("ALTER TABLE biblioitems
8474               ADD INDEX isbn ( isbn ( 255 ) ),
8475               ADD INDEX issn ( issn ( 255 ) )
8476     ");
8477
8478     $dbh->do("ALTER TABLE deletedbiblioitems DROP INDEX isbn");
8479     $dbh->do("ALTER TABLE deletedbiblioitems
8480               CHANGE isbn isbn MEDIUMTEXT NULL DEFAULT NULL,
8481               CHANGE issn issn MEDIUMTEXT NULL DEFAULT NULL
8482     ");
8483     $dbh->do("ALTER TABLE deletedbiblioitems
8484               ADD INDEX isbn ( isbn ( 255 ) )
8485     ");
8486
8487     print "Upgrade to $DBversion done (Bug 5377 - Biblioitems isbn and issn fields too small for multiple ISBN and ISSN)\n";
8488     SetVersion($DBversion);
8489 }
8490
8491 $DBversion = "3.15.00.050";
8492 if ( CheckVersion($DBversion) ) {
8493     $dbh->do("
8494         INSERT INTO systempreferences (
8495             variable,
8496             value,
8497             explanation,
8498             type
8499         ) VALUES (
8500             'AggressiveMatchOnISBN',
8501             '0',
8502             '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',
8503             'YesNo'
8504         )
8505     ");
8506
8507     print "Upgrade to $DBversion done (Bug 10500 - Improve isbn matching when importing records)\n";
8508     SetVersion($DBversion);
8509 }
8510
8511 $DBversion = "3.15.00.051";
8512 if ( CheckVersion($DBversion) ) {
8513     print "Upgrade to $DBversion done (Koha 3.16 beta)\n";
8514     SetVersion($DBversion);
8515 }
8516
8517 $DBversion = "3.15.00.052";
8518 if ( CheckVersion($DBversion) ) {
8519     print "Upgrade to $DBversion done (Koha 3.16 RC)\n";
8520     SetVersion($DBversion);
8521 }
8522
8523 $DBversion = "3.16.00.000";
8524 if ( CheckVersion($DBversion) ) {
8525     print "Upgrade to $DBversion done (3.16.0 release)\n";
8526     SetVersion ($DBversion);
8527 }
8528
8529 $DBversion = '3.17.00.000';
8530 if ( CheckVersion($DBversion) ) {
8531     print "Upgrade to $DBversion done (there is no time to rest on our laurels)\n";
8532     SetVersion ($DBversion);
8533 }
8534
8535 $DBversion = '3.17.00.001';
8536 if ( CheckVersion($DBversion) ) {
8537    $dbh->do("UPDATE systempreferences SET variable = 'AuthoritySeparator' WHERE variable = 'authoritysep'");
8538    print "Upgrade to $DBversion done (Bug 10330 - Rename system preference authoritysep to AuthoritySeparator)\n";
8539    SetVersion ($DBversion);
8540 }
8541
8542 $DBversion = "3.17.00.002";
8543 if (CheckVersion($DBversion)) {
8544     $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')");
8545     $dbh->do("
8546 CREATE TABLE IF NOT EXISTS `misc_files` (
8547   `file_id` int(11) NOT NULL AUTO_INCREMENT,
8548   `table_tag` varchar(255) NOT NULL,
8549   `record_id` int(11) NOT NULL,
8550   `file_name` varchar(255) NOT NULL,
8551   `file_type` varchar(255) NOT NULL,
8552   `file_description` varchar(255) DEFAULT NULL,
8553   `file_content` longblob NOT NULL, -- file content
8554   `date_uploaded` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
8555   PRIMARY KEY (`file_id`),
8556   KEY `table_tag` (`table_tag`),
8557   KEY `record_id` (`record_id`)
8558 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
8559     ");
8560     print "Upgrade to $DBversion done (Bug 3050 - Add an option to upload scanned invoices)\n";
8561     SetVersion($DBversion);
8562 }
8563
8564 $DBversion = "3.17.00.003";
8565 if (CheckVersion($DBversion)) {
8566     $dbh->do("UPDATE systempreferences SET type = 'Choice', options = '0|1|force' WHERE variable = 'OPACItemHolds'");
8567     print "Upgrade to $DBversion done (Bug 7825 - Changed OPACItemHolds syspref to Choice)\n";
8568     SetVersion($DBversion);
8569 }
8570
8571 $DBversion = "3.17.00.004";
8572 if (CheckVersion($DBversion)) {
8573     $dbh->do("ALTER TABLE categories ADD default_privacy ENUM( 'default', 'never', 'forever' ) NOT NULL DEFAULT 'default' AFTER category_type");
8574     print "Upgrade to $DBversion done (Bug 6254 - can't set patron privacy by default)\n";
8575     SetVersion($DBversion);
8576 }
8577
8578 $DBversion = "3.17.00.005";
8579 if (CheckVersion($DBversion)) {
8580     $dbh->do(q|
8581         ALTER TABLE issuingrules
8582         ADD maxsuspensiondays INT(11) DEFAULT NULL AFTER finedays;
8583     |);
8584     print "Upgrade to $DBversion done (Bug 12230: Add new issuing rule maxsuspensiondays)\n";
8585     SetVersion($DBversion);
8586 }
8587
8588 $DBversion = "3.17.00.006";
8589 if ( CheckVersion($DBversion) ) {
8590     $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')");
8591     $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')");
8592     print "Upgrade to $DBversion done (Bug 7720 - Ambiguity in OPAC Details location.)\n";
8593     SetVersion($DBversion);
8594 }
8595
8596 $DBversion = "3.17.00.007";
8597 if (CheckVersion($DBversion)) {
8598     $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');");
8599     print "Upgrade to $DBversion done (Bug 11629 - Add ability to update not for loan status on checkin)\n";
8600     SetVersion($DBversion);
8601 }
8602
8603 $DBversion = "3.17.00.008";
8604 if ( CheckVersion($DBversion) ) {
8605     $dbh->do(q|
8606         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('OPACAcquisitionDetails','0', '','Show the acquisition details at the OPAC','YesNo')
8607     |);
8608     print "Upgrade to $DBversion done (Bug 11169 - Add OPACAcquisitionDetails syspref)\n";
8609     SetVersion($DBversion);
8610 }
8611
8612 $DBversion = "3.17.00.009";
8613 if ( CheckVersion($DBversion) ) {
8614     $dbh->do(q{
8615         DELETE FROM systempreferences WHERE variable = 'UseTablesortForCirc'
8616     });
8617
8618     print "Upgrade to $DBversion done (Bug 11703 - Remove UseTablesortForCirc syspref)\n";
8619     SetVersion($DBversion);
8620 }
8621
8622 $DBversion = "3.17.00.010";
8623 if ( CheckVersion($DBversion) ) {
8624     $dbh->do("DELETE FROM systempreferences WHERE variable='opacsmallimage'");
8625     print "Upgrade to $DBversion done (Bug 11347 - PROG/CCSR deprecation: Remove opacsmallimage system preference)\n";
8626     SetVersion($DBversion);
8627 }
8628
8629 $DBversion = "3.17.00.011";
8630 if ( CheckVersion($DBversion) ) {
8631     $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'hr', 'language', 'Croatian','2014-07-24' )");
8632     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'hr','hrv')");
8633     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'hr', 'Hrvatski')");
8634     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'en', 'Croatian')");
8635     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'fr', 'Croate')");
8636     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'de', 'Kroatisch')");
8637     print "Upgrade to $DBversion done (Bug 12649: Add Croatian language)\n";
8638     SetVersion ($DBversion);
8639 }
8640
8641 $DBversion = "3.17.00.012";
8642 if ( CheckVersion($DBversion) ) {
8643     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacShowFiltersPulldownMobile'");
8644     print "Upgrade to $DBversion done ( Bug 12512 - PROG/CCSR deprecation: Remove OpacShowFiltersPulldownMobile system preference )\n";
8645     SetVersion ($DBversion);
8646 }
8647
8648 $DBversion = "3.17.00.013";
8649 if ( CheckVersion($DBversion) ) {
8650     $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')");
8651     print "Upgrade to $DBversion done (Re-add system preference maxreserves)\n";
8652     SetVersion ($DBversion);
8653 }
8654
8655 $DBversion = '3.17.00.014';
8656 if ( CheckVersion($DBversion) ) {
8657     $dbh->do("
8658         INSERT INTO systempreferences (variable,value,explanation,type) VALUES
8659         ('OverdueNoticeCalendar',0,'Take calendar into consideration when working out sending overdue notices','YesNo')
8660     ");
8661     print "Upgrade to $DBversion done (Bug 12529 - Adding a syspref to allow the overdue notices to consider the calendar when generating notices)\n";
8662     SetVersion($DBversion);
8663 }
8664
8665 $DBversion = "3.17.00.015";
8666 if ( CheckVersion($DBversion) ) {
8667     $dbh->do(q{
8668         CREATE TABLE IF NOT EXISTS columns_settings (
8669             module varchar(255) NOT NULL,
8670             page varchar(255) NOT NULL,
8671             tablename varchar(255) NOT NULL,
8672             columnname varchar(255) NOT NULL,
8673             cannot_be_toggled int(1) NOT NULL DEFAULT 0,
8674             is_hidden int(1) NOT NULL DEFAULT 0,
8675             PRIMARY KEY(module, page, tablename, columnname)
8676         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
8677     });
8678     print "Upgrade to $DBversion done (Bug 10212 - Create new table columns_settings)\n";
8679     SetVersion ($DBversion);
8680 }
8681
8682 $DBversion = "3.17.00.016";
8683 if ( CheckVersion($DBversion) ) {
8684     $dbh->do("CREATE TABLE aqcontacts (
8685         id int(11) NOT NULL auto_increment,
8686         name varchar(100) default NULL,
8687         position varchar(100) default NULL,
8688         phone varchar(100) default NULL,
8689         altphone varchar(100) default NULL,
8690         fax varchar(100) default NULL,
8691         email varchar(100) default NULL,
8692         notes mediumtext,
8693         claimacquisition BOOLEAN NOT NULL DEFAULT 0,
8694         claimissues BOOLEAN NOT NULL DEFAULT 0,
8695         acqprimary BOOLEAN NOT NULL DEFAULT 0,
8696         serialsprimary BOOLEAN NOT NULL DEFAULT 0,
8697         booksellerid int(11) not NULL,
8698         PRIMARY KEY  (id),
8699         CONSTRAINT booksellerid_aqcontacts_fk FOREIGN KEY (booksellerid)
8700             REFERENCES aqbooksellers (id) ON DELETE CASCADE ON UPDATE CASCADE
8701         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;");
8702     $dbh->do("INSERT INTO aqcontacts (name, position, phone, altphone, fax,
8703             email, notes, booksellerid, claimacquisition, claimissues, acqprimary, serialsprimary)
8704         SELECT contact, contpos, contphone, contaltphone, contfax, contemail,
8705             contnotes, id, 1, 1, 1, 1 FROM aqbooksellers;");
8706     $dbh->do("ALTER TABLE aqbooksellers DROP COLUMN contact,
8707         DROP COLUMN contpos, DROP COLUMN contphone,
8708         DROP COLUMN contaltphone, DROP COLUMN contfax,
8709         DROP COLUMN contemail, DROP COLUMN contnotes;");
8710     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contact>>', '<<aqcontacts.name>>')");
8711     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contpos>>', '<<aqcontacts.position>>')");
8712     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contphone>>', '<<aqcontacts.phone>>')");
8713     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contaltphone>>', '<<aqcontacts.altphone>>')");
8714     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contfax>>', '<<aqcontacts.contfax>>')");
8715     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contemail>>', '<<aqcontacts.contemail>>')");
8716     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contnotes>>', '<<aqcontacts.contnotes>>')");
8717     print "Upgrade to $DBversion done (Bug 10402: Move bookseller contacts to separate table)\n";
8718     SetVersion($DBversion);
8719 }
8720
8721 $DBversion = "3.17.00.017";
8722 if ( CheckVersion($DBversion) ) {
8723     # Correct invalid recordtypes (should be very exceptional)
8724     $dbh->do(q{
8725         UPDATE z3950servers set recordtype='biblio' WHERE recordtype NOT IN ('authority','biblio')
8726     });
8727     # Correct invalid server types (should also be very exceptional)
8728     $dbh->do(q{
8729         UPDATE z3950servers set type='zed' WHERE type <> 'zed'
8730     });
8731     # Adjust table
8732     $dbh->do(q{
8733         ALTER TABLE z3950servers
8734         DROP COLUMN icon,
8735         DROP COLUMN description,
8736         DROP COLUMN position,
8737         MODIFY COLUMN id int NOT NULL AUTO_INCREMENT FIRST,
8738         MODIFY COLUMN recordtype enum('authority','biblio') NOT NULL DEFAULT 'biblio',
8739         CHANGE COLUMN name servername mediumtext NOT NULL,
8740         CHANGE COLUMN type servertype enum('zed','sru') NOT NULL DEFAULT 'zed',
8741         ADD COLUMN sru_options varchar(255) default NULL,
8742         ADD COLUMN sru_fields mediumtext default NULL,
8743         ADD COLUMN add_xslt mediumtext default NULL
8744     });
8745     print "Upgrade to $DBversion done (Bug 6536: Z3950 improvements)\n";
8746     SetVersion ($DBversion);
8747 }
8748
8749 $DBversion = "3.17.00.018";
8750 if ( CheckVersion($DBversion) ) {
8751     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('HoldsInNoissuesCharge', '0', 'Hold charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
8752     print "Upgrade to $DBversion done (Bug 12205: Add HoldsInNoissuesCharge systempreference)\n";
8753     SetVersion($DBversion);
8754 }
8755
8756 $DBversion = "3.17.00.019";
8757 if ( CheckVersion($DBversion) ) {
8758     $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')"
8759     );
8760     print "Upgrade to $DBversion done (Bug 6149: Operator highlighted in search results)\n";
8761     SetVersion($DBversion);
8762 }
8763
8764 $DBversion = "3.17.00.020";
8765 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
8766     $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')");
8767     print "Upgrade to $DBversion done (Bug 8735 - Expire holds waiting only on days the library is open)\n";
8768     SetVersion ($DBversion);
8769 }
8770
8771 $DBversion = "3.17.00.021";
8772 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
8773     my $pref = C4::Context->preference('HomeOrHoldingBranch');
8774     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
8775        VALUES ('StaffSearchResultsDisplayBranch', ?,'homebranch|holdingbranch','Controls the display of the home or holding branch for staff search results','choice')", undef, $pref);
8776     print "Upgrade to $DBversion done (Bug 12582 - Control of branch displayed in search results linked to HomeOrHoldingBranch)\n";
8777     SetVersion ($DBversion);
8778 }
8779
8780 $DBversion = '3.17.00.022';
8781 if ( CheckVersion($DBversion) ) {
8782     my @temp= $dbh->selectrow_array(qq|
8783         SELECT count(*)
8784         FROM marc_subfield_structure
8785         WHERE kohafield='permanent_location' OR kohafield='items.permanent_location'
8786     |);
8787     print "Upgrade to $DBversion done (Bug 7817: Check for permanent_location)\n";
8788     if( $temp[0] ) {
8789         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";
8790     }
8791     SetVersion($DBversion);
8792 }
8793
8794 $DBversion = "3.17.00.023";
8795 if ( CheckVersion($DBversion) ) {
8796     $dbh->do(q{
8797         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')
8798     });
8799     print "Upgrade to $DBversion done (Bug 11169 - Add AcqItemSetSubfieldsWhenReceiptIsCancelled syspref)\n";
8800     SetVersion($DBversion);
8801 }
8802
8803 $DBversion = "3.17.00.024";
8804 if(CheckVersion($DBversion)) {
8805     $dbh->do(q{
8806         ALTER TABLE issues ADD auto_renew BOOLEAN default FALSE AFTER renewals
8807     });
8808     $dbh->do(q{
8809         ALTER TABLE old_issues ADD auto_renew BOOLEAN default FALSE AFTER renewals
8810     });
8811     $dbh->do(q{
8812         ALTER TABLE issuingrules ADD auto_renew BOOLEAN default FALSE AFTER norenewalbefore
8813     });
8814     print "Upgrade to $DBversion done (Bug 11577: [ENH] Automatic renewal feature)\n";
8815     SetVersion($DBversion);
8816 }
8817
8818 $DBversion = '3.17.00.025';
8819 if ( CheckVersion($DBversion) ) {
8820     $dbh->do(qq{
8821         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')
8822     });
8823     print "Upgrade to $DBversion done (Bug 12728: Checked syspref StatisticsFields)\n";
8824 }
8825
8826 $DBversion = "3.17.00.026";
8827 if ( CheckVersion($DBversion) ) {
8828     if ( C4::Context->preference('marcflavour') eq 'MARC21' ) {
8829         $dbh->do("UPDATE marc_subfield_structure SET liblibrarian = 'Encoded bitrate', libopac = 'Encoded bitrate' WHERE tagfield = '347' AND tagsubfield = 'f'");
8830         $dbh->do("UPDATE marc_subfield_structure SET repeatable = 1 WHERE tagfield IN ('110','111','610','611','710','711','810','811') AND tagsubfield = 'c'");
8831         $dbh->do("UPDATE auth_subfield_structure SET repeatable = 1 WHERE tagfield IN ('110','111','410','411','510','511','710','711') AND tagsubfield = 'c'");
8832         print "Upgrade to $DBversion done (Bug 12435 - Update MARC21 frameworks to Update No. 18 (April 2014))\n";
8833     }
8834     SetVersion($DBversion);
8835 }
8836
8837 $DBversion = "3.17.00.027";
8838 if ( CheckVersion($DBversion) ) {
8839     $dbh->do(q{
8840         DELETE FROM systempreferences WHERE variable = 'SearchEngine'
8841     });
8842     print "Upgrade to $DBversion done (Bug 12538 - Remove SearchEngine syspref)\n";
8843     SetVersion($DBversion);
8844 }
8845
8846 $DBversion = "3.17.00.028";
8847 if ( CheckVersion($DBversion) ) {
8848     $dbh->do(q{
8849         INSERT INTO systempreferences (variable,value) VALUES('OpacCustomSearch','');
8850     });
8851     print "Upgrade to $DBversion done (Bug 12296 - search box replaceable with a system preference)\n";
8852     SetVersion($DBversion);
8853 }
8854
8855 $DBversion = "3.17.00.029";
8856 if ( CheckVersion($DBversion) ) {
8857     $dbh->do("ALTER TABLE  `items` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8858     $dbh->do("ALTER TABLE  `deleteditems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8859     $dbh->do("ALTER TABLE  `biblioitems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8860     $dbh->do("ALTER TABLE  `deletedbiblioitems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8861     print "Upgrade to $DBversion done (Bug 12424 - ddc sorting of call numbers truncates long Cutter parts)\n";
8862     SetVersion ($DBversion);
8863 }
8864
8865 $DBversion = "3.17.00.030";
8866 if ( CheckVersion($DBversion) ) {
8867     $dbh->do(
8868         q{
8869        INSERT INTO systempreferences (variable, value, options, explanation, type )
8870        VALUES
8871         ('UsageStatsCountry', '', NULL, 'The country where your library is located, to be shown on the Hea Koha community website', 'YesNo'),
8872         ('UsageStatsID', '', NULL, 'This preference is part of Koha but it should not be deleted or updated manually.',  'Free'),
8873         ('UsageStatsLastUpdateTime', '', NULL, 'This preference is part of Koha but it should not be deleted or updated manually.', 'Free'),
8874         ('UsageStatsLibraryName', '', NULL, 'The library name to be shown on Hea Koha community website', 'Free'),
8875         ('UsageStatsLibraryType', 'public', 'public|university', 'The library type to be shown on the Hea Koha community website', 'Choice'),
8876         ('UsageStatsLibraryUrl', '', NULL, 'The library URL to be shown on Hea Koha community website', 'Free'),
8877         ('UsageStats', 0, NULL, 'Share anonymous usage data on the Hea Koha community website.', 'YesNo')
8878     });
8879     print "Upgrade to $DBversion done (Bug 11926: Add UsageStats systempreferences (HEA))\n";
8880     SetVersion ($DBversion);
8881 }
8882
8883 $DBversion = "3.17.00.031";
8884 if ( CheckVersion($DBversion) ) {
8885    $dbh->do("ALTER TABLE saved_sql CHANGE report_name report_name VARCHAR( 255 ) NOT NULL DEFAULT '' ");
8886    print "Upgrade to $DBversion done (Bug 2969: Report Name should be mandatory for saved reports)\n";
8887    SetVersion ($DBversion);
8888 }
8889
8890 $DBversion = "3.17.00.032";
8891 if ( CheckVersion($DBversion) ) {
8892     $dbh->do(
8893 "INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('ReplytoDefault',  '',  NULL,  'The default email address to be set as replyto.',  'Free')"
8894     );
8895     $dbh->do(
8896 "INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('ReturnpathDefault',  '',  NULL,  'The default email address to be set as return-path',  'Free')"
8897     );
8898     $dbh->do("ALTER TABLE branches ADD branchreplyto mediumtext AFTER branchemail");
8899     $dbh->do("ALTER TABLE branches ADD branchreturnpath mediumtext AFTER branchreplyto");
8900     print "Upgrade to $DBversion done (Bug 9530: Adding replyto and returnpath addresses.)\n";
8901     SetVersion($DBversion);
8902 }
8903
8904 $DBversion = "3.17.00.033";
8905 if ( CheckVersion($DBversion) ) {
8906     $dbh->do(q{
8907         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
8908         VALUES('FacetMaxCount', '20','Specify the max facet count for each category',NULL,'Integer')
8909     });
8910     print "Upgrade to $DBversion done (Bug 13088 - Allow the user to specify a max amount of facets to show)\n";
8911     SetVersion($DBversion);
8912 }
8913
8914 $DBversion = "3.17.00.034";
8915 if ( CheckVersion($DBversion) ) {
8916     $dbh->do(q|
8917         ALTER TABLE aqorders DROP COLUMN cancelledby;
8918     |);
8919
8920     print "Upgrade to $DBversion done (Bug 11007 - DROP column aqorders.cancelledby)\n";
8921     SetVersion($DBversion);
8922 }
8923
8924 $DBversion = "3.17.00.035";
8925 if ( CheckVersion($DBversion) ) {
8926     $dbh->do(q|
8927         ALTER TABLE serial ADD COLUMN claims_count INT(11) DEFAULT 0 after claimdate
8928     |);
8929     $dbh->do(q|
8930         UPDATE serial
8931         SET claims_count = 1
8932         WHERE claimdate IS NOT NULL
8933     |);
8934     print "Upgrade to $DBversion done (Bug 5342: Add claims_count field in serial table)\n";
8935     SetVersion($DBversion);
8936 }
8937
8938 $DBversion = "3.17.00.036";
8939 if ( CheckVersion($DBversion) ) {
8940     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacShowLibrariesPulldownMobile'");
8941     print "Upgrade to $DBversion done ( Bug 12513 - PROG/CCSR deprecation: Remove OpacShowLibrariesPulldownMobile system preference )\n";
8942     SetVersion ($DBversion);
8943 }
8944
8945 $DBversion = "3.17.00.037";
8946 if ( CheckVersion($DBversion) ) {
8947     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacMainUserBlockMobile'");
8948     print "Upgrade to $DBversion done ( Bug 12246 - PROG/CCSR deprecation: Remove OpacMainUserBlockMobile system preference )\n";
8949     SetVersion ($DBversion);
8950 }
8951
8952 $DBversion = "3.17.00.038";
8953 if ( CheckVersion($DBversion) ) {
8954     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACMobileUserCSS'");
8955     print "Upgrade to $DBversion done ( Bug 12245 - PROG/CCSR deprecation: Remove OPACMobileUserCSS system preference )\n";
8956     SetVersion ($DBversion);
8957 }
8958
8959 $DBversion = "3.17.00.039";
8960 if ( CheckVersion($DBversion) ) {
8961     $dbh->do("INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES
8962     ('OPACFallback', 'prog', 'bootstrap|prog', 'Define the fallback theme for the OPAC interface.', 'Themes')");
8963     print "Upgrade to $DBversion done (Bug 12539 - PROG/CCSR deprecation: Remove hardcoded theme from C4/Templates.pm)\n";
8964     SetVersion ($DBversion);
8965 }
8966
8967 $DBversion = "3.17.00.040";
8968 if ( CheckVersion($DBversion) ) {
8969     my $opac_theme = C4::Context->preference( 'opacthemes' );
8970     if ( !defined $opac_theme || $opac_theme eq 'prog' || $opac_theme eq 'ccsr' ) {
8971         $dbh->do("UPDATE systempreferences SET value='bootstrap' WHERE variable='opacthemes'");
8972     }
8973     print "Upgrade to $DBversion done (Bug 12223: 'prog' and 'ccsr' themes removed)\n";
8974     SetVersion($DBversion);
8975 }
8976
8977 $DBversion = "3.17.00.041";
8978 if ( CheckVersion($DBversion) ) {
8979     print "Upgrade to $DBversion done (Bug 11346: Deprecate the 'prog' and 'CCSR' themes)\n";
8980     SetVersion($DBversion);
8981 }
8982
8983 $DBversion = "3.17.00.042";
8984 if ( CheckVersion($DBversion) ) {
8985     $dbh->do("DELETE FROM systempreferences WHERE variable='yuipath'");
8986     print "Upgrade to $DBversion done (Bug 12494: Remove yuipath system preference)\n";
8987     SetVersion ($DBversion);
8988 }
8989
8990 $DBversion = "3.17.00.043";
8991 if ( CheckVersion($DBversion) ) {
8992     $dbh->do("
8993         ALTER TABLE aqorders
8994         ADD COLUMN cancellationreason TEXT DEFAULT NULL AFTER datecancellationprinted
8995     ");
8996     print "Upgrade to $DBversion done (Bug 7162: Add aqorders.cancellationreason)\n";
8997     SetVersion ($DBversion);
8998 }
8999
9000 $DBversion = "3.17.00.044";
9001 if ( CheckVersion($DBversion) ) {
9002     $dbh->do(q{
9003         INSERT IGNORE INTO systempreferences
9004             (variable,value,explanation,options,type)
9005             VALUES('OnSiteCheckouts','0','Enable/Disable the on-site checkouts feature','','YesNo');
9006     });
9007     $dbh->do(q{
9008         INSERT IGNORE INTO systempreferences
9009             (variable,value,explanation,options,type)
9010             VALUES('OnSiteCheckoutsForce','0','Enable/Disable the on-site for all cases (Even if a user is debarred, etc.)','','YesNo');
9011     });
9012     $dbh->do(q{
9013         ALTER TABLE issues ADD COLUMN onsite_checkout INT(1) NOT NULL DEFAULT 0 AFTER issuedate;
9014     });
9015     $dbh->do(q{
9016         ALTER TABLE old_issues ADD COLUMN onsite_checkout INT(1) NOT NULL DEFAULT 0 AFTER issuedate;
9017     });
9018     print "Upgrade to $DBversion done (Bug 10860: Add new system preference OnSiteCheckouts + fields [old_]issues.onsite_checkout)\n";
9019     SetVersion($DBversion);
9020 }
9021
9022 $DBversion = "3.17.00.045";
9023 if ( CheckVersion($DBversion) ) {
9024     $dbh->do(q{
9025         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
9026         ('LocalHoldsPriority',  '0', NULL,  'Enables the LocalHoldsPriority feature',  'YesNo'),
9027         ('LocalHoldsPriorityItemControl',  'holdingbranch',  'holdingbranch|homebranch',  'decides if the feature operates using the item''s home or holding library.',  'Choice'),
9028         ('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')
9029     });
9030     print "Upgrade to $DBversion done (Bug 11126 - Make the holds system optionally give precedence to local holds)\n";
9031     SetVersion($DBversion);
9032 }
9033
9034 $DBversion = "3.17.00.046";
9035 if ( CheckVersion($DBversion) ) {
9036     $dbh->do(q{
9037         CREATE TABLE IF NOT EXISTS items_search_fields (
9038           name VARCHAR(255) NOT NULL,
9039           label VARCHAR(255) NOT NULL,
9040           tagfield CHAR(3) NOT NULL,
9041           tagsubfield CHAR(1) NULL DEFAULT NULL,
9042           authorised_values_category VARCHAR(16) NULL DEFAULT NULL,
9043           PRIMARY KEY(name),
9044           CONSTRAINT items_search_fields_authorised_values_category
9045             FOREIGN KEY (authorised_values_category) REFERENCES authorised_values (category)
9046             ON DELETE SET NULL ON UPDATE CASCADE
9047         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
9048     });
9049     print "Upgrade to $DBversion done (Bug 11425: Add items_search_fields table)\n";
9050     SetVersion($DBversion);
9051 }
9052
9053 $DBversion = "3.17.00.047";
9054 if ( CheckVersion($DBversion) ) {
9055     $dbh->do(q{
9056         ALTER TABLE collections
9057             CHANGE colBranchcode colBranchcode VARCHAR( 10 ) NULL DEFAULT NULL,
9058             ADD INDEX ( colBranchcode ),
9059             ADD CONSTRAINT collections_ibfk_1 FOREIGN KEY (colBranchcode) REFERENCES branches (branchcode) ON DELETE CASCADE ON UPDATE CASCADE
9060     });
9061     print "Upgrade to $DBversion done (Bug 8836 - Resurrect Rotating Collections)\n";
9062     SetVersion($DBversion);
9063 }
9064
9065 $DBversion = "3.17.00.048";
9066 if ( CheckVersion($DBversion) ) {
9067     $dbh->do(q|
9068         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')
9069     |);
9070     print "Upgrade to $DBversion done (Bug 12448 - Add RentalFeesCheckoutConfirmation syspref)\n";
9071     SetVersion($DBversion);
9072 }
9073
9074 $DBversion = "3.17.00.049";
9075 if ( CheckVersion($DBversion) ) {
9076     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'am', 'language', 'Amharic','2014-10-29')");
9077     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'am','amh')");
9078     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'am', 'language', 'am', 'አማርኛ')");
9079     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'am', 'language', 'en', 'Amharic')");
9080
9081     $dbh->do("UPDATE language_descriptions SET description = 'لعربية' WHERE subtag = 'ar' AND type = 'language' AND lang = 'ar'");
9082
9083     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'az', 'language', 'Azerbaijani','2014-10-30')");
9084     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'az','aze')");
9085     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'az', 'language', 'az', 'Azərbaycan dili')");
9086     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'az', 'language', 'en', 'Azerbaijani')");
9087
9088     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'be', 'language', 'Byelorussian','2014-10-30')");
9089     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'be','bel')");
9090     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'be', 'language', 'be', 'Беларуская мова')");
9091     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'be', 'language', 'en', 'Byelorussian')");
9092
9093     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'bn', 'language', 'Bengali','2014-10-30')");
9094     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'bn','ben')");
9095     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'bn', 'language', 'bn', 'বাংলা')");
9096     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'bn', 'language', 'en', 'Bengali')");
9097
9098     $dbh->do("UPDATE language_descriptions SET description = 'Български' WHERE subtag = 'bg' AND type = 'language' AND lang = 'bg'");
9099     $dbh->do("UPDATE language_descriptions SET description = 'Ceština' WHERE subtag = 'cs' AND type = 'language' AND lang = 'cs'");
9100     $dbh->do("UPDATE language_descriptions SET description = 'Ελληνικά' WHERE subtag = 'el' AND type = 'language' AND lang = 'el'");
9101     $dbh->do("UPDATE language_descriptions SET description = 'Español' WHERE subtag = 'es' AND type = 'language' AND lang = 'es'");
9102
9103     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'eu', 'language', 'Basque','2014-10-30')");
9104     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'eu','eus')");
9105     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'eu', 'language', 'eu', 'Euskera')");
9106     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'eu', 'language', 'en', 'Basque')");
9107
9108     $dbh->do("UPDATE language_descriptions SET description = 'فارسى' WHERE subtag = 'fa' AND type = 'language' AND lang = 'fa'");
9109     $dbh->do("UPDATE language_descriptions SET description = 'Suomi' WHERE subtag = 'fi' AND type = 'language' AND lang = 'fi'");
9110
9111     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'fo', 'language', 'Faroese','2014-10-30')");
9112     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'fo','fao')");
9113     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'fo', 'language', 'fo', 'Føroyskt')");
9114     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'fo', 'language', 'en', 'Faroese')");
9115
9116     $dbh->do("UPDATE language_descriptions SET description = 'Français' WHERE subtag = 'fr' AND type = 'language' AND lang = 'fr'");
9117     $dbh->do("UPDATE language_descriptions SET description = 'עִבְרִית' WHERE subtag = 'he' AND type = 'language' AND lang = 'he'");
9118     $dbh->do("UPDATE language_descriptions SET description = 'हिन्दी' WHERE subtag = 'hi' AND type = 'language' AND lang = 'hi'");
9119
9120     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'is', 'language', 'Icelandic','2014-10-30')");
9121     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'is','ice')");
9122     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'is', 'language', 'is', 'Íslenska')");
9123     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'is', 'language', 'en', 'Icelandic')");
9124
9125     $dbh->do("UPDATE language_descriptions SET description = '日本語' WHERE subtag = 'ja' AND type = 'language' AND lang = 'ja'");
9126
9127     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ka', 'language', 'Kannada','2014-10-30')");
9128     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ka','kan')");
9129     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'ka', 'ಕನ್ನಡ')");
9130     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'en', 'Kannada')");
9131
9132     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'km', 'language', 'Khmer','2014-10-30')");
9133     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'km','khm')");
9134     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'km', 'language', 'km', 'ភាសាខ្មែរ')");
9135     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'km', 'language', 'en', 'Khmer')");
9136
9137     $dbh->do("UPDATE language_descriptions SET description = '한국어' WHERE subtag = 'ko' AND type = 'language' AND lang = 'ko'");
9138
9139     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ku', 'language', 'Kurdish','2014-05-13')");
9140     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ku','kur')");
9141     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'ku', 'کوردی')");
9142     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'en', 'Kurdish')");
9143     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'fr', 'Kurde')");
9144     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'de', 'Kurdisch')");
9145     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'es', 'Kurdo')");
9146
9147     $dbh->do("UPDATE language_descriptions SET description = 'ພາສາລາວ' WHERE subtag = 'lo' AND type = 'language' AND lang = 'lo'");
9148
9149     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mi', 'language', 'Maori','2014-10-30')");
9150     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mi','mri')");
9151     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mi', 'language', 'mi', 'Te Reo Māori')");
9152     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mi', 'language', 'en', 'Maori')");
9153
9154     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mn', 'language', 'Mongolian','2014-10-30')");
9155     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mn','mon')");
9156     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mn', 'language', 'mn', 'Mонгол')");
9157     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mn', 'language', 'en', 'Mongolian')");
9158
9159     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mr', 'language', 'Marathi','2014-10-30')");
9160     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mr','mar')");
9161     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mr', 'language', 'mr', 'मराठी')");
9162     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mr', 'language', 'en', 'Marathi')");
9163
9164     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ms', 'language', 'Malay','2014-10-30')");
9165     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ms','may')");
9166     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ms', 'language', 'ms', 'Bahasa melayu')");
9167     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ms', 'language', 'en', 'Malay')");
9168
9169     $dbh->do("UPDATE language_descriptions SET description = 'Norsk bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'nb'");
9170     $dbh->do("UPDATE language_descriptions SET description = 'Norwegian bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'en'");
9171     $dbh->do("UPDATE language_descriptions SET description = 'Norvégien bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'fr'");
9172     $dbh->do("UPDATE language_descriptions SET description = 'Norwegisch bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'de'");
9173
9174     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ne', 'language', 'Nepali','2014-10-30')");
9175     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ne','nep')");
9176     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)VALUES ( 'ne', 'language', 'ne', 'नेपाली')");
9177     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ne', 'language', 'en', 'Nepali')");
9178
9179     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'pbr', 'language', 'Pangwa','2014-10-30')");
9180     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'pbr','pbr')");
9181     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'pbr', 'language', 'pbr', 'Ekipangwa')");
9182     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'pbr', 'language', 'en', 'Pangwa')");
9183
9184     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'prs', 'language', 'Dari','2014-10-30')");
9185     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'prs','prs')");
9186     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'prs', 'language', 'prs', 'درى')");
9187     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'prs', 'language', 'en', 'Dari')");
9188
9189     $dbh->do("UPDATE language_descriptions SET description = 'Português' WHERE subtag = 'pt' AND type = 'language' AND lang = 'pt'");
9190     $dbh->do("UPDATE language_descriptions SET description = 'Român' WHERE subtag = 'ro' AND type = 'language' AND lang = 'ro'");
9191     $dbh->do("UPDATE language_descriptions SET description = 'Русский' WHERE subtag = 'ru' AND type = 'language' AND lang = 'ru'");
9192
9193     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'rw', 'language', 'Kinyarwanda','2014-10-30')");
9194     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'rw','kin')");
9195     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'rw', 'language', 'rw', 'Ikinyarwanda')");
9196     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'rw', 'language', 'en', 'Kinyarwanda')");
9197
9198     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sd', 'language', 'Sindhi','2014-10-30')");
9199     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sd','snd')");
9200     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sd', 'language', 'sd', 'سنڌي')");
9201     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sd', 'language', 'en', 'Sindhi')");
9202
9203     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sk', 'language', 'Slovak','2014-10-30')");
9204     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sk','slk')");
9205     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sk', 'language', 'sk', 'Slovenčina')");
9206     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sk', 'language', 'en', 'Slovak')");
9207
9208     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sl', 'language', 'Slovene','2014-10-30')");
9209     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sl','slv')");
9210     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sl', 'language', 'sl', 'Slovenščina')");
9211     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sl', 'language', 'en', 'Slovene')");
9212
9213     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sq', 'language', 'Albanian','2014-10-30')");
9214     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sq','sqi')");
9215     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sq', 'language', 'sq', 'Shqip')");
9216     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sq', 'language', 'en', 'Albanian')");
9217
9218     $dbh->do("UPDATE language_descriptions SET description = 'Cрпски' WHERE subtag = 'sr' AND type = 'language' AND lang = 'sr'");
9219
9220     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sw', 'language', 'Swahili','2014-10-30')");
9221     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sw','swa')");
9222     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sw', 'language', 'sw', 'Kiswahili')");
9223     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sw', 'language', 'en', 'Swahili')");
9224
9225     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ta', 'language', 'Tamil','2014-10-30')");
9226     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ta','tam')");
9227     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ta', 'language', 'ta', 'தமிழ்')");
9228     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ta', 'language', 'en', 'Tamil')");
9229
9230     $dbh->do("UPDATE language_descriptions SET description = 'Tetun' WHERE subtag = 'tet' AND type = 'language' AND lang = 'tet'");
9231     $dbh->do("UPDATE language_descriptions SET description = 'ภาษาไทย' WHERE subtag = 'th' AND type = 'language' AND lang = 'th'");
9232
9233     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'tl', 'language', 'Tagalog','2014-10-30')");
9234     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'tl','tgl')");
9235     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'tl', 'language', 'tl', 'Tagalog')");
9236     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'tl', 'language', 'en', 'Tagalog')");
9237
9238     $dbh->do("UPDATE language_descriptions SET description = 'Türkçe' WHERE subtag = 'tr' AND type = 'language' AND lang = 'tr'");
9239     $dbh->do("UPDATE language_descriptions SET description = 'Українська' WHERE subtag = 'uk' AND type = 'language' AND lang = 'uk'");
9240     $dbh->do("UPDATE language_descriptions SET description = 'اردو' WHERE subtag = 'ur' AND type = 'language' AND lang = 'ur'");
9241
9242     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'vi', 'language', 'Vietnamese','2014-10-30')");
9243     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'vi','vie')");
9244     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'vi', 'language', 'vi', '㗂越')");
9245     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'vi', 'language', 'en', 'Vietnamese')");
9246
9247     $dbh->do("UPDATE language_descriptions SET description = '中文' WHERE subtag = 'zh' AND type = 'language' AND lang = 'zh'");
9248     $dbh->do("UPDATE language_descriptions SET description = '' WHERE subtag = 'Arab,script' AND type = 'Arab' AND lang = 'العربية'");
9249
9250     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Armn', 'script', 'Armenian','2014-10-30')");
9251     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Armn', 'script', 'Armn', 'Հայոց այբուբեն')");
9252     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Armn', 'script', 'en', 'Armenian')");
9253
9254     $dbh->do("UPDATE language_descriptions SET description = 'Кирилица' WHERE subtag = 'Cyrl' AND type = 'script' AND lang = 'Cyrl'");
9255
9256     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Ethi', 'script', 'Ethiopic','2014-10-30')");
9257     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Ethi', 'script', 'Ethi', 'ግዕዝ')");
9258     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Ethi', 'script', 'en', 'Ethiopic')");
9259
9260     $dbh->do("UPDATE language_descriptions SET description = 'Ελληνικό αλφάβητο' WHERE subtag = 'Grek' AND type = 'script' AND lang = 'Grek'");
9261     $dbh->do("UPDATE language_descriptions SET description = '简体字' WHERE subtag = 'Hans' AND type = 'script' AND lang = 'Hans'");
9262     $dbh->do("UPDATE language_descriptions SET description = '繁體字' WHERE subtag = 'Hant' AND type = 'script' AND lang = 'Hant'");
9263     $dbh->do("UPDATE language_descriptions SET description = 'אָלֶף־בֵּית עִבְרִי' WHERE subtag = 'Hebr' AND type = 'script' AND lang = 'Hebr'");
9264
9265     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Jpan', 'script', 'Japanese','2014-10-30')");
9266     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Jpan', 'script', 'Jpan', '漢字')");
9267     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Jpan', 'script', 'en', 'Japanese')");
9268
9269     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Knda', 'script', 'Kannada','2014-10-30')");
9270     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Knda', 'script', 'Knda', 'ಕನ್ನಡ ಲಿಪಿ')");
9271     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Knda', 'script', 'en', 'Kannada')");
9272
9273     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Kore', 'script', 'Korean','2014-10-30')");
9274     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Kore', 'script', 'Kore', '한글')");
9275     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Kore', 'script', 'en', 'Korean')");
9276
9277     $dbh->do("UPDATE language_descriptions SET description = 'ອັກສອນລາວ' WHERE subtag = 'Laoo' AND type = 'script' AND lang = 'Laoo'");
9278
9279     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'AL', 'region', 'Albania','2014-10-30')");
9280     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AL', 'region', 'en', 'Albania')");
9281     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AL', 'region', 'sq', 'Shqipërisë')");
9282
9283     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'AZ', 'region', 'Azerbaijan','2014-10-30')");
9284     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AZ', 'region', 'en', 'Azerbaijan')");
9285     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AZ', 'region', 'az', 'Azərbaycan')");
9286
9287     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BE', 'region', 'Belgium','2014-10-30')");
9288     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BE', 'region', 'en', 'Belgium')");
9289     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BE', 'region', 'nl', 'België')");
9290
9291     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BR', 'region', 'Brazil','2014-10-30')");
9292     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BR', 'region', 'en', 'Brazil')");
9293     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BR', 'region', 'pt', 'Brasil')");
9294
9295     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BY', 'region', 'Belarus','2014-10-30')");
9296     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BY', 'region', 'en', 'Belarus')");
9297     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BY', 'region', 'be', 'Беларусь')");
9298
9299     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CA', 'region', 'fr', 'Canada')");
9300
9301     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CH', 'region', 'Switzerland','2014-10-30')");
9302     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CH', 'region', 'en', 'Switzerland')");
9303     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CH', 'region', 'de', 'Schweiz')");
9304
9305     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CN', 'region', 'China','2014-10-30')");
9306     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CN', 'region', 'en', 'China')");
9307     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CN', 'region', 'zh', '中国')");
9308
9309     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CZ', 'region', 'Czech Republic','2014-10-30')");
9310     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CZ', 'region', 'en', 'Czech Republic')");
9311     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CZ', 'region', 'cs', 'Česká republika')");
9312
9313     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'DE', 'region', 'Germany','2014-10-30')");
9314     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DE', 'region', 'en', 'Germany')");
9315     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DE', 'region', 'de', 'Deutschland')");
9316
9317     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DK', 'region', 'en', 'Denmark')");
9318
9319     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ES', 'region', 'Spain','2014-10-30')");
9320     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ES', 'region', 'en', 'Spain')");
9321     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ES', 'region', 'es', 'España')");
9322
9323     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'FI', 'region', 'Finland','2014-10-30')");
9324     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FI', 'region', 'en', 'Finland')");
9325     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FI', 'region', 'fi', 'Suomi')");
9326
9327     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'FO', 'region', 'Faroe Islands','2014-10-30')");
9328     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FO', 'region', 'en', 'Faroe Islands')");
9329     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FO', 'region', 'fo', 'Føroyar')");
9330
9331     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'GR', 'region', 'Greece','2014-10-30')");
9332     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'GR', 'region', 'en', 'Greece')");
9333     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'GR', 'region', 'el', 'Ελλάδα')");
9334
9335     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'HR', 'region', 'Croatia','2014-10-30')");
9336     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HR', 'region', 'en', 'Croatia')");
9337     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HR', 'region', 'hr', 'Hrvatska')");
9338
9339     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'HU', 'region', 'Hungary','2014-10-30')");
9340     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HU', 'region', 'en', 'Hungary')");
9341     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HU', 'region', 'hu', 'Magyarország')");
9342
9343     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ID', 'region', 'Indonesia','2014-10-30')");
9344     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ID', 'region', 'en', 'Indonesia')");
9345     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ID', 'region', 'id', 'Indonesia')");
9346
9347     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'IS', 'region', 'Iceland','2014-10-30')");
9348     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IS', 'region', 'en', 'Iceland')");
9349     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IS', 'region', 'is', 'Ísland')");
9350
9351     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'IT', 'region', 'Italy','2014-10-30')");
9352     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IT', 'region', 'en', 'Italy')");
9353     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IT', 'region', 'it', 'Italia')");
9354
9355     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'JP', 'region', 'Japan','2014-10-30')");
9356     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'JP', 'region', 'en', 'Japan')");
9357     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'JP', 'region', 'ja', '日本')");
9358
9359     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KE', 'region', 'Kenya','2014-10-30')");
9360     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KE', 'region', 'en', 'Kenya')");
9361     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KE', 'region', 'rw', 'Kenya')");
9362
9363     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KH', 'region', 'Cambodia','2014-10-30')");
9364     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KH', 'region', 'en', 'Cambodia')");
9365     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KH', 'region', 'km', 'កម្ពុជា')");
9366
9367     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KP', 'region', 'North Korea','2014-10-30')");
9368     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KP', 'region', 'en', 'North Korea')");
9369     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KP', 'region', 'ko', '조선민주주의인민공화국')");
9370
9371     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'LK', 'region', 'Sri Lanka','2014-10-30')");
9372     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'LK', 'region', 'en', 'Sri Lanka')");
9373     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'LK', 'region', 'ta', 'இலங்கை')");
9374
9375     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'MY', 'region', 'Malaysia','2014-10-30')");
9376     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'MY', 'region', 'en', 'Malaysia')");
9377     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'MY', 'region', 'ms', 'Malaysia')");
9378
9379     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NE', 'region', 'Niger','2014-10-30')");
9380     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NE', 'region', 'en', 'Niger')");
9381     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NE', 'region', 'ne', 'Niger')");
9382
9383     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NL', 'region', 'Netherlands','2014-10-30')");
9384     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NL', 'region', 'en', 'Netherlands')");
9385     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NL', 'region', 'nl', 'Nederland')");
9386
9387     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NO', 'region', 'Norway','2014-10-30')");
9388     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'en', 'Norway')");
9389     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'ne', 'Noreg')");
9390     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'nn', 'Noreg')");
9391
9392     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PH', 'region', 'Philippines','2014-10-30')");
9393     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PH', 'region', 'en', 'Philippines')");
9394     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PH', 'region', 'tl', 'Pilipinas')");
9395
9396     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PK', 'region', 'Pakistan','2014-10-30')");
9397     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PK', 'region', 'en', 'Pakistan')");
9398     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PK', 'region', 'sd', 'پاكستان')");
9399
9400     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PL', 'region', 'Poland','2014-10-30')");
9401     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PL', 'region', 'en', 'Poland')");
9402     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PL', 'region', 'pl', 'Polska')");
9403
9404     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PT', 'region', 'Portugal','2014-10-30')");
9405     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PT', 'region', 'en', 'Portugal')");
9406     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PT', 'region', 'pt', 'Portugal')");
9407
9408     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RO', 'region', 'Romania','2014-10-30')");
9409     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RO', 'region', 'en', 'Romania')");
9410     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RO', 'region', 'ro', 'România')");
9411
9412     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RU', 'region', 'Russia','2014-10-30')");
9413     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RU', 'region', 'en', 'Russia')");
9414     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RU', 'region', 'ru', 'Россия')");
9415
9416     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RW', 'region', 'Rwanda','2014-10-30')");
9417     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RW', 'region', 'en', 'Rwanda')");
9418     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RW', 'region', 'rw', 'Rwanda')");
9419
9420     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SE', 'region', 'Sweden','2014-10-30')");
9421     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SE', 'region', 'en', 'Sweden')");
9422     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SE', 'region', 'sv', 'Sverige')");
9423
9424     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SI', 'region', 'Slovenia','2014-10-30')");
9425     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SI', 'region', 'en', 'Slovenia')");
9426     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SI', 'region', 'sl', 'Slovenija')");
9427
9428     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SK', 'region', 'Slovakia','2014-10-30')");
9429     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SK', 'region', 'en', 'Slovakia')");
9430     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SK', 'region', 'sk', 'Slovensko')");
9431
9432     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TH', 'region', 'Thailand','2014-10-30')");
9433     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TH', 'region', 'en', 'Thailand')");
9434     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TH', 'region', 'th', 'ประเทศไทย')");
9435
9436     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TR', 'region', 'Turkey','2014-10-30')");
9437     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TR', 'region', 'en', 'Turkey')");
9438     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TR', 'region', 'tr', 'Türkiye')");
9439
9440     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TW', 'region', 'Taiwan','2014-10-30')");
9441     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TW', 'region', 'en', 'Taiwan')");
9442     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TW', 'region', 'zh', '台灣')");
9443
9444     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'UA', 'region', 'Ukraine','2014-10-30')");
9445     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'UA', 'region', 'en', 'Ukraine')");
9446     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'UA', 'region', 'uk', 'Україна')");
9447
9448     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'VN', 'region', 'Vietnam','2014-10-30')");
9449     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'VN', 'region', 'en', 'Vietnam')");
9450     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'VN', 'region', 'vi', 'Việt Nam')");
9451
9452     print "Upgrade to $DBversion done (Bug 12250: Update descriptions for languages, scripts and regions)\n";
9453     SetVersion($DBversion);
9454 }
9455
9456 $DBversion = "3.17.00.050";
9457 if ( CheckVersion($DBversion) ) {
9458     $dbh->do(q|
9459         INSERT INTO permissions (module_bit, code, description) VALUES
9460           (13, 'records_batchdel', 'Perform batch deletion of records (bibliographic or authority)')
9461     |);
9462     print "Upgrade to $DBversion done (Bug 12403: Add permission tools_records_batchdelitem)\n";
9463     SetVersion($DBversion);
9464 }
9465
9466 $DBversion = "3.17.00.051";
9467 if ( CheckVersion($DBversion) ) {
9468     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('GoogleIndicTransliteration','0','','GoogleIndicTransliteration on the OPAC.','YesNo')");
9469     print "Upgrade to $DBversion done (Bug 13211: Added system preferences GoogleIndicTransliteration on the OPAC)\n";
9470     SetVersion($DBversion);
9471 }
9472
9473 $DBversion = "3.17.00.052";
9474 if ( CheckVersion($DBversion) ) {
9475     $dbh->do(q{
9476         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');
9477     });
9478
9479     $dbh->do(q{
9480         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');
9481    });
9482    print "Upgrade to $DBversion done (Bug 9043: Add system preference OpacAdvSearchOptions and OpacAdvSearchMoreOptions)\n";
9483    SetVersion ($DBversion);
9484 }
9485
9486 $DBversion = "3.17.00.053";
9487 if ( CheckVersion($DBversion) ) {
9488     $dbh->do(q{
9489         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)');
9490     });
9491
9492     $dbh->do(q{
9493         INSERT INTO permissions (module_bit, code, description) VALUES ('9', 'delete_all_items', 'Delete all items at once');
9494     });
9495
9496     $dbh->do(q{
9497         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)');
9498     });
9499
9500     # The delete_all_items permission should be added to users having the edit_items permission.
9501     $dbh->do(q{
9502         INSERT INTO user_permissions (borrowernumber, module_bit, code) SELECT borrowernumber, module_bit, "delete_all_items" FROM user_permissions WHERE code="edit_items";
9503     });
9504
9505     # Add 2 new prefs
9506     $dbh->do(q{
9507         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');
9508     });
9509
9510     $dbh->do(q{
9511         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');
9512     });
9513
9514     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";
9515     SetVersion($DBversion);
9516 }
9517
9518 $DBversion = "3.17.00.054";
9519 if (CheckVersion($DBversion)) {
9520     $dbh->do(q{
9521         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
9522         ('AllowRenewalIfOtherItemsAvailable','0',NULL,'If enabled, allow a patron to renew an item with unfilled holds if other available items can fill that hold.','YesNo')
9523     });
9524     print "Upgrade to $DBversion done (Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds)\n";
9525     SetVersion($DBversion);
9526 }
9527
9528 $DBversion = "3.17.00.055";
9529 if ( CheckVersion($DBversion) ) {
9530     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBEnable', '0', NULL, 'Enable communication with the Norwegian national patron database.', 'YesNo')");
9531     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBEndpoint', '', NULL, 'Which NL endpoint to use.', 'Free')");
9532     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBUsername', '', NULL, 'Username for communication with the Norwegian national patron database.', 'Free')");
9533     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBPassword', '', NULL, 'Password for communication with the Norwegian national patron database.', 'Free')");
9534     $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')");
9535     $dbh->do("
9536 CREATE TABLE borrower_sync (
9537     borrowersyncid int(11) NOT NULL AUTO_INCREMENT,
9538     borrowernumber int(11) NOT NULL,
9539     synctype varchar(32) NOT NULL,
9540     sync tinyint(1) NOT NULL DEFAULT '0',
9541     syncstatus varchar(10) DEFAULT NULL,
9542     lastsync varchar(50) DEFAULT NULL,
9543     hashed_pin varchar(64) DEFAULT NULL,
9544     PRIMARY KEY (borrowersyncid),
9545     KEY borrowernumber (borrowernumber),
9546     CONSTRAINT borrower_sync_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
9547 ) ENGINE=InnoDB DEFAULT CHARSET=utf8"
9548 );
9549     print "Upgrade to $DBversion done (Bug 11401 - Add support for Norwegian national library card)\n";
9550     SetVersion($DBversion);
9551 }
9552
9553 $DBversion = "3.17.00.056";
9554 if ( CheckVersion($DBversion) ) {
9555     $dbh->do(q{
9556         UPDATE systempreferences SET value = 'pubdate,itemtype,language,sorting,location' WHERE variable='OpacAdvSearchOptions'
9557     });
9558
9559     $dbh->do(q{
9560         UPDATE systempreferences SET value = 'pubdate,itemtype,language,subtype,sorting,location' WHERE variable='OpacAdvSearchMoreOptions'
9561     });
9562
9563     print "Upgrade to $DBversion done (Bug 9043 - Update the values for OpacAdvSearchOptions and OpacAdvSearchOptions)\n";
9564     SetVersion($DBversion);
9565 }
9566
9567 $DBversion = "3.17.00.057";
9568 if ( CheckVersion($DBversion) ) {
9569     print "Upgrade to $DBversion done (Koha 3.18 beta)\n";
9570     SetVersion ($DBversion);
9571 }
9572
9573 $DBversion = "3.17.00.058";
9574 if( CheckVersion($DBversion) ){
9575     $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')");
9576     $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')");
9577     $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')");
9578     print "Upgrade to $DBversion done (Bug 8337: System preferences for longoverdue cron)\n";
9579     SetVersion($DBversion);
9580 }
9581
9582 $DBversion = "3.17.00.059";
9583 if ( CheckVersion($DBversion) ) {
9584     $dbh->do(q{
9585         UPDATE permissions SET description = "Add and delete budgets (but can't modifiy budgets)" WHERE description = "Add and delete budgets (but cant modify budgets)";
9586     });
9587     print "Upgrade to $DBversion done (Bug 10749: Fix typo in budget_add_del permission description)\n";
9588     SetVersion ($DBversion);
9589 }
9590
9591 $DBversion = "3.17.00.060";
9592 if ( CheckVersion($DBversion) ) {
9593     my $count_l = $dbh->selectcol_arrayref(q|
9594         SELECT COUNT(*) FROM letter WHERE message_transport_type='feed'
9595     |);
9596     my $count_mq = $dbh->selectcol_arrayref(q|
9597         SELECT COUNT(*) FROM message_queue WHERE message_transport_type='feed'
9598     |);
9599     my $count_ott = $dbh->selectcol_arrayref(q|
9600         SELECT COUNT(*) FROM overduerules_transport_types WHERE message_transport_type='feed'
9601     |);
9602     my $count_mt = $dbh->selectcol_arrayref(q|
9603         SELECT COUNT(*) FROM message_transports WHERE message_transport_type='feed'
9604     |);
9605     my $count_bmtp = $dbh->selectcol_arrayref(q|
9606         SELECT COUNT(*) FROM borrower_message_transport_preferences WHERE message_transport_type='feed'
9607     |);
9608
9609     my $deleted = 0;
9610     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 ) {
9611         $deleted = $dbh->do(q|
9612             DELETE FROM message_transport_types where message_transport_type='feed'
9613         |);
9614         $deleted = $deleted ne '0E0' ? 1 : 0;
9615     }
9616
9617     print "Upgrade to $DBversion done (Bug 12298: Delete the 'feed' message transport type " . ($deleted ? '(deleted!)' : '(not deleted)') . ")\n";
9618     SetVersion($DBversion);
9619 }
9620
9621 $DBversion = "3.18.00.000";
9622 if ( CheckVersion($DBversion) ) {
9623     print "Upgrade to $DBversion done (3.18.0 release)\n";
9624     SetVersion($DBversion);
9625 }
9626
9627 $DBversion = "3.19.00.000";
9628 if ( CheckVersion($DBversion) ) {
9629     print "Upgrade to $DBversion done (there's life after 3.18)\n";
9630     SetVersion ($DBversion);
9631 }
9632
9633 $DBversion = "3.19.00.001";
9634 if ( CheckVersion($DBversion) ) {
9635     $dbh->do("
9636         UPDATE systempreferences
9637         SET options = 'public|school|academic|research|private|societyAssociation|corporate|government|religiousOrg|subscription'
9638         WHERE variable = 'UsageStatsLibraryType'
9639     ");
9640     if ( C4::Context->preference("UsageStatsLibraryType") eq "university" ) {
9641         C4::Context->set_preference("UsageStatsLibraryType", "academic")
9642     }
9643     print "Upgrade to $DBversion done (Bug 13436: Add more options to UsageStatsLibraryType)\n";
9644     SetVersion ($DBversion);
9645 }
9646
9647 $DBversion = "3.19.00.002";
9648 if ( CheckVersion($DBversion) ) {
9649     $dbh->do(q|
9650         UPDATE suggestions SET branchcode="" WHERE branchcode="__ANY__"
9651     |);
9652     print "upgrade to $DBversion done (Bug 10753: replace __ANY__ with empty string in suggestions.branchcode)\n";
9653     SetVersion ($DBversion);
9654 }
9655
9656 $DBversion = "3.19.00.003";
9657 if ( CheckVersion($DBversion) ) {
9658     my ($count) = $dbh->selectrow_array("SELECT COUNT(*) FROM borrowers GROUP BY userid HAVING COUNT(userid) > 1");
9659
9660     if ( $count ) {
9661         print "Upgrade to $DBversion done (Bug 1861 - Unique patrons logins not (totally) enforced) FAILED!\n";
9662         print "Your database has users with duplicate user logins. Please have your administrator deduplicate your user logins.\n";
9663         print "Afterward, your Koha administrator should execute the following database query: ALTER TABLE borrowers DROP INDEX userid, ADD UNIQUE userid (userid)";
9664     } else {
9665         $dbh->do(q{
9666             ALTER TABLE borrowers
9667                 DROP INDEX userid ,
9668                 ADD UNIQUE userid (userid)
9669         });
9670         print "Upgrade to $DBversion done (Bug 1861: Unique patrons logins not (totally) enforced)\n";
9671     }
9672
9673     SetVersion($DBversion);
9674 }
9675
9676 $DBversion = "3.19.00.004";
9677 if ( CheckVersion($DBversion) ) {
9678     my $pref_value = C4::Context->preference('OpacExportOptions');
9679     $pref_value =~ s/\|/,/g; # multiple is separated by ,
9680     $dbh->do(q{
9681         UPDATE systempreferences
9682             SET value = ?,
9683                 type = 'multiple'
9684         WHERE variable = 'OpacExportOptions'
9685     }, {}, $pref_value );
9686     print "Upgrade to $DBversion done (Bug 13346: OpacExportOptions is now multiple)\n";
9687     SetVersion ($DBversion);
9688 }
9689
9690 $DBversion = "3.19.00.005";
9691 if(CheckVersion($DBversion)) {
9692     $dbh->do(q{
9693         ALTER TABLE authorised_values MODIFY COLUMN category VARCHAR(32) NOT NULL DEFAULT ''
9694     });
9695
9696     $dbh->do(q{
9697         ALTER TABLE borrower_attribute_types MODIFY COLUMN authorised_value_category VARCHAR(32) DEFAULT NULL
9698     });
9699
9700     print "Upgrade to $DBversion done (Bug 13379: Modify authorised_values.category to varchar(32))\n";
9701     SetVersion($DBversion);
9702 }
9703
9704 $DBversion = "3.19.00.006";
9705 if ( CheckVersion($DBversion) ) {
9706     $dbh->do(q|SET foreign_key_checks = 0|);
9707     my $sth = $dbh->table_info( '','','','TABLE' );
9708     my ( $cat, $schema, $name, $type, $remarks );
9709     while ( ( $cat, $schema, $name, $type, $remarks ) = $sth->fetchrow_array ) {
9710         my $table_sth = $dbh->prepare(qq|SHOW CREATE TABLE $name|);
9711         $table_sth->execute;
9712         my @table = $table_sth->fetchrow_array;
9713         unless ( $table[1] =~ /COLLATE=utf8mb4_unicode_ci/ ) { #catches utf8mb4 collated tables
9714             $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci|);
9715         }
9716     }
9717     $dbh->do(q|SET foreign_key_checks = 1|);;
9718
9719     print "Upgrade to $DBversion done (Bug 11944: Convert DB tables to utf8_unicode_ci)\n";
9720     SetVersion($DBversion);
9721 }
9722
9723 $DBversion = "3.19.00.007";
9724 if ( CheckVersion($DBversion) ) {
9725     my $orphan_budgets = $dbh->selectall_arrayref(q|
9726         SELECT budget_id, budget_name, budget_code
9727         FROM aqbudgets
9728         WHERE   budget_parent_id IS NOT NULL
9729             AND budget_parent_id NOT IN (
9730                 SELECT DISTINCT budget_id FROM aqbudgets
9731             )
9732     |, { Slice => {} } );
9733
9734     if ( @$orphan_budgets ) {
9735         for my $b ( @$orphan_budgets ) {
9736             print "Fund $b->{budget_name} (code:$b->{budget_code}, id:$b->{budget_id}) does not have a parent, it may cause problem\n";
9737         }
9738         print "Upgrade to $DBversion done (Bug 12905: Check budget integrity: FAIL)\n";
9739     } else {
9740         print "Upgrade to $DBversion done (Bug 12905: Check budget integrity: OK)\n";
9741     }
9742     SetVersion($DBversion);
9743 }
9744
9745 $DBversion = "3.19.00.008";
9746 if ( CheckVersion($DBversion) ) {
9747     my $number_of_orders_not_linked = $dbh->selectcol_arrayref(q|
9748         SELECT COUNT(*)
9749         FROM aqorders o
9750         WHERE NOT EXISTS (
9751             SELECT NULL
9752             FROM aqbudgets b
9753             WHERE b.budget_id = o.budget_id
9754         );
9755     |);
9756
9757     if ( $number_of_orders_not_linked->[0] > 0 ) {
9758         $dbh->do(q|
9759             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)
9760         |);
9761         my $budget_period_id = $dbh->last_insert_id( undef, undef, 'aqbudgetperiods', undef );
9762         $dbh->do(qq|
9763             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 );
9764         |);
9765         my $budget_id = $dbh->last_insert_id( undef, undef, 'aqbudgets', undef );
9766         $dbh->do(qq|
9767             UPDATE aqorders o
9768             SET budget_id = $budget_id
9769             WHERE NOT EXISTS (
9770                 SELECT NULL
9771                 FROM aqbudgets b
9772                 WHERE b.budget_id = o.budget_id
9773             )
9774         |);
9775     }
9776
9777     $dbh->do(q|
9778         ALTER TABLE aqorders
9779         ADD CONSTRAINT aqorders_budget_id_fk FOREIGN KEY (budget_id) REFERENCES aqbudgets(budget_id) ON DELETE CASCADE ON UPDATE CASCADE
9780     |);
9781
9782     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";
9783     SetVersion($DBversion);
9784 }
9785
9786 $DBversion = "3.19.00.009";
9787 if ( CheckVersion($DBversion) ) {
9788     $dbh->do(q|
9789         UPDATE suggestions s SET s.budgetid = NULL
9790         WHERE NOT EXISTS (
9791             SELECT NULL
9792             FROM aqbudgets b
9793             WHERE b.budget_id = s.budgetid
9794         );
9795     |);
9796
9797     $dbh->do(q|
9798         ALTER TABLE suggestions
9799         ADD CONSTRAINT suggestions_budget_id_fk FOREIGN KEY (budgetid) REFERENCES aqbudgets(budget_id) ON DELETE SET NULL ON UPDATE CASCADE
9800     |);
9801
9802     print "Upgrade to $DBversion done (Bug 13007: Add new foreign key suggestions.budgetid)\n";
9803     SetVersion($DBversion);
9804 }
9805
9806 $DBversion = "3.19.00.010";
9807 if ( CheckVersion($DBversion) ) {
9808     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('SessionRestrictionByIP','1','Check for Change in  Remote IP address for Session Security. Disable when remote ip address changes frequently.','','YesNo')");
9809     print "Upgrade to $DBversion done (Bug 5511: SessionRestrictionByIP)\n";
9810     SetVersion ($DBversion);
9811 }
9812
9813 $DBversion = "3.19.00.011";
9814 if ( CheckVersion($DBversion) ) {
9815     $dbh->do(q|
9816         INSERT INTO userflags (bit, flag, flagdesc, defaulton) VALUES
9817         (20, 'lists', 'Lists', 0)
9818     |);
9819     $dbh->do(q|
9820         INSERT INTO permissions (module_bit, code, description) VALUES
9821         (20, 'delete_public_lists', 'Delete public lists')
9822     |);
9823     print "Upgrade to $DBversion done (Bug 13417: Add permission to delete public lists)\n";
9824     SetVersion ($DBversion);
9825 }
9826
9827 $DBversion = "3.19.00.012";
9828 if(CheckVersion($DBversion)) {
9829     $dbh->do(q{
9830         ALTER TABLE biblioitems MODIFY COLUMN marcxml longtext
9831     });
9832
9833     $dbh->do(q{
9834         ALTER TABLE deletedbiblioitems MODIFY COLUMN marcxml longtext
9835     });
9836
9837     print "Upgrade to $DBversion done (Bug 13523 Remove NOT NULL restriction on field marcxml due to mysql STRICT_TRANS_TABLES)\n";
9838     SetVersion ($DBversion);
9839 }
9840
9841 $DBversion = "3.19.00.013";
9842 if ( CheckVersion($DBversion) ) {
9843     $dbh->do(q|
9844         INSERT INTO permissions (module_bit, code, description) VALUES
9845           (13, 'records_batchmod', 'Perform batch modification of records (biblios or authorities)')
9846     |);
9847     print "Upgrade to $DBversion done (Bug 11395: Add permission tools_records_batchmod)\n";
9848     SetVersion($DBversion);
9849 }
9850
9851 $DBversion = "3.19.00.014";
9852 if ( CheckVersion($DBversion) ) {
9853     $dbh->do(q|
9854         CREATE TABLE aqorder_users (
9855             ordernumber int(11) NOT NULL,
9856             borrowernumber int(11) NOT NULL,
9857             PRIMARY KEY (ordernumber, borrowernumber),
9858             CONSTRAINT aqorder_users_ibfk_1 FOREIGN KEY (ordernumber) REFERENCES aqorders (ordernumber) ON DELETE CASCADE ON UPDATE CASCADE,
9859             CONSTRAINT aqorder_users_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
9860         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
9861     |);
9862
9863     $dbh->do(q|
9864         INSERT INTO letter(module, code, branchcode, name, title, content, message_transport_type)
9865         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')
9866     |);
9867     print "Upgrade to $DBversion done (Bug 12648: Add letter ACQ_NOTIF_ON_RECEIV )\n";
9868     SetVersion ($DBversion);
9869 }
9870
9871 $DBversion = "3.19.00.015";
9872 if ( CheckVersion($DBversion) ) {
9873     $dbh->do(q|
9874         ALTER TABLE search_history ADD COLUMN id INT(11) NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY(id);
9875     |);
9876     print "Upgrade to $DBversion done (Bug 11430: Add primary key for search_history)\n";
9877     SetVersion($DBversion);
9878 }
9879
9880 $DBversion = "3.19.00.016";
9881 if(CheckVersion($DBversion)) {
9882     my @order_cancellation_reason = $dbh->selectrow_array("SELECT count(*) FROM authorised_values WHERE category='ORDER_CANCELLATION_REASON'");
9883     if ($order_cancellation_reason[0] == 0) {
9884         $dbh->do(q{
9885             INSERT INTO authorised_values (category, authorised_value, lib) VALUES
9886              ('ORDER_CANCELLATION_REASON', 0, 'No reason provided'),
9887              ('ORDER_CANCELLATION_REASON', 1, 'Out of stock'),
9888              ('ORDER_CANCELLATION_REASON', 2, 'Restocking')
9889         });
9890
9891         my $already_existing_reasons = $dbh->selectcol_arrayref(q{
9892             SELECT DISTINCT( cancellationreason )
9893             FROM aqorders;
9894         }, { Slice => {} });
9895
9896         my $update_orders_sth = $dbh->prepare(q{
9897             UPDATE aqorders
9898             SET cancellationreason = ?
9899             WHERE cancellationreason = ?
9900         });
9901
9902         my $insert_av_sth = $dbh->prepare(q{
9903             INSERT INTO authorised_values (category, authorised_value, lib) VALUES
9904              ('ORDER_CANCELLATION_REASON', ?, ?)
9905         });
9906         my $i = 3;
9907         for my $reason ( @$already_existing_reasons ) {
9908             next unless $reason;
9909             $insert_av_sth->execute( $i, $reason );
9910             $update_orders_sth->execute( $i, $reason );
9911             $i++;
9912         }
9913         print "Upgrade to $DBversion done (Bug 13380: Add the ORDER_CANCELLATION_REASON authorised value)\n";
9914     }
9915     else {
9916         print "Upgrade to $DBversion done (Bug 13380: ORDER_CANCELLATION_REASON authorised value already existed from earlier update!)\n";
9917     }
9918
9919     SetVersion($DBversion);
9920 }
9921
9922 $DBversion = '3.19.00.017';
9923 if ( CheckVersion($DBversion) ) {
9924     # First create the column
9925     $dbh->do("ALTER TABLE issuingrules ADD onshelfholds tinyint(1) default 0 NOT NULL");
9926     # Now update the column
9927     if (C4::Context->preference("AllowOnShelfHolds")){
9928         # Pref is on, set allow for all rules
9929         $dbh->do("UPDATE issuingrules SET onshelfholds=1");
9930     } else {
9931         # If the preference is not set, leave off
9932         $dbh->do("UPDATE issuingrules SET onshelfholds=0");
9933     }
9934     # Remove from the systempreferences table
9935     $dbh->do("DELETE FROM systempreferences WHERE variable = 'AllowOnShelfHolds'");
9936
9937     # First create the column
9938     $dbh->do("ALTER TABLE issuingrules ADD opacitemholds char(1) DEFAULT 'N' NOT NULL");
9939     # Now update the column
9940     my $opacitemholds = C4::Context->preference("OPACItemHolds") || '';
9941     if (lc ($opacitemholds) eq 'force') {
9942         $opacitemholds = 'F';
9943     }
9944     else {
9945         $opacitemholds = $opacitemholds ? 'Y' : 'N';
9946     }
9947     # Set allow for all rules
9948     $dbh->do("UPDATE issuingrules SET opacitemholds='$opacitemholds'");
9949
9950     # Remove from the systempreferences table
9951     $dbh->do("DELETE FROM systempreferences WHERE variable = 'OPACItemHolds'");
9952
9953     print "Upgrade to $DBversion done (Bug 5786: Move AllowOnShelfHolds to circulation matrix; Move OPACItemHolds system preference to circulation matrix)\n";
9954     SetVersion ($DBversion);
9955 }
9956
9957 $DBversion = "3.19.00.018";
9958 if ( CheckVersion($DBversion) ) {
9959     $dbh->do(q|
9960         UPDATE systempreferences set variable="OpacAdditionalStylesheet" WHERE variable="opaccolorstylesheet"
9961     |);
9962     print "Upgrade to $DBversion done (Bug 10328: Rename opaccolorstylesheet to OpacAdditionalStylesheet\n";
9963     SetVersion ($DBversion);
9964 }
9965
9966 $DBversion = "3.19.00.019";
9967 if ( CheckVersion($DBversion) ) {
9968     $dbh->do(q{
9969         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
9970         VALUES('Coce','0', 'If on, enables cover retrieval from the configured Coce server', NULL, 'YesNo')
9971     });
9972     $dbh->do(q{
9973         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
9974         VALUES('CoceHost', NULL, 'Coce server URL', NULL,'Free')
9975     });
9976     $dbh->do(q{
9977         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
9978         VALUES('CoceProviders', NULL, 'Coce providers', 'aws,gb,ol', 'multiple')
9979     });
9980     print "Upgrade to $DBversion done (Bug 9580: Cover image from Coce, a remote image URL cache)\n";
9981     SetVersion($DBversion);
9982 }
9983
9984 $DBversion = "3.19.00.020";
9985 if ( CheckVersion($DBversion) ) {
9986     $dbh->do(q|
9987         ALTER TABLE aqorders DROP COLUMN supplierreference;
9988     |);
9989
9990     print "Upgrade to $DBversion done (Bug 11008: DROP column aqorders.supplierreference)\n";
9991     SetVersion($DBversion);
9992 }
9993
9994 $DBversion = "3.19.00.021";
9995 if ( CheckVersion($DBversion) ) {
9996     $dbh->do(q|
9997         ALTER TABLE issues DROP COLUMN issuingbranch
9998     |);
9999     $dbh->do(q|
10000         ALTER TABLE old_issues DROP COLUMN issuingbranch
10001     |);
10002     print "Upgrade to $DBversion done (Bug 2806: Remove issuingbranch columns)\n";
10003     SetVersion ($DBversion);
10004 }
10005
10006 $DBversion = '3.19.00.022';
10007 if ( CheckVersion($DBversion) ) {
10008     $dbh->do(q{
10009         ALTER TABLE suggestions DROP COLUMN mailoverseeing;
10010     });
10011     print "Upgrade to $DBversion done (Bug 13006: Drop column suggestion.mailoverseeing)\n";
10012     SetVersion($DBversion);
10013 }
10014
10015 $DBversion = "3.19.00.023";
10016 if ( CheckVersion($DBversion) ) {
10017     $dbh->do(q|
10018         DELETE FROM systempreferences where variable = 'AddPatronLists'
10019     |);
10020     print "Upgrade to $DBversion done (Bug 13497: Remove the AddPatronLists system preferences)\n";
10021     SetVersion ($DBversion);
10022 }
10023
10024 $DBversion = "3.19.00.024";
10025 if ( CheckVersion($DBversion) ) {
10026     $dbh->do(qq|DROP table patroncards;|);
10027     print "Upgrade to $DBversion done (Bug 13539: Remove table patroncards from database as it's no longer in use)\n";
10028     SetVersion ($DBversion);
10029 }
10030
10031 $DBversion = "3.19.00.025";
10032 if ( CheckVersion($DBversion) ) {
10033     $dbh->do(q|
10034         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
10035         ('SearchWithISBNVariations','0',NULL,'If enabled, search on all variations of the ISBN','YesNo')
10036     |);
10037     print "Upgrade to $DBversion done (Bug 13528: Add the SearchWithISBNVariations syspref)\n";
10038     SetVersion ($DBversion);
10039 }
10040
10041 $DBversion = "3.19.00.026";
10042 if( CheckVersion($DBversion) ) {
10043     if ( C4::Context->preference('marcflavour') eq 'MARC21' ) {
10044     $dbh->do(q{
10045         INSERT IGNORE INTO auth_tag_structure (authtypecode, tagfield, liblibrarian, libopac, repeatable, mandatory, authorised_value) VALUES
10046         ('', '388', 'TIME PERIOD OF CREATION', 'TIME PERIOD OF CREATION', 1, 0, NULL);
10047     });
10048
10049     $dbh->do(q{
10050         INSERT IGNORE INTO auth_subfield_structure (authtypecode, tagfield, tagsubfield, liblibrarian, libopac, repeatable,
10051         mandatory, tab, authorised_value, value_builder, seealso, isurl, hidden, linkid, kohafield, frameworkcode) VALUES
10052         ('', '388', '0', 'Authority record control number or standard number', 'Authority record control number or standard number', 1, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10053         ('', '388', '2', 'Source of term', 'Source of term', 0, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10054         ('', '388', '3', 'Materials specified', 'Materials specified', 0, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10055         ('', '388', '6', 'Linkage', 'Linkage', 0, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10056         ('', '388', '8', 'Field link and sequence number', 'Field link and sequence number', 1, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10057         ('', '388', 'a', 'Time period of creation term', 'Time period of creation term', 1, 0, 3, NULL, NULL, NULL, 0, 0, '', '', '');
10058     });
10059
10060     $dbh->do(q{
10061         UPDATE IGNORE auth_subfield_structure SET repeatable = 1 WHERE tagsubfield = 'g' AND tagfield IN
10062         ('100','110','111','130','400','410','411','430','500','510','511','530','700','710','730');
10063     });
10064
10065     $dbh->do(q{
10066         INSERT IGNORE INTO auth_subfield_structure (authtypecode, tagfield, tagsubfield, liblibrarian, libopac, repeatable,
10067         mandatory, tab, authorised_value, value_builder, seealso, isurl, hidden, linkid, kohafield, frameworkcode) VALUES
10068         ('', '150', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 1, NULL, NULL, NULL, 0, 0, '', '', ''),
10069         ('', '151', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 1, NULL, NULL, NULL, 0, 0, '', '', ''),
10070         ('', '450', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 4, NULL, NULL, NULL, 0, 0, '', '', ''),
10071         ('', '451', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 4, NULL, NULL, NULL, 0, 0, '', '', ''),
10072         ('', '550', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 5, NULL, NULL, NULL, 0, 0, '', '', ''),
10073         ('', '551', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 5, NULL, NULL, NULL, 0, 0, '', '', ''),
10074         ('', '750', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10075         ('', '751', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10076         ('', '748', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10077         ('', '755', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10078         ('', '780', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10079         ('', '781', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10080         ('', '782', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10081         ('', '785', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10082         ('', '710', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10083         ('', '730', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10084         ('', '748', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10085         ('', '750', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10086         ('', '751', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10087         ('', '755', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10088         ('', '762', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10089         ('', '780', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10090         ('', '781', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10091         ('', '782', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10092         ('', '785', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10093         ('', '788', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', '');
10094     });
10095
10096     $dbh->do(q{
10097         UPDATE IGNORE auth_subfield_structure SET liblibrarian = 'Relationship information', libopac = 'Relationship information'
10098         WHERE tagsubfield = 'i' AND tagfield IN ('700','710','730','750','751','762');
10099     });
10100
10101     $dbh->do(q{
10102         UPDATE IGNORE auth_subfield_structure SET liblibrarian = 'Relationship code', libopac = 'Relationship code'
10103         WHERE tagsubfield = '4' AND tagfield IN ('700','710');
10104     });
10105
10106     $dbh->do(q{
10107         INSERT IGNORE INTO marc_tag_structure (tagfield, liblibrarian, libopac, repeatable, mandatory, authorised_value, frameworkcode) VALUES
10108         ('370', 'ASSOCIATED PLACE', 'ASSOCIATED PLACE', 1, 0, NULL, ''),
10109         ('388', 'TIME PERIOD OF CREATION', 'TIME PERIOD OF CREATION', 1, 0, NULL, '');
10110     });
10111
10112     $dbh->do(q{
10113         INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian, libopac, repeatable, mandatory,
10114         kohafield, tab, authorised_value, authtypecode, value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
10115         ('370', '0', 'Authority record control number or standard number', 'Authority record control number or standard number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10116         ('370', '2', 'Source of term', 'Source of term', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10117         ('370', '6', 'Linkage', 'Linkage', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10118         ('370', '8', 'Field link and sequence number', 'Field link and sequence number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10119         ('370', 'c', 'Associated country', 'Associated country', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10120         ('370', 'f', 'Other associated place', 'Other associated place', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10121         ('370', 'g', 'Place of origin of work', 'Place of origin of work', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10122         ('370', 's', 'Start period', 'Start period', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10123         ('370', 't', 'End period', 'End period', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10124         ('370', 'u', 'Uniform Resource Identifier', 'Uniform Resource Identifier', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10125         ('370', 'v', 'Source of information', 'Source of information', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10126         ('377', 'l', 'Language term', 'Language term', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10127         ('382', 's', 'Total number of performers', 'Total number of performers', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10128         ('388', '0', 'Authority record control number or standard number', 'Authority record control number or standard number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10129         ('388', '2', 'Source of term', 'Source of term', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10130         ('388', '3', ' Materials specified', ' Materials specified', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10131         ('388', '6', ' Linkage', ' Linkage', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10132         ('388', '8', 'Field link and sequence number', 'Field link and sequence number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10133         ('388', 'a', 'Time period of creation term', 'Time period of creation term', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10134         ('650', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, '', 6, '', '', '', 0, -1, '', '', '', NULL),
10135         ('651', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, '', 6, '', '', '', 0, -1, '', '', '', NULL);
10136     });
10137
10138     $dbh->do(q{
10139         UPDATE IGNORE marc_subfield_structure SET repeatable = 1 WHERE tagsubfield = 'g' AND
10140         tagfield IN ('100','110','111','130','240','243','246','247','600','610','611','630','700','710','711','730','800','810','811','830');
10141     });
10142     }
10143
10144     print "Upgrade to $DBversion done (Bug 13322: Update MARC21 frameworks to Update No. 19 - October 2014)\n";
10145     SetVersion($DBversion);
10146 }
10147
10148 $DBversion = '3.19.00.027';
10149 if ( CheckVersion($DBversion) ) {
10150     $dbh->do("ALTER TABLE items ADD COLUMN itemnotes_nonpublic MEDIUMTEXT AFTER itemnotes");
10151     $dbh->do("ALTER TABLE deleteditems ADD COLUMN itemnotes_nonpublic MEDIUMTEXT AFTER itemnotes");
10152     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";
10153     SetVersion($DBversion);
10154 }
10155
10156 $DBversion = "3.19.00.028";
10157 if( CheckVersion($DBversion) ) {
10158     eval {
10159         local $dbh->{PrintError} = 0;
10160         $dbh->do(q{
10161             ALTER TABLE issues DROP PRIMARY KEY
10162         });
10163     };
10164
10165     $dbh->do(q{
10166         ALTER TABLE old_issues ADD issue_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10167     });
10168
10169     $dbh->do(q{
10170         ALTER TABLE old_issues CHANGE issue_id issue_id INT( 11 ) NOT NULL
10171     });
10172
10173     $dbh->do(q{
10174         ALTER TABLE issues ADD issue_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10175     });
10176
10177     $dbh->do(q{
10178         UPDATE issues SET issue_id = issue_id + ( SELECT COUNT(*) FROM old_issues ) ORDER BY issue_id DESC
10179     });
10180
10181     my $max_issue_id = $schema->resultset('Issue')->get_column('issue_id')->max();
10182     if ($max_issue_id) {
10183         $max_issue_id++;
10184         $dbh->do(qq{
10185             ALTER TABLE issues AUTO_INCREMENT = $max_issue_id
10186         });
10187     }
10188
10189     print "Upgrade to $DBversion done (Bug 13790: Add unique id issue_id to issues and oldissues tables)\n";
10190     SetVersion($DBversion);
10191 }
10192
10193 $DBversion = "3.19.00.029";
10194 if ( CheckVersion($DBversion) ) {
10195     $dbh->do(q|
10196          ALTER TABLE sessions CHANGE COLUMN a_session a_session MEDIUMTEXT
10197     |);
10198     print "Upgrade to $DBversion done (Bug 13606: Upgrade sessions.a_session to MEDIUMTEXT)\n";
10199     SetVersion($DBversion);
10200 }
10201
10202 $DBversion = "3.19.00.030";
10203 if ( CheckVersion($DBversion) ) {
10204     $dbh->do(q|
10205 UPDATE language_subtag_registry SET subtag = 'kn' WHERE subtag = 'ka' AND description = 'Kannada';
10206     |);
10207     $dbh->do(q|
10208 UPDATE language_rfc4646_to_iso639 SET rfc4646_subtag = 'kn' WHERE rfc4646_subtag = 'ka' AND iso639_2_code = 'kan';
10209     |);
10210     $dbh->do(q|
10211 UPDATE language_descriptions SET subtag = 'kn', lang = 'kn' WHERE subtag = 'ka' AND lang = 'ka' AND description = 'ಕನ್ನಡ';
10212     |);
10213     $dbh->do(q|
10214 UPDATE language_descriptions SET subtag = 'kn' WHERE subtag = 'ka' AND description = 'Kannada';
10215     |);
10216     $dbh->do(q|
10217 INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ka', 'language', 'Georgian','2015-04-20');
10218     |);
10219     $dbh->do(q|
10220 DELETE FROM language_subtag_registry
10221        WHERE NOT id IN
10222          (SELECT id FROM
10223            (SELECT MIN(id) as id,subtag,type,description,added
10224             FROM language_subtag_registry
10225             GROUP BY subtag,type,description,added)
10226            AS subtable);
10227     |);
10228     $dbh->do(q|
10229 INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ka', 'geo');
10230     |);
10231     $dbh->do(q|
10232 DELETE FROM language_rfc4646_to_iso639
10233        WHERE NOT id IN
10234          (SELECT id FROM
10235            (SELECT MIN(id) as id,rfc4646_subtag,iso639_2_code
10236             FROM language_rfc4646_to_iso639
10237             GROUP BY rfc4646_subtag,iso639_2_code)
10238            AS subtable);
10239     |);
10240     $dbh->do(q|
10241 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'ka', 'ქართული');
10242     |);
10243     $dbh->do(q|
10244 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'en', 'Georgian');
10245     |);
10246     $dbh->do(q|
10247 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'fr', 'Géorgien');
10248     |);
10249     $dbh->do(q|
10250 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'de', 'Georgisch');
10251     |);
10252     $dbh->do(q|
10253 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'es', 'Georgiano');
10254     |);
10255     $dbh->do(q|
10256 DELETE FROM language_descriptions
10257        WHERE NOT id IN
10258          (SELECT id FROM
10259            (SELECT MIN(id) as id,subtag,type,lang,description
10260             FROM language_descriptions GROUP BY subtag,type,lang,description)
10261            AS subtable);
10262     |);
10263     print "Upgrade to $DBversion done (Bug 14030: Add Georgian language and fix Kannada language code)\n";
10264     SetVersion($DBversion);
10265 }
10266
10267 $DBversion = "3.19.00.031";
10268 if ( CheckVersion($DBversion) ) {
10269     $dbh->do(q{
10270         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10271         VALUES('IdRef','0','Disable/enable the IdRef webservice from the OPAC detail page.',NULL,'YesNo')
10272     });
10273     print "Upgrade to $DBversion done (Bug 8992: Add system preference IdRef))\n";
10274     SetVersion($DBversion);
10275 }
10276
10277 $DBversion = "3.19.00.032";
10278 if ( CheckVersion($DBversion) ) {
10279     $dbh->do(q|
10280         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10281         VALUES('AddressFormat','us','Choose format to display postal addresses','','Choice')
10282     |);
10283     print "Upgrade to $DBversion done (Bug 4041: Address Format as a I18N/L10N system preference\n";
10284     SetVersion ($DBversion);
10285 }
10286
10287 $DBversion = "3.19.00.033";
10288 if ( CheckVersion($DBversion) ) {
10289     $dbh->do(q|
10290         ALTER TABLE auth_header
10291         CHANGE COLUMN datemodified modification_time TIMESTAMP NOT NULL default CURRENT_TIMESTAMP
10292     |);
10293     $dbh->do(q|
10294         ALTER TABLE auth_header
10295         CHANGE COLUMN modification_time modification_time TIMESTAMP NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP
10296     |);
10297     print "Upgrade to $DBversion done (Bug 11165: Update auth_header.datemodified when updated)\n";
10298     SetVersion ($DBversion);
10299 }
10300
10301 $DBversion = "3.19.00.034";
10302 if ( CheckVersion($DBversion) ) {
10303     $dbh->do(q|
10304         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10305         VALUES('CardnumberLength', '', '', 'Set a length for card numbers.', 'Free')
10306     |);
10307     print "Upgrade to $DBversion done (Bug 13984: CardnumberLength syspref missing on some setups\n";
10308     SetVersion ($DBversion);
10309 }
10310
10311 $DBversion = "3.19.00.035";
10312 if ( CheckVersion($DBversion) ) {
10313     $dbh->do(q|
10314         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('useDischarge','','Allows librarians to discharge borrowers and borrowers to request a discharge','','YesNo')
10315     |);
10316     $dbh->do(q|
10317         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.')
10318     |);
10319
10320     $dbh->do(q|
10321         ALTER TABLE borrower_debarments CHANGE type type ENUM('SUSPENSION','OVERDUES','MANUAL','DISCHARGE') NOT NULL DEFAULT 'MANUAL'
10322     |);
10323
10324     $dbh->do(q|
10325         CREATE TABLE discharges (
10326           borrower int(11) DEFAULT NULL,
10327           needed timestamp NULL DEFAULT NULL,
10328           validated timestamp NULL DEFAULT NULL,
10329           KEY borrower_discharges_ibfk1 (borrower),
10330           CONSTRAINT borrower_discharges_ibfk1 FOREIGN KEY (borrower) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
10331         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
10332     |);
10333
10334     print "Upgrade to $DBversion done (Bug 8007: Add System Preferences useDischarge, the discharge notice and the new table discharges)\n";
10335     SetVersion($DBversion);
10336 }
10337
10338 $DBversion = "3.19.00.036";
10339 if ( CheckVersion($DBversion) ) {
10340     $dbh->do(q|
10341         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10342         VALUES ('CronjobLog','0',NULL,'If ON, log information from cron jobs.','YesNo')
10343     |);
10344     print "Upgrade to $DBversion done (Bug 13889: Add cron jobs information to system log)\n";
10345     SetVersion ($DBversion);
10346 }
10347
10348 # DEVELOPER PROCESS, search for anything to execute in the db_update directory
10349 # SEE bug 13068
10350 # if there is anything in the atomicupdate, read and execute it.
10351
10352 my $update_dir = C4::Context->config('intranetdir') . '/installer/data/mysql/atomicupdate/';
10353 opendir( my $dirh, $update_dir );
10354 foreach my $file ( sort readdir $dirh ) {
10355     next if $file !~ /\.(sql|perl)$/;  #skip other files
10356     print "DEV atomic update: $file\n";
10357     if ( $file =~ /\.sql$/ ) {
10358         my $installer = C4::Installer->new();
10359         my $rv = $installer->load_sql( $update_dir . $file ) ? 0 : 1;
10360     } elsif ( $file =~ /\.perl$/ ) {
10361         do $update_dir . $file;
10362     }
10363 }
10364
10365 =head1 FUNCTIONS
10366
10367 =head2 TableExists($table)
10368
10369 =cut
10370
10371 sub TableExists {
10372     my $table = shift;
10373     eval {
10374                 local $dbh->{PrintError} = 0;
10375                 local $dbh->{RaiseError} = 1;
10376                 $dbh->do(qq{SELECT * FROM $table WHERE 1 = 0 });
10377             };
10378     return 1 unless $@;
10379     return 0;
10380 }
10381
10382 =head2 DropAllForeignKeys($table)
10383
10384 Drop all foreign keys of the table $table
10385
10386 =cut
10387
10388 sub DropAllForeignKeys {
10389     my ($table) = @_;
10390     # get the table description
10391     my $sth = $dbh->prepare("SHOW CREATE TABLE $table");
10392     $sth->execute;
10393     my $vsc_structure = $sth->fetchrow;
10394     # split on CONSTRAINT keyword
10395     my @fks = split /CONSTRAINT /,$vsc_structure;
10396     # parse each entry
10397     foreach (@fks) {
10398         # isolate what is before FOREIGN KEY, if there is something, it's a foreign key to drop
10399         $_ = /(.*) FOREIGN KEY.*/;
10400         my $id = $1;
10401         if ($id) {
10402             # we have found 1 foreign, drop it
10403             $dbh->do("ALTER TABLE $table DROP FOREIGN KEY $id");
10404             $id="";
10405         }
10406     }
10407 }
10408
10409
10410 =head2 TransformToNum
10411
10412 Transform the Koha version from a 4 parts string
10413 to a number, with just 1 .
10414
10415 =cut
10416
10417 sub TransformToNum {
10418     my $version = shift;
10419     # remove the 3 last . to have a Perl number
10420     $version =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
10421     # three X's at the end indicate that you are testing patch with dbrev
10422     # change it into 999
10423     # prevents error on a < comparison between strings (should be: lt)
10424     $version =~ s/XXX$/999/;
10425     return $version;
10426 }
10427
10428 =head2 SetVersion
10429
10430 set the DBversion in the systempreferences
10431
10432 =cut
10433
10434 sub SetVersion {
10435     return if $_[0]=~ /XXX$/;
10436       #you are testing a patch with a db revision; do not change version
10437     my $kohaversion = TransformToNum($_[0]);
10438     if (C4::Context->preference('Version')) {
10439       my $finish=$dbh->prepare("UPDATE systempreferences SET value=? WHERE variable='Version'");
10440       $finish->execute($kohaversion);
10441     } else {
10442       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')");
10443       $finish->execute($kohaversion);
10444     }
10445     C4::Context::clear_syspref_cache(); # invalidate cached preferences
10446 }
10447
10448 =head2 CheckVersion
10449
10450 Check whether a given update should be run when passed the proposed version
10451 number. The update will always be run if the proposed version is greater
10452 than the current database version and less than or equal to the version in
10453 kohaversion.pl. The update is also run if the version contains XXX, though
10454 this behavior will be changed following the adoption of non-linear updates
10455 as implemented in bug 7167.
10456
10457 =cut
10458
10459 sub CheckVersion {
10460     my ($proposed_version) = @_;
10461     my $version_number = TransformToNum($proposed_version);
10462
10463     # The following line should be deleted when bug 7167 is pushed
10464     return 1 if ( $proposed_version =~ m/XXX/ );
10465
10466     if ( C4::Context->preference("Version") < $version_number
10467         && $version_number <= TransformToNum( C4::Context->final_linear_version ) )
10468     {
10469         return 1;
10470     }
10471     else {
10472         return 0;
10473     }
10474 }
10475
10476 exit;