Bug 9978: Replace license header with the correct license (GPLv3+)
[koha-equinox.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
41 use MARC::Record;
42 use MARC::File::XML ( BinaryEncoding => 'utf8' );
43
44 # FIXME - The user might be installing a new database, so can't rely
45 # on /etc/koha.conf anyway.
46
47 my $debug = 0;
48
49 my (
50     $sth, $sti,
51     $query,
52     %existingtables,    # tables already in database
53     %types,
54     $table,
55     $column,
56     $type, $null, $key, $default, $extra,
57     $prefitem,          # preference item in systempreferences table
58 );
59
60 my $silent;
61 GetOptions(
62     's' =>\$silent
63     );
64 my $dbh = C4::Context->dbh;
65 $|=1; # flushes output
66
67 local $dbh->{RaiseError} = 0;
68
69 # Record the version we are coming from
70
71 my $original_version = C4::Context->preference("Version");
72
73 # Deal with virtualshelves
74 my $DBversion = "3.00.00.001";
75 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
76     # update virtualshelves table to
77     #
78     $dbh->do("ALTER TABLE `bookshelf` RENAME `virtualshelves`");
79     $dbh->do("ALTER TABLE `shelfcontents` RENAME `virtualshelfcontents`");
80     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD `biblionumber` INT( 11 ) NOT NULL default '0' AFTER shelfnumber");
81     $dbh->do("UPDATE `virtualshelfcontents` SET biblionumber=(SELECT biblionumber FROM items WHERE items.itemnumber=virtualshelfcontents.itemnumber)");
82     # drop all foreign keys : otherwise, we can't drop itemnumber field.
83     DropAllForeignKeys('virtualshelfcontents');
84     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD KEY biblionumber (biblionumber)");
85     # create the new foreign keys (on biblionumber)
86     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD CONSTRAINT `virtualshelfcontents_ibfk_1` FOREIGN KEY (`shelfnumber`) REFERENCES `virtualshelves` (`shelfnumber`) ON DELETE CASCADE ON UPDATE CASCADE");
87     # re-create the foreign key on virtualshelf
88     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD CONSTRAINT `shelfcontents_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE");
89     $dbh->do("ALTER TABLE `virtualshelfcontents` DROP `itemnumber`");
90     print "Upgrade to $DBversion done (virtualshelves)\n";
91     SetVersion ($DBversion);
92 }
93
94
95 $DBversion = "3.00.00.002";
96 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
97     $dbh->do("DROP TABLE sessions");
98     $dbh->do("CREATE TABLE `sessions` (
99   `id` varchar(32) NOT NULL,
100   `a_session` text NOT NULL,
101   UNIQUE KEY `id` (`id`)
102 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
103     print "Upgrade to $DBversion done (sessions uses CGI::session, new table structure for sessions)\n";
104     SetVersion ($DBversion);
105 }
106
107
108 $DBversion = "3.00.00.003";
109 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
110     if (C4::Context->preference("opaclanguages") eq "fr") {
111         $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')");
112     } else {
113         $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')");
114     }
115     print "Upgrade to $DBversion done (adding ReservesNeedReturns systempref, in circulation)\n";
116     SetVersion ($DBversion);
117 }
118
119
120 $DBversion = "3.00.00.004";
121 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
122     $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')");
123     print "Upgrade to $DBversion done (adding DebugLevel systempref, in 'Admin' tab)\n";
124     SetVersion ($DBversion);
125 }
126
127 $DBversion = "3.00.00.005";
128 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
129     $dbh->do("CREATE TABLE `tags` (
130                     `entry` varchar(255) NOT NULL default '',
131                     `weight` bigint(20) NOT NULL default 0,
132                     PRIMARY KEY  (`entry`)
133                     ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
134                 ");
135         $dbh->do("CREATE TABLE `nozebra` (
136                 `server` varchar(20)     NOT NULL,
137                 `indexname` varchar(40)  NOT NULL,
138                 `value` varchar(250)     NOT NULL,
139                 `biblionumbers` longtext NOT NULL,
140                 KEY `indexname` (`server`,`indexname`),
141                 KEY `value` (`server`,`value`))
142                 ENGINE=InnoDB DEFAULT CHARSET=utf8;
143                 ");
144     print "Upgrade to $DBversion done (adding tags and nozebra tables )\n";
145     SetVersion ($DBversion);
146 }
147
148 $DBversion = "3.00.00.006";
149 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
150     $dbh->do("UPDATE issues SET issuedate=timestamp WHERE issuedate='0000-00-00'");
151     print "Upgrade to $DBversion done (filled issues.issuedate with timestamp)\n";
152     SetVersion ($DBversion);
153 }
154
155 $DBversion = "3.00.00.007";
156 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
157     $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')");
158     print "Upgrade to $DBversion done (set SessionStorage variable)\n";
159     SetVersion ($DBversion);
160 }
161
162 $DBversion = "3.00.00.008";
163 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
164     $dbh->do("ALTER TABLE `biblio` ADD `datecreated` DATE NOT NULL AFTER `timestamp` ;");
165     $dbh->do("UPDATE biblio SET datecreated=timestamp");
166     print "Upgrade to $DBversion done (biblio creation date)\n";
167     SetVersion ($DBversion);
168 }
169
170 $DBversion = "3.00.00.009";
171 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
172
173     # Create backups of call number columns
174     # in case default migration needs to be customized
175     #
176     # UPGRADE NOTE: temp_upg_biblioitems_call_num should be dropped
177     #               after call numbers have been transformed to the new structure
178     #
179     # Not bothering to do the same with deletedbiblioitems -- assume
180     # default is good enough.
181     $dbh->do("CREATE TABLE `temp_upg_biblioitems_call_num` AS
182               SELECT `biblioitemnumber`, `biblionumber`,
183                      `classification`, `dewey`, `subclass`,
184                      `lcsort`, `ccode`
185               FROM `biblioitems`");
186
187     # biblioitems changes
188     $dbh->do("ALTER TABLE `biblioitems` CHANGE COLUMN `volumeddesc` `volumedesc` TEXT,
189                                     ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
190                                     ADD `cn_class` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
191                                     ADD `cn_item` VARCHAR(10) DEFAULT NULL AFTER `cn_class`,
192                                     ADD `cn_suffix` VARCHAR(10) DEFAULT NULL AFTER `cn_item`,
193                                     ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_suffix`,
194                                     ADD `totalissues` INT(10) AFTER `cn_sort`");
195
196     # default mapping of call number columns:
197     #   cn_class = concatentation of classification + dewey,
198     #              trimmed to fit -- assumes that most users do not
199     #              populate both classification and dewey in a single record
200     #   cn_item  = subclass
201     #   cn_source = left null
202     #   cn_sort = lcsort
203     #
204     # After upgrade, cn_sort will have to be set based on whatever
205     # default call number scheme user sets as a preference.  Misc
206     # script will be added at some point to do that.
207     #
208     $dbh->do("UPDATE `biblioitems`
209               SET cn_class = SUBSTR(TRIM(CONCAT_WS(' ', `classification`, `dewey`)), 1, 30),
210                     cn_item = subclass,
211                     `cn_sort` = `lcsort`
212             ");
213
214     # Now drop the old call number columns
215     $dbh->do("ALTER TABLE `biblioitems` DROP COLUMN `classification`,
216                                         DROP COLUMN `dewey`,
217                                         DROP COLUMN `subclass`,
218                                         DROP COLUMN `lcsort`,
219                                         DROP COLUMN `ccode`");
220
221     # deletedbiblio changes
222     $dbh->do("ALTER TABLE `deletedbiblio` ALTER COLUMN `frameworkcode` SET DEFAULT '',
223                                         DROP COLUMN `marc`,
224                                         ADD `datecreated` DATE NOT NULL AFTER `timestamp`");
225     $dbh->do("UPDATE deletedbiblio SET datecreated = timestamp");
226
227     # deletedbiblioitems changes
228     $dbh->do("ALTER TABLE `deletedbiblioitems`
229                         MODIFY `publicationyear` TEXT,
230                         CHANGE `volumeddesc` `volumedesc` TEXT,
231                         MODIFY `collectiontitle` MEDIUMTEXT DEFAULT NULL AFTER `volumedesc`,
232                         MODIFY `collectionissn` TEXT DEFAULT NULL AFTER `collectiontitle`,
233                         MODIFY `collectionvolume` MEDIUMTEXT DEFAULT NULL AFTER `collectionissn`,
234                         MODIFY `editionstatement` TEXT DEFAULT NULL AFTER `collectionvolume`,
235                         MODIFY `editionresponsibility` TEXT DEFAULT NULL AFTER `editionstatement`,
236                         MODIFY `place` VARCHAR(255) DEFAULT NULL AFTER `size`,
237                         MODIFY `marc` LONGBLOB,
238                         ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `url`,
239                         ADD `cn_class` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
240                         ADD `cn_item` VARCHAR(10) DEFAULT NULL AFTER `cn_class`,
241                         ADD `cn_suffix` VARCHAR(10) DEFAULT NULL AFTER `cn_item`,
242                         ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_suffix`,
243                         ADD `totalissues` INT(10) AFTER `cn_sort`,
244                         ADD `marcxml` LONGTEXT NOT NULL AFTER `totalissues`,
245                         ADD KEY `isbn` (`isbn`),
246                         ADD KEY `publishercode` (`publishercode`)
247                     ");
248
249     $dbh->do("UPDATE `deletedbiblioitems`
250                 SET `cn_class` = SUBSTR(TRIM(CONCAT_WS(' ', `classification`, `dewey`)), 1, 30),
251                `cn_item` = `subclass`,
252                 `cn_sort` = `lcsort`
253             ");
254     $dbh->do("ALTER TABLE `deletedbiblioitems`
255                         DROP COLUMN `classification`,
256                         DROP COLUMN `dewey`,
257                         DROP COLUMN `subclass`,
258                         DROP COLUMN `lcsort`,
259                         DROP COLUMN `ccode`
260             ");
261
262     # deleteditems changes
263     $dbh->do("ALTER TABLE `deleteditems`
264                         MODIFY `barcode` VARCHAR(20) DEFAULT NULL,
265                         MODIFY `price` DECIMAL(8,2) DEFAULT NULL,
266                         MODIFY `replacementprice` DECIMAL(8,2) DEFAULT NULL,
267                         DROP `bulk`,
268                         MODIFY `itemcallnumber` VARCHAR(30) DEFAULT NULL AFTER `wthdrawn`,
269                         MODIFY `holdingbranch` VARCHAR(10) DEFAULT NULL,
270                         DROP `interim`,
271                         MODIFY `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP AFTER `paidfor`,
272                         DROP `cutterextra`,
273                         ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `onloan`,
274                         ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
275                         ADD `ccode` VARCHAR(10) DEFAULT NULL AFTER `cn_sort`,
276                         ADD `materials` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
277                         ADD `uri` VARCHAR(255) DEFAULT NULL AFTER `materials`,
278                         MODIFY `marc` LONGBLOB AFTER `uri`,
279                         DROP KEY `barcode`,
280                         DROP KEY `itembarcodeidx`,
281                         DROP KEY `itembinoidx`,
282                         DROP KEY `itembibnoidx`,
283                         ADD UNIQUE KEY `delitembarcodeidx` (`barcode`),
284                         ADD KEY `delitembinoidx` (`biblioitemnumber`),
285                         ADD KEY `delitembibnoidx` (`biblionumber`),
286                         ADD KEY `delhomebranch` (`homebranch`),
287                         ADD KEY `delholdingbranch` (`holdingbranch`)");
288     $dbh->do("UPDATE deleteditems SET `ccode` = `itype`");
289     $dbh->do("ALTER TABLE deleteditems DROP `itype`");
290     $dbh->do("UPDATE `deleteditems` SET `cn_sort` = `itemcallnumber`");
291
292     # items changes
293     $dbh->do("ALTER TABLE `items` ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `onloan`,
294                                 ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
295                                 ADD `ccode` VARCHAR(10) DEFAULT NULL AFTER `cn_sort`,
296                                 ADD `materials` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
297                                 ADD `uri` VARCHAR(255) DEFAULT NULL AFTER `materials`
298             ");
299     $dbh->do("ALTER TABLE `items`
300                         DROP KEY `itembarcodeidx`,
301                         ADD UNIQUE KEY `itembarcodeidx` (`barcode`)");
302
303     # map items.itype to items.ccode and
304     # set cn_sort to itemcallnumber -- as with biblioitems.cn_sort,
305     # will have to be subsequently updated per user's default
306     # classification scheme
307     $dbh->do("UPDATE `items` SET `cn_sort` = `itemcallnumber`,
308                             `ccode` = `itype`");
309
310     $dbh->do("ALTER TABLE `items` DROP `cutterextra`,
311                                 DROP `itype`");
312
313     print "Upgrade to $DBversion done (major changes to biblio, biblioitems, items, and deleted* versions of same\n";
314     SetVersion ($DBversion);
315 }
316
317 $DBversion = "3.00.00.010";
318 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
319     $dbh->do("CREATE INDEX `userid` ON borrowers (`userid`) ");
320     print "Upgrade to $DBversion done (userid index added)\n";
321     SetVersion ($DBversion);
322 }
323
324 $DBversion = "3.00.00.011";
325 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
326     $dbh->do("ALTER TABLE `branchcategories` CHANGE `categorycode` `categorycode` varchar(10) ");
327     $dbh->do("ALTER TABLE `branchcategories` CHANGE `categoryname` `categoryname` varchar(32) ");
328     $dbh->do("ALTER TABLE `branchcategories` ADD COLUMN `categorytype` varchar(16) ");
329     $dbh->do("UPDATE `branchcategories` SET `categorytype` = 'properties'");
330     $dbh->do("ALTER TABLE `branchrelations` CHANGE `categorycode` `categorycode` varchar(10) ");
331     print "Upgrade to $DBversion done (added branchcategory type)\n";
332     SetVersion ($DBversion);
333 }
334
335 $DBversion = "3.00.00.012";
336 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
337     $dbh->do("CREATE TABLE `class_sort_rules` (
338                                `class_sort_rule` varchar(10) NOT NULL default '',
339                                `description` mediumtext,
340                                `sort_routine` varchar(30) NOT NULL default '',
341                                PRIMARY KEY (`class_sort_rule`),
342                                UNIQUE KEY `class_sort_rule_idx` (`class_sort_rule`)
343                              ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
344     $dbh->do("CREATE TABLE `class_sources` (
345                                `cn_source` varchar(10) NOT NULL default '',
346                                `description` mediumtext,
347                                `used` tinyint(4) NOT NULL default 0,
348                                `class_sort_rule` varchar(10) NOT NULL default '',
349                                PRIMARY KEY (`cn_source`),
350                                UNIQUE KEY `cn_source_idx` (`cn_source`),
351                                KEY `used_idx` (`used`),
352                                CONSTRAINT `class_source_ibfk_1` FOREIGN KEY (`class_sort_rule`)
353                                           REFERENCES `class_sort_rules` (`class_sort_rule`)
354                              ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
355     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type)
356               VALUES('DefaultClassificationSource','ddc',
357                      'Default classification scheme used by the collection. E.g., Dewey, LCC, etc.', NULL,'free')");
358     $dbh->do("INSERT INTO `class_sort_rules` (`class_sort_rule`, `description`, `sort_routine`) VALUES
359                                ('dewey', 'Default filing rules for DDC', 'Dewey'),
360                                ('lcc', 'Default filing rules for LCC', 'LCC'),
361                                ('generic', 'Generic call number filing rules', 'Generic')");
362     $dbh->do("INSERT INTO `class_sources` (`cn_source`, `description`, `used`, `class_sort_rule`) VALUES
363                             ('ddc', 'Dewey Decimal Classification', 1, 'dewey'),
364                             ('lcc', 'Library of Congress Classification', 1, 'lcc'),
365                             ('udc', 'Universal Decimal Classification', 0, 'generic'),
366                             ('sudocs', 'SuDoc Classification (U.S. GPO)', 0, 'generic'),
367                             ('z', 'Other/Generic Classification Scheme', 0, 'generic')");
368     print "Upgrade to $DBversion done (classification sources added)\n";
369     SetVersion ($DBversion);
370 }
371
372 $DBversion = "3.00.00.013";
373 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
374     $dbh->do("CREATE TABLE `import_batches` (
375               `import_batch_id` int(11) NOT NULL auto_increment,
376               `template_id` int(11) default NULL,
377               `branchcode` varchar(10) default NULL,
378               `num_biblios` int(11) NOT NULL default 0,
379               `num_items` int(11) NOT NULL default 0,
380               `upload_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
381               `overlay_action` enum('replace', 'create_new', 'use_template') NOT NULL default 'create_new',
382               `import_status` enum('staging', 'staged', 'importing', 'imported', 'reverting', 'reverted', 'cleaned') NOT NULL default 'staging',
383               `batch_type` enum('batch', 'z3950') NOT NULL default 'batch',
384               `file_name` varchar(100),
385               `comments` mediumtext,
386               PRIMARY KEY (`import_batch_id`),
387               KEY `branchcode` (`branchcode`)
388               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
389     $dbh->do("CREATE TABLE `import_records` (
390               `import_record_id` int(11) NOT NULL auto_increment,
391               `import_batch_id` int(11) NOT NULL,
392               `branchcode` varchar(10) default NULL,
393               `record_sequence` int(11) NOT NULL default 0,
394               `upload_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
395               `import_date` DATE default NULL,
396               `marc` longblob NOT NULL,
397               `marcxml` longtext NOT NULL,
398               `marcxml_old` longtext NOT NULL,
399               `record_type` enum('biblio', 'auth', 'holdings') NOT NULL default 'biblio',
400               `overlay_status` enum('no_match', 'auto_match', 'manual_match', 'match_applied') NOT NULL default 'no_match',
401               `status` enum('error', 'staged', 'imported', 'reverted', 'items_reverted') NOT NULL default 'staged',
402               `import_error` mediumtext,
403               `encoding` varchar(40) NOT NULL default '',
404               `z3950random` varchar(40) default NULL,
405               PRIMARY KEY (`import_record_id`),
406               CONSTRAINT `import_records_ifbk_1` FOREIGN KEY (`import_batch_id`)
407                           REFERENCES `import_batches` (`import_batch_id`) ON DELETE CASCADE ON UPDATE CASCADE,
408               KEY `branchcode` (`branchcode`),
409               KEY `batch_sequence` (`import_batch_id`, `record_sequence`)
410               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
411     $dbh->do("CREATE TABLE `import_record_matches` (
412               `import_record_id` int(11) NOT NULL,
413               `candidate_match_id` int(11) NOT NULL,
414               `score` int(11) NOT NULL default 0,
415               CONSTRAINT `import_record_matches_ibfk_1` FOREIGN KEY (`import_record_id`)
416                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
417               KEY `record_score` (`import_record_id`, `score`)
418               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
419     $dbh->do("CREATE TABLE `import_biblios` (
420               `import_record_id` int(11) NOT NULL,
421               `matched_biblionumber` int(11) default NULL,
422               `control_number` varchar(25) default NULL,
423               `original_source` varchar(25) default NULL,
424               `title` varchar(128) default NULL,
425               `author` varchar(80) default NULL,
426               `isbn` varchar(14) default NULL,
427               `issn` varchar(9) default NULL,
428               `has_items` tinyint(1) NOT NULL default 0,
429               CONSTRAINT `import_biblios_ibfk_1` FOREIGN KEY (`import_record_id`)
430                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
431               KEY `matched_biblionumber` (`matched_biblionumber`),
432               KEY `title` (`title`),
433               KEY `isbn` (`isbn`)
434               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
435     $dbh->do("CREATE TABLE `import_items` (
436               `import_items_id` int(11) NOT NULL auto_increment,
437               `import_record_id` int(11) NOT NULL,
438               `itemnumber` int(11) default NULL,
439               `branchcode` varchar(10) default NULL,
440               `status` enum('error', 'staged', 'imported', 'reverted') NOT NULL default 'staged',
441               `marcxml` longtext NOT NULL,
442               `import_error` mediumtext,
443               PRIMARY KEY (`import_items_id`),
444               CONSTRAINT `import_items_ibfk_1` FOREIGN KEY (`import_record_id`)
445                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
446               KEY `itemnumber` (`itemnumber`),
447               KEY `branchcode` (`branchcode`)
448               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
449
450     $dbh->do("INSERT INTO `import_batches`
451                 (`overlay_action`, `import_status`, `batch_type`, `file_name`)
452               SELECT distinct 'create_new', 'staged', 'z3950', `file`
453               FROM   `marc_breeding`");
454
455     $dbh->do("INSERT INTO `import_records`
456                 (`import_batch_id`, `import_record_id`, `record_sequence`, `marc`, `record_type`, `status`,
457                 `encoding`, `z3950random`, `marcxml`, `marcxml_old`)
458               SELECT `import_batch_id`, `id`, 1, `marc`, 'biblio', 'staged', `encoding`, `z3950random`, '', ''
459               FROM `marc_breeding`
460               JOIN `import_batches` ON (`file_name` = `file`)");
461
462     $dbh->do("INSERT INTO `import_biblios`
463                 (`import_record_id`, `title`, `author`, `isbn`)
464               SELECT `import_record_id`, `title`, `author`, `isbn`
465               FROM   `marc_breeding`
466               JOIN   `import_records` ON (`import_record_id` = `id`)");
467
468     $dbh->do("UPDATE `import_batches`
469               SET `num_biblios` = (
470               SELECT COUNT(*)
471               FROM `import_records`
472               WHERE `import_batch_id` = `import_batches`.`import_batch_id`
473               )");
474
475     $dbh->do("DROP TABLE `marc_breeding`");
476
477     print "Upgrade to $DBversion done (import_batches et al. added)\n";
478     SetVersion ($DBversion);
479 }
480
481 $DBversion = "3.00.00.014";
482 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
483     $dbh->do("ALTER TABLE subscription ADD lastbranch VARCHAR(4)");
484     print "Upgrade to $DBversion done (userid index added)\n";
485     SetVersion ($DBversion);
486 }
487
488 $DBversion = "3.00.00.015";
489 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
490     $dbh->do("CREATE TABLE `saved_sql` (
491            `id` int(11) NOT NULL auto_increment,
492            `borrowernumber` int(11) default NULL,
493            `date_created` datetime default NULL,
494            `last_modified` datetime default NULL,
495            `savedsql` text,
496            `last_run` datetime default NULL,
497            `report_name` varchar(255) default NULL,
498            `type` varchar(255) default NULL,
499            `notes` text,
500            PRIMARY KEY  (`id`),
501            KEY boridx (`borrowernumber`)
502         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
503     $dbh->do("CREATE TABLE `saved_reports` (
504            `id` int(11) NOT NULL auto_increment,
505            `report_id` int(11) default NULL,
506            `report` longtext,
507            `date_run` datetime default NULL,
508            PRIMARY KEY  (`id`)
509         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
510     print "Upgrade to $DBversion done (saved_sql and saved_reports added)\n";
511     SetVersion ($DBversion);
512 }
513
514 $DBversion = "3.00.00.016";
515 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
516     $dbh->do(" CREATE TABLE reports_dictionary (
517           id int(11) NOT NULL auto_increment,
518           name varchar(255) default NULL,
519           description text,
520           date_created datetime default NULL,
521           date_modified datetime default NULL,
522           saved_sql text,
523           area int(11) default NULL,
524           PRIMARY KEY  (id)
525         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
526     print "Upgrade to $DBversion done (reports_dictionary) added)\n";
527     SetVersion ($DBversion);
528 }
529
530 $DBversion = "3.00.00.017";
531 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
532     $dbh->do("ALTER TABLE action_logs DROP PRIMARY KEY");
533     $dbh->do("ALTER TABLE action_logs ADD KEY  timestamp (timestamp,user)");
534     $dbh->do("ALTER TABLE action_logs ADD action_id INT(11) NOT NULL FIRST");
535     $dbh->do("UPDATE action_logs SET action_id = if (\@a, \@a:=\@a+1, \@a:=1)");
536     $dbh->do("ALTER TABLE action_logs MODIFY action_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY");
537     print "Upgrade to $DBversion done (added column to action_logs)\n";
538     SetVersion ($DBversion);
539 }
540
541 $DBversion = "3.00.00.018";
542 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
543     $dbh->do("ALTER TABLE `zebraqueue`
544                     ADD `done` INT NOT NULL DEFAULT '0',
545                     ADD `time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ;
546             ");
547     print "Upgrade to $DBversion done (adding timestamp and done columns to zebraque table to improve problem tracking) added)\n";
548     SetVersion ($DBversion);
549 }
550
551 $DBversion = "3.00.00.019";
552 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
553     $dbh->do("ALTER TABLE biblio MODIFY biblionumber INT(11) NOT NULL AUTO_INCREMENT");
554     $dbh->do("ALTER TABLE biblioitems MODIFY biblioitemnumber INT(11) NOT NULL AUTO_INCREMENT");
555     $dbh->do("ALTER TABLE items MODIFY itemnumber INT(11) NOT NULL AUTO_INCREMENT");
556     print "Upgrade to $DBversion done (made bib/item PKs auto_increment)\n";
557     SetVersion ($DBversion);
558 }
559
560 $DBversion = "3.00.00.020";
561 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
562     $dbh->do("ALTER TABLE deleteditems
563               DROP KEY `delitembarcodeidx`,
564               ADD KEY `delitembarcodeidx` (`barcode`)");
565     print "Upgrade to $DBversion done (dropped uniqueness of key on deleteditems.barcode)\n";
566     SetVersion ($DBversion);
567 }
568
569 $DBversion = "3.00.00.021";
570 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
571     $dbh->do("ALTER TABLE items CHANGE homebranch homebranch VARCHAR(10)");
572     $dbh->do("ALTER TABLE deleteditems CHANGE homebranch homebranch VARCHAR(10)");
573     $dbh->do("ALTER TABLE statistics CHANGE branch branch VARCHAR(10)");
574     $dbh->do("ALTER TABLE subscription CHANGE lastbranch lastbranch VARCHAR(10)");
575     print "Upgrade to $DBversion done (extended missed branchcode columns to 10 chars)\n";
576     SetVersion ($DBversion);
577 }
578
579 $DBversion = "3.00.00.022";
580 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
581     $dbh->do("ALTER TABLE items
582                 ADD `damaged` tinyint(1) default NULL AFTER notforloan");
583     $dbh->do("ALTER TABLE deleteditems
584                 ADD `damaged` tinyint(1) default NULL AFTER notforloan");
585     print "Upgrade to $DBversion done (adding damaged column to items table)\n";
586     SetVersion ($DBversion);
587 }
588
589 $DBversion = "3.00.00.023";
590 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
591      $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
592          VALUES ('yuipath','http://yui.yahooapis.com/2.3.1/build','Insert the path to YUI libraries','','free')");
593     print "Upgrade to $DBversion done (adding new system preference for controlling YUI path)\n";
594     SetVersion ($DBversion);
595 }
596 $DBversion = "3.00.00.024";
597 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
598     $dbh->do("ALTER TABLE biblioitems CHANGE  itemtype itemtype VARCHAR(10)");
599     print "Upgrade to $DBversion done (changing itemtype to (10))\n";
600     SetVersion ($DBversion);
601 }
602
603 $DBversion = "3.00.00.025";
604 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
605     $dbh->do("ALTER TABLE items ADD COLUMN itype VARCHAR(10)");
606     $dbh->do("ALTER TABLE deleteditems ADD COLUMN itype VARCHAR(10) AFTER uri");
607     if(C4::Context->preference('item-level_itypes')){
608         $dbh->do('update items,biblioitems set items.itype=biblioitems.itemtype where items.biblionumber=biblioitems.biblionumber and itype is null');
609     }
610     print "Upgrade to $DBversion done (reintroduce items.itype - fill from itemtype)\n ";
611     SetVersion ($DBversion);
612 }
613
614 $DBversion = "3.00.00.026";
615 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
616     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
617        VALUES ('HomeOrHoldingBranch','homebranch','homebranch|holdingbranch','With independent branches turned on this decides whether to check the items holdingbranch or homebranch at circulatilon','choice')");
618     print "Upgrade to $DBversion done (adding new system preference for choosing whether homebranch or holdingbranch is checked in circulation)\n";
619     SetVersion ($DBversion);
620 }
621
622 $DBversion = "3.00.00.027";
623 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
624     $dbh->do("CREATE TABLE `marc_matchers` (
625                 `matcher_id` int(11) NOT NULL auto_increment,
626                 `code` varchar(10) NOT NULL default '',
627                 `description` varchar(255) NOT NULL default '',
628                 `record_type` varchar(10) NOT NULL default 'biblio',
629                 `threshold` int(11) NOT NULL default 0,
630                 PRIMARY KEY (`matcher_id`),
631                 KEY `code` (`code`),
632                 KEY `record_type` (`record_type`)
633               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
634     $dbh->do("CREATE TABLE `matchpoints` (
635                 `matcher_id` int(11) NOT NULL,
636                 `matchpoint_id` int(11) NOT NULL auto_increment,
637                 `search_index` varchar(30) NOT NULL default '',
638                 `score` int(11) NOT NULL default 0,
639                 PRIMARY KEY (`matchpoint_id`),
640                 CONSTRAINT `matchpoints_ifbk_1` FOREIGN KEY (`matcher_id`)
641                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE
642               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
643     $dbh->do("CREATE TABLE `matchpoint_components` (
644                 `matchpoint_id` int(11) NOT NULL,
645                 `matchpoint_component_id` int(11) NOT NULL auto_increment,
646                 sequence int(11) NOT NULL default 0,
647                 tag varchar(3) NOT NULL default '',
648                 subfields varchar(40) NOT NULL default '',
649                 offset int(4) NOT NULL default 0,
650                 length int(4) NOT NULL default 0,
651                 PRIMARY KEY (`matchpoint_component_id`),
652                 KEY `by_sequence` (`matchpoint_id`, `sequence`),
653                 CONSTRAINT `matchpoint_components_ifbk_1` FOREIGN KEY (`matchpoint_id`)
654                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
655               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
656     $dbh->do("CREATE TABLE `matchpoint_component_norms` (
657                 `matchpoint_component_id` int(11) NOT NULL,
658                 `sequence`  int(11) NOT NULL default 0,
659                 `norm_routine` varchar(50) NOT NULL default '',
660                 KEY `matchpoint_component_norms` (`matchpoint_component_id`, `sequence`),
661                 CONSTRAINT `matchpoint_component_norms_ifbk_1` FOREIGN KEY (`matchpoint_component_id`)
662                            REFERENCES `matchpoint_components` (`matchpoint_component_id`) ON DELETE CASCADE ON UPDATE CASCADE
663               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
664     $dbh->do("CREATE TABLE `matcher_matchpoints` (
665                 `matcher_id` int(11) NOT NULL,
666                 `matchpoint_id` int(11) NOT NULL,
667                 CONSTRAINT `matcher_matchpoints_ifbk_1` FOREIGN KEY (`matcher_id`)
668                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE,
669                 CONSTRAINT `matcher_matchpoints_ifbk_2` FOREIGN KEY (`matchpoint_id`)
670                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
671               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
672     $dbh->do("CREATE TABLE `matchchecks` (
673                 `matcher_id` int(11) NOT NULL,
674                 `matchcheck_id` int(11) NOT NULL auto_increment,
675                 `source_matchpoint_id` int(11) NOT NULL,
676                 `target_matchpoint_id` int(11) NOT NULL,
677                 PRIMARY KEY (`matchcheck_id`),
678                 CONSTRAINT `matcher_matchchecks_ifbk_1` FOREIGN KEY (`matcher_id`)
679                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE,
680                 CONSTRAINT `matcher_matchchecks_ifbk_2` FOREIGN KEY (`source_matchpoint_id`)
681                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE,
682                 CONSTRAINT `matcher_matchchecks_ifbk_3` FOREIGN KEY (`target_matchpoint_id`)
683                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
684               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
685     print "Upgrade to $DBversion done (added C4::Matcher serialization tables)\n ";
686     SetVersion ($DBversion);
687 }
688
689 $DBversion = "3.00.00.028";
690 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
691     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
692        VALUES ('canreservefromotherbranches','1','','With Independent branches on, can a user from one library reserve an item from another library','YesNo')");
693     print "Upgrade to $DBversion done (adding new system preference for changing reserve/holds behaviour with independent branches)\n";
694     SetVersion ($DBversion);
695 }
696
697
698 $DBversion = "3.00.00.029";
699 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
700     $dbh->do("ALTER TABLE `import_batches` ADD `matcher_id` int(11) NULL AFTER `import_batch_id`");
701     print "Upgrade to $DBversion done (adding matcher_id to import_batches)\n";
702     SetVersion ($DBversion);
703 }
704
705 $DBversion = "3.00.00.030";
706 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
707     $dbh->do("
708 CREATE TABLE services_throttle (
709   service_type varchar(10) NOT NULL default '',
710   service_count varchar(45) default NULL,
711   PRIMARY KEY  (service_type)
712 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
713 ");
714     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
715        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')");
716  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
717        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')");
718  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
719        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')");
720  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
721        VALUES ('XISBNDailyLimit',499,'','The xISBN Web service is free for non-commercial use when usage does not exceed 500 requests per day','free')");
722  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
723        VALUES ('PINESISBN',0,'','Use with FRBRizeEditions. If ON, Koha will use PINES OISBN web service in the Editions tab on the detail pages.','YesNo')");
724  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
725        VALUES ('ThingISBN',0,'','Use with FRBRizeEditions. If ON, Koha will use the ThingISBN web service in the Editions tab on the detail pages.','YesNo')");
726     print "Upgrade to $DBversion done (adding services throttle table and sysprefs for xISBN)\n";
727     SetVersion ($DBversion);
728 }
729
730 $DBversion = "3.00.00.031";
731 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
732
733 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryStemming',1,'If ON, enables query stemming',NULL,'YesNo')");
734 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryFuzzy',1,'If ON, enables fuzzy option for searches',NULL,'YesNo')");
735 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryWeightFields',1,'If ON, enables field weighting',NULL,'YesNo')");
736 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('WebBasedSelfCheck',0,'If ON, enables the web-based self-check system',NULL,'YesNo')");
737 $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')");
738 $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')");
739 $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')");
740 $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')");
741 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('defaultSortOrder',NULL,'Specify the default sort order','asc|dsc|az|za','Choice')");
742 $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')");
743 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACdefaultSortOrder',NULL,'Specify the default sort order','asc|dsc|za|az','Choice')");
744 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('staffClientBaseURL','','Specify the base URL of the staff client',NULL,'free')");
745 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('minPasswordLength',3,'Specify the minimum length of a patron/staff password',NULL,'free')");
746 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('noItemTypeImages',0,'If ON, disables item-type images',NULL,'YesNo')");
747 $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')");
748 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('holdCancelLength','','Specify how many days before a hold is canceled',NULL,'free')");
749 $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')");
750 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('finesMode','test','Choose the fines mode, test or production','test|production','Choice')");
751 $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')");
752 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('itemBarcodeInputFilter','','If set, allows specification of a item barcode input filter','cuecat','Choice')");
753 $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')");
754 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('URLLinkText','','Text to display as the link anchor in the OPAC',NULL,'free')");
755 $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')");
756 $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')");
757 $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')");
758 $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')");
759 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACUserCSS',0,'Add CSS to be included in the OPAC',NULL,'free')");
760
761     print "Upgrade to $DBversion done (adding additional system preference)\n";
762     SetVersion ($DBversion);
763 }
764
765 $DBversion = "3.00.00.032";
766 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
767     $dbh->do("UPDATE `marc_subfield_structure` SET `kohafield` = 'items.wthdrawn' WHERE `kohafield` = 'items.withdrawn'");
768     print "Upgrade to $DBversion done (fixed MARC framework references to items.withdrawn)\n";
769     SetVersion ($DBversion);
770 }
771
772 $DBversion = "3.00.00.033";
773 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
774     $dbh->do("INSERT INTO `userflags` VALUES(17,'staffaccess','Modify login / permissions for staff users',0)");
775     print "Upgrade to $DBversion done (Adding permissions flag for staff member access modification.  )\n";
776     SetVersion ($DBversion);
777 }
778
779 $DBversion = "3.00.00.034";
780 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
781     $dbh->do("ALTER TABLE `virtualshelves` ADD COLUMN `sortfield` VARCHAR(16) ");
782     print "Upgrade to $DBversion done (Adding sortfield for Virtual Shelves.  )\n";
783     SetVersion ($DBversion);
784 }
785
786 $DBversion = "3.00.00.035";
787 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
788     $dbh->do("UPDATE marc_subfield_structure
789               SET authorised_value = 'cn_source'
790               WHERE kohafield IN ('items.cn_source', 'biblioitems.cn_source')
791               AND (authorised_value is NULL OR authorised_value = '')");
792     print "Upgrade to $DBversion done (MARC frameworks: make classification source a drop-down)\n";
793     SetVersion ($DBversion);
794 }
795
796 $DBversion = "3.00.00.036";
797 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
798     $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');");
799     print "Upgrade to $DBversion done (OPACItemsResultsDisplay systempreference added)\n";
800     SetVersion ($DBversion);
801 }
802
803 $DBversion = "3.00.00.037";
804 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
805     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactfirstname` varchar(255)");
806     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactsurname` varchar(255)");
807     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress1` varchar(255)");
808     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress2` varchar(255)");
809     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress3` varchar(255)");
810     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactzipcode` varchar(50)");
811     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactphone` varchar(50)");
812     print "Upgrade to $DBversion done (Adding Alternative Contact Person information to borrowers table)\n";
813     SetVersion ($DBversion);
814 }
815
816 $DBversion = "3.00.00.038";
817 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
818     $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'");
819     $dbh->do("DELETE FROM `systempreferences` WHERE variable='hideBiblioNumber'");
820     print "Upgrade to $DBversion done ('alter finesMode systempreference, remove superfluous syspref.')\n";
821     SetVersion ($DBversion);
822 }
823
824 $DBversion = "3.00.00.039";
825 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
826     $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')");
827     $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')");
828     $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')");
829     # $dbh->do("DELETE FROM `systempreferences` WHERE variable='HomeOrHoldingBranch'"); # Bug #2752
830     print "Upgrade to $DBversion done ('add circ sysprefs CircControl, finesCalendar, and uppercasesurnames, and delete HomeOrHoldingBranch.')\n";
831     SetVersion ($DBversion);
832 }
833
834 $DBversion = "3.00.00.040";
835 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
836         $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')");
837         $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')");
838         print "Upgrade to $DBversion done ('add circ sysprefs todaysIssuesDefaultSortOrder and previousIssuesDefaultSortOrder.')\n";
839     SetVersion ($DBversion);
840 }
841
842
843 $DBversion = "3.00.00.041";
844 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
845     # Strictly speaking it is not necessary to explicitly change
846     # NULL values to 0, because the ALTER TABLE statement will do that.
847     # However, setting them first avoids a warning.
848     $dbh->do("UPDATE items SET notforloan = 0 WHERE notforloan IS NULL");
849     $dbh->do("UPDATE items SET damaged = 0 WHERE damaged IS NULL");
850     $dbh->do("UPDATE items SET itemlost = 0 WHERE itemlost IS NULL");
851     $dbh->do("UPDATE items SET wthdrawn = 0 WHERE wthdrawn IS NULL");
852     $dbh->do("ALTER TABLE items
853                 MODIFY notforloan tinyint(1) NOT NULL default 0,
854                 MODIFY damaged    tinyint(1) NOT NULL default 0,
855                 MODIFY itemlost   tinyint(1) NOT NULL default 0,
856                 MODIFY wthdrawn   tinyint(1) NOT NULL default 0");
857     $dbh->do("UPDATE deleteditems SET notforloan = 0 WHERE notforloan IS NULL");
858     $dbh->do("UPDATE deleteditems SET damaged = 0 WHERE damaged IS NULL");
859     $dbh->do("UPDATE deleteditems SET itemlost = 0 WHERE itemlost IS NULL");
860     $dbh->do("UPDATE deleteditems SET wthdrawn = 0 WHERE wthdrawn IS NULL");
861     $dbh->do("ALTER TABLE deleteditems
862                 MODIFY notforloan tinyint(1) NOT NULL default 0,
863                 MODIFY damaged    tinyint(1) NOT NULL default 0,
864                 MODIFY itemlost   tinyint(1) NOT NULL default 0,
865                 MODIFY wthdrawn   tinyint(1) NOT NULL default 0");
866         print "Upgrade to $DBversion done (disallow NULL in several item status columns)\n";
867     SetVersion ($DBversion);
868 }
869
870 $DBversion = "3.00.00.04";
871 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
872     $dbh->do("ALTER TABLE aqbooksellers CHANGE name name mediumtext NOT NULL");
873         print "Upgrade to $DBversion done (disallow NULL in aqbooksellers.name; part of fix for bug 1251)\n";
874     SetVersion ($DBversion);
875 }
876
877 $DBversion = "3.00.00.043";
878 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
879     $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");
880         print "Upgrade to $DBversion done (currency table: add symbol and timestamp columns)\n";
881     SetVersion ($DBversion);
882 }
883
884 $DBversion = "3.00.00.044";
885 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
886     $dbh->do("ALTER TABLE deletedborrowers
887   ADD `altcontactfirstname` varchar(255) default NULL,
888   ADD `altcontactsurname` varchar(255) default NULL,
889   ADD `altcontactaddress1` varchar(255) default NULL,
890   ADD `altcontactaddress2` varchar(255) default NULL,
891   ADD `altcontactaddress3` varchar(255) default NULL,
892   ADD `altcontactzipcode` varchar(50) default NULL,
893   ADD `altcontactphone` varchar(50) default NULL
894   ");
895   $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES
896 ('OPACBaseURL',NULL,'Specify the Base URL of the OPAC, e.g., opac.mylibrary.com, the http:// will be added automatically by Koha.',NULL,'Free'),
897 ('language','en','Set the default language in the staff client.',NULL,'Languages'),
898 ('QueryAutoTruncate',1,'If ON, query truncation is enabled by default',NULL,'YesNo'),
899 ('QueryRemoveStopwords',0,'If ON, stopwords listed in the Administration area will be removed from queries',NULL,'YesNo')
900   ");
901         print "Upgrade to $DBversion done (syncing deletedborrowers table with borrowers table)\n";
902     SetVersion ($DBversion);
903 }
904
905 #-- http://www.w3.org/International/articles/language-tags/
906
907 #-- RFC4646
908 $DBversion = "3.00.00.045";
909 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
910     $dbh->do("
911 CREATE TABLE language_subtag_registry (
912         subtag varchar(25),
913         type varchar(25), -- language-script-region-variant-extension-privateuse
914         description varchar(25), -- only one of the possible descriptions for ease of reference, see language_descriptions for the complete list
915         added date,
916         KEY `subtag` (`subtag`)
917 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
918
919 #-- TODO: add suppress_scripts
920 #-- this maps three letter codes defined in iso639.2 back to their
921 #-- two letter equivilents in rfc4646 (LOC maintains iso639+)
922  $dbh->do("CREATE TABLE language_rfc4646_to_iso639 (
923         rfc4646_subtag varchar(25),
924         iso639_2_code varchar(25),
925         KEY `rfc4646_subtag` (`rfc4646_subtag`)
926 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
927
928  $dbh->do("CREATE TABLE language_descriptions (
929         subtag varchar(25),
930         type varchar(25),
931         lang varchar(25),
932         description varchar(255),
933         KEY `lang` (`lang`)
934 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
935
936 #-- bi-directional support, keyed by script subcode
937  $dbh->do("CREATE TABLE language_script_bidi (
938         rfc4646_subtag varchar(25), -- script subtag, Arab, Hebr, etc.
939         bidi varchar(3), -- rtl ltr
940         KEY `rfc4646_subtag` (`rfc4646_subtag`)
941 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
942
943 #-- BIDI Stuff, Arabic and Hebrew
944  $dbh->do("INSERT INTO language_script_bidi(rfc4646_subtag,bidi)
945 VALUES( 'Arab', 'rtl')");
946  $dbh->do("INSERT INTO language_script_bidi(rfc4646_subtag,bidi)
947 VALUES( 'Hebr', 'rtl')");
948
949 #-- TODO: need to map language subtags to script subtags for detection
950 #-- of bidi when script is not specified (like ar, he)
951  $dbh->do("CREATE TABLE language_script_mapping (
952         language_subtag varchar(25),
953         script_subtag varchar(25),
954         KEY `language_subtag` (`language_subtag`)
955 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
956
957 #-- Default mappings between script and language subcodes
958  $dbh->do("INSERT INTO language_script_mapping(language_subtag,script_subtag)
959 VALUES( 'ar', 'Arab')");
960  $dbh->do("INSERT INTO language_script_mapping(language_subtag,script_subtag)
961 VALUES( 'he', 'Hebr')");
962
963         print "Upgrade to $DBversion done (adding language subtag registry and basic BiDi support NOTE: You should import the subtag registry SQL)\n";
964     SetVersion ($DBversion);
965 }
966
967 $DBversion = "3.00.00.046";
968 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
969     $dbh->do("ALTER TABLE `subscription` CHANGE `numberlength` `numberlength` int(11) default '0' ,
970                  CHANGE `weeklength` `weeklength` int(11) default '0'");
971     $dbh->do("CREATE TABLE `serialitems` (`serialid` int(11) NOT NULL, `itemnumber` int(11) NOT NULL, UNIQUE KEY `serialididx` (`serialid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
972     $dbh->do("INSERT INTO `serialitems` SELECT `serialid`,`itemnumber` from serial where NOT ISNULL(itemnumber) && itemnumber <> '' && itemnumber NOT LIKE '%,%'");
973         print "Upgrade to $DBversion done (Add serialitems table to link serial issues to items. )\n";
974     SetVersion ($DBversion);
975 }
976
977 $DBversion = "3.00.00.047";
978 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
979     $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');");
980         print "Upgrade to $DBversion done ( Added OpacRenewalAllowed syspref )\n";
981     SetVersion ($DBversion);
982 }
983
984 $DBversion = "3.00.00.048";
985 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
986     $dbh->do("ALTER TABLE `items` ADD `more_subfields_xml` longtext default NULL AFTER `itype`");
987         print "Upgrade to $DBversion done (added items.more_subfields_xml)\n";
988     SetVersion ($DBversion);
989 }
990
991 $DBversion = "3.00.00.049";
992 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
993         $dbh->do("ALTER TABLE `z3950servers` ADD `encoding` text default NULL AFTER type ");
994         print "Upgrade to $DBversion done ( Added encoding field to z3950servers table )\n";
995     SetVersion ($DBversion);
996 }
997
998 $DBversion = "3.00.00.050";
999 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1000     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacHighlightedWords','0','If Set, query matched terms are highlighted in OPAC',NULL,'YesNo');");
1001         print "Upgrade to $DBversion done ( Added OpacHighlightedWords syspref )\n";
1002     SetVersion ($DBversion);
1003 }
1004
1005 $DBversion = "3.00.00.051";
1006 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1007     $dbh->do("UPDATE systempreferences SET explanation = 'Define the current theme for the OPAC interface.' WHERE variable = 'opacthemes';");
1008         print "Upgrade to $DBversion done ( Corrected opacthemes explanation. )\n";
1009     SetVersion ($DBversion);
1010 }
1011
1012 $DBversion = "3.00.00.052";
1013 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1014     $dbh->do("ALTER TABLE `deleteditems` ADD `more_subfields_xml` LONGTEXT DEFAULT NULL AFTER `itype`");
1015         print "Upgrade to $DBversion done ( Adding missing column to deleteditems table. )\n";
1016     SetVersion ($DBversion);
1017 }
1018
1019 $DBversion = "3.00.00.053";
1020 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1021     $dbh->do("CREATE TABLE `printers_profile` (
1022             `prof_id` int(4) NOT NULL auto_increment,
1023             `printername` varchar(40) NOT NULL,
1024             `tmpl_id` int(4) NOT NULL,
1025             `paper_bin` varchar(20) NOT NULL,
1026             `offset_horz` float default NULL,
1027             `offset_vert` float default NULL,
1028             `creep_horz` float default NULL,
1029             `creep_vert` float default NULL,
1030             `unit` char(20) NOT NULL default 'POINT',
1031             PRIMARY KEY  (`prof_id`),
1032             UNIQUE KEY `printername` (`printername`,`tmpl_id`,`paper_bin`),
1033             CONSTRAINT `printers_profile_pnfk_1` FOREIGN KEY (`tmpl_id`) REFERENCES `labels_templates` (`tmpl_id`) ON DELETE CASCADE ON UPDATE CASCADE
1034             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1035     $dbh->do("CREATE TABLE `labels_profile` (
1036             `tmpl_id` int(4) NOT NULL,
1037             `prof_id` int(4) NOT NULL,
1038             UNIQUE KEY `tmpl_id` (`tmpl_id`),
1039             UNIQUE KEY `prof_id` (`prof_id`)
1040             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1041     print "Upgrade to $DBversion done ( Printer Profile tables added )\n";
1042     SetVersion ($DBversion);
1043 }
1044
1045 $DBversion = "3.00.00.054";
1046 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1047     $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';");
1048         print "Upgrade to $DBversion done ( Added another barcode autogeneration sequence to barcode.pl. )\n";
1049     SetVersion ($DBversion);
1050 }
1051
1052 $DBversion = "3.00.00.055";
1053 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1054     $dbh->do("ALTER TABLE `zebraqueue` ADD KEY `zebraqueue_lookup` (`server`, `biblio_auth_number`, `operation`, `done`)");
1055         print "Upgrade to $DBversion done ( Added index on zebraqueue. )\n";
1056     SetVersion ($DBversion);
1057 }
1058 $DBversion = "3.00.00.056";
1059 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1060     if (C4::Context->preference("marcflavour") eq 'UNIMARC') {
1061         $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) ");
1062     } else {
1063         $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) ");
1064     }
1065     $dbh->do("ALTER TABLE `items` ADD `enumchron` VARCHAR(80) DEFAULT NULL;");
1066     print "Upgrade to $DBversion done ( Added item.enumchron column, and framework map to 952h )\n";
1067     SetVersion ($DBversion);
1068 }
1069
1070 $DBversion = "3.00.00.057";
1071 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1072     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH','0','if ON, OAI-PMH server is enabled',NULL,'YesNo');");
1073     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH:archiveID','KOHA-OAI-TEST','OAI-PMH archive identification',NULL,'Free');");
1074     $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');");
1075     $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');");
1076     $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');");
1077     SetVersion ($DBversion);
1078 }
1079
1080 $DBversion = "3.00.00.058";
1081 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1082     $dbh->do("ALTER TABLE `opac_news`
1083                 CHANGE `lang` `lang` VARCHAR( 25 )
1084                 CHARACTER SET utf8
1085                 COLLATE utf8_general_ci
1086                 NOT NULL default ''");
1087         print "Upgrade to $DBversion done ( lang field in opac_news made longer )\n";
1088     SetVersion ($DBversion);
1089 }
1090
1091 $DBversion = "3.00.00.059";
1092 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1093
1094     $dbh->do("CREATE TABLE IF NOT EXISTS `labels_templates` (
1095             `tmpl_id` int(4) NOT NULL auto_increment,
1096             `tmpl_code` char(100)  default '',
1097             `tmpl_desc` char(100) default '',
1098             `page_width` float default '0',
1099             `page_height` float default '0',
1100             `label_width` float default '0',
1101             `label_height` float default '0',
1102             `topmargin` float default '0',
1103             `leftmargin` float default '0',
1104             `cols` int(2) default '0',
1105             `rows` int(2) default '0',
1106             `colgap` float default '0',
1107             `rowgap` float default '0',
1108             `active` int(1) default NULL,
1109             `units` char(20)  default 'PX',
1110             `fontsize` int(4) NOT NULL default '3',
1111             PRIMARY KEY  (`tmpl_id`)
1112             ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1113     $dbh->do("CREATE TABLE  IF NOT EXISTS `printers_profile` (
1114             `prof_id` int(4) NOT NULL auto_increment,
1115             `printername` varchar(40) NOT NULL,
1116             `tmpl_id` int(4) NOT NULL,
1117             `paper_bin` varchar(20) NOT NULL,
1118             `offset_horz` float default NULL,
1119             `offset_vert` float default NULL,
1120             `creep_horz` float default NULL,
1121             `creep_vert` float default NULL,
1122             `unit` char(20) NOT NULL default 'POINT',
1123             PRIMARY KEY  (`prof_id`),
1124             UNIQUE KEY `printername` (`printername`,`tmpl_id`,`paper_bin`),
1125             CONSTRAINT `printers_profile_pnfk_1` FOREIGN KEY (`tmpl_id`) REFERENCES `labels_templates` (`tmpl_id`) ON DELETE CASCADE ON UPDATE CASCADE
1126             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1127     print "Upgrade to $DBversion done ( Added labels_templates table if it did not exist. )\n";
1128     SetVersion ($DBversion);
1129 }
1130
1131 $DBversion = "3.00.00.060";
1132 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1133     $dbh->do("CREATE TABLE IF NOT EXISTS `patronimage` (
1134             `cardnumber` varchar(16) NOT NULL,
1135             `mimetype` varchar(15) NOT NULL,
1136             `imagefile` mediumblob NOT NULL,
1137             PRIMARY KEY  (`cardnumber`),
1138             CONSTRAINT `patronimage_fk1` FOREIGN KEY (`cardnumber`) REFERENCES `borrowers` (`cardnumber`) ON DELETE CASCADE ON UPDATE CASCADE
1139             ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1140         print "Upgrade to $DBversion done ( Added patronimage table. )\n";
1141     SetVersion ($DBversion);
1142 }
1143
1144 $DBversion = "3.00.00.061";
1145 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1146     $dbh->do("ALTER TABLE labels_templates ADD COLUMN font char(10) NOT NULL DEFAULT 'TR';");
1147         print "Upgrade to $DBversion done ( Added font column to labels_templates )\n";
1148     SetVersion ($DBversion);
1149 }
1150
1151 $DBversion = "3.00.00.062";
1152 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1153     $dbh->do("CREATE TABLE `old_issues` (
1154                 `borrowernumber` int(11) default NULL,
1155                 `itemnumber` int(11) default NULL,
1156                 `date_due` date default NULL,
1157                 `branchcode` varchar(10) default NULL,
1158                 `issuingbranch` varchar(18) default NULL,
1159                 `returndate` date default NULL,
1160                 `lastreneweddate` date default NULL,
1161                 `return` varchar(4) default NULL,
1162                 `renewals` tinyint(4) default NULL,
1163                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1164                 `issuedate` date default NULL,
1165                 KEY `old_issuesborridx` (`borrowernumber`),
1166                 KEY `old_issuesitemidx` (`itemnumber`),
1167                 KEY `old_bordate` (`borrowernumber`,`timestamp`),
1168                 CONSTRAINT `old_issues_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1169                     ON DELETE SET NULL ON UPDATE SET NULL,
1170                 CONSTRAINT `old_issues_ibfk_2` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`)
1171                     ON DELETE SET NULL ON UPDATE SET NULL
1172                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1173     $dbh->do("CREATE TABLE `old_reserves` (
1174                 `borrowernumber` int(11) default NULL,
1175                 `reservedate` date default NULL,
1176                 `biblionumber` int(11) default NULL,
1177                 `constrainttype` varchar(1) default NULL,
1178                 `branchcode` varchar(10) default NULL,
1179                 `notificationdate` date default NULL,
1180                 `reminderdate` date default NULL,
1181                 `cancellationdate` date default NULL,
1182                 `reservenotes` mediumtext,
1183                 `priority` smallint(6) default NULL,
1184                 `found` varchar(1) default NULL,
1185                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1186                 `itemnumber` int(11) default NULL,
1187                 `waitingdate` date default NULL,
1188                 KEY `old_reserves_borrowernumber` (`borrowernumber`),
1189                 KEY `old_reserves_biblionumber` (`biblionumber`),
1190                 KEY `old_reserves_itemnumber` (`itemnumber`),
1191                 KEY `old_reserves_branchcode` (`branchcode`),
1192                 CONSTRAINT `old_reserves_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1193                     ON DELETE SET NULL ON UPDATE SET NULL,
1194                 CONSTRAINT `old_reserves_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`)
1195                     ON DELETE SET NULL ON UPDATE SET NULL,
1196                 CONSTRAINT `old_reserves_ibfk_3` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`)
1197                     ON DELETE SET NULL ON UPDATE SET NULL
1198                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1199
1200     # move closed transactions to old_* tables
1201     $dbh->do("INSERT INTO old_issues SELECT * FROM issues WHERE returndate IS NOT NULL");
1202     $dbh->do("DELETE FROM issues WHERE returndate IS NOT NULL");
1203     $dbh->do("INSERT INTO old_reserves SELECT * FROM reserves WHERE cancellationdate IS NOT NULL OR found = 'F'");
1204     $dbh->do("DELETE FROM reserves WHERE cancellationdate IS NOT NULL OR found = 'F'");
1205
1206         print "Upgrade to $DBversion done ( Added old_issues and old_reserves tables )\n";
1207     SetVersion ($DBversion);
1208 }
1209
1210 $DBversion = "3.00.00.063";
1211 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1212     $dbh->do("ALTER TABLE deleteditems
1213                 CHANGE COLUMN booksellerid booksellerid MEDIUMTEXT DEFAULT NULL,
1214                 ADD COLUMN enumchron VARCHAR(80) DEFAULT NULL AFTER more_subfields_xml,
1215                 ADD COLUMN copynumber SMALLINT(6) DEFAULT NULL AFTER enumchron;");
1216     $dbh->do("ALTER TABLE items
1217                 CHANGE COLUMN booksellerid booksellerid MEDIUMTEXT,
1218                 ADD COLUMN copynumber SMALLINT(6) DEFAULT NULL AFTER enumchron;");
1219         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";
1220     SetVersion ($DBversion);
1221 }
1222
1223 $DBversion = "3.00.00.064";
1224 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1225     $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');");
1226     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AWSAccessKeyID','','See:  http://aws.amazon.com','','free');");
1227     $dbh->do("DELETE FROM `systempreferences` WHERE variable='AmazonDevKey';");
1228     $dbh->do("DELETE FROM `systempreferences` WHERE variable='XISBNAmazonSimilarItems';");
1229     $dbh->do("DELETE FROM `systempreferences` WHERE variable='OPACXISBNAmazonSimilarItems';");
1230     print "Upgrade to $DBversion done (IMPORTANT: Upgrading to Amazon.com Associates Web Service 4.0 ) \n";
1231     SetVersion ($DBversion);
1232 }
1233
1234 $DBversion = "3.00.00.065";
1235 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1236     $dbh->do("CREATE TABLE `patroncards` (
1237                 `cardid` int(11) NOT NULL auto_increment,
1238                 `batch_id` varchar(10) NOT NULL default '1',
1239                 `borrowernumber` int(11) NOT NULL,
1240                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1241                 PRIMARY KEY  (`cardid`),
1242                 KEY `patroncards_ibfk_1` (`borrowernumber`),
1243                 CONSTRAINT `patroncards_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE
1244                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1245     print "Upgrade to $DBversion done (Adding patroncards table for patroncards generation feature. ) \n";
1246     SetVersion ($DBversion);
1247 }
1248
1249 $DBversion = "3.00.00.066";
1250 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1251     $dbh->do("ALTER TABLE `virtualshelfcontents` MODIFY `dateadded` timestamp NOT NULL
1252 DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP;
1253 ");
1254     print "Upgrade to $DBversion done (fix for bug 1873: virtualshelfcontents dateadded column empty. ) \n";
1255     SetVersion ($DBversion);
1256 }
1257
1258 $DBversion = "3.00.00.067";
1259 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1260     $dbh->do("UPDATE systempreferences SET explanation = 'Enable patron images for the Staff Client', type = 'YesNo' WHERE variable = 'patronimages'");
1261     print "Upgrade to $DBversion done (Updating patronimages syspref to reflect current kohastructure.sql. ) \n";
1262     SetVersion ($DBversion);
1263 }
1264
1265 $DBversion = "3.00.00.068";
1266 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1267     $dbh->do("CREATE TABLE `permissions` (
1268                 `module_bit` int(11) NOT NULL DEFAULT 0,
1269                 `code` varchar(30) DEFAULT NULL,
1270                 `description` varchar(255) DEFAULT NULL,
1271                 PRIMARY KEY  (`module_bit`, `code`),
1272                 CONSTRAINT `permissions_ibfk_1` FOREIGN KEY (`module_bit`) REFERENCES `userflags` (`bit`)
1273                     ON DELETE CASCADE ON UPDATE CASCADE
1274               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1275     $dbh->do("CREATE TABLE `user_permissions` (
1276                 `borrowernumber` int(11) NOT NULL DEFAULT 0,
1277                 `module_bit` int(11) NOT NULL DEFAULT 0,
1278                 `code` varchar(30) DEFAULT NULL,
1279                 CONSTRAINT `user_permissions_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1280                     ON DELETE CASCADE ON UPDATE CASCADE,
1281                 CONSTRAINT `user_permissions_ibfk_2` FOREIGN KEY (`module_bit`, `code`)
1282                     REFERENCES `permissions` (`module_bit`, `code`)
1283                     ON DELETE CASCADE ON UPDATE CASCADE
1284               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1285
1286     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
1287     (13, 'edit_news', 'Write news for the OPAC and staff interfaces'),
1288     (13, 'label_creator', 'Create printable labels and barcodes from catalog and patron data'),
1289     (13, 'edit_calendar', 'Define days when the library is closed'),
1290     (13, 'moderate_comments', 'Moderate patron comments'),
1291     (13, 'edit_notices', 'Define notices'),
1292     (13, 'edit_notice_status_triggers', 'Set notice/status triggers for overdue items'),
1293     (13, 'view_system_logs', 'Browse the system logs'),
1294     (13, 'inventory', 'Perform inventory (stocktaking) of your catalogue'),
1295     (13, 'stage_marc_import', 'Stage MARC records into the reservoir'),
1296     (13, 'manage_staged_marc', 'Managed staged MARC records, including completing and reversing imports'),
1297     (13, 'export_catalog', 'Export bibliographic and holdings data'),
1298     (13, 'import_patrons', 'Import patron data'),
1299     (13, 'delete_anonymize_patrons', 'Delete old borrowers and anonymize circulation history (deletes borrower reading history)'),
1300     (13, 'batch_upload_patron_images', 'Upload patron images in batch or one at a time'),
1301     (13, 'schedule_tasks', 'Schedule tasks to run')");
1302
1303     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('GranularPermissions','0','Use detailed staff user permissions',NULL,'YesNo')");
1304
1305     print "Upgrade to $DBversion done (adding permissions and user_permissions tables and GranularPermissions syspref) \n";
1306     SetVersion ($DBversion);
1307 }
1308 $DBversion = "3.00.00.069";
1309 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1310     $dbh->do("ALTER TABLE labels_conf CHANGE COLUMN class classification int(1) DEFAULT NULL;");
1311         print "Upgrade to $DBversion done ( Correcting columname in labels_conf )\n";
1312     SetVersion ($DBversion);
1313 }
1314
1315 $DBversion = "3.00.00.070";
1316 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1317     $sth = $dbh->prepare("SELECT value FROM systempreferences WHERE variable='yuipath'");
1318     $sth->execute;
1319     my ($value) = $sth->fetchrow;
1320     $value =~ s/2.3.1/2.5.1/;
1321     $dbh->do("UPDATE systempreferences SET value='$value' WHERE variable='yuipath';");
1322         print "Update yuipath syspref to 2.5.1 if necessary\n";
1323     SetVersion ($DBversion);
1324 }
1325
1326 $DBversion = "3.00.00.071";
1327 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1328     $dbh->do(" ALTER TABLE `subscription` ADD `serialsadditems` TINYINT( 1 ) NOT NULL DEFAULT '0';");
1329     # fill the new field with the previous systempreference value, then drop the syspref
1330     my $sth = $dbh->prepare("SELECT value FROM systempreferences WHERE variable='serialsadditems'");
1331     $sth->execute;
1332     my ($serialsadditems) = $sth->fetchrow();
1333     $dbh->do("UPDATE subscription SET serialsadditems=$serialsadditems");
1334     $dbh->do("DELETE FROM systempreferences WHERE variable='serialsadditems'");
1335     print "Upgrade to $DBversion done ( moving serialsadditems from syspref to subscription )\n";
1336     SetVersion ($DBversion);
1337 }
1338
1339 $DBversion = "3.00.00.072";
1340 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1341     $dbh->do("ALTER TABLE labels_conf ADD COLUMN formatstring mediumtext DEFAULT NULL AFTER printingtype");
1342         print "Upgrade to $DBversion done ( Adding format string to labels generator. )\n";
1343     SetVersion ($DBversion);
1344 }
1345
1346 $DBversion = "3.00.00.073";
1347 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1348         $dbh->do("DROP TABLE IF EXISTS `tags_all`;");
1349         $dbh->do(q#
1350         CREATE TABLE `tags_all` (
1351           `tag_id`         int(11) NOT NULL auto_increment,
1352           `borrowernumber` int(11) NOT NULL,
1353           `biblionumber`   int(11) NOT NULL,
1354           `term`      varchar(255) NOT NULL,
1355           `language`       int(4) default NULL,
1356           `date_created` datetime  NOT NULL,
1357           PRIMARY KEY  (`tag_id`),
1358           KEY `tags_borrowers_fk_1` (`borrowernumber`),
1359           KEY `tags_biblionumber_fk_1` (`biblionumber`),
1360           CONSTRAINT `tags_borrowers_fk_1` FOREIGN KEY (`borrowernumber`)
1361                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1362           CONSTRAINT `tags_biblionumber_fk_1` FOREIGN KEY (`biblionumber`)
1363                 REFERENCES `biblio`     (`biblionumber`)  ON DELETE CASCADE ON UPDATE CASCADE
1364         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1365         #);
1366         $dbh->do("DROP TABLE IF EXISTS `tags_approval`;");
1367         $dbh->do(q#
1368         CREATE TABLE `tags_approval` (
1369           `term`   varchar(255) NOT NULL,
1370           `approved`     int(1) NOT NULL default '0',
1371           `date_approved` datetime       default NULL,
1372           `approved_by` int(11)          default NULL,
1373           `weight_total` int(9) NOT NULL default '1',
1374           PRIMARY KEY  (`term`),
1375           KEY `tags_approval_borrowers_fk_1` (`approved_by`),
1376           CONSTRAINT `tags_approval_borrowers_fk_1` FOREIGN KEY (`approved_by`)
1377                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE
1378         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1379         #);
1380         $dbh->do("DROP TABLE IF EXISTS `tags_index`;");
1381         $dbh->do(q#
1382         CREATE TABLE `tags_index` (
1383           `term`    varchar(255) NOT NULL,
1384           `biblionumber` int(11) NOT NULL,
1385           `weight`        int(9) NOT NULL default '1',
1386           PRIMARY KEY  (`term`,`biblionumber`),
1387           KEY `tags_index_biblionumber_fk_1` (`biblionumber`),
1388           CONSTRAINT `tags_index_term_fk_1` FOREIGN KEY (`term`)
1389                 REFERENCES `tags_approval` (`term`)  ON DELETE CASCADE ON UPDATE CASCADE,
1390           CONSTRAINT `tags_index_biblionumber_fk_1` FOREIGN KEY (`biblionumber`)
1391                 REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
1392         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1393         #);
1394         $dbh->do(q#
1395         INSERT INTO `systempreferences` VALUES
1396                 ('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=',''),
1397                 ('BakerTaylorEnabled','0','','Enable or disable all Baker & Taylor features.','YesNo'),
1398                 ('BakerTaylorPassword','','','Baker & Taylor Password for Content Cafe (external content)','Textarea'),
1399                 ('BakerTaylorUsername','','','Baker & Taylor Username for Content Cafe (external content)','Textarea'),
1400                 ('TagsEnabled','1','','Enables or disables all tagging features.  This is the main switch for tags.','YesNo'),
1401                 ('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.',''),
1402                 ('TagsInputOnDetail','1','','Allow users to input tags from the detail page.',         'YesNo'),
1403                 ('TagsInputOnList',  '0','','Allow users to input tags from the search results list.', 'YesNo'),
1404                 ('TagsModeration',  NULL,'','Require tags from patrons to be approved before becoming visible.','YesNo'),
1405                 ('TagsShowOnDetail','10','','Number of tags to display on detail page.  0 is off.',        'Integer'),
1406                 ('TagsShowOnList',   '6','','Number of tags to display on search results list.  0 is off.','Integer')
1407         #);
1408         print "Upgrade to $DBversion done (Baker/Taylor,Tags: sysprefs and tables (tags_all, tags_index, tags_approval)) \n";
1409         SetVersion ($DBversion);
1410 }
1411
1412 $DBversion = "3.00.00.074";
1413 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1414     $dbh->do( q(update itemtypes set imageurl = concat( 'npl/', imageurl )
1415                   where imageurl not like 'http%'
1416                     and imageurl is not NULL
1417                     and imageurl != '') );
1418     print "Upgrade to $DBversion done (updating imagetype.imageurls to reflect new icon locations.)\n";
1419     SetVersion ($DBversion);
1420 }
1421
1422 $DBversion = "3.00.00.075";
1423 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1424     $dbh->do( q(alter table authorised_values add imageurl varchar(200) default NULL) );
1425     print "Upgrade to $DBversion done (adding imageurl field to authorised_values table)\n";
1426     SetVersion ($DBversion);
1427 }
1428
1429 $DBversion = "3.00.00.076";
1430 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1431     $dbh->do("ALTER TABLE import_batches
1432               ADD COLUMN nomatch_action enum('create_new', 'ignore') NOT NULL default 'create_new' AFTER overlay_action");
1433     $dbh->do("ALTER TABLE import_batches
1434               ADD COLUMN item_action enum('always_add', 'add_only_for_matches', 'add_only_for_new', 'ignore')
1435                   NOT NULL default 'always_add' AFTER nomatch_action");
1436     $dbh->do("ALTER TABLE import_batches
1437               MODIFY overlay_action  enum('replace', 'create_new', 'use_template', 'ignore')
1438                   NOT NULL default 'create_new'");
1439     $dbh->do("ALTER TABLE import_records
1440               MODIFY status  enum('error', 'staged', 'imported', 'reverted', 'items_reverted',
1441                                   'ignored') NOT NULL default 'staged'");
1442     $dbh->do("ALTER TABLE import_items
1443               MODIFY status enum('error', 'staged', 'imported', 'reverted', 'ignored') NOT NULL default 'staged'");
1444
1445         print "Upgrade to $DBversion done (changes to import_batches and import_records)\n";
1446         SetVersion ($DBversion);
1447 }
1448
1449 $DBversion = "3.00.00.077";
1450 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1451     # drop these tables only if they exist and none of them are empty
1452     # these tables are not defined in the packaged 2.2.9, but since it is believed
1453     # that at least one library may be using them in a post-2.2.9 but pre-3.0 Koha,
1454     # some care is taken.
1455     my ($print_error) = $dbh->{PrintError};
1456     $dbh->{PrintError} = 0;
1457     my ($raise_error) = $dbh->{RaiseError};
1458     $dbh->{RaiseError} = 1;
1459
1460     my $count = 0;
1461     my $do_drop = 1;
1462     eval { $count = $dbh->do("SELECT 1 FROM categorytable"); };
1463     if ($count > 0) {
1464         $do_drop = 0;
1465     }
1466     eval { $count = $dbh->do("SELECT 1 FROM mediatypetable"); };
1467     if ($count > 0) {
1468         $do_drop = 0;
1469     }
1470     eval { $count = $dbh->do("SELECT 1 FROM subcategorytable"); };
1471     if ($count > 0) {
1472         $do_drop = 0;
1473     }
1474
1475     if ($do_drop) {
1476         $dbh->do("DROP TABLE IF EXISTS `categorytable`");
1477         $dbh->do("DROP TABLE IF EXISTS `mediatypetable`");
1478         $dbh->do("DROP TABLE IF EXISTS `subcategorytable`");
1479     }
1480
1481     $dbh->{PrintError} = $print_error;
1482     $dbh->{RaiseError} = $raise_error;
1483         print "Upgrade to $DBversion done (drop categorytable, subcategorytable, and mediatypetable)\n";
1484         SetVersion ($DBversion);
1485 }
1486
1487 $DBversion = "3.00.00.078";
1488 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1489     my ($print_error) = $dbh->{PrintError};
1490     $dbh->{PrintError} = 0;
1491
1492     unless ($dbh->do("SELECT 1 FROM browser")) {
1493         $dbh->{PrintError} = $print_error;
1494         $dbh->do("CREATE TABLE `browser` (
1495                     `level` int(11) NOT NULL,
1496                     `classification` varchar(20) NOT NULL,
1497                     `description` varchar(255) NOT NULL,
1498                     `number` bigint(20) NOT NULL,
1499                     `endnode` tinyint(4) NOT NULL
1500                   ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1501     }
1502     $dbh->{PrintError} = $print_error;
1503         print "Upgrade to $DBversion done (add browser table if not already present)\n";
1504         SetVersion ($DBversion);
1505 }
1506
1507 $DBversion = "3.00.00.079";
1508 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1509  my ($print_error) = $dbh->{PrintError};
1510     $dbh->{PrintError} = 0;
1511
1512     $dbh->do("INSERT INTO `systempreferences` (variable, value,options,type, explanation)VALUES
1513         ('AddPatronLists','categorycode','categorycode|category_type','Choice','Allow user to choose what list to pick up from when adding patrons')");
1514     print "Upgrade to $DBversion done (add browser table if not already present)\n";
1515         SetVersion ($DBversion);
1516 }
1517
1518 $DBversion = "3.00.00.080";
1519 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1520     $dbh->do("ALTER TABLE subscription CHANGE monthlength monthlength int(11) default '0'");
1521     $dbh->do("ALTER TABLE deleteditems MODIFY marc LONGBLOB AFTER copynumber");
1522     $dbh->do("ALTER TABLE aqbooksellers CHANGE name name mediumtext NOT NULL");
1523         print "Upgrade to $DBversion done (catch up on DB schema changes since alpha and beta)\n";
1524         SetVersion ($DBversion);
1525 }
1526
1527 $DBversion = "3.00.00.081";
1528 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1529     $dbh->do("CREATE TABLE `borrower_attribute_types` (
1530                 `code` varchar(10) NOT NULL,
1531                 `description` varchar(255) NOT NULL,
1532                 `repeatable` tinyint(1) NOT NULL default 0,
1533                 `unique_id` tinyint(1) NOT NULL default 0,
1534                 `opac_display` tinyint(1) NOT NULL default 0,
1535                 `password_allowed` tinyint(1) NOT NULL default 0,
1536                 `staff_searchable` tinyint(1) NOT NULL default 0,
1537                 `authorised_value_category` varchar(10) default NULL,
1538                 PRIMARY KEY  (`code`)
1539               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1540     $dbh->do("CREATE TABLE `borrower_attributes` (
1541                 `borrowernumber` int(11) NOT NULL,
1542                 `code` varchar(10) NOT NULL,
1543                 `attribute` varchar(30) default NULL,
1544                 `password` varchar(30) default NULL,
1545                 KEY `borrowernumber` (`borrowernumber`),
1546                 KEY `code_attribute` (`code`, `attribute`),
1547                 CONSTRAINT `borrower_attributes_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1548                     ON DELETE CASCADE ON UPDATE CASCADE,
1549                 CONSTRAINT `borrower_attributes_ibfk_2` FOREIGN KEY (`code`) REFERENCES `borrower_attribute_types` (`code`)
1550                     ON DELETE CASCADE ON UPDATE CASCADE
1551             ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1552     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('ExtendedPatronAttributes','0','Use extended patron IDs and attributes',NULL,'YesNo')");
1553     print "Upgrade to $DBversion done (added borrower_attributes and  borrower_attribute_types)\n";
1554  SetVersion ($DBversion);
1555 }
1556
1557 $DBversion = "3.00.00.082";
1558 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1559     $dbh->do( q(alter table accountlines add column lastincrement decimal(28,6) default NULL) );
1560     print "Upgrade to $DBversion done (adding lastincrement column to accountlines table)\n";
1561     SetVersion ($DBversion);
1562 }
1563
1564 $DBversion = "3.00.00.083";
1565 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1566     $dbh->do( qq(UPDATE systempreferences SET value='local' where variable='yuipath' and value like "%/intranet-tmpl/prog/%"));
1567     print "Upgrade to $DBversion done (Changing yuipath behaviour in managing a local value)\n";
1568     SetVersion ($DBversion);
1569 }
1570 $DBversion = "3.00.00.084";
1571     if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1572     $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')");
1573     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('GoogleJackets','0','if ON, displays jacket covers from Google Books API',NULL,'YesNo')");
1574     print "Upgrade to $DBversion done (add new sysprefs)\n";
1575     SetVersion ($DBversion);
1576 }
1577
1578 $DBversion = "3.00.00.085";
1579 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1580     if (C4::Context->preference("marcflavour") eq 'MARC21') {
1581         $dbh->do("UPDATE marc_subfield_structure SET tab = 0 WHERE tab =  9 AND tagfield = '037'");
1582         $dbh->do("UPDATE marc_subfield_structure SET tab = 1 WHERE tab =  6 AND tagfield in ('100', '110', '111', '130')");
1583         $dbh->do("UPDATE marc_subfield_structure SET tab = 2 WHERE tab =  6 AND tagfield in ('240', '243')");
1584         $dbh->do("UPDATE marc_subfield_structure SET tab = 4 WHERE tab =  6 AND tagfield in ('400', '410', '411', '440')");
1585         $dbh->do("UPDATE marc_subfield_structure SET tab = 5 WHERE tab =  9 AND tagfield = '584'");
1586         $dbh->do("UPDATE marc_subfield_structure SET tab = 7 WHERE tab = -6 AND tagfield = '760'");
1587     }
1588     print "Upgrade to $DBversion done (move editing tab of various MARC21 subfields)\n";
1589     SetVersion ($DBversion);
1590 }
1591
1592 $DBversion = "3.00.00.086";
1593 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1594         $dbh->do(
1595         "CREATE TABLE `tmp_holdsqueue` (
1596         `biblionumber` int(11) default NULL,
1597         `itemnumber` int(11) default NULL,
1598         `barcode` varchar(20) default NULL,
1599         `surname` mediumtext NOT NULL,
1600         `firstname` text,
1601         `phone` text,
1602         `borrowernumber` int(11) NOT NULL,
1603         `cardnumber` varchar(16) default NULL,
1604         `reservedate` date default NULL,
1605         `title` mediumtext,
1606         `itemcallnumber` varchar(30) default NULL,
1607         `holdingbranch` varchar(10) default NULL,
1608         `pickbranch` varchar(10) default NULL,
1609         `notes` text
1610         ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1611
1612         $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')");
1613         $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')");
1614
1615         print "Upgrade to $DBversion done (Table structure for table `tmp_holdsqueue`)\n";
1616         SetVersion ($DBversion);
1617 }
1618
1619 $DBversion = "3.00.00.087";
1620 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1621     $dbh->do("INSERT INTO `systempreferences` VALUES ('AutoEmailOpacUser','0','','Sends notification emails containing new account details to patrons - when account is created.','YesNo')" );
1622     $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')");
1623     print "Upgrade to $DBversion done (added 2 new 'AutoEmailOpacUser' sysprefs)\n";
1624     SetVersion ($DBversion);
1625 }
1626
1627 $DBversion = "3.00.00.088";
1628 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1629         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('OPACShelfBrowser','1','','Enable/disable Shelf Browser on item details page','YesNo')");
1630         $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')");
1631         $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')");
1632         $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')");
1633         print "Upgrade to $DBversion done (added 2 new 'AutoEmailOpacUser' sysprefs)\n";
1634     SetVersion ($DBversion);
1635 }
1636
1637 $DBversion = "3.00.00.089";
1638 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1639         $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')");
1640         print "Upgrade to $DBversion done (added new AdvancedSearchTypes syspref)\n";
1641     SetVersion ($DBversion);
1642 }
1643
1644 $DBversion = "3.00.00.090";
1645 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1646     $dbh->do("
1647         CREATE TABLE `branch_borrower_circ_rules` (
1648           `branchcode` VARCHAR(10) NOT NULL,
1649           `categorycode` VARCHAR(10) NOT NULL,
1650           `maxissueqty` int(4) default NULL,
1651           PRIMARY KEY (`categorycode`, `branchcode`),
1652           CONSTRAINT `branch_borrower_circ_rules_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
1653             ON DELETE CASCADE ON UPDATE CASCADE,
1654           CONSTRAINT `branch_borrower_circ_rules_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`)
1655             ON DELETE CASCADE ON UPDATE CASCADE
1656         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1657     ");
1658     $dbh->do("
1659         CREATE TABLE `default_borrower_circ_rules` (
1660           `categorycode` VARCHAR(10) NOT NULL,
1661           `maxissueqty` int(4) default NULL,
1662           PRIMARY KEY (`categorycode`),
1663           CONSTRAINT `borrower_borrower_circ_rules_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
1664             ON DELETE CASCADE ON UPDATE CASCADE
1665         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1666     ");
1667     $dbh->do("
1668         CREATE TABLE `default_branch_circ_rules` (
1669           `branchcode` VARCHAR(10) NOT NULL,
1670           `maxissueqty` int(4) default NULL,
1671           PRIMARY KEY (`branchcode`),
1672           CONSTRAINT `default_branch_circ_rules_ibfk_1` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`)
1673             ON DELETE CASCADE ON UPDATE CASCADE
1674         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1675     ");
1676     $dbh->do("
1677         CREATE TABLE `default_circ_rules` (
1678             `singleton` enum('singleton') NOT NULL default 'singleton',
1679             `maxissueqty` int(4) default NULL,
1680             PRIMARY KEY (`singleton`)
1681         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1682     ");
1683     print "Upgrade to $DBversion done (added several circ rules tables)\n";
1684     SetVersion ($DBversion);
1685 }
1686
1687
1688 $DBversion = "3.00.00.091";
1689 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1690     $dbh->do(<<'END_SQL');
1691 ALTER TABLE borrowers
1692 ADD `smsalertnumber` varchar(50) default NULL
1693 END_SQL
1694
1695     $dbh->do(<<'END_SQL');
1696 CREATE TABLE `message_attributes` (
1697   `message_attribute_id` int(11) NOT NULL auto_increment,
1698   `message_name` varchar(20) NOT NULL default '',
1699   `takes_days` tinyint(1) NOT NULL default '0',
1700   PRIMARY KEY  (`message_attribute_id`),
1701   UNIQUE KEY `message_name` (`message_name`)
1702 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1703 END_SQL
1704
1705     $dbh->do(<<'END_SQL');
1706 CREATE TABLE `message_transport_types` (
1707   `message_transport_type` varchar(20) NOT NULL,
1708   PRIMARY KEY  (`message_transport_type`)
1709 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1710 END_SQL
1711
1712     $dbh->do(<<'END_SQL');
1713 CREATE TABLE `message_transports` (
1714   `message_attribute_id` int(11) NOT NULL,
1715   `message_transport_type` varchar(20) NOT NULL,
1716   `is_digest` tinyint(1) NOT NULL default '0',
1717   `letter_module` varchar(20) NOT NULL default '',
1718   `letter_code` varchar(20) NOT NULL default '',
1719   PRIMARY KEY  (`message_attribute_id`,`message_transport_type`,`is_digest`),
1720   KEY `message_transport_type` (`message_transport_type`),
1721   KEY `letter_module` (`letter_module`,`letter_code`),
1722   CONSTRAINT `message_transports_ibfk_1` FOREIGN KEY (`message_attribute_id`) REFERENCES `message_attributes` (`message_attribute_id`) ON DELETE CASCADE ON UPDATE CASCADE,
1723   CONSTRAINT `message_transports_ibfk_2` FOREIGN KEY (`message_transport_type`) REFERENCES `message_transport_types` (`message_transport_type`) ON DELETE CASCADE ON UPDATE CASCADE,
1724   CONSTRAINT `message_transports_ibfk_3` FOREIGN KEY (`letter_module`, `letter_code`) REFERENCES `letter` (`module`, `code`) ON DELETE CASCADE ON UPDATE CASCADE
1725 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1726 END_SQL
1727
1728     $dbh->do(<<'END_SQL');
1729 CREATE TABLE `borrower_message_preferences` (
1730   `borrower_message_preference_id` int(11) NOT NULL auto_increment,
1731   `borrowernumber` int(11) NOT NULL default '0',
1732   `message_attribute_id` int(11) default '0',
1733   `days_in_advance` int(11) default '0',
1734   `wants_digets` tinyint(1) NOT NULL default '0',
1735   PRIMARY KEY  (`borrower_message_preference_id`),
1736   KEY `borrowernumber` (`borrowernumber`),
1737   KEY `message_attribute_id` (`message_attribute_id`),
1738   CONSTRAINT `borrower_message_preferences_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1739   CONSTRAINT `borrower_message_preferences_ibfk_2` FOREIGN KEY (`message_attribute_id`) REFERENCES `message_attributes` (`message_attribute_id`) ON DELETE CASCADE ON UPDATE CASCADE
1740 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1741 END_SQL
1742
1743     $dbh->do(<<'END_SQL');
1744 CREATE TABLE `borrower_message_transport_preferences` (
1745   `borrower_message_preference_id` int(11) NOT NULL default '0',
1746   `message_transport_type` varchar(20) NOT NULL default '0',
1747   PRIMARY KEY  (`borrower_message_preference_id`,`message_transport_type`),
1748   KEY `message_transport_type` (`message_transport_type`),
1749   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,
1750   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
1751 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1752 END_SQL
1753
1754     $dbh->do(<<'END_SQL');
1755 CREATE TABLE `message_queue` (
1756   `message_id` int(11) NOT NULL auto_increment,
1757   `borrowernumber` int(11) NOT NULL,
1758   `subject` text,
1759   `content` text,
1760   `message_transport_type` varchar(20) NOT NULL,
1761   `status` enum('sent','pending','failed','deleted') NOT NULL default 'pending',
1762   `time_queued` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1763   KEY `message_id` (`message_id`),
1764   KEY `borrowernumber` (`borrowernumber`),
1765   KEY `message_transport_type` (`message_transport_type`),
1766   CONSTRAINT `messageq_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1767   CONSTRAINT `messageq_ibfk_2` FOREIGN KEY (`message_transport_type`) REFERENCES `message_transport_types` (`message_transport_type`) ON DELETE RESTRICT ON UPDATE CASCADE
1768 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1769 END_SQL
1770
1771     $dbh->do(<<'END_SQL');
1772 INSERT INTO `systempreferences`
1773   (variable,value,explanation,options,type)
1774 VALUES
1775 ('EnhancedMessagingPreferences',0,'If ON, allows patrons to select to receive additional messages about items due or nearly due.','','YesNo')
1776 END_SQL
1777
1778     $dbh->do( <<'END_SQL');
1779 INSERT INTO `letter`
1780 (module, code, name, title, content)
1781 VALUES
1782 ('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>>'),
1783 ('circulation','DUEDGST','Item Due Reminder (Digest)','Item Due Reminder','You have <<count>> items due'),
1784 ('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>>'),
1785 ('circulation','PREDUEDGST','Advance Notice of Item Due (Digest)','Advance Notice of Item Due','You have <<count>> items due soon'),
1786 ('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.');
1787 END_SQL
1788
1789     my @sql_scripts = (
1790         'installer/data/mysql/en/mandatory/message_transport_types.sql',
1791         'installer/data/mysql/en/optional/sample_notices_message_attributes.sql',
1792         'installer/data/mysql/en/optional/sample_notices_message_transports.sql',
1793     );
1794
1795     my $installer = C4::Installer->new();
1796     foreach my $script ( @sql_scripts ) {
1797         my $full_path = $installer->get_file_path_from_name($script);
1798         my $error = $installer->load_sql($full_path);
1799         warn $error if $error;
1800     }
1801
1802     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";
1803     SetVersion ($DBversion);
1804 }
1805
1806 $DBversion = "3.00.00.092";
1807 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1808     $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')");
1809     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES('AllowHoldsOnDamagedItems', '1', '', 'Allow hold requests to be placed on damaged items', 'YesNo')");
1810         print "Upgrade to $DBversion done (added new AllowOnShelfHolds syspref)\n";
1811     SetVersion ($DBversion);
1812 }
1813
1814 $DBversion = "3.00.00.093";
1815 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1816     $dbh->do("ALTER TABLE `items` MODIFY COLUMN `copynumber` VARCHAR(32) DEFAULT NULL");
1817     $dbh->do("ALTER TABLE `deleteditems` MODIFY COLUMN `copynumber` VARCHAR(32) DEFAULT NULL");
1818         print "Upgrade to $DBversion done (Change data type of items.copynumber to allow free text)\n";
1819     SetVersion ($DBversion);
1820 }
1821
1822 $DBversion = "3.00.00.094";
1823 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1824     $dbh->do("ALTER TABLE `marc_subfield_structure` MODIFY `tagsubfield` VARCHAR(1) NOT NULL DEFAULT '' COLLATE utf8_bin");
1825         print "Upgrade to $DBversion done (Change Collation of marc_subfield_structure to allow mixed case in subfield labels.)\n";
1826     SetVersion ($DBversion);
1827 }
1828
1829 $DBversion = "3.00.00.095";
1830 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1831     if (C4::Context->preference("marcflavour") eq 'MARC21') {
1832         $dbh->do("UPDATE marc_subfield_structure SET authtypecode = 'MEETI_NAME' WHERE authtypecode = 'Meeting Name'");
1833         $dbh->do("UPDATE marc_subfield_structure SET authtypecode = 'CORPO_NAME' WHERE authtypecode = 'CORP0_NAME'");
1834     }
1835         print "Upgrade to $DBversion done (fix invalid authority types in MARC21 frameworks [bug 2254])\n";
1836     SetVersion ($DBversion);
1837 }
1838
1839 $DBversion = "3.00.00.096";
1840 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1841     $sth = $dbh->prepare("SHOW COLUMNS FROM borrower_message_preferences LIKE 'wants_digets'");
1842     $sth->execute();
1843     if (my $row = $sth->fetchrow_hashref) {
1844         $dbh->do("ALTER TABLE borrower_message_preferences CHANGE wants_digets wants_digest tinyint(1) NOT NULL default 0");
1845     }
1846         print "Upgrade to $DBversion done (fix name borrower_message_preferences.wants_digest)\n";
1847     SetVersion ($DBversion);
1848 }
1849
1850 $DBversion = '3.00.00.097';
1851 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1852
1853     $dbh->do('ALTER TABLE message_queue ADD to_address   mediumtext default NULL');
1854     $dbh->do('ALTER TABLE message_queue ADD from_address mediumtext default NULL');
1855     $dbh->do('ALTER TABLE message_queue ADD content_type text');
1856     $dbh->do('ALTER TABLE message_queue CHANGE borrowernumber borrowernumber int(11) default NULL');
1857
1858     print "Upgrade to $DBversion done (updating 4 fields in message_queue table)\n";
1859     SetVersion($DBversion);
1860 }
1861
1862 $DBversion = '3.00.00.098';
1863 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1864
1865     $dbh->do(q(DELETE FROM message_transport_types WHERE message_transport_type = 'rss'));
1866     $dbh->do(q(DELETE FROM message_transports WHERE message_transport_type = 'rss'));
1867
1868     print "Upgrade to $DBversion done (removing unused RSS message_transport_type)\n";
1869     SetVersion($DBversion);
1870 }
1871
1872 $DBversion = '3.00.00.099';
1873 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1874     $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')");
1875     print "Upgrade to $DBversion done (Adding OpacSuppression syspref)\n";
1876     SetVersion($DBversion);
1877 }
1878
1879 $DBversion = '3.00.00.100';
1880 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1881         $dbh->do('ALTER TABLE virtualshelves ADD COLUMN lastmodified timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP');
1882     print "Upgrade to $DBversion done (Adding lastmodified column to virtualshelves)\n";
1883     SetVersion($DBversion);
1884 }
1885
1886 $DBversion = '3.00.00.101';
1887 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1888         $dbh->do('ALTER TABLE `overduerules` CHANGE `categorycode` `categorycode` VARCHAR(10) NOT NULL');
1889         $dbh->do('ALTER TABLE `deletedborrowers` CHANGE `categorycode` `categorycode` VARCHAR(10) NOT NULL');
1890     print "Upgrade to $DBversion done (Updating columnd definitions for patron category codes in notice/statsu triggers and deletedborrowers tables.)\n";
1891     SetVersion($DBversion);
1892 }
1893
1894 $DBversion = '3.00.00.102';
1895 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1896         $dbh->do('ALTER TABLE serialitems MODIFY `serialid` int(11) NOT NULL AFTER itemnumber' );
1897         $dbh->do('ALTER TABLE serialitems DROP KEY serialididx' );
1898         $dbh->do('ALTER TABLE serialitems ADD CONSTRAINT UNIQUE KEY serialitemsidx (itemnumber)' );
1899         # before setting constraint, delete any unvalid data
1900         $dbh->do('DELETE from serialitems WHERE serialid not in (SELECT serial.serialid FROM serial)');
1901         $dbh->do('ALTER TABLE serialitems ADD CONSTRAINT serialitems_sfk_1 FOREIGN KEY (serialid) REFERENCES serial (serialid) ON DELETE CASCADE ON UPDATE CASCADE' );
1902     print "Upgrade to $DBversion done (Updating serialitems table to allow for multiple items per serial fixing kohabug 2380)\n";
1903     SetVersion($DBversion);
1904 }
1905
1906 $DBversion = "3.00.00.103";
1907 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1908     $dbh->do("DELETE FROM systempreferences WHERE variable='serialsadditems'");
1909     print "Upgrade to $DBversion done ( Verifying the removal of serialsadditems from syspref fixing kohabug 2219)\n";
1910     SetVersion ($DBversion);
1911 }
1912
1913 $DBversion = "3.00.00.104";
1914 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1915     $dbh->do("DELETE FROM systempreferences WHERE variable='noOPACHolds'");
1916     print "Upgrade to $DBversion done (remove superseded 'noOPACHolds' system preference per bug 2413)\n";
1917     SetVersion ($DBversion);
1918 }
1919
1920 $DBversion = '3.00.00.105';
1921 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
1922
1923     # it is possible that this syspref is already defined since the feature was added some time ago.
1924     unless ( $dbh->do(q(SELECT variable FROM systempreferences WHERE variable = 'SMSSendDriver')) ) {
1925         $dbh->do(<<'END_SQL');
1926 INSERT INTO `systempreferences`
1927   (variable,value,explanation,options,type)
1928 VALUES
1929 ('SMSSendDriver','','Sets which SMS::Send driver is used to send SMS messages.','','free')
1930 END_SQL
1931     }
1932     print "Upgrade to $DBversion done (added SMSSendDriver system preference)\n";
1933     SetVersion($DBversion);
1934 }
1935
1936 $DBversion = "3.00.00.106";
1937 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1938     $dbh->do("DELETE FROM systempreferences WHERE variable='noOPACHolds'");
1939
1940 # db revision 105 didn't apply correctly, so we're rolling this into 106
1941         $dbh->do("INSERT INTO `systempreferences`
1942    (variable,value,explanation,options,type)
1943         VALUES
1944         ('SMSSendDriver','','Sets which SMS::Send driver is used to send SMS messages.','','free')");
1945
1946     print "Upgrade to $DBversion done (remove default '0000-00-00' in subscriptionhistory.enddate field)\n";
1947     $dbh->do("ALTER TABLE `subscriptionhistory` CHANGE `enddate` `enddate` DATE NULL DEFAULT NULL ");
1948     $dbh->do("UPDATE subscriptionhistory SET enddate=NULL WHERE enddate='0000-00-00'");
1949     SetVersion ($DBversion);
1950 }
1951
1952 $DBversion = '3.00.00.107';
1953 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1954     $dbh->do(<<'END_SQL');
1955 UPDATE systempreferences
1956   SET explanation = CONCAT( explanation, '. WARNING: this feature is very resource consuming on collections with large numbers of items.' )
1957   WHERE variable = 'OPACShelfBrowser'
1958     AND explanation NOT LIKE '%WARNING%'
1959 END_SQL
1960     $dbh->do(<<'END_SQL');
1961 UPDATE systempreferences
1962   SET explanation = CONCAT( explanation, '. WARNING: this feature is very resource consuming.' )
1963   WHERE variable = 'CataloguingLog'
1964     AND explanation NOT LIKE '%WARNING%'
1965 END_SQL
1966     $dbh->do(<<'END_SQL');
1967 UPDATE systempreferences
1968   SET explanation = CONCAT( explanation, '. WARNING: using NoZebra on even modest sized collections is very slow.' )
1969   WHERE variable = 'NoZebra'
1970     AND explanation NOT LIKE '%WARNING%'
1971 END_SQL
1972     print "Upgrade to $DBversion done (warning added to OPACShelfBrowser system preference)\n";
1973     SetVersion ($DBversion);
1974 }
1975
1976 $DBversion = '3.01.00.000';
1977 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1978     print "Upgrade to $DBversion done (start of 3.1)\n";
1979     SetVersion ($DBversion);
1980 }
1981
1982 $DBversion = '3.01.00.001';
1983 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1984     $dbh->do("
1985         CREATE TABLE hold_fill_targets (
1986             `borrowernumber` int(11) NOT NULL,
1987             `biblionumber` int(11) NOT NULL,
1988             `itemnumber` int(11) NOT NULL,
1989             `source_branchcode`  varchar(10) default NULL,
1990             `item_level_request` tinyint(4) NOT NULL default 0,
1991             PRIMARY KEY `itemnumber` (`itemnumber`),
1992             KEY `bib_branch` (`biblionumber`, `source_branchcode`),
1993             CONSTRAINT `hold_fill_targets_ibfk_1` FOREIGN KEY (`borrowernumber`)
1994                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1995             CONSTRAINT `hold_fill_targets_ibfk_2` FOREIGN KEY (`biblionumber`)
1996                 REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1997             CONSTRAINT `hold_fill_targets_ibfk_3` FOREIGN KEY (`itemnumber`)
1998                 REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1999             CONSTRAINT `hold_fill_targets_ibfk_4` FOREIGN KEY (`source_branchcode`)
2000                 REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
2001         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2002     ");
2003     $dbh->do("
2004         ALTER TABLE tmp_holdsqueue
2005             ADD item_level_request tinyint(4) NOT NULL default 0
2006     ");
2007
2008     print "Upgrade to $DBversion done (add hold_fill_targets table and a column to tmp_holdsqueue)\n";
2009     SetVersion($DBversion);
2010 }
2011
2012 $DBversion = '3.01.00.002';
2013 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2014     # use statistics where available
2015     $dbh->do("
2016         ALTER TABLE statistics ADD KEY  tmp_stats (type, itemnumber, borrowernumber)
2017     ");
2018     $dbh->do("
2019         UPDATE issues iss
2020         SET issuedate = (
2021             SELECT max(datetime)
2022             FROM statistics
2023             WHERE type = 'issue'
2024             AND itemnumber = iss.itemnumber
2025             AND borrowernumber = iss.borrowernumber
2026         )
2027         WHERE issuedate IS NULL;
2028     ");
2029     $dbh->do("ALTER TABLE statistics DROP KEY tmp_stats");
2030
2031     # default to last renewal date
2032     $dbh->do("
2033         UPDATE issues
2034         SET issuedate = lastreneweddate
2035         WHERE issuedate IS NULL
2036         and lastreneweddate IS NOT NULL
2037     ");
2038
2039     my $num_bad_issuedates = $dbh->selectrow_array("SELECT COUNT(*) FROM issues WHERE issuedate IS NULL");
2040     if ($num_bad_issuedates > 0) {
2041         print STDERR "After the upgrade to $DBversion, there are still $num_bad_issuedates loan(s) with a NULL (blank) loan date. ",
2042                      "Please check the issues table in your database.";
2043     }
2044     print "Upgrade to $DBversion done (bug 2582: set null issues.issuedate to lastreneweddate)\n";
2045     SetVersion($DBversion);
2046 }
2047
2048 $DBversion = "3.01.00.003";
2049 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2050     $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')");
2051     print "Upgrade to $DBversion done (add new syspref)\n";
2052     SetVersion ($DBversion);
2053 }
2054
2055 $DBversion = '3.01.00.004';
2056 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2057     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACDisplayRequestPriority','0','Show patrons the priority level on holds in the OPAC','','YesNo')");
2058     print "Upgrade to $DBversion done (added OPACDisplayRequestPriority system preference)\n";
2059     SetVersion ($DBversion);
2060 }
2061
2062 $DBversion = '3.01.00.005';
2063 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2064     $dbh->do("
2065         INSERT INTO `letter` (module, code, name, title, content)
2066         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>>')
2067     ");
2068     $dbh->do("INSERT INTO `message_attributes` (message_attribute_id, message_name, takes_days) values(4, 'Hold Filled', 0)");
2069     $dbh->do("INSERT INTO `message_transports` (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) values(4, 'sms', 0, 'reserves', 'HOLD')");
2070     $dbh->do("INSERT INTO `message_transports` (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) values(4, 'email', 0, 'reserves', 'HOLD')");
2071     print "Upgrade to $DBversion done (Add letter for holds notifications)\n";
2072     SetVersion ($DBversion);
2073 }
2074
2075 $DBversion = '3.01.00.006';
2076 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2077     $dbh->do("ALTER TABLE `biblioitems` ADD KEY issn (issn)");
2078     print "Upgrade to $DBversion done (add index on biblioitems.issn)\n";
2079     SetVersion ($DBversion);
2080 }
2081
2082 $DBversion = "3.01.00.007";
2083 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2084     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='intranetmainUserblock'");
2085     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='intranetuserjs'");
2086     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='opacheader'");
2087     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='OpacMainUserBlock'");
2088     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='OpacNav'");
2089     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='opacuserjs'");
2090     $dbh->do("UPDATE `systempreferences` SET options='30|10', type='Textarea' WHERE variable='OAI-PMH:Set'");
2091     $dbh->do("UPDATE `systempreferences` SET options='50' WHERE variable='intranetstylesheet'");
2092     $dbh->do("UPDATE `systempreferences` SET options='50' WHERE variable='intranetcolorstylesheet'");
2093     $dbh->do("UPDATE `systempreferences` SET options='10' WHERE variable='globalDueDate'");
2094     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='numSearchResults'");
2095     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='OPACnumSearchResults'");
2096     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='ReservesMaxPickupDelay'");
2097     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='TransfersMaxDaysWarning'");
2098     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='StaticHoldsQueueWeight'");
2099     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='holdCancelLength'");
2100     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='XISBNDailyLimit'");
2101     $dbh->do("UPDATE `systempreferences` SET type='Float' WHERE variable='gist'");
2102     $dbh->do("UPDATE `systempreferences` SET type='Free' WHERE variable='BakerTaylorUsername'");
2103     $dbh->do("UPDATE `systempreferences` SET type='Free' WHERE variable='BakerTaylorPassword'");
2104     $dbh->do("UPDATE `systempreferences` SET type='Textarea', options='70|10' WHERE variable='ISBD'");
2105     $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'");
2106     print "Upgrade to $DBversion done (fix display of many sysprefs)\n";
2107     SetVersion ($DBversion);
2108 }
2109
2110 $DBversion = '3.01.00.008';
2111 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2112
2113     $dbh->do("CREATE TABLE branch_transfer_limits (
2114                           limitId int(8) NOT NULL auto_increment,
2115                           toBranch varchar(4) NOT NULL,
2116                           fromBranch varchar(4) NOT NULL,
2117                           itemtype varchar(4) NOT NULL,
2118                           PRIMARY KEY  (limitId)
2119                           ) ENGINE=InnoDB DEFAULT CHARSET=utf8"
2120                         );
2121
2122     $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')");
2123
2124     print "Upgrade to $DBversion done (added branch_transfer_limits table and UseBranchTransferLimits system preference)\n";
2125     SetVersion ($DBversion);
2126 }
2127
2128 $DBversion = "3.01.00.009";
2129 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2130     $dbh->do("ALTER TABLE permissions MODIFY `code` varchar(64) DEFAULT NULL");
2131     $dbh->do("ALTER TABLE user_permissions MODIFY `code` varchar(64) DEFAULT NULL");
2132     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'circulate_remaining_permissions', 'Remaining circulation permissions')");
2133     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'override_renewals', 'Override blocked renewals')");
2134     print "Upgrade to $DBversion done (added subpermissions for circulate permission)\n";
2135 }
2136
2137 $DBversion = '3.01.00.010';
2138 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2139     $dbh->do("ALTER TABLE `borrower_attributes` MODIFY COLUMN `attribute` VARCHAR(64) DEFAULT NULL");
2140     $dbh->do("ALTER TABLE `borrower_attributes` MODIFY COLUMN `password` VARCHAR(64) DEFAULT NULL");
2141     print "Upgrade to $DBversion done (bug 2687: increase length of borrower attribute fields)\n";
2142     SetVersion ($DBversion);
2143 }
2144
2145 $DBversion = '3.01.00.011';
2146 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2147
2148     # Yes, the old value was ^M terminated.
2149     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);";
2150
2151     my $intranetuserjs = C4::Context->preference('intranetuserjs');
2152     if ($intranetuserjs  and  $intranetuserjs eq $bad_value) {
2153         my $sql = <<'END_SQL';
2154 UPDATE systempreferences
2155 SET value = ''
2156 WHERE variable = 'intranetuserjs'
2157 END_SQL
2158         $dbh->do($sql);
2159     }
2160     print "Upgrade to $DBversion done (removed bogus intranetuserjs syspref)\n";
2161     SetVersion($DBversion);
2162 }
2163
2164 $DBversion = "3.01.00.012";
2165 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2166     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowHoldPolicyOverride', '0', 'Allow staff to override hold policies when placing holds',NULL,'YesNo')");
2167     $dbh->do("
2168         CREATE TABLE `branch_item_rules` (
2169           `branchcode` varchar(10) NOT NULL,
2170           `itemtype` varchar(10) NOT NULL,
2171           `holdallowed` tinyint(1) default NULL,
2172           PRIMARY KEY  (`itemtype`,`branchcode`),
2173           KEY `branch_item_rules_ibfk_2` (`branchcode`),
2174           CONSTRAINT `branch_item_rules_ibfk_1` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE,
2175           CONSTRAINT `branch_item_rules_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
2176         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2177     ");
2178     $dbh->do("
2179         CREATE TABLE `default_branch_item_rules` (
2180           `itemtype` varchar(10) NOT NULL,
2181           `holdallowed` tinyint(1) default NULL,
2182           PRIMARY KEY  (`itemtype`),
2183           CONSTRAINT `default_branch_item_rules_ibfk_1` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE
2184         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2185     ");
2186     $dbh->do("
2187         ALTER TABLE default_branch_circ_rules
2188             ADD COLUMN holdallowed tinyint(1) NULL
2189     ");
2190     $dbh->do("
2191         ALTER TABLE default_circ_rules
2192             ADD COLUMN holdallowed tinyint(1) NULL
2193     ");
2194     print "Upgrade to $DBversion done (Add tables and system preferences for holds policies)\n";
2195     SetVersion ($DBversion);
2196 }
2197
2198 $DBversion = '3.01.00.013';
2199 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2200     $dbh->do("
2201         CREATE TABLE item_circulation_alert_preferences (
2202             id           int(11) AUTO_INCREMENT,
2203             branchcode   varchar(10) NOT NULL,
2204             categorycode varchar(10) NOT NULL,
2205             item_type    varchar(10) NOT NULL,
2206             notification varchar(16) NOT NULL,
2207             PRIMARY KEY (id),
2208             KEY (branchcode, categorycode, item_type, notification)
2209         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2210     ");
2211
2212     $dbh->do(q{ ALTER TABLE `message_queue` ADD metadata text DEFAULT NULL           AFTER content;  });
2213     $dbh->do(q{ ALTER TABLE `message_queue` ADD letter_code varchar(64) DEFAULT NULL AFTER metadata; });
2214
2215     $dbh->do(q{
2216         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
2217         ('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.');
2218     });
2219     $dbh->do(q{
2220         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
2221         ('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>>.');
2222     });
2223
2224     $dbh->do(q{INSERT INTO message_attributes (message_attribute_id, message_name, takes_days) VALUES (5, 'Item Check-in', 0);});
2225     $dbh->do(q{INSERT INTO message_attributes (message_attribute_id, message_name, takes_days) VALUES (6, 'Item Checkout', 0);});
2226
2227     $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');});
2228     $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');});
2229     $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');});
2230     $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');});
2231
2232     print "Upgrade to $DBversion done (data for Email Checkout Slips project)\n";
2233          SetVersion ($DBversion);
2234 }
2235
2236 $DBversion = "3.01.00.014";
2237 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2238     $dbh->do("ALTER TABLE `branch_transfer_limits` CHANGE `itemtype` `itemtype` VARCHAR( 4 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL");
2239     $dbh->do("ALTER TABLE `branch_transfer_limits` ADD `ccode` VARCHAR( 10 ) NULL ;");
2240     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2241     VALUES (
2242     'BranchTransferLimitsType', 'ccode', 'itemtype|ccode', 'When using branch transfer limits, choose whether to limit by itemtype or collection code.', 'Choice'
2243     );");
2244
2245     print "Upgrade to $DBversion done ( Updated table for Branch Transfer Limits)\n";
2246     SetVersion ($DBversion);
2247 }
2248
2249 $DBversion = '3.01.00.015';
2250 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2251     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsClientCode', '0', 'Client Code for using Syndetics Solutions content','','free')");
2252
2253     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsEnabled', '0', 'Turn on Syndetics Enhanced Content','','YesNo')");
2254
2255     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsCoverImages', '0', 'Display Cover Images from Syndetics','','YesNo')");
2256
2257     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsTOC', '0', 'Display Table of Content information from Syndetics','','YesNo')");
2258
2259     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsSummary', '0', 'Display Summary Information from Syndetics','','YesNo')");
2260
2261     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsEditions', '0', 'Display Editions from Syndetics','','YesNo')");
2262
2263     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsExcerpt', '0', 'Display Excerpts and first chapters on OPAC from Syndetics','','YesNo')");
2264
2265     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsReviews', '0', 'Display Reviews on OPAC from Syndetics','','YesNo')");
2266
2267     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsAuthorNotes', '0', 'Display Notes about the Author on OPAC from Syndetics','','YesNo')");
2268
2269     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsAwards', '0', 'Display Awards on OPAC from Syndetics','','YesNo')");
2270
2271     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsSeries', '0', 'Display Series information on OPAC from Syndetics','','YesNo')");
2272
2273     $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')");
2274
2275     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAmazonCoverImages', '0', 'Display cover images on OPAC from Amazon Web Services','','YesNo')");
2276
2277     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AmazonCoverImages', '0', 'Display Cover Images in Staff Client from Amazon Web Services','','YesNo')");
2278
2279     $dbh->do("UPDATE systempreferences SET variable='AmazonEnabled' WHERE variable = 'AmazonContent'");
2280
2281     $dbh->do("UPDATE systempreferences SET variable='OPACAmazonEnabled' WHERE variable = 'OPACAmazonContent'");
2282
2283     print "Upgrade to $DBversion done (added Syndetics Enhanced Content system preferences)\n";
2284     SetVersion ($DBversion);
2285 }
2286
2287 $DBversion = "3.01.00.016";
2288 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2289     $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')");
2290     print "Upgrade to $DBversion done (Added Babeltheque syspref)\n";
2291     SetVersion ($DBversion);
2292 }
2293
2294 $DBversion = "3.01.00.017";
2295 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2296     $dbh->do("ALTER TABLE `subscription` ADD `staffdisplaycount` VARCHAR(10) NULL;");
2297     $dbh->do("ALTER TABLE `subscription` ADD `opacdisplaycount` VARCHAR(10) NULL;");
2298     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2299     VALUES (
2300     'StaffSerialIssueDisplayCount', '3', '', 'Number of serial issues to display per subscription in the Staff client', 'Integer'
2301     );");
2302         $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2303     VALUES (
2304     'OPACSerialIssueDisplayCount', '3', '', 'Number of serial issues to display per subscription in the OPAC', 'Integer'
2305     );");
2306
2307     print "Upgrade to $DBversion done ( Updated table for Serials Display)\n";
2308     SetVersion ($DBversion);
2309 }
2310
2311 $DBversion = "3.01.00.018";
2312 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2313     $dbh->do("ALTER TABLE deletedborrowers ADD `smsalertnumber` varchar(50) default NULL");
2314     print "Upgrade to $DBversion done (added deletedborrowers.smsalertnumber, missed in 3.00.00.091)\n";
2315     SetVersion ($DBversion);
2316 }
2317
2318 $DBversion = "3.01.00.019";
2319 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2320         $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')");
2321     print "Upgrade to $DBversion done (adding OPACShowCheckoutName systempref)\n";
2322     SetVersion ($DBversion);
2323 }
2324
2325 $DBversion = "3.01.00.020";
2326 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2327     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesID','','See:http://librarything.com/forlibraries/','','free')");
2328     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesEnabled','0','Enable or Disable Library Thing for Libraries Features','','YesNo')");
2329     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesTabbedView','0','Put LibraryThingForLibraries Content in Tabs.','','YesNo')");
2330     print "Upgrade to $DBversion done (adding LibraryThing for Libraries sysprefs)\n";
2331     SetVersion ($DBversion);
2332 }
2333
2334 $DBversion = "3.01.00.021";
2335 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2336     my $enable_reviews = C4::Context->preference('OPACAmazonEnabled') ? '1' : '0';
2337     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAmazonReviews', '$enable_reviews', 'Display Amazon readers reviews on OPAC','','YesNo')");
2338     print "Upgrade to $DBversion done (adding OPACAmazonReviews syspref)\n";
2339     SetVersion ($DBversion);
2340 }
2341
2342 $DBversion = '3.01.00.022';
2343 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2344     $dbh->do("ALTER TABLE `labels_conf` MODIFY COLUMN `formatstring` mediumtext DEFAULT NULL");
2345     print "Upgrade to $DBversion done (bug 2945: increase size of labels_conf.formatstring)\n";
2346     SetVersion ($DBversion);
2347 }
2348
2349 $DBversion = '3.01.00.023';
2350 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2351     $dbh->do("ALTER TABLE biblioitems        MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2352     $dbh->do("ALTER TABLE deletedbiblioitems MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2353     $dbh->do("ALTER TABLE import_biblios     MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2354     $dbh->do("ALTER TABLE suggestions        MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2355     print "Upgrade to $DBversion done (bug 2765: increase width of isbn column in several tables)\n";
2356     SetVersion ($DBversion);
2357 }
2358
2359 $DBversion = "3.01.00.024";
2360 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2361     $dbh->do("ALTER TABLE labels MODIFY COLUMN batch_id int(10) NOT NULL default 1;");
2362     print "Upgrade to $DBversion done (change labels.batch_id from varchar to int)\n";
2363     SetVersion ($DBversion);
2364 }
2365
2366 $DBversion = '3.01.00.025';
2367 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2368     $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')");
2369
2370     print "Upgrade to $DBversion done (added ceilingDueDate system preference)\n";
2371     SetVersion ($DBversion);
2372 }
2373
2374 $DBversion = '3.01.00.026';
2375 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2376     $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')");
2377
2378     print "Upgrade to $DBversion done (added numReturnedItemsToShow system preference)\n";
2379     SetVersion ($DBversion);
2380 }
2381
2382 $DBversion = '3.01.00.027';
2383 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2384     $dbh->do("ALTER TABLE zebraqueue CHANGE `biblio_auth_number` `biblio_auth_number` bigint(20) unsigned NOT NULL default 0");
2385     print "Upgrade to $DBversion done (Increased size of zebraqueue biblio_auth_number to address bug 3148.)\n";
2386     SetVersion ($DBversion);
2387 }
2388
2389 $DBversion = '3.01.00.028';
2390 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2391     my $enable_reviews = C4::Context->preference('AmazonEnabled') ? '1' : '0';
2392     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AmazonReviews', '$enable_reviews', 'Display Amazon reviews on staff interface','','YesNo')");
2393     print "Upgrade to $DBversion done (added AmazonReviews)\n";
2394     SetVersion ($DBversion);
2395 }
2396
2397 $DBversion = '3.01.00.029';
2398 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2399     $dbh->do(q( UPDATE language_rfc4646_to_iso639
2400                 SET iso639_2_code = 'spa'
2401                 WHERE rfc4646_subtag = 'es'
2402                 AND   iso639_2_code = 'rus' )
2403             );
2404     print "Upgrade to $DBversion done (fixed bug 2599: using Spanish search limit retrieves Russian results)\n";
2405     SetVersion ($DBversion);
2406 }
2407
2408 $DBversion = "3.01.00.030";
2409 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2410     $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')");
2411     print "Upgrade to $DBversion done (added AllowNotForLoanOverride system preference)\n";
2412     SetVersion ($DBversion);
2413 }
2414
2415 $DBversion = "3.01.00.031";
2416 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2417     $dbh->do("ALTER TABLE branch_transfer_limits
2418               MODIFY toBranch   varchar(10) NOT NULL,
2419               MODIFY fromBranch varchar(10) NOT NULL,
2420               MODIFY itemtype   varchar(10) NULL");
2421     print "Upgrade to $DBversion done (fix column widths in branch_transfer_limits)\n";
2422     SetVersion ($DBversion);
2423 }
2424
2425 $DBversion = "3.01.00.032";
2426 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2427     $dbh->do(<<ENDOFRENEWAL);
2428 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');
2429 ENDOFRENEWAL
2430     print "Upgrade to $DBversion done (Change the field)\n";
2431     SetVersion ($DBversion);
2432 }
2433
2434 $DBversion = "3.01.00.033";
2435 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2436     $dbh->do(q/
2437         ALTER TABLE borrower_message_preferences
2438         MODIFY borrowernumber int(11) default NULL,
2439         ADD    categorycode varchar(10) default NULL AFTER borrowernumber,
2440         ADD KEY `categorycode` (`categorycode`),
2441         ADD CONSTRAINT `borrower_message_preferences_ibfk_3`
2442                        FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
2443                        ON DELETE CASCADE ON UPDATE CASCADE
2444     /);
2445     print "Upgrade to $DBversion done (DB changes to allow patron category defaults for messaging preferences)\n";
2446     SetVersion ($DBversion);
2447 }
2448
2449 $DBversion = "3.01.00.034";
2450 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2451     $dbh->do("ALTER TABLE `subscription` ADD COLUMN `graceperiod` INT(11) NOT NULL default '0';");
2452     print "Upgrade to $DBversion done (Adding graceperiod column to subscription table)\n";
2453     SetVersion ($DBversion);
2454 }
2455
2456 $DBversion = '3.01.00.035';
2457 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2458     $dbh->do(q{ ALTER TABLE `subscription` ADD location varchar(80) NULL DEFAULT '' AFTER callnumber; });
2459    print "Upgrade to $DBversion done (Adding location to subscription table)\n";
2460     SetVersion ($DBversion);
2461 }
2462
2463 $DBversion = '3.01.00.036';
2464 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2465     $dbh->do("UPDATE systempreferences SET explanation = 'Choose the default detail view in the staff interface; choose between normal, labeled_marc, marc or isbd'
2466               WHERE variable = 'IntranetBiblioDefaultView'
2467               AND   explanation = 'IntranetBiblioDefaultView'");
2468     $dbh->do("UPDATE systempreferences SET type = 'Choice', options = 'normal|marc|isbd|labeled_marc'
2469               WHERE variable = 'IntranetBiblioDefaultView'");
2470     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewISBD','1','Allow display of ISBD view of bibiographic records','','YesNo')");
2471     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewLabeledMARC','0','Allow display of labeled MARC view of bibiographic records','','YesNo')");
2472     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewMARC','1','Allow display of MARC view of bibiographic records','','YesNo')");
2473     print "Upgrade to $DBversion done (new viewISBD, viewLabeledMARC, viewMARC sysprefs and tweak IntranetBiblioDefaultView)\n";
2474     SetVersion ($DBversion);
2475 }
2476
2477 $DBversion = '3.01.00.037';
2478 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2479     $dbh->do('ALTER TABLE authorised_values ADD KEY `lib` (`lib`)');
2480     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('FilterBeforeOverdueReport','0','Do not run overdue report until filter selected','','YesNo')");
2481     SetVersion ($DBversion);
2482     print "Upgrade to $DBversion done (added FilterBeforeOverdueReport syspref and new index on authorised_values)\n";
2483 }
2484
2485 $DBversion = "3.01.00.038";
2486 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2487     # update branches table
2488     #
2489     $dbh->do("ALTER TABLE branches ADD `branchzip` varchar(25) default NULL AFTER `branchaddress3`");
2490     $dbh->do("ALTER TABLE branches ADD `branchcity` mediumtext AFTER `branchzip`");
2491     $dbh->do("ALTER TABLE branches ADD `branchcountry` text AFTER `branchcity`");
2492     $dbh->do("ALTER TABLE branches ADD `branchurl` mediumtext AFTER `branchemail`");
2493     $dbh->do("ALTER TABLE branches ADD `branchnotes` mediumtext AFTER `branchprinter`");
2494     print "Upgrade to $DBversion done (add ZIP, city, country, URL, and notes column to branches)\n";
2495     SetVersion ($DBversion);
2496 }
2497
2498 $DBversion = '3.01.00.039';
2499 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2500     $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')");
2501     $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')");
2502     SetVersion ($DBversion);
2503     print "Upgrade to $DBversion done (added SpineLabelFormat and SpineLabelAutoPrint sysprefs)\n";
2504 }
2505
2506 $DBversion = '3.01.00.040';
2507 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2508     $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')");
2509     $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')");
2510     SetVersion ($DBversion);
2511     print "Upgrade to $DBversion done (AllowHoldDateInFuture and OPACAllowHoldDateInFuture sysprefs)\n";
2512 }
2513
2514 $DBversion = '3.01.00.041';
2515 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2516     $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')");
2517     SetVersion ($DBversion);
2518     print "Upgrade to $DBversion done (added AWSPrivateKey syspref - note that if you use enhanced content from Amazon, this should be set right away.)\n";
2519 }
2520
2521 $DBversion = '3.01.00.042';
2522 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2523     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACFineNoRenewals','99999','Fine Limit above which user canmot renew books via OPAC','','Integer')");
2524     SetVersion ($DBversion);
2525     print "Upgrade to $DBversion done (added OPACFineNoRenewals syspref)\n";
2526 }
2527
2528 $DBversion = '3.01.00.043';
2529 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2530     $dbh->do('ALTER TABLE items ADD COLUMN permanent_location VARCHAR(80) DEFAULT NULL AFTER location');
2531     $dbh->do('UPDATE items SET permanent_location = location');
2532     $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 )', '')");
2533     $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')");
2534     $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')");
2535     SetVersion ($DBversion);
2536     print "Upgrade to $DBversion done (amended Item added NewItemsDefaultLocation, InProcessingToShelvingCart, ReturnToShelvingCart sysprefs)\n";
2537 }
2538
2539 $DBversion = '3.01.00.044';
2540 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2541     $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')");
2542     SetVersion ($DBversion);
2543     print "Upgrade to $DBversion done (added DisplayClearScreenButton system preference)\n";
2544 }
2545
2546 $DBversion = '3.01.00.045';
2547 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2548     $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')");
2549     SetVersion ($DBversion);
2550     print "Upgrade to $DBversion done (added a preference to hide the patrons name in the staff catalog)\n";
2551 }
2552
2553 $DBversion = "3.01.00.046";
2554 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2555     # update borrowers table
2556     #
2557     $dbh->do("ALTER TABLE borrowers ADD `country` text AFTER zipcode");
2558     $dbh->do("ALTER TABLE borrowers ADD `B_country` text AFTER B_zipcode");
2559     $dbh->do("ALTER TABLE deletedborrowers ADD `country` text AFTER zipcode");
2560     $dbh->do("ALTER TABLE deletedborrowers ADD `B_country` text AFTER B_zipcode");
2561     print "Upgrade to $DBversion done (add country and B_country to borrowers)\n";
2562     SetVersion ($DBversion);
2563 }
2564
2565 $DBversion = '3.01.00.047';
2566 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2567     $dbh->do("ALTER TABLE items MODIFY itemcallnumber varchar(255);");
2568     $dbh->do("ALTER TABLE deleteditems MODIFY itemcallnumber varchar(255);");
2569     $dbh->do("ALTER TABLE tmp_holdsqueue MODIFY itemcallnumber varchar(255);");
2570     SetVersion ($DBversion);
2571     print " Upgrade to $DBversion done (bug 2761: change max length of itemcallnumber to 255 from 30)\n";
2572 }
2573
2574 $DBversion = '3.01.00.048';
2575 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2576     $dbh->do("UPDATE userflags SET flagdesc='View Catalog (Librarian Interface)' WHERE bit=2;");
2577     $dbh->do("UPDATE userflags SET flagdesc='Edit Catalog (Modify bibliographic/holdings data)' WHERE bit=9;");
2578     $dbh->do("UPDATE userflags SET flagdesc='Allow to edit authorities' WHERE bit=14;");
2579     $dbh->do("UPDATE userflags SET flagdesc='Allow to access to the reports module' WHERE bit=16;");
2580     $dbh->do("UPDATE userflags SET flagdesc='Allow to manage serials subscriptions' WHERE bit=15;");
2581     SetVersion ($DBversion);
2582     print " Upgrade to $DBversion done (bug 2611: fix spelling/capitalization in permission flag descriptions)\n";
2583 }
2584
2585 $DBversion = '3.01.00.049';
2586 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2587     $dbh->do("UPDATE permissions SET description = 'Perform inventory (stocktaking) of your catalog' WHERE code = 'inventory';");
2588      SetVersion ($DBversion);
2589     print "Upgrade to $DBversion done (bug 2611: changed catalogue to catalog per the standard)\n";
2590 }
2591
2592 $DBversion = '3.01.00.050';
2593 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2594     $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');");
2595     SetVersion ($DBversion);
2596     print "Upgrade to $DBversion done (bug 1934: Add OPACSearchForTitleIn syspref)\n";
2597 }
2598
2599 $DBversion = '3.01.00.051';
2600 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2601     $dbh->do("UPDATE systempreferences SET explanation='Fine limit above which user cannot renew books via OPAC' WHERE variable='OPACFineNoRenewals';");
2602     $dbh->do("UPDATE systempreferences SET explanation='If set to ON, a clear screen button will appear on the circulation page.' WHERE variable='DisplayClearScreenButton';");
2603     SetVersion ($DBversion);
2604     print "Upgrade to $DBversion done (fixed typos in new sysprefs)\n";
2605 }
2606
2607 $DBversion = '3.01.00.052';
2608 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2609     $dbh->do('ALTER TABLE deleteditems ADD COLUMN permanent_location VARCHAR(80) DEFAULT NULL AFTER location');
2610     SetVersion ($DBversion);
2611     print "Upgrade to $DBversion done (bug 3481: add permanent_location column to deleteditems)\n";
2612 }
2613
2614 $DBversion = '3.01.00.053';
2615 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2616     my $upgrade_script = C4::Context->config("intranetdir") . "/installer/data/mysql/labels_upgrade.pl";
2617     system("perl $upgrade_script");
2618     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";
2619     SetVersion ($DBversion);
2620 }
2621
2622 $DBversion = '3.01.00.054';
2623 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2624     $dbh->do("ALTER TABLE borrowers ADD `B_address2` text AFTER B_address");
2625     $dbh->do("ALTER TABLE borrowers ADD `altcontactcountry` text AFTER altcontactzipcode");
2626     $dbh->do("ALTER TABLE deletedborrowers ADD `B_address2` text AFTER B_address");
2627     $dbh->do("ALTER TABLE deletedborrowers ADD `altcontactcountry` text AFTER altcontactzipcode");
2628     SetVersion ($DBversion);
2629     print "Upgrade to $DBversion done (bug 1600, bug 3454: add altcontactcountry and B_address2 to borrowers and deletedborrowers)\n";
2630 }
2631
2632 $DBversion = '3.01.00.055';
2633 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2634     $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'|);
2635     SetVersion ($DBversion);
2636     print "Upgrade to $DBversion done (changed OPACSearchForTitleIn per requests in bug 1934)\n";
2637 }
2638
2639 $DBversion = '3.01.00.056';
2640 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2641     $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');");
2642     SetVersion ($DBversion);
2643     print "Upgrade to $DBversion done (Bug 1172 : Add OPACPatronDetails syspref)\n";
2644 }
2645
2646 $DBversion = '3.01.00.057';
2647 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2648     $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');");
2649     SetVersion ($DBversion);
2650     print "Upgrade to $DBversion done (Bug 2576 : Add OPACFinesTab syspref)\n";
2651 }
2652
2653 $DBversion = '3.01.00.058';
2654 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2655     $dbh->do("ALTER TABLE `language_subtag_registry` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2656     $dbh->do("ALTER TABLE `language_rfc4646_to_iso639` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2657     $dbh->do("ALTER TABLE `language_descriptions` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2658     SetVersion ($DBversion);
2659     print "Upgrade to $DBversion done (Added primary keys to language tables)\n";
2660 }
2661
2662 $DBversion = '3.01.00.059';
2663 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2664     $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')");
2665     SetVersion ($DBversion);
2666     print "Upgrade to $DBversion done (added DisplayOPACiconsXSLT sysprefs)\n";
2667 }
2668
2669 $DBversion = '3.01.00.060';
2670 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2671     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowAllMessageDeletion','0','Allow any Library to delete any message','','YesNo');");
2672     $dbh->do('DROP TABLE IF EXISTS messages');
2673     $dbh->do("CREATE TABLE messages ( `message_id` int(11) NOT NULL auto_increment,
2674         `borrowernumber` int(11) NOT NULL,
2675         `branchcode` varchar(4) default NULL,
2676         `message_type` varchar(1) NOT NULL,
2677         `message` text NOT NULL,
2678         `message_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
2679         PRIMARY KEY (`message_id`)
2680         ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
2681
2682         print "Upgrade to $DBversion done ( Added AllowAllMessageDeletion syspref and messages table )\n";
2683     SetVersion ($DBversion);
2684 }
2685
2686 $DBversion = '3.01.00.061';
2687 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2688     $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')");
2689         print "Upgrade to $DBversion done ( Added ShowPatronImageInWebBasedSelfCheck system preference )\n";
2690     SetVersion ($DBversion);
2691 }
2692
2693 $DBversion = "3.01.00.062";
2694 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2695     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'manage_csv_profiles', 'Manage CSV export profiles')");
2696     $dbh->do(q/
2697         CREATE TABLE `export_format` (
2698           `export_format_id` int(11) NOT NULL auto_increment,
2699           `profile` varchar(255) NOT NULL,
2700           `description` mediumtext NOT NULL,
2701           `marcfields` mediumtext NOT NULL,
2702           PRIMARY KEY  (`export_format_id`)
2703         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Used for CSV export';
2704     /);
2705     print "Upgrade to $DBversion done (added csv export profiles)\n";
2706 }
2707
2708 $DBversion = "3.01.00.063";
2709 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2710     $dbh->do("
2711         CREATE TABLE `fieldmapping` (
2712           `id` int(11) NOT NULL auto_increment,
2713           `field` varchar(255) NOT NULL,
2714           `frameworkcode` char(4) NOT NULL default '',
2715           `fieldcode` char(3) NOT NULL,
2716           `subfieldcode` char(1) NOT NULL,
2717           PRIMARY KEY  (`id`)
2718         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2719              ");
2720     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";
2721 }
2722
2723 $DBversion = '3.01.00.065';
2724 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2725     $dbh->do('ALTER TABLE issuingrules ADD COLUMN `renewalsallowed` smallint(6) NOT NULL default "0" AFTER `issuelength`;');
2726     $sth = $dbh->prepare("SELECT itemtype, renewalsallowed FROM itemtypes");
2727     $sth->execute();
2728
2729     my $sthupd = $dbh->prepare("UPDATE issuingrules SET renewalsallowed = ? WHERE itemtype = ?");
2730
2731     while(my $row = $sth->fetchrow_hashref){
2732         $sthupd->execute($row->{renewalsallowed}, $row->{itemtype});
2733     }
2734
2735     $dbh->do('ALTER TABLE itemtypes DROP COLUMN `renewalsallowed`;');
2736
2737     SetVersion ($DBversion);
2738     print "Upgrade to $DBversion done (Moving allowed renewals from itemtypes to issuingrule)\n";
2739 }
2740
2741 $DBversion = '3.01.00.066';
2742 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2743     $dbh->do('ALTER TABLE issuingrules ADD COLUMN `reservesallowed` smallint(6) NOT NULL default "0" AFTER `renewalsallowed`;');
2744
2745     my $maxreserves = C4::Context->preference('maxreserves');
2746     $sth = $dbh->prepare('UPDATE issuingrules SET reservesallowed = ?;');
2747     $sth->execute($maxreserves);
2748
2749     $dbh->do('DELETE FROM systempreferences WHERE variable = "maxreserves";');
2750
2751     $dbh->do("INSERT INTO systempreferences (variable,value, options, explanation, type) VALUES('ReservesControlBranch','PatronLibrary','ItemHomeLibrary|PatronLibrary','Branch checked for members reservations rights','Choice')");
2752
2753     SetVersion ($DBversion);
2754     print "Upgrade to $DBversion done (Moving max allowed reserves from system preference to issuingrule)\n";
2755 }
2756
2757 $DBversion = "3.01.00.067";
2758 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2759     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'batchmod', 'Perform batch modification of items')");
2760     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'batchdel', 'Perform batch deletion of items')");
2761     print "Upgrade to $DBversion done (added permissions for batch modification and deletion)\n";
2762     SetVersion ($DBversion);
2763 }
2764
2765 $DBversion = "3.01.00.068";
2766 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2767         $dbh->do("ALTER TABLE issuingrules ADD COLUMN `finedays` int(11) default NULL AFTER `fine` ");
2768         print "Upgrade to $DBversion done (Adding finedays in issuingrules table)\n";
2769     SetVersion ($DBversion);
2770 }
2771
2772
2773 $DBversion = "3.01.00.069";
2774 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2775         $dbh->do("INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('EnableOpacSearchHistory', '1', '', 'Enable or disable opac search history', 'YesNo')");
2776
2777         my $create = <<SEARCHHIST;
2778 CREATE TABLE IF NOT EXISTS `search_history` (
2779   `userid` int(11) NOT NULL,
2780   `sessionid` varchar(32) NOT NULL,
2781   `query_desc` varchar(255) NOT NULL,
2782   `query_cgi` varchar(255) NOT NULL,
2783   `total` int(11) NOT NULL,
2784   `time` timestamp NOT NULL default CURRENT_TIMESTAMP,
2785   KEY `userid` (`userid`),
2786   KEY `sessionid` (`sessionid`)
2787 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Opac search history results';
2788 SEARCHHIST
2789         $dbh->do($create);
2790
2791         print "Upgrade to $DBversion done (added OPAC search history preference and table)\n";
2792 }
2793
2794 $DBversion = "3.01.00.070";
2795 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2796         $dbh->do("ALTER TABLE authorised_values ADD COLUMN `lib_opac` VARCHAR(80) default NULL AFTER `lib`");
2797         print "Upgrade to $DBversion done (Added a lib_opac field in authorised_values table)\n";
2798 }
2799
2800 $DBversion = "3.01.00.071";
2801 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2802         $dbh->do("ALTER TABLE `subscription` ADD `enddate` date default NULL");
2803         $dbh->do("ALTER TABLE subscriptionhistory CHANGE enddate histenddate DATE default NULL");
2804         print "Upgrade to $DBversion done ( Adding enddate to subscription)\n";
2805 }
2806
2807 # Acquisitions update
2808
2809 $DBversion = "3.01.00.072";
2810 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2811     $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')");
2812     # create a new syspref for the 'Mr anonymous' patron
2813     $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,'')");
2814     # fill AnonymousPatron with AnonymousSuggestion value (copy)
2815     my $sth=$dbh->prepare("SELECT value FROM systempreferences WHERE variable='AnonSuggestions'");
2816     $sth->execute;
2817     my ($value) = $sth->fetchrow() || 0;
2818     $dbh->do("UPDATE systempreferences SET value='$value' WHERE variable='AnonymousPatron'");
2819     # set AnonymousSuggestion do YesNo
2820     # 1st, set the value (1/True if it had a borrowernumber)
2821     $dbh->do("UPDATE systempreferences SET value=1 WHERE variable='AnonSuggestions' AND value>0");
2822     # 2nd, change the type to Choice
2823     $dbh->do("UPDATE systempreferences SET type='YesNo' WHERE variable='AnonSuggestions'");
2824         # borrower reading record privacy : 0 : forever, 1 : laws, 2 : don't keep at all
2825     $dbh->do("ALTER TABLE `borrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
2826     print "Upgrade to $DBversion done (add new syspref and column in borrowers)\n";
2827     SetVersion ($DBversion);
2828 }
2829
2830 $DBversion = '3.01.00.073';
2831 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2832     $dbh->do('SET FOREIGN_KEY_CHECKS=0 ');
2833     $dbh->do(<<'END_SQL');
2834 CREATE TABLE IF NOT EXISTS `aqcontract` (
2835   `contractnumber` int(11) NOT NULL auto_increment,
2836   `contractstartdate` date default NULL,
2837   `contractenddate` date default NULL,
2838   `contractname` varchar(50) default NULL,
2839   `contractdescription` mediumtext,
2840   `booksellerid` int(11) not NULL,
2841     PRIMARY KEY  (`contractnumber`),
2842         CONSTRAINT `booksellerid_fk1` FOREIGN KEY (`booksellerid`)
2843         REFERENCES `aqbooksellers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
2844 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
2845 END_SQL
2846     $dbh->do('SET FOREIGN_KEY_CHECKS=1 ');
2847     print "Upgrade to $DBversion done (adding aqcontract table)\n";
2848     SetVersion ($DBversion);
2849 }
2850
2851 $DBversion = '3.01.00.074';
2852 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2853     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `basketname` varchar(50) default NULL AFTER `basketno`");
2854     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `note` mediumtext AFTER `basketname`");
2855     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `booksellernote` mediumtext AFTER `note`");
2856     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `contractnumber` int(11) AFTER `booksellernote`");
2857     $dbh->do("ALTER TABLE `aqbasket` ADD FOREIGN KEY (`contractnumber`) REFERENCES `aqcontract` (`contractnumber`)");
2858     print "Upgrade to $DBversion done (edit aqbasket table done)\n";
2859     SetVersion ($DBversion);
2860 }
2861
2862 $DBversion = '3.01.00.075';
2863 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2864     $dbh->do("ALTER TABLE `aqorders` ADD COLUMN `uncertainprice` tinyint(1)");
2865
2866     print "Upgrade to $DBversion done (adding uncertainprices)\n";
2867     SetVersion ($DBversion);
2868 }
2869
2870 $DBversion = '3.01.00.076';
2871 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2872     $dbh->do('SET FOREIGN_KEY_CHECKS=0 ');
2873     $dbh->do("CREATE TABLE IF NOT EXISTS `aqbasketgroups` (
2874                          `id` int(11) NOT NULL auto_increment,
2875                          `name` varchar(50) default NULL,
2876                          `closed` tinyint(1) default NULL,
2877                          `booksellerid` int(11) NOT NULL,
2878                          PRIMARY KEY (`id`),
2879                          KEY `booksellerid` (`booksellerid`),
2880                          CONSTRAINT `aqbasketgroups_ibfk_1` FOREIGN KEY (`booksellerid`) REFERENCES `aqbooksellers` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
2881                          ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
2882     $dbh->do("ALTER TABLE aqbasket ADD COLUMN `basketgroupid` int(11)");
2883     $dbh->do("ALTER TABLE aqbasket ADD FOREIGN KEY (`basketgroupid`) REFERENCES `aqbasketgroups` (`id`) ON UPDATE CASCADE ON DELETE SET NULL");
2884     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('pdfformat','pdfformat::layout2pages','Controls what script is used for printing (basketgroups)','','free')");
2885     $dbh->do('SET FOREIGN_KEY_CHECKS=1 ');
2886     print "Upgrade to $DBversion done (adding basketgroups)\n";
2887     SetVersion ($DBversion);
2888 }
2889 $DBversion = '3.01.00.077';
2890 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2891
2892     $dbh->do("SET FOREIGN_KEY_CHECKS=0 ");
2893     # create a mapping table holding the info we need to match orders to budgets
2894     $dbh->do('DROP TABLE IF EXISTS fundmapping');
2895     $dbh->do(
2896         q|CREATE TABLE fundmapping AS
2897         SELECT aqorderbreakdown.ordernumber, branchcode, bookfundid, budgetdate, entrydate
2898         FROM aqorderbreakdown JOIN aqorders ON aqorderbreakdown.ordernumber = aqorders.ordernumber|);
2899     # match the new type of the corresponding field
2900     $dbh->do('ALTER TABLE fundmapping modify column bookfundid varchar(30)');
2901     # System did not ensure budgetdate was valid historically
2902     $dbh->do(q|UPDATE fundmapping SET budgetdate = entrydate WHERE budgetdate = '0000-00-00' OR budgetdate IS NULL|);
2903     # We save the map in fundmapping in case you need later processing
2904     $dbh->do(q|ALTER TABLE fundmapping add column aqbudgetid integer|);
2905     # these can speed processing up
2906     $dbh->do(q|CREATE INDEX fundmaporder ON fundmapping (ordernumber)|);
2907     $dbh->do(q|CREATE INDEX fundmapid ON fundmapping (bookfundid)|);
2908
2909     $dbh->do("DROP TABLE IF EXISTS `aqbudgetperiods` ");
2910
2911     $dbh->do(qq|
2912                     CREATE TABLE `aqbudgetperiods` (
2913                     `budget_period_id` int(11) NOT NULL auto_increment,
2914                     `budget_period_startdate` date NOT NULL,
2915                     `budget_period_enddate` date NOT NULL,
2916                     `budget_period_active` tinyint(1) default '0',
2917                     `budget_period_description` mediumtext,
2918                     `budget_period_locked` tinyint(1) default NULL,
2919                     `sort1_authcat` varchar(10) default NULL,
2920                     `sort2_authcat` varchar(10) default NULL,
2921                     PRIMARY KEY  (`budget_period_id`)
2922                     ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 |);
2923
2924    $dbh->do(<<ADDPERIODS);
2925 INSERT INTO aqbudgetperiods (budget_period_startdate,budget_period_enddate,budget_period_active,budget_period_description,budget_period_locked)
2926 SELECT DISTINCT startdate, enddate, NOW() BETWEEN startdate and enddate, concat(startdate," ",enddate),NOT NOW() BETWEEN startdate AND enddate from aqbudget
2927 ADDPERIODS
2928 # SORRY , NO AQBUDGET/AQBOOKFUND -> AQBUDGETS IMPORT JUST YET,
2929 # BUT A NEW CLEAN AQBUDGETS TABLE CREATE FOR NOW..
2930 # DROP TABLE IF EXISTS `aqbudget`;
2931 #CREATE TABLE `aqbudget` (
2932 #  `bookfundid` varchar(10) NOT NULL default ',
2933 #    `startdate` date NOT NULL default 0,
2934 #         `enddate` date default NULL,
2935 #           `budgetamount` decimal(13,2) default NULL,
2936 #                 `aqbudgetid` tinyint(4) NOT NULL auto_increment,
2937 #                   `branchcode` varchar(10) default NULL,
2938     DropAllForeignKeys('aqbudget');
2939   #$dbh->do("drop table aqbudget;");
2940
2941
2942     my $maxbudgetid = $dbh->selectcol_arrayref(<<IDsBUDGET);
2943 SELECT MAX(aqbudgetid) from aqbudget
2944 IDsBUDGET
2945
2946 $$maxbudgetid[0] = 0 if !$$maxbudgetid[0];
2947
2948     $dbh->do(<<BUDGETAUTOINCREMENT);
2949 ALTER TABLE aqbudget AUTO_INCREMENT=$$maxbudgetid[0]
2950 BUDGETAUTOINCREMENT
2951
2952     $dbh->do(<<BUDGETNAME);
2953 ALTER TABLE aqbudget RENAME `aqbudgets`
2954 BUDGETNAME
2955
2956     $dbh->do(<<BUDGETS);
2957 ALTER TABLE `aqbudgets`
2958    CHANGE  COLUMN aqbudgetid `budget_id` int(11) NOT NULL AUTO_INCREMENT,
2959    CHANGE  COLUMN branchcode `budget_branchcode` varchar(10) default NULL,
2960    CHANGE  COLUMN budgetamount `budget_amount` decimal(28,6) NOT NULL default '0.00',
2961    CHANGE  COLUMN bookfundid   `budget_code` varchar(30) default NULL,
2962    ADD     COLUMN `budget_parent_id` int(11) default NULL,
2963    ADD     COLUMN `budget_name` varchar(80) default NULL,
2964    ADD     COLUMN `budget_encumb` decimal(28,6) default '0.00',
2965    ADD     COLUMN `budget_expend` decimal(28,6) default '0.00',
2966    ADD     COLUMN `budget_notes` mediumtext,
2967    ADD     COLUMN `budget_description` mediumtext,
2968    ADD     COLUMN `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
2969    ADD     COLUMN `budget_amount_sublevel`  decimal(28,6) AFTER `budget_amount`,
2970    ADD     COLUMN `budget_period_id` int(11) default NULL,
2971    ADD     COLUMN `sort1_authcat` varchar(80) default NULL,
2972    ADD     COLUMN `sort2_authcat` varchar(80) default NULL,
2973    ADD     COLUMN `budget_owner_id` int(11) default NULL,
2974    ADD     COLUMN `budget_permission` int(1) default '0';
2975 BUDGETS
2976
2977     $dbh->do(<<BUDGETCONSTRAINTS);
2978 ALTER TABLE `aqbudgets`
2979    ADD CONSTRAINT `aqbudgets_ifbk_1` FOREIGN KEY (`budget_period_id`) REFERENCES `aqbudgetperiods` (`budget_period_id`) ON DELETE CASCADE ON UPDATE CASCADE
2980 BUDGETCONSTRAINTS
2981 #    $dbh->do(<<BUDGETPKDROP);
2982 #ALTER TABLE `aqbudgets`
2983 #   DROP PRIMARY KEY
2984 #BUDGETPKDROP
2985 #    $dbh->do(<<BUDGETPKADD);
2986 #ALTER TABLE `aqbudgets`
2987 #   ADD PRIMARY KEY budget_id
2988 #BUDGETPKADD
2989
2990
2991         my $query_period= $dbh->prepare(qq|SELECT budget_period_id from aqbudgetperiods where budget_period_startdate=? and budget_period_enddate=?|);
2992         my $query_bookfund= $dbh->prepare(qq|SELECT * from aqbookfund where bookfundid=?|);
2993         my $selectbudgets=$dbh->prepare(qq|SELECT * from aqbudgets|);
2994         my $updatebudgets=$dbh->prepare(qq|UPDATE aqbudgets SET budget_period_id= ? , budget_name=?, budget_branchcode=? where budget_id=?|);
2995         $selectbudgets->execute;
2996         while (my $databudget=$selectbudgets->fetchrow_hashref){
2997                 $query_period->execute ($$databudget{startdate},$$databudget{enddate});
2998                 my ($budgetperiodid)=$query_period->fetchrow;
2999                 $query_bookfund->execute ($$databudget{budget_code});
3000                 my $databf=$query_bookfund->fetchrow_hashref;
3001                 my $branchcode=$$databudget{budget_branchcode}||$$databf{branchcode};
3002                 $updatebudgets->execute($budgetperiodid,$$databf{bookfundname},$branchcode,$$databudget{budget_id});
3003         }
3004     $dbh->do(<<BUDGETDROPDATES);
3005 ALTER TABLE `aqbudgets`
3006    DROP startdate,
3007    DROP enddate
3008 BUDGETDROPDATES
3009
3010
3011     $dbh->do("DROP TABLE IF EXISTS `aqbudgets_planning` ");
3012     $dbh->do("CREATE TABLE  `aqbudgets_planning` (
3013                     `plan_id` int(11) NOT NULL auto_increment,
3014                     `budget_id` int(11) NOT NULL,
3015                     `budget_period_id` int(11) NOT NULL,
3016                     `estimated_amount` decimal(28,6) default NULL,
3017                     `authcat` varchar(30) NOT NULL,
3018                     `authvalue` varchar(30) NOT NULL,
3019                                         `display` tinyint(1) DEFAULT 1,
3020                         PRIMARY KEY  (`plan_id`),
3021                         CONSTRAINT `aqbudgets_planning_ifbk_1` FOREIGN KEY (`budget_id`) REFERENCES `aqbudgets` (`budget_id`) ON DELETE CASCADE ON UPDATE CASCADE
3022                         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
3023
3024     $dbh->do("ALTER TABLE `aqorders`
3025                     ADD COLUMN `budget_id` tinyint(4) NOT NULL,
3026                     ADD COLUMN `budgetgroup_id` int(11) NOT NULL,
3027                     ADD COLUMN  `sort1_authcat` varchar(10) default NULL,
3028                     ADD COLUMN  `sort2_authcat` varchar(10) default NULL" );
3029                 # We need to map the orders to the budgets
3030                 # For Historic reasons this is more complex than it should be on occasions
3031                 my $budg_arr = $dbh->selectall_arrayref(
3032                     q|SELECT aqbudgets.budget_id, aqbudgets.budget_code, aqbudgetperiods.budget_period_startdate,
3033                     aqbudgetperiods.budget_period_enddate
3034                     FROM aqbudgets JOIN aqbudgetperiods ON aqbudgets.budget_period_id = aqbudgetperiods.budget_period_id
3035                     ORDER BY budget_code, budget_period_startdate|, { Slice => {} });
3036                 # We arbitarily order on start date, this means if you have overlapping periods the order will be
3037                 # linked to the latest matching budget YMMV
3038                 my $b_sth = $dbh->prepare(
3039                     'UPDATE fundmapping set aqbudgetid = ? where bookfundid =? AND budgetdate >= ? AND budgetdate <= ?');
3040                 for my $b ( @{$budg_arr}) {
3041                     $b_sth->execute($b->{budget_id}, $b->{budget_code}, $b->{budget_period_startdate}, $b->{budget_period_enddate});
3042                 }
3043                 # move the budgetids to aqorders
3044                 $dbh->do(q|UPDATE aqorders, fundmapping SET aqorders.budget_id = fundmapping.aqbudgetid
3045                     WHERE aqorders.ordernumber = fundmapping.ordernumber AND fundmapping.aqbudgetid IS NOT NULL|);
3046                 # NB fundmapping is left as an accontants trail also if you have budgetids that werent set
3047                 # you can decide what to do with them
3048
3049      $dbh->do(
3050          q|UPDATE aqorders, aqbudgets SET aqorders.budgetgroup_id = aqbudgets.budget_period_id
3051          WHERE aqorders.budget_id = aqbudgets.budget_id|);
3052                 # cannot do until aqorderbreakdown removed
3053 #    $dbh->do("DROP TABLE aqbookfund ");
3054 #    $dbh->do("ALTER TABLE aqorders  ADD FOREIGN KEY (`budget_id`) REFERENCES `aqbudgets` (`budget_id`) ON UPDATE CASCADE  " ); ????
3055     $dbh->do("SET FOREIGN_KEY_CHECKS=1 ");
3056
3057     print "Upgrade to $DBversion done (Adding new aqbudgetperiods, aqbudgets and aqbudget_planning tables  )\n";
3058     SetVersion ($DBversion);
3059 }
3060
3061
3062
3063 $DBversion = '3.01.00.078';
3064 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3065     $dbh->do("ALTER TABLE aqbudgetperiods ADD COLUMN budget_period_total decimal(28,6)");
3066     print "Upgrade to $DBversion done (adds 'budget_period_total' column to aqbudgetperiods table)\n";
3067     SetVersion($DBversion);
3068 }
3069
3070
3071 $DBversion = '3.01.00.079';
3072 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3073     $dbh->do("ALTER TABLE currency ADD COLUMN active  tinyint(1)");
3074
3075     print "Upgrade to $DBversion done (adds 'active' column to currencies table)\n";
3076     SetVersion($DBversion);
3077 }
3078
3079 $DBversion = '3.01.00.080';
3080 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3081     $dbh->do(<<BUDG_PERM );
3082 INSERT INTO permissions (module_bit, code, description) VALUES
3083             (11, 'vendors_manage', 'Manage vendors'),
3084             (11, 'contracts_manage', 'Manage contracts'),
3085             (11, 'period_manage', 'Manage periods'),
3086             (11, 'budget_manage', 'Manage budgets'),
3087             (11, 'budget_modify', "Modify budget (can't create lines but can modify existing ones)"),
3088             (11, 'planning_manage', 'Manage budget plannings'),
3089             (11, 'order_manage', 'Manage orders & basket'),
3090             (11, 'group_manage', 'Manage orders & basketgroups'),
3091             (11, 'order_receive', 'Manage orders & basket'),
3092             (11, 'budget_add_del', "Add and delete budgets (but can't modify budgets)");
3093 BUDG_PERM
3094
3095     print "Upgrade to $DBversion done (adds permissions for the acquisitions module)\n";
3096     SetVersion($DBversion);
3097 }
3098
3099
3100 $DBversion = '3.01.00.081';
3101 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3102     $dbh->do("ALTER TABLE aqbooksellers ADD COLUMN `gstrate` decimal(6,4) default NULL");
3103     if (my $gist=C4::Context->preference("gist")){
3104                 my $sql=$dbh->prepare("UPDATE aqbooksellers set `gstrate`=? ");
3105         $sql->execute($gist) ;
3106         }
3107     print "Upgrade to $DBversion done (added per-supplier gstrate setting)\n";
3108     SetVersion($DBversion);
3109 }
3110
3111 $DBversion = "3.01.00.082";
3112 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3113     if (C4::Context->preference("opaclanguages") eq "fr") {
3114         $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')#);
3115     } else {
3116         $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')");
3117     }
3118     print "Upgrade to $DBversion done (adding ReservesNeedReturns systempref, in circulation)\n";
3119     SetVersion ($DBversion);
3120 }
3121
3122 $DBversion = "3.01.00.083";
3123 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3124     $dbh->do(qq|
3125  CREATE TABLE `aqorders_items` (
3126   `ordernumber` int(11) NOT NULL,
3127   `itemnumber` int(11) NOT NULL,
3128   `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
3129   PRIMARY KEY  (`itemnumber`),
3130   KEY `ordernumber` (`ordernumber`)
3131 ) ENGINE=InnoDB DEFAULT CHARSET=utf8   |
3132     );
3133
3134     $dbh->do(qq| DROP TABLE aqorderbreakdown |);
3135     $dbh->do('DROP TABLE aqbookfund');
3136     print "Upgrade to $DBversion done (New aqorders_items table for acqui)\n";
3137     SetVersion ($DBversion);
3138 }
3139
3140 $DBversion = "3.01.00.084";
3141 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3142     $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')  #);
3143
3144     print "Upgrade to $DBversion done (CurrencyFormat syspref added)\n";
3145     SetVersion ($DBversion);
3146 }
3147
3148 $DBversion = "3.01.00.085";
3149 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3150     $dbh->do("ALTER table aqorders drop column title");
3151     $dbh->do("ALTER TABLE `aqorders` CHANGE `budget_id` `budget_id` INT( 11 ) NOT NULL");
3152     print "Upgrade to $DBversion done update budget_id size that should not be a tinyint\n";
3153     SetVersion ($DBversion);
3154 }
3155
3156 $DBversion = "3.01.00.086";
3157 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3158     $dbh->do(<<SUGGESTIONS);
3159 ALTER table suggestions
3160     ADD budgetid INT(11),
3161     ADD branchcode VARCHAR(10) default NULL,
3162     ADD acceptedby INT(11) default NULL,
3163     ADD accepteddate date default NULL,
3164     ADD suggesteddate date default NULL,
3165     ADD manageddate date default NULL,
3166     ADD rejectedby INT(11) default NULL,
3167     ADD rejecteddate date default NULL,
3168     ADD collectiontitle text default NULL,
3169     ADD itemtype VARCHAR(30) default NULL
3170     ;
3171 SUGGESTIONS
3172     print "Upgrade to $DBversion done (Suggestions)\n";
3173     SetVersion ($DBversion);
3174 }
3175
3176 $DBversion = "3.01.00.087";
3177 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3178     $dbh->do("ALTER table aqbudgets drop column budget_amount_sublevel;");
3179     print "Upgrade to $DBversion done (Drop column budget_amount_sublevel from aqbudgets)\n";
3180     SetVersion ($DBversion);
3181 }
3182
3183 $DBversion = "3.01.00.088";
3184 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3185     $dbh->do(  qq# INSERT INTO `systempreferences` VALUES ('intranetbookbag','1','','If ON, enables display of Cart feature in the intranet','YesNo')  #);
3186
3187     print "Upgrade to $DBversion done (intranetbookbag syspref added)\n";
3188     SetVersion ($DBversion);
3189 }
3190
3191 $DBversion = "3.01.00.090";
3192 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3193 $dbh->do("
3194        INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3195                 (16, 'execute_reports', 'Execute SQL reports'),
3196                 (16, 'create_reports', 'Create SQL Reports')
3197         ");
3198
3199     print "Upgrade to $DBversion done (granular permissions for guided reports added)\n";
3200     SetVersion ($DBversion);
3201 }
3202
3203 $DBversion = "3.01.00.091";
3204 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3205 $dbh->do("
3206         UPDATE `systempreferences` SET `options` = 'holdings|serialcollection|subscriptions'
3207         WHERE `systempreferences`.`variable` = 'opacSerialDefaultTab' LIMIT 1
3208         ");
3209
3210     print "Upgrade to $DBversion done (opac-detail default tag updated)\n";
3211     SetVersion ($DBversion);
3212 }
3213
3214 $DBversion = "3.01.00.092";
3215 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3216     if (C4::Context->preference("opaclanguages") =~ /fr/) {
3217         $dbh->do(qq{
3218 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');
3219         });
3220         }else{
3221         $dbh->do(qq{
3222 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');
3223         });
3224         }
3225     print "Upgrade to $DBversion done (Added RoutingListAddReserves syspref)\n";
3226     SetVersion ($DBversion);
3227 }
3228
3229 $DBversion = "3.01.00.093";
3230 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3231         $dbh->do(qq{
3232         ALTER TABLE biblioitems ADD INDEX issn_idx (issn);
3233         });
3234     print "Upgrade to $DBversion done (added index to ISSN)\n";
3235     SetVersion ($DBversion);
3236 }
3237
3238 $DBversion = "3.01.00.094";
3239 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3240         $dbh->do(qq{
3241         ALTER TABLE aqbasketgroups ADD deliveryplace VARCHAR(10) default NULL, ADD deliverycomment VARCHAR(255) default NULL;
3242         });
3243
3244     print "Upgrade to $DBversion done (adding deliveryplace deliverycomment to basketgroups)\n";
3245     SetVersion ($DBversion);
3246 }
3247
3248 $DBversion = "3.01.00.095";
3249 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3250         $dbh->do(qq{
3251         ALTER TABLE items ADD stocknumber VARCHAR(32) DEFAULT NULL COMMENT "stores the inventory number";
3252         });
3253         $dbh->do(qq{
3254         ALTER TABLE items ADD UNIQUE INDEX itemsstocknumberidx (stocknumber);
3255         });
3256         $dbh->do(qq{
3257         ALTER TABLE deleteditems ADD stocknumber VARCHAR(32) DEFAULT NULL COMMENT "stores the inventory number of deleted items";
3258         });
3259         $dbh->do(qq{
3260         ALTER TABLE deleteditems ADD UNIQUE INDEX deleteditemsstocknumberidx (stocknumber);
3261         });
3262         if (C4::Context->preference('marcflavour') eq 'UNIMARC'){
3263                 $dbh->do(qq{
3264         INSERT IGNORE INTO marc_subfield_structure (frameworkcode,tagfield, tagsubfield, tab, repeatable, mandatory,kohafield)
3265         SELECT DISTINCT (frameworkcode),995,"j",10,0,0,"items.stocknumber" from biblio_framework ;
3266                 });
3267                 #Previously, copynumber was used as stocknumber
3268                 $dbh->do(qq{
3269         UPDATE items set stocknumber=copynumber;
3270                 });
3271                 $dbh->do(qq{
3272         UPDATE items set copynumber=NULL;
3273                 });
3274         }
3275     print "Upgrade to $DBversion done (stocknumber field added)\n";
3276     SetVersion ($DBversion);
3277 }
3278
3279 $DBversion = "3.01.00.096";
3280 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3281     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OrderPdfTemplate','','Uploads a PDF template to use for printing baskets','NULL','Upload')");
3282     $dbh->do("UPDATE systempreferences SET variable='OrderPdfFormat' WHERE variable='pdfformat'");
3283     print "Upgrade to $DBversion done (PDF orders system preferences added and updated)\n";
3284     SetVersion ($DBversion);
3285 }
3286
3287 $DBversion = "3.01.00.097";
3288 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3289         $dbh->do(qq{
3290         ALTER TABLE aqbasketgroups ADD billingplace VARCHAR(10) NOT NULL AFTER deliverycomment;
3291         });
3292
3293     print "Upgrade to $DBversion done (Adding billingplace to aqbasketgroups)\n";
3294     SetVersion ($DBversion);
3295 }
3296
3297 $DBversion = "3.01.00.098";
3298 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3299         $dbh->do(qq{
3300         ALTER TABLE auth_subfield_structure MODIFY frameworkcode VARCHAR(10) NULL;
3301         });
3302
3303     print "Upgrade to $DBversion done (changing frameworkcode length in auth_subfield_structure)\n";
3304     SetVersion ($DBversion);
3305 }
3306
3307 $DBversion = "3.01.00.099";
3308 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3309         $dbh->do(qq{
3310                 INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3311                 (9, 'edit_catalogue', 'Edit catalogue'),
3312                 (9, 'fast_cataloging', 'Fast cataloging')
3313         });
3314
3315     print "Upgrade to $DBversion done (granular permissions for cataloging added)\n";
3316     SetVersion ($DBversion);
3317 }
3318
3319 $DBversion = "3.01.00.100";
3320 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3321         $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')");
3322         print "Upgrade to $DBversion done (added CAS authentication system preferences)\n";
3323     SetVersion ($DBversion);
3324 }
3325
3326 $DBversion = "3.01.00.101";
3327 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3328         $dbh->do(
3329         "INSERT INTO systempreferences
3330            (variable, value, options, explanation, type)
3331          VALUES (
3332             'OverdueNoticeBcc', '', '',
3333             'Email address to Bcc outgoing notices sent by email',
3334             'free')
3335          ");
3336         print "Upgrade to $DBversion done (added OverdueNoticeBcc system preferences)\n";
3337     SetVersion ($DBversion);
3338 }
3339 $DBversion = "3.01.00.102";
3340 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3341     $dbh->do(
3342     "UPDATE permissions set description = 'Edit catalog (Modify bibliographic/holdings data)' where module_bit = 9 and code = 'edit_catalogue'"
3343     );
3344         print "Upgrade to $DBversion done (fixed spelling error in edit_catalogue permission)\n";
3345     SetVersion ($DBversion);
3346 }
3347
3348 $DBversion = "3.01.00.103";
3349 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3350         $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES (13, 'moderate_tags', 'Moderate patron tags')");
3351         print "Upgrade to $DBversion done (adding patron permissions for tags tool)\n";
3352     SetVersion ($DBversion);
3353 }
3354
3355 $DBversion = "3.01.00.104";
3356 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3357
3358     my ($maninv_count, $borrnotes_count);
3359     eval { $maninv_count = $dbh->do("SELECT 1 FROM authorised_values WHERE category='MANUAL_INV'"); };
3360     if ($maninv_count == 0) {
3361         $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('MANUAL_INV','Copier Fees','.25')");
3362     }
3363     eval { $borrnotes_count = $dbh->do("SELECT 1 FROM authorised_values WHERE category='BOR_NOTES'"); };
3364     if ($borrnotes_count == 0) {
3365         $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('BOR_NOTES','ADDR','Address Notes')");
3366     }
3367
3368     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('LOC','CART','Book Cart')");
3369     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('LOC','PROC','Processing Center')");
3370
3371         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";
3372         SetVersion ($DBversion);
3373 }
3374
3375
3376 $DBversion = "3.01.00.105";
3377 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3378     $dbh->do("
3379       CREATE TABLE `collections` (
3380         `colId` int(11) NOT NULL auto_increment,
3381         `colTitle` varchar(100) NOT NULL default '',
3382         `colDesc` text NOT NULL,
3383         `colBranchcode` varchar(4) default NULL COMMENT 'branchcode for branch where item should be held.',
3384         PRIMARY KEY  (`colId`)
3385       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3386     ");
3387
3388     $dbh->do("
3389       CREATE TABLE `collections_tracking` (
3390         `ctId` int(11) NOT NULL auto_increment,
3391         `colId` int(11) NOT NULL default '0' COMMENT 'collections.colId',
3392         `itemnumber` int(11) NOT NULL default '0' COMMENT 'items.itemnumber',
3393         PRIMARY KEY  (`ctId`)
3394       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3395     ");
3396     $dbh->do("
3397         INSERT INTO permissions (module_bit, code, description)
3398         VALUES ( 13, 'rotating_collections', 'Manage Rotating collections')" );
3399         print "Upgrade to $DBversion done (added collection and collection_tracking tables for rotating collections functionality)\n";
3400     SetVersion ($DBversion);
3401 }
3402 $DBversion = "3.01.00.106";
3403 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3404         $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' )");
3405         print "Upgrade to $DBversion done (added OpacAddMastheadLibraryPulldown system preferences)\n";
3406     SetVersion ($DBversion);
3407 }
3408
3409 $DBversion = '3.01.00.107';
3410 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3411     my $upgrade_script = C4::Context->config("intranetdir") . "/installer/data/mysql/patroncards_upgrade.pl";
3412     system("perl $upgrade_script");
3413     print "Upgrade to $DBversion done (Migrated labels and patroncards tables and data to new schema.)\n";
3414     SetVersion ($DBversion);
3415 }
3416
3417 $DBversion = '3.01.00.108';
3418 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3419         $dbh->do(qq{
3420     ALTER TABLE `export_format` ADD `csv_separator` VARCHAR( 2 ) NOT NULL AFTER `marcfields` ,
3421     ADD `field_separator` VARCHAR( 2 ) NOT NULL AFTER `csv_separator` ,
3422     ADD `subfield_separator` VARCHAR( 2 ) NOT NULL AFTER `field_separator`
3423     });
3424         print "Upgrade to $DBversion done (added separators for csv export)\n";
3425     SetVersion ($DBversion);
3426 }
3427
3428 $DBversion = "3.01.00.109";
3429 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3430         $dbh->do(qq{
3431         ALTER TABLE `export_format` ADD `encoding` VARCHAR(255) NOT NULL AFTER `subfield_separator`
3432         });
3433         print "Upgrade to $DBversion done (added encoding for csv export)\n";
3434     SetVersion ($DBversion);
3435 }
3436
3437 $DBversion = '3.01.00.110';
3438 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3439     $dbh->do('ALTER TABLE `categories` ADD COLUMN `enrolmentperioddate` DATE NULL DEFAULT NULL AFTER `enrolmentperiod`');
3440     print "Upgrade to $DBversion done (Add enrolment period date support)\n";
3441     SetVersion ($DBversion);
3442 }
3443
3444 $DBversion = '3.01.00.111';
3445 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3446     print "Upgrade to $DBversion done (mark DBrev for 3.2-alpha release)\n";
3447     SetVersion ($DBversion);
3448 }
3449
3450 $DBversion = '3.01.00.112';
3451 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3452         $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');");
3453         print "Upgrade to $DBversion done ( added Show Spine Label Printer on Bib Items Details preferences )\n";
3454     SetVersion ($DBversion);
3455 }
3456
3457 $DBversion = '3.01.00.113';
3458 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3459     my $value = C4::Context->preference("XSLTResultsDisplay");
3460     $dbh->do(
3461         "INSERT INTO systempreferences (variable,value,type)
3462          VALUES('OPACXSLTResultsDisplay',?,'YesNo')", {}, $value ? 1 : 0);
3463     $value = C4::Context->preference("XSLTDetailsDisplay");
3464     $dbh->do(
3465         "INSERT INTO systempreferences (variable,value,type)
3466          VALUES('OPACXSLTDetailsDisplay',?,'YesNo')", {}, $value ? 1 : 0);
3467     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";
3468     SetVersion ($DBversion);
3469 }
3470
3471 $DBversion = '3.01.00.114';
3472 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3473     $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')");
3474     $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')");
3475     $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')");
3476         print "Upgrade to $DBversion done ( Added AutoSelfCheckAllowed, AutoSelfCheckID, and AutoShelfCheckPass system preference )\n";
3477     SetVersion ($DBversion);
3478 }
3479
3480 $DBversion = '3.01.00.115';
3481 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3482     $dbh->do('UPDATE aqorders SET quantityreceived = 0 WHERE quantityreceived IS NULL');
3483     $dbh->do('ALTER TABLE aqorders MODIFY COLUMN quantityreceived smallint(6) NOT NULL DEFAULT 0');
3484         print "Upgrade to $DBversion done ( Default aqorders.quantityreceived to 0 )\n";
3485     SetVersion ($DBversion);
3486 }
3487
3488 $DBversion = '3.01.00.116';
3489 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3490         if (C4::Context->preference('OrderPdfFormat') eq 'pdfformat::example'){
3491                 $dbh->do("UPDATE `systempreferences` set value='pdfformat::layout2pages' WHERE variable='OrderPdfFormat'");
3492         }
3493         print "Upgrade to $DBversion done (corrected default OrderPdfFormat value if still set wrong )\n";
3494     SetVersion ($DBversion);
3495 }
3496
3497 $DBversion = '3.01.00.117';
3498 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3499     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'por' WHERE rfc4646_subtag='pt' ");
3500     print "Upgrade to $DBversion done (corrected ISO 639-2 language code for Portuguese)\n";
3501     SetVersion ($DBversion);
3502 }
3503
3504 $DBversion = '3.01.00.118';
3505 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3506     my ($count) = $dbh->selectrow_array("SELECT count(*) FROM information_schema.columns
3507                                          WHERE table_name = 'aqbudgets_planning'
3508                                          AND column_name = 'display'");
3509     if ($count < 1) {
3510         $dbh->do("ALTER TABLE aqbudgets_planning ADD COLUMN display tinyint(1) DEFAULT 1");
3511     }
3512     print "Upgrade to $DBversion done (bug 4203: add display column to aqbudgets_planning if missing)\n";
3513     SetVersion ($DBversion);
3514 }
3515
3516 $DBversion = '3.01.00.119';
3517 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3518     eval{require Locale::Currency::Format};
3519     if (!$@) {
3520         print "Upgrade to $DBversion done (Locale::Currency::Format installed.)\n";
3521         SetVersion ($DBversion);
3522     }
3523     else {
3524         print "Upgrade to $DBversion done.\n";
3525         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";
3526         SetVersion ($DBversion);
3527     }
3528 }
3529
3530 $DBversion = '3.01.00.120';
3531 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3532     $dbh->do(q{
3533 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');
3534 });
3535     print "Upgrade to $DBversion done (bug 1080: add soundon system preference for circulation sounds)\n";
3536     SetVersion ($DBversion);
3537 }
3538
3539 $DBversion = '3.01.00.121';
3540 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3541     $dbh->do("ALTER TABLE `reserves` ADD `expirationdate` DATE DEFAULT NULL");
3542     $dbh->do("ALTER TABLE `reserves` ADD `lowestPriority` tinyint(1) NOT NULL");
3543     $dbh->do("ALTER TABLE `old_reserves` ADD `expirationdate` DATE DEFAULT NULL");
3544     $dbh->do("ALTER TABLE `old_reserves` ADD `lowestPriority` tinyint(1) NOT NULL");
3545     print "Upgrade to $DBversion done ( Added Additional Fields to Reserves tables )\n";
3546     SetVersion ($DBversion);
3547 }
3548
3549 $DBversion = '3.01.00.122';
3550 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3551     $dbh->do(q{
3552       INSERT INTO systempreferences (variable,value,explanation,options,type)
3553       VALUES ('OAI-PMH:ConfFile', '', 'If empty, Koha OAI Server operates in normal mode, otherwise it operates in extended mode.','','File');
3554 });
3555     print "Upgrade to $DBversion done. — Add a new system preference OAI-PMF:ConfFile\n";
3556     SetVersion ($DBversion);
3557 }
3558
3559 $DBversion = "3.01.00.123";
3560 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3561     $dbh->do("INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3562         (6, 'place_holds', 'Place holds for patrons')");
3563     $dbh->do("INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3564         (6, 'modify_holds_priority', 'Modify holds priority')");
3565     $dbh->do("UPDATE `userflags` SET `flagdesc` = 'Place and modify holds for patrons' WHERE `flag` = 'reserveforothers'");
3566     print "Upgrade to $DBversion done (Add granular permission for holds modification and update description of reserveforothers permission)\n";
3567     SetVersion ($DBversion);
3568 }
3569
3570 $DBversion = '3.01.00.124';
3571 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3572     $dbh->do("
3573         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>>).');
3574     ");
3575     print "Upgrade to $DBversion done (bug 3242: add HOLDPLACED letter template, which is used when emailLibrarianWhenHoldIsPlaced is enabled)\n";
3576     SetVersion ($DBversion);
3577 }
3578
3579 $DBversion = '3.01.00.125';
3580 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3581     $dbh->do("
3582         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' );
3583     ");
3584     $dbh->do("
3585         INSERT INTO message_transport_types (message_transport_type) values ('print');
3586     ");
3587     print "Upgrade to $DBversion done (bug 3482: Printable hold and overdue notices)\n";
3588     SetVersion ($DBversion);
3589 }
3590
3591 $DBversion = "3.01.00.126";
3592 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3593         $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')");
3594         $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')");
3595
3596     print "Upgrade to $DBversion done (Adding ILS-DI updates and ILS-DI:AuthorizedIPs)\n";
3597     SetVersion ($DBversion);
3598 }
3599
3600 $DBversion = '3.01.00.127';
3601 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3602     $dbh->do("ALTER TABLE messages CHANGE branchcode branchcode varchar(10);");
3603     print "Upgrade to $DBversion done (bug 4190: messages in patron account did not work with branchcodes > 4)\n";
3604     SetVersion ($DBversion);
3605 }
3606
3607 $DBversion = '3.01.00.128';
3608 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3609     $dbh->do('CREATE INDEX budget_id ON aqorders (budget_id );');
3610     print "Upgrade to $DBversion done (bug 4331: index orders by budget_id)\n";
3611     SetVersion ($DBversion);
3612 }
3613
3614 $DBversion = "3.01.00.129";
3615 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3616         $dbh->do("UPDATE `permissions` SET `code` = 'items_batchdel' WHERE `permissions`.`module_bit` =13 AND `permissions`.`code` = 'batchdel' LIMIT 1 ;");
3617         $dbh->do("UPDATE `permissions` SET `code` = 'items_batchmod' WHERE `permissions`.`module_bit` =13 AND `permissions`.`code` = 'batchmod' LIMIT 1 ;");
3618         print "Upgrade to $DBversion done (Change permissions names for item batch modification / deletion)\n";
3619
3620     SetVersion ($DBversion);
3621 }
3622
3623 $DBversion = "3.01.00.130";
3624 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3625     $dbh->do("UPDATE reserves SET expirationdate = NULL WHERE expirationdate = '0000-00-00'");
3626     print "Upgrade to $DBversion done (change reserves.expirationdate values of 0000-00-00 to NULL (bug 1532)\n";
3627     SetVersion ($DBversion);
3628 }
3629
3630 $DBversion = "3.01.00.131";
3631 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3632         $dbh->do(q{
3633 INSERT IGNORE INTO message_transport_types (message_transport_type) VALUES ('print'),('feed');
3634     });
3635     print "Upgrade to $DBversion done (adding print and feed message transport types)\n";
3636     SetVersion ($DBversion);
3637 }
3638
3639 $DBversion = "3.01.00.132";
3640 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3641         $dbh->do(q{
3642     ALTER TABLE language_descriptions ADD INDEX subtag_type_lang (subtag, type, lang);
3643     });
3644     print "Upgrade to $DBversion done (Adding index to language_descriptions table)\n";
3645     SetVersion ($DBversion);
3646 }
3647
3648 $DBversion = '3.01.00.133';
3649 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3650     $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')");
3651     print "Upgrade to $DBversion done (bug 4405: added OverduesBlockCirc syspref to control whether circulation is blocked if a borrower has overdues)\n";
3652     SetVersion ($DBversion);
3653 }
3654
3655 $DBversion = '3.01.00.134';
3656 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3657     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('DisplayMultiPlaceHold','1','Display the ability to place multiple holds or not','','YesNo')");
3658     print "Upgrade to $DBversion done (adding syspref DisplayMultiPlaceHold to control whether multiple holds can be placed from the search results page)\n";
3659     SetVersion ($DBversion);
3660 }
3661
3662 $DBversion = '3.01.00.135';
3663 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3664     $dbh->do("
3665         INSERT INTO `letter` (module, code, name, title, content) VALUES
3666 ('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')
3667 ");
3668     print "Upgrade to $DBversion done (bug 4377: added HOLD_PRINT message template)\n";
3669     SetVersion ($DBversion);
3670 }
3671
3672 $DBversion = '3.01.00.136';
3673 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3674     $dbh->do(qq{
3675 INSERT INTO permissions (module_bit, code, description) VALUES
3676    ( 9, 'edit_items', 'Edit Items');});
3677     print "Upgrade to $DBversion done (Adding a new permission to edit items)\n";
3678     SetVersion ($DBversion);
3679 }
3680
3681 $DBversion = "3.01.00.137";
3682 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3683         $dbh->do("
3684           INSERT INTO permissions (module_bit, code, description) VALUES
3685           (15, 'check_expiration', 'Check the expiration of a serial'),
3686           (15, 'claim_serials', 'Claim missing serials'),
3687           (15, 'create_subscription', 'Create a new subscription'),
3688           (15, 'delete_subscription', 'Delete an existing subscription'),
3689           (15, 'edit_subscription', 'Edit an existing subscription'),
3690           (15, 'receive_serials', 'Serials receiving'),
3691           (15, 'renew_subscription', 'Renew a subscription'),
3692           (15, 'routing', 'Routing');
3693                  ");
3694     print "Upgrade to $DBversion done (adding granular permissions for serials)\n";
3695     SetVersion ($DBversion);
3696 }
3697
3698 $DBversion = "3.01.00.138";
3699 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3700     $dbh->do("DELETE FROM systempreferences WHERE variable = 'GranularPermissions'");
3701     print "Upgrade to $DBversion done (bug 4896: removing GranularPermissions syspref; use of granular permissions is now the default)\n";
3702     SetVersion ($DBversion);
3703 }
3704
3705 $DBversion = '3.01.00.139';
3706 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3707     $dbh->do("ALTER TABLE message_attributes CHANGE message_name message_name varchar(40);");
3708     print "Upgrade to $DBversion done (bug 3682: change message_name from varchar(20) to varchar(40))\n";
3709     SetVersion ($DBversion);
3710 }
3711
3712 $DBversion = '3.01.00.140';
3713 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3714     $dbh->do("UPDATE systempreferences SET value = '0' WHERE variable = 'TagsModeration' AND value is NULL");
3715     print "Upgrade to $DBversion done (bug 4312 TagsModeration changed from NULL to 0)\n";
3716     SetVersion ($DBversion);
3717 }
3718
3719 $DBversion = '3.01.00.141';
3720 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3721     $dbh->do(qq{DELETE FROM message_attributes WHERE message_attribute_id=3;});
3722     $dbh->do(qq{DELETE FROM letter WHERE code='EVENT' AND title='Upcoming Library Event';});
3723     print "Upgrade to $DBversion done Remove upcoming events messaging option (bug 2434)\n";
3724     SetVersion ($DBversion);
3725 }
3726
3727 $DBversion = '3.01.00.142';
3728 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3729     $dbh->do(qq{DELETE FROM message_transports WHERE message_attribute_id=3;});
3730     print "Upgrade to $DBversion done (Remove upcoming events messaging option part 2 (bug 2434))\n";
3731     SetVersion ($DBversion);
3732 }
3733
3734 $DBversion = '3.01.00.143';
3735 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3736     $dbh->do(qq{CREATE INDEX auth_value_idx ON authorised_values (authorised_value)});
3737     $dbh->do(qq{CREATE INDEX auth_val_cat_idx ON borrower_attribute_types (authorised_value_category)});
3738     print "Upgrade to $DBversion done (Create index on authorised_values and borrower_attribute_types (bug 4139))\n";
3739     SetVersion ($DBversion);
3740 }
3741
3742 $DBversion = '3.01.00.144';
3743 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3744     $dbh->do(qq{UPDATE systempreferences SET value='normal' where value='default' and variable='IntranetBiblioDefaultView'});
3745     print "Upgrade to $DBversion done (Update the 'default' to 'normal' for the IntranetBiblioDefaultView syspref (bug 5007))\n";
3746     SetVersion ($DBversion);
3747 }
3748
3749 $DBversion = "3.01.00.145";
3750 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3751     $dbh->do("ALTER TABLE borrowers ADD KEY `guarantorid` (guarantorid);");
3752     print "Upgrade to $DBversion done (Add index on guarantorid)\n";
3753     SetVersion ($DBversion);
3754 }
3755
3756 $DBversion = '3.01.00.999';
3757 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3758     print "Upgrade to $DBversion done (3.2.0 release candidate)\n";
3759     SetVersion ($DBversion);
3760 }
3761
3762 $DBversion = "3.02.00.000";
3763 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3764     my $value = $dbh->selectrow_array("SELECT value FROM systempreferences WHERE variable = 'HomeOrHoldingBranch'");
3765     $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');");
3766     print "Upgrade to $DBversion done (Add HomeOrHoldingBranchReturn system preference)\n";
3767     SetVersion ($DBversion);
3768 }
3769
3770 $DBversion = "3.02.00.001";
3771 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3772     $dbh->do(q{DELETE FROM systempreferences WHERE variable IN (
3773                 'holdCancelLength',
3774                 'PINESISBN',
3775                 'sortbynonfiling',
3776                 'TemplateEncoding',
3777                 'OPACSubscriptionDisplay',
3778                 'OPACDisplayExtendedSubInfo',
3779                 'OAI-PMH:Set',
3780                 'OAI-PMH:Subset',
3781                 'libraryAddress',
3782                 'kohaspsuggest',
3783                 'OrderPdfTemplate',
3784                 'marc',
3785                 'acquisitions',
3786                 'MIME')
3787                }
3788     );
3789     print "Upgrade to $DBversion done (bug 3756: remove disused system preferences)\n";
3790     SetVersion ($DBversion);
3791 }
3792
3793 $DBversion = "3.02.00.002";
3794 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3795     $dbh->do(q{DELETE FROM systempreferences WHERE variable = 'OpacPrivacy'});
3796     print "Upgrade to $DBversion done (bug 3881: remove unused OpacPrivacy system preference)\n";
3797     SetVersion ($DBversion);
3798 }
3799
3800 $DBversion = "3.02.00.003";
3801 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3802     $dbh->do(q{UPDATE systempreferences SET variable = 'ILS-DI:AuthorizedIPs' WHERE variable = 'ILS-DI:Authorized_IPs'});
3803     print "Upgrade to $DBversion done (correct ILS-DI:AuthorizedIPs)\n";
3804     SetVersion ($DBversion);
3805 }
3806
3807 $DBversion = "3.02.00.004";
3808 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3809     print "Upgrade to $DBversion done (3.2.0 general release)\n";
3810     SetVersion ($DBversion);
3811 }
3812
3813 # This is the point where 3.2.x and master diverged, we can use $original_version to make sure we don't
3814 # apply updates that have already been done
3815
3816 $DBversion = "3.03.00.001";
3817 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.005")) {
3818     $dbh->do("DELETE FROM subscriptionroutinglist WHERE borrowernumber IS NULL;");
3819     $dbh->do("ALTER TABLE subscriptionroutinglist MODIFY COLUMN `borrowernumber` int(11) NOT NULL;");
3820     $dbh->do("DELETE FROM subscriptionroutinglist WHERE subscriptionid IS NULL;");
3821     $dbh->do("ALTER TABLE subscriptionroutinglist MODIFY COLUMN `subscriptionid` int(11) NOT NULL;");
3822     $dbh->do("CREATE TEMPORARY TABLE del_subscriptionroutinglist
3823               SELECT s1.routingid FROM subscriptionroutinglist s1
3824               WHERE EXISTS (SELECT * FROM subscriptionroutinglist s2
3825                             WHERE s2.borrowernumber = s1.borrowernumber
3826                             AND   s2.subscriptionid = s1.subscriptionid
3827                             AND   s2.routingid < s1.routingid);");
3828     $dbh->do("DELETE FROM subscriptionroutinglist
3829               WHERE routingid IN (SELECT routingid FROM del_subscriptionroutinglist);");
3830     $dbh->do("ALTER TABLE subscriptionroutinglist ADD UNIQUE (subscriptionid, borrowernumber);");
3831     $dbh->do("ALTER TABLE subscriptionroutinglist
3832                 ADD CONSTRAINT `subscriptionroutinglist_ibfk_1` FOREIGN KEY (`borrowernumber`)
3833                 REFERENCES `borrowers` (`borrowernumber`)
3834                 ON DELETE CASCADE ON UPDATE CASCADE");
3835     $dbh->do("ALTER TABLE subscriptionroutinglist
3836                 ADD CONSTRAINT `subscriptionroutinglist_ibfk_2` FOREIGN KEY (`subscriptionid`)
3837                 REFERENCES `subscription` (`subscriptionid`)
3838                 ON DELETE CASCADE ON UPDATE CASCADE");
3839     print "Upgrade to $DBversion done (Make subscriptionroutinglist more strict)\n";
3840     SetVersion ($DBversion);
3841 }
3842
3843 $DBversion = '3.03.00.002';
3844 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.006")) {
3845     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='arm' WHERE rfc4646_subtag='hy';");
3846     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='eng' WHERE rfc4646_subtag='en';");
3847     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'fi','fin');");
3848     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='fre' WHERE rfc4646_subtag='fr';");
3849     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'lo','lao');");
3850     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='ita' WHERE rfc4646_subtag='it';");
3851     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'sr','srp');");
3852     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'tet','tet');");
3853     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'ur','urd');");
3854
3855     print "Upgrade to $DBversion done (Correct language mappings)\n";
3856     SetVersion ($DBversion);
3857 }
3858
3859 $DBversion = '3.03.00.003';
3860 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.007")) {
3861     $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');");
3862     print "Upgrade to $DBversion done (Add UseTablesortForCirc syspref)\n";
3863     SetVersion ($DBversion);
3864 }
3865
3866 $DBversion = '3.03.00.004';
3867 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.001")) {
3868     my $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'ACCEPTED');
3869     $dbh->do(q/
3870 INSERT INTO `letter`
3871 (module, code, name, title, content)
3872 VALUES
3873 ('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>>')
3874 /) unless $count > 0;
3875     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'AVAILABLE');
3876     $dbh->do(q/
3877 INSERT INTO `letter`
3878 (module, code, name, title, content)
3879 VALUES
3880 ('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>>')
3881 /) unless $count > 0;
3882     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'ORDERED');
3883     $dbh->do(q/
3884 INSERT INTO `letter`
3885 (module, code, name, title, content)
3886 VALUES
3887 ('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>>')
3888 /) unless $count > 0;
3889     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'REJECTED');
3890     $dbh->do(q/
3891 INSERT INTO `letter`
3892 (module, code, name, title, content)
3893 VALUES
3894 ('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>>')
3895 /) unless $count > 0;
3896     print "Upgrade to $DBversion done (bug 5127: add default templates for suggestion status change notifications)\n";
3897     SetVersion ($DBversion);
3898 };
3899
3900 $DBversion = '3.03.00.005';
3901 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3902     $dbh->do("update `systempreferences` set options='whitespace|T-prefix|cuecat|libsuite8' where variable='itemBarcodeInputFilter'");
3903     print "Upgrade to $DBversion done (Add itemBarcodeInputFilter choice libsuite8)\n";
3904 }
3905
3906 $DBversion = '3.03.00.006';
3907 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.002")) {
3908     $dbh->do("ALTER TABLE deletedborrowers ADD `privacy` int(11) AFTER smsalertnumber;");
3909     $dbh->do("ALTER TABLE deletedborrowers CHANGE `cardnumber` `cardnumber` varchar(16);");
3910     print "Upgrade to $DBversion done (Fix differences between borrowers and deletedborrowers)\n";
3911     SetVersion ($DBversion);
3912 }
3913
3914 $DBversion = '3.03.00.007';
3915 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3916     $dbh->do("ALTER table suggestions ADD quantity SMALLINT(6) default NULL,
3917                 ADD currency VARCHAR(3) default NULL,
3918                 ADD price DECIMAL(28,6) default NULL,
3919                 ADD total DECIMAL(28,6) default NULL;
3920                 ");
3921     print "Upgrade to $DBversion done (Added acq related columns to suggestions)\n";
3922     SetVersion ($DBversion);
3923 }
3924
3925 $DBversion = '3.03.00.008';
3926 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3927     $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')");
3928     print "Upgrade to $DBversion done (adding syspref OPACNoResultsFound to control what displays when no results are found for a search in the OPAC.)\n";
3929     SetVersion ($DBversion);
3930 }
3931
3932 $DBversion = '3.03.00.009';
3933 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.003")) {
3934     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('IntranetUserCSS','','Add CSS to be included in the Intranet',NULL,'free')");
3935     print "Upgrade to $DBversion done (Add IntranetUserCSS syspref)\n";
3936     SetVersion ($DBversion);
3937 }
3938
3939 $DBversion = "3.03.00.010";
3940 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.02.001")) {
3941     $dbh->do("UPDATE `marc_subfield_structure` SET liblibrarian = 'Distance from earth' WHERE liblibrarian = 'Distrance from earth' AND tagfield = '034' AND tagsubfield = 'r';");
3942     $dbh->do("UPDATE `marc_subfield_structure` SET libopac = 'Distance from earth' WHERE libopac = 'Distrance from earth' AND tagfield = '034' AND tagsubfield = 'r';");
3943     print "Upgrade to $DBversion done (Fix misspelled 034r subfield in MARC21 Frameworks)\n";
3944     SetVersion ($DBversion);
3945 }
3946
3947 $DBversion = "3.03.00.011";
3948 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3949     $dbh->do("UPDATE aqbooksellers SET gstrate=NULL WHERE gstrate=0.0");
3950     print "Upgrade to $DBversion done (Bug 5186: allow GST rate to be set to 0)\n";
3951     SetVersion ($DBversion);
3952 }
3953
3954 $DBversion = "3.03.00.012";
3955 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3956    $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')");
3957    print "Upgrade to $DBversion done (Bug 2142: maxItemsInSearchResults syspref resurrected)\n";
3958    SetVersion ($DBversion);
3959 }
3960
3961 $DBversion = "3.03.00.013";
3962 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3963     $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')");
3964     print "Upgrade to $DBversion done (added 'OpacPublic' syspref)\n";
3965    SetVersion ($DBversion);
3966 }
3967
3968 $DBversion = "3.03.00.014";
3969 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3970     $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')");
3971     $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')");
3972     $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')");
3973     print "Upgrade to $DBversion done (Add flexible shelf browser constraints)\n";
3974     SetVersion ($DBversion);
3975 }
3976
3977 $DBversion = "3.03.00.015";
3978 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3979     if ( C4::Context->preference("marcflavour") eq "MARC21" ) {
3980         my $sth = $dbh->prepare(
3981 "INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`,
3982                              `tab`, `authorised_value`, `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`)
3983                              VALUES ( ?, '9', '9 (RLIN)', '9 (RLIN)', 0, 0, '', 6, '', '', '', 0, -5, '', '', '', NULL)"
3984         );
3985         $sth->execute('648');
3986         $sth->execute('654');
3987         $sth->execute('655');
3988         $sth->execute('656');
3989         $sth->execute('657');
3990         $sth->execute('658');
3991         $sth->execute('662');
3992         $sth->finish;
3993         print
3994 "Upgrade to $DBversion done (Bug 5619: Add subfield 9 to marc21 648,654,655,656,657,658,662)\n";
3995     }
3996     SetVersion($DBversion);
3997 }
3998
3999 $DBversion = '3.03.00.016';
4000 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4001     # reimplement OpacPrivacy system preference
4002     $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')");
4003     $dbh->do("ALTER TABLE `borrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
4004     $dbh->do("ALTER TABLE `deletedborrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
4005     print "Upgrade to $DBversion done (OpacPrivacy reimplementation)\n";
4006     SetVersion($DBversion);
4007 };
4008
4009 $DBversion = '3.03.00.017';
4010 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.001")) {
4011     $dbh->do("ALTER TABLE  `currency` CHANGE `rate` `rate` FLOAT( 15, 5 ) NULL DEFAULT NULL;");
4012     print "Upgrade to $DBversion done (Enable currency rates >= 100)\n";
4013     SetVersion ($DBversion);
4014 }
4015
4016 $DBversion = '3.03.00.018';
4017 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.002")) {
4018     $dbh->do( q|update language_descriptions set description = 'Nederlands' where lang = 'nl' and subtag = 'nl'|);
4019     $dbh->do( q|update language_descriptions set description = 'Dansk' where lang = 'da' and subtag = 'da'|);
4020     print "Upgrade to $DBversion done (Correct language descriptions)\n";
4021     SetVersion ($DBversion);
4022 }
4023
4024 $DBversion = '3.03.00.019';
4025 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.003")) {
4026     # Fix bokmål
4027     $dbh->do("UPDATE language_subtag_registry SET description = 'Norwegian bokm&#229;l' WHERE subtag = 'nb';");
4028     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'nb','nob');");
4029     $dbh->do("UPDATE language_descriptions SET description = 'Norsk bokm&#229;l' WHERE subtag = 'nb' AND lang = 'nb';");
4030     $dbh->do("UPDATE language_descriptions SET description = 'Norwegian bokm&#229;l' WHERE subtag = 'nb' AND lang = 'en';");
4031     $dbh->do("UPDATE language_descriptions SET description = 'Norvégien bokm&#229;l' WHERE subtag = 'nb' AND lang = 'fr';");
4032     # Add nynorsk
4033     $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'nn', 'language', 'Norwegian nynorsk','2011-02-14' )");
4034     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'nn','nno')");
4035     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'nb', 'Norsk nynorsk')");
4036     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'nn', 'Norsk nynorsk')");
4037     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'en', 'Norwegian nynorsk')");
4038     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'fr', 'Norvégien nynorsk')");
4039     print "Upgrade to $DBversion done (Correct language descriptions for Norwegian)\n";
4040     SetVersion ($DBversion);
4041 }
4042
4043 $DBversion = '3.03.00.020';
4044 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4045     $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')");
4046     $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')");
4047     print "Upgrade to $DBversion done (Bug 5811: Add sysprefs controlling overriding fines)\n";
4048     SetVersion($DBversion);
4049 };
4050
4051 $DBversion = '3.03.00.021';
4052 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.001")) {
4053     $dbh->do("ALTER TABLE items MODIFY enumchron TEXT");
4054     $dbh->do("ALTER TABLE deleteditems MODIFY enumchron TEXT");
4055     print "Upgrade to $DBversion done (bug 5642: longer serial enumeration)\n";
4056     SetVersion ($DBversion);
4057 }
4058
4059 $DBversion = '3.03.00.022';
4060 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4061     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('AuthoritiesLog','0','If ON, log edit/create/delete actions on authorities.','','YesNo');");
4062     print "Upgrade to $DBversion done (Add AuthoritiesLog syspref)\n";
4063     SetVersion ($DBversion);
4064 }
4065
4066 # due to a mismatch in kohastructure.sql some koha will have missing columns in aqbasketgroup
4067 # this attempts to fix that
4068 $DBversion = '3.03.00.023';
4069 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.002")) {
4070     my $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'billingplace'");
4071     $sth->execute;
4072     $dbh->do("ALTER TABLE aqbasketgroups ADD billingplace VARCHAR(10)") if ! $sth->fetchrow_hashref;
4073     $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'deliveryplace'");
4074     $sth->execute;
4075     $dbh->do("ALTER TABLE aqbasketgroups ADD deliveryplace VARCHAR(10)") if ! $sth->fetchrow_hashref;
4076     $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'deliverycomment'");
4077     $sth->execute;
4078     $dbh->do("ALTER TABLE aqbasketgroups ADD deliverycomment VARCHAR(255)") if ! $sth->fetchrow_hashref;
4079     print "Upgrade to $DBversion done (Reconcile aqbasketgroups)\n";
4080     SetVersion ($DBversion);
4081 }
4082
4083 $DBversion = '3.03.00.024';
4084 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4085     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('TraceCompleteSubfields','0','Force subject tracings to only match complete subfields.','0','YesNo')");
4086     $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')");
4087     print "Upgrade to $DBversion done (Add syspref to force whole-subfield matching on subject tracings)\n";
4088     SetVersion($DBversion);
4089 };
4090
4091 $DBversion = "3.03.00.025";
4092 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4093     $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')");
4094     print "Upgrade to $DBversion done (Add syspref to control if user can choose pickup branch for holds)\n";
4095     SetVersion ($DBversion);
4096 }
4097
4098 $DBversion = '3.03.00.026';
4099 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.003")) {
4100     $dbh->do("UPDATE `message_attributes` SET message_name='Item Due' WHERE message_attribute_id=1 AND message_name LIKE 'Item DUE'");
4101         print "Upgrade to $DBversion done ( fix capitalization in message type )\n";
4102     SetVersion ($DBversion);
4103 }
4104
4105 $DBversion = '3.03.00.027';
4106 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4107     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('displayFacetCount', '0', NULL, NULL, 'YesNo')");
4108     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('maxRecordsForFacets', '20', NULL, NULL, 'Integer')");
4109     print "Upgrade to $DBversion done (Preferences for facet count)\n";
4110     SetVersion ($DBversion);
4111 }
4112
4113 $DBversion = "3.03.00.028";
4114 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4115     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('FacetLabelTruncationLength', 20, 'Truncate facets length to','','free')");
4116     print "Upgrade to $DBversion done (Add FacetLabelTruncationLength syspref to control facets displayed length)\n";
4117     SetVersion ($DBversion);
4118 }
4119
4120 $DBversion = "3.03.00.029";
4121 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4122     $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')");
4123     print "Upgrade to $DBversion done (Add syspref to control if user can choose branch when making purchase suggestion)\n";
4124     SetVersion ($DBversion);
4125 }
4126
4127 $DBversion = "3.03.00.030";
4128 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4129     $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')");
4130     $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')");
4131     print "Upgrade to $DBversion done (Add sysprefs to control custom favicons)\n";
4132     SetVersion ($DBversion);
4133 }
4134
4135 $DBversion = "3.03.00.031";
4136 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4137     $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');");
4138     print "Upgrade to $DBversion done (Add syspref FineNotifyAtCheckin)\n";
4139     SetVersion ($DBversion);
4140 }
4141
4142 $DBversion = '3.03.00.032';
4143 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4144     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('TraceSubjectSubdivisions', 1, 'Create searches on all subdivisions for subject tracings.','1','YesNo')");
4145     print "Upgrade to $DBversion done ( include subdivisions when generating subject tracing searches )\n";
4146 }
4147
4148
4149 $DBversion = '3.03.00.033';
4150 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4151     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('StaffAuthorisedValueImages', '1', '', NULL, 'YesNo')");
4152     print "Upgrade to $DBversion done (System pref StaffAuthorisedValueImages)\n";
4153     SetVersion ($DBversion);
4154 }
4155
4156 $DBversion = '3.03.00.034';
4157 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4158     $dbh->do("ALTER TABLE `categories` ADD `hidelostitems` tinyint(1) NOT NULL default '0' AFTER `reservefee`");
4159     print "Upgrade to $DBversion done (Add hidelostitems preference to borrower categories)\n";
4160     SetVersion ($DBversion);
4161 }
4162
4163 $DBversion = '3.03.00.035';
4164 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4165     $dbh->do("ALTER TABLE `issuingrules` ADD hardduedate date default NULL AFTER issuelength");
4166     $dbh->do("ALTER TABLE `issuingrules` ADD hardduedatecompare tinyint NOT NULL default 0 AFTER hardduedate");
4167     my $duedate;
4168     if (C4::Context->preference("globalDueDate")) {
4169       $duedate = C4::Dates::format_date_in_iso(C4::Context->preference("globalDueDate"));
4170       $dbh->do("UPDATE `issuingrules` SET hardduedate = '$duedate', hardduedatecompare = 0");
4171     } elsif (C4::Context->preference("ceilingDueDate")) {
4172       $duedate = C4::Dates::format_date_in_iso(C4::Context->preference("ceilingDueDate"));
4173       $dbh->do("UPDATE `issuingrules` SET hardduedate = '$duedate', hardduedatecompare = -1");
4174     }
4175     $dbh->do("DELETE FROM `systempreferences` WHERE variable = 'globalDueDate' OR variable = 'ceilingDueDate'");
4176     print "Upgrade to $DBversion done (Move global and ceiling due dates to Circ Rules level)\n";
4177     SetVersion ($DBversion);
4178 }
4179
4180 $DBversion = '3.03.00.036';
4181 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4182     $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')");
4183     print "Upgrade to $DBversion done ( Make COinS optional in OPAC search results )\n";
4184     SetVersion ($DBversion);
4185 }
4186
4187 $DBversion = '3.03.00.037';
4188 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4189     $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')");
4190     $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')");
4191     print "Upgrade to $DBversion done (Add 'Display856uAsImage' and 'OPACDisplay856uAsImage' syspref)\n";
4192     SetVersion ($DBversion);
4193 }
4194
4195 $DBversion = '3.03.00.038';
4196 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4197     $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')");
4198     $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')");
4199     $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')");
4200     print "Upgrade to $DBversion done ( Add Self-checkout by Login system preferences )\n";
4201 }
4202
4203 $DBversion = "3.03.00.039";
4204 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4205     $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');");
4206     print "Upgrade to $DBversion done (Add syspref ShowReviewer)\n";
4207 }
4208
4209 $DBversion = "3.03.00.040";
4210 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4211     $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');");
4212     print "Upgrade to $DBversion done (Add syspref UseControlNumber)\n";
4213 }
4214
4215 $DBversion = "3.03.00.041";
4216 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4217     $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')");
4218     $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')");
4219     print "Upgrade to $DBversion done (Add sysprefs to control alternate holdings information display)\n";
4220     SetVersion ($DBversion);
4221 }
4222
4223 $DBversion = '3.03.00.042';
4224 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4225     stocknumber_checker();
4226     print "Upgrade to $DBversion done (5860 Index itemstocknumber)\n";
4227     SetVersion ($DBversion);
4228 }
4229
4230 sub stocknumber_checker { #code reused later on
4231   my @row;
4232   #drop the obsolete itemSStocknumber idx if it exists
4233   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemsstocknumberidx'");
4234   $dbh->do("ALTER TABLE `items` DROP INDEX `itemsstocknumberidx`;") if @row;
4235
4236   #check itemstocknumber idx; remove it if it is unique
4237   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemstocknumberidx' AND non_unique=0");
4238   $dbh->do("ALTER TABLE `items` DROP INDEX `itemstocknumberidx`;") if @row;
4239
4240   #add itemstocknumber index non-unique IF it still not exists
4241   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemstocknumberidx'");
4242   $dbh->do("ALTER TABLE items ADD INDEX itemstocknumberidx (stocknumber);") unless @row;
4243 }
4244
4245 $DBversion = "3.03.00.043";
4246 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4247
4248     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib,lib_opac) VALUES ('YES_NO','0','No','No')");
4249     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib,lib_opac) VALUES ('YES_NO','1','Yes','Yes')");
4250
4251         print "Upgrade to $DBversion done ( add generic boolean YES_NO authorised_values pair )\n";
4252         SetVersion ($DBversion);
4253 }
4254
4255 $DBversion = '3.03.00.044';
4256 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4257     $dbh->do("ALTER TABLE `aqbasketgroups` ADD `freedeliveryplace` TEXT NULL AFTER `deliveryplace`;");
4258     print "Upgrade to $DBversion done (adding freedeliveryplace to basketgroups)\n";
4259 }
4260
4261 $DBversion = '3.03.00.045';
4262 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4263     #Remove obsolete columns from aqbooksellers if needed
4264     my $a = $dbh->selectall_hashref('SHOW columns from aqbooksellers','Field');
4265     my $sqldrop="ALTER TABLE aqbooksellers DROP COLUMN ";
4266     foreach(qw/deliverydays followupdays followupscancel invoicedisc nocalc specialty/) {
4267       $dbh->do($sqldrop.$_) if exists $a->{$_};
4268     }
4269     #Remove obsolete column from aqbudgets if needed
4270     #The correct column is budget_notes
4271     $a = $dbh->selectall_hashref('SHOW columns from aqbudgets','Field');
4272     if(exists $a->{budget_description}) {
4273       $dbh->do("ALTER TABLE aqbudgets DROP COLUMN budget_description");
4274     }
4275     print "Upgrade to $DBversion done (Remove obsolete columns from aqbooksellers and aqbudgets if needed)\n";
4276     SetVersion ($DBversion);
4277 }
4278
4279 $DBversion = "3.03.00.046";
4280 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4281     $dbh->do("ALTER TABLE overduerules ALTER delay1 SET DEFAULT NULL, ALTER delay2 SET DEFAULT NULL, ALTER delay3 SET DEFAULT NULL");
4282     print "Upgrade to $DBversion done (Setting NULL default value for delayn columns in table overduerules)\n";
4283     SetVersion($DBversion);
4284 }
4285
4286 $DBversion = '3.03.00.047';
4287 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4288     $dbh->do("ALTER TABLE borrowers ADD `state` mediumtext AFTER city;");
4289     $dbh->do("ALTER TABLE borrowers ADD `B_state` mediumtext AFTER B_city;");
4290     $dbh->do("ALTER TABLE borrowers ADD `altcontactstate` mediumtext AFTER altcontactaddress3;");
4291     $dbh->do("ALTER TABLE deletedborrowers ADD `state` mediumtext AFTER city;");
4292     $dbh->do("ALTER TABLE deletedborrowers ADD `B_state` mediumtext AFTER B_city;");
4293     $dbh->do("ALTER TABLE deletedborrowers ADD `altcontactstate` mediumtext AFTER altcontactaddress3;");
4294     print "Upgrade to $DBversion done (Add state field to patron's addresses)\n";
4295 }
4296
4297 $DBversion = '3.03.00.048';
4298 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4299     $dbh->do("ALTER TABLE branches ADD `branchstate` mediumtext AFTER `branchcity`;");
4300     print "Upgrade to $DBversion done (Add state to branch address)\n";
4301     SetVersion ($DBversion);
4302 }
4303
4304 $DBversion = '3.03.00.049';
4305 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4306     $dbh->do("ALTER TABLE `accountlines` ADD `note` text NULL default NULL");
4307     $dbh->do("ALTER TABLE `accountlines` ADD `manager_id` int( 11 ) NULL ");
4308     print "Upgrade to $DBversion done (adding note and manager_id fields in accountlines table)\n";
4309     SetVersion($DBversion);
4310 }
4311
4312 $DBversion = "3.03.00.050";
4313 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4314     $dbh->do("
4315         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');
4316         ");
4317     print "Upgrade to $DBversion done (Adding OpacHiddenItems syspref)\n";
4318     SetVersion($DBversion);
4319 }
4320
4321 $DBversion = "3.03.00.051";
4322 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4323     print "Upgrade to $DBversion done (Remove spaces and dashes from message_attribute names)\n";
4324     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Due' WHERE message_name='Item Due'");
4325     $dbh->do("UPDATE message_attributes SET message_name = 'Advance_Notice' WHERE message_name='Advance Notice'");
4326     $dbh->do("UPDATE message_attributes SET message_name = 'Hold_Filled' WHERE message_name='Hold Filled'");
4327     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Check_in' WHERE message_name='Item Check-in'");
4328     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Checkout' WHERE message_name='Item Checkout'");
4329     SetVersion ($DBversion);
4330 }
4331
4332 $DBversion = "3.03.00.052";
4333 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4334     $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');");
4335     print "Upgrade to $DBversion done (Add syspref WaitingNotifyAtCheckin)\n";
4336     SetVersion ($DBversion);
4337 }
4338
4339 $DBversion = "3.04.00.000";
4340 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4341     print "Upgrade to $DBversion done Koha 3.4.0 release \n";
4342     SetVersion ($DBversion);
4343 }
4344
4345 $DBversion = "3.05.00.001";
4346 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4347     $dbh->do(qq{
4348     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');
4349     });
4350     print "Upgrade to $DBversion done (Adds New System preference numSearchRSSResults)\n";
4351     SetVersion($DBversion);
4352 }
4353
4354 $DBversion = '3.05.00.002';
4355 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4356     #follow up fix 5860: some installs already past 3.3.0.42
4357     stocknumber_checker();
4358     print "Upgrade to $DBversion done (Fix for stocknumber index)\n";
4359     SetVersion ($DBversion);
4360 }
4361
4362 $DBversion = "3.05.00.003";
4363 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4364     $dbh->do(qq{
4365     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');
4366     });
4367     print "Upgrade to $DBversion done (Adds New System preference OpacRenewalBranch)\n";
4368     SetVersion($DBversion);
4369 }
4370
4371 $DBversion = "3.05.00.004";
4372 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4373     $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');");
4374     print "Upgrade to $DBversion done (Add syspref ShowReviewerPhoto)\n";
4375     SetVersion($DBversion);
4376 }
4377
4378 $DBversion = "3.05.00.005";
4379 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4380     $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');");
4381     print "Upgrade to $DBversion done (Adds pref BasketConfirmations)\n";
4382     SetVersion($DBversion);
4383 }
4384
4385 $DBversion = "3.05.00.006";
4386 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4387     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('MARCAuthorityControlField008', '|| aca||aabn           | a|a     d', NULL, NULL, 'Textarea')");
4388     print "Upgrade to $DBversion done (Add syspref MARCAuthorityControlField008)\n";
4389     SetVersion ($DBversion);
4390 }
4391
4392 $DBversion = "3.05.00.007";
4393 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4394     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpenLibraryCovers',0,'If ON Openlibrary book covers will be show',NULL,'YesNo');");
4395     print "Upgrade to $DBversion done (Add syspref OpenLibraryCovers)\n";
4396     SetVersion($DBversion);
4397 }
4398
4399 $DBversion = "3.05.00.008";
4400 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4401     $dbh->do("ALTER TABLE `cities` ADD `city_state` VARCHAR( 100 ) NULL DEFAULT NULL AFTER  `city_name`;");
4402     $dbh->do("ALTER TABLE `cities` ADD `city_country` VARCHAR( 100 ) NULL DEFAULT NULL AFTER  `city_zipcode`;");
4403     print "Add state and country to cities table corresponding to new columns in borrowers\n";
4404     SetVersion($DBversion);
4405 }
4406
4407 $DBversion = "3.05.00.009";
4408 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4409     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4410               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE borrowernumber IS NULL");
4411     $dbh->do("DELETE FROM issues WHERE borrowernumber IS NULL");
4412
4413     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4414               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE itemnumber IS NULL");
4415     $dbh->do("DELETE FROM issues WHERE itemnumber IS NULL");
4416
4417     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4418               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowernumber = issues.borrowernumber)");
4419     $dbh->do("DELETE FROM issues WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowernumber = issues.borrowernumber)");
4420
4421     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4422               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE NOT EXISTS (SELECT * FROM items WHERE itemnumber = issues.itemnumber)");
4423     $dbh->do("DELETE FROM issues WHERE NOT EXISTS (SELECT * FROM items WHERE itemnumber = issues.itemnumber)");
4424
4425     $dbh->do("ALTER TABLE issues DROP FOREIGN KEY `issues_ibfk_1`");
4426     $dbh->do("ALTER TABLE issues DROP FOREIGN KEY `issues_ibfk_2`");
4427     $dbh->do("ALTER TABLE issues ALTER COLUMN borrowernumber DROP DEFAULT");
4428     $dbh->do("ALTER TABLE issues ALTER COLUMN itemnumber DROP DEFAULT");
4429     $dbh->do("ALTER TABLE issues MODIFY COLUMN borrowernumber int(11) NOT NULL");
4430     $dbh->do("ALTER TABLE issues MODIFY COLUMN itemnumber int(11) NOT NULL");
4431     $dbh->do("ALTER TABLE issues DROP KEY `issuesitemidx`");
4432     $dbh->do("ALTER TABLE issues ADD PRIMARY KEY (`itemnumber`)");
4433     $dbh->do("ALTER TABLE issues ADD CONSTRAINT `issues_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE RESTRICT ON UPDATE CASCADE");
4434     $dbh->do("ALTER TABLE issues ADD CONSTRAINT `issues_ibfk_2` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE RESTRICT ON UPDATE CASCADE");
4435
4436     print "Upgrade to $DBversion done (issues referential integrity)\n";
4437     SetVersion ($DBversion);
4438 }
4439
4440 $DBversion = "3.05.00.010";
4441 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4442     $dbh->do("CREATE INDEX priorityfoundidx ON reserves (priority,found)");
4443     print "Create an index on reserves to speed up holds awaiting pickup report bug 5866\n";
4444     SetVersion($DBversion);
4445 }
4446
4447
4448 $DBversion = "3.05.00.011";
4449 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4450     $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')");
4451     print "Upgrade to $DBversion done (add OPACResultsSidebar syspref (enh 6165))\n";
4452     SetVersion($DBversion);
4453 }
4454
4455 $DBversion = "3.05.00.012";
4456 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4457     $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')");
4458     print "Upgrade to $DBversion done (add RecordLocalUseOnReturn syspref (enh 6403))\n";
4459     SetVersion($DBversion);
4460 }
4461
4462 $DBversion = "3.05.00.013";
4463 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4464     $dbh->do(qq|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OpacKohaUrl','0',"Show 'Powered by Koha' text on OPAC footer.",NULL,NULL)|);
4465     print "Upgrade to $DBversion done (Add syspref 'OpacKohaUrl')\n";
4466     SetVersion($DBversion);
4467 }
4468
4469 $DBversion = "3.05.00.014";
4470 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4471     $dbh->do("ALTER TABLE `borrowers` MODIFY `userid` VARCHAR(75)");
4472     print "Modified userid column length into 75 in borrowers\n";
4473     SetVersion($DBversion);
4474 }
4475
4476 $DBversion = "3.05.00.015";
4477 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4478     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectEnabled',0,'Enable Novelist Select content.  Requires Novelist Profile and Password',NULL,'YesNo')");
4479     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectProfile',NULL,'Novelist Select user Password',NULL,'free')");
4480     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectPassword',NULL,'Enable Novelist user Profile',NULL,'free')");
4481     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectView','tab','Where to display Novelist Select content','tab|above|below|right','Choice')");
4482     print "Upgrade to $DBversion done (Add support for EBSCO's NoveList Select (enh 6902))\n";
4483     SetVersion($DBversion);
4484 }
4485
4486 $DBversion = '3.05.00.016';
4487 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4488     $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');");
4489     print "Upgrade to $DBversion done (Add EasyAnalyticalRecords syspref)\n";
4490     SetVersion ($DBversion);
4491 }
4492
4493 $DBversion = '3.05.00.017';
4494 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4495     if (C4::Context->preference("marcflavour") eq 'MARC21' ||
4496         C4::Context->preference("marcflavour") eq 'NORMARC'){
4497         $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)");
4498         $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)");
4499         print "Upgrade to $DBversion done (Add 773 subfield 9 and 0 to default framework)\n";
4500         SetVersion ($DBversion);
4501     } elsif (C4::Context->preference("marcflavour") eq 'UNIMARC'){
4502         $dbh->do("INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`, `tab`, `authorised_value` , `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`) VALUES ('461', '9', 'Host Itemnumber', 'Host Itemnumber', 0, 0, NULL, 7, NULL, NULL, '', NULL, -6, '', '', '', NULL)");
4503         print "Upgrade to $DBversion done (Add 461 subfield 9 to default framework)\n";
4504         SetVersion ($DBversion);
4505     }
4506 }
4507
4508 $DBversion = "3.05.00.018";
4509 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4510     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacNavBottom','','Links after OpacNav links','70|10','Textarea')");
4511     print "Upgrade to $DBversion done (add OpacNavBottom syspref (enh 6825): if appropriate, you can split OpacNav into OpacNav and OpacNavBottom)\n";
4512     SetVersion($DBversion);
4513 }
4514
4515 $DBversion = "3.05.00.019";
4516 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4517     $dbh->do("UPDATE itemtypes SET imageurl = 'vokal/Book.png' WHERE imageurl = 'vokal/BOOK.png'");
4518     $dbh->do("UPDATE itemtypes SET imageurl = 'vokal/Book-32px.png' WHERE imageurl = 'vokal/BOOK-32px.png'");
4519     $dbh->do("UPDATE authorised_values SET imageurl = 'vokal/Book.png' WHERE imageurl = 'vokal/BOOK.png'");
4520     $dbh->do("UPDATE authorised_values SET imageurl = 'vokal/Book-32px.png' WHERE imageurl = 'vokal/BOOK-32px.png'");
4521     print "Upgrade to $DBversion done (remove duplicate VOKAL Book icons, bug 6862)\n";
4522     SetVersion($DBversion);
4523 }
4524
4525 $DBversion = "3.05.00.020";
4526 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4527     $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')");
4528     print "Upgrade to $DBversion done (Add syspref AcqViewBaskets)\n";
4529     SetVersion($DBversion);
4530 }
4531
4532 $DBversion = "3.05.00.021";
4533 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4534     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN display_checkout TINYINT(1) NOT NULL DEFAULT '0';");
4535     print "Upgrade to $DBversion done (Added a display_checkout field in borrower_attribute_types table)\n";
4536     SetVersion($DBversion);
4537 }
4538
4539 $DBversion = "3.05.00.022";
4540 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4541     $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");
4542     print "Upgrade to $DBversion done (6094: Fixing ModAuthority problems, add a need_merge_authorities table)\n";
4543     SetVersion($DBversion);
4544 }
4545
4546 $DBversion = "3.05.00.023";
4547 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4548     $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');");
4549     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";
4550     SetVersion($DBversion);
4551 }
4552
4553 $DBversion = "3.06.00.000";
4554 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4555     print "Upgrade to $DBversion done Koha 3.6.0 release \n";
4556     SetVersion ($DBversion);
4557 }
4558
4559 $DBversion = "3.07.00.001";
4560 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4561     my $borrowers = $dbh->selectcol_arrayref( "SELECT borrowernumber from borrowers where debarred =1;", { Columns => [1] } );
4562     $dbh->do("ALTER TABLE borrowers MODIFY debarred DATE DEFAULT NULL;");
4563     $dbh->do( "UPDATE borrowers set debarred='9999-12-31' where borrowernumber IN (" . join( ",", @$borrowers ) . ");" ) if ($borrowers and scalar(@$borrowers)>0);
4564     $dbh->do("ALTER TABLE borrowers ADD COLUMN debarredcomment VARCHAR(255) DEFAULT NULL AFTER debarred;");
4565     $dbh->do("ALTER TABLE deletedborrowers MODIFY debarred DATE DEFAULT NULL;");
4566     $dbh->do("ALTER TABLE deletedborrowers ADD COLUMN debarredcomment VARCHAR(255) DEFAULT NULL AFTER debarred;");
4567     print "Upgrade done (Change borrowers.debarred into Date )\n";
4568     SetVersion($DBversion);
4569 }
4570
4571 $DBversion = "3.07.00.002";
4572 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4573     $dbh->do("UPDATE borrowers SET debarred=NULL WHERE debarred='0000-00-00';");
4574     print "Setting NULL to debarred where 0000-00-00 is stored (bug 7272)\n";
4575     SetVersion($DBversion);
4576 }
4577
4578 $DBversion = "3.07.00.003";
4579 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4580     $dbh->do(" UPDATE `message_attributes` SET message_name='Item_Due' WHERE message_name='Item_DUE'");
4581     print "Updating message_name in message_attributes\n";
4582     SetVersion($DBversion);
4583 }
4584
4585 $DBversion = "3.07.00.004";
4586 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4587     $dbh->do("ALTER TABLE  `suggestions` ADD  `patronreason` TEXT NULL AFTER  `reason`");
4588     print "Upgrade to $DBversion done (Add column to suggestions table to store patrons' reasons for submitting a suggestion. )\n";
4589     SetVersion($DBversion);
4590 }
4591
4592 $DBversion = "3.07.00.005";
4593 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4594     $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')");
4595     print "Upgrade to $DBversion done (BorrowerUnwantedField syspref)\n";
4596     SetVersion ($DBversion);
4597 }
4598
4599 $DBversion = "3.07.00.006";
4600 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4601     $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');");
4602     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";
4603     SetVersion($DBversion);
4604 }
4605
4606 $DBversion = "3.07.00.007";
4607 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4608     $dbh->do("ALTER TABLE items MODIFY materials text;");
4609     print "Upgrade to $DBversion done alter items.material from varchar(10) to text \n";
4610     SetVersion($DBversion);
4611 }
4612
4613 $DBversion = '3.07.00.008';
4614 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4615     if (C4::Context->preference("marcflavour") eq 'MARC21') {
4616         if (C4::Context->preference("opaclanguages") eq "de") {
4617             $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, '');");
4618         } else {
4619             $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, '');");
4620         }
4621     }
4622     print "Upgrade to $DBversion done (add MARC21 field 545 to framework)\n";
4623     SetVersion ($DBversion);
4624 }
4625
4626 $DBversion = "3.07.00.009";
4627 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4628     $dbh->do("ALTER TABLE `aqorders` ADD COLUMN `claims_count` INT(11)  DEFAULT 0, ADD COLUMN `claimed_date` DATE  DEFAULT NULL AFTER `claims_count`");
4629     print "Upgrade to $DBversion done (Add claims_count and claimed_date fields in aqorders table)\n";
4630     SetVersion($DBversion);
4631 }
4632
4633 $DBversion = "3.07.00.010";
4634 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4635     $dbh->do(
4636         q|CREATE TABLE `biblioimages` (
4637           `imagenumber` int(11) NOT NULL AUTO_INCREMENT,
4638           `biblionumber` int(11) NOT NULL,
4639           `mimetype` varchar(15) NOT NULL,
4640           `imagefile` mediumblob NOT NULL,
4641           `thumbnail` mediumblob NOT NULL,
4642           PRIMARY KEY (`imagenumber`),
4643           CONSTRAINT `bibliocoverimage_fk1` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
4644           ) ENGINE=InnoDB DEFAULT CHARSET=utf8|
4645     );
4646     $dbh->do(
4647         q|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OPACLocalCoverImages','0','Display local cover images on OPAC search and details pages.','1','YesNo')|
4648         );
4649     $dbh->do(
4650         q|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('LocalCoverImages','0','Display local cover images on intranet search and details pages.','1','YesNo')|
4651         );
4652     $dbh->do(
4653         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')|
4654     );
4655     $dbh->do(
4656         q|INSERT INTO permissions (module_bit, code, description) VALUES (13, 'upload_local_cover_images', 'Upload local cover images')|
4657     );
4658     print "Upgrade to $DBversion done (Added support for local cover images)\n";
4659     SetVersion($DBversion);
4660 }
4661
4662 $DBversion = "3.07.00.011";
4663 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4664     $dbh->do(<<ENDOFRENEWAL);
4665     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');
4666 ENDOFRENEWAL
4667     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";
4668     SetVersion($DBversion);
4669 }
4670
4671 $DBversion = "3.07.00.012";
4672 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4673     $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')");
4674     print "Upgrade to $DBversion add 'AllowItemsOnHoldCheckout' syspref \n";
4675     SetVersion ($DBversion);
4676 }
4677
4678 $DBversion = "3.07.00.013";
4679 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4680     $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');");
4681     print "Upgrade to $DBversion done (Bug 7345: Add system preference OpacExportOptions.)\n";
4682     SetVersion ($DBversion);
4683 }
4684
4685 $DBversion = "3.07.00.014";
4686 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4687     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";
4688     SetVersion($DBversion);
4689 }
4690
4691 $DBversion = "3.07.00.015";
4692 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4693     my $sth = $dbh->prepare(q|
4694         SELECT COUNT(*) FROM marc_subfield_structure where kohafield="biblioitems.editionstatement"
4695         |);
4696     $sth->execute;
4697     my $already_exists = $sth->fetchrow;
4698     if ( not $already_exists ) {
4699         my $field = C4::Context->preference("marcflavour") eq "UNIMARC" ? "205" : "250";
4700         my $subfield = "a";
4701         my $sth = $dbh->prepare( q|
4702             UPDATE marc_subfield_structure SET kohafield = "biblioitems.editionstatement"
4703             WHERE tagfield = ? AND tagsubfield = ?
4704         |);
4705         $sth->execute( $field, $subfield );
4706         print "Upgrade to $DBversion done (Added a mapping for biblioitems.editionstatement.)\n";
4707     } else {
4708         print "Upgrade to $DBversion done (Added a mapping for biblioitems.editionstatement (already exists, nothing to do).)\n";
4709     }
4710     SetVersion($DBversion);
4711 }
4712
4713 $DBversion = "3.07.00.016";
4714 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4715     $dbh->do("ALTER TABLE items ADD KEY `itemcallnumber` (itemcallnumber)");
4716     print "Upgrade to $DBversion done (Added index on items.itemcallnumber)\n";
4717     SetVersion($DBversion);
4718 }
4719
4720 $DBversion = "3.07.00.017";
4721 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4722     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('TransferWhenCancelAllWaitingHolds','0','Transfer items when cancelling all waiting holds',NULL,'YesNo')");
4723     print "Upgrade to $DBversion done (Add sysprefs to control transfer when cancel all waiting holds)\n";
4724     SetVersion ($DBversion);
4725 }
4726
4727 $DBversion = "3.07.00.018";
4728 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4729     $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;");
4730     print "Upgrade to $DBversion done ( adding offline operations table )\n";
4731     SetVersion($DBversion);
4732 }
4733
4734 $DBversion = "3.07.00.019";
4735 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4736     $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");
4737     $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");
4738     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";
4739     SetVersion($DBversion);
4740 }
4741
4742 $DBversion = "3.07.00.020";
4743 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4744     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OPACpatronimages',0,'Enable patron images in the OPAC',NULL,'YesNo');");
4745     print "Upgrade to $DBversion done (Bug 3516: Add the option to show patron images in the OPAC.)\n";
4746     SetVersion($DBversion);
4747 }
4748
4749 $DBversion = "3.07.00.021";
4750 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4751     $dbh->do(
4752     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('LinkerModule','Default','Chooses which linker module to use (see documentation).','Default|FirstMatchLastMatch','Choice');"
4753     );
4754     $dbh->do(
4755     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('LinkerOptions','','A pipe-separated list of options for the linker.','','free');"
4756     );
4757     $dbh->do(
4758     "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');"
4759     );
4760     $dbh->do(
4761     "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');"
4762     );
4763     $dbh->do(
4764     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AutoCreateAuthorities',0,'Automatically create authorities that do not exist when cataloging records.',NULL,'YesNo');"
4765     );
4766     $dbh->do(
4767     "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');"
4768     );
4769     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";
4770     SetVersion($DBversion);
4771 }
4772
4773 $DBversion = "3.07.00.022";
4774 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4775     $dbh->do("DELETE FROM reviews WHERE biblionumber NOT IN (SELECT biblionumber from biblio)");
4776     $dbh->do("UPDATE reviews SET borrowernumber = NULL WHERE borrowernumber NOT IN (SELECT borrowernumber FROM borrowers)");
4777     $dbh->do("ALTER TABLE reviews ADD CONSTRAINT reviews_ibfk_2 FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE");
4778     $dbh->do("ALTER TABLE reviews ADD CONSTRAINT reviews_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber ) ON UPDATE CASCADE ON DELETE SET NULL");
4779     print "Upgrade to $DBversion done (Bug 7493 - Add constraint linking OPAC comment biblionumber to biblio, OPAC comment borrowernumber to borrowers.)\n";
4780     SetVersion($DBversion);
4781 }
4782
4783 $DBversion = "3.07.00.023";
4784 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4785     $dbh->do("ALTER TABLE `message_transports` DROP FOREIGN KEY `message_transports_ibfk_3`");
4786     $dbh->do("ALTER TABLE `letter` DROP PRIMARY KEY");
4787     $dbh->do("ALTER TABLE `letter` ADD `branchcode` varchar(10) default NULL AFTER `code`");
4788     $dbh->do("ALTER TABLE `letter` ADD PRIMARY KEY  (`module`,`code`, `branchcode`)");
4789     $dbh->do("ALTER TABLE `message_transports` ADD `branchcode` varchar(10) NOT NULL default ''");
4790     $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");
4791     $dbh->do("ALTER TABLE `letter` ADD `is_html` tinyint(1) default 0 AFTER `name`");
4792
4793     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4794               VALUES ('circulation','ISSUESLIP','Issue Slip','Issue Slip', '<h3><<branches.branchname>></h3>
4795 Checked out to <<borrowers.title>> <<borrowers.firstname>> <<borrowers.initials>> <<borrowers.surname>> <br />
4796 (<<borrowers.cardnumber>>) <br />
4797
4798 <<today>><br />
4799
4800 <h4>Checked Out</h4>
4801 <checkedout>
4802 <p>
4803 <<biblio.title>> <br />
4804 Barcode: <<items.barcode>><br />
4805 Date due: <<issues.date_due>><br />
4806 </p>
4807 </checkedout>
4808
4809 <h4>Overdues</h4>
4810 <overdue>
4811 <p>
4812 <<biblio.title>> <br />
4813 Barcode: <<items.barcode>><br />
4814 Date due: <<issues.date_due>><br />
4815 </p>
4816 </overdue>
4817
4818 <hr>
4819
4820 <h4 style=\"text-align: center; font-style:italic;\">News</h4>
4821 <news>
4822 <div class=\"newsitem\">
4823 <h5 style=\"margin-bottom: 1px; margin-top: 1px\"><b><<opac_news.title>></b></h5>
4824 <p style=\"margin-bottom: 1px; margin-top: 1px\"><<opac_news.new>></p>
4825 <p class=\"newsfooter\" style=\"font-size: 8pt; font-style:italic; margin-bottom: 1px; margin-top: 1px\">Posted on <<opac_news.timestamp>></p>
4826 <hr />
4827 </div>
4828 </news>', 1)");
4829     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4830               VALUES ('circulation','ISSUEQSLIP','Issue Quick Slip','Issue Quick Slip', '<h3><<branches.branchname>></h3>
4831 Checked out to <<borrowers.title>> <<borrowers.firstname>> <<borrowers.initials>> <<borrowers.surname>> <br />
4832 (<<borrowers.cardnumber>>) <br />
4833
4834 <<today>><br />
4835
4836 <h4>Checked Out Today</h4>
4837 <checkedout>
4838 <p>
4839 <<biblio.title>> <br />
4840 Barcode: <<items.barcode>><br />
4841 Date due: <<issues.date_due>><br />
4842 </p>
4843 </checkedout>', 1)");
4844     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4845               VALUES ('circulation','RESERVESLIP','Reserve Slip','Reserve Slip', '<h5>Date: <<today>></h5>
4846
4847 <h3> Transfer to/Hold in <<branches.branchname>></h3>
4848
4849 <h3><<borrowers.surname>>, <<borrowers.firstname>></h3>
4850
4851 <ul>
4852     <li><<borrowers.cardnumber>></li>
4853     <li><<borrowers.phone>></li>
4854     <li> <<borrowers.address>><br />
4855          <<borrowers.address2>><br />
4856          <<borrowers.city >>  <<borrowers.zipcode>>
4857     </li>
4858     <li><<borrowers.email>></li>
4859 </ul>
4860 <br />
4861 <h3>ITEM ON HOLD</h3>
4862 <h4><<biblio.title>></h4>
4863 <h5><<biblio.author>></h5>
4864 <ul>
4865    <li><<items.barcode>></li>
4866    <li><<items.itemcallnumber>></li>
4867    <li><<reserves.waitingdate>></li>
4868 </ul>
4869 <p>Notes:
4870 <pre><<reserves.reservenotes>></pre>
4871 </p>', 1)");
4872     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4873               VALUES ('circulation','TRANSFERSLIP','Transfer Slip','Transfer Slip', '<h5>Date: <<today>></h5>
4874 <h3>Transfer to <<branches.branchname>></h3>
4875
4876 <h3>ITEM</h3>
4877 <h4><<biblio.title>></h4>
4878 <h5><<biblio.author>></h5>
4879 <ul>
4880    <li><<items.barcode>></li>
4881    <li><<items.itemcallnumber>></li>
4882 </ul>', 1)");
4883
4884     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('NoticeCSS','','Notices CSS url.',NULL,'free')");
4885     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('SlipCSS','','Slips CSS url.',NULL,'free')");
4886
4887     $dbh->do("UPDATE `letter` SET content = replace(content, '<<title>>', '<<biblio.title>>') WHERE code = 'HOLDPLACED'");
4888
4889     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";
4890     SetVersion($DBversion);
4891 }
4892
4893 $DBversion = "3.07.00.024";
4894 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4895     $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')");
4896     $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')");
4897     print "Upgrade to $DBversion done (Added system preference ExpireReservesMaxPickUpDelay, system preference ExpireReservesMaxPickUpDelayCharge, add reseves.charge_if_expired)\n";
4898 }
4899
4900 $DBversion = "3.07.00.025";
4901 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4902     if (TableExists('bibliocoverimage')) {
4903         $dbh->do( q|DROP TABLE bibliocoverimage;| );
4904         $dbh->do(
4905             q|CREATE TABLE biblioimages (
4906               imagenumber int(11) NOT NULL AUTO_INCREMENT,
4907               biblionumber int(11) NOT NULL,
4908               mimetype varchar(15) NOT NULL,
4909               imagefile mediumblob NOT NULL,
4910               thumbnail mediumblob NOT NULL,
4911               PRIMARY KEY (imagenumber),
4912               CONSTRAINT bibliocoverimage_fk1 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
4913               ) ENGINE=InnoDB DEFAULT CHARSET=utf8;|
4914         );
4915     }
4916     print "Upgrade to $DBversion done (Correct table name for local cover images if needed. )\n";
4917     SetVersion($DBversion);
4918 }
4919
4920 $DBversion = "3.07.00.026";
4921 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4922     $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');");
4923     print "Upgrade to $DBversion done (Add syspref CalendarFirstDayOfWeek used to select the first day of week to use in the calendar. )\n";
4924     SetVersion($DBversion);
4925 }
4926
4927 $DBversion = "3.07.00.027";
4928 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4929     $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');});
4930     print "Upgrade to $DBversion done (Added system preference RoutingListNote for adding a general note to all routing lists.)\n";
4931     SetVersion($DBversion);
4932 }
4933
4934 $DBversion = "3.07.00.028";
4935 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4936     $dbh->do(qq{
4937     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');
4938     });
4939     print "Upgrade to $DBversion done (Bug 6296 New System preference AllowPKIAuth)\n";
4940 }
4941
4942 $DBversion = "3.07.00.029";
4943 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4944     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_descriptions`;});
4945     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_mappings`;});
4946     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_biblios`;});
4947     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets`;});
4948
4949     $dbh->do(q{
4950         CREATE TABLE `oai_sets` (
4951           `id` int(11) NOT NULL auto_increment,
4952           `spec` varchar(80) NOT NULL UNIQUE,
4953           `name` varchar(80) NOT NULL,
4954           PRIMARY KEY (`id`)
4955         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4956     });
4957
4958     $dbh->do(q{
4959         CREATE TABLE `oai_sets_descriptions` (
4960           `set_id` int(11) NOT NULL,
4961           `description` varchar(255) NOT NULL,
4962           CONSTRAINT `oai_sets_descriptions_ibfk_1` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4963         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4964     });
4965
4966     $dbh->do(q{
4967         CREATE TABLE `oai_sets_mappings` (
4968           `set_id` int(11) NOT NULL,
4969           `marcfield` char(3) NOT NULL,
4970           `marcsubfield` char(1) NOT NULL,
4971           `marcvalue` varchar(80) NOT NULL,
4972           CONSTRAINT `oai_sets_mappings_ibfk_1` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4973         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4974     });
4975
4976     $dbh->do(q{
4977         CREATE TABLE `oai_sets_biblios` (
4978           `biblionumber` int(11) NOT NULL,
4979           `set_id` int(11) NOT NULL,
4980           PRIMARY KEY (`biblionumber`, `set_id`),
4981           CONSTRAINT `oai_sets_biblios_ibfk_1` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
4982           CONSTRAINT `oai_sets_biblios_ibfk_2` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4983         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4984     });
4985
4986     $dbh->do(q{
4987         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');
4988     });
4989
4990     print "Upgrade to $DBversion done (Atomic update for OAI-PMH sets management)\n";
4991     SetVersion($DBversion);
4992 }
4993
4994 $DBversion = "3.07.00.030";
4995 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4996     $dbh->do("ALTER TABLE default_circ_rules ADD
4997             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
4998     $dbh->do("ALTER TABLE branch_item_rules ADD
4999             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5000     $dbh->do("ALTER TABLE default_branch_circ_rules ADD
5001             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5002     $dbh->do("ALTER TABLE default_branch_item_rules ADD
5003             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5004     # set the default rule to the current value of HomeOrHoldingBranchReturn (default to 'homebranch' if need be)
5005     my $homeorholdingbranchreturn = C4::Context->prefernce('HomeOrHoldingBranchReturn') || 'homebranch';
5006     $dbh->do("UPDATE default_circ_rules SET returnbranch = '$homeorholdingbranchreturn'");
5007     print "Upgrade to $DBversion done (Atomic update for OAI-PMH sets management)\n";
5008     SetVersion($DBversion);
5009 }
5010
5011 $DBversion = "3.07.00.031";
5012 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5013     $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')");
5014     print "Upgrade to $DBversion done (Add syspref to tell Koha if ICU indexing is in use for Zebra or not.)\n";
5015     SetVersion ($DBversion);
5016 }
5017
5018 $DBversion = "3.07.00.032";
5019 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5020     $dbh->do("ALTER TABLE virtualshelves MODIFY COLUMN owner int"); #should have been int already (fk to borrowers)
5021     $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
5022     $dbh->do("DELETE FROM virtualshelves WHERE owner IS NULL and category=1"); #delete private lists without owner (cascades to shelfcontents)
5023     $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");
5024     $dbh->do("UPDATE virtualshelves SET allow_add=0, allow_delete_own=1, allow_delete_other=0 WHERE category=1");
5025     $dbh->do("UPDATE virtualshelves SET allow_add=0, allow_delete_own=1, allow_delete_other=0 WHERE category=2");
5026     $dbh->do("UPDATE virtualshelves SET allow_add=1, allow_delete_own=1, allow_delete_other=1 WHERE category=3");
5027     $dbh->do("UPDATE virtualshelves SET category=2 WHERE category=3");
5028
5029     $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");
5030     $dbh->do("UPDATE virtualshelfcontents co LEFT JOIN virtualshelves sh USING (shelfnumber) SET co.borrowernumber=sh.owner");
5031
5032     $dbh->do("CREATE TABLE virtualshelfshares
5033     (id int AUTO_INCREMENT PRIMARY KEY, shelfnumber int NOT NULL,
5034     borrowernumber int, invitekey varchar(10), sharedate datetime,
5035     CONSTRAINT `virtualshelfshares_ibfk_1` FOREIGN KEY (`shelfnumber`) REFERENCES `virtualshelves` (`shelfnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
5036         CONSTRAINT `virtualshelfshares_ibfk_2` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE SET NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8");
5037
5038     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacAllowPublicListCreation',1,'If set, allows opac users to create public lists',NULL,'YesNo');");
5039     $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');");
5040
5041     print "Upgrade to $DBversion done (BZ7310: Improving list permissions)\n";
5042     SetVersion($DBversion);
5043 }
5044
5045 $DBversion = "3.07.00.033";
5046 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5047     $dbh->do("ALTER TABLE branches ADD opac_info text;");
5048     print "Upgrade to $DBversion done add opac_info to branches \n";
5049     SetVersion($DBversion);
5050 }
5051
5052 $DBversion = "3.07.00.034";
5053 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5054     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN category_code VARCHAR(10) NULL DEFAULT NULL AFTER `display_checkout`");
5055     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN class VARCHAR(255)  NOT NULL DEFAULT '' AFTER `category_code`");
5056     $dbh->do("ALTER TABLE borrower_attribute_types ADD CONSTRAINT category_code_fk FOREIGN KEY (category_code) REFERENCES categories(categorycode)");
5057     print "Upgrade to $DBversion done (New fields category_code and class in borrower_attribute_types table)\n";
5058     SetVersion($DBversion);
5059 }
5060
5061 $DBversion = "3.07.00.035";
5062 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5063     $dbh->do("ALTER TABLE issues CHANGE date_due date_due datetime");
5064     $dbh->do("UPDATE issues SET date_due = CONCAT(SUBSTR(date_due,1,11),'23:59:00')");
5065     $dbh->do("ALTER TABLE issues CHANGE returndate returndate datetime");
5066     $dbh->do("ALTER TABLE issues CHANGE lastreneweddate lastreneweddate datetime");
5067     $dbh->do("ALTER TABLE issues CHANGE issuedate issuedate datetime");
5068     $dbh->do("ALTER TABLE old_issues CHANGE date_due date_due datetime");
5069     $dbh->do("ALTER TABLE old_issues CHANGE returndate returndate datetime");
5070     $dbh->do("ALTER TABLE old_issues CHANGE lastreneweddate lastreneweddate datetime");
5071     $dbh->do("ALTER TABLE old_issues CHANGE issuedate issuedate datetime");
5072     $dbh->do("UPDATE accountlines SET description = CONCAT(description,' 23:59') WHERE accounttype='F' OR accounttype='FU'"); #BUG-8253
5073     print "Upgrade to $DBversion done (Setting up issues and accountlines tables for hourly loans)\n";
5074     SetVersion($DBversion);
5075 }
5076
5077 $DBversion = "3.07.00.036";
5078 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5079     $dbh->do(qq{
5080        ALTER TABLE z3950servers ADD timeout INT( 11 ) NOT NULL DEFAULT '0' AFTER syntax;
5081     });
5082     print "Upgrade to $DBversion done (New timeout field in z3950servers)\n";
5083 }
5084
5085 $DBversion = "3.07.00.037";
5086 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5087     $dbh->do("
5088        ALTER TABLE  `marc_subfield_structure` ADD  `maxlength` INT( 4 ) NOT NULL DEFAULT  '9999';
5089        ");
5090        $dbh->do("
5091        UPDATE `marc_subfield_structure` SET maxlength=24 WHERE tagfield='000';
5092        ");
5093        $dbh->do("
5094        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='MARC21','40','9999') WHERE tagfield='008';
5095        ");
5096        $dbh->do("
5097        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='NORMARC','40','9999') WHERE tagfield='008';
5098        ");
5099        $dbh->do("
5100        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='UNIMARC','36','9999') WHERE tagfield='100';
5101        ");
5102     print "Upgrade to $DBversion done (Add new field maxlength to marc_subfield_structure)\n";
5103     SetVersion($DBversion);
5104 }
5105
5106 $DBversion = "3.07.00.038";
5107 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5108     $dbh->do(qq{
5109         INSERT INTO systempreferences(variable,value,explanation,options,type)
5110         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')
5111     });
5112     print "Upgrade to $DBversion done (Added system preference 'UniqueItemFields')\n";
5113     SetVersion($DBversion);
5114 }
5115
5116 $DBversion = "3.07.00.039";
5117 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5118     $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')} );
5119     $dbh->do( qq{CREATE TABLE IF NOT EXISTS social_data
5120       ( isbn VARCHAR(30),
5121         num_critics INT,
5122         num_critics_pro INT,
5123         num_quotations INT,
5124         num_videos INT,
5125         score_avg DECIMAL(5,2),
5126         num_scores INT,
5127         PRIMARY KEY  (isbn)
5128       ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5129     } );
5130     $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')} );
5131     print "Upgrade to $DBversion done (added syspref and table for babeltheque (Babeltheque_url_js, babeltheque))\n";
5132     SetVersion($DBversion);
5133 }
5134
5135 $DBversion = "3.07.00.040";
5136 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5137     $dbh->do( qq{INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('SocialNetworks','0','Enable/Disable social networks links in opac detail','','YesNo')} );
5138     print "Upgrade to $DBversion done (added syspref SocialNetworks, to display facebook/ggl+ and other buttons)\n";
5139     SetVersion($DBversion);
5140 }
5141
5142
5143
5144 $DBversion = "3.07.00.041";
5145 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5146     $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')");
5147     print "Upgrade to $DBversion done (Add system preference SubscriptionDuplicateDroppedInput)\n";
5148     SetVersion($DBversion);
5149 }
5150
5151 $DBversion = "3.07.00.042";
5152 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5153     $dbh->do("ALTER TABLE reserves ADD suspend BOOLEAN NOT NULL DEFAULT 0");
5154     $dbh->do("ALTER TABLE old_reserves ADD suspend BOOLEAN NOT NULL DEFAULT 0");
5155
5156     $dbh->do("ALTER TABLE reserves ADD suspend_until DATETIME NULL DEFAULT NULL");
5157     $dbh->do("ALTER TABLE old_reserves ADD suspend_until DATETIME NULL DEFAULT NULL");
5158
5159     $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')");
5160
5161     print "Upgrade to $DBversion done (Add suspend fields to reserves table, add syspref AutoResumeSuspendedHolds)\n";
5162     SetVersion ($DBversion);
5163 }
5164
5165 $DBversion = "3.07.00.043";
5166 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5167     my $countXSLTDetailsDisplay = 0;
5168     my $valueXSLTDetailsDisplay = "";
5169     my $valueXSLTResultsDisplay = "";
5170     my $valueOPACXSLTDetailsDisplay = "";
5171     my $valueOPACXSLTResultsDisplay = "";
5172     #the line below test if database comes from a BibLibre's branch
5173     $countXSLTDetailsDisplay = $dbh->do('SELECT 1 FROM systempreferences WHERE variable="IntranetXSLTDetailsDisplay"');
5174     if ($countXSLTDetailsDisplay > 0)
5175     {
5176         #the two lines below will only be used to update the databases from the BibLibre's branch. They will not affect the others
5177         $dbh->do(q|UPDATE systempreferences SET variable="XSLTDetailsDisplay" WHERE variable="IntranetXSLTDetailsDisplay"|);
5178         $dbh->do(q|UPDATE systempreferences SET variable="XSLTResultsDisplay" WHERE variable="IntranetXSLTResultsDisplay"|);
5179     }
5180     else
5181     {
5182         $valueXSLTDetailsDisplay = "default" if (C4::Context->preference("XSLTDetailsDisplay"));
5183         $valueXSLTResultsDisplay = "default" if (C4::Context->preference("XSLTResultsDisplay"));
5184         $valueOPACXSLTDetailsDisplay = "default" if (C4::Context->preference("OPACXSLTDetailsDisplay"));
5185         $valueOPACXSLTResultsDisplay = "default" if (C4::Context->preference("OPACXSLTResultsDisplay"));
5186         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueXSLTDetailsDisplay\" WHERE variable='XSLTDetailsDisplay'");
5187         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueXSLTResultsDisplay\" WHERE variable='XSLTResultsDisplay'");
5188         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueOPACXSLTDetailsDisplay\" WHERE variable='OPACXSLTDetailsDisplay'");
5189         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueOPACXSLTResultsDisplay\" WHERE variable='OPACXSLTResultsDisplay'");
5190     }
5191     print "Upgrade to $DBversion done (XSLT systempreference takes a path to file rather than YesNo)\n";
5192     SetVersion($DBversion);
5193 }
5194
5195 $DBversion = "3.07.00.044";
5196 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5197     $dbh->do("ALTER TABLE aqbooksellers ADD deliverytime INT DEFAULT NULL");
5198     print "Upgrade to $DBversion done (Add deliverytime field in aqbooksellers table)";
5199     SetVersion($DBversion);
5200 }
5201
5202 $DBversion = "3.07.00.045";
5203 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5204     $dbh->do("ALTER TABLE import_batches MODIFY COLUMN batch_type ENUM('batch','z3950','webservice') NOT NULL default 'batch'");
5205     print "Upgrade to $DBversion done (Add 'webservice' to batch_type enum)\n";
5206     SetVersion ($DBversion);
5207 }
5208
5209 $DBversion = "3.07.00.046";
5210 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5211     $dbh->do("ALTER TABLE issuingrules ADD COLUMN lengthunit varchar(10) DEFAULT 'days' AFTER issuelength");
5212     print "Upgrade to $DBversion done (Setting up issues tables for hourly loans (lengthunit fix))\n";
5213     SetVersion($DBversion);
5214 }
5215
5216 $DBversion = "3.07.00.047";
5217 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5218     $dbh->do("CREATE INDEX items_location ON items(location)");
5219     $dbh->do("CREATE INDEX items_ccode ON items(ccode)");
5220     print "Upgrade to $DBversion done (items_location and items_ccode indexes added for ShelfBrowser)\n";
5221     SetVersion($DBversion);
5222 }
5223
5224 $DBversion = "3.07.00.048";
5225 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5226     $dbh->do(
5227         q | CREATE TABLE ratings (
5228   borrowernumber int(11) NOT NULL,
5229   biblionumber int(11) NOT NULL,
5230   rating_value tinyint(1) NOT NULL,
5231   timestamp timestamp NOT NULL default CURRENT_TIMESTAMP,
5232   PRIMARY KEY  (borrowernumber,biblionumber),
5233   CONSTRAINT ratings_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE,
5234   CONSTRAINT ratings_ibfk_2 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
5235 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
5236     );
5237
5238     $dbh->do(
5239 q /INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OpacStarRatings','disable',NULL,'disable|all|details','Choice') /
5240     );
5241
5242     print
5243 "Upgrade to $DBversion done (Add 'ratings' table and 'OpacStarRatings' syspref)\n";
5244     SetVersion($DBversion);
5245 }
5246
5247 $DBversion = "3.07.00.049";
5248 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5249     $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')");
5250     print "Upgrade to $DBversion done (Add system preference OpacBrowseResults ))\n";
5251     SetVersion($DBversion);
5252 }
5253
5254 $DBversion = "3.08.00.000";
5255 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5256     print "Upgrade to $DBversion done\n";
5257     SetVersion($DBversion);
5258 }
5259
5260 $DBversion = "3.09.00.001";
5261 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5262     $dbh->do("ALTER TABLE borrower_attribute_types MODIFY category_code VARCHAR( 1 ) NULL DEFAULT NULL");
5263     print "Upgrade to $DBversion done. (Bug 8002: Update patron attribute types table to allow NULL category_code)\n";
5264     SetVersion($DBversion);
5265 }
5266
5267 $DBversion = "3.09.00.002";
5268 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5269     $dbh->do("ALTER TABLE saved_sql
5270         ADD (
5271             cache_expiry INT NOT NULL DEFAULT 300,
5272             public BOOLEAN NOT NULL DEFAULT FALSE
5273         );
5274     ");
5275     print "Upgrade to $DBversion done (Added cache_expiry and public fields in
5276 saved_reports table.)\n";
5277     SetVersion($DBversion);
5278 }
5279
5280 $DBversion = "3.09.00.003";
5281 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5282     $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');");
5283     print "Upgrade to $DBversion done (Added SvcMaxReportRows syspref)\n";
5284     SetVersion($DBversion);
5285 }
5286
5287 $DBversion = "3.09.00.004";
5288 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5289     $dbh->do("INSERT IGNORE INTO permissions (module_bit, code, description) VALUES('13', 'edit_patrons', 'Perform batch modifivation of patrons')");
5290     print "Upgrade to $DBversion done (Adds permissions flag for access to the patron modifications tool)\n";
5291     SetVersion($DBversion);
5292 }
5293
5294 $DBversion = "3.09.00.005";
5295 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5296     unless (TableExists('quotes')) {
5297         $dbh->do( qq{
5298             CREATE TABLE `quotes` (
5299               `id` int(11) NOT NULL AUTO_INCREMENT,
5300               `source` text DEFAULT NULL,
5301               `text` mediumtext NOT NULL,
5302               `timestamp` datetime NOT NULL,
5303               PRIMARY KEY (`id`)
5304             ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5305         });
5306     }
5307     $dbh->do( qq{
5308         INSERT IGNORE INTO permissions VALUES (13, "edit_quotes","Edit quotes for quote-of-the-day feature");
5309     });
5310     $dbh->do( qq{
5311         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');
5312     });
5313     print "Upgrade to $DBversion done (Adding Quote of the Day Option.)\n";
5314     SetVersion($DBversion);
5315 }
5316
5317 $DBversion = "3.09.00.006";
5318 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5319     $dbh->do("UPDATE systempreferences SET
5320                 variable = 'OPACShowHoldQueueDetails',
5321                 value = CASE value WHEN '1' THEN 'priority' ELSE 'none' END,
5322                 options = 'none|priority|holds|holds_priority',
5323                 explanation = 'Show holds details in OPAC',
5324                 type = 'Choice'
5325               WHERE variable = 'OPACDisplayRequestPriority'");
5326     print "Upgrade to $DBversion done (Changed system preference OPACDisplayRequestPriority -> OPACShowHoldQueueDetails)\n";
5327     SetVersion($DBversion);
5328 }
5329
5330 $DBversion = "3.09.00.007";
5331 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5332     unless(C4::Context->preference('ReservesControlBranch')){
5333         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('ReservesControlBranch','PatronLibrary','ItemHomeLibrary|PatronLibrary','Branch checked for members reservations rights.','Choice')");
5334     }
5335     print "Upgrade to $DBversion done (Insert ReservesControlBranch systempreference into systempreferences table )\n";
5336     SetVersion($DBversion);
5337 }
5338
5339 $DBversion = "3.09.00.008";
5340 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5341     $dbh->do("ALTER TABLE sessions ADD PRIMARY KEY (id);");
5342     $dbh->do("ALTER TABLE sessions DROP INDEX `id`;");
5343     print "Upgrade to $DBversion done (redefine the field id as PRIMARY KEY of sessions)\n";
5344     SetVersion($DBversion);
5345 }
5346
5347 $DBversion = "3.09.00.009";
5348 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5349     $dbh->do("ALTER TABLE branches ADD PRIMARY KEY (branchcode);");
5350     $dbh->do("ALTER TABLE branches DROP INDEX branchcode;");
5351     print "Upgrade to $DBversion done (redefine the field branchcode as PRIMARY KEY of branches)\n";
5352     SetVersion ($DBversion);
5353 }
5354
5355 $DBversion = "3.09.00.010";
5356 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5357     $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')");
5358     print "Upgrade to $DBversion done (Add system preference issuelostitem ))\n";
5359     SetVersion($DBversion);
5360 }
5361
5362 $DBversion = "3.09.00.011";
5363 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5364     $dbh->do("ALTER TABLE `biblioitems` ADD `ean` VARCHAR( 13 ) NULL AFTER issn");
5365     $dbh->do("CREATE INDEX `ean` ON biblioitems (`ean`) ");
5366     $dbh->do("ALTER TABLE `deletedbiblioitems` ADD `ean` VARCHAR( 13 ) NULL AFTER issn");
5367     if (C4::Context->preference("marcflavour") eq 'UNIMARC') {
5368          $dbh->do("UPDATE marc_subfield_structure SET kohafield='biblioitems.ean' WHERE tagfield='073' and tagsubfield='a'");
5369     }
5370     print "Upgrade to $DBversion done (Adding ean in biblioitems and deletedbiblioitems)\n";
5371     print "If you have records with ean, please run misc/batchRebuildBiblioTables.pl to populate bibliotems.ean\n" if (C4::Context->preference("marcflavour") eq 'UNIMARC');
5372     SetVersion($DBversion);
5373 }
5374
5375 $DBversion = "3.09.00.012";
5376 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5377     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('SuspendHoldsIntranet', '1', NULL , 'Allow holds to be suspended from the intranet.', 'YesNo')");
5378     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('SuspendHoldsOpac', '1', NULL , 'Allow holds to be suspended from the OPAC.', 'YesNo')");
5379     print "Upgrade to $DBversion done (Add system preference OpacBrowseResults ))\n";
5380     SetVersion($DBversion);
5381 }
5382
5383 $DBversion ="3.09.00.013";
5384 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5385     $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');");
5386     print "Upgrade to $DBversion done (Add system preference DefaultLanguageField008))\n";
5387     SetVersion($DBversion);
5388 }
5389
5390 $DBversion ="3.09.00.014";
5391 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5392     # add phone message transport type
5393     $dbh->do("INSERT INTO message_transport_types (message_transport_type) VALUES ('phone')");
5394
5395     # adds HOLD_PHONE and PREDUE_PHONE letters (as placeholders)
5396     $dbh->do("INSERT INTO letter (module, code, name, title, content) VALUES
5397               ('reserves', 'HOLD_PHONE', 'Item Available for Pick-up (phone notice)', 'Item Available for Pick-up (phone notice)', 'Your item is available for pickup'),
5398               ('circulation', 'PREDUE_PHONE', 'Advance Notice of Item Due (phone notice)', 'Advance Notice of Item Due (phone notice)', 'Your item is due soon'),
5399               ('circulation', 'OVERDUE_PHONE', 'Overdue Notice (phone notice)', 'Overdue Notice (phone notice)', 'Your item is overdue')
5400               ");
5401
5402     # add phone notifications to patron message preferences options
5403     $dbh->do("INSERT INTO message_transports
5404              (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) VALUES
5405              (4, 'phone', 0, 'reserves', 'HOLD_PHONE'),
5406              (2, 'phone', 0, 'circulation', 'PREDUE_PHONE')
5407              ");
5408
5409     # add TalkingTechItivaPhoneNotification syspref
5410     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('TalkingTechItivaPhoneNotification',0,'If ON, enables Talking Tech I-tiva phone notifications',NULL,'YesNo');");
5411
5412     print "Upgrade done (Support for Talking Tech i-tiva phone notification system)\n";
5413     SetVersion($DBversion);
5414 }
5415
5416 $DBversion = "3.09.00.015";
5417 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5418     $dbh->do(qq{
5419         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')
5420     });
5421     print "Upgrade to $DBversion done (Add System preference StatisticsFields)\n";
5422     SetVersion($DBversion);
5423 }
5424
5425 $DBversion = "3.09.00.016";
5426 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5427     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACShowBarcode','0','Show items barcode in holding tab','','YesNo')");
5428     print "Upgrade to $DBversion done (Add syspref OPACShowBarcode)\n";
5429     SetVersion ($DBversion);
5430 }
5431
5432 $DBversion = "3.09.00.017";
5433 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5434     $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');");
5435     print "Upgrade to $DBversion done (Add customizable OpacNavRight region to the OPAC main page)\n";
5436     SetVersion ($DBversion);
5437 }
5438
5439 $DBversion = "3.09.00.018";
5440 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5441     $dbh->do("DROP TABLE IF EXISTS aqbudgetborrowers");
5442     $dbh->do("
5443         CREATE TABLE aqbudgetborrowers (
5444           budget_id int(11) NOT NULL,
5445           borrowernumber int(11) NOT NULL,
5446           PRIMARY KEY (budget_id, borrowernumber),
5447           CONSTRAINT aqbudgetborrowers_ibfk_1 FOREIGN KEY (budget_id)
5448             REFERENCES aqbudgets (budget_id)
5449             ON DELETE CASCADE ON UPDATE CASCADE,
5450           CONSTRAINT aqbudgetborrowers_ibfk_2 FOREIGN KEY (borrowernumber)
5451             REFERENCES borrowers (borrowernumber)
5452             ON DELETE CASCADE ON UPDATE CASCADE
5453         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
5454     ");
5455     $dbh->do("
5456         INSERT INTO permissions (module_bit, code, description)
5457         VALUES (11, 'budget_manage_all', 'Manage all budgets')
5458     ");
5459     print "Upgrade to $DBversion done (Add aqbudgetborrowers table)\n";
5460     SetVersion($DBversion);
5461 }
5462
5463 $DBversion = "3.09.00.019";
5464 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5465     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('OPACShowUnusedAuthorities','1','','Show authorities that are not being used in the OPAC.','YesNo')");
5466     print "Upgrade to $DBversion done (Add OPACShowUnusedAuthorities system preference)\n";
5467     SetVersion ($DBversion);
5468 }
5469
5470 $DBversion = "3.09.00.020";
5471 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5472     $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')");
5473     $dbh->do("
5474 CREATE TABLE IF NOT EXISTS borrower_files (
5475   file_id int(11) NOT NULL AUTO_INCREMENT,
5476   borrowernumber int(11) NOT NULL,
5477   file_name varchar(255) NOT NULL,
5478   file_type varchar(255) NOT NULL,
5479   file_description varchar(255) DEFAULT NULL,
5480   file_content longblob NOT NULL,
5481   date_uploaded timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
5482   PRIMARY KEY (file_id),
5483   KEY borrowernumber (borrowernumber)
5484 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
5485     ");
5486     $dbh->do("ALTER TABLE borrower_files ADD CONSTRAINT borrower_files_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE");
5487
5488     print "Upgrade to $DBversion done (Added borrow_files table, EnableBorrowerFiles syspref)\n";
5489     SetVersion($DBversion);
5490 }
5491
5492 $DBversion = "3.09.00.021";
5493 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5494     $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');");
5495     print "Upgrade to $DBversion done (Add syspref UpdateTotalIssuesOnCirc)\n";
5496     SetVersion($DBversion);
5497 }
5498
5499 $DBversion = "3.09.00.022";
5500 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5501     $dbh->do("ALTER TABLE search_history MODIFY COLUMN query_cgi text NOT NULL");
5502     print "Upgrade to $DBversion done (Change search_history.query_cgi type to text. bug 5981)\n";
5503     SetVersion($DBversion);
5504 }
5505
5506 $DBversion = "3.09.00.023";
5507 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5508     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('SearchEngine','Zebra','Solr|Zebra','Search Engine','Choice')");
5509     print "Upgrade to $DBversion done (Add system preference SearchEngine )\n";
5510     SetVersion($DBversion);
5511 }
5512
5513 $DBversion ="3.09.00.024";
5514 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5515     $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')");
5516     print "Upgrade to $DBversion done (Add system preference IntranetSlipPrinterJS))\n";
5517     SetVersion($DBversion);
5518 }
5519
5520 $DBversion = "3.09.00.025";
5521 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5522     $dbh->do('START TRANSACTION');
5523     $dbh->do('CREATE TABLE tmp_reserves AS SELECT * FROM old_reserves LIMIT 0');
5524     $dbh->do('ALTER TABLE tmp_reserves ADD reserve_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
5525     $dbh->do("
5526         INSERT INTO tmp_reserves (
5527           borrowernumber, reservedate, biblionumber,
5528           constrainttype, branchcode, notificationdate,
5529           reminderdate, cancellationdate, reservenotes,
5530           priority, found, timestamp, itemnumber,
5531           waitingdate, expirationdate, lowestPriority,
5532           suspend, suspend_until
5533         ) SELECT
5534           borrowernumber, reservedate, biblionumber,
5535           constrainttype, branchcode, notificationdate,
5536           reminderdate, cancellationdate, reservenotes,
5537           priority, found, timestamp, itemnumber,
5538           waitingdate, expirationdate, lowestPriority,
5539           suspend, suspend_until
5540         FROM old_reserves ORDER BY reservedate
5541     ");
5542     $dbh->do('SET @ai = ( SELECT MAX( reserve_id ) FROM tmp_reserves )');
5543     $dbh->do('TRUNCATE old_reserves');
5544     $dbh->do('ALTER TABLE old_reserves ADD reserve_id INT( 11 ) NOT NULL PRIMARY KEY FIRST');
5545     $dbh->do('INSERT INTO old_reserves SELECT * FROM tmp_reserves WHERE reserve_id <= @ai');
5546     $dbh->do("
5547         INSERT INTO tmp_reserves (
5548           borrowernumber, reservedate, biblionumber,
5549           constrainttype, branchcode, notificationdate,
5550           reminderdate, cancellationdate, reservenotes,
5551           priority, found, timestamp, itemnumber,
5552           waitingdate, expirationdate, lowestPriority,
5553           suspend, suspend_until
5554         ) SELECT
5555           borrowernumber, reservedate, biblionumber,
5556           constrainttype, branchcode, notificationdate,
5557           reminderdate, cancellationdate, reservenotes,
5558           priority, found, timestamp, itemnumber,
5559           waitingdate, expirationdate, lowestPriority,
5560           suspend, suspend_until
5561         FROM reserves ORDER BY reservedate
5562     ");
5563     $dbh->do('TRUNCATE reserves');
5564     $dbh->do('ALTER TABLE reserves ADD reserve_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
5565     $dbh->do('INSERT INTO reserves SELECT * FROM tmp_reserves WHERE reserve_id > COALESCE(@ai, 0)');
5566     $dbh->do('DROP TABLE tmp_reserves');
5567     $dbh->do('COMMIT');
5568
5569     my $sth = $dbh->prepare("
5570         SELECT COUNT( * ) AS count
5571         FROM information_schema.COLUMNS
5572         WHERE COLUMN_NAME =  'reserve_id'
5573         AND (
5574           TABLE_NAME LIKE  'reserves'
5575           OR
5576           TABLE_NAME LIKE  'old_reserves'
5577         )
5578     ");
5579     $sth->execute();
5580     my $row = $sth->fetchrow_hashref();
5581     die("Failed to add reserve_id to reserves tables, please refresh the page to try again.") unless ( $row->{'count'} );
5582
5583     print "Upgrade to $DBversion done (add reserve_id to reserves & old_reserves tables)\n";
5584     SetVersion($DBversion);
5585 }
5586
5587 $DBversion = "3.09.00.026";
5588 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5589     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
5590         ( 3, 'parameters_remaining_permissions', 'Remaining system parameters permissions'),
5591         ( 3, 'manage_circ_rules', 'manage circulation rules')");
5592     $dbh->do("INSERT INTO user_permissions (borrowernumber, module_bit, code)
5593         SELECT borrowernumber, 3, 'parameters_remaining_permissions'
5594         FROM borrowers WHERE flags & (1 << 3)");
5595     # Give new subpermissions to all users that have 'parameters' permission flag (bit 3) set
5596     # see userflags table
5597     $dbh->do("INSERT INTO user_permissions (borrowernumber, module_bit, code)
5598         SELECT borrowernumber, 3, 'manage_circ_rules'
5599         FROM borrowers WHERE flags & (1 << 3)");
5600     print "Upgrade to $DBversion done (Added parameters subpermissions)\n";
5601     SetVersion($DBversion);
5602 }
5603
5604 $DBversion = '3.09.00.027';
5605 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5606     $dbh->do("ALTER TABLE issuingrules ADD overduefinescap decimal(28,6) DEFAULT NULL");
5607     my $maxfine = C4::Context->preference('MaxFine');
5608     if ($maxfine && $maxfine < 900) { # an arbitrary value that tells us it's not "some huge value"
5609       $dbh->do("UPDATE issuingrules SET overduefinescap=?",undef,$maxfine);
5610       $dbh->do("UPDATE systempreferences SET value = NULL WHERE variable = 'MaxFine'");
5611     }
5612     $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'");
5613     print "Upgrade to $DBversion done (Bug 7420 add overduefinescap to circulation matrix)\n";
5614     SetVersion ($DBversion);
5615 }
5616
5617 $DBversion = "3.09.00.028";
5618 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5619     unless ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) {
5620         my %referencetypes = (  '00' => 'PERSO_NAME',
5621                                 '10' => 'CORPO_NAME',
5622                                 '11' => 'MEETI_NAME',
5623                                 '30' => 'UNIF_TITLE',
5624                                 '48' => 'CHRON_TERM',
5625                                 '50' => 'TOPIC_TERM',
5626                                 '51' => 'GEOGR_NAME',
5627                                 '55' => 'GENRE/FORM'
5628                 );
5629         my $query = q{SELECT DISTINCT authtypecode, tagfield
5630                     FROM auth_subfield_structure
5631                     WHERE (tagfield BETWEEN '400' AND '455' OR
5632                     tagfield BETWEEN '500' and '555') AND tagsubfield='a' AND
5633                     frameworkcode = '' AND ROW(authtypecode, tagfield) NOT IN
5634                     (SELECT authtypecode, tagfield FROM auth_subfield_structure
5635                     WHERE tagsubfield ='9' )};
5636         $sth = $dbh->prepare($query);
5637         $sth->execute;
5638         my $sth2 = $dbh->prepare(q{INSERT INTO auth_subfield_structure
5639                 (authtypecode, tagfield, tagsubfield, liblibrarian, libopac,
5640                  repeatable, mandatory, tab, authorised_value, value_builder,
5641                  seealso, isurl, hidden, linkid, kohafield, frameworkcode)
5642                 VALUES (?, ?, '9', '9 (RLIN)', '9 (RLIN)', 0, 0, ?, NULL, NULL,
5643                     NULL, 0, 1, '', '', '')});
5644         my $sth3 = $dbh->prepare(q{UPDATE auth_subfield_structure SET
5645                                     frameworkcode = ? WHERE authtypecode = ? AND
5646                                     tagfield = ? AND tagsubfield = 'a'});
5647         while (my $row = $sth->fetchrow_arrayref()) {
5648             my ($authtypecode, $field) = @$row;
5649             $sth2->execute($authtypecode, $field, substr($field, 0, 1));
5650             my $authtypemarker = substr $field, 1, 2;
5651             if ($authtypemarker && $referencetypes{$authtypemarker}) {
5652                 $sth3->execute($referencetypes{$authtypemarker}, $authtypecode, $field);
5653             }
5654         }
5655     }
5656
5657     print "Upgrade to $DBversion done (Add thesaurus links for MARC21/NORMARC)\n";
5658     SetVersion($DBversion);
5659 }
5660
5661 $DBversion = "3.09.00.029"; # FIXME
5662 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5663     $dbh->do("UPDATE systempreferences SET options=concat(options,'|EAN13') WHERE variable='itemBarcodeInputFilter' AND options NOT LIKE '%EAN13%'");
5664     print "Upgrade to $DBversion done (Add itemBarcodeInputFilter choice EAN13)\n";
5665
5666     $dbh->do("UPDATE systempreferences SET options = concat(options,'|EAN13'), explanation = concat(explanation,'; EAN13 - incremental') WHERE variable = 'autoBarcode' AND options NOT LIKE '%EAN13%'");
5667     print "Upgrade to $DBversion done ( Added EAN13 barcode autogeneration sequence )\n";
5668     SetVersion($DBversion);
5669 }
5670
5671 $DBversion ="3.09.00.030";
5672 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5673     my $query = "SELECT value FROM systempreferences WHERE variable='opacstylesheet'";
5674     my $remote= $dbh->selectrow_arrayref($query);
5675     $dbh->do("DELETE from systempreferences WHERE variable='opacstylesheet'");
5676     if($remote && $remote->[0]) {
5677         $query="UPDATE systempreferences SET value=? WHERE variable='opaclayoutstylesheet'";
5678         $dbh->do($query,undef,$remote->[0]);
5679         print "NOTE: The URL of your remote opac css file has been moved to preference opaclayoutstylesheet.\n";
5680     }
5681     print "Upgrade to $DBversion done (BZ 8263: Make OPAC stylesheet preferences more consistent)\n";
5682     SetVersion($DBversion);
5683 }
5684
5685 $DBversion = "3.09.00.031";
5686 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5687     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonReviews'");
5688     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonSimilarItems'");
5689     $dbh->do("DELETE FROM systempreferences WHERE variable='AWSAccessKeyID'");
5690     $dbh->do("DELETE FROM systempreferences WHERE variable='AWSPrivateKey'");
5691     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonReviews'");
5692     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonSimilarItems'");
5693     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonEnabled'");
5694     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonEnabled'");
5695     print "Upgrade to $DBversion done ('Remove preferences controlling broken Amazon features (Bug 8679')\n";
5696     SetVersion ($DBversion);
5697 }
5698
5699 $DBversion = "3.09.00.032";
5700 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5701     $dbh->do("UPDATE systempreferences SET value = 'call_number' WHERE variable = 'defaultSortField' AND value = 'callnumber'");
5702     $dbh->do("UPDATE systempreferences SET value = 'call_number' WHERE variable = 'OPACdefaultSortField' AND value = 'callnumber'");
5703     print "Upgrade to $DBversion done (Bug 8657 - Default sort by call number does not work. Correcting system preference value.)\n";
5704     SetVersion ($DBversion);
5705 }
5706
5707
5708 $DBversion = '3.09.00.033';
5709 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5710    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacSuppressionByIPRange','','Restrict the suppression to IP adresses outside of the IP range','','free');");
5711    print "Upgrade to $DBversion done (Add OpacSuppressionByIPRange syspref)\n";
5712    SetVersion ($DBversion);
5713 }
5714
5715 $DBversion ="3.09.00.034";
5716 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5717     $dbh->do("UPDATE auth_subfield_structure SET frameworkcode = 'PERSO_NAME' WHERE frameworkcode = 'PERSO_CODE'");
5718     $dbh->do("UPDATE auth_subfield_structure SET frameworkcode = 'CORPO_NAME' WHERE frameworkcode = 'ORGO_CODE'");
5719     print "Upgrade to $DBversion done (Bug 8207: correct typo in authority types)\n";
5720     SetVersion ($DBversion);
5721 }
5722
5723 $DBversion = "3.09.00.035";
5724 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5725     $dbh->do("
5726     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');
5727     ");
5728     $dbh->do(
5729     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SubfieldsToUseWhenPrefill','','Define a list of subfields to use when prefilling items (separated by space)','','Free');
5730     ");
5731     print "Upgrade to $DBversion done (Adding PrefillItem and SubfieldsToUseWhenPrefill sysprefs)\n";
5732     SetVersion ($DBversion);
5733 }
5734
5735 $DBversion = "3.09.00.036";
5736 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5737     # biblioitems changes
5738     $dbh->do("ALTER TABLE biblioitems ADD COLUMN agerestriction VARCHAR(255) DEFAULT NULL AFTER cn_sort");
5739     $dbh->do("ALTER TABLE deletedbiblioitems ADD COLUMN agerestriction VARCHAR(255) DEFAULT NULL AFTER cn_sort");
5740     # preferences changes
5741     $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')");
5742     $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')");
5743
5744     print "Upgrade to $DBversion done (Add colum agerestriction to biblioitems and deletedbiblioitems, add system preferences AgeRestrictionMarker and AgeRestrictionOverride)\n";
5745    SetVersion ($DBversion);
5746 }
5747
5748 $DBversion = "3.09.00.037";
5749 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5750     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('UseTransportCostMatrix',0,'Use Transport Cost Matrix when filling holds','','YesNo')");
5751
5752  $dbh->do("CREATE TABLE `transport_cost` (
5753               `frombranch` varchar(10) NOT NULL,
5754               `tobranch` varchar(10) NOT NULL,
5755               `cost` decimal(6,2) NOT NULL,
5756               `disable_transfer` tinyint(1) NOT NULL DEFAULT 0,
5757               CHECK ( `frombranch` <> `tobranch` ), -- a dud check, mysql does not support that
5758               PRIMARY KEY (`frombranch`, `tobranch`),
5759               CONSTRAINT `transport_cost_ibfk_1` FOREIGN KEY (`frombranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
5760               CONSTRAINT `transport_cost_ibfk_2` FOREIGN KEY (`tobranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
5761           ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
5762
5763     print "Upgrade to $DBversion done (creating `transport_cost` table; adding UseTransportCostMatrix systempref, in circulation)\n";
5764     SetVersion($DBversion);
5765 }
5766
5767 $DBversion ="3.09.00.038";
5768 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5769     $dbh->do("ALTER TABLE borrower_attributes CHANGE  attribute  attribute VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
5770     print "Upgrade to $DBversion done (Increase the maximum size of a borrower attribute value)\n";
5771     SetVersion($DBversion);
5772 }
5773
5774 $DBversion ="3.09.00.039";
5775 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5776     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,type) VALUES('DidYouMeanFromAuthorities','0','Suggest searches based on authority file.','YesNo');");
5777     print "Upgrade to $DBversion done (Add system preference DidYouMeanFromAuthorities)\n";
5778     SetVersion($DBversion);
5779 }
5780
5781 $DBversion = "3.09.00.040";
5782 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5783     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('IncludeSeeFromInSearches','0','','Include see-from references in searches.','YesNo');");
5784     print "Upgrade to $DBversion done (Add IncludeSeeFromInSearches system preference)\n";
5785     SetVersion ($DBversion);
5786 }
5787
5788 $DBversion = "3.09.00.041";
5789 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5790     $dbh->do(qq{
5791         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ExportRemoveFields','','List of fields for non export in circulation.pl (separated by a space)','','');
5792     });
5793     print "Upgrade to $DBversion done (Add system preference ExportRemoveFields)\n";
5794     SetVersion($DBversion);
5795 }
5796
5797 $DBversion = "3.09.00.042";
5798 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5799     $dbh->do(qq{
5800         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ExportWithCsvProfile','','Set a profile name for CSV export','','');
5801     });
5802     print "Upgrade to $DBversion done (Adds New System preference ExportWithCsvProfile)\n";
5803     SetVersion($DBversion)
5804 }
5805
5806 $DBversion = "3.09.00.043";
5807 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5808     $dbh->do("
5809         ALTER TABLE aqorders
5810         ADD parent_ordernumber int(11) DEFAULT NULL
5811     ");
5812     $dbh->do("
5813         UPDATE aqorders
5814         SET parent_ordernumber = ordernumber;
5815     ");
5816     print "Upgrade to $DBversion done (Adding parent_ordernumber in aqorders)\n";
5817     SetVersion($DBversion);
5818 }
5819
5820 $DBversion = '3.09.00.044';
5821 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5822     $dbh->do("ALTER TABLE statistics ADD COLUMN ccode VARCHAR ( 10 ) NULL AFTER associatedborrower");
5823     $dbh->do("UPDATE statistics SET statistics.ccode = ( SELECT items.ccode FROM items WHERE statistics.itemnumber = items.itemnumber )");
5824     $dbh->do("UPDATE statistics SET statistics.ccode = (
5825               SELECT deleteditems.ccode FROM deleteditems
5826                   WHERE statistics.itemnumber = deleteditems.itemnumber
5827               ) WHERE statistics.ccode IS NULL");
5828     print "Upgrade done ( Added Collection Code to Statistics table. )\n";
5829     SetVersion ($DBversion);
5830 }
5831
5832 $DBversion = "3.09.00.045";
5833 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5834     $dbh->do("ALTER TABLE borrower_attribute_types MODIFY category_code VARCHAR( 10 ) NULL DEFAULT NULL");
5835     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.";
5836     SetVersion($DBversion);
5837 }
5838
5839 $DBversion = "3.09.00.046";
5840 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5841     $dbh->do("ALTER TABLE `accountlines` ADD `accountlines_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;");
5842     print "Upgrade to $DBversion done (adding accountlines_id field in accountlines table)\n";
5843     SetVersion($DBversion);
5844 }
5845
5846 $DBversion = "3.09.00.047";
5847 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5848     # to preserve default behaviour as best as possible, set this new preference differently depending on whether IndependantBranches is set or not
5849     my $prefvalue = 'anywhere';
5850     if (C4::Context->preference("IndependantBranches")) { $prefvalue = 'homeorholdingbranch';}
5851     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowReturnToBranch', '$prefvalue', 'Where an item may be returned', 'anywhere|homebranch|holdingbranch|homeorholdingbranch', 'Choice');");
5852
5853     print "Upgrade to $DBversion done: adding AllowReturnToBranch syspref (bug 6151)";
5854     SetVersion($DBversion);
5855 }
5856
5857 $DBversion = "3.09.00.048";
5858 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5859     $dbh->do("ALTER TABLE authorised_values MODIFY lib varchar(200)");
5860     $dbh->do("ALTER TABLE authorised_values MODIFY lib_opac varchar(200)");
5861
5862     print "Upgrade to $DBversion done (Raise the length of Authorised Values descriptions)\n";
5863     SetVersion($DBversion);
5864 }
5865
5866 $DBversion ="3.09.00.049";
5867 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5868     $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');");
5869     $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');");
5870     $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');");
5871     $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');");
5872     print "Upgrade to $DBversion done (Add OPACMobileUserCSS, OpacMainUserBlockMobile, OpacShowLibrariesPulldownMobile and OpacShowFiltersPulldownMobile sysprefs)\n";
5873     SetVersion($DBversion);
5874 }
5875
5876 $DBversion = "3.09.00.050";
5877 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5878     $dbh->do("ALTER TABLE authorised_values MODIFY category varchar(16) NOT NULL DEFAULT '';");
5879     $dbh->do("INSERT INTO authorised_values (category, authorised_value, lib) VALUES
5880               ('REPORT_GROUP', 'CIRC', 'Circulation'),
5881               ('REPORT_GROUP', 'CAT', 'Catalog'),
5882               ('REPORT_GROUP', 'PAT', 'Patrons'),
5883               ('REPORT_GROUP', 'ACQ', 'Acquisitions'),
5884               ('REPORT_GROUP', 'ACC', 'Accounts');");
5885
5886     $dbh->do("ALTER TABLE reports_dictionary ADD report_area varchar(6) DEFAULT NULL;");
5887     $dbh->do("UPDATE reports_dictionary SET report_area = CASE area
5888                   WHEN 1 THEN 'CIRC'
5889                   WHEN 2 THEN 'CAT'
5890                   WHEN 3 THEN 'PAT'
5891                   WHEN 4 THEN 'ACQ'
5892                   WHEN 5 THEN 'ACC'
5893                   END;");
5894     $dbh->do("ALTER TABLE reports_dictionary DROP area;");
5895     $dbh->do("ALTER TABLE reports_dictionary ADD KEY dictionary_area_idx (report_area);");
5896
5897     $dbh->do("ALTER TABLE saved_sql ADD report_area varchar(6) DEFAULT NULL;");
5898     $dbh->do("ALTER TABLE saved_sql ADD report_group varchar(80) DEFAULT NULL;");
5899     $dbh->do("ALTER TABLE saved_sql ADD report_subgroup varchar(80) DEFAULT NULL;");
5900     $dbh->do("ALTER TABLE saved_sql ADD KEY sql_area_group_idx (report_group, report_subgroup);");
5901
5902     print "Upgrade to $DBversion done saved_sql new fields report_group and report_area; authorised_values.category 16 char \n";
5903     SetVersion($DBversion);
5904 }
5905
5906 $DBversion = "3.09.00.051";
5907 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5908     $dbh->do("
5909         CREATE TABLE aqinvoices (
5910           invoiceid int(11) NOT NULL AUTO_INCREMENT,
5911           invoicenumber mediumtext NOT NULL,
5912           booksellerid int(11) NOT NULL,
5913           shipmentdate date default NULL,
5914           billingdate date default NULL,
5915           closedate date default NULL,
5916           shipmentcost decimal(28,6) default NULL,
5917           shipmentcost_budgetid int(11) default NULL,
5918           PRIMARY KEY (invoiceid),
5919           CONSTRAINT aqinvoices_fk_aqbooksellerid FOREIGN KEY (booksellerid) REFERENCES aqbooksellers (id) ON DELETE CASCADE ON UPDATE CASCADE,
5920           CONSTRAINT aqinvoices_fk_shipmentcost_budgetid FOREIGN KEY (shipmentcost_budgetid) REFERENCES aqbudgets (budget_id) ON DELETE SET NULL ON UPDATE CASCADE
5921         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5922     ");
5923
5924     # Fill this new table with existing invoices
5925     my $sth = $dbh->prepare("
5926         SELECT aqorders.booksellerinvoicenumber AS invoicenumber, aqbasket.booksellerid, aqorders.datereceived
5927         FROM aqorders
5928           LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
5929         WHERE aqorders.booksellerinvoicenumber IS NOT NULL
5930           AND aqorders.booksellerinvoicenumber != ''
5931         GROUP BY aqorders.booksellerinvoicenumber
5932     ");
5933     $sth->execute;
5934     my $results = $sth->fetchall_arrayref({});
5935     $sth = $dbh->prepare("
5936         INSERT INTO aqinvoices (invoicenumber, booksellerid, shipmentdate) VALUES (?,?,?)
5937     ");
5938     foreach(@$results) {
5939         $sth->execute($_->{invoicenumber}, $_->{booksellerid}, $_->{datereceived});
5940     }
5941
5942     # Add the column in aqorders, fill it with correct value
5943     # and then drop booksellerinvoicenumber column
5944     $dbh->do("
5945         ALTER TABLE aqorders
5946         ADD COLUMN invoiceid int(11) default NULL AFTER booksellerinvoicenumber,
5947         ADD CONSTRAINT aqorders_ibfk_3 FOREIGN KEY (invoiceid) REFERENCES aqinvoices (invoiceid) ON DELETE SET NULL ON UPDATE CASCADE
5948     ");
5949
5950     $dbh->do("
5951         UPDATE aqorders, aqinvoices
5952         SET aqorders.invoiceid = aqinvoices.invoiceid
5953         WHERE aqorders.booksellerinvoicenumber = aqinvoices.invoicenumber
5954     ");
5955
5956     $dbh->do("
5957         ALTER TABLE aqorders
5958         DROP COLUMN booksellerinvoicenumber
5959     ");
5960
5961     print "Upgrade to $DBversion done (Add aqinvoices table) \n";
5962     SetVersion ($DBversion);
5963 }
5964
5965 $DBversion = "3.09.00.052";
5966 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5967     $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');");
5968     $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');");
5969     $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');");
5970     print "Upgrade to $DBversion done (Add systempreferences to decrease loan length on high demand items decreaseLoanHighHolds, decreaseLoanHighHoldsValue and decreaseLoanHighHoldsDuration) \n";
5971     SetVersion ($DBversion);
5972 }
5973
5974 $DBversion = "3.09.00.053";
5975 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5976     $dbh->do(
5977     q|CREATE TABLE `import_auths` (
5978         import_record_id int(11) NOT NULL,
5979         matched_authid int(11) default NULL,
5980         control_number varchar(25) default NULL,
5981         authorized_heading varchar(128) default NULL,
5982         original_source varchar(25) default NULL,
5983         CONSTRAINT import_auths_ibfk_1 FOREIGN KEY (import_record_id)
5984         REFERENCES import_records (import_record_id) ON DELETE CASCADE ON UPDATE CASCADE,
5985         KEY matched_authid (matched_authid)
5986         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;|
5987     );
5988     $dbh->do("ALTER TABLE import_batches
5989                 CHANGE COLUMN num_biblios num_records int(11) NOT NULL default 0,
5990                 ADD COLUMN record_type enum('biblio', 'auth', 'holdings') NOT NULL default 'biblio'");
5991     $dbh->do("UPDATE import_batches SET record_type='auth' WHERE import_batch_id IN
5992                 (SELECT import_batch_id FROM import_records WHERE record_type='auth')");
5993
5994     print "Upgrade to $DBversion done (Added support for staging authorities)\n";
5995     SetVersion ($DBversion);
5996 }
5997
5998 $DBversion = "3.09.00.054";
5999 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6000     $dbh->do("ALTER TABLE aqorders CHANGE COLUMN gst gstrate DECIMAL(6,4)  DEFAULT NULL");
6001     print "Upgrade to $DBversion done (Change column name in aqorders gst --> gstrate)\n";
6002     SetVersion($DBversion);
6003 }
6004
6005 $DBversion = "3.09.00.055";
6006 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6007     $dbh->do("ALTER TABLE aqorders ADD discount float(6,4) DEFAULT NULL AFTER gstrate");
6008     print "Upgrade to $DBversion done (Add discount field in aqorders table)\n";
6009     SetVersion($DBversion);
6010 }
6011
6012 $DBversion ="3.09.00.056";
6013 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6014     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('AuthDisplayHierarchy','0','Display authority hierarchies','','YesNo')");
6015     print "Upgrade to $DBversion done (Add system preference AuthDisplayHierarchy)\n";
6016     SetVersion($DBversion);
6017 }
6018
6019 $DBversion = "3.09.00.057";
6020 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6021     $dbh->do("ALTER TABLE aqbasket ADD deliveryplace VARCHAR(10) default NULL AFTER basketgroupid;");
6022     $dbh->do("ALTER TABLE aqbasket ADD billingplace VARCHAR(10) default NULL AFTER deliveryplace;");
6023     print "Upgrade to $DBversion done (Bug 5356: Added billingplace, deliveryplace to the aqbasket table)\n";
6024     SetVersion($DBversion);
6025 }
6026
6027 $DBversion ="3.09.00.058";
6028 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6029     $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');");
6030     $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');");
6031     print "Upgrade to $DBversion done (Add Did You Mean? configuration)\n";
6032     SetVersion($DBversion);
6033 }
6034
6035 $DBversion ="3.09.00.059";
6036 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6037     $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');");
6038     print "Upgrade to $DBversion done (Add system preference BlockReturnOfWithdrawnItems)\n";
6039     SetVersion($DBversion);
6040 }
6041
6042 $DBversion = "3.09.00.060";
6043 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6044     $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')");
6045     print "Upgrade to $DBversion done (Added HoldsToPullStartDate syspref)\n";
6046     SetVersion($DBversion);
6047 }
6048
6049 $DBversion = "3.09.00.061";
6050 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6051     $dbh->do("UPDATE systempreferences set value=0 WHERE variable='OPACItemsResultsDisplay' AND value='statuses'");
6052     $dbh->do("UPDATE systempreferences set value=1 WHERE variable='OPACItemsResultsDisplay' AND value='itemdetails'");
6053     $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'");
6054     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";
6055     SetVersion ($DBversion);
6056 }
6057
6058 $DBversion = "3.09.00.062";
6059 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6060    $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='NoZebra'");
6061    $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='QueryRemoveStopwords'");
6062    print "Upgrade to $DBversion done (Disable obsolete NoZebra and QueryRemoveStopwords sysprefs)\n";
6063    SetVersion ($DBversion);
6064 }
6065
6066 $DBversion = "3.09.00.063";
6067 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6068     my $gst_booksellers = $dbh->selectcol_arrayref("SELECT DISTINCT(gstrate) FROM aqbooksellers");
6069     my $gist_syspref = C4::Context->preference("gist");
6070     # remove the undef values and construct and array with the syspref and the supplier values
6071     my @gstrates = map { defined $_ ? $_ : () } @$gst_booksellers;
6072     push @gstrates, split ('\|', $gist_syspref);
6073     # we want to compare integer (or float)
6074     $_ = $_ + 0 for @gstrates;
6075     use List::MoreUtils qw/uniq/;
6076     # remove duplicate values
6077     @gstrates = uniq sort @gstrates;
6078     my $new_syspref_value = join '|', @gstrates;
6079     # update the syspref with the new values
6080     my $sth = $dbh->prepare("UPDATE systempreferences set value=? WHERE variable='gist'");
6081     $sth->execute( $new_syspref_value );
6082
6083     print "Upgrade to $DBversion done (Bug 8832, Set the syspref gist with the existing values)\n";
6084     SetVersion ($DBversion);
6085 }
6086
6087 $DBversion = "3.09.00.064";
6088 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6089    $dbh->do('ALTER TABLE items ADD coded_location_qualifier varchar(10) default NULL AFTER itemcallnumber');
6090    print "Upgrade to $DBversion done (Bug 6428: Added coded_location_qualifier to the items table)\n";
6091    SetVersion ($DBversion);
6092 }
6093
6094 $DBversion = "3.09.00.065";
6095 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6096    $dbh->do('ALTER TABLE deleteditems ADD coded_location_qualifier varchar(10) default NULL AFTER itemcallnumber');
6097    print "Upgrade to $DBversion done (Bug 6428: Added coded_location_qualifier to the deleteditems table)\n";
6098    SetVersion ($DBversion);
6099 }
6100
6101 $DBversion = "3.09.00.066";
6102 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6103    $dbh->do("DELETE FROM systempreferences WHERE variable='DidYouMeanFromAuthorities'");
6104    print "Upgrade to $DBversion done (Bug 9107: remove DidYouMeanFromAuthorities syspref)\n";
6105    SetVersion ($DBversion);
6106 }
6107
6108 $DBversion = "3.09.00.067";
6109 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6110    $dbh->do("ALTER TABLE statistics CHANGE COLUMN ccode ccode varchar(10) NULL");
6111    print "Upgrade to $DBversion done (Bug 9064: statistics.ccode potentially wrongly defined)\n";
6112    SetVersion ($DBversion);
6113 }
6114
6115 $DBversion = "3.10.00.00";
6116 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6117    print "Upgrade to $DBversion done (release tag)\n";
6118    SetVersion ($DBversion);
6119 }
6120
6121 $DBversion = "3.11.00.001";
6122 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6123     $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')");
6124     print "Upgrade to $DBversion done (Bug 2832 - Add alphabet syspref)\n";
6125 }
6126
6127 $DBversion = "3.11.00.002";
6128 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6129     $dbh->do(q{
6130         DELETE from aqorders_items where ordernumber NOT IN (SELECT ordernumber FROM aqorders);
6131     });
6132     $dbh->do(q{
6133         ALTER TABLE aqorders_items
6134         ADD CONSTRAINT aqorders_items_ibfk_1 FOREIGN KEY (ordernumber) REFERENCES aqorders (ordernumber)
6135         ON DELETE CASCADE ON UPDATE CASCADE;
6136     });
6137     print "Upgrade to $DBversion done (Bug 9030: Add constraint on aqorders_items.ordernumber)\n";
6138     SetVersion ($DBversion);
6139 }
6140
6141 $DBversion = "3.11.00.003";
6142 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6143     $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')");
6144     print "Upgrade to $DBversion done (Bug 7189: Add system preference RefundLostItemFeeOnReturn)\n";
6145     SetVersion($DBversion);
6146 }
6147
6148 $DBversion = "3.11.00.004";
6149 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6150     $dbh->do(qq{
6151         ALTER TABLE subscription ADD COLUMN closed INT(1) NOT NULL DEFAULT 0 AFTER enddate;
6152     });
6153
6154     print "Upgrade to $DBversion done (Bug 8782: Add field subscription.closed)\n";
6155     SetVersion($DBversion);
6156 }
6157
6158 $DBversion = "3.11.00.005";
6159 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6160     $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;});
6161
6162     $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;});
6163
6164     $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;});
6165
6166     print "Upgrade to $DBversion done (Bug 7919: Display of values depending on the connexion library)\n";
6167     SetVersion($DBversion);
6168 }
6169
6170 $DBversion = "3.11.00.006";
6171 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6172     $dbh->do(q{
6173         UPDATE virtualshelves SET sortfield="copyrightdate" where sortfield="year";
6174     });
6175     print "Upgrade to $DBversion done (Bug 9167: Update the virtualshelves.sortfield column with 'copyrightdate' if needed)\n";
6176     SetVersion($DBversion);
6177 }
6178
6179 $DBversion = "3.11.00.007";
6180 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6181     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ar', 'language', 'de', 'Arabisch')");
6182     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hy', 'language', 'de', 'Armenisch')");
6183     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'bg', 'language', 'de', 'Bulgarisch')");
6184     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'zh', 'language', 'de', 'Chinesisch')");
6185     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'cs', 'language', 'de', 'Tschechisch')");
6186     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'da', 'language', 'de', 'Dänisch')");
6187     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nl', 'language', 'de', 'Niederländisch')");
6188     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'en', 'language', 'de', 'Englisch')");
6189     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fi', 'language', 'de', 'Finnisch')");
6190     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fr', 'language', 'de', 'Französisch')");
6191     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'lo', 'language', 'fr', 'Laotien')");
6192     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'lo', 'language', 'de', 'Laotisch')");
6193     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'el', 'language', 'de', 'Griechisch (Nach 1453)')");
6194     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'he', 'language', 'de', 'Hebräisch')");
6195     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hi', 'language', 'de', 'Hindi')");
6196     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hu', 'language', 'de', 'Ungarisch')");
6197     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'id', 'language', 'de', 'Indonesisch')");
6198     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'it', 'language', 'de', 'Italienisch')");
6199     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ja', 'language', 'de', 'Japanisch')");
6200     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ko', 'language', 'de', 'Koreanisch')");
6201     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'la', 'language', 'de', 'Latein')");
6202     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'gl', 'language', 'fr', 'Galicien')");
6203     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'gl', 'language', 'de', 'Galizisch')");
6204     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nb', 'language', 'de', 'Norwegisch bokm&#229;l')");
6205     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nn', 'language', 'de', 'Norwegisch nynorsk')");
6206     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fa', 'language', 'de', 'Persisch')");
6207     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'pl', 'language', 'de', 'Polnisch')");
6208     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'pt', 'language', 'de', 'Portugiesisch')");
6209     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ro', 'language', 'de', 'Rumänisch')");
6210     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ru', 'language', 'de', 'Russisch')");
6211     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sr', 'language', 'fr', 'Serbe')");
6212     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sr', 'language', 'de', 'Serbisch')");
6213     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'es', 'language', 'de', 'Spanisch')");
6214     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sv', 'language', 'de', 'Schwedisch')");
6215     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tet', 'language', 'fr', 'Tétoum')");
6216     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tet', 'language', 'de', 'Tetum')");
6217     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'th', 'language', 'de', 'Thailändisch')");
6218     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tr', 'language', 'de', 'Türkisch')");
6219     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'uk', 'language', 'de', 'Ukrainisch')");
6220     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ur', 'language', 'fr', 'Ourdou')");
6221     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ur', 'language', 'de', 'Urdu')");
6222     print "Upgrade to $DBversion done (Bug 9056: add German and a couple of French translations to language_descriptions)\n";
6223     SetVersion ($DBversion);
6224 }
6225
6226 $DBversion = "3.11.00.008";
6227 if (CheckVersion($DBversion)) {
6228     $dbh->do("
6229         CREATE TABLE IF NOT EXISTS `borrower_modifications` (
6230           `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6231           `verification_token` varchar(255) NOT NULL DEFAULT '',
6232           `borrowernumber` int(11) NOT NULL DEFAULT '0',
6233           `cardnumber` varchar(16) DEFAULT NULL,
6234           `surname` mediumtext,
6235           `firstname` text,
6236           `title` mediumtext,
6237           `othernames` mediumtext,
6238           `initials` text,
6239           `streetnumber` varchar(10) DEFAULT NULL,
6240           `streettype` varchar(50) DEFAULT NULL,
6241           `address` mediumtext,
6242           `address2` text,
6243           `city` mediumtext,
6244           `state` text,
6245           `zipcode` varchar(25) DEFAULT NULL,
6246           `country` text,
6247           `email` mediumtext,
6248           `phone` text,
6249           `mobile` varchar(50) DEFAULT NULL,
6250           `fax` mediumtext,
6251           `emailpro` text,
6252           `phonepro` text,
6253           `B_streetnumber` varchar(10) DEFAULT NULL,
6254           `B_streettype` varchar(50) DEFAULT NULL,
6255           `B_address` varchar(100) DEFAULT NULL,
6256           `B_address2` text,
6257           `B_city` mediumtext,
6258           `B_state` text,
6259           `B_zipcode` varchar(25) DEFAULT NULL,
6260           `B_country` text,
6261           `B_email` text,
6262           `B_phone` mediumtext,
6263           `dateofbirth` date DEFAULT NULL,
6264           `branchcode` varchar(10) DEFAULT NULL,
6265           `categorycode` varchar(10) DEFAULT NULL,
6266           `dateenrolled` date DEFAULT NULL,
6267           `dateexpiry` date DEFAULT NULL,
6268           `gonenoaddress` tinyint(1) DEFAULT NULL,
6269           `lost` tinyint(1) DEFAULT NULL,
6270           `debarred` date DEFAULT NULL,
6271           `debarredcomment` varchar(255) DEFAULT NULL,
6272           `contactname` mediumtext,
6273           `contactfirstname` text,
6274           `contacttitle` text,
6275           `guarantorid` int(11) DEFAULT NULL,
6276           `borrowernotes` mediumtext,
6277           `relationship` varchar(100) DEFAULT NULL,
6278           `ethnicity` varchar(50) DEFAULT NULL,
6279           `ethnotes` varchar(255) DEFAULT NULL,
6280           `sex` varchar(1) DEFAULT NULL,
6281           `password` varchar(30) DEFAULT NULL,
6282           `flags` int(11) DEFAULT NULL,
6283           `userid` varchar(75) DEFAULT NULL,
6284           `opacnote` mediumtext,
6285           `contactnote` varchar(255) DEFAULT NULL,
6286           `sort1` varchar(80) DEFAULT NULL,
6287           `sort2` varchar(80) DEFAULT NULL,
6288           `altcontactfirstname` varchar(255) DEFAULT NULL,
6289           `altcontactsurname` varchar(255) DEFAULT NULL,
6290           `altcontactaddress1` varchar(255) DEFAULT NULL,
6291           `altcontactaddress2` varchar(255) DEFAULT NULL,
6292           `altcontactaddress3` varchar(255) DEFAULT NULL,
6293           `altcontactstate` text,
6294           `altcontactzipcode` varchar(50) DEFAULT NULL,
6295           `altcontactcountry` text,
6296           `altcontactphone` varchar(50) DEFAULT NULL,
6297           `smsalertnumber` varchar(50) DEFAULT NULL,
6298           `privacy` int(11) DEFAULT NULL,
6299           PRIMARY KEY (`verification_token`,`borrowernumber`),
6300           KEY `verification_token` (`verification_token`),
6301           KEY `borrowernumber` (`borrowernumber`)
6302         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6303 ");
6304
6305     $dbh->do("
6306         INSERT INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES
6307         ('PatronSelfRegistration', '0', NULL, 'If enabled, patrons will be able to register themselves via the OPAC.', 'YesNo'),
6308         ('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'),
6309         ('PatronSelfRegistrationDefaultCategory', '', '', 'A patron registered via the OPAC will receive a borrower category code set in this system preference.', 'free'),
6310         ('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'),
6311         ('PatronSelfRegistrationBorrowerMandatoryField',  'surname|firstname', NULL ,  'Choose the mandatory fields for a patron''s account, when registering via the OPAC.',  'free'),
6312         ('PatronSelfRegistrationBorrowerUnwantedField',  '', NULL ,  'Name the fields you don''t want to display when registering a new patron via the OPAC.',  'free');
6313     ");
6314
6315     $dbh->do("
6316     INSERT INTO  letter ( `module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content` )
6317     VALUES ( 'members', 'OPAC_REG_VERIFY', '', 'Opac Self-Registration Verification Email', '1', 'Verify Your Account', 'Hello!
6318
6319     Your library account has been created. Please verify your email address by clicking this link to complete the signup process:
6320
6321     http://<<OPACBaseURL>>/cgi-bin/koha/opac-registration-verify.pl?token=<<borrower_modifications.verification_token>>
6322
6323     If you did not initiate this request, you may safely ignore this one-time message. The request will expire shortly.'
6324     )");
6325
6326     print "Upgrade to $DBversion done (Bug 7067: Add Patron Self Registration)\n";
6327     SetVersion ($DBversion);
6328 }
6329
6330 $DBversion = "3.11.00.009";
6331 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6332     $dbh->do("
6333         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
6334         ('SeparateHoldings', '0', 'Separate current branch holdings from other holdings', NULL, 'YesNo'),
6335         ('SeparateHoldingsBranch', 'homebranch', 'Branch used to separate holdings', 'homebranch|holdingbranch', 'Choice'),
6336         ('OpacSeparateHoldings', '0', 'Separate current branch holdings from other holdings (OPAC)', NULL, 'YesNo'),
6337         ('OpacSeparateHoldingsBranch', 'homebranch', 'Branch used to separate holdings (OPAC)', 'homebranch|holdingbranch', 'Choice')
6338     ");
6339
6340     print "Upgrade to $DBversion done (Bug 7674: Add systempreferences SeparateHoldings, SeparateHoldingsBranch, OpacSeparateHoldings and OpacSeparateHoldingsBranch) \n";
6341     SetVersion ($DBversion);
6342 }
6343
6344 $DBversion = "3.11.00.010";
6345 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6346     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('RenewalSendNotice', '0', '', NULL, 'YesNo')");
6347     $dbh->do(q{
6348         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
6349         ('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>>.');
6350     });
6351     print "Upgrade to $DBversion done (Bug 9151 - Renewal notice according to patron alert preferences)\n";
6352     SetVersion($DBversion);
6353 }
6354
6355 $DBversion = "3.11.00.011";
6356 if ( CheckVersion($DBversion) ) {
6357    $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');");
6358    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('HTML5MediaExtensions','webm|ogg|ogv|oga|vtt','Media file extensions','','free');");
6359    print "Upgrade to $DBversion done (Bug 8377: Add HTML5MediaEnabled and HTML5MediaExtensions sysprefs)\n";
6360    SetVersion ($DBversion);
6361 }
6362
6363 $DBversion = "3.11.00.012";
6364 if ( CheckVersion($DBversion) ) {
6365     $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')");
6366     print "Upgrade to $DBversion done (Bug 9206: Only allow place holds in records that the patron don't have in his possession)\n";
6367     SetVersion($DBversion);
6368 }
6369
6370 $DBversion = "3.11.00.013";
6371 if ( CheckVersion($DBversion) ) {
6372     $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')");
6373     print "Upgrade to $DBversion done (Bug 9162 - Add a system preference to set which notes fields appears on title notes/description separator)\n";
6374     SetVersion($DBversion);
6375 }
6376
6377 $DBversion = "3.11.00.014";
6378 if ( CheckVersion($DBversion) ) {
6379    $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' )");
6380    $dbh->do("INSERT INTO systempreferences ( variable, value, explanation, type ) VALUES ( 'SCOUserJS', '', 'Define custom javascript for inclusion in the SCO module', 'free' )");
6381    print "Upgrade to $DBversion done (Bug 9009: Add SCOUserCSS and SCOUserJS sysprefs)\n";
6382 }
6383
6384 $DBversion = "3.11.00.015";
6385 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6386     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('RentalsInNoissuesCharge', '1', 'Rental charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
6387     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('ManInvInNoissuesCharge', '1', 'MANUAL_INV charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
6388     print "Upgrade to $DBversion done (Add sysprefs RentalsInNoissuesCharge and ManInvInNoissuesCharge.)\n";
6389     SetVersion($DBversion);
6390 }
6391
6392 $DBversion = "3.11.00.016";
6393 if ( CheckVersion($DBversion) ) {
6394    $dbh->do(q{
6395         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";
6396         });
6397    $dbh->do(q{
6398         UPDATE userflags SET flagdesc="Edit Authorities" where flagdesc="Allow to edit authorities";
6399         });
6400    $dbh->do(q{
6401         UPDATE userflags SET flagdesc="Allow access to the reports module" where flagdesc="Allow to access to the reports module";
6402         });
6403    $dbh->do(q{
6404         UPDATE userflags SET flagdesc="Set library management parameters (deprecated)" where flagdesc="Set library management parameters";
6405         });
6406    $dbh->do(q{
6407         UPDATE userflags SET flagdesc="Manage serial subscriptions" where flagdesc="Allow to manage serials subscriptions";
6408         });
6409    $dbh->do(q{
6410         UPDATE userflags SET flagdesc="Manage patrons fines and fees" where flagdesc="Update borrower charges";
6411         });
6412    $dbh->do(q{
6413         UPDATE userflags SET flagdesc="Check out and check in items" where flagdesc="Circulate books";
6414         });
6415    $dbh->do(q{
6416         UPDATE userflags SET flagdesc="Manage Koha system settings (Administration panel)" where flagdesc="Set Koha system parameters";
6417         });
6418    $dbh->do(q{
6419         UPDATE userflags SET flagdesc="Add or modify patrons" where flagdesc="Add or modify borrowers";
6420         });
6421    $dbh->do(q{
6422         UPDATE userflags SET flagdesc="Use all tools (expand for granular tools permissions)" where flagdesc="Use tools (export, import, barcodes)";
6423         });
6424    $dbh->do(q{
6425         UPDATE userflags SET flagdesc="Allow staff members to modify permissions for other staff members" where flagdesc="Set user permissions";
6426         });
6427    $dbh->do(q{
6428         UPDATE permissions SET description="Perform batch modification of patrons" where description="Perform batch modifivation of patrons";
6429         });
6430
6431    print "Upgrade to $DBversion done (Bug 9382 (updated with bug 9745) - refresh permission descriptions to make more sense)\n";
6432    SetVersion ($DBversion);
6433 }
6434
6435 $DBversion ="3.11.00.017";
6436 if ( CheckVersion($DBversion) ) {
6437     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksReviews','0','Display book review snippets from IDreamBooks.com','','YesNo');");
6438     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksReadometer','0','Display Readometer from IDreamBooks.com','','YesNo');");
6439     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksResults','0','Display IDreamBooks.com rating in search results','','YesNo');");
6440     print "Upgrade to $DBversion done (Add IDreamBooks enhanced content)\n";
6441     SetVersion($DBversion);
6442 }
6443
6444 $DBversion = "3.11.00.018";
6445 if ( CheckVersion($DBversion) ) {
6446    $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')");
6447    $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')");
6448    print "Upgrade to $DBversion done (Bug 9395: Problem with callnumber and standard number search in OPAC and Staff Client)\n";
6449    SetVersion ($DBversion);
6450 }
6451
6452 $DBversion = "3.11.00.019";
6453 if ( CheckVersion($DBversion) ) {
6454     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('UNIMARCAuthorityField100', 'afrey50      ba0', NULL, NULL, 'Textarea')");
6455     print "Upgrade to $DBversion done (Bug 9145 - Add syspref UNIMARCAuthorityField100)\n";
6456     SetVersion ($DBversion);
6457 }
6458
6459 $DBversion = "3.11.00.020";
6460 if ( CheckVersion($DBversion) ) {
6461     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UNIMARCField100Language', 'fre','UNIMARC field 100 default language',NULL,'short')");
6462     print "Upgrade to $DBversion done (Bug 8347 - Koha forces UNIMARC 100 field code language to 'fre')\n";
6463     SetVersion($DBversion);
6464 }
6465
6466 $DBversion ="3.11.00.021";
6467 if ( CheckVersion($DBversion) ) {
6468     $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');");
6469     print "Upgrade to $DBversion done (Bug 5888 - Subject search pop-up for the OPAC)\n";
6470     SetVersion($DBversion);
6471 }
6472
6473 $DBversion = "3.11.00.022";
6474 if ( CheckVersion($DBversion) ) {
6475     $dbh->do(
6476 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('Persona',0,'Use Mozilla Persona for login','','YesNo')"
6477     );
6478     print "Upgrade to $DBversion done (Bug 9587 - Allow login via Persona)\n";
6479     SetVersion($DBversion);
6480 }
6481
6482 $DBversion = "3.11.00.023";
6483 if ( CheckVersion($DBversion) ) {
6484     $dbh->do("UPDATE z3950servers SET host = 'lx2.loc.gov', port = 210, db = 'LCDB', syntax = 'USMARC', encoding = 'utf8' WHERE name = 'LIBRARY OF CONGRESS'");
6485     print "Upgrade to $DBversion done (Bug 9520 - Update default LOC Z39.50 target)\n";
6486     SetVersion($DBversion);
6487 }
6488
6489 $DBversion = "3.11.00.024";
6490 if ( CheckVersion($DBversion) ) {
6491     $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');");
6492     print "Upgrade to $DBversion done (Bug 5079: Add OpacItemLocation syspref)\n";
6493     SetVersion ($DBversion);
6494 }
6495
6496 $DBversion = "3.11.00.025";
6497 if ( CheckVersion($DBversion) ) {
6498     $dbh->do(
6499         "CREATE TABLE linktracker (
6500   id int(11) NOT NULL AUTO_INCREMENT,
6501   biblionumber int(11) DEFAULT NULL,
6502   itemnumber int(11) DEFAULT NULL,
6503   borrowernumber int(11) DEFAULT NULL,
6504   url text,
6505   timeclicked datetime DEFAULT NULL,
6506   PRIMARY KEY (id),
6507   KEY bibidx (biblionumber),
6508   KEY itemidx (itemnumber),
6509   KEY borridx (borrowernumber),
6510   KEY dateidx (timeclicked)
6511     ) ENGINE=InnoDB DEFAULT CHARSET=utf8;"
6512     );
6513     $dbh->do( "
6514   INSERT INTO systempreferences (variable,value,explanation,options,type)
6515   VALUES('TrackClicks','0','Track links clicked',NULL,'Integer')" );
6516     print
6517 "Upgrade to $DBversion done (Adds feature Bug 8917, the ability to track links clicked)\n";
6518     SetVersion($DBversion);
6519 }
6520
6521 $DBversion = "3.11.00.026";
6522 if ( CheckVersion($DBversion) ) {
6523     $dbh->do(qq{
6524         ALTER TABLE import_records ADD INDEX batch_id_record_type ( import_batch_id, record_type );
6525     });
6526     print "Upgrade to $DBversion done (Bug 9207: Add new index batch_id_record_type to import_records)\n";
6527     SetVersion($DBversion);
6528 }
6529
6530 $DBversion = "3.11.00.027";
6531 if ( CheckVersion($DBversion) ) {
6532     $dbh->do(q{
6533         INSERT INTO permissions ( module_bit, code, description )
6534         VALUES  ( '1', 'overdues_report', 'Execute overdue items report' )
6535     });
6536     # add new permission for users with all report permissions and circulation remaining permission
6537     $dbh->do(q{
6538         INSERT INTO user_permissions (borrowernumber, module_bit, code)
6539         SELECT user_permissions.borrowernumber, 1, 'overdues_report'
6540         FROM user_permissions
6541         LEFT JOIN borrowers USING(borrowernumber)
6542         WHERE borrowers.flags & (1 << 16)
6543         AND user_permissions.code = 'circulate_remaining_permissions'
6544     });
6545     print "Upgrade to $DBversion done ( Add circ permission overdues_report )\n";
6546     SetVersion($DBversion);
6547 }
6548
6549 $DBversion = "3.11.00.028";
6550 if ( CheckVersion($DBversion) ) {
6551     $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'    );");
6552     print "Upgrade to $DBversion done (Bug 9756 - Patron self registration missing the system preference PatronSelfRegistrationAdditionalInstructions)\n";
6553     SetVersion($DBversion);
6554 }
6555
6556 $DBversion = "3.11.00.029";
6557 if (CheckVersion($DBversion)) {
6558     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UseQueryParser', '0', 'If enabled, try to use QueryParser for queries.', NULL, 'YesNo')");
6559     print "Upgrade to $DBversion done (Bug 9239: Make it possible for Koha to use QueryParser)\n";
6560     SetVersion ($DBversion);
6561 }
6562
6563 $DBversion = "3.11.00.030";
6564 if ( CheckVersion($DBversion) ) {
6565     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('FinesIncludeGracePeriod','1','If enabled, fines calculations will include the grace period.',NULL,'YesNo');");
6566     print "Upgrade to $DBversion done (Add system preference FinesIncludeGracePeriod)\n";
6567     SetVersion($DBversion);
6568 }
6569
6570 $DBversion = "3.11.00.100";
6571 if ( CheckVersion($DBversion) ) {
6572     print "Upgrade to $DBversion done (3.12-alpha release)\n";
6573     SetVersion ($DBversion);
6574 }
6575
6576 $DBversion = "3.11.00.101";
6577 if ( CheckVersion($DBversion) ) {
6578    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('UNIMARCAuthorsFacetsSeparator',', ', 'UNIMARC authors facets separator', NULL, 'short')");
6579    print "Upgrade to $DBversion done (Bug 9341: Problem with UNIMARC authors facets)\n";
6580    SetVersion ($DBversion);
6581 }
6582
6583 $DBversion = "3.11.00.102";
6584 if ( CheckVersion($DBversion) ) {
6585     $dbh->do(q{
6586         DELETE FROM systempreferences WHERE variable='NoZebra'
6587     });
6588     $dbh->do(q{
6589         DELETE FROM systempreferences WHERE variable='QueryRemoveStopwords'
6590     });
6591     print "Upgrade to $DBversion done (Remove deprecated NoZebra and QueryRemoveStopwords sysprefs)\n";
6592     SetVersion($DBversion);
6593 }
6594
6595 $DBversion = "3.11.00.103";
6596 if ( CheckVersion($DBversion) ) {
6597     $dbh->do("DELETE FROM systempreferences WHERE variable = 'insecure';");
6598     print "Upgrade to $DBversion done (Bug 9827 - Remove 'insecure' system preference)\n";
6599     SetVersion($DBversion);
6600 }
6601
6602 $DBversion = "3.11.00.104";
6603 if ( CheckVersion($DBversion) ) {
6604     print "Upgrade to $DBversion done (3.12-alpha2 release)\n";
6605     SetVersion ($DBversion);
6606 }
6607
6608 $DBversion = "3.11.00.105";
6609 if ( CheckVersion($DBversion) ) {
6610     if ( C4::Context->preference("marcflavour") eq 'MARC21' ) {
6611         $sth = $dbh->prepare(
6612 "SELECT frameworkcode FROM marc_tag_structure WHERE tagfield = '029'"
6613         );
6614         $sth->execute;
6615         my $frameworkcodes = $sth->fetchall_hashref('frameworkcode');
6616
6617         for my $frameworkcode ( keys %$frameworkcodes ) {
6618             $dbh->do( "
6619     INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian,
6620     libopac, repeatable, mandatory, kohafield, tab, authorised_value, authtypecode,
6621     value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
6622     ('029', 'a', 'OCLC library identifier', 'OCLC library identifier', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6623     ('029', 'b', 'System control number', 'System control number', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6624     ('029', 'c', 'OAI set name', 'OAI set name', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6625     ('029', 't', 'Content type identifier', 'Content type identifier', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL)
6626    " );
6627         }
6628
6629         for my $tag ( '863', '864', '865' ) {
6630             $sth = $dbh->prepare(
6631 "SELECT frameworkcode FROM marc_tag_structure WHERE tagfield = '$tag'"
6632             );
6633             $sth->execute;
6634             my $frameworkcodes = $sth->fetchall_hashref('frameworkcode');
6635
6636             for my $frameworkcode ( keys %$frameworkcodes ) {
6637                 $dbh->do( "
6638      INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian,
6639      libopac, repeatable, mandatory, kohafield, tab, authorised_value, authtypecode,
6640      value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
6641      ('$tag', '6', 'Linkage', 'Linkage', 0, 0, '', 8, '', '', '', NULL, 5, '$frameworkcode', '', '', NULL),
6642      ('$tag', '8', 'Field link and sequence number', 'Field link and sequence number', 0, 0, '', 8, '', '', '', NULL, 5, '$frameworkcode', '', '', NULL),
6643      ('$tag', 'a', 'First level of enumeration', 'First level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6644      ('$tag', 'b', 'Second level of enumeration', 'Second level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6645      ('$tag', 'c', 'Third level of enumeration', 'Third level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6646      ('$tag', 'd', 'Fourth level of enumeration', 'Fourth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6647      ('$tag', 'e', 'Fifth level of enumeration', 'Fifth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6648      ('$tag', 'f', 'Sixth level of enumeration', 'Sixth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6649      ('$tag', 'g', 'Alternative numbering scheme, first level of enumeration', 'Alternative numbering scheme, first level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6650      ('$tag', 'h', 'Alternative numbering scheme, second level of enumeration', 'Alternative numbering scheme, second level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6651      ('$tag', 'i', 'First level of chronology', 'First level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6652      ('$tag', 'j', 'Second level of chronology', 'Second level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6653      ('$tag', 'k', 'Third level of chronology', 'Third level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6654      ('$tag', 'l', 'Fourth level of chronology', 'Fourth level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6655      ('$tag', 'm', 'Alternative numbering scheme, chronology', 'Alternative numbering scheme, chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6656      ('$tag', 'n', 'Converted Gregorian year', 'Converted Gregorian year', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6657      ('$tag', 'o', 'Type of unit', 'Type of unit', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6658      ('$tag', 'p', 'Piece designation', 'Piece designation', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6659      ('$tag', 'q', 'Piece physical condition', 'Piece physical condition', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6660      ('$tag', 's', 'Copyright article-fee code', 'Copyright article-fee code', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6661      ('$tag', 't', 'Copy number', 'Copy number', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6662      ('$tag', 'v', 'Issuing date', 'Issuing date', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6663      ('$tag', 'w', 'Break indicator', 'Break indicator', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6664      ('$tag', 'x', 'Nonpublic note', 'Nonpublic note', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6665      ('$tag', 'z', 'Public note', 'Public note', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL)
6666     " );
6667             }
6668         }
6669     }
6670     print "Upgrade to $DBversion done (Bug 9353: Missing subfields on MARC21 frameworks)\n";
6671     SetVersion($DBversion);
6672 }
6673
6674
6675 $DBversion = "3.11.00.106";
6676 if ( CheckVersion($DBversion) ) {
6677     $dbh->do("INSERT INTO userflags (bit, flag, flagdesc, defaulton) VALUES ('19', 'plugins', 'Koha plugins', '0')");
6678     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
6679               ('19', 'manage', 'Manage plugins ( install / uninstall )'),
6680               ('19', 'tool', 'Use tool plugins'),
6681               ('19', 'report', 'Use report plugins'),
6682               ('19', 'configure', 'Configure plugins')
6683             ");
6684     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UseKohaPlugins','0','Enable or disable the ability to use Koha Plugins.','','YesNo')");
6685
6686     $dbh->do("
6687         CREATE TABLE IF NOT EXISTS plugin_data (
6688             plugin_class varchar(255) NOT NULL,
6689             plugin_key varchar(255) NOT NULL,
6690             plugin_value text,
6691             PRIMARY KEY (plugin_class,plugin_key)
6692         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6693     ");
6694
6695     print "Upgrade to $DBversion done (Bug 7804: Added plugin system.)\n";
6696     SetVersion($DBversion);
6697 }
6698
6699 $DBversion = "3.11.00.107";
6700 if ( CheckVersion($DBversion) ) {
6701    $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('TimeFormat','24hr','12hr|24hr','Defines the global time format for visual output.','Choice')");
6702    print "Upgrade to $DBversion done (Bug 9014: Add syspref TimeFormat)\n";
6703    SetVersion ($DBversion);
6704 }
6705
6706 $DBversion = "3.11.00.108";
6707 if ( CheckVersion($DBversion) ) {
6708     $dbh->do("ALTER TABLE action_logs CHANGE timestamp timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;");
6709     $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');");
6710     $dbh->do("ALTER TABLE action_logs CHANGE timestamp timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;");
6711     print "Upgrade to $DBversion done (Bug 7241: Fix on circulation logs)\n";
6712     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";
6713     SetVersion($DBversion);
6714 }
6715
6716 $DBversion = "3.11.00.109";
6717 if ( CheckVersion($DBversion) ) {
6718    $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');");
6719    print "Upgrade to $DBversion done (Bug 9403: Add DisplayIconsXSLT)\n";
6720    SetVersion ($DBversion);
6721 }
6722
6723 $DBversion = "3.11.00.110";
6724 if ( CheckVersion($DBversion) ) {
6725     $dbh->do("ALTER TABLE pending_offline_operations CHANGE barcode barcode VARCHAR( 20 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
6726     $dbh->do("ALTER TABLE pending_offline_operations ADD amount DECIMAL( 28, 6 ) NULL DEFAULT NULL");
6727     print "Upgrade to $DBversion done (Bug 8220 - Allow koc uploads to go to process queue)\n";
6728     SetVersion ($DBversion);
6729 }
6730
6731 $DBversion = "3.11.00.111";
6732 if ( CheckVersion($DBversion) ) {
6733     my $sth = $dbh->prepare("
6734         SELECT module, code, branchcode, content
6735         FROM letter
6736         WHERE content LIKE '%<fine>%'
6737     ");
6738     $sth->execute;
6739     my $sth_update = $dbh->prepare("UPDATE letter SET content = ? WHERE module = ? AND code = ? AND branchcode = ?");
6740     while(my $row = $sth->fetchrow_hashref){
6741         $row->{content} =~ s/<fine>\w+<\/fine>/<<items.fine>>/;
6742         $sth_update->execute($row->{content}, $row->{module}, $row->{code}, $row->{branchcode});
6743     }
6744     print "Upgrade to $DBversion done (use new <<items.fine>> syntax in notices)\n";
6745     SetVersion($DBversion);
6746 }
6747
6748 $DBversion = "3.11.00.112";
6749 if ( CheckVersion($DBversion) ) {
6750     $dbh->do(qq{
6751         ALTER TABLE issuingrules ADD COLUMN renewalperiod int(4) DEFAULT NULL AFTER renewalsallowed
6752     });
6753     $dbh->do(qq{
6754         UPDATE issuingrules SET renewalperiod = issuelength
6755     });
6756     print "Upgrade to $DBversion done (Bug 8365: Add colum issuingrules.renewalperiod)\n";
6757     SetVersion ($DBversion);
6758 }
6759
6760 $DBversion = "3.11.00.113";
6761 if ( CheckVersion($DBversion) ) {
6762     $dbh->do(q{
6763         ALTER TABLE branchcategories ADD show_in_pulldown BOOLEAN NOT NULL DEFAULT '0',
6764         ADD INDEX ( show_in_pulldown )
6765     });
6766     print "Upgrade to $DBversion done (Bug 9257 - Add groups to normal search pulldown)\n";
6767     SetVersion ($DBversion);
6768 }
6769
6770 $DBversion = "3.11.00.115";
6771 if ( CheckVersion($DBversion) ) {
6772     $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')");
6773     $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')");
6774     print "Upgrade to $DBversion done (Bug 7740: Add syspref HighlightOwnItemsOnOPAC)\n";
6775     SetVersion ($DBversion);
6776 }
6777
6778 $DBversion = "3.11.00.116";
6779 if ( CheckVersion($DBversion) ) {
6780     $dbh->do(q{ALTER TABLE aqorders DROP COLUMN serialid;});
6781     $dbh->do(q{ALTER TABLE aqorders DROP COLUMN subscription;});
6782     $dbh->do(q{ALTER TABLE aqorders ADD COLUMN subscriptionid INT(11) DEFAULT NULL;});
6783     $dbh->do(q{ALTER TABLE aqorders ADD CONSTRAINT aqorders_subscriptionid FOREIGN KEY (subscriptionid) REFERENCES subscription (subscriptionid) ON DELETE CASCADE ON UPDATE CASCADE;});
6784     $dbh->do(q{ALTER TABLE subscription ADD COLUMN reneweddate DATE DEFAULT NULL;});
6785     print "Upgrade to $DBversion done (Bug 5343: table aqorders: DROP serialid and subscription fields and ADD subscriptionid, table subscription: ADD reneweddate)\n";
6786     SetVersion ($DBversion);
6787 }
6788
6789 $DBversion = "3.11.00.200";
6790 if ( CheckVersion($DBversion) ) {
6791     print "Upgrade to $DBversion done (3.12-beta1 release)\n";
6792     SetVersion ($DBversion);
6793 }
6794
6795 $DBversion = "3.11.00.201";
6796 if ( CheckVersion($DBversion) ) {
6797     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'BIBSYS' AND host LIKE 'z3950.bibsys.no'");
6798     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'NORBOK' AND host LIKE 'z3950.nb.no'");
6799     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'SAMBOK' AND host LIKE 'z3950.nb.no'");
6800     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'DEICHMAN' AND host like 'z3950.deich.folkebibl.no'");
6801     print "Upgrade to $DBversion done (Bug 9498 - Update encoding for Norwegian sample Z39.50 servers)\n";
6802     SetVersion($DBversion);
6803 }
6804
6805 $DBversion = "3.11.00.202";
6806 if ( CheckVersion($DBversion) ) {
6807    $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ca', 'language', 'Catalan','2013-01-12' )");
6808    $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'ca','cat')");
6809    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'es', 'Catalán')");
6810    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'en', 'Catalan')");
6811    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'fr', 'Catalan')");
6812    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'ca', 'Català')");
6813    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'de', 'Katalanisch')");
6814    print "Upgrade to $DBversion done (Bug 9381: Add Catalan laguage)\n";
6815    SetVersion ($DBversion);
6816 }
6817
6818 $DBversion = "3.11.00.203";
6819 if ( CheckVersion($DBversion) ) {
6820     $dbh->do(q{ALTER TABLE suggestions CHANGE COLUMN title title VARCHAR(255) DEFAULT NULL;});
6821     print "Upgrade to $DBversion done (Bug 2046 - increasing title column length for suggestions)\n";
6822     SetVersion ($DBversion);
6823 }
6824
6825 $DBversion = "3.11.00.300";
6826 if ( CheckVersion($DBversion) ) {
6827     print "Upgrade to $DBversion done (3.12-beta3 release)\n";
6828     SetVersion ($DBversion);
6829 }
6830
6831 $DBversion = "3.11.00.301";
6832 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6833     #issues
6834     $dbh->do(q{
6835         ALTER TABLE `issues`
6836             ADD KEY `itemnumber_idx` (`itemnumber`),
6837             ADD KEY `branchcode_idx` (`branchcode`),
6838             ADD KEY `issuingbranch_idx` (`issuingbranch`)
6839     });
6840     $dbh->do(q{
6841         ALTER TABLE `old_issues`
6842             ADD KEY `branchcode_idx` (`branchcode`),
6843             ADD KEY `issuingbranch_idx` (`issuingbranch`)
6844     });
6845     #items
6846     $dbh->do(q{
6847         ALTER TABLE `items` ADD KEY `itype_idx` (`itype`)
6848     });
6849     $dbh->do(q{
6850         ALTER TABLE `deleteditems` ADD KEY `itype_idx` (`itype`)
6851     });
6852     # biblioitems
6853     $dbh->do(q{
6854         ALTER TABLE `biblioitems` ADD KEY `itemtype_idx` (`itemtype`)
6855     });
6856     $dbh->do(q{
6857         ALTER TABLE `deletedbiblioitems` ADD KEY `itemtype_idx` (`itemtype`)
6858     });
6859     # statistics
6860     $dbh->do(q{
6861         ALTER TABLE `statistics`
6862             ADD KEY `branch_idx` (`branch`),
6863             ADD KEY `proccode_idx` (`proccode`),
6864             ADD KEY `type_idx` (`type`),
6865             ADD KEY `usercode_idx` (`usercode`),
6866             ADD KEY `itemnumber_idx` (`itemnumber`),
6867             ADD KEY `itemtype_idx` (`itemtype`),
6868             ADD KEY `borrowernumber_idx` (`borrowernumber`),
6869             ADD KEY `associatedborrower_idx` (`associatedborrower`),
6870             ADD KEY `ccode_idx` (`ccode`)
6871     });
6872
6873     print "Upgrade to $DBversion done (Bug 9681: Add some database indexes)\n";
6874     SetVersion($DBversion);
6875 }
6876
6877 $DBversion = "3.12.00.000";
6878 if ( CheckVersion($DBversion) ) {
6879     print "Upgrade to $DBversion done (3.12.0 release)\n";
6880     SetVersion ($DBversion);
6881 }
6882
6883 $DBversion = '3.13.00.000';
6884 if ( CheckVersion($DBversion) ) {
6885     print "Upgrade to $DBversion done (start the journey to Koha Pi)\n";
6886     SetVersion ($DBversion);
6887 }
6888
6889 $DBversion = "3.13.00.001";
6890 if ( CheckVersion($DBversion) ) {
6891     $dbh->do("INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('UseCourseReserves', '0', NULL, 'Enable the course reserves feature.', 'YesNo')");
6892     $dbh->do("INSERT INTO userflags (bit,flag,flagdesc,defaulton) VALUES ('18','coursereserves','Course Reserves','0')");
6893     $dbh->do("
6894 CREATE TABLE `courses` (
6895   `course_id` int(11) NOT NULL AUTO_INCREMENT,
6896   `department` varchar(20) DEFAULT NULL,
6897   `course_number` varchar(255) DEFAULT NULL,
6898   `section` varchar(255) DEFAULT NULL,
6899   `course_name` varchar(255) DEFAULT NULL,
6900   `term` varchar(20) DEFAULT NULL,
6901   `staff_note` mediumtext,
6902   `public_note` mediumtext,
6903   `students_count` varchar(20) DEFAULT NULL,
6904   `enabled` enum('yes','no') NOT NULL DEFAULT 'yes',
6905   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6906    PRIMARY KEY (`course_id`)
6907 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6908     ");
6909
6910     $dbh->do("
6911 CREATE TABLE `course_instructors` (
6912   `course_id` int(11) NOT NULL,
6913   `borrowernumber` int(11) NOT NULL,
6914   PRIMARY KEY (`course_id`,`borrowernumber`),
6915   KEY `borrowernumber` (`borrowernumber`)
6916 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6917     ");
6918
6919     $dbh->do("
6920 ALTER TABLE `course_instructors`
6921   ADD CONSTRAINT `course_instructors_ibfk_2` FOREIGN KEY (`course_id`) REFERENCES `courses` (`course_id`),
6922   ADD CONSTRAINT `course_instructors_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE;
6923     ");
6924
6925     $dbh->do("
6926 CREATE TABLE `course_items` (
6927   `ci_id` int(11) NOT NULL AUTO_INCREMENT,
6928   `itemnumber` int(11) NOT NULL,
6929   `itype` varchar(10) DEFAULT NULL,
6930   `ccode` varchar(10) DEFAULT NULL,
6931   `holdingbranch` varchar(10) DEFAULT NULL,
6932   `location` varchar(80) DEFAULT NULL,
6933   `enabled` enum('yes','no') NOT NULL DEFAULT 'no',
6934   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6935    PRIMARY KEY (`ci_id`),
6936    UNIQUE KEY `itemnumber` (`itemnumber`),
6937    KEY `holdingbranch` (`holdingbranch`)
6938 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6939     ");
6940
6941     $dbh->do("
6942 ALTER TABLE `course_items`
6943   ADD CONSTRAINT `course_items_ibfk_2` FOREIGN KEY (`holdingbranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
6944   ADD CONSTRAINT `course_items_ibfk_1` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE;
6945 ");
6946
6947     $dbh->do("
6948 CREATE TABLE `course_reserves` (
6949   `cr_id` int(11) NOT NULL AUTO_INCREMENT,
6950   `course_id` int(11) NOT NULL,
6951   `ci_id` int(11) NOT NULL,
6952   `staff_note` mediumtext,
6953   `public_note` mediumtext,
6954   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6955    PRIMARY KEY (`cr_id`),
6956    UNIQUE KEY `pseudo_key` (`course_id`,`ci_id`),
6957    KEY `course_id` (`course_id`)
6958 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6959 ");
6960
6961     $dbh->do("
6962 ALTER TABLE `course_reserves`
6963   ADD CONSTRAINT `course_reserves_ibfk_1` FOREIGN KEY (`course_id`) REFERENCES `courses` (`course_id`);
6964     ");
6965
6966     $dbh->do("
6967 INSERT INTO permissions (module_bit, code, description) VALUES
6968   (18, 'manage_courses', 'Add, edit and delete courses'),
6969   (18, 'add_reserves', 'Add course reserves'),
6970   (18, 'delete_reserves', 'Remove course reserves')
6971 ;
6972     ");
6973
6974
6975     print "Upgrade to $DBversion done (Add Course Reserves ( system preference UseCourseReserves ))\n";
6976     SetVersion($DBversion);
6977 }
6978
6979 $DBversion = "3.13.00.002";
6980 if ( CheckVersion($DBversion) ) {
6981    $dbh->do("UPDATE systempreferences SET variable = 'IndependentBranches' WHERE variable = 'IndependantBranches'");
6982    print "Upgrade to $DBversion done (Bug 10080 - Change system pref IndependantBranches to IndependentBranches)\n";
6983    SetVersion ($DBversion);
6984 }
6985
6986 $DBversion = '3.13.00.003';
6987 if ( CheckVersion($DBversion) ) {
6988     $dbh->do("ALTER TABLE serial DROP itemnumber");
6989     print "Upgrade to $DBversion done (Bug 7718 - Remove itemnumber column from serials table)\n";
6990     SetVersion($DBversion);
6991 }
6992
6993 $DBversion = "3.13.00.004";
6994 if(CheckVersion($DBversion)) {
6995     $dbh->do(
6996 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacShowHoldNotes',0,'Show hold notes on OPAC','','YesNo')"
6997     );
6998     print "Upgrade to $DBversion done (Bug 9722: Allow users to add notes when placing a hold in OPAC)\n";
6999     SetVersion($DBversion);
7000 }
7001
7002 $DBversion = "3.13.00.005";
7003 if(CheckVersion($DBversion)) {
7004     my $intra= C4::Context->preference("intranetstylesheet");
7005     #if this pref is not blank or starting with http, https or / [root], then
7006     #add an additional / to the front
7007     if($intra && $intra !~ /^(\/|https?)/) {
7008         $dbh->do("UPDATE systempreferences SET value=? WHERE variable=?",
7009             undef,('/'.$intra,"intranetstylesheet"));
7010         print "WARNING: Your system preference intranetstylesheet has been prefixed with a slash to make it an absolute path.\n";
7011     }
7012     print "Upgrade to $DBversion done (Bug 10052: Make intranetstylesheet and intranetcolorstylesheet behave exactly like their opac counterparts)\n";
7013     SetVersion ($DBversion);
7014 }
7015
7016 $DBversion = "3.13.00.006";
7017 if ( CheckVersion($DBversion) ) {
7018     $dbh->do(
7019         q{
7020 INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('CalculateFinesOnReturn','1','Switch to control if overdue fines are calculated on return or not', '', 'YesNo');
7021 }
7022     );
7023     print
7024 "Upgrade to $DBversion done (Bug 10120 - Fines on item return controlled by a systempreference)\n";
7025     SetVersion($DBversion);
7026 }
7027
7028 $DBversion = "3.13.00.007";
7029 if ( CheckVersion($DBversion) ) {
7030     $dbh->do("UPDATE systempreferences SET variable='OpacHoldNotes' WHERE variable='OpacShowHoldNotes'");
7031     print "Upgrade to $DBversion done (Bug 10343: Rename OpacShowHoldNotes to OpacHoldNotes)\n";
7032     SetVersion($DBversion);
7033 }
7034
7035 $DBversion = "3.13.00.008";
7036 if ( CheckVersion($DBversion) ) {
7037     $dbh->do("
7038 CREATE TABLE IF NOT EXISTS borrower_files (
7039   file_id int(11) NOT NULL AUTO_INCREMENT,
7040   borrowernumber int(11) NOT NULL,
7041   file_name varchar(255) NOT NULL,
7042   file_type varchar(255) NOT NULL,
7043   file_description varchar(255) DEFAULT NULL,
7044   file_content longblob NOT NULL,
7045   date_uploaded timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
7046   PRIMARY KEY (file_id),
7047   KEY borrowernumber (borrowernumber),
7048   CONSTRAINT borrower_files_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
7049 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7050     ");
7051     print "Upgrade to $DBversion done (Bug 10443: make sure borrower_files table exists)\n";
7052     SetVersion($DBversion);
7053 }
7054
7055 $DBversion = "3.13.00.009";
7056 if ( CheckVersion($DBversion) ) {
7057     $dbh->do("ALTER TABLE aqorders DROP COLUMN biblioitemnumber");
7058     print "Upgrade to $DBversion done (Bug 9987 - Drop column aqorders.biblioitemnumber)\n";
7059     SetVersion($DBversion);
7060 }
7061
7062 $DBversion = "3.13.00.010";
7063 if ( CheckVersion($DBversion) ) {
7064     $dbh->do(
7065         q{
7066 INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AcqWarnOnDuplicateInvoice','0','Warn librarians when they try to create a duplicate invoice', '', 'YesNo');
7067 }
7068     );
7069     print
7070 "Upgrade to $DBversion done (Bug 10366 - Add system preference to enabling warning librarian when invoice is duplicated)\n";
7071     SetVersion($DBversion);
7072 }
7073
7074 $DBversion = "3.13.00.011";
7075 if ( CheckVersion($DBversion) ) {
7076     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='ita' WHERE rfc4646_subtag='it'");
7077     print "Upgrade to $DBversion done (Bug 9519: Wrong language code for Italian in the advanced search language limitations)\n";
7078     SetVersion($DBversion);
7079 }
7080
7081 $DBversion = "3.13.00.012";
7082 if ( CheckVersion($DBversion) ) {
7083     $dbh->do("ALTER TABLE issuingrules MODIFY COLUMN overduefinescap decimal(28,6) DEFAULT NULL;");
7084     print "Upgrade to $DBversion done (Bug 10490: Correct datatype for overduefinescap in issuingrules)\n";
7085     SetVersion($DBversion);
7086 }
7087
7088 $DBversion ="3.13.00.013";
7089 if ( CheckVersion($DBversion) ) {
7090     $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');");
7091     print "Upgrade to $DBversion done (Bug 9576: add AllowTooManyOverride syspref to enable or disable issue limit confirmation)\n";
7092     SetVersion($DBversion);
7093 }
7094
7095 $DBversion = "3.13.00.014";
7096 if ( CheckVersion($DBversion) ) {
7097     $dbh->do("ALTER TABLE courses MODIFY COLUMN department varchar(80) DEFAULT NULL;");
7098     $dbh->do("ALTER TABLE courses MODIFY COLUMN term       varchar(80) DEFAULT NULL;");
7099     print "Upgrade to $DBversion done (Bug 10604: correct width of courses.department and courses.term)\n";
7100     SetVersion($DBversion);
7101 }
7102
7103 $DBversion = "3.13.00.015";
7104 if ( CheckVersion($DBversion) ) {
7105     $dbh->do(
7106 "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')"
7107     );
7108     print "Upgrade to $DBversion done (Bug 7494: Add itemBarcodeFallbackSearch syspref)\n";
7109     SetVersion($DBversion);
7110 }
7111
7112 $DBversion = "3.13.00.016";
7113 if ( CheckVersion($DBversion) ) {
7114     $dbh->do(q{
7115         ALTER TABLE items CHANGE wthdrawn withdrawn TINYINT( 1 ) NOT NULL DEFAULT  '0'
7116     });
7117
7118     $dbh->do(q{
7119         ALTER TABLE deleteditems CHANGE wthdrawn withdrawn TINYINT( 1 ) NOT NULL DEFAULT  '0'
7120     });
7121
7122     $dbh->do(q{
7123         UPDATE saved_sql SET savedsql = REPLACE(savedsql, 'wthdrawn', 'withdrawn')
7124     });
7125
7126     $dbh->do(q{
7127         UPDATE marc_subfield_structure SET kohafield = 'items.withdrawn' WHERE kohafield = 'items.wthdrawn'
7128     });
7129
7130     print "Upgrade to $DBversion done (Bug 10550 - Fix database typo wthdrawn)\n";
7131     SetVersion($DBversion);
7132 }
7133
7134 $DBversion = "3.13.00.017";
7135 if ( CheckVersion($DBversion) ) {
7136     $dbh->do(
7137 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveClientKey','','Client key for OverDrive integration','30','Free')"
7138     );
7139     $dbh->do(
7140 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveClientSecret','','Client key for OverDrive integration','30','YesNo')"
7141     );
7142     $dbh->do(
7143 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveLibraryID','','Library ID for OverDrive integration','','Integer')"
7144     );
7145     print "Upgrade to $DBversion done (Bug 10320 - Show results from library's OverDrive collection in OPAC search)\n";
7146     SetVersion($DBversion);
7147 }
7148
7149 $DBversion = "3.13.00.018";
7150 if ( CheckVersion($DBversion) ) {
7151     $dbh->do(qq{DROP TABLE IF EXISTS aqorders_transfers;});
7152     $dbh->do(qq{
7153         CREATE TABLE aqorders_transfers (
7154           ordernumber_from int(11) NULL,
7155           ordernumber_to int(11) NULL,
7156           timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
7157           UNIQUE KEY ordernumber_from (ordernumber_from),
7158           UNIQUE KEY ordernumber_to (ordernumber_to),
7159           CONSTRAINT aqorders_transfers_ordernumber_from FOREIGN KEY (ordernumber_from) REFERENCES aqorders (ordernumber) ON DELETE SET NULL ON UPDATE CASCADE,
7160           CONSTRAINT aqorders_transfers_ordernumber_to FOREIGN KEY (ordernumber_to) REFERENCES aqorders (ordernumber) ON DELETE SET NULL ON UPDATE CASCADE
7161         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7162     });
7163     print "Upgrade to $DBversion done (Bug 5349: Add aqorders_transfers table)\n";
7164     SetVersion($DBversion);
7165 }
7166
7167 $DBversion = "3.13.00.019";
7168 if ( CheckVersion($DBversion) ) {
7169     $dbh->do("ALTER TABLE itemtypes ADD COLUMN checkinmsg VARCHAR(255) AFTER summary;");
7170     $dbh->do("ALTER TABLE itemtypes ADD COLUMN checkinmsgtype CHAR(16) DEFAULT 'message' NOT NULL AFTER checkinmsg;");
7171     print "Upgrade to $DBversion done (Bug 10513 - Light up a warning/message when returning a chosen item type)\n";
7172     SetVersion($DBversion);
7173 }
7174
7175 $DBversion = "3.13.00.020";
7176 if ( CheckVersion($DBversion) ) {
7177     $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')");
7178     $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')");
7179     print "Upgrade to $DBversion done (Bug 7639: system preferences to forgive fines on lost items)\n";
7180     SetVersion($DBversion);
7181 }
7182
7183 $DBversion ="3.13.00.021";
7184 if ( CheckVersion($DBversion) ) {
7185     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ConfirmFutureHolds','0','Number of days for confirming future holds','','Integer');");
7186     print "Upgrade to $DBversion done (Bug 9761: Add ConfirmFutureHolds pref)\n";
7187     SetVersion($DBversion);
7188 }
7189
7190 $DBversion = "3.13.00.022";
7191 if ( CheckVersion($DBversion) ) {
7192     $dbh->do("DELETE from auth_tag_structure WHERE tagfield IN ('68a','68b')");
7193     $dbh->do("DELETE from auth_subfield_structure WHERE tagfield IN ('68a','68b')");
7194     print "Upgrade to $DBversion done (Bug 10687 - Delete erroneous tags 68a and 68b on default MARC21 auth framework)\n";
7195     SetVersion($DBversion);
7196 }
7197
7198 $DBversion = "3.13.00.023";
7199 if ( CheckVersion($DBversion) ) {
7200     $dbh->do("ALTER TABLE borrowers CHANGE password password VARCHAR(60);");
7201     print "Upgrade to $DBversion done (Bug 9611 upgrading password storage system)\n";
7202     SetVersion($DBversion);
7203 }
7204
7205 $DBversion = "3.13.00.024";
7206 if ( CheckVersion($DBversion) ) {
7207     $dbh->do(q{ALTER TABLE z3950servers ADD COLUMN recordtype VARCHAR(45) NOT NULL DEFAULT 'biblio' AFTER description;});
7208     print "Upgrade to $DBversion done (Bug 10096 - Add a Z39.50 interface for authority searching)\n";
7209 }
7210
7211 $DBversion = "3.13.00.025";
7212 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
7213    $dbh->do("ALTER TABLE oai_sets_mappings ADD COLUMN operator varchar(8) NOT NULL default 'equal' AFTER marcsubfield;");
7214    print "Upgrade to $DBversion done (Bug 9295: OAI notequal: add operator column to OAI mappings table)\n";
7215    SetVersion ($DBversion);
7216 }
7217
7218 $DBversion = "3.13.00.026";
7219 if ( CheckVersion($DBversion) ) {
7220     $dbh->do(q|
7221         ALTER TABLE auth_subfield_structure ADD COLUMN defaultvalue TEXT DEFAULT NULL AFTER frameworkcode
7222     |);
7223     print "Upgrade to $DBversion done (Bug 10602: Add the column auth_subfield_structure.defaultvalue)\n";
7224     SetVersion($DBversion);
7225 }
7226
7227 $DBversion = "3.13.00.027";
7228 if ( CheckVersion($DBversion) ) {
7229     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('AllowOfflineCirculation','0','','If on, enables HTML5 offline circulation functionality.','YesNo')");
7230     print "Upgrade to $DBversion done (Bug 10240: Add syspref AllowOfflineCirculation)\n";
7231     SetVersion ($DBversion);
7232 }
7233
7234 $DBversion = "3.13.00.028";
7235 if ( CheckVersion($DBversion) ) {
7236     $dbh->do(q{
7237         ALTER TABLE export_format ADD type VARCHAR(255) DEFAULT 'marc' AFTER encoding
7238     });
7239     $dbh->do(q{
7240         ALTER TABLE export_format CHANGE marcfields content mediumtext NOT NULL
7241     });
7242     print "Upgrade to $DBversion done (Bug 10853: Add new field export_format.type and rename export_format.marcfields with export_format.content)\n";
7243     SetVersion($DBversion);
7244 }
7245
7246 $DBversion = "3.13.00.029";
7247 if ( CheckVersion($DBversion) ) {
7248     $dbh->do(q{
7249         INSERT IGNORE INTO export_format( profile, description, content, csv_separator, type )
7250         VALUES ( "issues to claim", "Default CSV export for serial issue claims",
7251                 "SUPPLIER=aqbooksellers.name|TITLE=subscription.title|ISSUE NUMBER=serial.serialseq|LATE SINCE=serial.planneddate",
7252                 ",", "sql" )
7253     });
7254     print "Upgrade to $DBversion done (Bug 10854: Add the default CSV profile for claiming issues)\n";
7255     SetVersion($DBversion);
7256 }
7257
7258 $DBversion = "3.13.00.030";
7259 if ( CheckVersion($DBversion) ) {
7260     $dbh->do(qq{
7261         DELETE FROM patronimage WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowers.cardnumber = patronimage.cardnumber)
7262     });
7263
7264     $dbh->do(qq{
7265         ALTER TABLE patronimage ADD borrowernumber INT( 11 ) NULL FIRST
7266     });
7267
7268     $dbh->{AutoCommit} = 0;
7269     $dbh->{RaiseError} = 1;
7270
7271     eval {
7272         $dbh->do(qq{
7273             UPDATE patronimage LEFT JOIN borrowers USING ( cardnumber ) SET patronimage.borrowernumber = borrowers.borrowernumber
7274         });
7275         $dbh->commit();
7276     };
7277
7278     if ($@) {
7279         print "Upgrade to $DBversion done (Bug 10636 - patronimage should have borrowernumber as PK, not cardnumber) failed! Transaction aborted because $@\n";
7280         eval { $dbh->rollback };
7281     }
7282     else {
7283         $dbh->do(qq{
7284             ALTER TABLE patronimage DROP FOREIGN KEY patronimage_fk1
7285         });
7286         $dbh->do(qq{
7287             ALTER TABLE patronimage DROP PRIMARY KEY, ADD PRIMARY KEY( borrowernumber )
7288         });
7289         $dbh->do(qq{
7290             ALTER TABLE patronimage DROP cardnumber
7291         });
7292         $dbh->do(qq{
7293             ALTER TABLE patronimage ADD FOREIGN KEY ( borrowernumber ) REFERENCES borrowers ( borrowernumber ) ON DELETE CASCADE ON UPDATE CASCADE
7294         });
7295
7296         print "Upgrade to $DBversion done (Bug 10636 - patronimage should have borrowernumber as PK, not cardnumber)\n";
7297         SetVersion($DBversion);
7298     }
7299
7300     $dbh->{AutoCommit} = 1;
7301     $dbh->{RaiseError} = 0;
7302 }
7303
7304 $DBversion = "3.13.00.031";
7305 if ( CheckVersion($DBversion) ) {
7306
7307     $dbh->do(q{
7308         CREATE TABLE IF NOT EXISTS `patron_lists` (
7309           patron_list_id int(11) NOT NULL AUTO_INCREMENT,
7310           name varchar(255) CHARACTER SET utf8 NOT NULL,
7311           owner int(11) NOT NULL,
7312           PRIMARY KEY (patron_list_id),
7313           KEY owner (owner)
7314         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7315     });
7316
7317     $dbh->do(q{
7318         ALTER TABLE `patron_lists`
7319           ADD CONSTRAINT patron_lists_ibfk_1 FOREIGN KEY (`owner`) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE;
7320     });
7321
7322     $dbh->do(q{
7323         CREATE TABLE patron_list_patrons (
7324           patron_list_patron_id int(11) NOT NULL AUTO_INCREMENT,
7325           patron_list_id int(11) NOT NULL,
7326           borrowernumber int(11) NOT NULL,
7327           PRIMARY KEY (patron_list_patron_id),
7328           KEY patron_list_id (patron_list_id),
7329           KEY borrowernumber (borrowernumber)
7330         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7331     });
7332
7333     $dbh->do(q{
7334         ALTER TABLE `patron_list_patrons`
7335           ADD CONSTRAINT patron_list_patrons_ibfk_1 FOREIGN KEY (patron_list_id) REFERENCES patron_lists (patron_list_id) ON DELETE CASCADE ON UPDATE CASCADE,
7336           ADD CONSTRAINT patron_list_patrons_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE;
7337     });
7338
7339     $dbh->do(q{
7340         INSERT INTO permissions (module_bit, code, description) VALUES
7341         (13, 'manage_patron_lists', 'Add, edit and delete patron lists and their contents')
7342     });
7343
7344     print "Upgrade to $DBversion done (Bug 10565 - Add a 'Patron List' feature for storing and manipulating collections of patrons)\n";
7345     SetVersion($DBversion);
7346 }
7347
7348 $DBversion = "3.13.00.032";
7349 if ( CheckVersion($DBversion) ) {
7350     $dbh->do("ALTER TABLE aqorders ADD COLUMN orderstatus varchar(16) DEFAULT 'new' AFTER parent_ordernumber");
7351     $dbh->do("UPDATE aqorders SET orderstatus='ordered' WHERE basketno IN (SELECT basketno FROM aqbasket WHERE closedate IS NOT NULL)");
7352     $dbh->do(q{
7353         UPDATE aqorders SET orderstatus='partial'
7354         WHERE quantity > quantityreceived
7355         AND quantityreceived > 0
7356         AND ordernumber IN (
7357             SELECT parent_ordernumber
7358             FROM (
7359                 SELECT DISTINCT(parent_ordernumber)
7360                 FROM aqorders
7361                 WHERE ordernumber != parent_ordernumber
7362             ) AS aq
7363         )
7364         AND basketno IN (SELECT basketno FROM aqbasket WHERE closedate IS NOT NULL)
7365     });
7366     $dbh->do("UPDATE aqorders SET orderstatus='complete' WHERE quantity=quantityreceived");
7367     $dbh->do("UPDATE aqorders SET orderstatus='cancelled' WHERE datecancellationprinted IS NOT NULL");
7368     print "Upgrade to $DBversion done (Bug 5336: Add the new column aqorders.orderstatus)\n";
7369     SetVersion($DBversion);
7370 }
7371
7372 $DBversion = "3.13.00.033";
7373 if ( CheckVersion($DBversion) ) {
7374     $dbh->do(qq|
7375         DROP TABLE IF EXISTS subscription_frequencies
7376     |);
7377     $dbh->do(qq|
7378         CREATE TABLE subscription_frequencies (
7379             id INTEGER NOT NULL AUTO_INCREMENT,
7380             description TEXT NOT NULL,
7381             displayorder INT DEFAULT NULL,
7382             unit ENUM('day','week','month','year') DEFAULT NULL,
7383             unitsperissue INTEGER NOT NULL DEFAULT '1',
7384             issuesperunit INTEGER NOT NULL DEFAULT '1',
7385             PRIMARY KEY (id)
7386         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
7387     |);
7388
7389     $dbh->do(qq|
7390         DROP TABLE IF EXISTS subscription_numberpatterns
7391     |);
7392     $dbh->do(qq|
7393         CREATE TABLE subscription_numberpatterns (
7394             id INTEGER NOT NULL AUTO_INCREMENT,
7395             label VARCHAR(255) NOT NULL,
7396             displayorder INTEGER DEFAULT NULL,
7397             description TEXT NOT NULL,
7398             numberingmethod VARCHAR(255) NOT NULL,
7399             label1 VARCHAR(255) DEFAULT NULL,
7400             add1 INTEGER DEFAULT NULL,
7401             every1 INTEGER DEFAULT NULL,
7402             whenmorethan1 INTEGER DEFAULT NULL,
7403             setto1 INTEGER DEFAULT NULL,
7404             numbering1 VARCHAR(255) DEFAULT NULL,
7405             label2 VARCHAR(255) DEFAULT NULL,
7406             add2 INTEGER DEFAULT NULL,
7407             every2 INTEGER DEFAULT NULL,
7408             whenmorethan2 INTEGER DEFAULT NULL,
7409             setto2 INTEGER DEFAULT NULL,
7410             numbering2 VARCHAR(255) DEFAULT NULL,
7411             label3 VARCHAR(255) DEFAULT NULL,
7412             add3 INTEGER DEFAULT NULL,
7413             every3 INTEGER DEFAULT NULL,
7414             whenmorethan3 INTEGER DEFAULT NULL,
7415             setto3 INTEGER DEFAULT NULL,
7416             numbering3 VARCHAR(255) DEFAULT NULL,
7417             PRIMARY KEY (id)
7418         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
7419     |);
7420
7421     $dbh->do(qq|
7422         INSERT INTO subscription_frequencies (description, unit, unitsperissue, issuesperunit, displayorder)
7423         VALUES
7424             ('2/day', 'day', 1, 2, 1),
7425             ('1/day', 'day', 1, 1, 2),
7426             ('3/week', 'week', 1, 3, 3),
7427             ('1/week', 'week', 1, 1, 4),
7428             ('1/2 weeks', 'week', 2, 1, 5),
7429             ('1/3 weeks', 'week', 3, 1, 6),
7430             ('1/month', 'month', 1, 1, 7),
7431             ('1/2 months', 'month', 2, 1, 8),
7432             ('1/3 months', 'month', 3, 1, 9),
7433             ('2/year', 'month', 6, 1, 10),
7434             ('1/year', 'year', 1, 1, 11),
7435             ('1/2 year', 'year', 2, 1, 12),
7436             ('Irregular', NULL, 1, 1, 13)
7437     |);
7438
7439     # Used to link existing subscription to newly created frequencies
7440     my $frequencies_mapping = {     # keys are old frequency numbers, values are the new ones
7441         1 => 2,     # daily (n/week)
7442         2 => 4,     # 1/week
7443         3 => 5,     # 1/2 weeks
7444         4 => 6,     # 1/3 weeks
7445         5 => 7,     # 1/month
7446         6 => 8,     # 1/2 months (6/year)
7447         7 => 9,     # 1/3 months (1/quarter)
7448         8 => 9,    # 1/quarter (seasonal)
7449         9 => 10,    # 2/year
7450         10 => 11,   # 1/year
7451         11 => 12,   # 1/2 years
7452         12 => 1,    # 2/day
7453         16 => 13,   # Without periodicity
7454         32 => 13,   # Irregular
7455         48 => 13    # Unknown
7456     };
7457
7458     $dbh->do(qq|
7459         INSERT INTO subscription_numberpatterns
7460             (label, displayorder, description, numberingmethod,
7461             label1, add1, every1, whenmorethan1, setto1, numbering1,
7462             label2, add2, every2, whenmorethan2, setto2, numbering2,
7463             label3, add3, every3, whenmorethan3, setto3, numbering3)
7464         VALUES
7465             ('Number', 1, 'Simple Numbering method', 'No.{X}',
7466             'Number', 1, 1, 99999, 1, NULL,
7467             NULL, NULL, NULL, NULL, NULL, NULL,
7468             NULL, NULL, NULL, NULL, NULL, NULL),
7469
7470             ('Volume, Number, Issue', 2, 'Volume Number Issue 1', 'Vol.{X}, Number {Y}, Issue {Z}',
7471             'Volume', 1, 48, 99999, 1, NULL,
7472             'Number', 1, 4, 12, 1, NULL,
7473             'Issue', 1, 1, 4, 1, NULL),
7474
7475             ('Volume, Number', 3, 'Volume Number 1', 'Vol {X}, No {Y}',
7476             'Volume', 1, 12, 99999, 1, NULL,
7477             'Number', 1, 1, 12, 1, NULL,
7478             NULL, NULL, NULL, NULL, NULL, NULL),
7479
7480             ('Seasonal', 4, 'Season Year', '{X} {Y}',
7481             'Season', 1, 1, 3, 0, 'season',
7482             'Year', 1, 4, 99999, 1, NULL,
7483             NULL, NULL, NULL, NULL, NULL, NULL)
7484     |);
7485
7486     $dbh->do(qq|
7487         ALTER TABLE subscription
7488         MODIFY COLUMN numberpattern INTEGER DEFAULT NULL,
7489         MODIFY COLUMN periodicity INTEGER DEFAULT NULL
7490     |);
7491
7492     # Update existing subscriptions
7493
7494     my $query = qq|
7495         SELECT subscriptionid, periodicity, numberingmethod,
7496             add1, every1, whenmorethan1, setto1,
7497             add2, every2, whenmorethan2, setto2,
7498             add3, every3, whenmorethan3, setto3
7499         FROM subscription
7500         ORDER BY subscriptionid
7501     |;
7502     my $sth = $dbh->prepare($query);
7503     $sth->execute;
7504     my $insert_numberpatterns_sth = $dbh->prepare(qq|
7505         INSERT INTO subscription_numberpatterns
7506              (label, displayorder, description, numberingmethod,
7507             label1, add1, every1, whenmorethan1, setto1, numbering1,
7508             label2, add2, every2, whenmorethan2, setto2, numbering2,
7509             label3, add3, every3, whenmorethan3, setto3, numbering3)
7510         VALUES
7511             (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
7512     |);
7513     my $check_numberpatterns_sth = $dbh->prepare(qq|
7514         SELECT * FROM subscription_numberpatterns
7515         WHERE (add1 = ? OR (add1 IS NULL AND ? IS NULL)) AND (add2 = ? OR (add2 IS NULL AND ? IS NULL))
7516         AND (add3 = ? OR (add3 IS NULL AND ? IS NULL)) AND (every1 = ? OR (every1 IS NULL AND ? IS NULL))
7517         AND (every2 = ? OR (every2 IS NULL AND ? IS NULL)) AND (every3 = ? OR (every3 IS NULL AND ? IS NULL))
7518         AND (whenmorethan1 = ? OR (whenmorethan1 IS NULL AND ? IS NULL)) AND (whenmorethan2 = ? OR (whenmorethan2 IS NULL AND ? IS NULL))
7519         AND (whenmorethan3 = ? OR (whenmorethan3 IS NULL AND ? IS NULL)) AND (setto1 = ? OR (setto1 IS NULL AND ? IS NULL))
7520         AND (setto2 = ? OR (setto2 IS NULL AND ? IS NULL)) AND (setto3 = ? OR (setto3 IS NULL AND ? IS NULL))
7521         AND (numberingmethod = ? OR (numberingmethod IS NULL AND ? IS NULL))
7522         LIMIT 1
7523     |);
7524     my $update_subscription_sth = $dbh->prepare(qq|
7525         UPDATE subscription
7526         SET numberpattern = ?,
7527             periodicity = ?
7528         WHERE subscriptionid = ?
7529     |);
7530
7531     my $i = 1;
7532     while(my $sub = $sth->fetchrow_hashref) {
7533         $check_numberpatterns_sth->execute(
7534             $sub->{add1}, $sub->{add1}, $sub->{add2}, $sub->{add2}, $sub->{add3}, $sub->{add3},
7535             $sub->{every1}, $sub->{every1}, $sub->{every2}, $sub->{every2}, $sub->{every3}, $sub->{every3},
7536             $sub->{whenmorethan1}, $sub->{whenmorethan1}, $sub->{whenmorethan2}, $sub->{whenmorethan2},
7537             $sub->{whenmorethan3}, $sub->{whenmorethan3}, $sub->{setto1}, $sub->{setto1}, $sub->{setto2},
7538             $sub->{setto2}, $sub->{setto3}, $sub->{setto3}, $sub->{numberingmethod}, $sub->{numberingmethod}
7539         );
7540         my $p = $check_numberpatterns_sth->fetchrow_hashref;
7541         if (defined $p) {
7542             # Pattern already exists, link to it
7543             $update_subscription_sth->execute($p->{id},
7544                 $frequencies_mapping->{$sub->{periodicity}},
7545                 $sub->{subscriptionid});
7546         } else {
7547             # Create a new numbering pattern for this subscription
7548             my $ok = $insert_numberpatterns_sth->execute(
7549                 "Backup pattern $i", 4+$i, "Automatically created pattern by updatedatabase", $sub->{numberingmethod},
7550                 "X", $sub->{add1}, $sub->{every1}, $sub->{whenmorethan1}, $sub->{setto1}, undef,
7551                 "Y", $sub->{add2}, $sub->{every2}, $sub->{whenmorethan2}, $sub->{setto2}, undef,
7552                 "Z", $sub->{add3}, $sub->{every3}, $sub->{whenmorethan3}, $sub->{setto3}, undef
7553             );
7554             if($ok) {
7555                 my $id = $dbh->last_insert_id(undef, undef, 'subscription_numberpatterns', undef);
7556                 # Link to subscription_numberpatterns and subscription_frequencies
7557                 $update_subscription_sth->execute($id,
7558                     $frequencies_mapping->{$sub->{periodicity}},
7559                     $sub->{subscriptionid});
7560             }
7561             $i++;
7562         }
7563     }
7564
7565     # Remove now useless columns
7566     $dbh->do(qq|
7567         ALTER TABLE subscription
7568         DROP COLUMN numberingmethod,
7569         DROP COLUMN add1,
7570         DROP COLUMN every1,
7571         DROP COLUMN whenmorethan1,
7572         DROP COLUMN setto1,
7573         DROP COLUMN add2,
7574         DROP COLUMN every2,
7575         DROP COLUMN whenmorethan2,
7576         DROP COLUMN setto2,
7577         DROP COLUMN add3,
7578         DROP COLUMN every3,
7579         DROP COLUMN whenmorethan3,
7580         DROP COLUMN setto3,
7581         DROP COLUMN dow,
7582         DROP COLUMN issuesatonce,
7583         DROP COLUMN hemisphere,
7584         ADD COLUMN countissuesperunit INTEGER NOT NULL DEFAULT 1 AFTER periodicity,
7585         ADD COLUMN skip_serialseq BOOLEAN NOT NULL DEFAULT 0 AFTER irregularity,
7586         ADD COLUMN locale VARCHAR(80) DEFAULT NULL AFTER numberpattern,
7587         ADD CONSTRAINT subscription_ibfk_1 FOREIGN KEY (periodicity) REFERENCES subscription_frequencies (id) ON DELETE SET NULL ON UPDATE CASCADE,
7588         ADD CONSTRAINT subscription_ibfk_2 FOREIGN KEY (numberpattern) REFERENCES subscription_numberpatterns (id) ON DELETE SET NULL ON UPDATE CASCADE
7589     |);
7590
7591     # Set firstacquidate if not already set (firstacquidate is now mandatory)
7592     my $get_first_planneddate_sth = $dbh->prepare(qq|
7593         SELECT planneddate
7594         FROM serial
7595         WHERE subscriptionid = ?
7596         ORDER BY serialid
7597         LIMIT 1
7598     |);
7599     my $update_firstacquidate_sth = $dbh->prepare(qq|
7600         UPDATE subscription
7601         SET firstacquidate = ?
7602         WHERE subscriptionid = ?
7603     |);
7604     my $get_subscriptions_sth = $dbh->prepare(qq|
7605         SELECT subscriptionid, startdate
7606         FROM subscription
7607         WHERE firstacquidate IS NULL
7608           OR firstacquidate = '0000-00-00'
7609     |);
7610     $get_subscriptions_sth->execute;
7611     while ( my ($subscriptionid, $startdate) = $get_subscriptions_sth->fetchrow ) {
7612         # Try to get the planned date of the first serial
7613         $get_first_planneddate_sth->execute($subscriptionid);
7614         my ($first_planneddate) = $get_first_planneddate_sth->fetchrow;
7615         if ($first_planneddate and $first_planneddate =~ /^\d{4}-\d{2}-\d{2}$/) {
7616             $update_firstacquidate_sth->execute($first_planneddate, $subscriptionid);
7617         } else {
7618             # Defaults to subscription start date
7619             $update_firstacquidate_sth->execute($startdate, $subscriptionid);
7620         }
7621     }
7622
7623     print "Upgrade to $DBversion done (Bug 7688: add subscription_frequencies and subscription_numberpatterns tables)\n";
7624     SetVersion($DBversion);
7625 }
7626
7627 $DBversion = "3.13.00.034";
7628 if ( CheckVersion($DBversion) ) {
7629     $dbh->do("
7630         ALTER TABLE `import_batches`
7631         CHANGE `item_action` `item_action`
7632           ENUM( 'always_add', 'add_only_for_matches', 'add_only_for_new', 'ignore', 'replace' )
7633           NOT NULL DEFAULT 'always_add'
7634     ");
7635     print "Upgrade to $DBversion done (Bug 7131 - way to overlay items in in marc import)\n";
7636     SetVersion($DBversion);
7637 }
7638
7639 $DBversion ="3.13.00.035";
7640 if ( CheckVersion($DBversion) ) {
7641     $dbh->do(q{
7642 CREATE TABLE borrower_debarments (
7643   borrower_debarment_id int(11) NOT NULL AUTO_INCREMENT,
7644   borrowernumber int(11) NOT NULL,
7645   expiration date DEFAULT NULL,
7646   `type` enum('SUSPENSION','OVERDUES','MANUAL') NOT NULL DEFAULT 'MANUAL',
7647   `comment` text,
7648   manager_id int(11) DEFAULT NULL,
7649   created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
7650   updated timestamp NULL DEFAULT NULL,
7651   PRIMARY KEY (borrower_debarment_id),
7652   KEY borrowernumber (borrowernumber) ,
7653   CONSTRAINT `borrower_debarments_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
7654     ON DELETE CASCADE ON UPDATE CASCADE
7655 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7656     });
7657
7658     # debarments with end date
7659     $dbh->do(q{
7660 INSERT INTO borrower_debarments ( borrowernumber, expiration, comment ) SELECT borrowernumber, debarred, debarredcomment FROM borrowers WHERE debarred IS NOT NULL AND debarred <> '9999-12-31'
7661     });
7662     # debarments with no end date
7663     $dbh->do(q{
7664 INSERT INTO borrower_debarments ( borrowernumber, comment ) SELECT borrowernumber, debarredcomment FROM borrowers WHERE debarred = '9999-12-31'
7665     });
7666
7667     $dbh->do(q{
7668 INSERT IGNORE INTO systempreferences (variable,value,explanation,type) VALUES
7669 ('AutoRemoveOverduesRestrictions','0','Defines whether an OVERDUES debarment should be lifted automatically if all overdue items are returned by the patron.','YesNo')
7670     });
7671
7672     print "Upgrade to $DBversion done (Bug 2720 - Overdues which debar automatically should undebar automatically when returned)\n";
7673     SetVersion($DBversion);
7674 }
7675
7676 $DBversion = "3.13.00.036";
7677 if ( CheckVersion($DBversion) ) {
7678     $dbh->do(qq{
7679         INSERT INTO systempreferences (variable, value, explanation, options, type)
7680         VALUES ('StaffDetailItemSelection', '1', 'Enable item selection in record detail page', NULL, 'YesNo')
7681     });
7682     print "Upgrade to $DBversion done (Add system preference StaffDetailItemSelection)\n";
7683     SetVersion($DBversion);
7684 }
7685
7686 $DBversion = "3.13.00.037";
7687 if ( CheckVersion($DBversion) ) {
7688     #add phone if it is not there already (explains the ignore option)
7689     $dbh->do("
7690 INSERT IGNORE INTO message_transport_types (message_transport_type) values ('phone');
7691     ");
7692     print "Upgrade to $DBversion done (Bug 10572: Add phone to message_transport_types table for new installs)\n";
7693     SetVersion($DBversion);
7694 }
7695
7696 $DBversion = "3.13.00.038";
7697 if ( CheckVersion($DBversion) ) {
7698     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES(15, 'superserials', 'Manage subscriptions from any branch (only applies when IndependentBranches is used)')");
7699     print "Upgrade to $DBversion done (Bug 8435: Add superserials permission)\n";
7700     SetVersion($DBversion);
7701 }
7702
7703 $DBversion = "3.13.00.039";
7704 if ( CheckVersion($DBversion) ) {
7705     $dbh->do("
7706         ALTER TABLE aqbasket ADD branch varchar(10) default NULL
7707     ");
7708     $dbh->do("
7709         ALTER TABLE aqbasket
7710         ADD CONSTRAINT aqbasket_ibfk_4 FOREIGN KEY (branch)
7711             REFERENCES branches (branchcode)
7712             ON UPDATE CASCADE ON DELETE SET NULL
7713     ");
7714     $dbh->do("
7715         DROP TABLE IF EXISTS aqbasketusers
7716     ");
7717     $dbh->do("
7718         CREATE TABLE aqbasketusers (
7719             basketno int(11) NOT NULL,
7720             borrowernumber int(11) NOT NULL,
7721             PRIMARY KEY (basketno,borrowernumber),
7722             CONSTRAINT aqbasketusers_ibfk_1 FOREIGN KEY (basketno) REFERENCES aqbasket (basketno) ON DELETE CASCADE ON UPDATE CASCADE,
7723             CONSTRAINT aqbasketusers_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
7724         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7725     ");
7726     $dbh->do("
7727         INSERT INTO permissions (module_bit, code, description)
7728         VALUES (11, 'order_manage_all', 'Manage all orders and baskets, regardless of restrictions on them')
7729     ");
7730
7731     print "Upgrade to $DBversion done (Add branch and users list to baskets. "
7732         . "New permission order_manage_all)\n";
7733     SetVersion($DBversion);
7734 }
7735
7736 $DBversion = "3.13.00.040";
7737 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
7738     $dbh->do("CREATE TABLE IF NOT EXISTS marc_modification_templates (
7739               template_id int(11) NOT NULL auto_increment,
7740               name text NOT NULL,
7741               PRIMARY KEY  (template_id)
7742               ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;"
7743     );
7744
7745     $dbh->do("
7746       CREATE TABLE IF NOT EXISTS marc_modification_template_actions (
7747       mmta_id int(11) NOT NULL auto_increment,
7748       template_id int(11) NOT NULL,
7749       ordering int(3) NOT NULL,
7750       action enum('delete_field','update_field','move_field','copy_field') NOT NULL,
7751       field_number smallint(6) NOT NULL default '0',
7752       from_field varchar(3) NOT NULL,
7753       from_subfield varchar(1) NULL,
7754       field_value varchar(100) default NULL,
7755       to_field varchar(3) default NULL,
7756       to_subfield varchar(1) default NULL,
7757       to_regex_search text,
7758       to_regex_replace text,
7759       to_regex_modifiers varchar(8) default '',
7760       conditional enum('if','unless') default NULL,
7761       conditional_field varchar(3) default NULL,
7762       conditional_subfield varchar(1) default NULL,
7763       conditional_comparison enum('exists','not_exists','equals','not_equals') default NULL,
7764       conditional_value text,
7765       conditional_regex tinyint(1) NOT NULL default '0',
7766       description text,
7767       PRIMARY KEY  (mmta_id),
7768       CONSTRAINT `mmta_ibfk_1` FOREIGN KEY (`template_id`) REFERENCES `marc_modification_templates` (`template_id`) ON DELETE CASCADE ON UPDATE CASCADE
7769       ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7770     ");
7771
7772     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('13', 'marc_modification_templates', 'Manage marc modification templates')");
7773
7774     print "Upgrade to $DBversion done ( Bug 8015: Added tables for MARC Modification Framework )\n";
7775     SetVersion($DBversion);
7776 }
7777
7778 $DBversion = "3.13.00.041";
7779 if(CheckVersion($DBversion)) {
7780     $dbh->do(q{
7781         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');
7782     });
7783     print "Upgrade to $DBversion done (Bug 10986: Added AcqItemSetSubfieldsWhenReceived syspref)\n";
7784     SetVersion($DBversion);
7785 }
7786
7787 $DBversion = "3.13.00.042";
7788 if(CheckVersion($DBversion)) {
7789     print "Upgrade to $DBversion done (Koha 3.14 beta)\n";
7790     SetVersion($DBversion);
7791 }
7792
7793 $DBversion = "3.13.00.043";
7794 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
7795     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('SearchEngine','Zebra','Solr|Zebra','Search Engine','Choice')");
7796     print "Upgrade to $DBversion done (Bug 11196: Add system preference SearchEngine if missing )\n";
7797     SetVersion($DBversion);
7798 }
7799
7800 $DBversion = "3.14.00.000";
7801 if ( CheckVersion($DBversion) ) {
7802     print "Upgrade to $DBversion done (3.14.0 release)\n";
7803     SetVersion ($DBversion);
7804 }
7805
7806 $DBversion = '3.15.00.000';
7807 if ( CheckVersion($DBversion) ) {
7808     print "Upgrade to $DBversion done (the road goes ever on)\n";
7809     SetVersion ($DBversion);
7810 }
7811
7812 $DBversion = "3.15.00.001";
7813 if ( CheckVersion($DBversion) ) {
7814     $dbh->do("UPDATE systempreferences SET value='clear' where variable = 'CircAutoPrintQuickSlip' and value = '0'");
7815     $dbh->do("UPDATE systempreferences SET value='qslip' where variable = 'CircAutoPrintQuickSlip' and value = '1'");
7816     $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'");
7817     print "Upgrade to $DBversion done (Bug 11040: Add option to print full slip when checking out a null barcode)\n";
7818     SetVersion($DBversion);
7819 }
7820
7821 $DBversion = "3.15.00.002";
7822 if(CheckVersion($DBversion)) {
7823     $dbh->do("ALTER TABLE deleteditems MODIFY materials text;");
7824     print "Upgrade to $DBversion done (Bug 11275: alter deleteditems.materials from varchar(10) to text)\n";
7825     SetVersion($DBversion);
7826 }
7827
7828 $DBversion = "3.15.00.003";
7829 if ( CheckVersion($DBversion) ) {
7830     $dbh->do(q{
7831         UPDATE accountlines
7832         SET description = ''
7833         WHERE description IN (
7834             ' New Card',
7835             ' Fine',
7836             ' Sundry',
7837             'Writeoff',
7838             ' Account Management fee',
7839             'Payment,thanks', 'Payment,thanks - ',
7840             ' Lost Item'
7841         )
7842     });
7843     print "Upgrade to $DBversion done (Bug 2546: Update fine descriptions)\n";
7844     SetVersion($DBversion);
7845 }
7846
7847 $DBversion = "3.15.00.004";
7848 if ( CheckVersion($DBversion) ) {
7849     if ( C4::Context->preference("marcflavour") eq 'MARC21' ) {
7850         $dbh->do(qq{
7851             INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian, libopac, repeatable, mandatory,
7852             kohafield, tab, authorised_value, authtypecode, value_builder, isurl, hidden, frameworkcode, seealso, link,
7853             defaultvalue) VALUES
7854             ('015', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7855             ('020', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7856             ('024', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7857             ('027', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7858             ('800', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7859             ('810', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7860             ('811', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7861             ('830', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL);
7862         });
7863         $dbh->do(qq{
7864             INSERT IGNORE INTO auth_subfield_structure (authtypecode, tagfield, tagsubfield, liblibrarian, libopac, repeatable,
7865             mandatory, tab, authorised_value, value_builder, seealso, isurl, hidden, linkid, kohafield, frameworkcode) VALUES
7866             ('', '020', 'q', 'Qualifying information', 'Qualifying information', 1, 0, 0, NULL, NULL, NULL, 0, 0, '', '', ''),
7867             ('', '024', 'q', 'Qualifying information', 'Qualifying information', 1, 0, 0, NULL, NULL, NULL, 0, 0, '', '', '');
7868         });
7869     }
7870     print "Upgrade to $DBversion done (Bug 10970 - Update MARC21 frameworks to Update Nr. 17 - DB update)\n";
7871     SetVersion($DBversion);
7872 }
7873
7874 $DBversion = "3.15.00.005";
7875 if ( CheckVersion($DBversion) ) {
7876    $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('AcquisitionDetails', '1', '', 'Hide/Show acquisition details on the biblio detail page.', 'YesNo');");
7877    print "Upgrade to $DBversion done (Bug 8230: Add AcquisitionDetails system preference)\n";
7878    SetVersion ($DBversion);
7879 }
7880
7881 $DBversion = "3.15.00.006";
7882 if(CheckVersion($DBversion)) {
7883     $dbh->do(q{
7884         ALTER TABLE `borrowers`
7885         ADD KEY `surname_idx` (`surname`(255)),
7886         ADD KEY `firstname_idx` (`firstname`(255)),
7887         ADD KEY `othernames_idx` (`othernames`(255))
7888     });
7889     print "Upgrade to $DBversion done (Bug 11249 - Add DB indexes on borrower names)\n";
7890     SetVersion($DBversion);
7891 }
7892
7893 $DBversion = "3.15.00.007";
7894 if ( CheckVersion($DBversion) ) {
7895    $dbh->do("ALTER TABLE items ADD itemlost_on DATETIME NULL AFTER itemlost");
7896    $dbh->do("ALTER TABLE items ADD withdrawn_on DATETIME NULL AFTER withdrawn");
7897    $dbh->do("ALTER TABLE deleteditems ADD itemlost_on DATETIME NULL AFTER itemlost");
7898    $dbh->do("ALTER TABLE deleteditems ADD withdrawn_on DATETIME NULL AFTER withdrawn");
7899    print "Upgrade to $DBversion done (Bug 9673 - Track when items are marked as lost or withdrawn)\n";
7900    SetVersion ($DBversion);
7901 }
7902
7903 $DBversion = "3.15.00.008";
7904 if ( CheckVersion($DBversion) ) {
7905     $dbh->do(q{
7906         ALTER TABLE collections_tracking CHANGE ctId collections_tracking_id integer(11) NOT NULL auto_increment;
7907     });
7908     print "Upgrade to $DBversion done (Bug 11384) - change name of collections_tracker.ctId column)\n";
7909    SetVersion ($DBversion);
7910 }
7911
7912 $DBversion = "3.15.00.009";
7913 if ( CheckVersion($DBversion) ) {
7914     $dbh->do(q{
7915         ALTER TABLE suggestions MODIFY suggesteddate DATE NOT NULL
7916     });
7917     print "Upgrade to $DBversion done (Bug 11391) - drop default value on suggestions.suggesteddate column)\n";
7918    SetVersion ($DBversion);
7919 }
7920
7921 $DBversion = "3.15.00.010";
7922 if(CheckVersion($DBversion)) {
7923     $dbh->do("ALTER TABLE deleteditems DROP COLUMN marc");
7924     print "Upgrade to $DBversion done (Bug 6331: remove obsolete column in deleteditems.marc)\n";
7925     SetVersion ($DBversion);
7926 }
7927
7928 $DBversion = "3.15.00.011";
7929 if(CheckVersion($DBversion)) {
7930     $dbh->do("UPDATE marc_subfield_structure SET maxlength=9999 WHERE maxlength IS NULL OR maxlength=0;");
7931     print "Upgrade to $DBversion done (Bug 8018: set 9999 as default max length for subfields)\n";
7932     SetVersion ($DBversion);
7933 }
7934
7935 $DBversion = "3.15.00.012";
7936 if ( CheckVersion($DBversion) ) {
7937     $dbh->do(q{
7938         INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'force_checkout', 'Force checkout if a limitation exists')
7939     });
7940     $dbh->do(q{
7941         INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'manage_restrictions', 'Manage restrictions for accounts')
7942     });
7943     $dbh->do(q{
7944         INSERT INTO user_permissions (borrowernumber, module_bit, code)
7945             SELECT user_permissions.borrowernumber, 1, 'force_checkout'
7946             FROM user_permissions
7947             LEFT JOIN borrowers USING(borrowernumber)
7948             WHERE borrowers.flags & (1 << 1)
7949     });
7950     $dbh->do(q{
7951         INSERT INTO user_permissions (borrowernumber, module_bit, code)
7952             SELECT user_permissions.borrowernumber, 1, 'manage_restrictions'
7953             FROM user_permissions
7954             LEFT JOIN borrowers USING(borrowernumber)
7955             WHERE borrowers.flags & (1 << 1)
7956     });
7957
7958     print "Upgrade to $DBversion done (Bug 10863 - Add permissions force_checkout and manage_restrictions)\n";
7959     SetVersion($DBversion);
7960 }
7961
7962 $DBversion = "3.15.00.013";
7963 if(CheckVersion($DBversion)) {
7964     $dbh->do(q{
7965         UPDATE systempreferences
7966         SET explanation = 'Upon receiving items, update their subfields if they were created when placing an order (e.g. o=5|a="foo bar")'
7967         WHERE variable = "AcqItemSetSubfieldsWhenReceived"
7968     });
7969
7970     $dbh->do(q{
7971         UPDATE systempreferences
7972         SET value = ''
7973         WHERE variable = "AcqItemSetSubfieldsWhenReceived"
7974             AND value = "0"
7975     });
7976     print "Upgrade to $DBversion done (Bug 11237: Update explanation and default value for AcqItemSetSubfieldsWhenReceived syspref)\n";
7977     SetVersion($DBversion);
7978 }
7979
7980 $DBversion = "3.15.00.014";
7981 if (CheckVersion($DBversion)) {
7982     $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');");
7983     print "Upgrade to $DBversion done (Bug 11415: add system preference for automatic self checkout receipt printing)\n";
7984     SetVersion($DBversion);
7985 }
7986
7987 $DBversion = "3.15.00.015";
7988 if (CheckVersion($DBversion)) {
7989     $dbh->do("INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
7990         ('OpacSuggestionManagedBy',1,'','Show the name of the staff member who managed a suggestion in OPAC','YesNo');");
7991     print "Upgrade to $DBversion done (Bug 10907: Add OpacSuggestionManagedBy system preference)\n";
7992     SetVersion($DBversion);
7993 }
7994
7995 $DBversion = "3.15.00.016";
7996 if (CheckVersion($DBversion)) {
7997     $dbh->do("ALTER TABLE biblioitems CHANGE url url TEXT NULL DEFAULT NULL");
7998     $dbh->do("ALTER TABLE deletedbiblioitems CHANGE url url TEXT NULL DEFAULT NULL");
7999     print "Upgrade to $DBversion done (Bug 11268 - Biblioitems URL field is too small for some URLs)\n";
8000     SetVersion($DBversion);
8001 }
8002
8003 $DBversion = "3.15.00.017";
8004 if(CheckVersion($DBversion)) {
8005     $dbh->do(q{
8006         UPDATE systempreferences
8007         SET explanation = 'Define the contents of UNIMARC authority control field 100 position 08-35'
8008         WHERE variable = "UNIMARCAuthorityField100"
8009     });
8010     $dbh->do(q{
8011         UPDATE systempreferences
8012         SET explanation = 'Define the contents of MARC21 authority control field 008 position 06-39'
8013         WHERE variable = "MARCAuthorityControlField008"
8014     });
8015     $dbh->do(q{
8016         UPDATE systempreferences
8017         SET explanation = 'Define MARC Organization Code for MARC21 records - http://www.loc.gov/marc/organizations/orgshome.html'
8018         WHERE variable = "MARCOrgCode"
8019     });
8020     print "Upgrade to $DBversion done (Bug 11611 - fix possible confusion between UNIMARC and MARC21 in some sysprefs)\n";
8021     SetVersion($DBversion);
8022 }
8023
8024 $DBversion = "3.15.00.018";
8025 if ( CheckVersion($DBversion) ) {
8026     $dbh->{AutoCommit} = 0;
8027     $dbh->{RaiseError} = 1;
8028
8029     eval {
8030         $dbh->selectcol_arrayref(q|SELECT COUNT(*) FROM roadtype|);
8031     };
8032     unless ( $@ ) {
8033         my $av_added = $dbh->do(q|
8034             INSERT INTO authorised_values(category, authorised_value, lib, lib_opac)
8035                 SELECT 'ROADTYPE', roadtypeid, road_type, road_type
8036                 FROM roadtype;
8037         |);
8038
8039         my $rt_deleted = $dbh->do(q|
8040             DELETE FROM roadtype
8041         |);
8042
8043         if ( $av_added == $rt_deleted or $rt_deleted eq "0E0" ) {
8044             $dbh->do(q|
8045                 DROP TABLE roadtype;
8046             |);
8047             $dbh->commit;
8048             print "Upgrade to $DBversion done (Bug 7372: Move road types from the roadtype table to the ROADTYPE authorised values)\n";
8049             SetVersion($DBversion);
8050         } else {
8051             print "Upgrade to $DBversion failed (Bug 7372: Move road types from the roadtype table to the ROADTYPE authorised values.\nTransaction aborted because $@\n)";
8052             $dbh->rollback;
8053         }
8054     }
8055     $dbh->{AutoCommit} = 1;
8056     $dbh->{RaiseError} = 0;
8057 }
8058
8059 $DBversion = "3.15.00.019";
8060 if ( CheckVersion($DBversion) ) {
8061     $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')");
8062     print "Upgrade to $DBversion done (Bug 11256: Add system preference OpacMaxItemsToDisplay)\n";
8063     SetVersion($DBversion);
8064 }
8065
8066 $DBversion = "3.15.00.020";
8067 if ( CheckVersion($DBversion) ) {
8068     $dbh->do(q|
8069         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')
8070     |);
8071     print "Upgrade to $DBversion done (Bug 11343: Add system preference MaxItemsForBatch )\n";
8072     SetVersion($DBversion);
8073 }
8074
8075 $DBversion = "3.15.00.021";
8076 if(CheckVersion($DBversion)) {
8077     $dbh->do(q{
8078         ALTER TABLE `action_logs`
8079             DROP KEY timestamp,
8080             ADD KEY `timestamp_idx` (`timestamp`),
8081             ADD KEY `user_idx` (`user`),
8082             ADD KEY `module_idx` (`module`(255)),
8083             ADD KEY `action_idx` (`action`(255)),
8084             ADD KEY `object_idx` (`object`),
8085             ADD KEY `info_idx` (`info`(255))
8086     });
8087     print "Upgrade to $DBversion done (Bug 3445: Add indexes to action_logs table)\n";
8088     SetVersion($DBversion);
8089 }
8090
8091 $DBversion = "3.15.00.022";
8092 if (CheckVersion($DBversion)) {
8093     $dbh->do(q|
8094         DELETE FROM systempreferences WHERE variable= "memberofinstitution"
8095     |);
8096     print "Upgrade to $DBversion done (Bug 11751: Remove memberofinstitytion system preference)\n";
8097     SetVersion($DBversion);
8098 }
8099
8100 $DBversion = "3.15.00.023";
8101 if ( CheckVersion($DBversion) ) {
8102    $dbh->do("
8103        INSERT INTO systempreferences (variable,value,options,explanation,type)
8104        VALUES('CardnumberLength', '', '', 'Set a length for card numbers.', 'Free');
8105     ");
8106    print "Upgrade to $DBversion done (Bug 10861: Add CardnumberLength syspref)\n";
8107    SetVersion ($DBversion);
8108 }
8109
8110 $DBversion = "3.15.00.024";
8111 if ( CheckVersion($DBversion) ) {
8112     $dbh->do(q{
8113         DELETE FROM systempreferences WHERE variable = 'NoZebraIndexes'
8114     });
8115     print "Upgrade to $DBversion done (Bug 10012 - remove last vestiges of NoZebra)\n";
8116     SetVersion($DBversion);
8117 }
8118
8119 $DBversion = "3.15.00.025";
8120 if ( CheckVersion($DBversion) ) {
8121     $dbh->do(q{
8122         DROP TABLE aqorderdelivery;
8123     });
8124     print "Upgrade to $DBversion done (Bug 11928 - remove unused table)\n";
8125     SetVersion($DBversion);
8126 }
8127
8128 $DBversion = "3.15.00.026";
8129 if ( CheckVersion($DBversion) ) {
8130     $dbh->do(q{
8131         UPDATE language_descriptions SET description = 'Հայերեն' WHERE subtag = 'hy' AND lang = 'hy';
8132     });
8133     print "Upgrade to $DBversion done (Bug 11973 - Fix Armenian language description)\n";
8134     SetVersion($DBversion);
8135 }
8136
8137 $DBversion = "3.15.00.027";
8138 if (CheckVersion($DBversion)) {
8139     $dbh->do(q{
8140         ALTER TABLE opac_news ADD branchcode varchar(10) DEFAULT NULL
8141                                   AFTER idnew,
8142                               ADD CONSTRAINT opac_news_branchcode_ibfk
8143                                   FOREIGN KEY (branchcode)
8144                                   REFERENCES branches (branchcode)
8145                                   ON DELETE CASCADE ON UPDATE CASCADE;
8146     });
8147     print "Upgrade to $DBversion done (Bug 7567: Add branchcode to opac_news)\n";
8148     SetVersion($DBversion);
8149 }
8150
8151 $DBversion = "3.15.00.028";
8152 if(CheckVersion($DBversion)) {
8153     $dbh->do(q{
8154         ALTER TABLE issuingrules ADD norenewalbefore int(4) default NULL AFTER renewalperiod
8155     });
8156     print "Upgrade to $DBversion done (Bug 7413: Allow OPAC renewal x days before due date)\n";
8157     SetVersion($DBversion);
8158 }
8159
8160 $DBversion = "3.15.00.029";
8161 if ( CheckVersion($DBversion) ) {
8162     $dbh->do(q{
8163         UPDATE borrower_debarments SET expiration = NULL WHERE expiration = '9999-12-31'
8164     });
8165     print "Upgrade to $DBversion done (Bug 11846 - correct borrower_debarments with expiration 9999-12-31)\n";
8166     SetVersion($DBversion);
8167 }
8168
8169 $DBversion = "3.15.00.030";
8170 if(CheckVersion($DBversion)) {
8171     $dbh->do(q|
8172         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')
8173     |);
8174     print "Upgrade to $DBversion done (Bug 12052: Add OPACMySummaryNote syspref)\n";
8175     SetVersion($DBversion);
8176 }
8177
8178 $DBversion = "3.15.00.031";
8179 if ( CheckVersion($DBversion) ) {
8180    $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('10', 'writeoff', 'Write off fines and fees')");
8181    $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('10', 'remaining_permissions', 'Remaining permissions for managing fines and fees')");
8182    print "Upgrade to $DBversion done (Bug 9448 - Add separate permission for writing off fees)\n";
8183    SetVersion ($DBversion);
8184 }
8185
8186 $DBversion = "3.15.00.032";
8187 if ( CheckVersion($DBversion) ) {
8188     $dbh->do("ALTER TABLE aqorders CHANGE notes order_internalnote MEDIUMTEXT;");
8189     $dbh->do("ALTER TABLE aqorders ADD COLUMN order_vendornote MEDIUMTEXT AFTER order_internalnote;");
8190     print "Upgrade to $DBversion done (Bug 9416 - In each order, add a new note made for the vendor)\n";
8191    SetVersion ($DBversion);
8192 }
8193
8194 $DBversion = "3.15.00.033";
8195 if ( CheckVersion($DBversion) ) {
8196     $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')");
8197     print "Upgrade to $DBversion done (Bug 10951: Add NoLoginInstructions pref)\n";
8198     SetVersion($DBversion);
8199 }
8200
8201 $DBversion = "3.15.00.034";
8202 if ( CheckVersion($DBversion) ) {
8203     $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')");
8204     print "Upgrade to $DBversion done (Bug 10986: system preferences to limit languages in advanced search )\n";
8205     SetVersion ($DBversion);
8206 }
8207
8208 $DBversion = "3.15.00.035";
8209 if ( CheckVersion($DBversion) ) {
8210     #insert a notice for sharing a list and accepting a share
8211     $dbh->do("
8212 INSERT INTO letter (module, code, branchcode, name, is_html, title, content)
8213 VALUES ( 'members', 'SHARE_INVITE', '', 'Invitation for sharing a list', '0', 'Share list <<listname>>', 'Dear patron,
8214
8215 One of our patrons, <<borrowers.firstname>> <<borrowers.surname>>, invites you to share a list <<listname>> in our library catalog.
8216
8217 To access this shared list, please click on the following URL or copy-and-paste it into your browser address bar.
8218
8219 <<shareurl>>
8220
8221 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.
8222
8223 Thank you.
8224
8225 Your library.'
8226     )");
8227     $dbh->do("
8228 INSERT INTO letter (module, code, branchcode, name, is_html, title, content)
8229 VALUES ( 'members', 'SHARE_ACCEPT', '', 'Notification about an accepted share', '0', 'Share on list <<listname>> accepted', 'Dear patron,
8230
8231 We want to inform you that <<borrowers.firstname>> <<borrowers.surname>> accepted your invitation to share your list <<listname>> in our library catalog.
8232
8233 Thank you.
8234
8235 Your library.'
8236     )");
8237     print "Upgrade to $DBversion done (Bug 9032: Share a list)\n";
8238     SetVersion($DBversion);
8239 }
8240
8241 $DBversion = "3.15.00.036";
8242 if ( CheckVersion($DBversion) ) {
8243     $dbh->do(q{
8244         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
8245         VALUES('AllowMultipleIssuesOnABiblio',1,'Allow/Don\'t allow patrons to check out multiple items from one biblio','','YesNo')
8246     });
8247
8248     print "Upgrade to $DBversion done (Bug 10859 - Add system preference AllowMultipleIssuesOnABiblio)\n";
8249     SetVersion($DBversion);
8250 }
8251
8252 $DBversion = "3.15.00.037";
8253 if(CheckVersion($DBversion)) {
8254     $dbh->do(q{
8255         ALTER TABLE itemtypes ADD sip_media_type VARCHAR( 3 ) DEFAULT NULL AFTER checkinmsgtype
8256     });
8257     $dbh->do(q{
8258         INSERT INTO authorised_values (category, authorised_value, lib) VALUES
8259          ('SIP_MEDIA_TYPE', '000', 'Other'),
8260          ('SIP_MEDIA_TYPE', '001', 'Book'),
8261          ('SIP_MEDIA_TYPE', '002', 'Magazine'),
8262          ('SIP_MEDIA_TYPE', '003', 'Bound journal'),
8263          ('SIP_MEDIA_TYPE', '004', 'Audio tape'),
8264          ('SIP_MEDIA_TYPE', '005', 'Video tape'),
8265          ('SIP_MEDIA_TYPE', '006', 'CD/CDROM'),
8266          ('SIP_MEDIA_TYPE', '007', 'Diskette'),
8267          ('SIP_MEDIA_TYPE', '008', 'Book with diskette'),
8268          ('SIP_MEDIA_TYPE', '009', 'Book with CD'),
8269          ('SIP_MEDIA_TYPE', '010', 'Book with audio tape')
8270     });
8271     print "Upgrade to $DBversion done (Bug 11351 - Add support for SIP2 media type)\n";
8272     SetVersion($DBversion);
8273 }
8274
8275 $DBversion = '3.15.00.038';
8276 if ( CheckVersion($DBversion) ) {
8277     $dbh->do(q{
8278         INSERT INTO  systempreferences (
8279             variable,
8280             value,
8281             options,
8282             explanation,
8283             type
8284             )
8285         VALUES (
8286             'DisplayLibraryFacets',  'holding',  'home|holding|both',  'Defines which library facets to display.',  'Choice'
8287         );
8288     });
8289     print "Upgrade to $DBversion done (Bug 11334 - Add facet for home library)\n";
8290     SetVersion ($DBversion);
8291 }
8292
8293 $DBversion = "3.15.00.039";
8294 if ( CheckVersion($DBversion) ) {
8295
8296     $dbh->do( q{
8297         ALTER TABLE letter ADD COLUMN message_transport_type VARCHAR(20) NOT NULL DEFAULT 'email' AFTER content
8298     } );
8299
8300     $dbh->do( q{
8301         ALTER TABLE letter ADD CONSTRAINT message_transport_type_fk FOREIGN KEY (message_transport_type) REFERENCES message_transport_types(message_transport_type);
8302     } );
8303
8304     $dbh->do( q{
8305         ALTER TABLE letter DROP PRIMARY KEY, ADD PRIMARY KEY (`module`,`code`,`branchcode`, message_transport_type);
8306     } );
8307
8308     $dbh->do( q{
8309         CREATE TABLE overduerules_transport_types(
8310             id INT(11) NOT NULL AUTO_INCREMENT,
8311             branchcode varchar(10) NOT NULL DEFAULT '',
8312             categorycode VARCHAR(10) NOT NULL DEFAULT '',
8313             letternumber INT(1) NOT NULL DEFAULT 1,
8314             message_transport_type VARCHAR(20) NOT NULL DEFAULT 'email',
8315             PRIMARY KEY (id),
8316             CONSTRAINT overduerules_fk FOREIGN KEY (branchcode, categorycode) REFERENCES overduerules (branchcode, categorycode) ON DELETE CASCADE ON UPDATE CASCADE,
8317             CONSTRAINT mtt_fk FOREIGN KEY (message_transport_type) REFERENCES message_transport_types (message_transport_type) ON DELETE CASCADE ON UPDATE CASCADE
8318         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
8319     } );
8320
8321     my $sth = $dbh->prepare( q{
8322         SELECT * FROM overduerules;
8323     } );
8324
8325     $sth->execute;
8326     my $sth_insert_mtt = $dbh->prepare( q{
8327         INSERT INTO overduerules_transport_types (branchcode, categorycode, letternumber, message_transport_type) VALUES ( ?, ?, ?, ? )
8328     } );
8329     while ( my $row = $sth->fetchrow_hashref ) {
8330         my $branchcode = $row->{branchcode};
8331         my $categorycode = $row->{categorycode};
8332         for my $letternumber ( 1 .. 3 ) {
8333             next unless $row->{"letter$letternumber"};
8334             $sth_insert_mtt->execute(
8335                 $branchcode, $categorycode, $letternumber, 'email'
8336             );
8337         }
8338     }
8339
8340     print "Upgrade done (Bug 9016: Adds multi transport types management for notices)\n";
8341     SetVersion($DBversion);
8342 }
8343
8344 $DBversion = "3.15.00.040";
8345 if ( CheckVersion($DBversion) ) {
8346     $dbh->do(q|
8347         UPDATE message_transports SET letter_code='HOLD' WHERE letter_code='HOLD_PHONE' OR letter_code='HOLD_PRINT'
8348     |);
8349     $dbh->do(q|
8350         UPDATE letter SET code='HOLD', message_transport_type='print' WHERE code='HOLD_PRINT'
8351     |);
8352     $dbh->do(q|
8353         UPDATE letter SET code='HOLD', message_transport_type='phone' WHERE code='HOLD_PHONE'
8354     |);
8355     print "Upgrade to $DBversion done (Bug 10845: Multi transport types for holds)\n";
8356     SetVersion($DBversion);
8357 }
8358
8359 $DBversion = "3.15.00.041";
8360 if ( CheckVersion($DBversion) ) {
8361     my $name = $dbh->selectcol_arrayref(q|
8362         SELECT name FROM letter WHERE code="HOLD"
8363     |);
8364     $name = $name->[0];
8365     $dbh->do(q|
8366         UPDATE letter
8367         SET code="HOLD",
8368             message_transport_type="phone",
8369             name= ?
8370         WHERE code="HOLD_PHONE"
8371     |, {}, $name);
8372
8373     $dbh->do(q|
8374         UPDATE letter
8375         SET code="PREDUE",
8376             message_transport_type="phone",
8377             name= ?
8378         WHERE code="PREDUE_PHONE"
8379     |, {}, $name);
8380
8381     $dbh->do(q|
8382         UPDATE letter
8383         SET code="OVERDUE",
8384             message_transport_type="phone",
8385             name= ?
8386         WHERE code="OVERDUE_PHONE"
8387     |, {}, $name);
8388
8389     print "Upgrade to $DBversion done (Bug 11867: Update letters *_PHONE)\n";
8390     SetVersion($DBversion);
8391 }
8392
8393 $DBversion = "3.15.00.042";
8394 if ( CheckVersion($DBversion) ) {
8395     $dbh->do(q{
8396         INSERT INTO systempreferences
8397             (variable,value,explanation,options,type)
8398         VALUES
8399             ('SpecifyReturnDate',0,'Define whether to display \"Specify Return Date\" form in Circulation','','YesNo')
8400     });
8401     print "Upgrade to $DBversion done (Bug 10694 - Allow arbitrary backdating of returns)\n";
8402     SetVersion($DBversion);
8403 }
8404
8405 $DBversion = "3.15.00.043";
8406 if ( CheckVersion($DBversion) ) {
8407     $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')");
8408    print "Upgrade to $DBversion done (Bug 7180: Added MarcFieldsToOrder syspref)\n";
8409    SetVersion ($DBversion);
8410 }
8411
8412 $DBversion = "3.15.00.044";
8413 if ( CheckVersion($DBversion) ) {
8414     $dbh->do("ALTER TABLE currency ADD isocode VARCHAR(5) default NULL AFTER symbol;");
8415     print "Upgrade to $DBversion done (Added isocode to the currency table)\n";
8416     SetVersion($DBversion);
8417 }
8418
8419 $DBversion = "3.15.00.045";
8420 if ( CheckVersion($DBversion) ) {
8421     $dbh->do("
8422         INSERT INTO systempreferences (variable,value,explanation,options,type)
8423         VALUES (
8424             'BlockExpiredPatronOpacActions',
8425             '0',
8426             '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',
8427             NULL,
8428             'YesNo'
8429         )
8430     ");
8431     $dbh->do("ALTER TABLE `categories` ADD COLUMN `BlockExpiredPatronOpacActions` TINYINT(1) DEFAULT -1 NOT NULL AFTER category_type");
8432     print "Upgraded to $DBversion done (Bug 6739 - expired patrons not blocked from opac actions)\n";
8433     SetVersion ($DBversion);
8434 }
8435
8436 $DBversion = "3.15.00.046";
8437 if ( CheckVersion($DBversion) ) {
8438     $dbh->do(q|
8439         ALTER TABLE search_history ADD COLUMN type VARCHAR(16) NOT NULL DEFAULT 'biblio' AFTER query_cgi
8440     |);
8441     print "Upgrade to $DBversion done (Bug 10807 - Add db field search_history.type)\n";
8442     SetVersion($DBversion);
8443 }
8444
8445 $DBversion = "3.15.00.047";
8446 if ( CheckVersion($DBversion) ) {
8447     $dbh->do(q|
8448         INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('EnableSearchHistory','0','','Enable or disable search history','YesNo')
8449     |);
8450     print "Upgrade to $DBversion done (Bug 10862: Add EnableSearchHistory syspref)\n";
8451     SetVersion($DBversion);
8452 }
8453
8454 $DBversion = "3.15.00.048";
8455 if ( CheckVersion($DBversion) ) {
8456     $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')");
8457     $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')");
8458     print "Upgrade to $DBversion done (Bug 10195: Records hidden with OpacSuppression can still be accessed)\n";
8459     SetVersion($DBversion);
8460 }
8461
8462 $DBversion = "3.15.00.049";
8463 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
8464     $dbh->do("ALTER TABLE biblioitems DROP INDEX isbn");
8465     $dbh->do("ALTER TABLE biblioitems DROP INDEX issn");
8466     $dbh->do("ALTER TABLE biblioitems
8467               CHANGE isbn isbn MEDIUMTEXT NULL DEFAULT NULL,
8468               CHANGE issn issn MEDIUMTEXT NULL DEFAULT NULL
8469     ");
8470     $dbh->do("ALTER TABLE biblioitems
8471               ADD INDEX isbn ( isbn ( 255 ) ),
8472               ADD INDEX issn ( issn ( 255 ) )
8473     ");
8474
8475     $dbh->do("ALTER TABLE deletedbiblioitems DROP INDEX isbn");
8476     $dbh->do("ALTER TABLE deletedbiblioitems
8477               CHANGE isbn isbn MEDIUMTEXT NULL DEFAULT NULL,
8478               CHANGE issn issn MEDIUMTEXT NULL DEFAULT NULL
8479     ");
8480     $dbh->do("ALTER TABLE deletedbiblioitems
8481               ADD INDEX isbn ( isbn ( 255 ) )
8482     ");
8483
8484     print "Upgrade to $DBversion done (Bug 5377 - Biblioitems isbn and issn fields too small for multiple ISBN and ISSN)\n";
8485     SetVersion($DBversion);
8486 }
8487
8488 $DBversion = "3.15.00.050";
8489 if ( CheckVersion($DBversion) ) {
8490     $dbh->do("
8491         INSERT INTO systempreferences (
8492             variable,
8493             value,
8494             explanation,
8495             type
8496         ) VALUES (
8497             'AggressiveMatchOnISBN',
8498             '0',
8499             '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',
8500             'YesNo'
8501         )
8502     ");
8503
8504     print "Upgrade to $DBversion done (Bug 10500 - Improve isbn matching when importing records)\n";
8505     SetVersion($DBversion);
8506 }
8507
8508 $DBversion = "3.15.00.051";
8509 if ( CheckVersion($DBversion) ) {
8510     print "Upgrade to $DBversion done (Koha 3.16 beta)\n";
8511     SetVersion($DBversion);
8512 }
8513
8514 $DBversion = "3.15.00.052";
8515 if ( CheckVersion($DBversion) ) {
8516     print "Upgrade to $DBversion done (Koha 3.16 RC)\n";
8517     SetVersion($DBversion);
8518 }
8519
8520 $DBversion = "3.16.00.000";
8521 if ( CheckVersion($DBversion) ) {
8522     print "Upgrade to $DBversion done (3.16.0 release)\n";
8523     SetVersion ($DBversion);
8524 }
8525
8526 $DBversion = '3.17.00.000';
8527 if ( CheckVersion($DBversion) ) {
8528     print "Upgrade to $DBversion done (there is no time to rest on our laurels)\n";
8529     SetVersion ($DBversion);
8530 }
8531
8532 $DBversion = '3.17.00.001';
8533 if ( CheckVersion($DBversion) ) {
8534    $dbh->do("UPDATE systempreferences SET variable = 'AuthoritySeparator' WHERE variable = 'authoritysep'");
8535    print "Upgrade to $DBversion done (Bug 10330 - Rename system preference authoritysep to AuthoritySeparator)\n";
8536    SetVersion ($DBversion);
8537 }
8538
8539 $DBversion = "3.17.00.002";
8540 if (CheckVersion($DBversion)) {
8541     $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')");
8542     $dbh->do("
8543 CREATE TABLE IF NOT EXISTS `misc_files` (
8544   `file_id` int(11) NOT NULL AUTO_INCREMENT,
8545   `table_tag` varchar(255) NOT NULL,
8546   `record_id` int(11) NOT NULL,
8547   `file_name` varchar(255) NOT NULL,
8548   `file_type` varchar(255) NOT NULL,
8549   `file_description` varchar(255) DEFAULT NULL,
8550   `file_content` longblob NOT NULL, -- file content
8551   `date_uploaded` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
8552   PRIMARY KEY (`file_id`),
8553   KEY `table_tag` (`table_tag`),
8554   KEY `record_id` (`record_id`)
8555 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
8556     ");
8557     print "Upgrade to $DBversion done (Bug 3050 - Add an option to upload scanned invoices)\n";
8558     SetVersion($DBversion);
8559 }
8560
8561 $DBversion = "3.17.00.003";
8562 if (CheckVersion($DBversion)) {
8563     $dbh->do("UPDATE systempreferences SET type = 'Choice', options = '0|1|force' WHERE variable = 'OPACItemHolds'");
8564     print "Upgrade to $DBversion done (Bug 7825 - Changed OPACItemHolds syspref to Choice)\n";
8565     SetVersion($DBversion);
8566 }
8567
8568 $DBversion = "3.17.00.004";
8569 if (CheckVersion($DBversion)) {
8570     $dbh->do("ALTER TABLE categories ADD default_privacy ENUM( 'default', 'never', 'forever' ) NOT NULL DEFAULT 'default' AFTER category_type");
8571     print "Upgrade to $DBversion done (Bug 6254 - can't set patron privacy by default)\n";
8572     SetVersion($DBversion);
8573 }
8574
8575 $DBversion = "3.17.00.005";
8576 if (CheckVersion($DBversion)) {
8577     $dbh->do(q|
8578         ALTER TABLE issuingrules
8579         ADD maxsuspensiondays INT(11) DEFAULT NULL AFTER finedays;
8580     |);
8581     print "Upgrade to $DBversion done (Bug 12230: Add new issuing rule maxsuspensiondays)\n";
8582     SetVersion($DBversion);
8583 }
8584
8585 $DBversion = "3.17.00.006";
8586 if ( CheckVersion($DBversion) ) {
8587     $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')");
8588     $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')");
8589     print "Upgrade to $DBversion done (Bug 7720 - Ambiguity in OPAC Details location.)\n";
8590     SetVersion($DBversion);
8591 }
8592
8593 $DBversion = "3.17.00.007";
8594 if (CheckVersion($DBversion)) {
8595     $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');");
8596     print "Upgrade to $DBversion done (Bug 11629 - Add ability to update not for loan status on checkin)\n";
8597     SetVersion($DBversion);
8598 }
8599
8600 $DBversion = "3.17.00.008";
8601 if ( CheckVersion($DBversion) ) {
8602     $dbh->do(q|
8603         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('OPACAcquisitionDetails','0', '','Show the acquisition details at the OPAC','YesNo')
8604     |);
8605     print "Upgrade to $DBversion done (Bug 11169 - Add OPACAcquisitionDetails syspref)\n";
8606     SetVersion($DBversion);
8607 }
8608
8609 $DBversion = "3.17.00.009";
8610 if ( CheckVersion($DBversion) ) {
8611     $dbh->do(q{
8612         DELETE FROM systempreferences WHERE variable = 'UseTablesortForCirc'
8613     });
8614
8615     print "Upgrade to $DBversion done (Bug 11703 - Remove UseTablesortForCirc syspref)\n";
8616     SetVersion($DBversion);
8617 }
8618
8619 $DBversion = "3.17.00.010";
8620 if ( CheckVersion($DBversion) ) {
8621     $dbh->do("DELETE FROM systempreferences WHERE variable='opacsmallimage'");
8622     print "Upgrade to $DBversion done (Bug 11347 - PROG/CCSR deprecation: Remove opacsmallimage system preference)\n";
8623     SetVersion($DBversion);
8624 }
8625
8626 $DBversion = "3.17.00.011";
8627 if ( CheckVersion($DBversion) ) {
8628     $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'hr', 'language', 'Croatian','2014-07-24' )");
8629     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'hr','hrv')");
8630     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'hr', 'Hrvatski')");
8631     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'en', 'Croatian')");
8632     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'fr', 'Croate')");
8633     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'de', 'Kroatisch')");
8634     print "Upgrade to $DBversion done (Bug 12649: Add Croatian language)\n";
8635     SetVersion ($DBversion);
8636 }
8637
8638 $DBversion = "3.17.00.012";
8639 if ( CheckVersion($DBversion) ) {
8640     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacShowFiltersPulldownMobile'");
8641     print "Upgrade to $DBversion done ( Bug 12512 - PROG/CCSR deprecation: Remove OpacShowFiltersPulldownMobile system preference )\n";
8642     SetVersion ($DBversion);
8643 }
8644
8645 $DBversion = "3.17.00.013";
8646 if ( CheckVersion($DBversion) ) {
8647     $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')");
8648     print "Upgrade to $DBversion done (Re-add system preference maxreserves)\n";
8649     SetVersion ($DBversion);
8650 }
8651
8652 $DBversion = '3.17.00.014';
8653 if ( CheckVersion($DBversion) ) {
8654     $dbh->do("
8655         INSERT INTO systempreferences (variable,value,explanation,type) VALUES
8656         ('OverdueNoticeCalendar',0,'Take calendar into consideration when working out sending overdue notices','YesNo')
8657     ");
8658     print "Upgrade to $DBversion done (Bug 12529 - Adding a syspref to allow the overdue notices to consider the calendar when generating notices)\n";
8659     SetVersion($DBversion);
8660 }
8661
8662 $DBversion = "3.17.00.015";
8663 if ( CheckVersion($DBversion) ) {
8664     $dbh->do(q{
8665         CREATE TABLE IF NOT EXISTS columns_settings (
8666             module varchar(255) NOT NULL,
8667             page varchar(255) NOT NULL,
8668             tablename varchar(255) NOT NULL,
8669             columnname varchar(255) NOT NULL,
8670             cannot_be_toggled int(1) NOT NULL DEFAULT 0,
8671             is_hidden int(1) NOT NULL DEFAULT 0,
8672             PRIMARY KEY(module, page, tablename, columnname)
8673         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
8674     });
8675     print "Upgrade to $DBversion done (Bug 10212 - Create new table columns_settings)\n";
8676     SetVersion ($DBversion);
8677 }
8678
8679 $DBversion = "3.17.00.016";
8680 if ( CheckVersion($DBversion) ) {
8681     $dbh->do("CREATE TABLE aqcontacts (
8682         id int(11) NOT NULL auto_increment,
8683         name varchar(100) default NULL,
8684         position varchar(100) default NULL,
8685         phone varchar(100) default NULL,
8686         altphone varchar(100) default NULL,
8687         fax varchar(100) default NULL,
8688         email varchar(100) default NULL,
8689         notes mediumtext,
8690         claimacquisition BOOLEAN NOT NULL DEFAULT 0,
8691         claimissues BOOLEAN NOT NULL DEFAULT 0,
8692         acqprimary BOOLEAN NOT NULL DEFAULT 0,
8693         serialsprimary BOOLEAN NOT NULL DEFAULT 0,
8694         booksellerid int(11) not NULL,
8695         PRIMARY KEY  (id),
8696         CONSTRAINT booksellerid_aqcontacts_fk FOREIGN KEY (booksellerid)
8697             REFERENCES aqbooksellers (id) ON DELETE CASCADE ON UPDATE CASCADE
8698         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;");
8699     $dbh->do("INSERT INTO aqcontacts (name, position, phone, altphone, fax,
8700             email, notes, booksellerid, claimacquisition, claimissues, acqprimary, serialsprimary)
8701         SELECT contact, contpos, contphone, contaltphone, contfax, contemail,
8702             contnotes, id, 1, 1, 1, 1 FROM aqbooksellers;");
8703     $dbh->do("ALTER TABLE aqbooksellers DROP COLUMN contact,
8704         DROP COLUMN contpos, DROP COLUMN contphone,
8705         DROP COLUMN contaltphone, DROP COLUMN contfax,
8706         DROP COLUMN contemail, DROP COLUMN contnotes;");
8707     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contact>>', '<<aqcontacts.name>>')");
8708     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contpos>>', '<<aqcontacts.position>>')");
8709     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contphone>>', '<<aqcontacts.phone>>')");
8710     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contaltphone>>', '<<aqcontacts.altphone>>')");
8711     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contfax>>', '<<aqcontacts.contfax>>')");
8712     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contemail>>', '<<aqcontacts.contemail>>')");
8713     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contnotes>>', '<<aqcontacts.contnotes>>')");
8714     print "Upgrade to $DBversion done (Bug 10402: Move bookseller contacts to separate table)\n";
8715     SetVersion($DBversion);
8716 }
8717
8718 $DBversion = "3.17.00.017";
8719 if ( CheckVersion($DBversion) ) {
8720     # Correct invalid recordtypes (should be very exceptional)
8721     $dbh->do(q{
8722         UPDATE z3950servers set recordtype='biblio' WHERE recordtype NOT IN ('authority','biblio')
8723     });
8724     # Correct invalid server types (should also be very exceptional)
8725     $dbh->do(q{
8726         UPDATE z3950servers set type='zed' WHERE type <> 'zed'
8727     });
8728     # Adjust table
8729     $dbh->do(q{
8730         ALTER TABLE z3950servers
8731         DROP COLUMN icon,
8732         DROP COLUMN description,
8733         DROP COLUMN position,
8734         MODIFY COLUMN id int NOT NULL AUTO_INCREMENT FIRST,
8735         MODIFY COLUMN recordtype enum('authority','biblio') NOT NULL DEFAULT 'biblio',
8736         CHANGE COLUMN name servername mediumtext NOT NULL,
8737         CHANGE COLUMN type servertype enum('zed','sru') NOT NULL DEFAULT 'zed',
8738         ADD COLUMN sru_options varchar(255) default NULL,
8739         ADD COLUMN sru_fields mediumtext default NULL,
8740         ADD COLUMN add_xslt mediumtext default NULL
8741     });
8742     print "Upgrade to $DBversion done (Bug 6536: Z3950 improvements)\n";
8743     SetVersion ($DBversion);
8744 }
8745
8746 $DBversion = "3.17.00.018";
8747 if ( CheckVersion($DBversion) ) {
8748     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('HoldsInNoissuesCharge', '0', 'Hold charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
8749     print "Upgrade to $DBversion done (Bug 12205: Add HoldsInNoissuesCharge systempreference)\n";
8750     SetVersion($DBversion);
8751 }
8752
8753 $DBversion = "3.17.00.019";
8754 if ( CheckVersion($DBversion) ) {
8755     $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')"
8756     );
8757     print "Upgrade to $DBversion done (Bug 6149: Operator highlighted in search results)\n";
8758     SetVersion($DBversion);
8759 }
8760
8761 $DBversion = "3.17.00.020";
8762 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
8763     $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')");
8764     print "Upgrade to $DBversion done (Bug 8735 - Expire holds waiting only on days the library is open)\n";
8765     SetVersion ($DBversion);
8766 }
8767
8768 $DBversion = "3.17.00.021";
8769 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
8770     my $pref = C4::Context->preference('HomeOrHoldingBranch');
8771     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
8772        VALUES ('StaffSearchResultsDisplayBranch', ?,'homebranch|holdingbranch','Controls the display of the home or holding branch for staff search results','choice')", undef, $pref);
8773     print "Upgrade to $DBversion done (Bug 12582 - Control of branch displayed in search results linked to HomeOrHoldingBranch)\n";
8774     SetVersion ($DBversion);
8775 }
8776
8777 $DBversion = '3.17.00.022';
8778 if ( CheckVersion($DBversion) ) {
8779     my @temp= $dbh->selectrow_array(qq|
8780         SELECT count(*)
8781         FROM marc_subfield_structure
8782         WHERE kohafield='permanent_location' OR kohafield='items.permanent_location'
8783     |);
8784     print "Upgrade to $DBversion done (Bug 7817: Check for permanent_location)\n";
8785     if( $temp[0] ) {
8786         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";
8787     }
8788     SetVersion($DBversion);
8789 }
8790
8791 $DBversion = "3.17.00.023";
8792 if ( CheckVersion($DBversion) ) {
8793     $dbh->do(q{
8794         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')
8795     });
8796     print "Upgrade to $DBversion done (Bug 11169 - Add AcqItemSetSubfieldsWhenReceiptIsCancelled syspref)\n";
8797     SetVersion($DBversion);
8798 }
8799
8800 $DBversion = "3.17.00.024";
8801 if(CheckVersion($DBversion)) {
8802     $dbh->do(q{
8803         ALTER TABLE issues ADD auto_renew BOOLEAN default FALSE AFTER renewals
8804     });
8805     $dbh->do(q{
8806         ALTER TABLE old_issues ADD auto_renew BOOLEAN default FALSE AFTER renewals
8807     });
8808     $dbh->do(q{
8809         ALTER TABLE issuingrules ADD auto_renew BOOLEAN default FALSE AFTER norenewalbefore
8810     });
8811     print "Upgrade to $DBversion done (Bug 11577: [ENH] Automatic renewal feature)\n";
8812     SetVersion($DBversion);
8813 }
8814
8815 $DBversion = '3.17.00.025';
8816 if ( CheckVersion($DBversion) ) {
8817     $dbh->do(qq{
8818         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')
8819     });
8820     print "Upgrade to $DBversion done (Bug 12728: Checked syspref StatisticsFields)\n";
8821 }
8822
8823 $DBversion = "3.17.00.026";
8824 if ( CheckVersion($DBversion) ) {
8825     if ( C4::Context->preference('marcflavour') eq 'MARC21' ) {
8826         $dbh->do("UPDATE marc_subfield_structure SET liblibrarian = 'Encoded bitrate', libopac = 'Encoded bitrate' WHERE tagfield = '347' AND tagsubfield = 'f'");
8827         $dbh->do("UPDATE marc_subfield_structure SET repeatable = 1 WHERE tagfield IN ('110','111','610','611','710','711','810','811') AND tagsubfield = 'c'");
8828         $dbh->do("UPDATE auth_subfield_structure SET repeatable = 1 WHERE tagfield IN ('110','111','410','411','510','511','710','711') AND tagsubfield = 'c'");
8829         print "Upgrade to $DBversion done (Bug 12435 - Update MARC21 frameworks to Update No. 18 (April 2014))\n";
8830     }
8831     SetVersion($DBversion);
8832 }
8833
8834 $DBversion = "3.17.00.027";
8835 if ( CheckVersion($DBversion) ) {
8836     $dbh->do(q{
8837         DELETE FROM systempreferences WHERE variable = 'SearchEngine'
8838     });
8839     print "Upgrade to $DBversion done (Bug 12538 - Remove SearchEngine syspref)\n";
8840     SetVersion($DBversion);
8841 }
8842
8843 $DBversion = "3.17.00.028";
8844 if ( CheckVersion($DBversion) ) {
8845     $dbh->do(q{
8846         INSERT INTO systempreferences (variable,value) VALUES('OpacCustomSearch','');
8847     });
8848     print "Upgrade to $DBversion done (Bug 12296 - search box replaceable with a system preference)\n";
8849     SetVersion($DBversion);
8850 }
8851
8852 $DBversion = "3.17.00.029";
8853 if ( CheckVersion($DBversion) ) {
8854     $dbh->do("ALTER TABLE  `items` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8855     $dbh->do("ALTER TABLE  `deleteditems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8856     $dbh->do("ALTER TABLE  `biblioitems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8857     $dbh->do("ALTER TABLE  `deletedbiblioitems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8858     print "Upgrade to $DBversion done (Bug 12424 - ddc sorting of call numbers truncates long Cutter parts)\n";
8859     SetVersion ($DBversion);
8860 }
8861
8862 $DBversion = "3.17.00.030";
8863 if ( CheckVersion($DBversion) ) {
8864     $dbh->do(
8865         q{
8866        INSERT INTO systempreferences (variable, value, options, explanation, type )
8867        VALUES
8868         ('UsageStatsCountry', '', NULL, 'The country where your library is located, to be shown on the Hea Koha community website', 'YesNo'),
8869         ('UsageStatsID', '', NULL, 'This preference is part of Koha but it should not be deleted or updated manually.',  'Free'),
8870         ('UsageStatsLastUpdateTime', '', NULL, 'This preference is part of Koha but it should not be deleted or updated manually.', 'Free'),
8871         ('UsageStatsLibraryName', '', NULL, 'The library name to be shown on Hea Koha community website', 'Free'),
8872         ('UsageStatsLibraryType', 'public', 'public|university', 'The library type to be shown on the Hea Koha community website', 'Choice'),
8873         ('UsageStatsLibraryUrl', '', NULL, 'The library URL to be shown on Hea Koha community website', 'Free'),
8874         ('UsageStats', 0, NULL, 'Share anonymous usage data on the Hea Koha community website.', 'YesNo')
8875     });
8876     print "Upgrade to $DBversion done (Bug 11926: Add UsageStats systempreferences (HEA))\n";
8877     SetVersion ($DBversion);
8878 }
8879
8880 $DBversion = "3.17.00.031";
8881 if ( CheckVersion($DBversion) ) {
8882    $dbh->do("ALTER TABLE saved_sql CHANGE report_name report_name VARCHAR( 255 ) NOT NULL DEFAULT '' ");
8883    print "Upgrade to $DBversion done (Bug 2969: Report Name should be mandatory for saved reports)\n";
8884    SetVersion ($DBversion);
8885 }
8886
8887 $DBversion = "3.17.00.032";
8888 if ( CheckVersion($DBversion) ) {
8889     $dbh->do(
8890 "INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('ReplytoDefault',  '',  NULL,  'The default email address to be set as replyto.',  'Free')"
8891     );
8892     $dbh->do(
8893 "INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('ReturnpathDefault',  '',  NULL,  'The default email address to be set as return-path',  'Free')"
8894     );
8895     $dbh->do("ALTER TABLE branches ADD branchreplyto mediumtext AFTER branchemail");
8896     $dbh->do("ALTER TABLE branches ADD branchreturnpath mediumtext AFTER branchreplyto");
8897     print "Upgrade to $DBversion done (Bug 9530: Adding replyto and returnpath addresses.)\n";
8898     SetVersion($DBversion);
8899 }
8900
8901 $DBversion = "3.17.00.033";
8902 if ( CheckVersion($DBversion) ) {
8903     $dbh->do(q{
8904         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
8905         VALUES('FacetMaxCount', '20','Specify the max facet count for each category',NULL,'Integer')
8906     });
8907     print "Upgrade to $DBversion done (Bug 13088 - Allow the user to specify a max amount of facets to show)\n";
8908     SetVersion($DBversion);
8909 }
8910
8911 $DBversion = "3.17.00.034";
8912 if ( CheckVersion($DBversion) ) {
8913     $dbh->do(q|
8914         ALTER TABLE aqorders DROP COLUMN cancelledby;
8915     |);
8916
8917     print "Upgrade to $DBversion done (Bug 11007 - DROP column aqorders.cancelledby)\n";
8918     SetVersion($DBversion);
8919 }
8920
8921 $DBversion = "3.17.00.035";
8922 if ( CheckVersion($DBversion) ) {
8923     $dbh->do(q|
8924         ALTER TABLE serial ADD COLUMN claims_count INT(11) DEFAULT 0 after claimdate
8925     |);
8926     $dbh->do(q|
8927         UPDATE serial
8928         SET claims_count = 1
8929         WHERE claimdate IS NOT NULL
8930     |);
8931     print "Upgrade to $DBversion done (Bug 5342: Add claims_count field in serial table)\n";
8932     SetVersion($DBversion);
8933 }
8934
8935 $DBversion = "3.17.00.036";
8936 if ( CheckVersion($DBversion) ) {
8937     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacShowLibrariesPulldownMobile'");
8938     print "Upgrade to $DBversion done ( Bug 12513 - PROG/CCSR deprecation: Remove OpacShowLibrariesPulldownMobile system preference )\n";
8939     SetVersion ($DBversion);
8940 }
8941
8942 $DBversion = "3.17.00.037";
8943 if ( CheckVersion($DBversion) ) {
8944     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacMainUserBlockMobile'");
8945     print "Upgrade to $DBversion done ( Bug 12246 - PROG/CCSR deprecation: Remove OpacMainUserBlockMobile system preference )\n";
8946     SetVersion ($DBversion);
8947 }
8948
8949 $DBversion = "3.17.00.038";
8950 if ( CheckVersion($DBversion) ) {
8951     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACMobileUserCSS'");
8952     print "Upgrade to $DBversion done ( Bug 12245 - PROG/CCSR deprecation: Remove OPACMobileUserCSS system preference )\n";
8953     SetVersion ($DBversion);
8954 }
8955
8956 $DBversion = "3.17.00.039";
8957 if ( CheckVersion($DBversion) ) {
8958     $dbh->do("INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES
8959     ('OPACFallback', 'prog', 'bootstrap|prog', 'Define the fallback theme for the OPAC interface.', 'Themes')");
8960     print "Upgrade to $DBversion done (Bug 12539 - PROG/CCSR deprecation: Remove hardcoded theme from C4/Templates.pm)\n";
8961     SetVersion ($DBversion);
8962 }
8963
8964 $DBversion = "3.17.00.040";
8965 if ( CheckVersion($DBversion) ) {
8966     my $opac_theme = C4::Context->preference( 'opacthemes' );
8967     if ( !defined $opac_theme || $opac_theme eq 'prog' || $opac_theme eq 'ccsr' ) {
8968         $dbh->do("UPDATE systempreferences SET value='bootstrap' WHERE variable='opacthemes'");
8969     }
8970     print "Upgrade to $DBversion done (Bug 12223: 'prog' and 'ccsr' themes removed)\n";
8971     SetVersion($DBversion);
8972 }
8973
8974 $DBversion = "3.17.00.041";
8975 if ( CheckVersion($DBversion) ) {
8976     print "Upgrade to $DBversion done (Bug 11346: Deprecate the 'prog' and 'CCSR' themes)\n";
8977     SetVersion($DBversion);
8978 }
8979
8980 $DBversion = "3.17.00.042";
8981 if ( CheckVersion($DBversion) ) {
8982     $dbh->do("DELETE FROM systempreferences WHERE variable='yuipath'");
8983     print "Upgrade to $DBversion done (Bug 12494: Remove yuipath system preference)\n";
8984     SetVersion ($DBversion);
8985 }
8986
8987 $DBversion = "3.17.00.043";
8988 if ( CheckVersion($DBversion) ) {
8989     $dbh->do("
8990         ALTER TABLE aqorders
8991         ADD COLUMN cancellationreason TEXT DEFAULT NULL AFTER datecancellationprinted
8992     ");
8993     print "Upgrade to $DBversion done (Bug 7162: Add aqorders.cancellationreason)\n";
8994     SetVersion ($DBversion);
8995 }
8996
8997 $DBversion = "3.17.00.044";
8998 if ( CheckVersion($DBversion) ) {
8999     $dbh->do(q{
9000         INSERT IGNORE INTO systempreferences
9001             (variable,value,explanation,options,type)
9002             VALUES('OnSiteCheckouts','0','Enable/Disable the on-site checkouts feature','','YesNo');
9003     });
9004     $dbh->do(q{
9005         INSERT IGNORE INTO systempreferences
9006             (variable,value,explanation,options,type)
9007             VALUES('OnSiteCheckoutsForce','0','Enable/Disable the on-site for all cases (Even if a user is debarred, etc.)','','YesNo');
9008     });
9009     $dbh->do(q{
9010         ALTER TABLE issues ADD COLUMN onsite_checkout INT(1) NOT NULL DEFAULT 0 AFTER issuedate;
9011     });
9012     $dbh->do(q{
9013         ALTER TABLE old_issues ADD COLUMN onsite_checkout INT(1) NOT NULL DEFAULT 0 AFTER issuedate;
9014     });
9015     print "Upgrade to $DBversion done (Bug 10860: Add new system preference OnSiteCheckouts + fields [old_]issues.onsite_checkout)\n";
9016     SetVersion($DBversion);
9017 }
9018
9019 $DBversion = "3.17.00.045";
9020 if ( CheckVersion($DBversion) ) {
9021     $dbh->do(q{
9022         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
9023         ('LocalHoldsPriority',  '0', NULL,  'Enables the LocalHoldsPriority feature',  'YesNo'),
9024         ('LocalHoldsPriorityItemControl',  'holdingbranch',  'holdingbranch|homebranch',  'decides if the feature operates using the item''s home or holding library.',  'Choice'),
9025         ('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')
9026     });
9027     print "Upgrade to $DBversion done (Bug 11126 - Make the holds system optionally give precedence to local holds)\n";
9028     SetVersion($DBversion);
9029 }
9030
9031 $DBversion = "3.17.00.046";
9032 if ( CheckVersion($DBversion) ) {
9033     $dbh->do(q{
9034         CREATE TABLE IF NOT EXISTS items_search_fields (
9035           name VARCHAR(255) NOT NULL,
9036           label VARCHAR(255) NOT NULL,
9037           tagfield CHAR(3) NOT NULL,
9038           tagsubfield CHAR(1) NULL DEFAULT NULL,
9039           authorised_values_category VARCHAR(16) NULL DEFAULT NULL,
9040           PRIMARY KEY(name),
9041           CONSTRAINT items_search_fields_authorised_values_category
9042             FOREIGN KEY (authorised_values_category) REFERENCES authorised_values (category)
9043             ON DELETE SET NULL ON UPDATE CASCADE
9044         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
9045     });
9046     print "Upgrade to $DBversion done (Bug 11425: Add items_search_fields table)\n";
9047     SetVersion($DBversion);
9048 }
9049
9050 $DBversion = "3.17.00.047";
9051 if ( CheckVersion($DBversion) ) {
9052     $dbh->do(q{
9053         ALTER TABLE collections
9054             CHANGE colBranchcode colBranchcode VARCHAR( 10 ) NULL DEFAULT NULL,
9055             ADD INDEX ( colBranchcode ),
9056             ADD CONSTRAINT collections_ibfk_1 FOREIGN KEY (colBranchcode) REFERENCES branches (branchcode) ON DELETE CASCADE ON UPDATE CASCADE
9057     });
9058     print "Upgrade to $DBversion done (Bug 8836 - Resurrect Rotating Collections)\n";
9059     SetVersion($DBversion);
9060 }
9061
9062 $DBversion = "3.17.00.048";
9063 if ( CheckVersion($DBversion) ) {
9064     $dbh->do(q|
9065         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')
9066     |);
9067     print "Upgrade to $DBversion done (Bug 12448 - Add RentalFeesCheckoutConfirmation syspref)\n";
9068     SetVersion($DBversion);
9069 }
9070
9071 $DBversion = "3.17.00.049";
9072 if ( CheckVersion($DBversion) ) {
9073     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'am', 'language', 'Amharic','2014-10-29')");
9074     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'am','amh')");
9075     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'am', 'language', 'am', 'አማርኛ')");
9076     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'am', 'language', 'en', 'Amharic')");
9077
9078     $dbh->do("UPDATE language_descriptions SET description = 'لعربية' WHERE subtag = 'ar' AND type = 'language' AND lang = 'ar'");
9079
9080     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'az', 'language', 'Azerbaijani','2014-10-30')");
9081     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'az','aze')");
9082     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'az', 'language', 'az', 'Azərbaycan dili')");
9083     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'az', 'language', 'en', 'Azerbaijani')");
9084
9085     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'be', 'language', 'Byelorussian','2014-10-30')");
9086     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'be','bel')");
9087     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'be', 'language', 'be', 'Беларуская мова')");
9088     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'be', 'language', 'en', 'Byelorussian')");
9089
9090     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'bn', 'language', 'Bengali','2014-10-30')");
9091     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'bn','ben')");
9092     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'bn', 'language', 'bn', 'বাংলা')");
9093     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'bn', 'language', 'en', 'Bengali')");
9094
9095     $dbh->do("UPDATE language_descriptions SET description = 'Български' WHERE subtag = 'bg' AND type = 'language' AND lang = 'bg'");
9096     $dbh->do("UPDATE language_descriptions SET description = 'Ceština' WHERE subtag = 'cs' AND type = 'language' AND lang = 'cs'");
9097     $dbh->do("UPDATE language_descriptions SET description = 'Ελληνικά' WHERE subtag = 'el' AND type = 'language' AND lang = 'el'");
9098     $dbh->do("UPDATE language_descriptions SET description = 'Español' WHERE subtag = 'es' AND type = 'language' AND lang = 'es'");
9099
9100     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'eu', 'language', 'Basque','2014-10-30')");
9101     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'eu','eus')");
9102     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'eu', 'language', 'eu', 'Euskera')");
9103     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'eu', 'language', 'en', 'Basque')");
9104
9105     $dbh->do("UPDATE language_descriptions SET description = 'فارسى' WHERE subtag = 'fa' AND type = 'language' AND lang = 'fa'");
9106     $dbh->do("UPDATE language_descriptions SET description = 'Suomi' WHERE subtag = 'fi' AND type = 'language' AND lang = 'fi'");
9107
9108     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'fo', 'language', 'Faroese','2014-10-30')");
9109     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'fo','fao')");
9110     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'fo', 'language', 'fo', 'Føroyskt')");
9111     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'fo', 'language', 'en', 'Faroese')");
9112
9113     $dbh->do("UPDATE language_descriptions SET description = 'Français' WHERE subtag = 'fr' AND type = 'language' AND lang = 'fr'");
9114     $dbh->do("UPDATE language_descriptions SET description = 'עִבְרִית' WHERE subtag = 'he' AND type = 'language' AND lang = 'he'");
9115     $dbh->do("UPDATE language_descriptions SET description = 'हिन्दी' WHERE subtag = 'hi' AND type = 'language' AND lang = 'hi'");
9116
9117     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'is', 'language', 'Icelandic','2014-10-30')");
9118     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'is','ice')");
9119     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'is', 'language', 'is', 'Íslenska')");
9120     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'is', 'language', 'en', 'Icelandic')");
9121
9122     $dbh->do("UPDATE language_descriptions SET description = '日本語' WHERE subtag = 'ja' AND type = 'language' AND lang = 'ja'");
9123
9124     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ka', 'language', 'Kannada','2014-10-30')");
9125     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ka','kan')");
9126     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'ka', 'ಕನ್ನಡ')");
9127     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'en', 'Kannada')");
9128
9129     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'km', 'language', 'Khmer','2014-10-30')");
9130     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'km','khm')");
9131     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'km', 'language', 'km', 'ភាសាខ្មែរ')");
9132     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'km', 'language', 'en', 'Khmer')");
9133
9134     $dbh->do("UPDATE language_descriptions SET description = '한국어' WHERE subtag = 'ko' AND type = 'language' AND lang = 'ko'");
9135
9136     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ku', 'language', 'Kurdish','2014-05-13')");
9137     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ku','kur')");
9138     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'ku', 'کوردی')");
9139     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'en', 'Kurdish')");
9140     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'fr', 'Kurde')");
9141     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'de', 'Kurdisch')");
9142     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'es', 'Kurdo')");
9143
9144     $dbh->do("UPDATE language_descriptions SET description = 'ພາສາລາວ' WHERE subtag = 'lo' AND type = 'language' AND lang = 'lo'");
9145
9146     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mi', 'language', 'Maori','2014-10-30')");
9147     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mi','mri')");
9148     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mi', 'language', 'mi', 'Te Reo Māori')");
9149     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mi', 'language', 'en', 'Maori')");
9150
9151     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mn', 'language', 'Mongolian','2014-10-30')");
9152     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mn','mon')");
9153     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mn', 'language', 'mn', 'Mонгол')");
9154     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mn', 'language', 'en', 'Mongolian')");
9155
9156     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mr', 'language', 'Marathi','2014-10-30')");
9157     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mr','mar')");
9158     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mr', 'language', 'mr', 'मराठी')");
9159     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mr', 'language', 'en', 'Marathi')");
9160
9161     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ms', 'language', 'Malay','2014-10-30')");
9162     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ms','may')");
9163     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ms', 'language', 'ms', 'Bahasa melayu')");
9164     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ms', 'language', 'en', 'Malay')");
9165
9166     $dbh->do("UPDATE language_descriptions SET description = 'Norsk bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'nb'");
9167     $dbh->do("UPDATE language_descriptions SET description = 'Norwegian bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'en'");
9168     $dbh->do("UPDATE language_descriptions SET description = 'Norvégien bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'fr'");
9169     $dbh->do("UPDATE language_descriptions SET description = 'Norwegisch bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'de'");
9170
9171     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ne', 'language', 'Nepali','2014-10-30')");
9172     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ne','nep')");
9173     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)VALUES ( 'ne', 'language', 'ne', 'नेपाली')");
9174     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ne', 'language', 'en', 'Nepali')");
9175
9176     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'pbr', 'language', 'Pangwa','2014-10-30')");
9177     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'pbr','pbr')");
9178     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'pbr', 'language', 'pbr', 'Ekipangwa')");
9179     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'pbr', 'language', 'en', 'Pangwa')");
9180
9181     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'prs', 'language', 'Dari','2014-10-30')");
9182     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'prs','prs')");
9183     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'prs', 'language', 'prs', 'درى')");
9184     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'prs', 'language', 'en', 'Dari')");
9185
9186     $dbh->do("UPDATE language_descriptions SET description = 'Português' WHERE subtag = 'pt' AND type = 'language' AND lang = 'pt'");
9187     $dbh->do("UPDATE language_descriptions SET description = 'Român' WHERE subtag = 'ro' AND type = 'language' AND lang = 'ro'");
9188     $dbh->do("UPDATE language_descriptions SET description = 'Русский' WHERE subtag = 'ru' AND type = 'language' AND lang = 'ru'");
9189
9190     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'rw', 'language', 'Kinyarwanda','2014-10-30')");
9191     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'rw','kin')");
9192     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'rw', 'language', 'rw', 'Ikinyarwanda')");
9193     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'rw', 'language', 'en', 'Kinyarwanda')");
9194
9195     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sd', 'language', 'Sindhi','2014-10-30')");
9196     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sd','snd')");
9197     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sd', 'language', 'sd', 'سنڌي')");
9198     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sd', 'language', 'en', 'Sindhi')");
9199
9200     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sk', 'language', 'Slovak','2014-10-30')");
9201     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sk','slk')");
9202     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sk', 'language', 'sk', 'Slovenčina')");
9203     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sk', 'language', 'en', 'Slovak')");
9204
9205     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sl', 'language', 'Slovene','2014-10-30')");
9206     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sl','slv')");
9207     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sl', 'language', 'sl', 'Slovenščina')");
9208     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sl', 'language', 'en', 'Slovene')");
9209
9210     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sq', 'language', 'Albanian','2014-10-30')");
9211     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sq','sqi')");
9212     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sq', 'language', 'sq', 'Shqip')");
9213     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sq', 'language', 'en', 'Albanian')");
9214
9215     $dbh->do("UPDATE language_descriptions SET description = 'Cрпски' WHERE subtag = 'sr' AND type = 'language' AND lang = 'sr'");
9216
9217     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sw', 'language', 'Swahili','2014-10-30')");
9218     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sw','swa')");
9219     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sw', 'language', 'sw', 'Kiswahili')");
9220     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sw', 'language', 'en', 'Swahili')");
9221
9222     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ta', 'language', 'Tamil','2014-10-30')");
9223     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ta','tam')");
9224     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ta', 'language', 'ta', 'தமிழ்')");
9225     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ta', 'language', 'en', 'Tamil')");
9226
9227     $dbh->do("UPDATE language_descriptions SET description = 'Tetun' WHERE subtag = 'tet' AND type = 'language' AND lang = 'tet'");
9228     $dbh->do("UPDATE language_descriptions SET description = 'ภาษาไทย' WHERE subtag = 'th' AND type = 'language' AND lang = 'th'");
9229
9230     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'tl', 'language', 'Tagalog','2014-10-30')");
9231     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'tl','tgl')");
9232     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'tl', 'language', 'tl', 'Tagalog')");
9233     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'tl', 'language', 'en', 'Tagalog')");
9234
9235     $dbh->do("UPDATE language_descriptions SET description = 'Türkçe' WHERE subtag = 'tr' AND type = 'language' AND lang = 'tr'");
9236     $dbh->do("UPDATE language_descriptions SET description = 'Українська' WHERE subtag = 'uk' AND type = 'language' AND lang = 'uk'");
9237     $dbh->do("UPDATE language_descriptions SET description = 'اردو' WHERE subtag = 'ur' AND type = 'language' AND lang = 'ur'");
9238
9239     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'vi', 'language', 'Vietnamese','2014-10-30')");
9240     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'vi','vie')");
9241     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'vi', 'language', 'vi', '㗂越')");
9242     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'vi', 'language', 'en', 'Vietnamese')");
9243
9244     $dbh->do("UPDATE language_descriptions SET description = '中文' WHERE subtag = 'zh' AND type = 'language' AND lang = 'zh'");
9245     $dbh->do("UPDATE language_descriptions SET description = '' WHERE subtag = 'Arab,script' AND type = 'Arab' AND lang = 'العربية'");
9246
9247     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Armn', 'script', 'Armenian','2014-10-30')");
9248     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Armn', 'script', 'Armn', 'Հայոց այբուբեն')");
9249     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Armn', 'script', 'en', 'Armenian')");
9250
9251     $dbh->do("UPDATE language_descriptions SET description = 'Кирилица' WHERE subtag = 'Cyrl' AND type = 'script' AND lang = 'Cyrl'");
9252
9253     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Ethi', 'script', 'Ethiopic','2014-10-30')");
9254     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Ethi', 'script', 'Ethi', 'ግዕዝ')");
9255     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Ethi', 'script', 'en', 'Ethiopic')");
9256
9257     $dbh->do("UPDATE language_descriptions SET description = 'Ελληνικό αλφάβητο' WHERE subtag = 'Grek' AND type = 'script' AND lang = 'Grek'");
9258     $dbh->do("UPDATE language_descriptions SET description = '简体字' WHERE subtag = 'Hans' AND type = 'script' AND lang = 'Hans'");
9259     $dbh->do("UPDATE language_descriptions SET description = '繁體字' WHERE subtag = 'Hant' AND type = 'script' AND lang = 'Hant'");
9260     $dbh->do("UPDATE language_descriptions SET description = 'אָלֶף־בֵּית עִבְרִי' WHERE subtag = 'Hebr' AND type = 'script' AND lang = 'Hebr'");
9261
9262     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Jpan', 'script', 'Japanese','2014-10-30')");
9263     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Jpan', 'script', 'Jpan', '漢字')");
9264     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Jpan', 'script', 'en', 'Japanese')");
9265
9266     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Knda', 'script', 'Kannada','2014-10-30')");
9267     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Knda', 'script', 'Knda', 'ಕನ್ನಡ ಲಿಪಿ')");
9268     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Knda', 'script', 'en', 'Kannada')");
9269
9270     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Kore', 'script', 'Korean','2014-10-30')");
9271     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Kore', 'script', 'Kore', '한글')");
9272     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Kore', 'script', 'en', 'Korean')");
9273
9274     $dbh->do("UPDATE language_descriptions SET description = 'ອັກສອນລາວ' WHERE subtag = 'Laoo' AND type = 'script' AND lang = 'Laoo'");
9275
9276     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'AL', 'region', 'Albania','2014-10-30')");
9277     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AL', 'region', 'en', 'Albania')");
9278     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AL', 'region', 'sq', 'Shqipërisë')");
9279
9280     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'AZ', 'region', 'Azerbaijan','2014-10-30')");
9281     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AZ', 'region', 'en', 'Azerbaijan')");
9282     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AZ', 'region', 'az', 'Azərbaycan')");
9283
9284     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BE', 'region', 'Belgium','2014-10-30')");
9285     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BE', 'region', 'en', 'Belgium')");
9286     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BE', 'region', 'nl', 'België')");
9287
9288     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BR', 'region', 'Brazil','2014-10-30')");
9289     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BR', 'region', 'en', 'Brazil')");
9290     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BR', 'region', 'pt', 'Brasil')");
9291
9292     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BY', 'region', 'Belarus','2014-10-30')");
9293     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BY', 'region', 'en', 'Belarus')");
9294     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BY', 'region', 'be', 'Беларусь')");
9295
9296     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CA', 'region', 'fr', 'Canada')");
9297
9298     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CH', 'region', 'Switzerland','2014-10-30')");
9299     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CH', 'region', 'en', 'Switzerland')");
9300     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CH', 'region', 'de', 'Schweiz')");
9301
9302     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CN', 'region', 'China','2014-10-30')");
9303     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CN', 'region', 'en', 'China')");
9304     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CN', 'region', 'zh', '中国')");
9305
9306     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CZ', 'region', 'Czech Republic','2014-10-30')");
9307     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CZ', 'region', 'en', 'Czech Republic')");
9308     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CZ', 'region', 'cs', 'Česká republika')");
9309
9310     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'DE', 'region', 'Germany','2014-10-30')");
9311     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DE', 'region', 'en', 'Germany')");
9312     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DE', 'region', 'de', 'Deutschland')");
9313
9314     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DK', 'region', 'en', 'Denmark')");
9315
9316     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ES', 'region', 'Spain','2014-10-30')");
9317     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ES', 'region', 'en', 'Spain')");
9318     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ES', 'region', 'es', 'España')");
9319
9320     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'FI', 'region', 'Finland','2014-10-30')");
9321     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FI', 'region', 'en', 'Finland')");
9322     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FI', 'region', 'fi', 'Suomi')");
9323
9324     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'FO', 'region', 'Faroe Islands','2014-10-30')");
9325     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FO', 'region', 'en', 'Faroe Islands')");
9326     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FO', 'region', 'fo', 'Føroyar')");
9327
9328     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'GR', 'region', 'Greece','2014-10-30')");
9329     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'GR', 'region', 'en', 'Greece')");
9330     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'GR', 'region', 'el', 'Ελλάδα')");
9331
9332     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'HR', 'region', 'Croatia','2014-10-30')");
9333     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HR', 'region', 'en', 'Croatia')");
9334     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HR', 'region', 'hr', 'Hrvatska')");
9335
9336     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'HU', 'region', 'Hungary','2014-10-30')");
9337     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HU', 'region', 'en', 'Hungary')");
9338     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HU', 'region', 'hu', 'Magyarország')");
9339
9340     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ID', 'region', 'Indonesia','2014-10-30')");
9341     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ID', 'region', 'en', 'Indonesia')");
9342     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ID', 'region', 'id', 'Indonesia')");
9343
9344     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'IS', 'region', 'Iceland','2014-10-30')");
9345     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IS', 'region', 'en', 'Iceland')");
9346     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IS', 'region', 'is', 'Ísland')");
9347
9348     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'IT', 'region', 'Italy','2014-10-30')");
9349     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IT', 'region', 'en', 'Italy')");
9350     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IT', 'region', 'it', 'Italia')");
9351
9352     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'JP', 'region', 'Japan','2014-10-30')");
9353     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'JP', 'region', 'en', 'Japan')");
9354     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'JP', 'region', 'ja', '日本')");
9355
9356     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KE', 'region', 'Kenya','2014-10-30')");
9357     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KE', 'region', 'en', 'Kenya')");
9358     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KE', 'region', 'rw', 'Kenya')");
9359
9360     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KH', 'region', 'Cambodia','2014-10-30')");
9361     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KH', 'region', 'en', 'Cambodia')");
9362     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KH', 'region', 'km', 'កម្ពុជា')");
9363
9364     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KP', 'region', 'North Korea','2014-10-30')");
9365     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KP', 'region', 'en', 'North Korea')");
9366     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KP', 'region', 'ko', '조선민주주의인민공화국')");
9367
9368     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'LK', 'region', 'Sri Lanka','2014-10-30')");
9369     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'LK', 'region', 'en', 'Sri Lanka')");
9370     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'LK', 'region', 'ta', 'இலங்கை')");
9371
9372     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'MY', 'region', 'Malaysia','2014-10-30')");
9373     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'MY', 'region', 'en', 'Malaysia')");
9374     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'MY', 'region', 'ms', 'Malaysia')");
9375
9376     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NE', 'region', 'Niger','2014-10-30')");
9377     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NE', 'region', 'en', 'Niger')");
9378     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NE', 'region', 'ne', 'Niger')");
9379
9380     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NL', 'region', 'Netherlands','2014-10-30')");
9381     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NL', 'region', 'en', 'Netherlands')");
9382     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NL', 'region', 'nl', 'Nederland')");
9383
9384     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NO', 'region', 'Norway','2014-10-30')");
9385     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'en', 'Norway')");
9386     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'ne', 'Noreg')");
9387     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'nn', 'Noreg')");
9388
9389     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PH', 'region', 'Philippines','2014-10-30')");
9390     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PH', 'region', 'en', 'Philippines')");
9391     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PH', 'region', 'tl', 'Pilipinas')");
9392
9393     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PK', 'region', 'Pakistan','2014-10-30')");
9394     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PK', 'region', 'en', 'Pakistan')");
9395     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PK', 'region', 'sd', 'پاكستان')");
9396
9397     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PL', 'region', 'Poland','2014-10-30')");
9398     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PL', 'region', 'en', 'Poland')");
9399     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PL', 'region', 'pl', 'Polska')");
9400
9401     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PT', 'region', 'Portugal','2014-10-30')");
9402     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PT', 'region', 'en', 'Portugal')");
9403     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PT', 'region', 'pt', 'Portugal')");
9404
9405     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RO', 'region', 'Romania','2014-10-30')");
9406     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RO', 'region', 'en', 'Romania')");
9407     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RO', 'region', 'ro', 'România')");
9408
9409     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RU', 'region', 'Russia','2014-10-30')");
9410     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RU', 'region', 'en', 'Russia')");
9411     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RU', 'region', 'ru', 'Россия')");
9412
9413     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RW', 'region', 'Rwanda','2014-10-30')");
9414     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RW', 'region', 'en', 'Rwanda')");
9415     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RW', 'region', 'rw', 'Rwanda')");
9416
9417     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SE', 'region', 'Sweden','2014-10-30')");
9418     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SE', 'region', 'en', 'Sweden')");
9419     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SE', 'region', 'sv', 'Sverige')");
9420
9421     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SI', 'region', 'Slovenia','2014-10-30')");
9422     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SI', 'region', 'en', 'Slovenia')");
9423     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SI', 'region', 'sl', 'Slovenija')");
9424
9425     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SK', 'region', 'Slovakia','2014-10-30')");
9426     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SK', 'region', 'en', 'Slovakia')");
9427     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SK', 'region', 'sk', 'Slovensko')");
9428
9429     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TH', 'region', 'Thailand','2014-10-30')");
9430     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TH', 'region', 'en', 'Thailand')");
9431     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TH', 'region', 'th', 'ประเทศไทย')");
9432
9433     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TR', 'region', 'Turkey','2014-10-30')");
9434     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TR', 'region', 'en', 'Turkey')");
9435     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TR', 'region', 'tr', 'Türkiye')");
9436
9437     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TW', 'region', 'Taiwan','2014-10-30')");
9438     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TW', 'region', 'en', 'Taiwan')");
9439     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TW', 'region', 'zh', '台灣')");
9440
9441     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'UA', 'region', 'Ukraine','2014-10-30')");
9442     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'UA', 'region', 'en', 'Ukraine')");
9443     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'UA', 'region', 'uk', 'Україна')");
9444
9445     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'VN', 'region', 'Vietnam','2014-10-30')");
9446     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'VN', 'region', 'en', 'Vietnam')");
9447     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'VN', 'region', 'vi', 'Việt Nam')");
9448
9449     print "Upgrade to $DBversion done (Bug 12250: Update descriptions for languages, scripts and regions)\n";
9450     SetVersion($DBversion);
9451 }
9452
9453 $DBversion = "3.17.00.050";
9454 if ( CheckVersion($DBversion) ) {
9455     $dbh->do(q|
9456         INSERT INTO permissions (module_bit, code, description) VALUES
9457           (13, 'records_batchdel', 'Perform batch deletion of records (bibliographic or authority)')
9458     |);
9459     print "Upgrade to $DBversion done (Bug 12403: Add permission tools_records_batchdelitem)\n";
9460     SetVersion($DBversion);
9461 }
9462
9463 $DBversion = "3.17.00.051";
9464 if ( CheckVersion($DBversion) ) {
9465     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('GoogleIndicTransliteration','0','','GoogleIndicTransliteration on the OPAC.','YesNo')");
9466     print "Upgrade to $DBversion done (Bug 13211: Added system preferences GoogleIndicTransliteration on the OPAC)\n";
9467     SetVersion($DBversion);
9468 }
9469
9470 $DBversion = "3.17.00.052";
9471 if ( CheckVersion($DBversion) ) {
9472     $dbh->do(q{
9473         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');
9474     });
9475
9476     $dbh->do(q{
9477         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');
9478    });
9479    print "Upgrade to $DBversion done (Bug 9043: Add system preference OpacAdvSearchOptions and OpacAdvSearchMoreOptions)\n";
9480    SetVersion ($DBversion);
9481 }
9482
9483 $DBversion = "3.17.00.053";
9484 if ( CheckVersion($DBversion) ) {
9485     $dbh->do(q{
9486         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)');
9487     });
9488
9489     $dbh->do(q{
9490         INSERT INTO permissions (module_bit, code, description) VALUES ('9', 'delete_all_items', 'Delete all items at once');
9491     });
9492
9493     $dbh->do(q{
9494         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)');
9495     });
9496
9497     # The delete_all_items permission should be added to users having the edit_items permission.
9498     $dbh->do(q{
9499         INSERT INTO user_permissions (borrowernumber, module_bit, code) SELECT borrowernumber, module_bit, "delete_all_items" FROM user_permissions WHERE code="edit_items";
9500     });
9501
9502     # Add 2 new prefs
9503     $dbh->do(q{
9504         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');
9505     });
9506
9507     $dbh->do(q{
9508         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');
9509     });
9510
9511     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";
9512     SetVersion($DBversion);
9513 }
9514
9515 $DBversion = "3.17.00.054";
9516 if (CheckVersion($DBversion)) {
9517     $dbh->do(q{
9518         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
9519         ('AllowRenewalIfOtherItemsAvailable','0',NULL,'If enabled, allow a patron to renew an item with unfilled holds if other available items can fill that hold.','YesNo')
9520     });
9521     print "Upgrade to $DBversion done (Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds)\n";
9522     SetVersion($DBversion);
9523 }
9524
9525 $DBversion = "3.17.00.055";
9526 if ( CheckVersion($DBversion) ) {
9527     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBEnable', '0', NULL, 'Enable communication with the Norwegian national patron database.', 'YesNo')");
9528     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBEndpoint', '', NULL, 'Which NL endpoint to use.', 'Free')");
9529     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBUsername', '', NULL, 'Username for communication with the Norwegian national patron database.', 'Free')");
9530     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBPassword', '', NULL, 'Password for communication with the Norwegian national patron database.', 'Free')");
9531     $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')");
9532     $dbh->do("
9533 CREATE TABLE borrower_sync (
9534     borrowersyncid int(11) NOT NULL AUTO_INCREMENT,
9535     borrowernumber int(11) NOT NULL,
9536     synctype varchar(32) NOT NULL,
9537     sync tinyint(1) NOT NULL DEFAULT '0',
9538     syncstatus varchar(10) DEFAULT NULL,
9539     lastsync varchar(50) DEFAULT NULL,
9540     hashed_pin varchar(64) DEFAULT NULL,
9541     PRIMARY KEY (borrowersyncid),
9542     KEY borrowernumber (borrowernumber),
9543     CONSTRAINT borrower_sync_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
9544 ) ENGINE=InnoDB DEFAULT CHARSET=utf8"
9545 );
9546     print "Upgrade to $DBversion done (Bug 11401 - Add support for Norwegian national library card)\n";
9547     SetVersion($DBversion);
9548 }
9549
9550 $DBversion = "3.17.00.056";
9551 if ( CheckVersion($DBversion) ) {
9552     $dbh->do(q{
9553         UPDATE systempreferences SET value = 'pubdate,itemtype,language,sorting,location' WHERE variable='OpacAdvSearchOptions'
9554     });
9555
9556     $dbh->do(q{
9557         UPDATE systempreferences SET value = 'pubdate,itemtype,language,subtype,sorting,location' WHERE variable='OpacAdvSearchMoreOptions'
9558     });
9559
9560     print "Upgrade to $DBversion done (Bug 9043 - Update the values for OpacAdvSearchOptions and OpacAdvSearchOptions)\n";
9561     SetVersion($DBversion);
9562 }
9563
9564 $DBversion = "3.17.00.057";
9565 if ( CheckVersion($DBversion) ) {
9566     print "Upgrade to $DBversion done (Koha 3.18 beta)\n";
9567     SetVersion ($DBversion);
9568 }
9569
9570 $DBversion = "3.17.00.058";
9571 if( CheckVersion($DBversion) ){
9572     $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')");
9573     $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')");
9574     $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')");
9575     print "Upgrade to $DBversion done (Bug 8337: System preferences for longoverdue cron)\n";
9576     SetVersion($DBversion);
9577 }
9578
9579 $DBversion = "3.17.00.059";
9580 if ( CheckVersion($DBversion) ) {
9581     $dbh->do(q{
9582         UPDATE permissions SET description = "Add and delete budgets (but can't modifiy budgets)" WHERE description = "Add and delete budgets (but cant modify budgets)";
9583     });
9584     print "Upgrade to $DBversion done (Bug 10749: Fix typo in budget_add_del permission description)\n";
9585     SetVersion ($DBversion);
9586 }
9587
9588 $DBversion = "3.17.00.060";
9589 if ( CheckVersion($DBversion) ) {
9590     my $count_l = $dbh->selectcol_arrayref(q|
9591         SELECT COUNT(*) FROM letter WHERE message_transport_type='feed'
9592     |);
9593     my $count_mq = $dbh->selectcol_arrayref(q|
9594         SELECT COUNT(*) FROM message_queue WHERE message_transport_type='feed'
9595     |);
9596     my $count_ott = $dbh->selectcol_arrayref(q|
9597         SELECT COUNT(*) FROM overduerules_transport_types WHERE message_transport_type='feed'
9598     |);
9599     my $count_mt = $dbh->selectcol_arrayref(q|
9600         SELECT COUNT(*) FROM message_transports WHERE message_transport_type='feed'
9601     |);
9602     my $count_bmtp = $dbh->selectcol_arrayref(q|
9603         SELECT COUNT(*) FROM borrower_message_transport_preferences WHERE message_transport_type='feed'
9604     |);
9605
9606     my $deleted = 0;
9607     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 ) {
9608         $deleted = $dbh->do(q|
9609             DELETE FROM message_transport_types where message_transport_type='feed'
9610         |);
9611         $deleted = $deleted ne '0E0' ? 1 : 0;
9612     }
9613
9614     print "Upgrade to $DBversion done (Bug 12298: Delete the 'feed' message transport type " . ($deleted ? '(deleted!)' : '(not deleted)') . ")\n";
9615     SetVersion($DBversion);
9616 }
9617
9618 $DBversion = "3.18.00.000";
9619 if ( CheckVersion($DBversion) ) {
9620     print "Upgrade to $DBversion done (3.18.0 release)\n";
9621     SetVersion($DBversion);
9622 }
9623
9624 $DBversion = "3.19.00.000";
9625 if ( CheckVersion($DBversion) ) {
9626     print "Upgrade to $DBversion done (there's life after 3.18)\n";
9627     SetVersion ($DBversion);
9628 }
9629
9630 $DBversion = "3.19.00.001";
9631 if ( CheckVersion($DBversion) ) {
9632     $dbh->do("
9633         UPDATE systempreferences
9634         SET options = 'public|school|academic|research|private|societyAssociation|corporate|government|religiousOrg|subscription'
9635         WHERE variable = 'UsageStatsLibraryType'
9636     ");
9637     if ( C4::Context->preference("UsageStatsLibraryType") eq "university" ) {
9638         C4::Context->set_preference("UsageStatsLibraryType", "academic")
9639     }
9640     print "Upgrade to $DBversion done (Bug 13436: Add more options to UsageStatsLibraryType)\n";
9641     SetVersion ($DBversion);
9642 }
9643
9644 $DBversion = "3.19.00.002";
9645 if ( CheckVersion($DBversion) ) {
9646     $dbh->do(q|
9647         UPDATE suggestions SET branchcode="" WHERE branchcode="__ANY__"
9648     |);
9649     print "upgrade to $DBversion done (Bug 10753: replace __ANY__ with empty string in suggestions.branchcode)\n";
9650     SetVersion ($DBversion);
9651 }
9652
9653 $DBversion = "3.19.00.003";
9654 if ( CheckVersion($DBversion) ) {
9655     my ($count) = $dbh->selectrow_array("SELECT COUNT(*) FROM borrowers GROUP BY userid HAVING COUNT(userid) > 1");
9656
9657     if ( $count ) {
9658         print "Upgrade to $DBversion done (Bug 1861 - Unique patrons logins not (totally) enforced) FAILED!\n";
9659         print "Your database has users with duplicate user logins. Please have your administrator deduplicate your user logins.\n";
9660         print "Afterward, your Koha administrator should execute the following database query: ALTER TABLE borrowers DROP INDEX userid, ADD UNIQUE userid (userid)";
9661     } else {
9662         $dbh->do(q{
9663             ALTER TABLE borrowers
9664                 DROP INDEX userid ,
9665                 ADD UNIQUE userid (userid)
9666         });
9667         print "Upgrade to $DBversion done (Bug 1861 - Unique patrons logins not (totally) enforced)\n";
9668     }
9669
9670     SetVersion($DBversion);
9671 }
9672
9673 $DBversion = "3.19.00.004";
9674 if ( CheckVersion($DBversion) ) {
9675     my $pref_value = C4::Context->preference('OpacExportOptions');
9676     $pref_value =~ s/\|/,/g; # multiple is separated by ,
9677     $dbh->do(q{
9678         UPDATE systempreferences
9679             SET value = ?,
9680                 type = 'multiple'
9681         WHERE variable = 'OpacExportOptions'
9682     }, {}, $pref_value );
9683     print "Upgrade to $DBversion done (Bug 13346: OpacExportOptions is now multiple)\n";
9684     SetVersion ($DBversion);
9685 }
9686
9687 $DBversion = "3.19.00.005";
9688 if(CheckVersion($DBversion)) {
9689     $dbh->do(q{
9690         ALTER TABLE authorised_values MODIFY COLUMN category VARCHAR(32) NOT NULL DEFAULT ''
9691     });
9692
9693     $dbh->do(q{
9694         ALTER TABLE borrower_attribute_types MODIFY COLUMN authorised_value_category VARCHAR(32) DEFAULT NULL
9695     });
9696
9697     print "Upgrade to $DBversion done (Bug 13379 - Modify authorised_values.category to varchar(32))\n";
9698     SetVersion($DBversion);
9699 }
9700
9701 $DBversion = "3.19.00.006";
9702 if ( CheckVersion($DBversion) ) {
9703     $dbh->do(q|SET foreign_key_checks = 0|);
9704     my $sth = $dbh->table_info( '','','','TABLE' );
9705     my ( $cat, $schema, $name, $type, $remarks );
9706     while ( ( $cat, $schema, $name, $type, $remarks ) = $sth->fetchrow_array ) {
9707         my $table_sth = $dbh->prepare(qq|SHOW CREATE TABLE $name|);
9708         $table_sth->execute;
9709         my @table = $table_sth->fetchrow_array;
9710         unless ( $table[1] =~ /COLLATE=utf8mb4_unicode_ci/ ) { #catches utf8mb4 collated tables
9711             $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci|);
9712         }
9713     }
9714     $dbh->do(q|SET foreign_key_checks = 1|);;
9715
9716     print "Upgrade to $DBversion done (Bug 11944 - Convert DB tables to utf8_unicode_ci)\n";
9717     SetVersion($DBversion);
9718 }
9719
9720 $DBversion = "3.19.00.007";
9721 if ( CheckVersion($DBversion) ) {
9722     my $orphan_budgets = $dbh->selectall_arrayref(q|
9723         SELECT budget_id, budget_name, budget_code
9724         FROM aqbudgets
9725         WHERE   budget_parent_id IS NOT NULL
9726             AND budget_parent_id NOT IN (
9727                 SELECT DISTINCT budget_id FROM aqbudgets
9728             )
9729     |, { Slice => {} } );
9730
9731     if ( @$orphan_budgets ) {
9732         for my $b ( @$orphan_budgets ) {
9733             print "Fund $b->{budget_name} (code:$b->{budget_code}, id:$b->{budget_id}) does not have a parent, it may cause problem\n";
9734         }
9735         print "Upgrade to $DBversion done (Bug 12905: Check budget integrity: FAIL)\n";
9736     } else {
9737         print "Upgrade to $DBversion done (Bug 12905: Check budget integrity: OK)\n";
9738     }
9739     SetVersion($DBversion);
9740 }
9741
9742 $DBversion = "3.19.00.008";
9743 if ( CheckVersion($DBversion) ) {
9744     my $number_of_orders_not_linked = $dbh->selectcol_arrayref(q|
9745         SELECT COUNT(*)
9746         FROM aqorders o
9747         WHERE NOT EXISTS (
9748             SELECT NULL
9749             FROM aqbudgets b
9750             WHERE b.budget_id = o.budget_id
9751         );
9752     |);
9753
9754     if ( $number_of_orders_not_linked->[0] > 0 ) {
9755         $dbh->do(q|
9756             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)
9757         |);
9758         my $budget_period_id = $dbh->last_insert_id( undef, undef, 'aqbudgetperiods', undef );
9759         $dbh->do(qq|
9760             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 );
9761         |);
9762         my $budget_id = $dbh->last_insert_id( undef, undef, 'aqbudgets', undef );
9763         $dbh->do(qq|
9764             UPDATE aqorders o
9765             SET budget_id = $budget_id
9766             WHERE NOT EXISTS (
9767                 SELECT NULL
9768                 FROM aqbudgets b
9769                 WHERE b.budget_id = o.budget_id
9770             )
9771         |);
9772     }
9773
9774     $dbh->do(q|
9775         ALTER TABLE aqorders
9776         ADD CONSTRAINT aqorders_budget_id_fk FOREIGN KEY (budget_id) REFERENCES aqbudgets(budget_id) ON DELETE CASCADE ON UPDATE CASCADE
9777     |);
9778
9779     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";
9780     SetVersion($DBversion);
9781 }
9782
9783 $DBversion = "3.19.00.009";
9784 if ( CheckVersion($DBversion) ) {
9785     $dbh->do(q|
9786         UPDATE suggestions s SET s.budgetid = NULL
9787         WHERE NOT EXISTS (
9788             SELECT NULL
9789             FROM aqbudgets b
9790             WHERE b.budget_id = s.budgetid
9791         );
9792     |);
9793
9794     $dbh->do(q|
9795         ALTER TABLE suggestions
9796         ADD CONSTRAINT suggestions_budget_id_fk FOREIGN KEY (budgetid) REFERENCES aqbudgets(budget_id) ON DELETE SET NULL ON UPDATE CASCADE
9797     |);
9798
9799     print "Upgrade to $DBversion done (Bug 13007 - Add new foreign key suggestions.budgetid)\n";
9800     SetVersion($DBversion);
9801 }
9802
9803 $DBversion = "3.19.00.010";
9804 if ( CheckVersion($DBversion) ) {
9805     $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')");
9806     print "Upgrade to $DBversion done (Bug 5511 - SessionRestrictionByIP)\n";
9807     SetVersion ($DBversion);
9808 }
9809
9810 $DBversion = "3.19.00.011";
9811 if ( CheckVersion($DBversion) ) {
9812     $dbh->do(q|
9813         INSERT INTO userflags (bit, flag, flagdesc, defaulton) VALUES
9814         (20, 'lists', 'Lists', 0)
9815     |);
9816     $dbh->do(q|
9817         INSERT INTO permissions (module_bit, code, description) VALUES
9818         (20, 'delete_public_lists', 'Delete public lists')
9819     |);
9820     print "Upgrade to $DBversion done (Bug 13417: Add permission to delete public lists)\n";
9821     SetVersion ($DBversion);
9822 }
9823
9824 $DBversion = "3.19.00.012";
9825 if(CheckVersion($DBversion)) {
9826     $dbh->do(q{
9827         ALTER TABLE biblioitems MODIFY COLUMN marcxml longtext
9828     });
9829
9830     $dbh->do(q{
9831         ALTER TABLE deletedbiblioitems MODIFY COLUMN marcxml longtext
9832     });
9833
9834     print "Upgrade to $DBversion done (Bug 13523 - Remove NOT NULL restriction on field marcxml due to mysql STRICT_TRANS_TABLES)\n";
9835     SetVersion($DBversion);
9836 }
9837
9838 $DBversion = "3.19.00.013";
9839 if ( CheckVersion($DBversion) ) {
9840     $dbh->do(q|
9841         INSERT INTO permissions (module_bit, code, description) VALUES
9842           (13, 'records_batchmod', 'Perform batch modification of records (biblios or authorities)')
9843     |);
9844     print "Upgrade to $DBversion done (Bug 11395: Add permission tools_records_batchmod)\n";
9845     SetVersion($DBversion);
9846 }
9847
9848 $DBversion = "3.19.00.014";
9849 if ( CheckVersion($DBversion) ) {
9850     $dbh->do(q|
9851         CREATE TABLE aqorder_users (
9852             ordernumber int(11) NOT NULL,
9853             borrowernumber int(11) NOT NULL,
9854             PRIMARY KEY (ordernumber, borrowernumber),
9855             CONSTRAINT aqorder_users_ibfk_1 FOREIGN KEY (ordernumber) REFERENCES aqorders (ordernumber) ON DELETE CASCADE ON UPDATE CASCADE,
9856             CONSTRAINT aqorder_users_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
9857         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
9858     |);
9859
9860     $dbh->do(q|
9861         INSERT INTO letter(module, code, branchcode, name, title, content, message_transport_type)
9862         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')
9863     |);
9864     print "Upgrade to $DBversion done (Bug 12648: Add letter ACQ_NOTIF_ON_RECEIV )\n";
9865     SetVersion ($DBversion);
9866 }
9867
9868 $DBversion = "3.19.00.015";
9869 if ( CheckVersion($DBversion) ) {
9870     $dbh->do(q|
9871         ALTER TABLE search_history ADD COLUMN id INT(11) NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY(id);
9872     |);
9873     print "Upgrade to $DBversion done (Bug 11430 - Add primary key for search_history)\n";
9874     SetVersion($DBversion);
9875 }
9876
9877 $DBversion = "3.19.00.016";
9878 if(CheckVersion($DBversion)) {
9879     my @order_cancellation_reason = $dbh->selectrow_array("SELECT count(*) FROM authorised_values WHERE category='ORDER_CANCELLATION_REASON'");
9880     if ($order_cancellation_reason[0] == 0) {
9881         $dbh->do(q{
9882             INSERT INTO authorised_values (category, authorised_value, lib) VALUES
9883              ('ORDER_CANCELLATION_REASON', 0, 'No reason provided'),
9884              ('ORDER_CANCELLATION_REASON', 1, 'Out of stock'),
9885              ('ORDER_CANCELLATION_REASON', 2, 'Restocking')
9886         });
9887
9888         my $already_existing_reasons = $dbh->selectcol_arrayref(q{
9889             SELECT DISTINCT( cancellationreason )
9890             FROM aqorders;
9891         }, { Slice => {} });
9892
9893         my $update_orders_sth = $dbh->prepare(q{
9894             UPDATE aqorders
9895             SET cancellationreason = ?
9896             WHERE cancellationreason = ?
9897         });
9898
9899         my $insert_av_sth = $dbh->prepare(q{
9900             INSERT INTO authorised_values (category, authorised_value, lib) VALUES
9901              ('ORDER_CANCELLATION_REASON', ?, ?)
9902         });
9903         my $i = 3;
9904         for my $reason ( @$already_existing_reasons ) {
9905             next unless $reason;
9906             $insert_av_sth->execute( $i, $reason );
9907             $update_orders_sth->execute( $i, $reason );
9908             $i++;
9909         }
9910         print "Upgrade to $DBversion done (Bug 13380: Add the ORDER_CANCELLATION_REASON authorised value)\n";
9911     }
9912     else {
9913         print "Upgrade to $DBversion done (Bug 13380: ORDER_CANCELLATION_REASON authorised value already existed from earlier update!)\n";
9914     }
9915
9916     SetVersion($DBversion);
9917 }
9918
9919 $DBversion = '3.19.00.017';
9920 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
9921     # First create the column
9922     $dbh->do("ALTER TABLE issuingrules ADD onshelfholds tinyint(1) default 0 NOT NULL");
9923     # Now update the column
9924     if (C4::Context->preference("AllowOnShelfHolds")){
9925         # Pref is on, set allow for all rules
9926         $dbh->do("UPDATE issuingrules SET onshelfholds=1");
9927     } else {
9928         # If the preference is not set, leave off
9929         $dbh->do("UPDATE issuingrules SET onshelfholds=0");
9930     }
9931     # Remove from the systempreferences table
9932     $dbh->do("DELETE FROM systempreferences WHERE variable = 'AllowOnShelfHolds'");
9933
9934     # First create the column
9935     $dbh->do("ALTER TABLE issuingrules ADD opacitemholds char(1) DEFAULT 'N' NOT NULL");
9936     # Now update the column
9937     my $opacitemholds = C4::Context->preference("OPACItemHolds") || '';
9938     if (lc ($opacitemholds) eq 'force') {
9939         $opacitemholds = 'F';
9940     }
9941     else {
9942         $opacitemholds = $opacitemholds ? 'Y' : 'N';
9943     }
9944     # Set allow for all rules
9945     $dbh->do("UPDATE issuingrules SET opacitemholds='$opacitemholds'");
9946
9947     # Remove from the systempreferences table
9948     $dbh->do("DELETE FROM systempreferences WHERE variable = 'OPACItemHolds'");
9949
9950     print "Upgrade to $DBversion done (Bug 5786 - Move AllowOnShelfHolds to circulation matrix; Move OPACItemHolds system preference to circulation matrix)\n";
9951     SetVersion ($DBversion);
9952 }
9953
9954 $DBversion = "3.19.00.018";
9955 if ( CheckVersion($DBversion) ) {
9956     $dbh->do(q|
9957         UPDATE systempreferences set variable="OpacAdditionalStylesheet" WHERE variable="opaccolorstylesheet"
9958     |);
9959     print "Upgrade to $DBversion done (Bug 10328: Rename opaccolorstylesheet to OpacAdditionalStylesheet\n";
9960     SetVersion ($DBversion);
9961 }
9962
9963 $DBversion = "3.19.00.019";
9964 if ( CheckVersion($DBversion) ) {
9965     $dbh->do(q{
9966         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
9967         VALUES('Coce','0', 'If on, enables cover retrieval from the configured Coce server', NULL, 'YesNo')
9968     });
9969     $dbh->do(q{
9970         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
9971         VALUES('CoceHost', NULL, 'Coce server URL', NULL,'Free')
9972     });
9973     $dbh->do(q{
9974         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
9975         VALUES('CoceProviders', NULL, 'Coce providers', 'aws,gb,ol', 'multiple')
9976     });
9977     print "Upgrade to $DBversion done (Bug 9580: Cover image from Coce, a remote image URL cache)\n";
9978     SetVersion($DBversion);
9979 }
9980
9981 $DBversion = "3.19.00.020";
9982 if ( CheckVersion($DBversion) ) {
9983     $dbh->do(q|
9984         ALTER TABLE aqorders DROP COLUMN supplierreference;
9985     |);
9986
9987     print "Upgrade to $DBversion done (Bug 11008: DROP column aqorders.supplierreference)\n";
9988     SetVersion($DBversion);
9989 }
9990
9991 $DBversion = "3.19.00.021";
9992 if ( CheckVersion($DBversion) ) {
9993     $dbh->do(q|
9994         ALTER TABLE issues DROP COLUMN issuingbranch
9995     |);
9996     $dbh->do(q|
9997         ALTER TABLE old_issues DROP COLUMN issuingbranch
9998     |);
9999     print "Upgrade to $DBversion done (Bug 2806: Remove issuingbranch columns)\n";
10000     SetVersion ($DBversion);
10001 }
10002
10003 $DBversion = '3.19.00.022';
10004 if ( CheckVersion($DBversion) ) {
10005     $dbh->do(q{
10006         ALTER TABLE suggestions DROP COLUMN mailoverseeing;
10007     });
10008     print "Upgrade to $DBversion done (Bug 13006: Drop column suggestion.mailoverseeing)\n";
10009     SetVersion($DBversion);
10010 }
10011
10012 $DBversion = "3.19.00.023";
10013 if ( CheckVersion($DBversion) ) {
10014     $dbh->do(q|
10015         DELETE FROM systempreferences where variable = 'AddPatronLists'
10016     |);
10017     print "Upgrade to $DBversion done (Bug 13497: Remove the AddPatronLists system preferences)\n";
10018     SetVersion ($DBversion);
10019 }
10020
10021 $DBversion = "3.19.00.024";
10022 if ( CheckVersion($DBversion) ) {
10023     $dbh->do(qq|DROP table patroncards;|);
10024     print "Upgrade to $DBversion done (Bug 13539: Remove table patroncards from database as it's no longer in use)\n";
10025     SetVersion ($DBversion);
10026 }
10027
10028 $DBversion = "3.19.00.025";
10029 if ( CheckVersion($DBversion) ) {
10030     $dbh->do(q|
10031         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
10032         ('SearchWithISBNVariations','0',NULL,'If enabled, search on all variations of the ISBN','YesNo')
10033     |);
10034     print "Upgrade to $DBversion done (Bug 13528 - Add the SearchWithISBNVariations syspref)\n";
10035     SetVersion ($DBversion);
10036 }
10037
10038 # DEVELOPER PROCESS, search for anything to execute in the db_update directory
10039 # SEE bug 13068
10040 # if there is anything in the atomicupdate, read and execute it.
10041
10042 my $update_dir = C4::Context->config('intranetdir') . '/installer/data/mysql/atomicupdate/';
10043 opendir( my $dirh, $update_dir );
10044 while ( my $file = readdir $dirh ) {
10045     next unless $file =~ /\.sql$/;    # skip non SQL files
10046     print "DEV atomic update : $file \n";
10047     my $installer = C4::Installer->new();
10048     my $rv = $installer->load_sql( $update_dir . $file ) ? 0 : 1;
10049 }
10050
10051 =head1 FUNCTIONS
10052
10053 =head2 TableExists($table)
10054
10055 =cut
10056
10057 sub TableExists {
10058     my $table = shift;
10059     eval {
10060                 local $dbh->{PrintError} = 0;
10061                 local $dbh->{RaiseError} = 1;
10062                 $dbh->do(qq{SELECT * FROM $table WHERE 1 = 0 });
10063             };
10064     return 1 unless $@;
10065     return 0;
10066 }
10067
10068 =head2 DropAllForeignKeys($table)
10069
10070 Drop all foreign keys of the table $table
10071
10072 =cut
10073
10074 sub DropAllForeignKeys {
10075     my ($table) = @_;
10076     # get the table description
10077     my $sth = $dbh->prepare("SHOW CREATE TABLE $table");
10078     $sth->execute;
10079     my $vsc_structure = $sth->fetchrow;
10080     # split on CONSTRAINT keyword
10081     my @fks = split /CONSTRAINT /,$vsc_structure;
10082     # parse each entry
10083     foreach (@fks) {
10084         # isolate what is before FOREIGN KEY, if there is something, it's a foreign key to drop
10085         $_ = /(.*) FOREIGN KEY.*/;
10086         my $id = $1;
10087         if ($id) {
10088             # we have found 1 foreign, drop it
10089             $dbh->do("ALTER TABLE $table DROP FOREIGN KEY $id");
10090             $id="";
10091         }
10092     }
10093 }
10094
10095
10096 =head2 TransformToNum
10097
10098 Transform the Koha version from a 4 parts string
10099 to a number, with just 1 .
10100
10101 =cut
10102
10103 sub TransformToNum {
10104     my $version = shift;
10105     # remove the 3 last . to have a Perl number
10106     $version =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
10107     # three X's at the end indicate that you are testing patch with dbrev
10108     # change it into 999
10109     # prevents error on a < comparison between strings (should be: lt)
10110     $version =~ s/XXX$/999/;
10111     return $version;
10112 }
10113
10114 =head2 SetVersion
10115
10116 set the DBversion in the systempreferences
10117
10118 =cut
10119
10120 sub SetVersion {
10121     return if $_[0]=~ /XXX$/;
10122       #you are testing a patch with a db revision; do not change version
10123     my $kohaversion = TransformToNum($_[0]);
10124     if (C4::Context->preference('Version')) {
10125       my $finish=$dbh->prepare("UPDATE systempreferences SET value=? WHERE variable='Version'");
10126       $finish->execute($kohaversion);
10127     } else {
10128       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')");
10129       $finish->execute($kohaversion);
10130     }
10131     C4::Context::clear_syspref_cache(); # invalidate cached preferences
10132 }
10133
10134 =head2 CheckVersion
10135
10136 Check whether a given update should be run when passed the proposed version
10137 number. The update will always be run if the proposed version is greater
10138 than the current database version and less than or equal to the version in
10139 kohaversion.pl. The update is also run if the version contains XXX, though
10140 this behavior will be changed following the adoption of non-linear updates
10141 as implemented in bug 7167.
10142
10143 =cut
10144
10145 sub CheckVersion {
10146     my ($proposed_version) = @_;
10147     my $version_number = TransformToNum($proposed_version);
10148
10149     # The following line should be deleted when bug 7167 is pushed
10150     return 1 if ( $proposed_version =~ m/XXX/ );
10151
10152     if ( C4::Context->preference("Version") < $version_number
10153         && $version_number <= TransformToNum( C4::Context->final_linear_version ) )
10154     {
10155         return 1;
10156     }
10157     else {
10158         return 0;
10159     }
10160 }
10161
10162 exit;