Bug 8207: Allow see also fields in auths to link to thesauri
[koha.git] / installer / data / mysql / updatedatabase.pl
1 #!/usr/bin/perl
2
3 # Database Updater
4 # This script checks for required updates to the database.
5
6 # Parts copyright Catalyst IT 2011
7
8 # Part of the Koha Library Software www.koha-community.org
9 # Koha is free software; you can redistribute it and/or modify it under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
12 # version.
13 #
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License along
19 # with Koha; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
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
68 # Record the version we are coming from
69
70 my $original_version = C4::Context->preference("Version");
71
72 # Deal with virtualshelves
73 my $DBversion = "3.00.00.001";
74 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
75     # update virtualshelves table to
76     #
77     $dbh->do("ALTER TABLE `bookshelf` RENAME `virtualshelves`");
78     $dbh->do("ALTER TABLE `shelfcontents` RENAME `virtualshelfcontents`");
79     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD `biblionumber` INT( 11 ) NOT NULL default '0' AFTER shelfnumber");
80     $dbh->do("UPDATE `virtualshelfcontents` SET biblionumber=(SELECT biblionumber FROM items WHERE items.itemnumber=virtualshelfcontents.itemnumber)");
81     # drop all foreign keys : otherwise, we can't drop itemnumber field.
82     DropAllForeignKeys('virtualshelfcontents');
83     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD KEY biblionumber (biblionumber)");
84     # create the new foreign keys (on biblionumber)
85     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD CONSTRAINT `virtualshelfcontents_ibfk_1` FOREIGN KEY (`shelfnumber`) REFERENCES `virtualshelves` (`shelfnumber`) ON DELETE CASCADE ON UPDATE CASCADE");
86     # re-create the foreign key on virtualshelf
87     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD CONSTRAINT `shelfcontents_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE");
88     $dbh->do("ALTER TABLE `virtualshelfcontents` DROP `itemnumber`");
89     print "Upgrade to $DBversion done (virtualshelves)\n";
90     SetVersion ($DBversion);
91 }
92
93
94 $DBversion = "3.00.00.002";
95 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
96     $dbh->do("DROP TABLE sessions");
97     $dbh->do("CREATE TABLE `sessions` (
98   `id` varchar(32) NOT NULL,
99   `a_session` text NOT NULL,
100   UNIQUE KEY `id` (`id`)
101 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
102     print "Upgrade to $DBversion done (sessions uses CGI::session, new table structure for sessions)\n";
103     SetVersion ($DBversion);
104 }
105
106
107 $DBversion = "3.00.00.003";
108 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
109     if (C4::Context->preference("opaclanguages") eq "fr") {
110         $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')");
111     } else {
112         $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')");
113     }
114     print "Upgrade to $DBversion done (adding ReservesNeedReturns systempref, in circulation)\n";
115     SetVersion ($DBversion);
116 }
117
118
119 $DBversion = "3.00.00.004";
120 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
121     $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')");
122     print "Upgrade to $DBversion done (adding DebugLevel systempref, in 'Admin' tab)\n";
123     SetVersion ($DBversion);
124 }
125
126 $DBversion = "3.00.00.005";
127 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
128     $dbh->do("CREATE TABLE `tags` (
129                     `entry` varchar(255) NOT NULL default '',
130                     `weight` bigint(20) NOT NULL default 0,
131                     PRIMARY KEY  (`entry`)
132                     ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
133                 ");
134         $dbh->do("CREATE TABLE `nozebra` (
135                 `server` varchar(20)     NOT NULL,
136                 `indexname` varchar(40)  NOT NULL,
137                 `value` varchar(250)     NOT NULL,
138                 `biblionumbers` longtext NOT NULL,
139                 KEY `indexname` (`server`,`indexname`),
140                 KEY `value` (`server`,`value`))
141                 ENGINE=InnoDB DEFAULT CHARSET=utf8;
142                 ");
143     print "Upgrade to $DBversion done (adding tags and nozebra tables )\n";
144     SetVersion ($DBversion);
145 }
146
147 $DBversion = "3.00.00.006";
148 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
149     $dbh->do("UPDATE issues SET issuedate=timestamp WHERE issuedate='0000-00-00'");
150     print "Upgrade to $DBversion done (filled issues.issuedate with timestamp)\n";
151     SetVersion ($DBversion);
152 }
153
154 $DBversion = "3.00.00.007";
155 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
156     $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')");
157     print "Upgrade to $DBversion done (set SessionStorage variable)\n";
158     SetVersion ($DBversion);
159 }
160
161 $DBversion = "3.00.00.008";
162 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
163     $dbh->do("ALTER TABLE `biblio` ADD `datecreated` DATE NOT NULL AFTER `timestamp` ;");
164     $dbh->do("UPDATE biblio SET datecreated=timestamp");
165     print "Upgrade to $DBversion done (biblio creation date)\n";
166     SetVersion ($DBversion);
167 }
168
169 $DBversion = "3.00.00.009";
170 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
171
172     # Create backups of call number columns
173     # in case default migration needs to be customized
174     #
175     # UPGRADE NOTE: temp_upg_biblioitems_call_num should be dropped
176     #               after call numbers have been transformed to the new structure
177     #
178     # Not bothering to do the same with deletedbiblioitems -- assume
179     # default is good enough.
180     $dbh->do("CREATE TABLE `temp_upg_biblioitems_call_num` AS
181               SELECT `biblioitemnumber`, `biblionumber`,
182                      `classification`, `dewey`, `subclass`,
183                      `lcsort`, `ccode`
184               FROM `biblioitems`");
185
186     # biblioitems changes
187     $dbh->do("ALTER TABLE `biblioitems` CHANGE COLUMN `volumeddesc` `volumedesc` TEXT,
188                                     ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
189                                     ADD `cn_class` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
190                                     ADD `cn_item` VARCHAR(10) DEFAULT NULL AFTER `cn_class`,
191                                     ADD `cn_suffix` VARCHAR(10) DEFAULT NULL AFTER `cn_item`,
192                                     ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_suffix`,
193                                     ADD `totalissues` INT(10) AFTER `cn_sort`");
194
195     # default mapping of call number columns:
196     #   cn_class = concatentation of classification + dewey,
197     #              trimmed to fit -- assumes that most users do not
198     #              populate both classification and dewey in a single record
199     #   cn_item  = subclass
200     #   cn_source = left null
201     #   cn_sort = lcsort
202     #
203     # After upgrade, cn_sort will have to be set based on whatever
204     # default call number scheme user sets as a preference.  Misc
205     # script will be added at some point to do that.
206     #
207     $dbh->do("UPDATE `biblioitems`
208               SET cn_class = SUBSTR(TRIM(CONCAT_WS(' ', `classification`, `dewey`)), 1, 30),
209                     cn_item = subclass,
210                     `cn_sort` = `lcsort`
211             ");
212
213     # Now drop the old call number columns
214     $dbh->do("ALTER TABLE `biblioitems` DROP COLUMN `classification`,
215                                         DROP COLUMN `dewey`,
216                                         DROP COLUMN `subclass`,
217                                         DROP COLUMN `lcsort`,
218                                         DROP COLUMN `ccode`");
219
220     # deletedbiblio changes
221     $dbh->do("ALTER TABLE `deletedbiblio` ALTER COLUMN `frameworkcode` SET DEFAULT '',
222                                         DROP COLUMN `marc`,
223                                         ADD `datecreated` DATE NOT NULL AFTER `timestamp`");
224     $dbh->do("UPDATE deletedbiblio SET datecreated = timestamp");
225
226     # deletedbiblioitems changes
227     $dbh->do("ALTER TABLE `deletedbiblioitems`
228                         MODIFY `publicationyear` TEXT,
229                         CHANGE `volumeddesc` `volumedesc` TEXT,
230                         MODIFY `collectiontitle` MEDIUMTEXT DEFAULT NULL AFTER `volumedesc`,
231                         MODIFY `collectionissn` TEXT DEFAULT NULL AFTER `collectiontitle`,
232                         MODIFY `collectionvolume` MEDIUMTEXT DEFAULT NULL AFTER `collectionissn`,
233                         MODIFY `editionstatement` TEXT DEFAULT NULL AFTER `collectionvolume`,
234                         MODIFY `editionresponsibility` TEXT DEFAULT NULL AFTER `editionstatement`,
235                         MODIFY `place` VARCHAR(255) DEFAULT NULL AFTER `size`,
236                         MODIFY `marc` LONGBLOB,
237                         ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `url`,
238                         ADD `cn_class` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
239                         ADD `cn_item` VARCHAR(10) DEFAULT NULL AFTER `cn_class`,
240                         ADD `cn_suffix` VARCHAR(10) DEFAULT NULL AFTER `cn_item`,
241                         ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_suffix`,
242                         ADD `totalissues` INT(10) AFTER `cn_sort`,
243                         ADD `marcxml` LONGTEXT NOT NULL AFTER `totalissues`,
244                         ADD KEY `isbn` (`isbn`),
245                         ADD KEY `publishercode` (`publishercode`)
246                     ");
247
248     $dbh->do("UPDATE `deletedbiblioitems`
249                 SET `cn_class` = SUBSTR(TRIM(CONCAT_WS(' ', `classification`, `dewey`)), 1, 30),
250                `cn_item` = `subclass`,
251                 `cn_sort` = `lcsort`
252             ");
253     $dbh->do("ALTER TABLE `deletedbiblioitems`
254                         DROP COLUMN `classification`,
255                         DROP COLUMN `dewey`,
256                         DROP COLUMN `subclass`,
257                         DROP COLUMN `lcsort`,
258                         DROP COLUMN `ccode`
259             ");
260
261     # deleteditems changes
262     $dbh->do("ALTER TABLE `deleteditems`
263                         MODIFY `barcode` VARCHAR(20) DEFAULT NULL,
264                         MODIFY `price` DECIMAL(8,2) DEFAULT NULL,
265                         MODIFY `replacementprice` DECIMAL(8,2) DEFAULT NULL,
266                         DROP `bulk`,
267                         MODIFY `itemcallnumber` VARCHAR(30) DEFAULT NULL AFTER `wthdrawn`,
268                         MODIFY `holdingbranch` VARCHAR(10) DEFAULT NULL,
269                         DROP `interim`,
270                         MODIFY `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP AFTER `paidfor`,
271                         DROP `cutterextra`,
272                         ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `onloan`,
273                         ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
274                         ADD `ccode` VARCHAR(10) DEFAULT NULL AFTER `cn_sort`,
275                         ADD `materials` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
276                         ADD `uri` VARCHAR(255) DEFAULT NULL AFTER `materials`,
277                         MODIFY `marc` LONGBLOB AFTER `uri`,
278                         DROP KEY `barcode`,
279                         DROP KEY `itembarcodeidx`,
280                         DROP KEY `itembinoidx`,
281                         DROP KEY `itembibnoidx`,
282                         ADD UNIQUE KEY `delitembarcodeidx` (`barcode`),
283                         ADD KEY `delitembinoidx` (`biblioitemnumber`),
284                         ADD KEY `delitembibnoidx` (`biblionumber`),
285                         ADD KEY `delhomebranch` (`homebranch`),
286                         ADD KEY `delholdingbranch` (`holdingbranch`)");
287     $dbh->do("UPDATE deleteditems SET `ccode` = `itype`");
288     $dbh->do("ALTER TABLE deleteditems DROP `itype`");
289     $dbh->do("UPDATE `deleteditems` SET `cn_sort` = `itemcallnumber`");
290
291     # items changes
292     $dbh->do("ALTER TABLE `items` ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `onloan`,
293                                 ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
294                                 ADD `ccode` VARCHAR(10) DEFAULT NULL AFTER `cn_sort`,
295                                 ADD `materials` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
296                                 ADD `uri` VARCHAR(255) DEFAULT NULL AFTER `materials`
297             ");
298     $dbh->do("ALTER TABLE `items`
299                         DROP KEY `itembarcodeidx`,
300                         ADD UNIQUE KEY `itembarcodeidx` (`barcode`)");
301
302     # map items.itype to items.ccode and
303     # set cn_sort to itemcallnumber -- as with biblioitems.cn_sort,
304     # will have to be subsequently updated per user's default
305     # classification scheme
306     $dbh->do("UPDATE `items` SET `cn_sort` = `itemcallnumber`,
307                             `ccode` = `itype`");
308
309     $dbh->do("ALTER TABLE `items` DROP `cutterextra`,
310                                 DROP `itype`");
311
312     print "Upgrade to $DBversion done (major changes to biblio, biblioitems, items, and deleted* versions of same\n";
313     SetVersion ($DBversion);
314 }
315
316 $DBversion = "3.00.00.010";
317 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
318     $dbh->do("CREATE INDEX `userid` ON borrowers (`userid`) ");
319     print "Upgrade to $DBversion done (userid index added)\n";
320     SetVersion ($DBversion);
321 }
322
323 $DBversion = "3.00.00.011";
324 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
325     $dbh->do("ALTER TABLE `branchcategories` CHANGE `categorycode` `categorycode` varchar(10) ");
326     $dbh->do("ALTER TABLE `branchcategories` CHANGE `categoryname` `categoryname` varchar(32) ");
327     $dbh->do("ALTER TABLE `branchcategories` ADD COLUMN `categorytype` varchar(16) ");
328     $dbh->do("UPDATE `branchcategories` SET `categorytype` = 'properties'");
329     $dbh->do("ALTER TABLE `branchrelations` CHANGE `categorycode` `categorycode` varchar(10) ");
330     print "Upgrade to $DBversion done (added branchcategory type)\n";
331     SetVersion ($DBversion);
332 }
333
334 $DBversion = "3.00.00.012";
335 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
336     $dbh->do("CREATE TABLE `class_sort_rules` (
337                                `class_sort_rule` varchar(10) NOT NULL default '',
338                                `description` mediumtext,
339                                `sort_routine` varchar(30) NOT NULL default '',
340                                PRIMARY KEY (`class_sort_rule`),
341                                UNIQUE KEY `class_sort_rule_idx` (`class_sort_rule`)
342                              ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
343     $dbh->do("CREATE TABLE `class_sources` (
344                                `cn_source` varchar(10) NOT NULL default '',
345                                `description` mediumtext,
346                                `used` tinyint(4) NOT NULL default 0,
347                                `class_sort_rule` varchar(10) NOT NULL default '',
348                                PRIMARY KEY (`cn_source`),
349                                UNIQUE KEY `cn_source_idx` (`cn_source`),
350                                KEY `used_idx` (`used`),
351                                CONSTRAINT `class_source_ibfk_1` FOREIGN KEY (`class_sort_rule`)
352                                           REFERENCES `class_sort_rules` (`class_sort_rule`)
353                              ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
354     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type)
355               VALUES('DefaultClassificationSource','ddc',
356                      'Default classification scheme used by the collection. E.g., Dewey, LCC, etc.', NULL,'free')");
357     $dbh->do("INSERT INTO `class_sort_rules` (`class_sort_rule`, `description`, `sort_routine`) VALUES
358                                ('dewey', 'Default filing rules for DDC', 'Dewey'),
359                                ('lcc', 'Default filing rules for LCC', 'LCC'),
360                                ('generic', 'Generic call number filing rules', 'Generic')");
361     $dbh->do("INSERT INTO `class_sources` (`cn_source`, `description`, `used`, `class_sort_rule`) VALUES
362                             ('ddc', 'Dewey Decimal Classification', 1, 'dewey'),
363                             ('lcc', 'Library of Congress Classification', 1, 'lcc'),
364                             ('udc', 'Universal Decimal Classification', 0, 'generic'),
365                             ('sudocs', 'SuDoc Classification (U.S. GPO)', 0, 'generic'),
366                             ('z', 'Other/Generic Classification Scheme', 0, 'generic')");
367     print "Upgrade to $DBversion done (classification sources added)\n";
368     SetVersion ($DBversion);
369 }
370
371 $DBversion = "3.00.00.013";
372 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
373     $dbh->do("CREATE TABLE `import_batches` (
374               `import_batch_id` int(11) NOT NULL auto_increment,
375               `template_id` int(11) default NULL,
376               `branchcode` varchar(10) default NULL,
377               `num_biblios` int(11) NOT NULL default 0,
378               `num_items` int(11) NOT NULL default 0,
379               `upload_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
380               `overlay_action` enum('replace', 'create_new', 'use_template') NOT NULL default 'create_new',
381               `import_status` enum('staging', 'staged', 'importing', 'imported', 'reverting', 'reverted', 'cleaned') NOT NULL default 'staging',
382               `batch_type` enum('batch', 'z3950') NOT NULL default 'batch',
383               `file_name` varchar(100),
384               `comments` mediumtext,
385               PRIMARY KEY (`import_batch_id`),
386               KEY `branchcode` (`branchcode`)
387               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
388     $dbh->do("CREATE TABLE `import_records` (
389               `import_record_id` int(11) NOT NULL auto_increment,
390               `import_batch_id` int(11) NOT NULL,
391               `branchcode` varchar(10) default NULL,
392               `record_sequence` int(11) NOT NULL default 0,
393               `upload_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
394               `import_date` DATE default NULL,
395               `marc` longblob NOT NULL,
396               `marcxml` longtext NOT NULL,
397               `marcxml_old` longtext NOT NULL,
398               `record_type` enum('biblio', 'auth', 'holdings') NOT NULL default 'biblio',
399               `overlay_status` enum('no_match', 'auto_match', 'manual_match', 'match_applied') NOT NULL default 'no_match',
400               `status` enum('error', 'staged', 'imported', 'reverted', 'items_reverted') NOT NULL default 'staged',
401               `import_error` mediumtext,
402               `encoding` varchar(40) NOT NULL default '',
403               `z3950random` varchar(40) default NULL,
404               PRIMARY KEY (`import_record_id`),
405               CONSTRAINT `import_records_ifbk_1` FOREIGN KEY (`import_batch_id`)
406                           REFERENCES `import_batches` (`import_batch_id`) ON DELETE CASCADE ON UPDATE CASCADE,
407               KEY `branchcode` (`branchcode`),
408               KEY `batch_sequence` (`import_batch_id`, `record_sequence`)
409               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
410     $dbh->do("CREATE TABLE `import_record_matches` (
411               `import_record_id` int(11) NOT NULL,
412               `candidate_match_id` int(11) NOT NULL,
413               `score` int(11) NOT NULL default 0,
414               CONSTRAINT `import_record_matches_ibfk_1` FOREIGN KEY (`import_record_id`)
415                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
416               KEY `record_score` (`import_record_id`, `score`)
417               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
418     $dbh->do("CREATE TABLE `import_biblios` (
419               `import_record_id` int(11) NOT NULL,
420               `matched_biblionumber` int(11) default NULL,
421               `control_number` varchar(25) default NULL,
422               `original_source` varchar(25) default NULL,
423               `title` varchar(128) default NULL,
424               `author` varchar(80) default NULL,
425               `isbn` varchar(14) default NULL,
426               `issn` varchar(9) default NULL,
427               `has_items` tinyint(1) NOT NULL default 0,
428               CONSTRAINT `import_biblios_ibfk_1` FOREIGN KEY (`import_record_id`)
429                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
430               KEY `matched_biblionumber` (`matched_biblionumber`),
431               KEY `title` (`title`),
432               KEY `isbn` (`isbn`)
433               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
434     $dbh->do("CREATE TABLE `import_items` (
435               `import_items_id` int(11) NOT NULL auto_increment,
436               `import_record_id` int(11) NOT NULL,
437               `itemnumber` int(11) default NULL,
438               `branchcode` varchar(10) default NULL,
439               `status` enum('error', 'staged', 'imported', 'reverted') NOT NULL default 'staged',
440               `marcxml` longtext NOT NULL,
441               `import_error` mediumtext,
442               PRIMARY KEY (`import_items_id`),
443               CONSTRAINT `import_items_ibfk_1` FOREIGN KEY (`import_record_id`)
444                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
445               KEY `itemnumber` (`itemnumber`),
446               KEY `branchcode` (`branchcode`)
447               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
448
449     $dbh->do("INSERT INTO `import_batches`
450                 (`overlay_action`, `import_status`, `batch_type`, `file_name`)
451               SELECT distinct 'create_new', 'staged', 'z3950', `file`
452               FROM   `marc_breeding`");
453
454     $dbh->do("INSERT INTO `import_records`
455                 (`import_batch_id`, `import_record_id`, `record_sequence`, `marc`, `record_type`, `status`,
456                 `encoding`, `z3950random`, `marcxml`, `marcxml_old`)
457               SELECT `import_batch_id`, `id`, 1, `marc`, 'biblio', 'staged', `encoding`, `z3950random`, '', ''
458               FROM `marc_breeding`
459               JOIN `import_batches` ON (`file_name` = `file`)");
460
461     $dbh->do("INSERT INTO `import_biblios`
462                 (`import_record_id`, `title`, `author`, `isbn`)
463               SELECT `import_record_id`, `title`, `author`, `isbn`
464               FROM   `marc_breeding`
465               JOIN   `import_records` ON (`import_record_id` = `id`)");
466
467     $dbh->do("UPDATE `import_batches`
468               SET `num_biblios` = (
469               SELECT COUNT(*)
470               FROM `import_records`
471               WHERE `import_batch_id` = `import_batches`.`import_batch_id`
472               )");
473
474     $dbh->do("DROP TABLE `marc_breeding`");
475
476     print "Upgrade to $DBversion done (import_batches et al. added)\n";
477     SetVersion ($DBversion);
478 }
479
480 $DBversion = "3.00.00.014";
481 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
482     $dbh->do("ALTER TABLE subscription ADD lastbranch VARCHAR(4)");
483     print "Upgrade to $DBversion done (userid index added)\n";
484     SetVersion ($DBversion);
485 }
486
487 $DBversion = "3.00.00.015";
488 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
489     $dbh->do("CREATE TABLE `saved_sql` (
490            `id` int(11) NOT NULL auto_increment,
491            `borrowernumber` int(11) default NULL,
492            `date_created` datetime default NULL,
493            `last_modified` datetime default NULL,
494            `savedsql` text,
495            `last_run` datetime default NULL,
496            `report_name` varchar(255) default NULL,
497            `type` varchar(255) default NULL,
498            `notes` text,
499            PRIMARY KEY  (`id`),
500            KEY boridx (`borrowernumber`)
501         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
502     $dbh->do("CREATE TABLE `saved_reports` (
503            `id` int(11) NOT NULL auto_increment,
504            `report_id` int(11) default NULL,
505            `report` longtext,
506            `date_run` datetime default NULL,
507            PRIMARY KEY  (`id`)
508         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
509     print "Upgrade to $DBversion done (saved_sql and saved_reports added)\n";
510     SetVersion ($DBversion);
511 }
512
513 $DBversion = "3.00.00.016";
514 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
515     $dbh->do(" CREATE TABLE reports_dictionary (
516           id int(11) NOT NULL auto_increment,
517           name varchar(255) default NULL,
518           description text,
519           date_created datetime default NULL,
520           date_modified datetime default NULL,
521           saved_sql text,
522           area int(11) default NULL,
523           PRIMARY KEY  (id)
524         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
525     print "Upgrade to $DBversion done (reports_dictionary) added)\n";
526     SetVersion ($DBversion);
527 }
528
529 $DBversion = "3.00.00.017";
530 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
531     $dbh->do("ALTER TABLE action_logs DROP PRIMARY KEY");
532     $dbh->do("ALTER TABLE action_logs ADD KEY  timestamp (timestamp,user)");
533     $dbh->do("ALTER TABLE action_logs ADD action_id INT(11) NOT NULL FIRST");
534     $dbh->do("UPDATE action_logs SET action_id = if (\@a, \@a:=\@a+1, \@a:=1)");
535     $dbh->do("ALTER TABLE action_logs MODIFY action_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY");
536     print "Upgrade to $DBversion done (added column to action_logs)\n";
537     SetVersion ($DBversion);
538 }
539
540 $DBversion = "3.00.00.018";
541 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
542     $dbh->do("ALTER TABLE `zebraqueue`
543                     ADD `done` INT NOT NULL DEFAULT '0',
544                     ADD `time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ;
545             ");
546     print "Upgrade to $DBversion done (adding timestamp and done columns to zebraque table to improve problem tracking) added)\n";
547     SetVersion ($DBversion);
548 }
549
550 $DBversion = "3.00.00.019";
551 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
552     $dbh->do("ALTER TABLE biblio MODIFY biblionumber INT(11) NOT NULL AUTO_INCREMENT");
553     $dbh->do("ALTER TABLE biblioitems MODIFY biblioitemnumber INT(11) NOT NULL AUTO_INCREMENT");
554     $dbh->do("ALTER TABLE items MODIFY itemnumber INT(11) NOT NULL AUTO_INCREMENT");
555     print "Upgrade to $DBversion done (made bib/item PKs auto_increment)\n";
556     SetVersion ($DBversion);
557 }
558
559 $DBversion = "3.00.00.020";
560 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
561     $dbh->do("ALTER TABLE deleteditems
562               DROP KEY `delitembarcodeidx`,
563               ADD KEY `delitembarcodeidx` (`barcode`)");
564     print "Upgrade to $DBversion done (dropped uniqueness of key on deleteditems.barcode)\n";
565     SetVersion ($DBversion);
566 }
567
568 $DBversion = "3.00.00.021";
569 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
570     $dbh->do("ALTER TABLE items CHANGE homebranch homebranch VARCHAR(10)");
571     $dbh->do("ALTER TABLE deleteditems CHANGE homebranch homebranch VARCHAR(10)");
572     $dbh->do("ALTER TABLE statistics CHANGE branch branch VARCHAR(10)");
573     $dbh->do("ALTER TABLE subscription CHANGE lastbranch lastbranch VARCHAR(10)");
574     print "Upgrade to $DBversion done (extended missed branchcode columns to 10 chars)\n";
575     SetVersion ($DBversion);
576 }
577
578 $DBversion = "3.00.00.022";
579 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
580     $dbh->do("ALTER TABLE items
581                 ADD `damaged` tinyint(1) default NULL AFTER notforloan");
582     $dbh->do("ALTER TABLE deleteditems
583                 ADD `damaged` tinyint(1) default NULL AFTER notforloan");
584     print "Upgrade to $DBversion done (adding damaged column to items table)\n";
585     SetVersion ($DBversion);
586 }
587
588 $DBversion = "3.00.00.023";
589 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
590      $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
591          VALUES ('yuipath','http://yui.yahooapis.com/2.3.1/build','Insert the path to YUI libraries','','free')");
592     print "Upgrade to $DBversion done (adding new system preference for controlling YUI path)\n";
593     SetVersion ($DBversion);
594 }
595 $DBversion = "3.00.00.024";
596 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
597     $dbh->do("ALTER TABLE biblioitems CHANGE  itemtype itemtype VARCHAR(10)");
598     print "Upgrade to $DBversion done (changing itemtype to (10))\n";
599     SetVersion ($DBversion);
600 }
601
602 $DBversion = "3.00.00.025";
603 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
604     $dbh->do("ALTER TABLE items ADD COLUMN itype VARCHAR(10)");
605     $dbh->do("ALTER TABLE deleteditems ADD COLUMN itype VARCHAR(10) AFTER uri");
606     if(C4::Context->preference('item-level_itypes')){
607         $dbh->do('update items,biblioitems set items.itype=biblioitems.itemtype where items.biblionumber=biblioitems.biblionumber and itype is null');
608     }
609     print "Upgrade to $DBversion done (reintroduce items.itype - fill from itemtype)\n ";
610     SetVersion ($DBversion);
611 }
612
613 $DBversion = "3.00.00.026";
614 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
615     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
616        VALUES ('HomeOrHoldingBranch','homebranch','homebranch|holdingbranch','With independent branches turned on this decides whether to check the items holdingbranch or homebranch at circulatilon','choice')");
617     print "Upgrade to $DBversion done (adding new system preference for choosing whether homebranch or holdingbranch is checked in circulation)\n";
618     SetVersion ($DBversion);
619 }
620
621 $DBversion = "3.00.00.027";
622 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
623     $dbh->do("CREATE TABLE `marc_matchers` (
624                 `matcher_id` int(11) NOT NULL auto_increment,
625                 `code` varchar(10) NOT NULL default '',
626                 `description` varchar(255) NOT NULL default '',
627                 `record_type` varchar(10) NOT NULL default 'biblio',
628                 `threshold` int(11) NOT NULL default 0,
629                 PRIMARY KEY (`matcher_id`),
630                 KEY `code` (`code`),
631                 KEY `record_type` (`record_type`)
632               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
633     $dbh->do("CREATE TABLE `matchpoints` (
634                 `matcher_id` int(11) NOT NULL,
635                 `matchpoint_id` int(11) NOT NULL auto_increment,
636                 `search_index` varchar(30) NOT NULL default '',
637                 `score` int(11) NOT NULL default 0,
638                 PRIMARY KEY (`matchpoint_id`),
639                 CONSTRAINT `matchpoints_ifbk_1` FOREIGN KEY (`matcher_id`)
640                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE
641               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
642     $dbh->do("CREATE TABLE `matchpoint_components` (
643                 `matchpoint_id` int(11) NOT NULL,
644                 `matchpoint_component_id` int(11) NOT NULL auto_increment,
645                 sequence int(11) NOT NULL default 0,
646                 tag varchar(3) NOT NULL default '',
647                 subfields varchar(40) NOT NULL default '',
648                 offset int(4) NOT NULL default 0,
649                 length int(4) NOT NULL default 0,
650                 PRIMARY KEY (`matchpoint_component_id`),
651                 KEY `by_sequence` (`matchpoint_id`, `sequence`),
652                 CONSTRAINT `matchpoint_components_ifbk_1` FOREIGN KEY (`matchpoint_id`)
653                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
654               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
655     $dbh->do("CREATE TABLE `matchpoint_component_norms` (
656                 `matchpoint_component_id` int(11) NOT NULL,
657                 `sequence`  int(11) NOT NULL default 0,
658                 `norm_routine` varchar(50) NOT NULL default '',
659                 KEY `matchpoint_component_norms` (`matchpoint_component_id`, `sequence`),
660                 CONSTRAINT `matchpoint_component_norms_ifbk_1` FOREIGN KEY (`matchpoint_component_id`)
661                            REFERENCES `matchpoint_components` (`matchpoint_component_id`) ON DELETE CASCADE ON UPDATE CASCADE
662               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
663     $dbh->do("CREATE TABLE `matcher_matchpoints` (
664                 `matcher_id` int(11) NOT NULL,
665                 `matchpoint_id` int(11) NOT NULL,
666                 CONSTRAINT `matcher_matchpoints_ifbk_1` FOREIGN KEY (`matcher_id`)
667                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE,
668                 CONSTRAINT `matcher_matchpoints_ifbk_2` FOREIGN KEY (`matchpoint_id`)
669                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
670               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
671     $dbh->do("CREATE TABLE `matchchecks` (
672                 `matcher_id` int(11) NOT NULL,
673                 `matchcheck_id` int(11) NOT NULL auto_increment,
674                 `source_matchpoint_id` int(11) NOT NULL,
675                 `target_matchpoint_id` int(11) NOT NULL,
676                 PRIMARY KEY (`matchcheck_id`),
677                 CONSTRAINT `matcher_matchchecks_ifbk_1` FOREIGN KEY (`matcher_id`)
678                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE,
679                 CONSTRAINT `matcher_matchchecks_ifbk_2` FOREIGN KEY (`source_matchpoint_id`)
680                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE,
681                 CONSTRAINT `matcher_matchchecks_ifbk_3` FOREIGN KEY (`target_matchpoint_id`)
682                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
683               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
684     print "Upgrade to $DBversion done (added C4::Matcher serialization tables)\n ";
685     SetVersion ($DBversion);
686 }
687
688 $DBversion = "3.00.00.028";
689 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
690     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
691        VALUES ('canreservefromotherbranches','1','','With Independent branches on, can a user from one library reserve an item from another library','YesNo')");
692     print "Upgrade to $DBversion done (adding new system preference for changing reserve/holds behaviour with independent branches)\n";
693     SetVersion ($DBversion);
694 }
695
696
697 $DBversion = "3.00.00.029";
698 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
699     $dbh->do("ALTER TABLE `import_batches` ADD `matcher_id` int(11) NULL AFTER `import_batch_id`");
700     print "Upgrade to $DBversion done (adding matcher_id to import_batches)\n";
701     SetVersion ($DBversion);
702 }
703
704 $DBversion = "3.00.00.030";
705 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
706     $dbh->do("
707 CREATE TABLE services_throttle (
708   service_type varchar(10) NOT NULL default '',
709   service_count varchar(45) default NULL,
710   PRIMARY KEY  (service_type)
711 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
712 ");
713     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
714        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')");
715  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
716        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')");
717  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
718        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')");
719  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
720        VALUES ('XISBNDailyLimit',499,'','The xISBN Web service is free for non-commercial use when usage does not exceed 500 requests per day','free')");
721  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
722        VALUES ('PINESISBN',0,'','Use with FRBRizeEditions. If ON, Koha will use PINES OISBN web service in the Editions tab on the detail pages.','YesNo')");
723  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
724        VALUES ('ThingISBN',0,'','Use with FRBRizeEditions. If ON, Koha will use the ThingISBN web service in the Editions tab on the detail pages.','YesNo')");
725     print "Upgrade to $DBversion done (adding services throttle table and sysprefs for xISBN)\n";
726     SetVersion ($DBversion);
727 }
728
729 $DBversion = "3.00.00.031";
730 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
731
732 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryStemming',1,'If ON, enables query stemming',NULL,'YesNo')");
733 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryFuzzy',1,'If ON, enables fuzzy option for searches',NULL,'YesNo')");
734 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryWeightFields',1,'If ON, enables field weighting',NULL,'YesNo')");
735 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('WebBasedSelfCheck',0,'If ON, enables the web-based self-check system',NULL,'YesNo')");
736 $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')");
737 $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')");
738 $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')");
739 $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')");
740 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('defaultSortOrder',NULL,'Specify the default sort order','asc|dsc|az|za','Choice')");
741 $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')");
742 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACdefaultSortOrder',NULL,'Specify the default sort order','asc|dsc|za|az','Choice')");
743 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('staffClientBaseURL','','Specify the base URL of the staff client',NULL,'free')");
744 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('minPasswordLength',3,'Specify the minimum length of a patron/staff password',NULL,'free')");
745 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('noItemTypeImages',0,'If ON, disables item-type images',NULL,'YesNo')");
746 $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')");
747 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('holdCancelLength','','Specify how many days before a hold is canceled',NULL,'free')");
748 $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')");
749 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('finesMode','test','Choose the fines mode, test or production','test|production','Choice')");
750 $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')");
751 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('itemBarcodeInputFilter','','If set, allows specification of a item barcode input filter','cuecat','Choice')");
752 $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')");
753 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('URLLinkText','','Text to display as the link anchor in the OPAC',NULL,'free')");
754 $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')");
755 $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')");
756 $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')");
757 $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')");
758 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACUserCSS',0,'Add CSS to be included in the OPAC',NULL,'free')");
759
760     print "Upgrade to $DBversion done (adding additional system preference)\n";
761     SetVersion ($DBversion);
762 }
763
764 $DBversion = "3.00.00.032";
765 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
766     $dbh->do("UPDATE `marc_subfield_structure` SET `kohafield` = 'items.wthdrawn' WHERE `kohafield` = 'items.withdrawn'");
767     print "Upgrade to $DBversion done (fixed MARC framework references to items.withdrawn)\n";
768     SetVersion ($DBversion);
769 }
770
771 $DBversion = "3.00.00.033";
772 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
773     $dbh->do("INSERT INTO `userflags` VALUES(17,'staffaccess','Modify login / permissions for staff users',0)");
774     print "Upgrade to $DBversion done (Adding permissions flag for staff member access modification.  )\n";
775     SetVersion ($DBversion);
776 }
777
778 $DBversion = "3.00.00.034";
779 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
780     $dbh->do("ALTER TABLE `virtualshelves` ADD COLUMN `sortfield` VARCHAR(16) ");
781     print "Upgrade to $DBversion done (Adding sortfield for Virtual Shelves.  )\n";
782     SetVersion ($DBversion);
783 }
784
785 $DBversion = "3.00.00.035";
786 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
787     $dbh->do("UPDATE marc_subfield_structure
788               SET authorised_value = 'cn_source'
789               WHERE kohafield IN ('items.cn_source', 'biblioitems.cn_source')
790               AND (authorised_value is NULL OR authorised_value = '')");
791     print "Upgrade to $DBversion done (MARC frameworks: make classification source a drop-down)\n";
792     SetVersion ($DBversion);
793 }
794
795 $DBversion = "3.00.00.036";
796 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
797     $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');");
798     print "Upgrade to $DBversion done (OPACItemsResultsDisplay systempreference added)\n";
799     SetVersion ($DBversion);
800 }
801
802 $DBversion = "3.00.00.037";
803 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
804     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactfirstname` varchar(255)");
805     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactsurname` varchar(255)");
806     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress1` varchar(255)");
807     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress2` varchar(255)");
808     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress3` varchar(255)");
809     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactzipcode` varchar(50)");
810     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactphone` varchar(50)");
811     print "Upgrade to $DBversion done (Adding Alternative Contact Person information to borrowers table)\n";
812     SetVersion ($DBversion);
813 }
814
815 $DBversion = "3.00.00.038";
816 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
817     $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'");
818     $dbh->do("DELETE FROM `systempreferences` WHERE variable='hideBiblioNumber'");
819     print "Upgrade to $DBversion done ('alter finesMode systempreference, remove superfluous syspref.')\n";
820     SetVersion ($DBversion);
821 }
822
823 $DBversion = "3.00.00.039";
824 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
825     $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')");
826     $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')");
827     $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')");
828     # $dbh->do("DELETE FROM `systempreferences` WHERE variable='HomeOrHoldingBranch'"); # Bug #2752
829     print "Upgrade to $DBversion done ('add circ sysprefs CircControl, finesCalendar, and uppercasesurnames, and delete HomeOrHoldingBranch.')\n";
830     SetVersion ($DBversion);
831 }
832
833 $DBversion = "3.00.00.040";
834 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
835         $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')");
836         $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')");
837         print "Upgrade to $DBversion done ('add circ sysprefs todaysIssuesDefaultSortOrder and previousIssuesDefaultSortOrder.')\n";
838     SetVersion ($DBversion);
839 }
840
841
842 $DBversion = "3.00.00.041";
843 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
844     # Strictly speaking it is not necessary to explicitly change
845     # NULL values to 0, because the ALTER TABLE statement will do that.
846     # However, setting them first avoids a warning.
847     $dbh->do("UPDATE items SET notforloan = 0 WHERE notforloan IS NULL");
848     $dbh->do("UPDATE items SET damaged = 0 WHERE damaged IS NULL");
849     $dbh->do("UPDATE items SET itemlost = 0 WHERE itemlost IS NULL");
850     $dbh->do("UPDATE items SET wthdrawn = 0 WHERE wthdrawn IS NULL");
851     $dbh->do("ALTER TABLE items
852                 MODIFY notforloan tinyint(1) NOT NULL default 0,
853                 MODIFY damaged    tinyint(1) NOT NULL default 0,
854                 MODIFY itemlost   tinyint(1) NOT NULL default 0,
855                 MODIFY wthdrawn   tinyint(1) NOT NULL default 0");
856     $dbh->do("UPDATE deleteditems SET notforloan = 0 WHERE notforloan IS NULL");
857     $dbh->do("UPDATE deleteditems SET damaged = 0 WHERE damaged IS NULL");
858     $dbh->do("UPDATE deleteditems SET itemlost = 0 WHERE itemlost IS NULL");
859     $dbh->do("UPDATE deleteditems SET wthdrawn = 0 WHERE wthdrawn IS NULL");
860     $dbh->do("ALTER TABLE deleteditems
861                 MODIFY notforloan tinyint(1) NOT NULL default 0,
862                 MODIFY damaged    tinyint(1) NOT NULL default 0,
863                 MODIFY itemlost   tinyint(1) NOT NULL default 0,
864                 MODIFY wthdrawn   tinyint(1) NOT NULL default 0");
865         print "Upgrade to $DBversion done (disallow NULL in several item status columns)\n";
866     SetVersion ($DBversion);
867 }
868
869 $DBversion = "3.00.00.04";
870 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
871     $dbh->do("ALTER TABLE aqbooksellers CHANGE name name mediumtext NOT NULL");
872         print "Upgrade to $DBversion done (disallow NULL in aqbooksellers.name; part of fix for bug 1251)\n";
873     SetVersion ($DBversion);
874 }
875
876 $DBversion = "3.00.00.043";
877 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
878     $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");
879         print "Upgrade to $DBversion done (currency table: add symbol and timestamp columns)\n";
880     SetVersion ($DBversion);
881 }
882
883 $DBversion = "3.00.00.044";
884 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
885     $dbh->do("ALTER TABLE deletedborrowers
886   ADD `altcontactfirstname` varchar(255) default NULL,
887   ADD `altcontactsurname` varchar(255) default NULL,
888   ADD `altcontactaddress1` varchar(255) default NULL,
889   ADD `altcontactaddress2` varchar(255) default NULL,
890   ADD `altcontactaddress3` varchar(255) default NULL,
891   ADD `altcontactzipcode` varchar(50) default NULL,
892   ADD `altcontactphone` varchar(50) default NULL
893   ");
894   $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES
895 ('OPACBaseURL',NULL,'Specify the Base URL of the OPAC, e.g., opac.mylibrary.com, the http:// will be added automatically by Koha.',NULL,'Free'),
896 ('language','en','Set the default language in the staff client.',NULL,'Languages'),
897 ('QueryAutoTruncate',1,'If ON, query truncation is enabled by default',NULL,'YesNo'),
898 ('QueryRemoveStopwords',0,'If ON, stopwords listed in the Administration area will be removed from queries',NULL,'YesNo')
899   ");
900         print "Upgrade to $DBversion done (syncing deletedborrowers table with borrowers table)\n";
901     SetVersion ($DBversion);
902 }
903
904 #-- http://www.w3.org/International/articles/language-tags/
905
906 #-- RFC4646
907 $DBversion = "3.00.00.045";
908 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
909     $dbh->do("
910 CREATE TABLE language_subtag_registry (
911         subtag varchar(25),
912         type varchar(25), -- language-script-region-variant-extension-privateuse
913         description varchar(25), -- only one of the possible descriptions for ease of reference, see language_descriptions for the complete list
914         added date,
915         KEY `subtag` (`subtag`)
916 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
917
918 #-- TODO: add suppress_scripts
919 #-- this maps three letter codes defined in iso639.2 back to their
920 #-- two letter equivilents in rfc4646 (LOC maintains iso639+)
921  $dbh->do("CREATE TABLE language_rfc4646_to_iso639 (
922         rfc4646_subtag varchar(25),
923         iso639_2_code varchar(25),
924         KEY `rfc4646_subtag` (`rfc4646_subtag`)
925 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
926
927  $dbh->do("CREATE TABLE language_descriptions (
928         subtag varchar(25),
929         type varchar(25),
930         lang varchar(25),
931         description varchar(255),
932         KEY `lang` (`lang`)
933 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
934
935 #-- bi-directional support, keyed by script subcode
936  $dbh->do("CREATE TABLE language_script_bidi (
937         rfc4646_subtag varchar(25), -- script subtag, Arab, Hebr, etc.
938         bidi varchar(3), -- rtl ltr
939         KEY `rfc4646_subtag` (`rfc4646_subtag`)
940 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
941
942 #-- BIDI Stuff, Arabic and Hebrew
943  $dbh->do("INSERT INTO language_script_bidi(rfc4646_subtag,bidi)
944 VALUES( 'Arab', 'rtl')");
945  $dbh->do("INSERT INTO language_script_bidi(rfc4646_subtag,bidi)
946 VALUES( 'Hebr', 'rtl')");
947
948 #-- TODO: need to map language subtags to script subtags for detection
949 #-- of bidi when script is not specified (like ar, he)
950  $dbh->do("CREATE TABLE language_script_mapping (
951         language_subtag varchar(25),
952         script_subtag varchar(25),
953         KEY `language_subtag` (`language_subtag`)
954 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
955
956 #-- Default mappings between script and language subcodes
957  $dbh->do("INSERT INTO language_script_mapping(language_subtag,script_subtag)
958 VALUES( 'ar', 'Arab')");
959  $dbh->do("INSERT INTO language_script_mapping(language_subtag,script_subtag)
960 VALUES( 'he', 'Hebr')");
961
962         print "Upgrade to $DBversion done (adding language subtag registry and basic BiDi support NOTE: You should import the subtag registry SQL)\n";
963     SetVersion ($DBversion);
964 }
965
966 $DBversion = "3.00.00.046";
967 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
968     $dbh->do("ALTER TABLE `subscription` CHANGE `numberlength` `numberlength` int(11) default '0' ,
969                  CHANGE `weeklength` `weeklength` int(11) default '0'");
970     $dbh->do("CREATE TABLE `serialitems` (`serialid` int(11) NOT NULL, `itemnumber` int(11) NOT NULL, UNIQUE KEY `serialididx` (`serialid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
971     $dbh->do("INSERT INTO `serialitems` SELECT `serialid`,`itemnumber` from serial where NOT ISNULL(itemnumber) && itemnumber <> '' && itemnumber NOT LIKE '%,%'");
972         print "Upgrade to $DBversion done (Add serialitems table to link serial issues to items. )\n";
973     SetVersion ($DBversion);
974 }
975
976 $DBversion = "3.00.00.047";
977 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
978     $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');");
979         print "Upgrade to $DBversion done ( Added OpacRenewalAllowed syspref )\n";
980     SetVersion ($DBversion);
981 }
982
983 $DBversion = "3.00.00.048";
984 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
985     $dbh->do("ALTER TABLE `items` ADD `more_subfields_xml` longtext default NULL AFTER `itype`");
986         print "Upgrade to $DBversion done (added items.more_subfields_xml)\n";
987     SetVersion ($DBversion);
988 }
989
990 $DBversion = "3.00.00.049";
991 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
992         $dbh->do("ALTER TABLE `z3950servers` ADD `encoding` text default NULL AFTER type ");
993         print "Upgrade to $DBversion done ( Added encoding field to z3950servers table )\n";
994     SetVersion ($DBversion);
995 }
996
997 $DBversion = "3.00.00.050";
998 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
999     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacHighlightedWords','0','If Set, query matched terms are highlighted in OPAC',NULL,'YesNo');");
1000         print "Upgrade to $DBversion done ( Added OpacHighlightedWords syspref )\n";
1001     SetVersion ($DBversion);
1002 }
1003
1004 $DBversion = "3.00.00.051";
1005 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1006     $dbh->do("UPDATE systempreferences SET explanation = 'Define the current theme for the OPAC interface.' WHERE variable = 'opacthemes';");
1007         print "Upgrade to $DBversion done ( Corrected opacthemes explanation. )\n";
1008     SetVersion ($DBversion);
1009 }
1010
1011 $DBversion = "3.00.00.052";
1012 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1013     $dbh->do("ALTER TABLE `deleteditems` ADD `more_subfields_xml` LONGTEXT DEFAULT NULL AFTER `itype`");
1014         print "Upgrade to $DBversion done ( Adding missing column to deleteditems table. )\n";
1015     SetVersion ($DBversion);
1016 }
1017
1018 $DBversion = "3.00.00.053";
1019 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1020     $dbh->do("CREATE TABLE `printers_profile` (
1021             `prof_id` int(4) NOT NULL auto_increment,
1022             `printername` varchar(40) NOT NULL,
1023             `tmpl_id` int(4) NOT NULL,
1024             `paper_bin` varchar(20) NOT NULL,
1025             `offset_horz` float default NULL,
1026             `offset_vert` float default NULL,
1027             `creep_horz` float default NULL,
1028             `creep_vert` float default NULL,
1029             `unit` char(20) NOT NULL default 'POINT',
1030             PRIMARY KEY  (`prof_id`),
1031             UNIQUE KEY `printername` (`printername`,`tmpl_id`,`paper_bin`),
1032             CONSTRAINT `printers_profile_pnfk_1` FOREIGN KEY (`tmpl_id`) REFERENCES `labels_templates` (`tmpl_id`) ON DELETE CASCADE ON UPDATE CASCADE
1033             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1034     $dbh->do("CREATE TABLE `labels_profile` (
1035             `tmpl_id` int(4) NOT NULL,
1036             `prof_id` int(4) NOT NULL,
1037             UNIQUE KEY `tmpl_id` (`tmpl_id`),
1038             UNIQUE KEY `prof_id` (`prof_id`)
1039             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1040     print "Upgrade to $DBversion done ( Printer Profile tables added )\n";
1041     SetVersion ($DBversion);
1042 }
1043
1044 $DBversion = "3.00.00.054";
1045 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1046     $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';");
1047         print "Upgrade to $DBversion done ( Added another barcode autogeneration sequence to barcode.pl. )\n";
1048     SetVersion ($DBversion);
1049 }
1050
1051 $DBversion = "3.00.00.055";
1052 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1053     $dbh->do("ALTER TABLE `zebraqueue` ADD KEY `zebraqueue_lookup` (`server`, `biblio_auth_number`, `operation`, `done`)");
1054         print "Upgrade to $DBversion done ( Added index on zebraqueue. )\n";
1055     SetVersion ($DBversion);
1056 }
1057 $DBversion = "3.00.00.056";
1058 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1059     if (C4::Context->preference("marcflavour") eq 'UNIMARC') {
1060         $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) ");
1061     } else {
1062         $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) ");
1063     }
1064     $dbh->do("ALTER TABLE `items` ADD `enumchron` VARCHAR(80) DEFAULT NULL;");
1065     print "Upgrade to $DBversion done ( Added item.enumchron column, and framework map to 952h )\n";
1066     SetVersion ($DBversion);
1067 }
1068
1069 $DBversion = "3.00.00.057";
1070 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1071     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH','0','if ON, OAI-PMH server is enabled',NULL,'YesNo');");
1072     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH:archiveID','KOHA-OAI-TEST','OAI-PMH archive identification',NULL,'Free');");
1073     $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');");
1074     $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');");
1075     $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');");
1076     SetVersion ($DBversion);
1077 }
1078
1079 $DBversion = "3.00.00.058";
1080 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1081     $dbh->do("ALTER TABLE `opac_news`
1082                 CHANGE `lang` `lang` VARCHAR( 25 )
1083                 CHARACTER SET utf8
1084                 COLLATE utf8_general_ci
1085                 NOT NULL default ''");
1086         print "Upgrade to $DBversion done ( lang field in opac_news made longer )\n";
1087     SetVersion ($DBversion);
1088 }
1089
1090 $DBversion = "3.00.00.059";
1091 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1092
1093     $dbh->do("CREATE TABLE IF NOT EXISTS `labels_templates` (
1094             `tmpl_id` int(4) NOT NULL auto_increment,
1095             `tmpl_code` char(100)  default '',
1096             `tmpl_desc` char(100) default '',
1097             `page_width` float default '0',
1098             `page_height` float default '0',
1099             `label_width` float default '0',
1100             `label_height` float default '0',
1101             `topmargin` float default '0',
1102             `leftmargin` float default '0',
1103             `cols` int(2) default '0',
1104             `rows` int(2) default '0',
1105             `colgap` float default '0',
1106             `rowgap` float default '0',
1107             `active` int(1) default NULL,
1108             `units` char(20)  default 'PX',
1109             `fontsize` int(4) NOT NULL default '3',
1110             PRIMARY KEY  (`tmpl_id`)
1111             ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1112     $dbh->do("CREATE TABLE  IF NOT EXISTS `printers_profile` (
1113             `prof_id` int(4) NOT NULL auto_increment,
1114             `printername` varchar(40) NOT NULL,
1115             `tmpl_id` int(4) NOT NULL,
1116             `paper_bin` varchar(20) NOT NULL,
1117             `offset_horz` float default NULL,
1118             `offset_vert` float default NULL,
1119             `creep_horz` float default NULL,
1120             `creep_vert` float default NULL,
1121             `unit` char(20) NOT NULL default 'POINT',
1122             PRIMARY KEY  (`prof_id`),
1123             UNIQUE KEY `printername` (`printername`,`tmpl_id`,`paper_bin`),
1124             CONSTRAINT `printers_profile_pnfk_1` FOREIGN KEY (`tmpl_id`) REFERENCES `labels_templates` (`tmpl_id`) ON DELETE CASCADE ON UPDATE CASCADE
1125             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1126     print "Upgrade to $DBversion done ( Added labels_templates table if it did not exist. )\n";
1127     SetVersion ($DBversion);
1128 }
1129
1130 $DBversion = "3.00.00.060";
1131 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1132     $dbh->do("CREATE TABLE IF NOT EXISTS `patronimage` (
1133             `cardnumber` varchar(16) NOT NULL,
1134             `mimetype` varchar(15) NOT NULL,
1135             `imagefile` mediumblob NOT NULL,
1136             PRIMARY KEY  (`cardnumber`),
1137             CONSTRAINT `patronimage_fk1` FOREIGN KEY (`cardnumber`) REFERENCES `borrowers` (`cardnumber`) ON DELETE CASCADE ON UPDATE CASCADE
1138             ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1139         print "Upgrade to $DBversion done ( Added patronimage table. )\n";
1140     SetVersion ($DBversion);
1141 }
1142
1143 $DBversion = "3.00.00.061";
1144 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1145     $dbh->do("ALTER TABLE labels_templates ADD COLUMN font char(10) NOT NULL DEFAULT 'TR';");
1146         print "Upgrade to $DBversion done ( Added font column to labels_templates )\n";
1147     SetVersion ($DBversion);
1148 }
1149
1150 $DBversion = "3.00.00.062";
1151 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1152     $dbh->do("CREATE TABLE `old_issues` (
1153                 `borrowernumber` int(11) default NULL,
1154                 `itemnumber` int(11) default NULL,
1155                 `date_due` date default NULL,
1156                 `branchcode` varchar(10) default NULL,
1157                 `issuingbranch` varchar(18) default NULL,
1158                 `returndate` date default NULL,
1159                 `lastreneweddate` date default NULL,
1160                 `return` varchar(4) default NULL,
1161                 `renewals` tinyint(4) default NULL,
1162                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1163                 `issuedate` date default NULL,
1164                 KEY `old_issuesborridx` (`borrowernumber`),
1165                 KEY `old_issuesitemidx` (`itemnumber`),
1166                 KEY `old_bordate` (`borrowernumber`,`timestamp`),
1167                 CONSTRAINT `old_issues_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1168                     ON DELETE SET NULL ON UPDATE SET NULL,
1169                 CONSTRAINT `old_issues_ibfk_2` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`)
1170                     ON DELETE SET NULL ON UPDATE SET NULL
1171                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1172     $dbh->do("CREATE TABLE `old_reserves` (
1173                 `borrowernumber` int(11) default NULL,
1174                 `reservedate` date default NULL,
1175                 `biblionumber` int(11) default NULL,
1176                 `constrainttype` varchar(1) default NULL,
1177                 `branchcode` varchar(10) default NULL,
1178                 `notificationdate` date default NULL,
1179                 `reminderdate` date default NULL,
1180                 `cancellationdate` date default NULL,
1181                 `reservenotes` mediumtext,
1182                 `priority` smallint(6) default NULL,
1183                 `found` varchar(1) default NULL,
1184                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1185                 `itemnumber` int(11) default NULL,
1186                 `waitingdate` date default NULL,
1187                 KEY `old_reserves_borrowernumber` (`borrowernumber`),
1188                 KEY `old_reserves_biblionumber` (`biblionumber`),
1189                 KEY `old_reserves_itemnumber` (`itemnumber`),
1190                 KEY `old_reserves_branchcode` (`branchcode`),
1191                 CONSTRAINT `old_reserves_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1192                     ON DELETE SET NULL ON UPDATE SET NULL,
1193                 CONSTRAINT `old_reserves_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`)
1194                     ON DELETE SET NULL ON UPDATE SET NULL,
1195                 CONSTRAINT `old_reserves_ibfk_3` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`)
1196                     ON DELETE SET NULL ON UPDATE SET NULL
1197                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1198
1199     # move closed transactions to old_* tables
1200     $dbh->do("INSERT INTO old_issues SELECT * FROM issues WHERE returndate IS NOT NULL");
1201     $dbh->do("DELETE FROM issues WHERE returndate IS NOT NULL");
1202     $dbh->do("INSERT INTO old_reserves SELECT * FROM reserves WHERE cancellationdate IS NOT NULL OR found = 'F'");
1203     $dbh->do("DELETE FROM reserves WHERE cancellationdate IS NOT NULL OR found = 'F'");
1204
1205         print "Upgrade to $DBversion done ( Added old_issues and old_reserves tables )\n";
1206     SetVersion ($DBversion);
1207 }
1208
1209 $DBversion = "3.00.00.063";
1210 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1211     $dbh->do("ALTER TABLE deleteditems
1212                 CHANGE COLUMN booksellerid booksellerid MEDIUMTEXT DEFAULT NULL,
1213                 ADD COLUMN enumchron VARCHAR(80) DEFAULT NULL AFTER more_subfields_xml,
1214                 ADD COLUMN copynumber SMALLINT(6) DEFAULT NULL AFTER enumchron;");
1215     $dbh->do("ALTER TABLE items
1216                 CHANGE COLUMN booksellerid booksellerid MEDIUMTEXT,
1217                 ADD COLUMN copynumber SMALLINT(6) DEFAULT NULL AFTER enumchron;");
1218         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";
1219     SetVersion ($DBversion);
1220 }
1221
1222 $DBversion = "3.00.00.064";
1223 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1224     $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');");
1225     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AWSAccessKeyID','','See:  http://aws.amazon.com','','free');");
1226     $dbh->do("DELETE FROM `systempreferences` WHERE variable='AmazonDevKey';");
1227     $dbh->do("DELETE FROM `systempreferences` WHERE variable='XISBNAmazonSimilarItems';");
1228     $dbh->do("DELETE FROM `systempreferences` WHERE variable='OPACXISBNAmazonSimilarItems';");
1229     print "Upgrade to $DBversion done (IMPORTANT: Upgrading to Amazon.com Associates Web Service 4.0 ) \n";
1230     SetVersion ($DBversion);
1231 }
1232
1233 $DBversion = "3.00.00.065";
1234 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1235     $dbh->do("CREATE TABLE `patroncards` (
1236                 `cardid` int(11) NOT NULL auto_increment,
1237                 `batch_id` varchar(10) NOT NULL default '1',
1238                 `borrowernumber` int(11) NOT NULL,
1239                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1240                 PRIMARY KEY  (`cardid`),
1241                 KEY `patroncards_ibfk_1` (`borrowernumber`),
1242                 CONSTRAINT `patroncards_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE
1243                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1244     print "Upgrade to $DBversion done (Adding patroncards table for patroncards generation feature. ) \n";
1245     SetVersion ($DBversion);
1246 }
1247
1248 $DBversion = "3.00.00.066";
1249 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1250     $dbh->do("ALTER TABLE `virtualshelfcontents` MODIFY `dateadded` timestamp NOT NULL
1251 DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP;
1252 ");
1253     print "Upgrade to $DBversion done (fix for bug 1873: virtualshelfcontents dateadded column empty. ) \n";
1254     SetVersion ($DBversion);
1255 }
1256
1257 $DBversion = "3.00.00.067";
1258 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1259     $dbh->do("UPDATE systempreferences SET explanation = 'Enable patron images for the Staff Client', type = 'YesNo' WHERE variable = 'patronimages'");
1260     print "Upgrade to $DBversion done (Updating patronimages syspref to reflect current kohastructure.sql. ) \n";
1261     SetVersion ($DBversion);
1262 }
1263
1264 $DBversion = "3.00.00.068";
1265 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1266     $dbh->do("CREATE TABLE `permissions` (
1267                 `module_bit` int(11) NOT NULL DEFAULT 0,
1268                 `code` varchar(30) DEFAULT NULL,
1269                 `description` varchar(255) DEFAULT NULL,
1270                 PRIMARY KEY  (`module_bit`, `code`),
1271                 CONSTRAINT `permissions_ibfk_1` FOREIGN KEY (`module_bit`) REFERENCES `userflags` (`bit`)
1272                     ON DELETE CASCADE ON UPDATE CASCADE
1273               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1274     $dbh->do("CREATE TABLE `user_permissions` (
1275                 `borrowernumber` int(11) NOT NULL DEFAULT 0,
1276                 `module_bit` int(11) NOT NULL DEFAULT 0,
1277                 `code` varchar(30) DEFAULT NULL,
1278                 CONSTRAINT `user_permissions_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1279                     ON DELETE CASCADE ON UPDATE CASCADE,
1280                 CONSTRAINT `user_permissions_ibfk_2` FOREIGN KEY (`module_bit`, `code`)
1281                     REFERENCES `permissions` (`module_bit`, `code`)
1282                     ON DELETE CASCADE ON UPDATE CASCADE
1283               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1284
1285     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
1286     (13, 'edit_news', 'Write news for the OPAC and staff interfaces'),
1287     (13, 'label_creator', 'Create printable labels and barcodes from catalog and patron data'),
1288     (13, 'edit_calendar', 'Define days when the library is closed'),
1289     (13, 'moderate_comments', 'Moderate patron comments'),
1290     (13, 'edit_notices', 'Define notices'),
1291     (13, 'edit_notice_status_triggers', 'Set notice/status triggers for overdue items'),
1292     (13, 'view_system_logs', 'Browse the system logs'),
1293     (13, 'inventory', 'Perform inventory (stocktaking) of your catalogue'),
1294     (13, 'stage_marc_import', 'Stage MARC records into the reservoir'),
1295     (13, 'manage_staged_marc', 'Managed staged MARC records, including completing and reversing imports'),
1296     (13, 'export_catalog', 'Export bibliographic and holdings data'),
1297     (13, 'import_patrons', 'Import patron data'),
1298     (13, 'delete_anonymize_patrons', 'Delete old borrowers and anonymize circulation history (deletes borrower reading history)'),
1299     (13, 'batch_upload_patron_images', 'Upload patron images in batch or one at a time'),
1300     (13, 'schedule_tasks', 'Schedule tasks to run')");
1301
1302     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('GranularPermissions','0','Use detailed staff user permissions',NULL,'YesNo')");
1303
1304     print "Upgrade to $DBversion done (adding permissions and user_permissions tables and GranularPermissions syspref) \n";
1305     SetVersion ($DBversion);
1306 }
1307 $DBversion = "3.00.00.069";
1308 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1309     $dbh->do("ALTER TABLE labels_conf CHANGE COLUMN class classification int(1) DEFAULT NULL;");
1310         print "Upgrade to $DBversion done ( Correcting columname in labels_conf )\n";
1311     SetVersion ($DBversion);
1312 }
1313
1314 $DBversion = "3.00.00.070";
1315 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1316     $sth = $dbh->prepare("SELECT value FROM systempreferences WHERE variable='yuipath'");
1317     $sth->execute;
1318     my ($value) = $sth->fetchrow;
1319     $value =~ s/2.3.1/2.5.1/;
1320     $dbh->do("UPDATE systempreferences SET value='$value' WHERE variable='yuipath';");
1321         print "Update yuipath syspref to 2.5.1 if necessary\n";
1322     SetVersion ($DBversion);
1323 }
1324
1325 $DBversion = "3.00.00.071";
1326 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1327     $dbh->do(" ALTER TABLE `subscription` ADD `serialsadditems` TINYINT( 1 ) NOT NULL DEFAULT '0';");
1328     # fill the new field with the previous systempreference value, then drop the syspref
1329     my $sth = $dbh->prepare("SELECT value FROM systempreferences WHERE variable='serialsadditems'");
1330     $sth->execute;
1331     my ($serialsadditems) = $sth->fetchrow();
1332     $dbh->do("UPDATE subscription SET serialsadditems=$serialsadditems");
1333     $dbh->do("DELETE FROM systempreferences WHERE variable='serialsadditems'");
1334     print "Upgrade to $DBversion done ( moving serialsadditems from syspref to subscription )\n";
1335     SetVersion ($DBversion);
1336 }
1337
1338 $DBversion = "3.00.00.072";
1339 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1340     $dbh->do("ALTER TABLE labels_conf ADD COLUMN formatstring mediumtext DEFAULT NULL AFTER printingtype");
1341         print "Upgrade to $DBversion done ( Adding format string to labels generator. )\n";
1342     SetVersion ($DBversion);
1343 }
1344
1345 $DBversion = "3.00.00.073";
1346 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1347         $dbh->do("DROP TABLE IF EXISTS `tags_all`;");
1348         $dbh->do(q#
1349         CREATE TABLE `tags_all` (
1350           `tag_id`         int(11) NOT NULL auto_increment,
1351           `borrowernumber` int(11) NOT NULL,
1352           `biblionumber`   int(11) NOT NULL,
1353           `term`      varchar(255) NOT NULL,
1354           `language`       int(4) default NULL,
1355           `date_created` datetime  NOT NULL,
1356           PRIMARY KEY  (`tag_id`),
1357           KEY `tags_borrowers_fk_1` (`borrowernumber`),
1358           KEY `tags_biblionumber_fk_1` (`biblionumber`),
1359           CONSTRAINT `tags_borrowers_fk_1` FOREIGN KEY (`borrowernumber`)
1360                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1361           CONSTRAINT `tags_biblionumber_fk_1` FOREIGN KEY (`biblionumber`)
1362                 REFERENCES `biblio`     (`biblionumber`)  ON DELETE CASCADE ON UPDATE CASCADE
1363         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1364         #);
1365         $dbh->do("DROP TABLE IF EXISTS `tags_approval`;");
1366         $dbh->do(q#
1367         CREATE TABLE `tags_approval` (
1368           `term`   varchar(255) NOT NULL,
1369           `approved`     int(1) NOT NULL default '0',
1370           `date_approved` datetime       default NULL,
1371           `approved_by` int(11)          default NULL,
1372           `weight_total` int(9) NOT NULL default '1',
1373           PRIMARY KEY  (`term`),
1374           KEY `tags_approval_borrowers_fk_1` (`approved_by`),
1375           CONSTRAINT `tags_approval_borrowers_fk_1` FOREIGN KEY (`approved_by`)
1376                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE
1377         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1378         #);
1379         $dbh->do("DROP TABLE IF EXISTS `tags_index`;");
1380         $dbh->do(q#
1381         CREATE TABLE `tags_index` (
1382           `term`    varchar(255) NOT NULL,
1383           `biblionumber` int(11) NOT NULL,
1384           `weight`        int(9) NOT NULL default '1',
1385           PRIMARY KEY  (`term`,`biblionumber`),
1386           KEY `tags_index_biblionumber_fk_1` (`biblionumber`),
1387           CONSTRAINT `tags_index_term_fk_1` FOREIGN KEY (`term`)
1388                 REFERENCES `tags_approval` (`term`)  ON DELETE CASCADE ON UPDATE CASCADE,
1389           CONSTRAINT `tags_index_biblionumber_fk_1` FOREIGN KEY (`biblionumber`)
1390                 REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
1391         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1392         #);
1393         $dbh->do(q#
1394         INSERT INTO `systempreferences` VALUES
1395                 ('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=',''),
1396                 ('BakerTaylorEnabled','0','','Enable or disable all Baker & Taylor features.','YesNo'),
1397                 ('BakerTaylorPassword','','','Baker & Taylor Password for Content Cafe (external content)','Textarea'),
1398                 ('BakerTaylorUsername','','','Baker & Taylor Username for Content Cafe (external content)','Textarea'),
1399                 ('TagsEnabled','1','','Enables or disables all tagging features.  This is the main switch for tags.','YesNo'),
1400                 ('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.',''),
1401                 ('TagsInputOnDetail','1','','Allow users to input tags from the detail page.',         'YesNo'),
1402                 ('TagsInputOnList',  '0','','Allow users to input tags from the search results list.', 'YesNo'),
1403                 ('TagsModeration',  NULL,'','Require tags from patrons to be approved before becoming visible.','YesNo'),
1404                 ('TagsShowOnDetail','10','','Number of tags to display on detail page.  0 is off.',        'Integer'),
1405                 ('TagsShowOnList',   '6','','Number of tags to display on search results list.  0 is off.','Integer')
1406         #);
1407         print "Upgrade to $DBversion done (Baker/Taylor,Tags: sysprefs and tables (tags_all, tags_index, tags_approval)) \n";
1408         SetVersion ($DBversion);
1409 }
1410
1411 $DBversion = "3.00.00.074";
1412 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1413     $dbh->do( q(update itemtypes set imageurl = concat( 'npl/', imageurl )
1414                   where imageurl not like 'http%'
1415                     and imageurl is not NULL
1416                     and imageurl != '') );
1417     print "Upgrade to $DBversion done (updating imagetype.imageurls to reflect new icon locations.)\n";
1418     SetVersion ($DBversion);
1419 }
1420
1421 $DBversion = "3.00.00.075";
1422 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1423     $dbh->do( q(alter table authorised_values add imageurl varchar(200) default NULL) );
1424     print "Upgrade to $DBversion done (adding imageurl field to authorised_values table)\n";
1425     SetVersion ($DBversion);
1426 }
1427
1428 $DBversion = "3.00.00.076";
1429 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1430     $dbh->do("ALTER TABLE import_batches
1431               ADD COLUMN nomatch_action enum('create_new', 'ignore') NOT NULL default 'create_new' AFTER overlay_action");
1432     $dbh->do("ALTER TABLE import_batches
1433               ADD COLUMN item_action enum('always_add', 'add_only_for_matches', 'add_only_for_new', 'ignore')
1434                   NOT NULL default 'always_add' AFTER nomatch_action");
1435     $dbh->do("ALTER TABLE import_batches
1436               MODIFY overlay_action  enum('replace', 'create_new', 'use_template', 'ignore')
1437                   NOT NULL default 'create_new'");
1438     $dbh->do("ALTER TABLE import_records
1439               MODIFY status  enum('error', 'staged', 'imported', 'reverted', 'items_reverted',
1440                                   'ignored') NOT NULL default 'staged'");
1441     $dbh->do("ALTER TABLE import_items
1442               MODIFY status enum('error', 'staged', 'imported', 'reverted', 'ignored') NOT NULL default 'staged'");
1443
1444         print "Upgrade to $DBversion done (changes to import_batches and import_records)\n";
1445         SetVersion ($DBversion);
1446 }
1447
1448 $DBversion = "3.00.00.077";
1449 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1450     # drop these tables only if they exist and none of them are empty
1451     # these tables are not defined in the packaged 2.2.9, but since it is believed
1452     # that at least one library may be using them in a post-2.2.9 but pre-3.0 Koha,
1453     # some care is taken.
1454     my ($print_error) = $dbh->{PrintError};
1455     $dbh->{PrintError} = 0;
1456     my ($raise_error) = $dbh->{RaiseError};
1457     $dbh->{RaiseError} = 1;
1458
1459     my $count = 0;
1460     my $do_drop = 1;
1461     eval { $count = $dbh->do("SELECT 1 FROM categorytable"); };
1462     if ($count > 0) {
1463         $do_drop = 0;
1464     }
1465     eval { $count = $dbh->do("SELECT 1 FROM mediatypetable"); };
1466     if ($count > 0) {
1467         $do_drop = 0;
1468     }
1469     eval { $count = $dbh->do("SELECT 1 FROM subcategorytable"); };
1470     if ($count > 0) {
1471         $do_drop = 0;
1472     }
1473
1474     if ($do_drop) {
1475         $dbh->do("DROP TABLE IF EXISTS `categorytable`");
1476         $dbh->do("DROP TABLE IF EXISTS `mediatypetable`");
1477         $dbh->do("DROP TABLE IF EXISTS `subcategorytable`");
1478     }
1479
1480     $dbh->{PrintError} = $print_error;
1481     $dbh->{RaiseError} = $raise_error;
1482         print "Upgrade to $DBversion done (drop categorytable, subcategorytable, and mediatypetable)\n";
1483         SetVersion ($DBversion);
1484 }
1485
1486 $DBversion = "3.00.00.078";
1487 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1488     my ($print_error) = $dbh->{PrintError};
1489     $dbh->{PrintError} = 0;
1490
1491     unless ($dbh->do("SELECT 1 FROM browser")) {
1492         $dbh->{PrintError} = $print_error;
1493         $dbh->do("CREATE TABLE `browser` (
1494                     `level` int(11) NOT NULL,
1495                     `classification` varchar(20) NOT NULL,
1496                     `description` varchar(255) NOT NULL,
1497                     `number` bigint(20) NOT NULL,
1498                     `endnode` tinyint(4) NOT NULL
1499                   ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1500     }
1501     $dbh->{PrintError} = $print_error;
1502         print "Upgrade to $DBversion done (add browser table if not already present)\n";
1503         SetVersion ($DBversion);
1504 }
1505
1506 $DBversion = "3.00.00.079";
1507 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1508  my ($print_error) = $dbh->{PrintError};
1509     $dbh->{PrintError} = 0;
1510
1511     $dbh->do("INSERT INTO `systempreferences` (variable, value,options,type, explanation)VALUES
1512         ('AddPatronLists','categorycode','categorycode|category_type','Choice','Allow user to choose what list to pick up from when adding patrons')");
1513     print "Upgrade to $DBversion done (add browser table if not already present)\n";
1514         SetVersion ($DBversion);
1515 }
1516
1517 $DBversion = "3.00.00.080";
1518 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1519     $dbh->do("ALTER TABLE subscription CHANGE monthlength monthlength int(11) default '0'");
1520     $dbh->do("ALTER TABLE deleteditems MODIFY marc LONGBLOB AFTER copynumber");
1521     $dbh->do("ALTER TABLE aqbooksellers CHANGE name name mediumtext NOT NULL");
1522         print "Upgrade to $DBversion done (catch up on DB schema changes since alpha and beta)\n";
1523         SetVersion ($DBversion);
1524 }
1525
1526 $DBversion = "3.00.00.081";
1527 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1528     $dbh->do("CREATE TABLE `borrower_attribute_types` (
1529                 `code` varchar(10) NOT NULL,
1530                 `description` varchar(255) NOT NULL,
1531                 `repeatable` tinyint(1) NOT NULL default 0,
1532                 `unique_id` tinyint(1) NOT NULL default 0,
1533                 `opac_display` tinyint(1) NOT NULL default 0,
1534                 `password_allowed` tinyint(1) NOT NULL default 0,
1535                 `staff_searchable` tinyint(1) NOT NULL default 0,
1536                 `authorised_value_category` varchar(10) default NULL,
1537                 PRIMARY KEY  (`code`)
1538               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1539     $dbh->do("CREATE TABLE `borrower_attributes` (
1540                 `borrowernumber` int(11) NOT NULL,
1541                 `code` varchar(10) NOT NULL,
1542                 `attribute` varchar(30) default NULL,
1543                 `password` varchar(30) default NULL,
1544                 KEY `borrowernumber` (`borrowernumber`),
1545                 KEY `code_attribute` (`code`, `attribute`),
1546                 CONSTRAINT `borrower_attributes_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1547                     ON DELETE CASCADE ON UPDATE CASCADE,
1548                 CONSTRAINT `borrower_attributes_ibfk_2` FOREIGN KEY (`code`) REFERENCES `borrower_attribute_types` (`code`)
1549                     ON DELETE CASCADE ON UPDATE CASCADE
1550             ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1551     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('ExtendedPatronAttributes','0','Use extended patron IDs and attributes',NULL,'YesNo')");
1552     print "Upgrade to $DBversion done (added borrower_attributes and  borrower_attribute_types)\n";
1553  SetVersion ($DBversion);
1554 }
1555
1556 $DBversion = "3.00.00.082";
1557 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1558     $dbh->do( q(alter table accountlines add column lastincrement decimal(28,6) default NULL) );
1559     print "Upgrade to $DBversion done (adding lastincrement column to accountlines table)\n";
1560     SetVersion ($DBversion);
1561 }
1562
1563 $DBversion = "3.00.00.083";
1564 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1565     $dbh->do( qq(UPDATE systempreferences SET value='local' where variable='yuipath' and value like "%/intranet-tmpl/prog/%"));
1566     print "Upgrade to $DBversion done (Changing yuipath behaviour in managing a local value)\n";
1567     SetVersion ($DBversion);
1568 }
1569 $DBversion = "3.00.00.084";
1570     if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1571     $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')");
1572     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('GoogleJackets','0','if ON, displays jacket covers from Google Books API',NULL,'YesNo')");
1573     print "Upgrade to $DBversion done (add new sysprefs)\n";
1574     SetVersion ($DBversion);
1575 }
1576
1577 $DBversion = "3.00.00.085";
1578 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1579     if (C4::Context->preference("marcflavour") eq 'MARC21') {
1580         $dbh->do("UPDATE marc_subfield_structure SET tab = 0 WHERE tab =  9 AND tagfield = '037'");
1581         $dbh->do("UPDATE marc_subfield_structure SET tab = 1 WHERE tab =  6 AND tagfield in ('100', '110', '111', '130')");
1582         $dbh->do("UPDATE marc_subfield_structure SET tab = 2 WHERE tab =  6 AND tagfield in ('240', '243')");
1583         $dbh->do("UPDATE marc_subfield_structure SET tab = 4 WHERE tab =  6 AND tagfield in ('400', '410', '411', '440')");
1584         $dbh->do("UPDATE marc_subfield_structure SET tab = 5 WHERE tab =  9 AND tagfield = '584'");
1585         $dbh->do("UPDATE marc_subfield_structure SET tab = 7 WHERE tab = -6 AND tagfield = '760'");
1586     }
1587     print "Upgrade to $DBversion done (move editing tab of various MARC21 subfields)\n";
1588     SetVersion ($DBversion);
1589 }
1590
1591 $DBversion = "3.00.00.086";
1592 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1593         $dbh->do(
1594         "CREATE TABLE `tmp_holdsqueue` (
1595         `biblionumber` int(11) default NULL,
1596         `itemnumber` int(11) default NULL,
1597         `barcode` varchar(20) default NULL,
1598         `surname` mediumtext NOT NULL,
1599         `firstname` text,
1600         `phone` text,
1601         `borrowernumber` int(11) NOT NULL,
1602         `cardnumber` varchar(16) default NULL,
1603         `reservedate` date default NULL,
1604         `title` mediumtext,
1605         `itemcallnumber` varchar(30) default NULL,
1606         `holdingbranch` varchar(10) default NULL,
1607         `pickbranch` varchar(10) default NULL,
1608         `notes` text
1609         ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1610
1611         $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')");
1612         $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')");
1613
1614         print "Upgrade to $DBversion done (Table structure for table `tmp_holdsqueue`)\n";
1615         SetVersion ($DBversion);
1616 }
1617
1618 $DBversion = "3.00.00.087";
1619 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1620     $dbh->do("INSERT INTO `systempreferences` VALUES ('AutoEmailOpacUser','0','','Sends notification emails containing new account details to patrons - when account is created.','YesNo')" );
1621     $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')");
1622     print "Upgrade to $DBversion done (added 2 new 'AutoEmailOpacUser' sysprefs)\n";
1623     SetVersion ($DBversion);
1624 }
1625
1626 $DBversion = "3.00.00.088";
1627 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1628         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('OPACShelfBrowser','1','','Enable/disable Shelf Browser on item details page','YesNo')");
1629         $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')");
1630         $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')");
1631         $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')");
1632         print "Upgrade to $DBversion done (added 2 new 'AutoEmailOpacUser' sysprefs)\n";
1633     SetVersion ($DBversion);
1634 }
1635
1636 $DBversion = "3.00.00.089";
1637 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1638         $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')");
1639         print "Upgrade to $DBversion done (added new AdvancedSearchTypes syspref)\n";
1640     SetVersion ($DBversion);
1641 }
1642
1643 $DBversion = "3.00.00.090";
1644 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1645     $dbh->do("
1646         CREATE TABLE `branch_borrower_circ_rules` (
1647           `branchcode` VARCHAR(10) NOT NULL,
1648           `categorycode` VARCHAR(10) NOT NULL,
1649           `maxissueqty` int(4) default NULL,
1650           PRIMARY KEY (`categorycode`, `branchcode`),
1651           CONSTRAINT `branch_borrower_circ_rules_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
1652             ON DELETE CASCADE ON UPDATE CASCADE,
1653           CONSTRAINT `branch_borrower_circ_rules_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`)
1654             ON DELETE CASCADE ON UPDATE CASCADE
1655         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1656     ");
1657     $dbh->do("
1658         CREATE TABLE `default_borrower_circ_rules` (
1659           `categorycode` VARCHAR(10) NOT NULL,
1660           `maxissueqty` int(4) default NULL,
1661           PRIMARY KEY (`categorycode`),
1662           CONSTRAINT `borrower_borrower_circ_rules_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
1663             ON DELETE CASCADE ON UPDATE CASCADE
1664         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1665     ");
1666     $dbh->do("
1667         CREATE TABLE `default_branch_circ_rules` (
1668           `branchcode` VARCHAR(10) NOT NULL,
1669           `maxissueqty` int(4) default NULL,
1670           PRIMARY KEY (`branchcode`),
1671           CONSTRAINT `default_branch_circ_rules_ibfk_1` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`)
1672             ON DELETE CASCADE ON UPDATE CASCADE
1673         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1674     ");
1675     $dbh->do("
1676         CREATE TABLE `default_circ_rules` (
1677             `singleton` enum('singleton') NOT NULL default 'singleton',
1678             `maxissueqty` int(4) default NULL,
1679             PRIMARY KEY (`singleton`)
1680         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1681     ");
1682     print "Upgrade to $DBversion done (added several circ rules tables)\n";
1683     SetVersion ($DBversion);
1684 }
1685
1686
1687 $DBversion = "3.00.00.091";
1688 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1689     $dbh->do(<<'END_SQL');
1690 ALTER TABLE borrowers
1691 ADD `smsalertnumber` varchar(50) default NULL
1692 END_SQL
1693
1694     $dbh->do(<<'END_SQL');
1695 CREATE TABLE `message_attributes` (
1696   `message_attribute_id` int(11) NOT NULL auto_increment,
1697   `message_name` varchar(20) NOT NULL default '',
1698   `takes_days` tinyint(1) NOT NULL default '0',
1699   PRIMARY KEY  (`message_attribute_id`),
1700   UNIQUE KEY `message_name` (`message_name`)
1701 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1702 END_SQL
1703
1704     $dbh->do(<<'END_SQL');
1705 CREATE TABLE `message_transport_types` (
1706   `message_transport_type` varchar(20) NOT NULL,
1707   PRIMARY KEY  (`message_transport_type`)
1708 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1709 END_SQL
1710
1711     $dbh->do(<<'END_SQL');
1712 CREATE TABLE `message_transports` (
1713   `message_attribute_id` int(11) NOT NULL,
1714   `message_transport_type` varchar(20) NOT NULL,
1715   `is_digest` tinyint(1) NOT NULL default '0',
1716   `letter_module` varchar(20) NOT NULL default '',
1717   `letter_code` varchar(20) NOT NULL default '',
1718   PRIMARY KEY  (`message_attribute_id`,`message_transport_type`,`is_digest`),
1719   KEY `message_transport_type` (`message_transport_type`),
1720   KEY `letter_module` (`letter_module`,`letter_code`),
1721   CONSTRAINT `message_transports_ibfk_1` FOREIGN KEY (`message_attribute_id`) REFERENCES `message_attributes` (`message_attribute_id`) ON DELETE CASCADE ON UPDATE CASCADE,
1722   CONSTRAINT `message_transports_ibfk_2` FOREIGN KEY (`message_transport_type`) REFERENCES `message_transport_types` (`message_transport_type`) ON DELETE CASCADE ON UPDATE CASCADE,
1723   CONSTRAINT `message_transports_ibfk_3` FOREIGN KEY (`letter_module`, `letter_code`) REFERENCES `letter` (`module`, `code`) ON DELETE CASCADE ON UPDATE CASCADE
1724 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1725 END_SQL
1726
1727     $dbh->do(<<'END_SQL');
1728 CREATE TABLE `borrower_message_preferences` (
1729   `borrower_message_preference_id` int(11) NOT NULL auto_increment,
1730   `borrowernumber` int(11) NOT NULL default '0',
1731   `message_attribute_id` int(11) default '0',
1732   `days_in_advance` int(11) default '0',
1733   `wants_digets` tinyint(1) NOT NULL default '0',
1734   PRIMARY KEY  (`borrower_message_preference_id`),
1735   KEY `borrowernumber` (`borrowernumber`),
1736   KEY `message_attribute_id` (`message_attribute_id`),
1737   CONSTRAINT `borrower_message_preferences_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1738   CONSTRAINT `borrower_message_preferences_ibfk_2` FOREIGN KEY (`message_attribute_id`) REFERENCES `message_attributes` (`message_attribute_id`) ON DELETE CASCADE ON UPDATE CASCADE
1739 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1740 END_SQL
1741
1742     $dbh->do(<<'END_SQL');
1743 CREATE TABLE `borrower_message_transport_preferences` (
1744   `borrower_message_preference_id` int(11) NOT NULL default '0',
1745   `message_transport_type` varchar(20) NOT NULL default '0',
1746   PRIMARY KEY  (`borrower_message_preference_id`,`message_transport_type`),
1747   KEY `message_transport_type` (`message_transport_type`),
1748   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,
1749   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
1750 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1751 END_SQL
1752
1753     $dbh->do(<<'END_SQL');
1754 CREATE TABLE `message_queue` (
1755   `message_id` int(11) NOT NULL auto_increment,
1756   `borrowernumber` int(11) NOT NULL,
1757   `subject` text,
1758   `content` text,
1759   `message_transport_type` varchar(20) NOT NULL,
1760   `status` enum('sent','pending','failed','deleted') NOT NULL default 'pending',
1761   `time_queued` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1762   KEY `message_id` (`message_id`),
1763   KEY `borrowernumber` (`borrowernumber`),
1764   KEY `message_transport_type` (`message_transport_type`),
1765   CONSTRAINT `messageq_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1766   CONSTRAINT `messageq_ibfk_2` FOREIGN KEY (`message_transport_type`) REFERENCES `message_transport_types` (`message_transport_type`) ON DELETE RESTRICT ON UPDATE CASCADE
1767 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1768 END_SQL
1769
1770     $dbh->do(<<'END_SQL');
1771 INSERT INTO `systempreferences`
1772   (variable,value,explanation,options,type)
1773 VALUES
1774 ('EnhancedMessagingPreferences',0,'If ON, allows patrons to select to receive additional messages about items due or nearly due.','','YesNo')
1775 END_SQL
1776
1777     $dbh->do( <<'END_SQL');
1778 INSERT INTO `letter`
1779 (module, code, name, title, content)
1780 VALUES
1781 ('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>>'),
1782 ('circulation','DUEDGST','Item Due Reminder (Digest)','Item Due Reminder','You have <<count>> items due'),
1783 ('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>>'),
1784 ('circulation','PREDUEDGST','Advance Notice of Item Due (Digest)','Advance Notice of Item Due','You have <<count>> items due soon'),
1785 ('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.');
1786 END_SQL
1787
1788     my @sql_scripts = (
1789         'installer/data/mysql/en/mandatory/message_transport_types.sql',
1790         'installer/data/mysql/en/optional/sample_notices_message_attributes.sql',
1791         'installer/data/mysql/en/optional/sample_notices_message_transports.sql',
1792     );
1793
1794     my $installer = C4::Installer->new();
1795     foreach my $script ( @sql_scripts ) {
1796         my $full_path = $installer->get_file_path_from_name($script);
1797         my $error = $installer->load_sql($full_path);
1798         warn $error if $error;
1799     }
1800
1801     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";
1802     SetVersion ($DBversion);
1803 }
1804
1805 $DBversion = "3.00.00.092";
1806 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1807     $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')");
1808     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES('AllowHoldsOnDamagedItems', '1', '', 'Allow hold requests to be placed on damaged items', 'YesNo')");
1809         print "Upgrade to $DBversion done (added new AllowOnShelfHolds syspref)\n";
1810     SetVersion ($DBversion);
1811 }
1812
1813 $DBversion = "3.00.00.093";
1814 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1815     $dbh->do("ALTER TABLE `items` MODIFY COLUMN `copynumber` VARCHAR(32) DEFAULT NULL");
1816     $dbh->do("ALTER TABLE `deleteditems` MODIFY COLUMN `copynumber` VARCHAR(32) DEFAULT NULL");
1817         print "Upgrade to $DBversion done (Change data type of items.copynumber to allow free text)\n";
1818     SetVersion ($DBversion);
1819 }
1820
1821 $DBversion = "3.00.00.094";
1822 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1823     $dbh->do("ALTER TABLE `marc_subfield_structure` MODIFY `tagsubfield` VARCHAR(1) NOT NULL DEFAULT '' COLLATE utf8_bin");
1824         print "Upgrade to $DBversion done (Change Collation of marc_subfield_structure to allow mixed case in subfield labels.)\n";
1825     SetVersion ($DBversion);
1826 }
1827
1828 $DBversion = "3.00.00.095";
1829 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1830     if (C4::Context->preference("marcflavour") eq 'MARC21') {
1831         $dbh->do("UPDATE marc_subfield_structure SET authtypecode = 'MEETI_NAME' WHERE authtypecode = 'Meeting Name'");
1832         $dbh->do("UPDATE marc_subfield_structure SET authtypecode = 'CORPO_NAME' WHERE authtypecode = 'CORP0_NAME'");
1833     }
1834         print "Upgrade to $DBversion done (fix invalid authority types in MARC21 frameworks [bug 2254])\n";
1835     SetVersion ($DBversion);
1836 }
1837
1838 $DBversion = "3.00.00.096";
1839 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1840     $sth = $dbh->prepare("SHOW COLUMNS FROM borrower_message_preferences LIKE 'wants_digets'");
1841     $sth->execute();
1842     if (my $row = $sth->fetchrow_hashref) {
1843         $dbh->do("ALTER TABLE borrower_message_preferences CHANGE wants_digets wants_digest tinyint(1) NOT NULL default 0");
1844     }
1845         print "Upgrade to $DBversion done (fix name borrower_message_preferences.wants_digest)\n";
1846     SetVersion ($DBversion);
1847 }
1848
1849 $DBversion = '3.00.00.097';
1850 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1851
1852     $dbh->do('ALTER TABLE message_queue ADD to_address   mediumtext default NULL');
1853     $dbh->do('ALTER TABLE message_queue ADD from_address mediumtext default NULL');
1854     $dbh->do('ALTER TABLE message_queue ADD content_type text');
1855     $dbh->do('ALTER TABLE message_queue CHANGE borrowernumber borrowernumber int(11) default NULL');
1856
1857     print "Upgrade to $DBversion done (updating 4 fields in message_queue table)\n";
1858     SetVersion($DBversion);
1859 }
1860
1861 $DBversion = '3.00.00.098';
1862 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1863
1864     $dbh->do(q(DELETE FROM message_transport_types WHERE message_transport_type = 'rss'));
1865     $dbh->do(q(DELETE FROM message_transports WHERE message_transport_type = 'rss'));
1866
1867     print "Upgrade to $DBversion done (removing unused RSS message_transport_type)\n";
1868     SetVersion($DBversion);
1869 }
1870
1871 $DBversion = '3.00.00.099';
1872 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1873     $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')");
1874     print "Upgrade to $DBversion done (Adding OpacSuppression syspref)\n";
1875     SetVersion($DBversion);
1876 }
1877
1878 $DBversion = '3.00.00.100';
1879 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1880         $dbh->do('ALTER TABLE virtualshelves ADD COLUMN lastmodified timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP');
1881     print "Upgrade to $DBversion done (Adding lastmodified column to virtualshelves)\n";
1882     SetVersion($DBversion);
1883 }
1884
1885 $DBversion = '3.00.00.101';
1886 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1887         $dbh->do('ALTER TABLE `overduerules` CHANGE `categorycode` `categorycode` VARCHAR(10) NOT NULL');
1888         $dbh->do('ALTER TABLE `deletedborrowers` CHANGE `categorycode` `categorycode` VARCHAR(10) NOT NULL');
1889     print "Upgrade to $DBversion done (Updating columnd definitions for patron category codes in notice/statsu triggers and deletedborrowers tables.)\n";
1890     SetVersion($DBversion);
1891 }
1892
1893 $DBversion = '3.00.00.102';
1894 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1895         $dbh->do('ALTER TABLE serialitems MODIFY `serialid` int(11) NOT NULL AFTER itemnumber' );
1896         $dbh->do('ALTER TABLE serialitems DROP KEY serialididx' );
1897         $dbh->do('ALTER TABLE serialitems ADD CONSTRAINT UNIQUE KEY serialitemsidx (itemnumber)' );
1898         # before setting constraint, delete any unvalid data
1899         $dbh->do('DELETE from serialitems WHERE serialid not in (SELECT serial.serialid FROM serial)');
1900         $dbh->do('ALTER TABLE serialitems ADD CONSTRAINT serialitems_sfk_1 FOREIGN KEY (serialid) REFERENCES serial (serialid) ON DELETE CASCADE ON UPDATE CASCADE' );
1901     print "Upgrade to $DBversion done (Updating serialitems table to allow for multiple items per serial fixing kohabug 2380)\n";
1902     SetVersion($DBversion);
1903 }
1904
1905 $DBversion = "3.00.00.103";
1906 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1907     $dbh->do("DELETE FROM systempreferences WHERE variable='serialsadditems'");
1908     print "Upgrade to $DBversion done ( Verifying the removal of serialsadditems from syspref fixing kohabug 2219)\n";
1909     SetVersion ($DBversion);
1910 }
1911
1912 $DBversion = "3.00.00.104";
1913 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1914     $dbh->do("DELETE FROM systempreferences WHERE variable='noOPACHolds'");
1915     print "Upgrade to $DBversion done (remove superseded 'noOPACHolds' system preference per bug 2413)\n";
1916     SetVersion ($DBversion);
1917 }
1918
1919 $DBversion = '3.00.00.105';
1920 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
1921
1922     # it is possible that this syspref is already defined since the feature was added some time ago.
1923     unless ( $dbh->do(q(SELECT variable FROM systempreferences WHERE variable = 'SMSSendDriver')) ) {
1924         $dbh->do(<<'END_SQL');
1925 INSERT INTO `systempreferences`
1926   (variable,value,explanation,options,type)
1927 VALUES
1928 ('SMSSendDriver','','Sets which SMS::Send driver is used to send SMS messages.','','free')
1929 END_SQL
1930     }
1931     print "Upgrade to $DBversion done (added SMSSendDriver system preference)\n";
1932     SetVersion($DBversion);
1933 }
1934
1935 $DBversion = "3.00.00.106";
1936 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1937     $dbh->do("DELETE FROM systempreferences WHERE variable='noOPACHolds'");
1938
1939 # db revision 105 didn't apply correctly, so we're rolling this into 106
1940         $dbh->do("INSERT INTO `systempreferences`
1941    (variable,value,explanation,options,type)
1942         VALUES
1943         ('SMSSendDriver','','Sets which SMS::Send driver is used to send SMS messages.','','free')");
1944
1945     print "Upgrade to $DBversion done (remove default '0000-00-00' in subscriptionhistory.enddate field)\n";
1946     $dbh->do("ALTER TABLE `subscriptionhistory` CHANGE `enddate` `enddate` DATE NULL DEFAULT NULL ");
1947     $dbh->do("UPDATE subscriptionhistory SET enddate=NULL WHERE enddate='0000-00-00'");
1948     SetVersion ($DBversion);
1949 }
1950
1951 $DBversion = '3.00.00.107';
1952 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1953     $dbh->do(<<'END_SQL');
1954 UPDATE systempreferences
1955   SET explanation = CONCAT( explanation, '. WARNING: this feature is very resource consuming on collections with large numbers of items.' )
1956   WHERE variable = 'OPACShelfBrowser'
1957     AND explanation NOT LIKE '%WARNING%'
1958 END_SQL
1959     $dbh->do(<<'END_SQL');
1960 UPDATE systempreferences
1961   SET explanation = CONCAT( explanation, '. WARNING: this feature is very resource consuming.' )
1962   WHERE variable = 'CataloguingLog'
1963     AND explanation NOT LIKE '%WARNING%'
1964 END_SQL
1965     $dbh->do(<<'END_SQL');
1966 UPDATE systempreferences
1967   SET explanation = CONCAT( explanation, '. WARNING: using NoZebra on even modest sized collections is very slow.' )
1968   WHERE variable = 'NoZebra'
1969     AND explanation NOT LIKE '%WARNING%'
1970 END_SQL
1971     print "Upgrade to $DBversion done (warning added to OPACShelfBrowser system preference)\n";
1972     SetVersion ($DBversion);
1973 }
1974
1975 $DBversion = '3.01.00.000';
1976 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1977     print "Upgrade to $DBversion done (start of 3.1)\n";
1978     SetVersion ($DBversion);
1979 }
1980
1981 $DBversion = '3.01.00.001';
1982 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1983     $dbh->do("
1984         CREATE TABLE hold_fill_targets (
1985             `borrowernumber` int(11) NOT NULL,
1986             `biblionumber` int(11) NOT NULL,
1987             `itemnumber` int(11) NOT NULL,
1988             `source_branchcode`  varchar(10) default NULL,
1989             `item_level_request` tinyint(4) NOT NULL default 0,
1990             PRIMARY KEY `itemnumber` (`itemnumber`),
1991             KEY `bib_branch` (`biblionumber`, `source_branchcode`),
1992             CONSTRAINT `hold_fill_targets_ibfk_1` FOREIGN KEY (`borrowernumber`)
1993                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1994             CONSTRAINT `hold_fill_targets_ibfk_2` FOREIGN KEY (`biblionumber`)
1995                 REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1996             CONSTRAINT `hold_fill_targets_ibfk_3` FOREIGN KEY (`itemnumber`)
1997                 REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1998             CONSTRAINT `hold_fill_targets_ibfk_4` FOREIGN KEY (`source_branchcode`)
1999                 REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
2000         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2001     ");
2002     $dbh->do("
2003         ALTER TABLE tmp_holdsqueue
2004             ADD item_level_request tinyint(4) NOT NULL default 0
2005     ");
2006
2007     print "Upgrade to $DBversion done (add hold_fill_targets table and a column to tmp_holdsqueue)\n";
2008     SetVersion($DBversion);
2009 }
2010
2011 $DBversion = '3.01.00.002';
2012 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2013     # use statistics where available
2014     $dbh->do("
2015         ALTER TABLE statistics ADD KEY  tmp_stats (type, itemnumber, borrowernumber)
2016     ");
2017     $dbh->do("
2018         UPDATE issues iss
2019         SET issuedate = (
2020             SELECT max(datetime)
2021             FROM statistics
2022             WHERE type = 'issue'
2023             AND itemnumber = iss.itemnumber
2024             AND borrowernumber = iss.borrowernumber
2025         )
2026         WHERE issuedate IS NULL;
2027     ");
2028     $dbh->do("ALTER TABLE statistics DROP KEY tmp_stats");
2029
2030     # default to last renewal date
2031     $dbh->do("
2032         UPDATE issues
2033         SET issuedate = lastreneweddate
2034         WHERE issuedate IS NULL
2035         and lastreneweddate IS NOT NULL
2036     ");
2037
2038     my $num_bad_issuedates = $dbh->selectrow_array("SELECT COUNT(*) FROM issues WHERE issuedate IS NULL");
2039     if ($num_bad_issuedates > 0) {
2040         print STDERR "After the upgrade to $DBversion, there are still $num_bad_issuedates loan(s) with a NULL (blank) loan date. ",
2041                      "Please check the issues table in your database.";
2042     }
2043     print "Upgrade to $DBversion done (bug 2582: set null issues.issuedate to lastreneweddate)\n";
2044     SetVersion($DBversion);
2045 }
2046
2047 $DBversion = "3.01.00.003";
2048 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2049     $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')");
2050     print "Upgrade to $DBversion done (add new syspref)\n";
2051     SetVersion ($DBversion);
2052 }
2053
2054 $DBversion = '3.01.00.004';
2055 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2056     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACDisplayRequestPriority','0','Show patrons the priority level on holds in the OPAC','','YesNo')");
2057     print "Upgrade to $DBversion done (added OPACDisplayRequestPriority system preference)\n";
2058     SetVersion ($DBversion);
2059 }
2060
2061 $DBversion = '3.01.00.005';
2062 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2063     $dbh->do("
2064         INSERT INTO `letter` (module, code, name, title, content)
2065         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>>')
2066     ");
2067     $dbh->do("INSERT INTO `message_attributes` (message_attribute_id, message_name, takes_days) values(4, 'Hold Filled', 0)");
2068     $dbh->do("INSERT INTO `message_transports` (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) values(4, 'sms', 0, 'reserves', 'HOLD')");
2069     $dbh->do("INSERT INTO `message_transports` (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) values(4, 'email', 0, 'reserves', 'HOLD')");
2070     print "Upgrade to $DBversion done (Add letter for holds notifications)\n";
2071     SetVersion ($DBversion);
2072 }
2073
2074 $DBversion = '3.01.00.006';
2075 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2076     $dbh->do("ALTER TABLE `biblioitems` ADD KEY issn (issn)");
2077     print "Upgrade to $DBversion done (add index on biblioitems.issn)\n";
2078     SetVersion ($DBversion);
2079 }
2080
2081 $DBversion = "3.01.00.007";
2082 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2083     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='intranetmainUserblock'");
2084     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='intranetuserjs'");
2085     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='opacheader'");
2086     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='OpacMainUserBlock'");
2087     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='OpacNav'");
2088     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='opacuserjs'");
2089     $dbh->do("UPDATE `systempreferences` SET options='30|10', type='Textarea' WHERE variable='OAI-PMH:Set'");
2090     $dbh->do("UPDATE `systempreferences` SET options='50' WHERE variable='intranetstylesheet'");
2091     $dbh->do("UPDATE `systempreferences` SET options='50' WHERE variable='intranetcolorstylesheet'");
2092     $dbh->do("UPDATE `systempreferences` SET options='10' WHERE variable='globalDueDate'");
2093     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='numSearchResults'");
2094     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='OPACnumSearchResults'");
2095     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='ReservesMaxPickupDelay'");
2096     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='TransfersMaxDaysWarning'");
2097     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='StaticHoldsQueueWeight'");
2098     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='holdCancelLength'");
2099     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='XISBNDailyLimit'");
2100     $dbh->do("UPDATE `systempreferences` SET type='Float' WHERE variable='gist'");
2101     $dbh->do("UPDATE `systempreferences` SET type='Free' WHERE variable='BakerTaylorUsername'");
2102     $dbh->do("UPDATE `systempreferences` SET type='Free' WHERE variable='BakerTaylorPassword'");
2103     $dbh->do("UPDATE `systempreferences` SET type='Textarea', options='70|10' WHERE variable='ISBD'");
2104     $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'");
2105     print "Upgrade to $DBversion done (fix display of many sysprefs)\n";
2106     SetVersion ($DBversion);
2107 }
2108
2109 $DBversion = '3.01.00.008';
2110 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2111
2112     $dbh->do("CREATE TABLE branch_transfer_limits (
2113                           limitId int(8) NOT NULL auto_increment,
2114                           toBranch varchar(4) NOT NULL,
2115                           fromBranch varchar(4) NOT NULL,
2116                           itemtype varchar(4) NOT NULL,
2117                           PRIMARY KEY  (limitId)
2118                           ) ENGINE=InnoDB DEFAULT CHARSET=utf8"
2119                         );
2120
2121     $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')");
2122
2123     print "Upgrade to $DBversion done (added branch_transfer_limits table and UseBranchTransferLimits system preference)\n";
2124     SetVersion ($DBversion);
2125 }
2126
2127 $DBversion = "3.01.00.009";
2128 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2129     $dbh->do("ALTER TABLE permissions MODIFY `code` varchar(64) DEFAULT NULL");
2130     $dbh->do("ALTER TABLE user_permissions MODIFY `code` varchar(64) DEFAULT NULL");
2131     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'circulate_remaining_permissions', 'Remaining circulation permissions')");
2132     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'override_renewals', 'Override blocked renewals')");
2133     print "Upgrade to $DBversion done (added subpermissions for circulate permission)\n";
2134 }
2135
2136 $DBversion = '3.01.00.010';
2137 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2138     $dbh->do("ALTER TABLE `borrower_attributes` MODIFY COLUMN `attribute` VARCHAR(64) DEFAULT NULL");
2139     $dbh->do("ALTER TABLE `borrower_attributes` MODIFY COLUMN `password` VARCHAR(64) DEFAULT NULL");
2140     print "Upgrade to $DBversion done (bug 2687: increase length of borrower attribute fields)\n";
2141     SetVersion ($DBversion);
2142 }
2143
2144 $DBversion = '3.01.00.011';
2145 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2146
2147     # Yes, the old value was ^M terminated.
2148     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);";
2149
2150     my $intranetuserjs = C4::Context->preference('intranetuserjs');
2151     if ($intranetuserjs  and  $intranetuserjs eq $bad_value) {
2152         my $sql = <<'END_SQL';
2153 UPDATE systempreferences
2154 SET value = ''
2155 WHERE variable = 'intranetuserjs'
2156 END_SQL
2157         $dbh->do($sql);
2158     }
2159     print "Upgrade to $DBversion done (removed bogus intranetuserjs syspref)\n";
2160     SetVersion($DBversion);
2161 }
2162
2163 $DBversion = "3.01.00.012";
2164 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2165     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowHoldPolicyOverride', '0', 'Allow staff to override hold policies when placing holds',NULL,'YesNo')");
2166     $dbh->do("
2167         CREATE TABLE `branch_item_rules` (
2168           `branchcode` varchar(10) NOT NULL,
2169           `itemtype` varchar(10) NOT NULL,
2170           `holdallowed` tinyint(1) default NULL,
2171           PRIMARY KEY  (`itemtype`,`branchcode`),
2172           KEY `branch_item_rules_ibfk_2` (`branchcode`),
2173           CONSTRAINT `branch_item_rules_ibfk_1` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE,
2174           CONSTRAINT `branch_item_rules_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
2175         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2176     ");
2177     $dbh->do("
2178         CREATE TABLE `default_branch_item_rules` (
2179           `itemtype` varchar(10) NOT NULL,
2180           `holdallowed` tinyint(1) default NULL,
2181           PRIMARY KEY  (`itemtype`),
2182           CONSTRAINT `default_branch_item_rules_ibfk_1` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE
2183         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2184     ");
2185     $dbh->do("
2186         ALTER TABLE default_branch_circ_rules
2187             ADD COLUMN holdallowed tinyint(1) NULL
2188     ");
2189     $dbh->do("
2190         ALTER TABLE default_circ_rules
2191             ADD COLUMN holdallowed tinyint(1) NULL
2192     ");
2193     print "Upgrade to $DBversion done (Add tables and system preferences for holds policies)\n";
2194     SetVersion ($DBversion);
2195 }
2196
2197 $DBversion = '3.01.00.013';
2198 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2199     $dbh->do("
2200         CREATE TABLE item_circulation_alert_preferences (
2201             id           int(11) AUTO_INCREMENT,
2202             branchcode   varchar(10) NOT NULL,
2203             categorycode varchar(10) NOT NULL,
2204             item_type    varchar(10) NOT NULL,
2205             notification varchar(16) NOT NULL,
2206             PRIMARY KEY (id),
2207             KEY (branchcode, categorycode, item_type, notification)
2208         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2209     ");
2210
2211     $dbh->do(q{ ALTER TABLE `message_queue` ADD metadata text DEFAULT NULL           AFTER content;  });
2212     $dbh->do(q{ ALTER TABLE `message_queue` ADD letter_code varchar(64) DEFAULT NULL AFTER metadata; });
2213
2214     $dbh->do(q{
2215         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
2216         ('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.');
2217     });
2218     $dbh->do(q{
2219         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
2220         ('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>>.');
2221     });
2222
2223     $dbh->do(q{INSERT INTO message_attributes (message_attribute_id, message_name, takes_days) VALUES (5, 'Item Check-in', 0);});
2224     $dbh->do(q{INSERT INTO message_attributes (message_attribute_id, message_name, takes_days) VALUES (6, 'Item Checkout', 0);});
2225
2226     $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');});
2227     $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');});
2228     $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');});
2229     $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');});
2230
2231     print "Upgrade to $DBversion done (data for Email Checkout Slips project)\n";
2232          SetVersion ($DBversion);
2233 }
2234
2235 $DBversion = "3.01.00.014";
2236 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2237     $dbh->do("ALTER TABLE `branch_transfer_limits` CHANGE `itemtype` `itemtype` VARCHAR( 4 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL");
2238     $dbh->do("ALTER TABLE `branch_transfer_limits` ADD `ccode` VARCHAR( 10 ) NULL ;");
2239     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2240     VALUES (
2241     'BranchTransferLimitsType', 'ccode', 'itemtype|ccode', 'When using branch transfer limits, choose whether to limit by itemtype or collection code.', 'Choice'
2242     );");
2243
2244     print "Upgrade to $DBversion done ( Updated table for Branch Transfer Limits)\n";
2245     SetVersion ($DBversion);
2246 }
2247
2248 $DBversion = '3.01.00.015';
2249 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2250     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsClientCode', '0', 'Client Code for using Syndetics Solutions content','','free')");
2251
2252     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsEnabled', '0', 'Turn on Syndetics Enhanced Content','','YesNo')");
2253
2254     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsCoverImages', '0', 'Display Cover Images from Syndetics','','YesNo')");
2255
2256     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsTOC', '0', 'Display Table of Content information from Syndetics','','YesNo')");
2257
2258     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsSummary', '0', 'Display Summary Information from Syndetics','','YesNo')");
2259
2260     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsEditions', '0', 'Display Editions from Syndetics','','YesNo')");
2261
2262     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsExcerpt', '0', 'Display Excerpts and first chapters on OPAC from Syndetics','','YesNo')");
2263
2264     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsReviews', '0', 'Display Reviews on OPAC from Syndetics','','YesNo')");
2265
2266     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsAuthorNotes', '0', 'Display Notes about the Author on OPAC from Syndetics','','YesNo')");
2267
2268     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsAwards', '0', 'Display Awards on OPAC from Syndetics','','YesNo')");
2269
2270     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsSeries', '0', 'Display Series information on OPAC from Syndetics','','YesNo')");
2271
2272     $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')");
2273
2274     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAmazonCoverImages', '0', 'Display cover images on OPAC from Amazon Web Services','','YesNo')");
2275
2276     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AmazonCoverImages', '0', 'Display Cover Images in Staff Client from Amazon Web Services','','YesNo')");
2277
2278     $dbh->do("UPDATE systempreferences SET variable='AmazonEnabled' WHERE variable = 'AmazonContent'");
2279
2280     $dbh->do("UPDATE systempreferences SET variable='OPACAmazonEnabled' WHERE variable = 'OPACAmazonContent'");
2281
2282     print "Upgrade to $DBversion done (added Syndetics Enhanced Content system preferences)\n";
2283     SetVersion ($DBversion);
2284 }
2285
2286 $DBversion = "3.01.00.016";
2287 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2288     $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')");
2289     print "Upgrade to $DBversion done (Added Babeltheque syspref)\n";
2290     SetVersion ($DBversion);
2291 }
2292
2293 $DBversion = "3.01.00.017";
2294 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2295     $dbh->do("ALTER TABLE `subscription` ADD `staffdisplaycount` VARCHAR(10) NULL;");
2296     $dbh->do("ALTER TABLE `subscription` ADD `opacdisplaycount` VARCHAR(10) NULL;");
2297     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2298     VALUES (
2299     'StaffSerialIssueDisplayCount', '3', '', 'Number of serial issues to display per subscription in the Staff client', 'Integer'
2300     );");
2301         $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2302     VALUES (
2303     'OPACSerialIssueDisplayCount', '3', '', 'Number of serial issues to display per subscription in the OPAC', 'Integer'
2304     );");
2305
2306     print "Upgrade to $DBversion done ( Updated table for Serials Display)\n";
2307     SetVersion ($DBversion);
2308 }
2309
2310 $DBversion = "3.01.00.018";
2311 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2312     $dbh->do("ALTER TABLE deletedborrowers ADD `smsalertnumber` varchar(50) default NULL");
2313     print "Upgrade to $DBversion done (added deletedborrowers.smsalertnumber, missed in 3.00.00.091)\n";
2314     SetVersion ($DBversion);
2315 }
2316
2317 $DBversion = "3.01.00.019";
2318 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2319         $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')");
2320     print "Upgrade to $DBversion done (adding OPACShowCheckoutName systempref)\n";
2321     SetVersion ($DBversion);
2322 }
2323
2324 $DBversion = "3.01.00.020";
2325 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2326     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesID','','See:http://librarything.com/forlibraries/','','free')");
2327     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesEnabled','0','Enable or Disable Library Thing for Libraries Features','','YesNo')");
2328     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesTabbedView','0','Put LibraryThingForLibraries Content in Tabs.','','YesNo')");
2329     print "Upgrade to $DBversion done (adding LibraryThing for Libraries sysprefs)\n";
2330     SetVersion ($DBversion);
2331 }
2332
2333 $DBversion = "3.01.00.021";
2334 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2335     my $enable_reviews = C4::Context->preference('OPACAmazonEnabled') ? '1' : '0';
2336     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAmazonReviews', '$enable_reviews', 'Display Amazon readers reviews on OPAC','','YesNo')");
2337     print "Upgrade to $DBversion done (adding OPACAmazonReviews syspref)\n";
2338     SetVersion ($DBversion);
2339 }
2340
2341 $DBversion = '3.01.00.022';
2342 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2343     $dbh->do("ALTER TABLE `labels_conf` MODIFY COLUMN `formatstring` mediumtext DEFAULT NULL");
2344     print "Upgrade to $DBversion done (bug 2945: increase size of labels_conf.formatstring)\n";
2345     SetVersion ($DBversion);
2346 }
2347
2348 $DBversion = '3.01.00.023';
2349 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2350     $dbh->do("ALTER TABLE biblioitems        MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2351     $dbh->do("ALTER TABLE deletedbiblioitems MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2352     $dbh->do("ALTER TABLE import_biblios     MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2353     $dbh->do("ALTER TABLE suggestions        MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2354     print "Upgrade to $DBversion done (bug 2765: increase width of isbn column in several tables)\n";
2355     SetVersion ($DBversion);
2356 }
2357
2358 $DBversion = "3.01.00.024";
2359 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2360     $dbh->do("ALTER TABLE labels MODIFY COLUMN batch_id int(10) NOT NULL default 1;");
2361     print "Upgrade to $DBversion done (change labels.batch_id from varchar to int)\n";
2362     SetVersion ($DBversion);
2363 }
2364
2365 $DBversion = '3.01.00.025';
2366 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2367     $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')");
2368
2369     print "Upgrade to $DBversion done (added ceilingDueDate system preference)\n";
2370     SetVersion ($DBversion);
2371 }
2372
2373 $DBversion = '3.01.00.026';
2374 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2375     $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')");
2376
2377     print "Upgrade to $DBversion done (added numReturnedItemsToShow system preference)\n";
2378     SetVersion ($DBversion);
2379 }
2380
2381 $DBversion = '3.01.00.027';
2382 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2383     $dbh->do("ALTER TABLE zebraqueue CHANGE `biblio_auth_number` `biblio_auth_number` bigint(20) unsigned NOT NULL default 0");
2384     print "Upgrade to $DBversion done (Increased size of zebraqueue biblio_auth_number to address bug 3148.)\n";
2385     SetVersion ($DBversion);
2386 }
2387
2388 $DBversion = '3.01.00.028';
2389 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2390     my $enable_reviews = C4::Context->preference('AmazonEnabled') ? '1' : '0';
2391     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AmazonReviews', '$enable_reviews', 'Display Amazon reviews on staff interface','','YesNo')");
2392     print "Upgrade to $DBversion done (added AmazonReviews)\n";
2393     SetVersion ($DBversion);
2394 }
2395
2396 $DBversion = '3.01.00.029';
2397 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2398     $dbh->do(q( UPDATE language_rfc4646_to_iso639
2399                 SET iso639_2_code = 'spa'
2400                 WHERE rfc4646_subtag = 'es'
2401                 AND   iso639_2_code = 'rus' )
2402             );
2403     print "Upgrade to $DBversion done (fixed bug 2599: using Spanish search limit retrieves Russian results)\n";
2404     SetVersion ($DBversion);
2405 }
2406
2407 $DBversion = "3.01.00.030";
2408 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2409     $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')");
2410     print "Upgrade to $DBversion done (added AllowNotForLoanOverride system preference)\n";
2411     SetVersion ($DBversion);
2412 }
2413
2414 $DBversion = "3.01.00.031";
2415 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2416     $dbh->do("ALTER TABLE branch_transfer_limits
2417               MODIFY toBranch   varchar(10) NOT NULL,
2418               MODIFY fromBranch varchar(10) NOT NULL,
2419               MODIFY itemtype   varchar(10) NULL");
2420     print "Upgrade to $DBversion done (fix column widths in branch_transfer_limits)\n";
2421     SetVersion ($DBversion);
2422 }
2423
2424 $DBversion = "3.01.00.032";
2425 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2426     $dbh->do(<<ENDOFRENEWAL);
2427 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');
2428 ENDOFRENEWAL
2429     print "Upgrade to $DBversion done (Change the field)\n";
2430     SetVersion ($DBversion);
2431 }
2432
2433 $DBversion = "3.01.00.033";
2434 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2435     $dbh->do(q/
2436         ALTER TABLE borrower_message_preferences
2437         MODIFY borrowernumber int(11) default NULL,
2438         ADD    categorycode varchar(10) default NULL AFTER borrowernumber,
2439         ADD KEY `categorycode` (`categorycode`),
2440         ADD CONSTRAINT `borrower_message_preferences_ibfk_3`
2441                        FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
2442                        ON DELETE CASCADE ON UPDATE CASCADE
2443     /);
2444     print "Upgrade to $DBversion done (DB changes to allow patron category defaults for messaging preferences)\n";
2445     SetVersion ($DBversion);
2446 }
2447
2448 $DBversion = "3.01.00.034";
2449 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2450     $dbh->do("ALTER TABLE `subscription` ADD COLUMN `graceperiod` INT(11) NOT NULL default '0';");
2451     print "Upgrade to $DBversion done (Adding graceperiod column to subscription table)\n";
2452     SetVersion ($DBversion);
2453 }
2454
2455 $DBversion = '3.01.00.035';
2456 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2457     $dbh->do(q{ ALTER TABLE `subscription` ADD location varchar(80) NULL DEFAULT '' AFTER callnumber; });
2458    print "Upgrade to $DBversion done (Adding location to subscription table)\n";
2459     SetVersion ($DBversion);
2460 }
2461
2462 $DBversion = '3.01.00.036';
2463 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2464     $dbh->do("UPDATE systempreferences SET explanation = 'Choose the default detail view in the staff interface; choose between normal, labeled_marc, marc or isbd'
2465               WHERE variable = 'IntranetBiblioDefaultView'
2466               AND   explanation = 'IntranetBiblioDefaultView'");
2467     $dbh->do("UPDATE systempreferences SET type = 'Choice', options = 'normal|marc|isbd|labeled_marc'
2468               WHERE variable = 'IntranetBiblioDefaultView'");
2469     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewISBD','1','Allow display of ISBD view of bibiographic records','','YesNo')");
2470     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewLabeledMARC','0','Allow display of labeled MARC view of bibiographic records','','YesNo')");
2471     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewMARC','1','Allow display of MARC view of bibiographic records','','YesNo')");
2472     print "Upgrade to $DBversion done (new viewISBD, viewLabeledMARC, viewMARC sysprefs and tweak IntranetBiblioDefaultView)\n";
2473     SetVersion ($DBversion);
2474 }
2475
2476 $DBversion = '3.01.00.037';
2477 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2478     $dbh->do('ALTER TABLE authorised_values ADD KEY `lib` (`lib`)');
2479     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('FilterBeforeOverdueReport','0','Do not run overdue report until filter selected','','YesNo')");
2480     SetVersion ($DBversion);
2481     print "Upgrade to $DBversion done (added FilterBeforeOverdueReport syspref and new index on authorised_values)\n";
2482 }
2483
2484 $DBversion = "3.01.00.038";
2485 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2486     # update branches table
2487     #
2488     $dbh->do("ALTER TABLE branches ADD `branchzip` varchar(25) default NULL AFTER `branchaddress3`");
2489     $dbh->do("ALTER TABLE branches ADD `branchcity` mediumtext AFTER `branchzip`");
2490     $dbh->do("ALTER TABLE branches ADD `branchcountry` text AFTER `branchcity`");
2491     $dbh->do("ALTER TABLE branches ADD `branchurl` mediumtext AFTER `branchemail`");
2492     $dbh->do("ALTER TABLE branches ADD `branchnotes` mediumtext AFTER `branchprinter`");
2493     print "Upgrade to $DBversion done (add ZIP, city, country, URL, and notes column to branches)\n";
2494     SetVersion ($DBversion);
2495 }
2496
2497 $DBversion = '3.01.00.039';
2498 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2499     $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')");
2500     $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')");
2501     SetVersion ($DBversion);
2502     print "Upgrade to $DBversion done (added SpineLabelFormat and SpineLabelAutoPrint sysprefs)\n";
2503 }
2504
2505 $DBversion = '3.01.00.040';
2506 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2507     $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')");
2508     $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')");
2509     SetVersion ($DBversion);
2510     print "Upgrade to $DBversion done (AllowHoldDateInFuture and OPACAllowHoldDateInFuture sysprefs)\n";
2511 }
2512
2513 $DBversion = '3.01.00.041';
2514 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2515     $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')");
2516     SetVersion ($DBversion);
2517     print "Upgrade to $DBversion done (added AWSPrivateKey syspref - note that if you use enhanced content from Amazon, this should be set right away.)\n";
2518 }
2519
2520 $DBversion = '3.01.00.042';
2521 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2522     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACFineNoRenewals','99999','Fine Limit above which user canmot renew books via OPAC','','Integer')");
2523     SetVersion ($DBversion);
2524     print "Upgrade to $DBversion done (added OPACFineNoRenewals syspref)\n";
2525 }
2526
2527 $DBversion = '3.01.00.043';
2528 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2529     $dbh->do('ALTER TABLE items ADD COLUMN permanent_location VARCHAR(80) DEFAULT NULL AFTER location');
2530     $dbh->do('UPDATE items SET permanent_location = location');
2531     $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 )', '')");
2532     $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')");
2533     $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')");
2534     SetVersion ($DBversion);
2535     print "Upgrade to $DBversion done (amended Item added NewItemsDefaultLocation, InProcessingToShelvingCart, ReturnToShelvingCart sysprefs)\n";
2536 }
2537
2538 $DBversion = '3.01.00.044';
2539 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2540     $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')");
2541     SetVersion ($DBversion);
2542     print "Upgrade to $DBversion done (added DisplayClearScreenButton system preference)\n";
2543 }
2544
2545 $DBversion = '3.01.00.045';
2546 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2547     $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')");
2548     SetVersion ($DBversion);
2549     print "Upgrade to $DBversion done (added a preference to hide the patrons name in the staff catalog)\n";
2550 }
2551
2552 $DBversion = "3.01.00.046";
2553 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2554     # update borrowers table
2555     #
2556     $dbh->do("ALTER TABLE borrowers ADD `country` text AFTER zipcode");
2557     $dbh->do("ALTER TABLE borrowers ADD `B_country` text AFTER B_zipcode");
2558     $dbh->do("ALTER TABLE deletedborrowers ADD `country` text AFTER zipcode");
2559     $dbh->do("ALTER TABLE deletedborrowers ADD `B_country` text AFTER B_zipcode");
2560     print "Upgrade to $DBversion done (add country and B_country to borrowers)\n";
2561     SetVersion ($DBversion);
2562 }
2563
2564 $DBversion = '3.01.00.047';
2565 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2566     $dbh->do("ALTER TABLE items MODIFY itemcallnumber varchar(255);");
2567     $dbh->do("ALTER TABLE deleteditems MODIFY itemcallnumber varchar(255);");
2568     $dbh->do("ALTER TABLE tmp_holdsqueue MODIFY itemcallnumber varchar(255);");
2569     SetVersion ($DBversion);
2570     print " Upgrade to $DBversion done (bug 2761: change max length of itemcallnumber to 255 from 30)\n";
2571 }
2572
2573 $DBversion = '3.01.00.048';
2574 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2575     $dbh->do("UPDATE userflags SET flagdesc='View Catalog (Librarian Interface)' WHERE bit=2;");
2576     $dbh->do("UPDATE userflags SET flagdesc='Edit Catalog (Modify bibliographic/holdings data)' WHERE bit=9;");
2577     $dbh->do("UPDATE userflags SET flagdesc='Allow to edit authorities' WHERE bit=14;");
2578     $dbh->do("UPDATE userflags SET flagdesc='Allow to access to the reports module' WHERE bit=16;");
2579     $dbh->do("UPDATE userflags SET flagdesc='Allow to manage serials subscriptions' WHERE bit=15;");
2580     SetVersion ($DBversion);
2581     print " Upgrade to $DBversion done (bug 2611: fix spelling/capitalization in permission flag descriptions)\n";
2582 }
2583
2584 $DBversion = '3.01.00.049';
2585 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2586     $dbh->do("UPDATE permissions SET description = 'Perform inventory (stocktaking) of your catalog' WHERE code = 'inventory';");
2587      SetVersion ($DBversion);
2588     print "Upgrade to $DBversion done (bug 2611: changed catalogue to catalog per the standard)\n";
2589 }
2590
2591 $DBversion = '3.01.00.050';
2592 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2593     $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');");
2594     SetVersion ($DBversion);
2595     print "Upgrade to $DBversion done (bug 1934: Add OPACSearchForTitleIn syspref)\n";
2596 }
2597
2598 $DBversion = '3.01.00.051';
2599 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2600     $dbh->do("UPDATE systempreferences SET explanation='Fine limit above which user cannot renew books via OPAC' WHERE variable='OPACFineNoRenewals';");
2601     $dbh->do("UPDATE systempreferences SET explanation='If set to ON, a clear screen button will appear on the circulation page.' WHERE variable='DisplayClearScreenButton';");
2602     SetVersion ($DBversion);
2603     print "Upgrade to $DBversion done (fixed typos in new sysprefs)\n";
2604 }
2605
2606 $DBversion = '3.01.00.052';
2607 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2608     $dbh->do('ALTER TABLE deleteditems ADD COLUMN permanent_location VARCHAR(80) DEFAULT NULL AFTER location');
2609     SetVersion ($DBversion);
2610     print "Upgrade to $DBversion done (bug 3481: add permanent_location column to deleteditems)\n";
2611 }
2612
2613 $DBversion = '3.01.00.053';
2614 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2615     my $upgrade_script = C4::Context->config("intranetdir") . "/installer/data/mysql/labels_upgrade.pl";
2616     system("perl $upgrade_script");
2617     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";
2618     SetVersion ($DBversion);
2619 }
2620
2621 $DBversion = '3.01.00.054';
2622 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2623     $dbh->do("ALTER TABLE borrowers ADD `B_address2` text AFTER B_address");
2624     $dbh->do("ALTER TABLE borrowers ADD `altcontactcountry` text AFTER altcontactzipcode");
2625     $dbh->do("ALTER TABLE deletedborrowers ADD `B_address2` text AFTER B_address");
2626     $dbh->do("ALTER TABLE deletedborrowers ADD `altcontactcountry` text AFTER altcontactzipcode");
2627     SetVersion ($DBversion);
2628     print "Upgrade to $DBversion done (bug 1600, bug 3454: add altcontactcountry and B_address2 to borrowers and deletedborrowers)\n";
2629 }
2630
2631 $DBversion = '3.01.00.055';
2632 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2633     $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'|);
2634     SetVersion ($DBversion);
2635     print "Upgrade to $DBversion done (changed OPACSearchForTitleIn per requests in bug 1934)\n";
2636 }
2637
2638 $DBversion = '3.01.00.056';
2639 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2640     $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');");
2641     SetVersion ($DBversion);
2642     print "Upgrade to $DBversion done (Bug 1172 : Add OPACPatronDetails syspref)\n";
2643 }
2644
2645 $DBversion = '3.01.00.057';
2646 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2647     $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');");
2648     SetVersion ($DBversion);
2649     print "Upgrade to $DBversion done (Bug 2576 : Add OPACFinesTab syspref)\n";
2650 }
2651
2652 $DBversion = '3.01.00.058';
2653 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2654     $dbh->do("ALTER TABLE `language_subtag_registry` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2655     $dbh->do("ALTER TABLE `language_rfc4646_to_iso639` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2656     $dbh->do("ALTER TABLE `language_descriptions` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2657     SetVersion ($DBversion);
2658     print "Upgrade to $DBversion done (Added primary keys to language tables)\n";
2659 }
2660
2661 $DBversion = '3.01.00.059';
2662 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2663     $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')");
2664     SetVersion ($DBversion);
2665     print "Upgrade to $DBversion done (added DisplayOPACiconsXSLT sysprefs)\n";
2666 }
2667
2668 $DBversion = '3.01.00.060';
2669 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2670     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowAllMessageDeletion','0','Allow any Library to delete any message','','YesNo');");
2671     $dbh->do('DROP TABLE IF EXISTS messages');
2672     $dbh->do("CREATE TABLE messages ( `message_id` int(11) NOT NULL auto_increment,
2673         `borrowernumber` int(11) NOT NULL,
2674         `branchcode` varchar(4) default NULL,
2675         `message_type` varchar(1) NOT NULL,
2676         `message` text NOT NULL,
2677         `message_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
2678         PRIMARY KEY (`message_id`)
2679         ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
2680
2681         print "Upgrade to $DBversion done ( Added AllowAllMessageDeletion syspref and messages table )\n";
2682     SetVersion ($DBversion);
2683 }
2684
2685 $DBversion = '3.01.00.061';
2686 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2687     $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')");
2688         print "Upgrade to $DBversion done ( Added ShowPatronImageInWebBasedSelfCheck system preference )\n";
2689     SetVersion ($DBversion);
2690 }
2691
2692 $DBversion = "3.01.00.062";
2693 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2694     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'manage_csv_profiles', 'Manage CSV export profiles')");
2695     $dbh->do(q/
2696         CREATE TABLE `export_format` (
2697           `export_format_id` int(11) NOT NULL auto_increment,
2698           `profile` varchar(255) NOT NULL,
2699           `description` mediumtext NOT NULL,
2700           `marcfields` mediumtext NOT NULL,
2701           PRIMARY KEY  (`export_format_id`)
2702         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Used for CSV export';
2703     /);
2704     print "Upgrade to $DBversion done (added csv export profiles)\n";
2705 }
2706
2707 $DBversion = "3.01.00.063";
2708 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2709     $dbh->do("
2710         CREATE TABLE `fieldmapping` (
2711           `id` int(11) NOT NULL auto_increment,
2712           `field` varchar(255) NOT NULL,
2713           `frameworkcode` char(4) NOT NULL default '',
2714           `fieldcode` char(3) NOT NULL,
2715           `subfieldcode` char(1) NOT NULL,
2716           PRIMARY KEY  (`id`)
2717         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2718              ");
2719     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";
2720 }
2721
2722 $DBversion = '3.01.00.065';
2723 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2724     $dbh->do('ALTER TABLE issuingrules ADD COLUMN `renewalsallowed` smallint(6) NOT NULL default "0" AFTER `issuelength`;');
2725     $sth = $dbh->prepare("SELECT itemtype, renewalsallowed FROM itemtypes");
2726     $sth->execute();
2727
2728     my $sthupd = $dbh->prepare("UPDATE issuingrules SET renewalsallowed = ? WHERE itemtype = ?");
2729
2730     while(my $row = $sth->fetchrow_hashref){
2731         $sthupd->execute($row->{renewalsallowed}, $row->{itemtype});
2732     }
2733
2734     $dbh->do('ALTER TABLE itemtypes DROP COLUMN `renewalsallowed`;');
2735
2736     SetVersion ($DBversion);
2737     print "Upgrade to $DBversion done (Moving allowed renewals from itemtypes to issuingrule)\n";
2738 }
2739
2740 $DBversion = '3.01.00.066';
2741 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2742     $dbh->do('ALTER TABLE issuingrules ADD COLUMN `reservesallowed` smallint(6) NOT NULL default "0" AFTER `renewalsallowed`;');
2743     
2744     my $maxreserves = C4::Context->preference('maxreserves');
2745     $sth = $dbh->prepare('UPDATE issuingrules SET reservesallowed = ?;');
2746     $sth->execute($maxreserves);
2747
2748     $dbh->do('DELETE FROM systempreferences WHERE variable = "maxreserves";');
2749
2750     $dbh->do("INSERT INTO systempreferences (variable,value, options, explanation, type) VALUES('ReservesControlBranch','PatronLibrary','ItemHomeLibrary|PatronLibrary','Branch checked for members reservations rights','Choice')");
2751
2752     SetVersion ($DBversion);
2753     print "Upgrade to $DBversion done (Moving max allowed reserves from system preference to issuingrule)\n";
2754 }
2755
2756 $DBversion = "3.01.00.067";
2757 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2758     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'batchmod', 'Perform batch modification of items')");
2759     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'batchdel', 'Perform batch deletion of items')");
2760     print "Upgrade to $DBversion done (added permissions for batch modification and deletion)\n";
2761     SetVersion ($DBversion);
2762 }
2763
2764 $DBversion = "3.01.00.068";
2765 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2766         $dbh->do("ALTER TABLE issuingrules ADD COLUMN `finedays` int(11) default NULL AFTER `fine` ");
2767         print "Upgrade to $DBversion done (Adding finedays in issuingrules table)\n";
2768     SetVersion ($DBversion);
2769 }
2770
2771
2772 $DBversion = "3.01.00.069";
2773 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2774         $dbh->do("INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('EnableOpacSearchHistory', '1', '', 'Enable or disable opac search history', 'YesNo')");
2775
2776         my $create = <<SEARCHHIST;
2777 CREATE TABLE IF NOT EXISTS `search_history` (
2778   `userid` int(11) NOT NULL,
2779   `sessionid` varchar(32) NOT NULL,
2780   `query_desc` varchar(255) NOT NULL,
2781   `query_cgi` varchar(255) NOT NULL,
2782   `total` int(11) NOT NULL,
2783   `time` timestamp NOT NULL default CURRENT_TIMESTAMP,
2784   KEY `userid` (`userid`),
2785   KEY `sessionid` (`sessionid`)
2786 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Opac search history results';
2787 SEARCHHIST
2788         $dbh->do($create);
2789
2790         print "Upgrade to $DBversion done (added OPAC search history preference and table)\n";
2791 }
2792
2793 $DBversion = "3.01.00.070";
2794 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2795         $dbh->do("ALTER TABLE authorised_values ADD COLUMN `lib_opac` VARCHAR(80) default NULL AFTER `lib`");
2796         print "Upgrade to $DBversion done (Added a lib_opac field in authorised_values table)\n";
2797 }
2798
2799 $DBversion = "3.01.00.071";
2800 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2801         $dbh->do("ALTER TABLE `subscription` ADD `enddate` date default NULL");
2802         $dbh->do("ALTER TABLE subscriptionhistory CHANGE enddate histenddate DATE default NULL");
2803         print "Upgrade to $DBversion done ( Adding enddate to subscription)\n";
2804 }
2805
2806 # Acquisitions update
2807
2808 $DBversion = "3.01.00.072";
2809 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2810     $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')");
2811     # create a new syspref for the 'Mr anonymous' patron
2812     $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,'')");
2813     # fill AnonymousPatron with AnonymousSuggestion value (copy)
2814     my $sth=$dbh->prepare("SELECT value FROM systempreferences WHERE variable='AnonSuggestions'");
2815     $sth->execute;
2816     my ($value) = $sth->fetchrow() || 0;
2817     $dbh->do("UPDATE systempreferences SET value='$value' WHERE variable='AnonymousPatron'");
2818     # set AnonymousSuggestion do YesNo
2819     # 1st, set the value (1/True if it had a borrowernumber)
2820     $dbh->do("UPDATE systempreferences SET value=1 WHERE variable='AnonSuggestions' AND value>0");
2821     # 2nd, change the type to Choice
2822     $dbh->do("UPDATE systempreferences SET type='YesNo' WHERE variable='AnonSuggestions'");
2823         # borrower reading record privacy : 0 : forever, 1 : laws, 2 : don't keep at all
2824     $dbh->do("ALTER TABLE `borrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
2825     print "Upgrade to $DBversion done (add new syspref and column in borrowers)\n";
2826     SetVersion ($DBversion);
2827 }
2828
2829 $DBversion = '3.01.00.073';
2830 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2831     $dbh->do('SET FOREIGN_KEY_CHECKS=0 ');
2832     $dbh->do(<<'END_SQL');
2833 CREATE TABLE IF NOT EXISTS `aqcontract` (
2834   `contractnumber` int(11) NOT NULL auto_increment,
2835   `contractstartdate` date default NULL,
2836   `contractenddate` date default NULL,
2837   `contractname` varchar(50) default NULL,
2838   `contractdescription` mediumtext,
2839   `booksellerid` int(11) not NULL,
2840     PRIMARY KEY  (`contractnumber`),
2841         CONSTRAINT `booksellerid_fk1` FOREIGN KEY (`booksellerid`)
2842         REFERENCES `aqbooksellers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
2843 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
2844 END_SQL
2845     $dbh->do('SET FOREIGN_KEY_CHECKS=1 ');
2846     print "Upgrade to $DBversion done (adding aqcontract table)\n";
2847     SetVersion ($DBversion);
2848 }
2849
2850 $DBversion = '3.01.00.074';
2851 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2852     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `basketname` varchar(50) default NULL AFTER `basketno`");
2853     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `note` mediumtext AFTER `basketname`");
2854     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `booksellernote` mediumtext AFTER `note`");
2855     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `contractnumber` int(11) AFTER `booksellernote`");
2856     $dbh->do("ALTER TABLE `aqbasket` ADD FOREIGN KEY (`contractnumber`) REFERENCES `aqcontract` (`contractnumber`)");
2857     print "Upgrade to $DBversion done (edit aqbasket table done)\n";
2858     SetVersion ($DBversion);
2859 }
2860
2861 $DBversion = '3.01.00.075';
2862 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2863     $dbh->do("ALTER TABLE `aqorders` ADD COLUMN `uncertainprice` tinyint(1)");
2864
2865     print "Upgrade to $DBversion done (adding uncertainprices)\n";
2866     SetVersion ($DBversion);
2867 }
2868
2869 $DBversion = '3.01.00.076';
2870 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2871     $dbh->do('SET FOREIGN_KEY_CHECKS=0 ');
2872     $dbh->do("CREATE TABLE IF NOT EXISTS `aqbasketgroups` (
2873                          `id` int(11) NOT NULL auto_increment,
2874                          `name` varchar(50) default NULL,
2875                          `closed` tinyint(1) default NULL,
2876                          `booksellerid` int(11) NOT NULL,
2877                          PRIMARY KEY (`id`),
2878                          KEY `booksellerid` (`booksellerid`),
2879                          CONSTRAINT `aqbasketgroups_ibfk_1` FOREIGN KEY (`booksellerid`) REFERENCES `aqbooksellers` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
2880                          ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
2881     $dbh->do("ALTER TABLE aqbasket ADD COLUMN `basketgroupid` int(11)");
2882     $dbh->do("ALTER TABLE aqbasket ADD FOREIGN KEY (`basketgroupid`) REFERENCES `aqbasketgroups` (`id`) ON UPDATE CASCADE ON DELETE SET NULL");
2883     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('pdfformat','pdfformat::layout2pages','Controls what script is used for printing (basketgroups)','','free')");
2884     $dbh->do('SET FOREIGN_KEY_CHECKS=1 ');
2885     print "Upgrade to $DBversion done (adding basketgroups)\n";
2886     SetVersion ($DBversion);
2887 }
2888 $DBversion = '3.01.00.077';
2889 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2890
2891     $dbh->do("SET FOREIGN_KEY_CHECKS=0 ");
2892     # create a mapping table holding the info we need to match orders to budgets
2893     $dbh->do('DROP TABLE IF EXISTS fundmapping');
2894     $dbh->do(
2895         q|CREATE TABLE fundmapping AS
2896         SELECT aqorderbreakdown.ordernumber, branchcode, bookfundid, budgetdate, entrydate
2897         FROM aqorderbreakdown JOIN aqorders ON aqorderbreakdown.ordernumber = aqorders.ordernumber|);
2898     # match the new type of the corresponding field
2899     $dbh->do('ALTER TABLE fundmapping modify column bookfundid varchar(30)');
2900     # System did not ensure budgetdate was valid historically
2901     $dbh->do(q|UPDATE fundmapping SET budgetdate = entrydate WHERE budgetdate = '0000-00-00' OR budgetdate IS NULL|);
2902     # We save the map in fundmapping in case you need later processing
2903     $dbh->do(q|ALTER TABLE fundmapping add column aqbudgetid integer|);
2904     # these can speed processing up
2905     $dbh->do(q|CREATE INDEX fundmaporder ON fundmapping (ordernumber)|);
2906     $dbh->do(q|CREATE INDEX fundmapid ON fundmapping (bookfundid)|);
2907
2908     $dbh->do("DROP TABLE IF EXISTS `aqbudgetperiods` ");
2909
2910     $dbh->do(qq|
2911                     CREATE TABLE `aqbudgetperiods` (
2912                     `budget_period_id` int(11) NOT NULL auto_increment,
2913                     `budget_period_startdate` date NOT NULL,
2914                     `budget_period_enddate` date NOT NULL,
2915                     `budget_period_active` tinyint(1) default '0',
2916                     `budget_period_description` mediumtext,
2917                     `budget_period_locked` tinyint(1) default NULL,
2918                     `sort1_authcat` varchar(10) default NULL,
2919                     `sort2_authcat` varchar(10) default NULL,
2920                     PRIMARY KEY  (`budget_period_id`)
2921                     ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 |);
2922
2923    $dbh->do(<<ADDPERIODS);
2924 INSERT INTO aqbudgetperiods (budget_period_startdate,budget_period_enddate,budget_period_active,budget_period_description,budget_period_locked)
2925 SELECT DISTINCT startdate, enddate, NOW() BETWEEN startdate and enddate, concat(startdate," ",enddate),NOT NOW() BETWEEN startdate AND enddate from aqbudget
2926 ADDPERIODS
2927 # SORRY , NO AQBUDGET/AQBOOKFUND -> AQBUDGETS IMPORT JUST YET,
2928 # BUT A NEW CLEAN AQBUDGETS TABLE CREATE FOR NOW..
2929 # DROP TABLE IF EXISTS `aqbudget`;
2930 #CREATE TABLE `aqbudget` (
2931 #  `bookfundid` varchar(10) NOT NULL default ',
2932 #    `startdate` date NOT NULL default 0,
2933 #         `enddate` date default NULL,
2934 #           `budgetamount` decimal(13,2) default NULL,
2935 #                 `aqbudgetid` tinyint(4) NOT NULL auto_increment,
2936 #                   `branchcode` varchar(10) default NULL,
2937     DropAllForeignKeys('aqbudget');
2938   #$dbh->do("drop table aqbudget;");
2939
2940
2941     my $maxbudgetid = $dbh->selectcol_arrayref(<<IDsBUDGET);
2942 SELECT MAX(aqbudgetid) from aqbudget
2943 IDsBUDGET
2944
2945 $$maxbudgetid[0] = 0 if !$$maxbudgetid[0];
2946
2947     $dbh->do(<<BUDGETAUTOINCREMENT);
2948 ALTER TABLE aqbudget AUTO_INCREMENT=$$maxbudgetid[0]
2949 BUDGETAUTOINCREMENT
2950     
2951     $dbh->do(<<BUDGETNAME);
2952 ALTER TABLE aqbudget RENAME `aqbudgets`
2953 BUDGETNAME
2954
2955     $dbh->do(<<BUDGETS);
2956 ALTER TABLE `aqbudgets`
2957    CHANGE  COLUMN aqbudgetid `budget_id` int(11) NOT NULL AUTO_INCREMENT,
2958    CHANGE  COLUMN branchcode `budget_branchcode` varchar(10) default NULL,
2959    CHANGE  COLUMN budgetamount `budget_amount` decimal(28,6) NOT NULL default '0.00',
2960    CHANGE  COLUMN bookfundid   `budget_code` varchar(30) default NULL,
2961    ADD     COLUMN `budget_parent_id` int(11) default NULL,
2962    ADD     COLUMN `budget_name` varchar(80) default NULL,
2963    ADD     COLUMN `budget_encumb` decimal(28,6) default '0.00',
2964    ADD     COLUMN `budget_expend` decimal(28,6) default '0.00',
2965    ADD     COLUMN `budget_notes` mediumtext,
2966    ADD     COLUMN `budget_description` mediumtext,
2967    ADD     COLUMN `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
2968    ADD     COLUMN `budget_amount_sublevel`  decimal(28,6) AFTER `budget_amount`,
2969    ADD     COLUMN `budget_period_id` int(11) default NULL,
2970    ADD     COLUMN `sort1_authcat` varchar(80) default NULL,
2971    ADD     COLUMN `sort2_authcat` varchar(80) default NULL,
2972    ADD     COLUMN `budget_owner_id` int(11) default NULL,
2973    ADD     COLUMN `budget_permission` int(1) default '0';
2974 BUDGETS
2975
2976     $dbh->do(<<BUDGETCONSTRAINTS);
2977 ALTER TABLE `aqbudgets`
2978    ADD CONSTRAINT `aqbudgets_ifbk_1` FOREIGN KEY (`budget_period_id`) REFERENCES `aqbudgetperiods` (`budget_period_id`) ON DELETE CASCADE ON UPDATE CASCADE
2979 BUDGETCONSTRAINTS
2980 #    $dbh->do(<<BUDGETPKDROP);
2981 #ALTER TABLE `aqbudgets`
2982 #   DROP PRIMARY KEY
2983 #BUDGETPKDROP
2984 #    $dbh->do(<<BUDGETPKADD);
2985 #ALTER TABLE `aqbudgets`
2986 #   ADD PRIMARY KEY budget_id
2987 #BUDGETPKADD
2988
2989
2990         my $query_period= $dbh->prepare(qq|SELECT budget_period_id from aqbudgetperiods where budget_period_startdate=? and budget_period_enddate=?|);
2991         my $query_bookfund= $dbh->prepare(qq|SELECT * from aqbookfund where bookfundid=?|);
2992         my $selectbudgets=$dbh->prepare(qq|SELECT * from aqbudgets|);
2993         my $updatebudgets=$dbh->prepare(qq|UPDATE aqbudgets SET budget_period_id= ? , budget_name=?, budget_branchcode=? where budget_id=?|);
2994         $selectbudgets->execute;
2995         while (my $databudget=$selectbudgets->fetchrow_hashref){
2996                 $query_period->execute ($$databudget{startdate},$$databudget{enddate});
2997                 my ($budgetperiodid)=$query_period->fetchrow;
2998                 $query_bookfund->execute ($$databudget{budget_code});
2999                 my $databf=$query_bookfund->fetchrow_hashref;
3000                 my $branchcode=$$databudget{budget_branchcode}||$$databf{branchcode};
3001                 $updatebudgets->execute($budgetperiodid,$$databf{bookfundname},$branchcode,$$databudget{budget_id});
3002         }
3003     $dbh->do(<<BUDGETDROPDATES);
3004 ALTER TABLE `aqbudgets`
3005    DROP startdate,
3006    DROP enddate
3007 BUDGETDROPDATES
3008
3009
3010     $dbh->do("DROP TABLE IF EXISTS `aqbudgets_planning` ");
3011     $dbh->do("CREATE TABLE  `aqbudgets_planning` (
3012                     `plan_id` int(11) NOT NULL auto_increment,
3013                     `budget_id` int(11) NOT NULL,
3014                     `budget_period_id` int(11) NOT NULL,
3015                     `estimated_amount` decimal(28,6) default NULL,
3016                     `authcat` varchar(30) NOT NULL,
3017                     `authvalue` varchar(30) NOT NULL,
3018                                         `display` tinyint(1) DEFAULT 1,
3019                         PRIMARY KEY  (`plan_id`),
3020                         CONSTRAINT `aqbudgets_planning_ifbk_1` FOREIGN KEY (`budget_id`) REFERENCES `aqbudgets` (`budget_id`) ON DELETE CASCADE ON UPDATE CASCADE
3021                         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
3022
3023     $dbh->do("ALTER TABLE `aqorders`
3024                     ADD COLUMN `budget_id` tinyint(4) NOT NULL,
3025                     ADD COLUMN `budgetgroup_id` int(11) NOT NULL,
3026                     ADD COLUMN  `sort1_authcat` varchar(10) default NULL,
3027                     ADD COLUMN  `sort2_authcat` varchar(10) default NULL" );
3028                 # We need to map the orders to the budgets
3029                 # For Historic reasons this is more complex than it should be on occasions
3030                 my $budg_arr = $dbh->selectall_arrayref(
3031                     q|SELECT aqbudgets.budget_id, aqbudgets.budget_code, aqbudgetperiods.budget_period_startdate,
3032                     aqbudgetperiods.budget_period_enddate
3033                     FROM aqbudgets JOIN aqbudgetperiods ON aqbudgets.budget_period_id = aqbudgetperiods.budget_period_id
3034                     ORDER BY budget_code, budget_period_startdate|, { Slice => {} });
3035                 # We arbitarily order on start date, this means if you have overlapping periods the order will be
3036                 # linked to the latest matching budget YMMV
3037                 my $b_sth = $dbh->prepare(
3038                     'UPDATE fundmapping set aqbudgetid = ? where bookfundid =? AND budgetdate >= ? AND budgetdate <= ?');
3039                 for my $b ( @{$budg_arr}) {
3040                     $b_sth->execute($b->{budget_id}, $b->{budget_code}, $b->{budget_period_startdate}, $b->{budget_period_enddate});
3041                 }
3042                 # move the budgetids to aqorders
3043                 $dbh->do(q|UPDATE aqorders, fundmapping SET aqorders.budget_id = fundmapping.aqbudgetid
3044                     WHERE aqorders.ordernumber = fundmapping.ordernumber AND fundmapping.aqbudgetid IS NOT NULL|);
3045                 # NB fundmapping is left as an accontants trail also if you have budgetids that werent set
3046                 # you can decide what to do with them
3047
3048      $dbh->do(
3049          q|UPDATE aqorders, aqbudgets SET aqorders.budgetgroup_id = aqbudgets.budget_period_id
3050          WHERE aqorders.budget_id = aqbudgets.budget_id|);
3051                 # cannot do until aqorderbreakdown removed
3052 #    $dbh->do("DROP TABLE aqbookfund ");
3053 #    $dbh->do("ALTER TABLE aqorders  ADD FOREIGN KEY (`budget_id`) REFERENCES `aqbudgets` (`budget_id`) ON UPDATE CASCADE  " ); ????
3054     $dbh->do("SET FOREIGN_KEY_CHECKS=1 ");
3055
3056     print "Upgrade to $DBversion done (Adding new aqbudgetperiods, aqbudgets and aqbudget_planning tables  )\n";
3057     SetVersion ($DBversion);
3058 }
3059
3060
3061
3062 $DBversion = '3.01.00.078';
3063 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3064     $dbh->do("ALTER TABLE aqbudgetperiods ADD COLUMN budget_period_total decimal(28,6)");
3065     print "Upgrade to $DBversion done (adds 'budget_period_total' column to aqbudgetperiods table)\n";
3066     SetVersion($DBversion);
3067 }
3068
3069
3070 $DBversion = '3.01.00.079';
3071 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3072     $dbh->do("ALTER TABLE currency ADD COLUMN active  tinyint(1)");
3073
3074     print "Upgrade to $DBversion done (adds 'active' column to currencies table)\n";
3075     SetVersion($DBversion);
3076 }
3077
3078 $DBversion = '3.01.00.080';
3079 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3080     $dbh->do(<<BUDG_PERM );
3081 INSERT INTO permissions (module_bit, code, description) VALUES
3082             (11, 'vendors_manage', 'Manage vendors'),
3083             (11, 'contracts_manage', 'Manage contracts'),
3084             (11, 'period_manage', 'Manage periods'),
3085             (11, 'budget_manage', 'Manage budgets'),
3086             (11, 'budget_modify', "Modify budget (can't create lines but can modify existing ones)"),
3087             (11, 'planning_manage', 'Manage budget plannings'),
3088             (11, 'order_manage', 'Manage orders & basket'),
3089             (11, 'group_manage', 'Manage orders & basketgroups'),
3090             (11, 'order_receive', 'Manage orders & basket'),
3091             (11, 'budget_add_del', "Add and delete budgets (but can't modify budgets)");
3092 BUDG_PERM
3093
3094     print "Upgrade to $DBversion done (adds permissions for the acquisitions module)\n";
3095     SetVersion($DBversion);
3096 }
3097
3098
3099 $DBversion = '3.01.00.081';
3100 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3101     $dbh->do("ALTER TABLE aqbooksellers ADD COLUMN `gstrate` decimal(6,4) default NULL");
3102     if (my $gist=C4::Context->preference("gist")){
3103                 my $sql=$dbh->prepare("UPDATE aqbooksellers set `gstrate`=? ");
3104         $sql->execute($gist) ;
3105         }
3106     print "Upgrade to $DBversion done (added per-supplier gstrate setting)\n";
3107     SetVersion($DBversion);
3108 }
3109
3110 $DBversion = "3.01.00.082";
3111 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3112     if (C4::Context->preference("opaclanguages") eq "fr") {
3113         $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')#);
3114     } else {
3115         $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')");
3116     }
3117     print "Upgrade to $DBversion done (adding ReservesNeedReturns systempref, in circulation)\n";
3118     SetVersion ($DBversion);
3119 }
3120
3121 $DBversion = "3.01.00.083";
3122 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3123     $dbh->do(qq|
3124  CREATE TABLE `aqorders_items` (
3125   `ordernumber` int(11) NOT NULL,
3126   `itemnumber` int(11) NOT NULL,
3127   `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
3128   PRIMARY KEY  (`itemnumber`),
3129   KEY `ordernumber` (`ordernumber`)
3130 ) ENGINE=InnoDB DEFAULT CHARSET=utf8   |
3131     );
3132
3133     $dbh->do(qq| DROP TABLE aqorderbreakdown |);
3134     $dbh->do('DROP TABLE aqbookfund');
3135     print "Upgrade to $DBversion done (New aqorders_items table for acqui)\n";
3136     SetVersion ($DBversion);
3137 }
3138
3139 $DBversion = "3.01.00.084";
3140 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3141     $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')  #);
3142
3143     print "Upgrade to $DBversion done (CurrencyFormat syspref added)\n";
3144     SetVersion ($DBversion);
3145 }
3146
3147 $DBversion = "3.01.00.085";
3148 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3149     $dbh->do("ALTER table aqorders drop column title");
3150     $dbh->do("ALTER TABLE `aqorders` CHANGE `budget_id` `budget_id` INT( 11 ) NOT NULL");
3151     print "Upgrade to $DBversion done update budget_id size that should not be a tinyint\n";
3152     SetVersion ($DBversion);
3153 }
3154
3155 $DBversion = "3.01.00.086";
3156 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3157     $dbh->do(<<SUGGESTIONS);
3158 ALTER table suggestions
3159     ADD budgetid INT(11),
3160     ADD branchcode VARCHAR(10) default NULL,
3161     ADD acceptedby INT(11) default NULL,
3162     ADD accepteddate date default NULL,
3163     ADD suggesteddate date default NULL,
3164     ADD manageddate date default NULL,
3165     ADD rejectedby INT(11) default NULL,
3166     ADD rejecteddate date default NULL,
3167     ADD collectiontitle text default NULL,
3168     ADD itemtype VARCHAR(30) default NULL
3169     ;
3170 SUGGESTIONS
3171     print "Upgrade to $DBversion done (Suggestions)\n";
3172     SetVersion ($DBversion);
3173 }
3174
3175 $DBversion = "3.01.00.087";
3176 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3177     $dbh->do("ALTER table aqbudgets drop column budget_amount_sublevel;");
3178     print "Upgrade to $DBversion done (Drop column budget_amount_sublevel from aqbudgets)\n";
3179     SetVersion ($DBversion);
3180 }
3181
3182 $DBversion = "3.01.00.088";
3183 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3184     $dbh->do(  qq# INSERT INTO `systempreferences` VALUES ('intranetbookbag','1','','If ON, enables display of Cart feature in the intranet','YesNo')  #);
3185
3186     print "Upgrade to $DBversion done (intranetbookbag syspref added)\n";
3187     SetVersion ($DBversion);
3188 }
3189
3190 $DBversion = "3.01.00.090";
3191 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3192 $dbh->do("
3193        INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3194                 (16, 'execute_reports', 'Execute SQL reports'),
3195                 (16, 'create_reports', 'Create SQL Reports')
3196         ");
3197
3198     print "Upgrade to $DBversion done (granular permissions for guided reports added)\n";
3199     SetVersion ($DBversion);
3200 }
3201
3202 $DBversion = "3.01.00.091";
3203 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3204 $dbh->do("
3205         UPDATE `systempreferences` SET `options` = 'holdings|serialcollection|subscriptions'
3206         WHERE `systempreferences`.`variable` = 'opacSerialDefaultTab' LIMIT 1
3207         ");
3208
3209     print "Upgrade to $DBversion done (opac-detail default tag updated)\n";
3210     SetVersion ($DBversion);
3211 }
3212
3213 $DBversion = "3.01.00.092";
3214 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3215     if (C4::Context->preference("opaclanguages") =~ /fr/) {
3216         $dbh->do(qq{
3217 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');
3218         });
3219         }else{
3220         $dbh->do(qq{
3221 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');
3222         });
3223         }
3224     print "Upgrade to $DBversion done (Added RoutingListAddReserves syspref)\n";
3225     SetVersion ($DBversion);
3226 }
3227
3228 $DBversion = "3.01.00.093";
3229 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3230         $dbh->do(qq{
3231         ALTER TABLE biblioitems ADD INDEX issn_idx (issn);
3232         });
3233     print "Upgrade to $DBversion done (added index to ISSN)\n";
3234     SetVersion ($DBversion);
3235 }
3236
3237 $DBversion = "3.01.00.094";
3238 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3239         $dbh->do(qq{
3240         ALTER TABLE aqbasketgroups ADD deliveryplace VARCHAR(10) default NULL, ADD deliverycomment VARCHAR(255) default NULL;
3241         });
3242
3243     print "Upgrade to $DBversion done (adding deliveryplace deliverycomment to basketgroups)\n";
3244     SetVersion ($DBversion);
3245 }
3246
3247 $DBversion = "3.01.00.095";
3248 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3249         $dbh->do(qq{
3250         ALTER TABLE items ADD stocknumber VARCHAR(32) DEFAULT NULL COMMENT "stores the inventory number";
3251         });
3252         $dbh->do(qq{
3253         ALTER TABLE items ADD UNIQUE INDEX itemsstocknumberidx (stocknumber);
3254         });
3255         $dbh->do(qq{
3256         ALTER TABLE deleteditems ADD stocknumber VARCHAR(32) DEFAULT NULL COMMENT "stores the inventory number of deleted items";
3257         });
3258         $dbh->do(qq{
3259         ALTER TABLE deleteditems ADD UNIQUE INDEX deleteditemsstocknumberidx (stocknumber);
3260         });
3261         if (C4::Context->preference('marcflavour') eq 'UNIMARC'){
3262                 $dbh->do(qq{
3263         INSERT IGNORE INTO marc_subfield_structure (frameworkcode,tagfield, tagsubfield, tab, repeatable, mandatory,kohafield)
3264         SELECT DISTINCT (frameworkcode),995,"j",10,0,0,"items.stocknumber" from biblio_framework ;
3265                 });
3266                 #Previously, copynumber was used as stocknumber
3267                 $dbh->do(qq{
3268         UPDATE items set stocknumber=copynumber;
3269                 });
3270                 $dbh->do(qq{
3271         UPDATE items set copynumber=NULL;
3272                 });
3273         }
3274     print "Upgrade to $DBversion done (stocknumber field added)\n";
3275     SetVersion ($DBversion);
3276 }
3277
3278 $DBversion = "3.01.00.096";
3279 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3280     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OrderPdfTemplate','','Uploads a PDF template to use for printing baskets','NULL','Upload')");
3281     $dbh->do("UPDATE systempreferences SET variable='OrderPdfFormat' WHERE variable='pdfformat'");
3282     print "Upgrade to $DBversion done (PDF orders system preferences added and updated)\n";
3283     SetVersion ($DBversion);
3284 }
3285
3286 $DBversion = "3.01.00.097";
3287 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3288         $dbh->do(qq{
3289         ALTER TABLE aqbasketgroups ADD billingplace VARCHAR(10) NOT NULL AFTER deliverycomment;
3290         });
3291
3292     print "Upgrade to $DBversion done (Adding billingplace to aqbasketgroups)\n";
3293     SetVersion ($DBversion);
3294 }
3295
3296 $DBversion = "3.01.00.098";
3297 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3298         $dbh->do(qq{
3299         ALTER TABLE auth_subfield_structure MODIFY frameworkcode VARCHAR(10) NULL;
3300         });
3301
3302     print "Upgrade to $DBversion done (changing frameworkcode length in auth_subfield_structure)\n";
3303     SetVersion ($DBversion);
3304 }
3305
3306 $DBversion = "3.01.00.099";
3307 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3308         $dbh->do(qq{
3309                 INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3310                 (9, 'edit_catalogue', 'Edit catalogue'),
3311                 (9, 'fast_cataloging', 'Fast cataloging')
3312         });
3313
3314     print "Upgrade to $DBversion done (granular permissions for cataloging added)\n";
3315     SetVersion ($DBversion);
3316 }
3317
3318 $DBversion = "3.01.00.100";
3319 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3320         $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')");
3321         print "Upgrade to $DBversion done (added CAS authentication system preferences)\n";
3322     SetVersion ($DBversion);
3323 }
3324
3325 $DBversion = "3.01.00.101";
3326 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3327         $dbh->do(
3328         "INSERT INTO systempreferences 
3329            (variable, value, options, explanation, type)
3330          VALUES (
3331             'OverdueNoticeBcc', '', '', 
3332             'Email address to Bcc outgoing notices sent by email',
3333             'free')
3334          ");
3335         print "Upgrade to $DBversion done (added OverdueNoticeBcc system preferences)\n";
3336     SetVersion ($DBversion);
3337 }
3338 $DBversion = "3.01.00.102";
3339 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3340     $dbh->do(
3341     "UPDATE permissions set description = 'Edit catalog (Modify bibliographic/holdings data)' where module_bit = 9 and code = 'edit_catalogue'"
3342     );
3343         print "Upgrade to $DBversion done (fixed spelling error in edit_catalogue permission)\n";
3344     SetVersion ($DBversion);
3345 }
3346
3347 $DBversion = "3.01.00.103";
3348 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3349         $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES (13, 'moderate_tags', 'Moderate patron tags')");
3350         print "Upgrade to $DBversion done (adding patron permissions for tags tool)\n";
3351     SetVersion ($DBversion);
3352 }
3353
3354 $DBversion = "3.01.00.104";
3355 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3356
3357     my ($maninv_count, $borrnotes_count);
3358     eval { $maninv_count = $dbh->do("SELECT 1 FROM authorised_values WHERE category='MANUAL_INV'"); };
3359     if ($maninv_count == 0) {
3360         $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('MANUAL_INV','Copier Fees','.25')");
3361     }
3362     eval { $borrnotes_count = $dbh->do("SELECT 1 FROM authorised_values WHERE category='BOR_NOTES'"); };
3363     if ($borrnotes_count == 0) {
3364         $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('BOR_NOTES','ADDR','Address Notes')");
3365     }
3366     
3367     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('LOC','CART','Book Cart')");
3368     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('LOC','PROC','Processing Center')");
3369
3370         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";
3371         SetVersion ($DBversion);
3372 }
3373
3374
3375 $DBversion = "3.01.00.105";
3376 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3377     $dbh->do("
3378       CREATE TABLE `collections` (
3379         `colId` int(11) NOT NULL auto_increment,
3380         `colTitle` varchar(100) NOT NULL default '',
3381         `colDesc` text NOT NULL,
3382         `colBranchcode` varchar(4) default NULL COMMENT 'branchcode for branch where item should be held.',
3383         PRIMARY KEY  (`colId`)
3384       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3385     ");
3386        
3387     $dbh->do("
3388       CREATE TABLE `collections_tracking` (
3389         `ctId` int(11) NOT NULL auto_increment,
3390         `colId` int(11) NOT NULL default '0' COMMENT 'collections.colId',
3391         `itemnumber` int(11) NOT NULL default '0' COMMENT 'items.itemnumber',
3392         PRIMARY KEY  (`ctId`)
3393       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3394     ");
3395     $dbh->do("
3396         INSERT INTO permissions (module_bit, code, description) 
3397         VALUES ( 13, 'rotating_collections', 'Manage Rotating collections')" );
3398         print "Upgrade to $DBversion done (added collection and collection_tracking tables for rotating collections functionality)\n";
3399     SetVersion ($DBversion);
3400 }
3401 $DBversion = "3.01.00.106";
3402 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3403         $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' )");
3404         print "Upgrade to $DBversion done (added OpacAddMastheadLibraryPulldown system preferences)\n";
3405     SetVersion ($DBversion);
3406 }
3407
3408 $DBversion = '3.01.00.107';
3409 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3410     my $upgrade_script = C4::Context->config("intranetdir") . "/installer/data/mysql/patroncards_upgrade.pl";
3411     system("perl $upgrade_script");
3412     print "Upgrade to $DBversion done (Migrated labels and patroncards tables and data to new schema.)\n";
3413     SetVersion ($DBversion);
3414 }
3415
3416 $DBversion = '3.01.00.108';
3417 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3418         $dbh->do(qq{
3419         ALTER TABLE `export_format` ADD `csv_separator` VARCHAR( 2 ) NOT NULL AFTER `marcfields` ,
3420         ADD `field_separator` VARCHAR( 2 ) NOT NULL AFTER `csv_separator` ,
3421         ADD `subfield_separator` VARCHAR( 2 ) NOT NULL AFTER `field_separator` 
3422         });
3423         print "Upgrade to $DBversion done (added separators for csv export)\n";
3424     SetVersion ($DBversion);
3425 }
3426
3427 $DBversion = "3.01.00.109";
3428 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3429         $dbh->do(qq{
3430         ALTER TABLE `export_format` ADD `encoding` VARCHAR(255) NOT NULL AFTER `subfield_separator`
3431         });
3432         print "Upgrade to $DBversion done (added encoding for csv export)\n";
3433     SetVersion ($DBversion);
3434 }
3435
3436 $DBversion = '3.01.00.110';
3437 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3438     $dbh->do('ALTER TABLE `categories` ADD COLUMN `enrolmentperioddate` DATE NULL DEFAULT NULL AFTER `enrolmentperiod`');
3439     print "Upgrade to $DBversion done (Add enrolment period date support)\n";
3440     SetVersion ($DBversion);
3441 }
3442
3443 $DBversion = '3.01.00.111';
3444 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3445     print "Upgrade to $DBversion done (mark DBrev for 3.2-alpha release)\n";
3446     SetVersion ($DBversion);
3447 }
3448
3449 $DBversion = '3.01.00.112';
3450 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3451         $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');");
3452         print "Upgrade to $DBversion done ( added Show Spine Label Printer on Bib Items Details preferences )\n";
3453     SetVersion ($DBversion);
3454 }
3455
3456 $DBversion = '3.01.00.113';
3457 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3458     my $value = C4::Context->preference("XSLTResultsDisplay");
3459     $dbh->do(
3460         "INSERT INTO systempreferences (variable,value,type)
3461          VALUES('OPACXSLTResultsDisplay',?,'YesNo')", {}, $value ? 1 : 0);
3462     $value = C4::Context->preference("XSLTDetailsDisplay");
3463     $dbh->do(
3464         "INSERT INTO systempreferences (variable,value,type)
3465          VALUES('OPACXSLTDetailsDisplay',?,'YesNo')", {}, $value ? 1 : 0);
3466     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";
3467     SetVersion ($DBversion);
3468 }
3469
3470 $DBversion = '3.01.00.114';
3471 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3472     $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')");
3473     $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')");
3474     $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')");
3475         print "Upgrade to $DBversion done ( Added AutoSelfCheckAllowed, AutoSelfCheckID, and AutoShelfCheckPass system preference )\n";
3476     SetVersion ($DBversion);
3477 }
3478
3479 $DBversion = '3.01.00.115';
3480 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3481     $dbh->do('UPDATE aqorders SET quantityreceived = 0 WHERE quantityreceived IS NULL');
3482     $dbh->do('ALTER TABLE aqorders MODIFY COLUMN quantityreceived smallint(6) NOT NULL DEFAULT 0');
3483         print "Upgrade to $DBversion done ( Default aqorders.quantityreceived to 0 )\n";
3484     SetVersion ($DBversion);
3485 }
3486
3487 $DBversion = '3.01.00.116';
3488 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3489         if (C4::Context->preference('OrderPdfFormat') eq 'pdfformat::example'){
3490                 $dbh->do("UPDATE `systempreferences` set value='pdfformat::layout2pages' WHERE variable='OrderPdfFormat'");
3491         }
3492         print "Upgrade to $DBversion done (corrected default OrderPdfFormat value if still set wrong )\n";
3493     SetVersion ($DBversion);
3494 }
3495
3496 $DBversion = '3.01.00.117';
3497 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3498     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'por' WHERE rfc4646_subtag='pt' ");
3499     print "Upgrade to $DBversion done (corrected ISO 639-2 language code for Portuguese)\n";
3500     SetVersion ($DBversion);
3501 }
3502
3503 $DBversion = '3.01.00.118';
3504 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3505     my ($count) = $dbh->selectrow_array("SELECT count(*) FROM information_schema.columns
3506                                          WHERE table_name = 'aqbudgets_planning'
3507                                          AND column_name = 'display'");
3508     if ($count < 1) {
3509         $dbh->do("ALTER TABLE aqbudgets_planning ADD COLUMN display tinyint(1) DEFAULT 1");
3510     }
3511     print "Upgrade to $DBversion done (bug 4203: add display column to aqbudgets_planning if missing)\n";
3512     SetVersion ($DBversion);
3513 }
3514
3515 $DBversion = '3.01.00.119';
3516 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3517     eval{require Locale::Currency::Format};
3518     if (!$@) {
3519         print "Upgrade to $DBversion done (Locale::Currency::Format installed.)\n";
3520         SetVersion ($DBversion);
3521     }
3522     else {
3523         print "Upgrade to $DBversion done.\n";
3524         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";
3525         SetVersion ($DBversion);
3526     }
3527 }
3528
3529 $DBversion = '3.01.00.120';
3530 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3531     $dbh->do(q{
3532 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');
3533 });
3534     print "Upgrade to $DBversion done (bug 1080: add soundon system preference for circulation sounds)\n";
3535     SetVersion ($DBversion);
3536 }
3537
3538 $DBversion = '3.01.00.121';
3539 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3540     $dbh->do("ALTER TABLE `reserves` ADD `expirationdate` DATE DEFAULT NULL");
3541     $dbh->do("ALTER TABLE `reserves` ADD `lowestPriority` tinyint(1) NOT NULL");
3542     $dbh->do("ALTER TABLE `old_reserves` ADD `expirationdate` DATE DEFAULT NULL");
3543     $dbh->do("ALTER TABLE `old_reserves` ADD `lowestPriority` tinyint(1) NOT NULL");
3544     print "Upgrade to $DBversion done ( Added Additional Fields to Reserves tables )\n";
3545     SetVersion ($DBversion);
3546 }
3547
3548 $DBversion = '3.01.00.122';
3549 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3550     $dbh->do(q{
3551       INSERT INTO systempreferences (variable,value,explanation,options,type)
3552       VALUES ('OAI-PMH:ConfFile', '', 'If empty, Koha OAI Server operates in normal mode, otherwise it operates in extended mode.','','File');
3553 });
3554     print "Upgrade to $DBversion done. — Add a new system preference OAI-PMF:ConfFile\n";
3555     SetVersion ($DBversion);
3556 }
3557
3558 $DBversion = "3.01.00.123";
3559 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3560     $dbh->do("INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3561         (6, 'place_holds', 'Place holds for patrons')");
3562     $dbh->do("INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3563         (6, 'modify_holds_priority', 'Modify holds priority')");
3564     $dbh->do("UPDATE `userflags` SET `flagdesc` = 'Place and modify holds for patrons' WHERE `flag` = 'reserveforothers'");
3565     print "Upgrade to $DBversion done (Add granular permission for holds modification and update description of reserveforothers permission)\n";
3566     SetVersion ($DBversion);
3567 }
3568
3569 $DBversion = '3.01.00.124';
3570 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3571     $dbh->do("
3572         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>>).');
3573     ");
3574     print "Upgrade to $DBversion done (bug 3242: add HOLDPLACED letter template, which is used when emailLibrarianWhenHoldIsPlaced is enabled)\n";
3575     SetVersion ($DBversion);
3576 }
3577
3578 $DBversion = '3.01.00.125';
3579 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3580     $dbh->do("
3581         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' );
3582     ");
3583     $dbh->do("
3584         INSERT INTO message_transport_types (message_transport_type) values ('print');
3585     ");
3586     print "Upgrade to $DBversion done (bug 3482: Printable hold and overdue notices)\n";
3587     SetVersion ($DBversion);
3588 }
3589
3590 $DBversion = "3.01.00.126";
3591 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3592         $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')");
3593         $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')");
3594         
3595     print "Upgrade to $DBversion done (Adding ILS-DI updates and ILS-DI:AuthorizedIPs)\n";
3596     SetVersion ($DBversion);
3597 }
3598
3599 $DBversion = '3.01.00.127';
3600 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3601     $dbh->do("ALTER TABLE messages CHANGE branchcode branchcode varchar(10);");
3602     print "Upgrade to $DBversion done (bug 4190: messages in patron account did not work with branchcodes > 4)\n";
3603     SetVersion ($DBversion);
3604 }
3605
3606 $DBversion = '3.01.00.128';
3607 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3608     $dbh->do('CREATE INDEX budget_id ON aqorders (budget_id );');
3609     print "Upgrade to $DBversion done (bug 4331: index orders by budget_id)\n";
3610     SetVersion ($DBversion);
3611 }
3612
3613 $DBversion = "3.01.00.129";
3614 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3615         $dbh->do("UPDATE `permissions` SET `code` = 'items_batchdel' WHERE `permissions`.`module_bit` =13 AND `permissions`.`code` = 'batchdel' LIMIT 1 ;");
3616         $dbh->do("UPDATE `permissions` SET `code` = 'items_batchmod' WHERE `permissions`.`module_bit` =13 AND `permissions`.`code` = 'batchmod' LIMIT 1 ;");
3617         print "Upgrade to $DBversion done (Change permissions names for item batch modification / deletion)\n";
3618
3619     SetVersion ($DBversion);
3620 }
3621
3622 $DBversion = "3.01.00.130";
3623 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3624     $dbh->do("UPDATE reserves SET expirationdate = NULL WHERE expirationdate = '0000-00-00'");
3625     print "Upgrade to $DBversion done (change reserves.expirationdate values of 0000-00-00 to NULL (bug 1532)\n";
3626     SetVersion ($DBversion);
3627 }
3628
3629 $DBversion = "3.01.00.131";
3630 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3631         $dbh->do(q{
3632 INSERT IGNORE INTO message_transport_types (message_transport_type) VALUES ('print'),('feed');
3633     });
3634     print "Upgrade to $DBversion done (adding print and feed message transport types)\n";
3635     SetVersion ($DBversion);
3636 }
3637
3638 $DBversion = "3.01.00.132";
3639 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3640         $dbh->do(q{
3641     ALTER TABLE language_descriptions ADD INDEX subtag_type_lang (subtag, type, lang);
3642     });
3643     print "Upgrade to $DBversion done (Adding index to language_descriptions table)\n";
3644     SetVersion ($DBversion);
3645 }
3646
3647 $DBversion = '3.01.00.133';
3648 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3649     $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')");
3650     print "Upgrade to $DBversion done (bug 4405: added OverduesBlockCirc syspref to control whether circulation is blocked if a borrower has overdues)\n";
3651     SetVersion ($DBversion);
3652 }
3653
3654 $DBversion = '3.01.00.134';
3655 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3656     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('DisplayMultiPlaceHold','1','Display the ability to place multiple holds or not','','YesNo')");
3657     print "Upgrade to $DBversion done (adding syspref DisplayMultiPlaceHold to control whether multiple holds can be placed from the search results page)\n";
3658     SetVersion ($DBversion);
3659 }
3660
3661 $DBversion = '3.01.00.135';
3662 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3663     $dbh->do("
3664         INSERT INTO `letter` (module, code, name, title, content) VALUES
3665 ('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')
3666 ");
3667     print "Upgrade to $DBversion done (bug 4377: added HOLD_PRINT message template)\n";
3668     SetVersion ($DBversion);
3669 }
3670
3671 $DBversion = '3.01.00.136';
3672 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3673     $dbh->do(qq{
3674 INSERT INTO permissions (module_bit, code, description) VALUES
3675    ( 9, 'edit_items', 'Edit Items');});
3676     print "Upgrade to $DBversion done (Adding a new permission to edit items)\n";
3677     SetVersion ($DBversion);
3678 }
3679
3680 $DBversion = "3.01.00.137";
3681 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3682         $dbh->do("
3683           INSERT INTO permissions (module_bit, code, description) VALUES
3684           (15, 'check_expiration', 'Check the expiration of a serial'),
3685           (15, 'claim_serials', 'Claim missing serials'),
3686           (15, 'create_subscription', 'Create a new subscription'),
3687           (15, 'delete_subscription', 'Delete an existing subscription'),
3688           (15, 'edit_subscription', 'Edit an existing subscription'),
3689           (15, 'receive_serials', 'Serials receiving'),
3690           (15, 'renew_subscription', 'Renew a subscription'),
3691           (15, 'routing', 'Routing');
3692                  ");
3693     print "Upgrade to $DBversion done (adding granular permissions for serials)\n";
3694     SetVersion ($DBversion);
3695 }
3696
3697 $DBversion = "3.01.00.138";
3698 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3699     $dbh->do("DELETE FROM systempreferences WHERE variable = 'GranularPermissions'");
3700     print "Upgrade to $DBversion done (bug 4896: removing GranularPermissions syspref; use of granular permissions is now the default)\n";
3701     SetVersion ($DBversion);
3702 }
3703
3704 $DBversion = '3.01.00.139';
3705 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3706     $dbh->do("ALTER TABLE message_attributes CHANGE message_name message_name varchar(40);");
3707     print "Upgrade to $DBversion done (bug 3682: change message_name from varchar(20) to varchar(40))\n";
3708     SetVersion ($DBversion);
3709 }
3710
3711 $DBversion = '3.01.00.140';
3712 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3713     $dbh->do("UPDATE systempreferences SET value = '0' WHERE variable = 'TagsModeration' AND value is NULL");
3714     print "Upgrade to $DBversion done (bug 4312 TagsModeration changed from NULL to 0)\n";
3715     SetVersion ($DBversion);
3716 }
3717
3718 $DBversion = '3.01.00.141';
3719 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3720     $dbh->do(qq{DELETE FROM message_attributes WHERE message_attribute_id=3;});
3721     $dbh->do(qq{DELETE FROM letter WHERE code='EVENT' AND title='Upcoming Library Event';});
3722     print "Upgrade to $DBversion done Remove upcoming events messaging option (bug 2434)\n";
3723     SetVersion ($DBversion);
3724 }
3725
3726 $DBversion = '3.01.00.142';
3727 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3728     $dbh->do(qq{DELETE FROM message_transports WHERE message_attribute_id=3;});
3729     print "Upgrade to $DBversion done (Remove upcoming events messaging option part 2 (bug 2434))\n";
3730     SetVersion ($DBversion);
3731 }
3732
3733 $DBversion = '3.01.00.143';
3734 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3735     $dbh->do(qq{CREATE INDEX auth_value_idx ON authorised_values (authorised_value)});
3736     $dbh->do(qq{CREATE INDEX auth_val_cat_idx ON borrower_attribute_types (authorised_value_category)});
3737     print "Upgrade to $DBversion done (Create index on authorised_values and borrower_attribute_types (bug 4139))\n";
3738     SetVersion ($DBversion);
3739 }
3740
3741 $DBversion = '3.01.00.144';
3742 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3743     $dbh->do(qq{UPDATE systempreferences SET value='normal' where value='default' and variable='IntranetBiblioDefaultView'});
3744     print "Upgrade to $DBversion done (Update the 'default' to 'normal' for the IntranetBiblioDefaultView syspref (bug 5007))\n";
3745     SetVersion ($DBversion);
3746 }
3747
3748 $DBversion = "3.01.00.145";
3749 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3750     $dbh->do("ALTER TABLE borrowers ADD KEY `guarantorid` (guarantorid);");
3751     print "Upgrade to $DBversion done (Add index on guarantorid)\n";
3752     SetVersion ($DBversion);
3753 }
3754
3755 $DBversion = '3.01.00.999';
3756 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3757     print "Upgrade to $DBversion done (3.2.0 release candidate)\n";
3758     SetVersion ($DBversion);
3759 }
3760
3761 $DBversion = "3.02.00.000";
3762 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3763     my $value = $dbh->selectrow_array("SELECT value FROM systempreferences WHERE variable = 'HomeOrHoldingBranch'");
3764     $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');");
3765     print "Upgrade to $DBversion done (Add HomeOrHoldingBranchReturn system preference)\n";
3766     SetVersion ($DBversion);
3767 }
3768
3769 $DBversion = "3.02.00.001";
3770 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3771     $dbh->do(q{DELETE FROM systempreferences WHERE variable IN (
3772                 'holdCancelLength',
3773                 'PINESISBN',
3774                 'sortbynonfiling',
3775                 'TemplateEncoding',
3776                 'OPACSubscriptionDisplay',
3777                 'OPACDisplayExtendedSubInfo',
3778                 'OAI-PMH:Set',
3779                 'OAI-PMH:Subset',
3780                 'libraryAddress',
3781                 'kohaspsuggest',
3782                 'OrderPdfTemplate',
3783                 'marc',
3784                 'acquisitions',
3785                 'MIME')
3786                }
3787     );
3788     print "Upgrade to $DBversion done (bug 3756: remove disused system preferences)\n";
3789     SetVersion ($DBversion);
3790 }
3791
3792 $DBversion = "3.02.00.002";
3793 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3794     $dbh->do(q{DELETE FROM systempreferences WHERE variable = 'OpacPrivacy'});
3795     print "Upgrade to $DBversion done (bug 3881: remove unused OpacPrivacy system preference)\n";
3796     SetVersion ($DBversion);
3797 }
3798
3799 $DBversion = "3.02.00.003";
3800 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3801     $dbh->do(q{UPDATE systempreferences SET variable = 'ILS-DI:AuthorizedIPs' WHERE variable = 'ILS-DI:Authorized_IPs'});
3802     print "Upgrade to $DBversion done (correct ILS-DI:AuthorizedIPs)\n";
3803     SetVersion ($DBversion);
3804 }
3805
3806 $DBversion = "3.02.00.004";
3807 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3808     print "Upgrade to $DBversion done (3.2.0 general release)\n";
3809     SetVersion ($DBversion);
3810 }
3811
3812 # This is the point where 3.2.x and master diverged, we can use $original_version to make sure we don't
3813 # apply updates that have already been done
3814
3815 $DBversion = "3.03.00.001";
3816 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.005")) {
3817     $dbh->do("DELETE FROM subscriptionroutinglist WHERE borrowernumber IS NULL;");
3818     $dbh->do("ALTER TABLE subscriptionroutinglist MODIFY COLUMN `borrowernumber` int(11) NOT NULL;");
3819     $dbh->do("DELETE FROM subscriptionroutinglist WHERE subscriptionid IS NULL;");
3820     $dbh->do("ALTER TABLE subscriptionroutinglist MODIFY COLUMN `subscriptionid` int(11) NOT NULL;");
3821     $dbh->do("CREATE TEMPORARY TABLE del_subscriptionroutinglist 
3822               SELECT s1.routingid FROM subscriptionroutinglist s1
3823               WHERE EXISTS (SELECT * FROM subscriptionroutinglist s2
3824                             WHERE s2.borrowernumber = s1.borrowernumber
3825                             AND   s2.subscriptionid = s1.subscriptionid 
3826                             AND   s2.routingid < s1.routingid);");
3827     $dbh->do("DELETE FROM subscriptionroutinglist
3828               WHERE routingid IN (SELECT routingid FROM del_subscriptionroutinglist);");
3829     $dbh->do("ALTER TABLE subscriptionroutinglist ADD UNIQUE (subscriptionid, borrowernumber);");
3830     $dbh->do("ALTER TABLE subscriptionroutinglist 
3831                 ADD CONSTRAINT `subscriptionroutinglist_ibfk_1` FOREIGN KEY (`borrowernumber`) 
3832                 REFERENCES `borrowers` (`borrowernumber`)
3833                 ON DELETE CASCADE ON UPDATE CASCADE");
3834     $dbh->do("ALTER TABLE subscriptionroutinglist 
3835                 ADD CONSTRAINT `subscriptionroutinglist_ibfk_2` FOREIGN KEY (`subscriptionid`) 
3836                 REFERENCES `subscription` (`subscriptionid`)
3837                 ON DELETE CASCADE ON UPDATE CASCADE");
3838     print "Upgrade to $DBversion done (Make subscriptionroutinglist more strict)\n";
3839     SetVersion ($DBversion);
3840 }
3841
3842 $DBversion = '3.03.00.002';
3843 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.006")) {
3844     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='arm' WHERE rfc4646_subtag='hy';");
3845     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='eng' WHERE rfc4646_subtag='en';");
3846     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'fi','fin');");
3847     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='fre' WHERE rfc4646_subtag='fr';");
3848     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'lo','lao');");
3849     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='ita' WHERE rfc4646_subtag='it';");
3850     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'sr','srp');");
3851     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'tet','tet');");
3852     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'ur','urd');");
3853
3854     print "Upgrade to $DBversion done (Correct language mappings)\n";
3855     SetVersion ($DBversion);
3856 }
3857
3858 $DBversion = '3.03.00.003';
3859 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.007")) {
3860     $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');");
3861     print "Upgrade to $DBversion done (Add UseTablesortForCirc syspref)\n";
3862     SetVersion ($DBversion);
3863 }
3864
3865 $DBversion = '3.03.00.004';
3866 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.001")) {
3867     my $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'ACCEPTED');
3868     $dbh->do(q/
3869 INSERT INTO `letter`
3870 (module, code, name, title, content)
3871 VALUES
3872 ('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>>')
3873 /) unless $count > 0;
3874     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'AVAILABLE');
3875     $dbh->do(q/
3876 INSERT INTO `letter`
3877 (module, code, name, title, content)
3878 VALUES
3879 ('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>>')
3880 /) unless $count > 0;
3881     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'ORDERED');
3882     $dbh->do(q/
3883 INSERT INTO `letter`
3884 (module, code, name, title, content)
3885 VALUES
3886 ('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>>')
3887 /) unless $count > 0;
3888     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'REJECTED');
3889     $dbh->do(q/
3890 INSERT INTO `letter`
3891 (module, code, name, title, content)
3892 VALUES
3893 ('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>>')
3894 /) unless $count > 0;
3895     print "Upgrade to $DBversion done (bug 5127: add default templates for suggestion status change notifications)\n";
3896     SetVersion ($DBversion);
3897 };
3898
3899 $DBversion = '3.03.00.005';
3900 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3901     $dbh->do("update `systempreferences` set options='whitespace|T-prefix|cuecat|libsuite8' where variable='itemBarcodeInputFilter'");
3902     print "Upgrade to $DBversion done (Add itemBarcodeInputFilter choice libsuite8)\n";
3903 }
3904
3905 $DBversion = '3.03.00.006';
3906 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.002")) {
3907     $dbh->do("ALTER TABLE deletedborrowers ADD `privacy` int(11) AFTER smsalertnumber;");
3908     $dbh->do("ALTER TABLE deletedborrowers CHANGE `cardnumber` `cardnumber` varchar(16);");
3909     print "Upgrade to $DBversion done (Fix differences between borrowers and deletedborrowers)\n";
3910     SetVersion ($DBversion);
3911 }
3912
3913 $DBversion = '3.03.00.007';
3914 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3915     $dbh->do("ALTER table suggestions ADD quantity SMALLINT(6) default NULL,
3916                 ADD currency VARCHAR(3) default NULL,
3917                 ADD price DECIMAL(28,6) default NULL,
3918                 ADD total DECIMAL(28,6) default NULL;
3919                 ");
3920     print "Upgrade to $DBversion done (Added acq related columns to suggestions)\n";
3921     SetVersion ($DBversion);
3922 }
3923
3924 $DBversion = '3.03.00.008';
3925 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3926     $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')");
3927     print "Upgrade to $DBversion done (adding syspref OPACNoResultsFound to control what displays when no results are found for a search in the OPAC.)\n";
3928     SetVersion ($DBversion);
3929 }
3930
3931 $DBversion = '3.03.00.009';
3932 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.003")) {
3933     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('IntranetUserCSS','','Add CSS to be included in the Intranet',NULL,'free')");
3934     print "Upgrade to $DBversion done (Add IntranetUserCSS syspref)\n";
3935     SetVersion ($DBversion);
3936 }
3937
3938 $DBversion = "3.03.00.010";
3939 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.02.001")) {
3940     $dbh->do("UPDATE `marc_subfield_structure` SET liblibrarian = 'Distance from earth' WHERE liblibrarian = 'Distrance from earth' AND tagfield = '034' AND tagsubfield = 'r';");
3941     $dbh->do("UPDATE `marc_subfield_structure` SET libopac = 'Distance from earth' WHERE libopac = 'Distrance from earth' AND tagfield = '034' AND tagsubfield = 'r';");
3942     print "Upgrade to $DBversion done (Fix misspelled 034r subfield in MARC21 Frameworks)\n";
3943     SetVersion ($DBversion);
3944 }
3945
3946 $DBversion = "3.03.00.011";
3947 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3948     $dbh->do("UPDATE aqbooksellers SET gstrate=NULL WHERE gstrate=0.0");
3949     print "Upgrade to $DBversion done (Bug 5186: allow GST rate to be set to 0)\n";
3950     SetVersion ($DBversion);
3951 }
3952
3953 $DBversion = "3.03.00.012";
3954 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3955    $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')");
3956    print "Upgrade to $DBversion done (Bug 2142: maxItemsInSearchResults syspref resurrected)\n";
3957    SetVersion ($DBversion);
3958 }
3959
3960 $DBversion = "3.03.00.013";
3961 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3962     $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')");
3963     print "Upgrade to $DBversion done (added 'OpacPublic' syspref)\n";
3964    SetVersion ($DBversion);
3965 }
3966
3967 $DBversion = "3.03.00.014";
3968 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3969     $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')");
3970     $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')");
3971     $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')");
3972     print "Upgrade to $DBversion done (Add flexible shelf browser constraints)\n";
3973     SetVersion ($DBversion);
3974 }
3975
3976 $DBversion = "3.03.00.015";
3977 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3978     if ( C4::Context->preference("marcflavour") eq "MARC21" ) {
3979         my $sth = $dbh->prepare(
3980 "INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`,
3981                              `tab`, `authorised_value`, `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`)
3982                              VALUES ( ?, '9', '9 (RLIN)', '9 (RLIN)', 0, 0, '', 6, '', '', '', 0, -5, '', '', '', NULL)"
3983         );
3984         $sth->execute('648');
3985         $sth->execute('654');
3986         $sth->execute('655');
3987         $sth->execute('656');
3988         $sth->execute('657');
3989         $sth->execute('658');
3990         $sth->execute('662');
3991         $sth->finish;
3992         print
3993 "Upgrade to $DBversion done (Bug 5619: Add subfield 9 to marc21 648,654,655,656,657,658,662)\n";
3994     }
3995     SetVersion($DBversion);
3996 }
3997
3998 $DBversion = '3.03.00.016';
3999 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4000     # reimplement OpacPrivacy system preference
4001     $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')");
4002     $dbh->do("ALTER TABLE `borrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
4003     $dbh->do("ALTER TABLE `deletedborrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
4004     print "Upgrade to $DBversion done (OpacPrivacy reimplementation)\n";
4005     SetVersion($DBversion);
4006 };
4007
4008 $DBversion = '3.03.00.017';
4009 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.001")) {
4010     $dbh->do("ALTER TABLE  `currency` CHANGE `rate` `rate` FLOAT( 15, 5 ) NULL DEFAULT NULL;");
4011     print "Upgrade to $DBversion done (Enable currency rates >= 100)\n";
4012     SetVersion ($DBversion);
4013 }
4014
4015 $DBversion = '3.03.00.018';
4016 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.002")) {
4017     $dbh->do( q|update language_descriptions set description = 'Nederlands' where lang = 'nl' and subtag = 'nl'|);
4018     $dbh->do( q|update language_descriptions set description = 'Dansk' where lang = 'da' and subtag = 'da'|);
4019     print "Upgrade to $DBversion done (Correct language descriptions)\n";
4020     SetVersion ($DBversion);
4021 }
4022
4023 $DBversion = '3.03.00.019';
4024 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.003")) {
4025     # Fix bokmål
4026     $dbh->do("UPDATE language_subtag_registry SET description = 'Norwegian bokm&#229;l' WHERE subtag = 'nb';");
4027     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'nb','nob');");
4028     $dbh->do("UPDATE language_descriptions SET description = 'Norsk bokm&#229;l' WHERE subtag = 'nb' AND lang = 'nb';");
4029     $dbh->do("UPDATE language_descriptions SET description = 'Norwegian bokm&#229;l' WHERE subtag = 'nb' AND lang = 'en';");
4030     $dbh->do("UPDATE language_descriptions SET description = 'Norvégien bokm&#229;l' WHERE subtag = 'nb' AND lang = 'fr';");
4031     # Add nynorsk
4032     $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'nn', 'language', 'Norwegian nynorsk','2011-02-14' )");
4033     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'nn','nno')");
4034     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'nb', 'Norsk nynorsk')");
4035     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'nn', 'Norsk nynorsk')");
4036     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'en', 'Norwegian nynorsk')");
4037     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'fr', 'Norvégien nynorsk')");
4038     print "Upgrade to $DBversion done (Correct language descriptions for Norwegian)\n";
4039     SetVersion ($DBversion);
4040 }
4041
4042 $DBversion = '3.03.00.020';
4043 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4044     $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')");
4045     $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')");
4046     print "Upgrade to $DBversion done (Bug 5811: Add sysprefs controlling overriding fines)\n";
4047     SetVersion($DBversion);
4048 };
4049
4050 $DBversion = '3.03.00.021';
4051 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.001")) {
4052     $dbh->do("ALTER TABLE items MODIFY enumchron TEXT");
4053     $dbh->do("ALTER TABLE deleteditems MODIFY enumchron TEXT");
4054     print "Upgrade to $DBversion done (bug 5642: longer serial enumeration)\n";
4055     SetVersion ($DBversion);
4056 }
4057
4058 $DBversion = '3.03.00.022';
4059 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4060     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('AuthoritiesLog','0','If ON, log edit/create/delete actions on authorities.','','YesNo');");
4061     print "Upgrade to $DBversion done (Add AuthoritiesLog syspref)\n";
4062     SetVersion ($DBversion);
4063 }
4064
4065 # due to a mismatch in kohastructure.sql some koha will have missing columns in aqbasketgroup
4066 # this attempts to fix that
4067 $DBversion = '3.03.00.023';
4068 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.002")) {
4069     my $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'billingplace'");
4070     $sth->execute;
4071     $dbh->do("ALTER TABLE aqbasketgroups ADD billingplace VARCHAR(10)") if ! $sth->fetchrow_hashref;
4072     $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'deliveryplace'");
4073     $sth->execute;
4074     $dbh->do("ALTER TABLE aqbasketgroups ADD deliveryplace VARCHAR(10)") if ! $sth->fetchrow_hashref;
4075     $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'deliverycomment'");
4076     $sth->execute;
4077     $dbh->do("ALTER TABLE aqbasketgroups ADD deliverycomment VARCHAR(255)") if ! $sth->fetchrow_hashref;
4078     print "Upgrade to $DBversion done (Reconcile aqbasketgroups)\n";
4079     SetVersion ($DBversion);
4080 }
4081
4082 $DBversion = '3.03.00.024';
4083 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4084     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('TraceCompleteSubfields','0','Force subject tracings to only match complete subfields.','0','YesNo')");
4085     $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')");
4086     print "Upgrade to $DBversion done (Add syspref to force whole-subfield matching on subject tracings)\n";
4087     SetVersion($DBversion);
4088 };
4089
4090 $DBversion = "3.03.00.025";
4091 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4092     $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')");
4093     print "Upgrade to $DBversion done (Add syspref to control if user can choose pickup branch for holds)\n";
4094     SetVersion ($DBversion);
4095 }
4096
4097 $DBversion = '3.03.00.026';
4098 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.003")) {
4099     $dbh->do("UPDATE `message_attributes` SET message_name='Item Due' WHERE message_attribute_id=1 AND message_name LIKE 'Item DUE'");
4100         print "Upgrade to $DBversion done ( fix capitalization in message type )\n";
4101     SetVersion ($DBversion);
4102 }
4103
4104 $DBversion = '3.03.00.027'; 
4105 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4106     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('displayFacetCount', '0', NULL, NULL, 'YesNo')");
4107     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('maxRecordsForFacets', '20', NULL, NULL, 'Integer')");
4108     print "Upgrade to $DBversion done (Preferences for facet count)\n";
4109     SetVersion ($DBversion);
4110 }
4111
4112 $DBversion = "3.03.00.028";
4113 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4114     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('FacetLabelTruncationLength', 20, 'Truncate facets length to','','free')");
4115     print "Upgrade to $DBversion done (Add FacetLabelTruncationLength syspref to control facets displayed length)\n";
4116     SetVersion ($DBversion);
4117 }
4118
4119 $DBversion = "3.03.00.029";
4120 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4121     $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')");
4122     print "Upgrade to $DBversion done (Add syspref to control if user can choose branch when making purchase suggestion)\n";
4123     SetVersion ($DBversion);
4124 }
4125
4126 $DBversion = "3.03.00.030";
4127 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4128     $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')");
4129     $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')");
4130     print "Upgrade to $DBversion done (Add sysprefs to control custom favicons)\n";
4131     SetVersion ($DBversion);
4132 }
4133
4134 $DBversion = "3.03.00.031";
4135 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4136     $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');");
4137     print "Upgrade to $DBversion done (Add syspref FineNotifyAtCheckin)\n";
4138     SetVersion ($DBversion);    
4139 }
4140
4141 $DBversion = '3.03.00.032';
4142 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4143     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('TraceSubjectSubdivisions', 1, 'Create searches on all subdivisions for subject tracings.','1','YesNo')");
4144     print "Upgrade to $DBversion done ( include subdivisions when generating subject tracing searches )\n";
4145 }
4146
4147
4148 $DBversion = '3.03.00.033';
4149 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4150     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('StaffAuthorisedValueImages', '1', '', NULL, 'YesNo')");
4151     print "Upgrade to $DBversion done (System pref StaffAuthorisedValueImages)\n";
4152     SetVersion ($DBversion);
4153 }
4154
4155 $DBversion = '3.03.00.034';
4156 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4157     $dbh->do("ALTER TABLE `categories` ADD `hidelostitems` tinyint(1) NOT NULL default '0' AFTER `reservefee`");
4158     print "Upgrade to $DBversion done (Add hidelostitems preference to borrower categories)\n";
4159     SetVersion ($DBversion);
4160 }
4161
4162 $DBversion = '3.03.00.035';
4163 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4164     $dbh->do("ALTER TABLE `issuingrules` ADD hardduedate date default NULL AFTER issuelength");
4165     $dbh->do("ALTER TABLE `issuingrules` ADD hardduedatecompare tinyint NOT NULL default 0 AFTER hardduedate");
4166     my $duedate;
4167     if (C4::Context->preference("globalDueDate")) {
4168       $duedate = C4::Dates::format_date_in_iso(C4::Context->preference("globalDueDate"));
4169       $dbh->do("UPDATE `issuingrules` SET hardduedate = '$duedate', hardduedatecompare = 0");
4170     } elsif (C4::Context->preference("ceilingDueDate")) {
4171       $duedate = C4::Dates::format_date_in_iso(C4::Context->preference("ceilingDueDate"));
4172       $dbh->do("UPDATE `issuingrules` SET hardduedate = '$duedate', hardduedatecompare = -1");
4173     }
4174     $dbh->do("DELETE FROM `systempreferences` WHERE variable = 'globalDueDate' OR variable = 'ceilingDueDate'");
4175     print "Upgrade to $DBversion done (Move global and ceiling due dates to Circ Rules level)\n";
4176     SetVersion ($DBversion);
4177 }
4178
4179 $DBversion = '3.03.00.036';
4180 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4181     $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')");
4182     print "Upgrade to $DBversion done ( Make COinS optional in OPAC search results )\n";
4183     SetVersion ($DBversion);
4184 }
4185
4186 $DBversion = '3.03.00.037';
4187 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4188     $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')");
4189     $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')");
4190     print "Upgrade to $DBversion done (Add 'Display856uAsImage' and 'OPACDisplay856uAsImage' syspref)\n";
4191     SetVersion ($DBversion);
4192 }
4193
4194 $DBversion = '3.03.00.038';
4195 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4196     $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')");
4197     $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')");
4198     $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')");
4199     print "Upgrade to $DBversion done ( Add Self-checkout by Login system preferences )\n";
4200 }
4201
4202 $DBversion = "3.03.00.039";
4203 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4204     $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');");
4205     print "Upgrade to $DBversion done (Add syspref ShowReviewer)\n";
4206 }
4207     
4208 $DBversion = "3.03.00.040";
4209 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4210     $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');");
4211     print "Upgrade to $DBversion done (Add syspref UseControlNumber)\n";
4212 }
4213
4214 $DBversion = "3.03.00.041";
4215 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4216     $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')");
4217     $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')");
4218     print "Upgrade to $DBversion done (Add sysprefs to control alternate holdings information display)\n";
4219     SetVersion ($DBversion);
4220 }
4221
4222 $DBversion = '3.03.00.042';
4223 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4224     stocknumber_checker();
4225     print "Upgrade to $DBversion done (5860 Index itemstocknumber)\n";
4226     SetVersion ($DBversion);
4227 }
4228
4229 sub stocknumber_checker { #code reused later on
4230   my @row;
4231   #drop the obsolete itemSStocknumber idx if it exists
4232   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemsstocknumberidx'");
4233   $dbh->do("ALTER TABLE `items` DROP INDEX `itemsstocknumberidx`;") if @row;
4234
4235   #check itemstocknumber idx; remove it if it is unique
4236   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemstocknumberidx' AND non_unique=0");
4237   $dbh->do("ALTER TABLE `items` DROP INDEX `itemstocknumberidx`;") if @row;
4238
4239   #add itemstocknumber index non-unique IF it still not exists
4240   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemstocknumberidx'");
4241   $dbh->do("ALTER TABLE items ADD INDEX itemstocknumberidx (stocknumber);") unless @row;
4242 }
4243
4244 $DBversion = "3.03.00.043";
4245 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4246
4247     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib,lib_opac) VALUES ('YES_NO','0','No','No')");
4248     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib,lib_opac) VALUES ('YES_NO','1','Yes','Yes')");
4249
4250         print "Upgrade to $DBversion done ( add generic boolean YES_NO authorised_values pair )\n";
4251         SetVersion ($DBversion);
4252 }
4253
4254 $DBversion = '3.03.00.044';
4255 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4256     $dbh->do("ALTER TABLE `aqbasketgroups` ADD `freedeliveryplace` TEXT NULL AFTER `deliveryplace`;");
4257     print "Upgrade to $DBversion done (adding freedeliveryplace to basketgroups)\n";
4258 }
4259
4260 $DBversion = '3.03.00.045';
4261 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4262     #Remove obsolete columns from aqbooksellers if needed
4263     my $a = $dbh->selectall_hashref('SHOW columns from aqbooksellers','Field');
4264     my $sqldrop="ALTER TABLE aqbooksellers DROP COLUMN ";
4265     foreach(qw/deliverydays followupdays followupscancel invoicedisc nocalc specialty/) {
4266       $dbh->do($sqldrop.$_) if exists $a->{$_};
4267     }
4268     #Remove obsolete column from aqbudgets if needed
4269     #The correct column is budget_notes
4270     $a = $dbh->selectall_hashref('SHOW columns from aqbudgets','Field');
4271     if(exists $a->{budget_description}) {
4272       $dbh->do("ALTER TABLE aqbudgets DROP COLUMN budget_description");
4273     }
4274     print "Upgrade to $DBversion done (Remove obsolete columns from aqbooksellers and aqbudgets if needed)\n";
4275     SetVersion ($DBversion);
4276 }
4277
4278 $DBversion = "3.03.00.046";
4279 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4280     $dbh->do("ALTER TABLE overduerules ALTER delay1 SET DEFAULT NULL, ALTER delay2 SET DEFAULT NULL, ALTER delay3 SET DEFAULT NULL");
4281     print "Upgrade to $DBversion done (Setting NULL default value for delayn columns in table overduerules)\n";
4282     SetVersion($DBversion);
4283 }
4284
4285 $DBversion = '3.03.00.047';
4286 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4287     $dbh->do("ALTER TABLE borrowers ADD `state` mediumtext AFTER city;");
4288     $dbh->do("ALTER TABLE borrowers ADD `B_state` mediumtext AFTER B_city;");
4289     $dbh->do("ALTER TABLE borrowers ADD `altcontactstate` mediumtext AFTER altcontactaddress3;");
4290     $dbh->do("ALTER TABLE deletedborrowers ADD `state` mediumtext AFTER city;");
4291     $dbh->do("ALTER TABLE deletedborrowers ADD `B_state` mediumtext AFTER B_city;");
4292     $dbh->do("ALTER TABLE deletedborrowers ADD `altcontactstate` mediumtext AFTER altcontactaddress3;");
4293     print "Upgrade to $DBversion done (Add state field to patron's addresses)\n";
4294 }
4295
4296 $DBversion = '3.03.00.048';
4297 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4298     $dbh->do("ALTER TABLE branches ADD `branchstate` mediumtext AFTER `branchcity`;");
4299     print "Upgrade to $DBversion done (Add state to branch address)\n";
4300     SetVersion ($DBversion);
4301 }
4302
4303 $DBversion = '3.03.00.049';
4304 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4305     $dbh->do("ALTER TABLE `accountlines` ADD `note` text NULL default NULL");
4306     $dbh->do("ALTER TABLE `accountlines` ADD `manager_id` int( 11 ) NULL ");
4307     print "Upgrade to $DBversion done (adding note and manager_id fields in accountlines table)\n";
4308     SetVersion($DBversion);
4309 }
4310
4311 $DBversion = "3.03.00.050";
4312 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4313     $dbh->do("
4314         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');
4315         ");
4316     print "Upgrade to $DBversion done (Adding OpacHiddenItems syspref)\n";
4317     SetVersion($DBversion);
4318 }
4319
4320 $DBversion = "3.03.00.051";
4321 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4322     print "Upgrade to $DBversion done (Remove spaces and dashes from message_attribute names)\n";
4323     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Due' WHERE message_name='Item Due'");
4324     $dbh->do("UPDATE message_attributes SET message_name = 'Advance_Notice' WHERE message_name='Advance Notice'");
4325     $dbh->do("UPDATE message_attributes SET message_name = 'Hold_Filled' WHERE message_name='Hold Filled'");
4326     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Check_in' WHERE message_name='Item Check-in'");
4327     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Checkout' WHERE message_name='Item Checkout'");    
4328     SetVersion ($DBversion);
4329 }
4330
4331 $DBversion = "3.03.00.052";
4332 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4333     $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');");
4334     print "Upgrade to $DBversion done (Add syspref WaitingNotifyAtCheckin)\n";
4335     SetVersion ($DBversion);
4336 }
4337
4338 $DBversion = "3.04.00.000";
4339 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4340     print "Upgrade to $DBversion done Koha 3.4.0 release \n";
4341     SetVersion ($DBversion);
4342 }
4343
4344 $DBversion = "3.05.00.001";
4345 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4346     $dbh->do(qq{
4347     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');
4348     });
4349     print "Upgrade to $DBversion done (Adds New System preference numSearchRSSResults)\n";
4350     SetVersion($DBversion);
4351 }
4352
4353 $DBversion = '3.05.00.002';
4354 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4355     #follow up fix 5860: some installs already past 3.3.0.42
4356     stocknumber_checker();
4357     print "Upgrade to $DBversion done (Fix for stocknumber index)\n";
4358     SetVersion ($DBversion);
4359 }
4360
4361 $DBversion = "3.05.00.003";
4362 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4363     $dbh->do(qq{
4364     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');
4365     });
4366     print "Upgrade to $DBversion done (Adds New System preference OpacRenewalBranch)\n";
4367     SetVersion($DBversion);
4368 }
4369
4370 $DBversion = "3.05.00.004";
4371 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4372     $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');");
4373     print "Upgrade to $DBversion done (Add syspref ShowReviewerPhoto)\n";
4374     SetVersion($DBversion);    
4375 }
4376     
4377 $DBversion = "3.05.00.005";
4378 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4379     $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');");
4380     print "Upgrade to $DBversion done (Adds pref BasketConfirmations)\n";
4381     SetVersion($DBversion);
4382 }
4383
4384 $DBversion = "3.05.00.006"; 
4385 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4386     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('MARCAuthorityControlField008', '|| aca||aabn           | a|a     d', NULL, NULL, 'Textarea')");
4387     print "Upgrade to $DBversion done (Add syspref MARCAuthorityControlField008)\n";
4388     SetVersion ($DBversion);
4389 }
4390
4391 $DBversion = "3.05.00.007";
4392 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4393     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpenLibraryCovers',0,'If ON Openlibrary book covers will be show',NULL,'YesNo');");
4394     print "Upgrade to $DBversion done (Add syspref OpenLibraryCovers)\n";
4395     SetVersion($DBversion);
4396 }
4397
4398 $DBversion = "3.05.00.008";
4399 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4400     $dbh->do("ALTER TABLE `cities` ADD `city_state` VARCHAR( 100 ) NULL DEFAULT NULL AFTER  `city_name`;");
4401     $dbh->do("ALTER TABLE `cities` ADD `city_country` VARCHAR( 100 ) NULL DEFAULT NULL AFTER  `city_zipcode`;");
4402     print "Add state and country to cities table corresponding to new columns in borrowers\n";
4403     SetVersion($DBversion);
4404 }
4405
4406 $DBversion = "3.05.00.009";
4407 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4408     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4409               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE borrowernumber IS NULL");
4410     $dbh->do("DELETE FROM issues WHERE borrowernumber IS NULL");
4411
4412     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4413               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE itemnumber IS NULL");
4414     $dbh->do("DELETE FROM issues WHERE itemnumber IS NULL");
4415
4416     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4417               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowernumber = issues.borrowernumber)");
4418     $dbh->do("DELETE FROM issues WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowernumber = issues.borrowernumber)");
4419
4420     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4421               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE NOT EXISTS (SELECT * FROM items WHERE itemnumber = issues.itemnumber)");
4422     $dbh->do("DELETE FROM issues WHERE NOT EXISTS (SELECT * FROM items WHERE itemnumber = issues.itemnumber)");
4423
4424     $dbh->do("ALTER TABLE issues DROP FOREIGN KEY `issues_ibfk_1`");
4425     $dbh->do("ALTER TABLE issues DROP FOREIGN KEY `issues_ibfk_2`");
4426     $dbh->do("ALTER TABLE issues ALTER COLUMN borrowernumber DROP DEFAULT");
4427     $dbh->do("ALTER TABLE issues ALTER COLUMN itemnumber DROP DEFAULT");
4428     $dbh->do("ALTER TABLE issues MODIFY COLUMN borrowernumber int(11) NOT NULL");
4429     $dbh->do("ALTER TABLE issues MODIFY COLUMN itemnumber int(11) NOT NULL");
4430     $dbh->do("ALTER TABLE issues DROP KEY `issuesitemidx`");
4431     $dbh->do("ALTER TABLE issues ADD PRIMARY KEY (`itemnumber`)");
4432     $dbh->do("ALTER TABLE issues ADD CONSTRAINT `issues_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE RESTRICT ON UPDATE CASCADE");
4433     $dbh->do("ALTER TABLE issues ADD CONSTRAINT `issues_ibfk_2` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE RESTRICT ON UPDATE CASCADE");
4434
4435     print "Upgrade to $DBversion done (issues referential integrity)\n";
4436     SetVersion ($DBversion);
4437 }
4438
4439 $DBversion = "3.05.00.010";
4440 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4441     $dbh->do("CREATE INDEX priorityfoundidx ON reserves (priority,found)");
4442     print "Create an index on reserves to speed up holds awaiting pickup report bug 5866\n";
4443     SetVersion($DBversion);
4444 }
4445
4446
4447 $DBversion = "3.05.00.011";
4448 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4449     $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')");
4450     print "Upgrade to $DBversion done (add OPACResultsSidebar syspref (enh 6165))\n";
4451     SetVersion($DBversion);
4452 }
4453     
4454 $DBversion = "3.05.00.012";
4455 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4456     $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')");
4457     print "Upgrade to $DBversion done (add RecordLocalUseOnReturn syspref (enh 6403))\n";
4458     SetVersion($DBversion);
4459 }
4460
4461 $DBversion = "3.05.00.013";
4462 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4463     $dbh->do(qq|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OpacKohaUrl','0',"Show 'Powered by Koha' text on OPAC footer.",NULL,NULL)|);
4464     print "Upgrade to $DBversion done (Add syspref 'OpacKohaUrl')\n";
4465     SetVersion($DBversion);
4466 }
4467
4468 $DBversion = "3.05.00.014";
4469 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4470     $dbh->do("ALTER TABLE `borrowers` MODIFY `userid` VARCHAR(75)");
4471     print "Modified userid column length into 75 in borrowers\n";
4472     SetVersion($DBversion);
4473 }
4474
4475 $DBversion = "3.05.00.015";
4476 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4477     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectEnabled',0,'Enable Novelist Select content.  Requires Novelist Profile and Password',NULL,'YesNo')");
4478     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectProfile',NULL,'Novelist Select user Password',NULL,'free')");
4479     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectPassword',NULL,'Enable Novelist user Profile',NULL,'free')");
4480     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectView','tab','Where to display Novelist Select content','tab|above|below|right','Choice')");
4481     print "Upgrade to $DBversion done (Add support for EBSCO's NoveList Select (enh 6902))\n";
4482     SetVersion($DBversion);
4483 }
4484
4485 $DBversion = '3.05.00.016';
4486 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4487     $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');");
4488     print "Upgrade to $DBversion done (Add EasyAnalyticalRecords syspref)\n";
4489     SetVersion ($DBversion);
4490 }
4491
4492 $DBversion = '3.05.00.017';
4493 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4494     if (C4::Context->preference("marcflavour") eq 'MARC21' ||
4495         C4::Context->preference("marcflavour") eq 'NORMARC'){
4496         $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)");
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', '9', 'Host Itemnumber', 'Host Itemnumber', 0, 0, NULL, 7, NULL, NULL, '', NULL, -6, '', '', '', NULL)");
4498         print "Upgrade to $DBversion done (Add 773 subfield 9 and 0 to default framework)\n";
4499         SetVersion ($DBversion);
4500     } elsif (C4::Context->preference("marcflavour") eq 'UNIMARC'){
4501         $dbh->do("INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`, `tab`, `authorised_value` , `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`) VALUES ('461', '9', 'Host Itemnumber', 'Host Itemnumber', 0, 0, NULL, 7, NULL, NULL, '', NULL, -6, '', '', '', NULL)");
4502         print "Upgrade to $DBversion done (Add 461 subfield 9 to default framework)\n";
4503         SetVersion ($DBversion);
4504     }
4505 }
4506
4507 $DBversion = "3.05.00.018";
4508 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4509     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacNavBottom','','Links after OpacNav links','70|10','Textarea')");
4510     print "Upgrade to $DBversion done (add OpacNavBottom syspref (enh 6825): if appropriate, you can split OpacNav into OpacNav and OpacNavBottom)\n";
4511     SetVersion($DBversion);
4512 }
4513
4514 $DBversion = "3.05.00.019";
4515 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4516     $dbh->do("UPDATE itemtypes SET imageurl = 'vokal/Book.png' WHERE imageurl = 'vokal/BOOK.png'");
4517     $dbh->do("UPDATE itemtypes SET imageurl = 'vokal/Book-32px.png' WHERE imageurl = 'vokal/BOOK-32px.png'");
4518     $dbh->do("UPDATE authorised_values SET imageurl = 'vokal/Book.png' WHERE imageurl = 'vokal/BOOK.png'");
4519     $dbh->do("UPDATE authorised_values SET imageurl = 'vokal/Book-32px.png' WHERE imageurl = 'vokal/BOOK-32px.png'");
4520     print "Upgrade to $DBversion done (remove duplicate VOKAL Book icons, bug 6862)\n";
4521     SetVersion($DBversion);
4522 }
4523
4524 $DBversion = "3.05.00.020";
4525 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4526     $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')");
4527     print "Upgrade to $DBversion done (Add syspref AcqViewBaskets)\n";
4528     SetVersion($DBversion);
4529 }
4530
4531 $DBversion = "3.05.00.021";
4532 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4533     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN display_checkout TINYINT(1) NOT NULL DEFAULT '0';");
4534     print "Upgrade to $DBversion done (Added a display_checkout field in borrower_attribute_types table)\n"; 
4535     SetVersion($DBversion);
4536 }
4537
4538 $DBversion = "3.05.00.022"; 
4539 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4540     $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");
4541     print "Upgrade to $DBversion done (6094: Fixing ModAuthority problems, add a need_merge_authorities table)\n";
4542     SetVersion($DBversion);
4543 }
4544
4545 $DBversion = "3.05.00.023";
4546 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4547     $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');");
4548     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";
4549     SetVersion($DBversion);
4550 }
4551
4552 $DBversion = "3.06.00.000";
4553 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4554     print "Upgrade to $DBversion done Koha 3.6.0 release \n";
4555     SetVersion ($DBversion);
4556 }
4557
4558 $DBversion = "3.07.00.001";
4559 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4560     my $borrowers = $dbh->selectcol_arrayref( "SELECT borrowernumber from borrowers where debarred =1;", { Columns => [1] } );
4561     $dbh->do("ALTER TABLE borrowers MODIFY debarred DATE DEFAULT NULL;");
4562     $dbh->do( "UPDATE borrowers set debarred='9999-12-31' where borrowernumber IN (" . join( ",", @$borrowers ) . ");" ) if ($borrowers and scalar(@$borrowers)>0);
4563     $dbh->do("ALTER TABLE borrowers ADD COLUMN debarredcomment VARCHAR(255) DEFAULT NULL AFTER debarred;");
4564     $dbh->do("ALTER TABLE deletedborrowers MODIFY debarred DATE DEFAULT NULL;");
4565     $dbh->do("ALTER TABLE deletedborrowers ADD COLUMN debarredcomment VARCHAR(255) DEFAULT NULL AFTER debarred;");
4566     print "Upgrade done (Change borrowers.debarred into Date )\n";
4567     SetVersion($DBversion);
4568 }
4569
4570 $DBversion = "3.07.00.002";
4571 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4572     $dbh->do("UPDATE borrowers SET debarred=NULL WHERE debarred='0000-00-00';");
4573     print "Setting NULL to debarred where 0000-00-00 is stored (bug 7272)\n";
4574     SetVersion($DBversion);
4575 }
4576
4577 $DBversion = "3.07.00.003";
4578 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4579     $dbh->do(" UPDATE `message_attributes` SET message_name='Item_Due' WHERE message_name='Item_DUE'");
4580     print "Updating message_name in message_attributes\n";
4581     SetVersion($DBversion);
4582 }
4583
4584 $DBversion = "3.07.00.004";
4585 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4586     $dbh->do("ALTER TABLE  `suggestions` ADD  `patronreason` TEXT NULL AFTER  `reason`");
4587     print "Upgrade to $DBversion done (Add column to suggestions table to store patrons' reasons for submitting a suggestion. )\n";
4588     SetVersion($DBversion);
4589 }
4590
4591 $DBversion = "3.07.00.005";
4592 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4593     $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')");
4594     print "Upgrade to $DBversion done (BorrowerUnwantedField syspref)\n";
4595     SetVersion ($DBversion);
4596 }
4597
4598 $DBversion = "3.07.00.006";
4599 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4600     $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');");
4601     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";
4602     SetVersion($DBversion);
4603 }
4604
4605 $DBversion = "3.07.00.007";
4606 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4607     $dbh->do("ALTER TABLE items MODIFY materials text;");
4608     print "Upgrade to $DBversion done alter items.material from varchar(10) to text \n";
4609     SetVersion($DBversion);
4610 }
4611
4612 $DBversion = '3.07.00.008';
4613 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4614     if (C4::Context->preference("marcflavour") eq 'MARC21') {
4615         if (C4::Context->preference("opaclanguages") eq "de") {
4616             $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, '');");
4617         } else {
4618             $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, '');");
4619         }
4620     }
4621     print "Upgrade to $DBversion done (add MARC21 field 545 to framework)\n";
4622     SetVersion ($DBversion);
4623 }
4624
4625 $DBversion = "3.07.00.009";
4626 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4627     $dbh->do("ALTER TABLE `aqorders` ADD COLUMN `claims_count` INT(11)  DEFAULT 0, ADD COLUMN `claimed_date` DATE  DEFAULT NULL AFTER `claims_count`");
4628     print "Upgrade to $DBversion done (Add claims_count and claimed_date fields in aqorders table)\n";
4629     SetVersion($DBversion);
4630 }
4631
4632 $DBversion = "3.07.00.010";
4633 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4634     $dbh->do(
4635         q|CREATE TABLE `biblioimages` (
4636           `imagenumber` int(11) NOT NULL AUTO_INCREMENT,
4637           `biblionumber` int(11) NOT NULL,
4638           `mimetype` varchar(15) NOT NULL,
4639           `imagefile` mediumblob NOT NULL,
4640           `thumbnail` mediumblob NOT NULL,
4641           PRIMARY KEY (`imagenumber`),
4642           CONSTRAINT `bibliocoverimage_fk1` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
4643           ) ENGINE=InnoDB DEFAULT CHARSET=utf8|
4644     );
4645     $dbh->do(
4646         q|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OPACLocalCoverImages','0','Display local cover images on OPAC search and details pages.','1','YesNo')|
4647         );
4648     $dbh->do(
4649         q|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('LocalCoverImages','0','Display local cover images on intranet search and details pages.','1','YesNo')|
4650         );
4651     $dbh->do(
4652         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')|
4653     );
4654     $dbh->do(
4655         q|INSERT INTO permissions (module_bit, code, description) VALUES (13, 'upload_local_cover_images', 'Upload local cover images')|
4656     );
4657     print "Upgrade to $DBversion done (Added support for local cover images)\n";
4658     SetVersion($DBversion);
4659 }
4660
4661 $DBversion = "3.07.00.011";
4662 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4663     $dbh->do(<<ENDOFRENEWAL);
4664     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');
4665 ENDOFRENEWAL
4666     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";
4667     SetVersion($DBversion);
4668 }
4669
4670 $DBversion = "3.07.00.012";
4671 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4672     $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')");
4673     print "Upgrade to $DBversion add 'AllowItemsOnHoldCheckout' syspref \n";
4674     SetVersion ($DBversion);
4675 }
4676
4677 $DBversion = "3.07.00.013";
4678 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4679     $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');");
4680     print "Upgrade to $DBversion done (Bug 7345: Add system preference OpacExportOptions.)\n";
4681     SetVersion ($DBversion);
4682 }
4683
4684 $DBversion = "3.07.00.014";
4685 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4686     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";
4687     SetVersion($DBversion);
4688 }
4689
4690 $DBversion = "3.07.00.015";
4691 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4692     my $sth = $dbh->prepare(q|
4693         SELECT COUNT(*) FROM marc_subfield_structure where kohafield="biblioitems.editionstatement"
4694         |);
4695     $sth->execute;
4696     my $already_exists = $sth->fetchrow;
4697     if ( not $already_exists ) {
4698         my $field = C4::Context->preference("marcflavour") eq "UNIMARC" ? "205" : "250";
4699         my $subfield = "a";
4700         my $sth = $dbh->prepare( q|
4701             UPDATE marc_subfield_structure SET kohafield = "biblioitems.editionstatement"
4702             WHERE tagfield = ? AND tagsubfield = ?
4703         |);
4704         $sth->execute( $field, $subfield );
4705         print "Upgrade to $DBversion done (Added a mapping for biblioitems.editionstatement.)\n";
4706     } else {
4707         print "Upgrade to $DBversion done (Added a mapping for biblioitems.editionstatement (already exists, nothing to do).)\n";
4708     }
4709     SetVersion($DBversion);
4710 }
4711
4712 $DBversion = "3.07.00.016";
4713 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4714     $dbh->do("ALTER TABLE items ADD KEY `itemcallnumber` (itemcallnumber)");
4715     print "Upgrade to $DBversion done (Added index on items.itemcallnumber)\n";
4716     SetVersion($DBversion);
4717 }
4718
4719 $DBversion = "3.07.00.017";
4720 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4721     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('TransferWhenCancelAllWaitingHolds','0','Transfer items when cancelling all waiting holds',NULL,'YesNo')");
4722     print "Upgrade to $DBversion done (Add sysprefs to control transfer when cancel all waiting holds)\n";
4723     SetVersion ($DBversion);
4724 }
4725
4726 $DBversion = "3.07.00.018";
4727 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4728     $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;");
4729     print "Upgrade to $DBversion done ( adding offline operations table )\n";
4730     SetVersion($DBversion);
4731 }
4732
4733 $DBversion = "3.07.00.019";
4734 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4735     $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");
4736     $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");
4737     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";
4738     SetVersion($DBversion);
4739 }
4740
4741 $DBversion = "3.07.00.020";
4742 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4743     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OPACpatronimages',0,'Enable patron images in the OPAC',NULL,'YesNo');");
4744     print "Upgrade to $DBversion done (Bug 3516: Add the option to show patron images in the OPAC.)\n";
4745     SetVersion($DBversion);
4746 }
4747
4748 $DBversion = "3.07.00.021";
4749 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4750     $dbh->do(
4751     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('LinkerModule','Default','Chooses which linker module to use (see documentation).','Default|FirstMatchLastMatch','Choice');"
4752     );
4753     $dbh->do(
4754     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('LinkerOptions','','A pipe-separated list of options for the linker.','','free');"
4755     );
4756     $dbh->do(
4757     "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');"
4758     );
4759     $dbh->do(
4760     "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');"
4761     );
4762     $dbh->do(
4763     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AutoCreateAuthorities',0,'Automatically create authorities that do not exist when cataloging records.',NULL,'YesNo');"
4764     );
4765     $dbh->do(
4766     "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');"
4767     );
4768     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";
4769     SetVersion($DBversion);
4770 }
4771
4772 $DBversion = "3.07.00.022";
4773 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4774     $dbh->do("DELETE FROM reviews WHERE biblionumber NOT IN (SELECT biblionumber from biblio)");
4775     $dbh->do("UPDATE reviews SET borrowernumber = NULL WHERE borrowernumber NOT IN (SELECT borrowernumber FROM borrowers)");
4776     $dbh->do("ALTER TABLE reviews ADD CONSTRAINT reviews_ibfk_2 FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE");
4777     $dbh->do("ALTER TABLE reviews ADD CONSTRAINT reviews_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber ) ON UPDATE CASCADE ON DELETE SET NULL");
4778     print "Upgrade to $DBversion done (Bug 7493 - Add constraint linking OPAC comment biblionumber to biblio, OPAC comment borrowernumber to borrowers.)\n";
4779     SetVersion($DBversion);
4780 }
4781
4782 $DBversion = "3.07.00.023";
4783 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4784     $dbh->do("ALTER TABLE `message_transports` DROP FOREIGN KEY `message_transports_ibfk_3`");
4785     $dbh->do("ALTER TABLE `letter` DROP PRIMARY KEY");
4786     $dbh->do("ALTER TABLE `letter` ADD `branchcode` varchar(10) default NULL AFTER `code`");
4787     $dbh->do("ALTER TABLE `letter` ADD PRIMARY KEY  (`module`,`code`, `branchcode`)");
4788     $dbh->do("ALTER TABLE `message_transports` ADD `branchcode` varchar(10) NOT NULL default ''");
4789     $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");
4790     $dbh->do("ALTER TABLE `letter` ADD `is_html` tinyint(1) default 0 AFTER `name`");
4791
4792     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4793               VALUES ('circulation','ISSUESLIP','Issue Slip','Issue Slip', '<h3><<branches.branchname>></h3>
4794 Checked out to <<borrowers.title>> <<borrowers.firstname>> <<borrowers.initials>> <<borrowers.surname>> <br />
4795 (<<borrowers.cardnumber>>) <br />
4796
4797 <<today>><br />
4798
4799 <h4>Checked Out</h4>
4800 <checkedout>
4801 <p>
4802 <<biblio.title>> <br />
4803 Barcode: <<items.barcode>><br />
4804 Date due: <<issues.date_due>><br />
4805 </p>
4806 </checkedout>
4807
4808 <h4>Overdues</h4>
4809 <overdue>
4810 <p>
4811 <<biblio.title>> <br />
4812 Barcode: <<items.barcode>><br />
4813 Date due: <<issues.date_due>><br />
4814 </p>
4815 </overdue>
4816
4817 <hr>
4818
4819 <h4 style=\"text-align: center; font-style:italic;\">News</h4>
4820 <news>
4821 <div class=\"newsitem\">
4822 <h5 style=\"margin-bottom: 1px; margin-top: 1px\"><b><<opac_news.title>></b></h5>
4823 <p style=\"margin-bottom: 1px; margin-top: 1px\"><<opac_news.new>></p>
4824 <p class=\"newsfooter\" style=\"font-size: 8pt; font-style:italic; margin-bottom: 1px; margin-top: 1px\">Posted on <<opac_news.timestamp>></p>
4825 <hr />
4826 </div>
4827 </news>', 1)");
4828     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4829               VALUES ('circulation','ISSUEQSLIP','Issue Quick Slip','Issue Quick Slip', '<h3><<branches.branchname>></h3>
4830 Checked out to <<borrowers.title>> <<borrowers.firstname>> <<borrowers.initials>> <<borrowers.surname>> <br />
4831 (<<borrowers.cardnumber>>) <br />
4832
4833 <<today>><br />
4834
4835 <h4>Checked Out Today</h4>
4836 <checkedout>
4837 <p>
4838 <<biblio.title>> <br />
4839 Barcode: <<items.barcode>><br />
4840 Date due: <<issues.date_due>><br />
4841 </p>
4842 </checkedout>', 1)");
4843     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4844               VALUES ('circulation','RESERVESLIP','Reserve Slip','Reserve Slip', '<h5>Date: <<today>></h5>
4845
4846 <h3> Transfer to/Hold in <<branches.branchname>></h3>
4847
4848 <h3><<borrowers.surname>>, <<borrowers.firstname>></h3>
4849
4850 <ul>
4851     <li><<borrowers.cardnumber>></li>
4852     <li><<borrowers.phone>></li>
4853     <li> <<borrowers.address>><br />
4854          <<borrowers.address2>><br />
4855          <<borrowers.city >>  <<borrowers.zipcode>>
4856     </li>
4857     <li><<borrowers.email>></li>
4858 </ul>
4859 <br />
4860 <h3>ITEM ON HOLD</h3>
4861 <h4><<biblio.title>></h4>
4862 <h5><<biblio.author>></h5>
4863 <ul>
4864    <li><<items.barcode>></li>
4865    <li><<items.itemcallnumber>></li>
4866    <li><<reserves.waitingdate>></li>
4867 </ul>
4868 <p>Notes:
4869 <pre><<reserves.reservenotes>></pre>
4870 </p>', 1)");
4871     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4872               VALUES ('circulation','TRANSFERSLIP','Transfer Slip','Transfer Slip', '<h5>Date: <<today>></h5>
4873 <h3>Transfer to <<branches.branchname>></h3>
4874
4875 <h3>ITEM</h3>
4876 <h4><<biblio.title>></h4>
4877 <h5><<biblio.author>></h5>
4878 <ul>
4879    <li><<items.barcode>></li>
4880    <li><<items.itemcallnumber>></li>
4881 </ul>', 1)");
4882
4883     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('NoticeCSS','','Notices CSS url.',NULL,'free')");
4884     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('SlipCSS','','Slips CSS url.',NULL,'free')");
4885
4886     $dbh->do("UPDATE `letter` SET content = replace(content, '<<title>>', '<<biblio.title>>') WHERE code = 'HOLDPLACED'");
4887
4888     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";
4889     SetVersion($DBversion);
4890 }
4891
4892 $DBversion = "3.07.00.024";
4893 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4894     $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')");
4895     $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')");
4896     print "Upgrade to $DBversion done (Added system preference ExpireReservesMaxPickUpDelay, system preference ExpireReservesMaxPickUpDelayCharge, add reseves.charge_if_expired)\n";
4897 }
4898
4899 $DBversion = "3.07.00.025";
4900 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4901     if (TableExists('bibliocoverimage')) {
4902         $dbh->do( q|DROP TABLE bibliocoverimage;| );
4903         $dbh->do(
4904             q|CREATE TABLE biblioimages (
4905               imagenumber int(11) NOT NULL AUTO_INCREMENT,
4906               biblionumber int(11) NOT NULL,
4907               mimetype varchar(15) NOT NULL,
4908               imagefile mediumblob NOT NULL,
4909               thumbnail mediumblob NOT NULL,
4910               PRIMARY KEY (imagenumber),
4911               CONSTRAINT bibliocoverimage_fk1 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
4912               ) ENGINE=InnoDB DEFAULT CHARSET=utf8;|
4913         );
4914     }
4915     print "Upgrade to $DBversion done (Correct table name for local cover images if needed. )\n";
4916     SetVersion($DBversion);
4917 }
4918
4919 $DBversion = "3.07.00.026";
4920 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4921     $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');");
4922     print "Upgrade to $DBversion done (Add syspref CalendarFirstDayOfWeek used to select the first day of week to use in the calendar. )\n";
4923     SetVersion($DBversion);
4924 }
4925
4926 $DBversion = "3.07.00.027";
4927 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4928     $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');});
4929     print "Upgrade to $DBversion done (Added system preference RoutingListNote for adding a general note to all routing lists.)\n";
4930     SetVersion($DBversion);
4931 }
4932
4933 $DBversion = "3.07.00.028";
4934 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4935     $dbh->do(qq{
4936     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');
4937     });
4938     print "Upgrade to $DBversion done (Bug 6296 New System preference AllowPKIAuth)\n";
4939 }
4940
4941 $DBversion = "3.07.00.029";
4942 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4943     my $installer = C4::Installer->new();
4944     my $full_path = C4::Context->config('intranetdir') . "/installer/data/$installer->{dbms}/atomicupdate/oai_sets.sql";
4945     my $error     = $installer->load_sql($full_path);
4946     warn $error if $error;
4947     print "Upgrade to $DBversion done (Atomic update for OAI-PMH sets management)\n";
4948     SetVersion($DBversion);
4949 }
4950
4951 $DBversion = "3.07.00.030";
4952 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4953     $dbh->do("ALTER TABLE default_circ_rules ADD
4954             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
4955     $dbh->do("ALTER TABLE branch_item_rules ADD
4956             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
4957     $dbh->do("ALTER TABLE default_branch_circ_rules ADD
4958             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
4959     $dbh->do("ALTER TABLE default_branch_item_rules ADD
4960             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
4961     # set the default rule to the current value of HomeOrHoldingBranchReturn (default to 'homebranch' if need be)
4962     my $homeorholdingbranchreturn = C4::Context->prefernce('HomeOrHoldingBranchReturn') || 'homebranch';
4963     $dbh->do("UPDATE default_circ_rules SET returnbranch = '$homeorholdingbranchreturn'");
4964     print "Upgrade to $DBversion done (Atomic update for OAI-PMH sets management)\n";
4965     SetVersion($DBversion);
4966 }
4967
4968 $DBversion = "3.07.00.031";
4969 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4970     $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')");
4971     print "Upgrade to $DBversion done (Add syspref to tell Koha if ICU indexing is in use for Zebra or not.)\n";
4972     SetVersion ($DBversion);
4973 }
4974
4975 $DBversion = "3.07.00.032";
4976 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4977     $dbh->do("ALTER TABLE virtualshelves MODIFY COLUMN owner int"); #should have been int already (fk to borrowers)
4978     $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
4979     $dbh->do("DELETE FROM virtualshelves WHERE owner IS NULL and category=1"); #delete private lists without owner (cascades to shelfcontents)
4980     $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");
4981     $dbh->do("UPDATE virtualshelves SET allow_add=0, allow_delete_own=1, allow_delete_other=0 WHERE category=1");
4982     $dbh->do("UPDATE virtualshelves SET allow_add=0, allow_delete_own=1, allow_delete_other=0 WHERE category=2");
4983     $dbh->do("UPDATE virtualshelves SET allow_add=1, allow_delete_own=1, allow_delete_other=1 WHERE category=3");
4984     $dbh->do("UPDATE virtualshelves SET category=2 WHERE category=3");
4985
4986     $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");
4987     $dbh->do("UPDATE virtualshelfcontents co LEFT JOIN virtualshelves sh USING (shelfnumber) SET co.borrowernumber=sh.owner");
4988
4989     $dbh->do("CREATE TABLE virtualshelfshares
4990     (id int AUTO_INCREMENT PRIMARY KEY, shelfnumber int NOT NULL,
4991     borrowernumber int, invitekey varchar(10), sharedate datetime,
4992     CONSTRAINT `virtualshelfshares_ibfk_1` FOREIGN KEY (`shelfnumber`) REFERENCES `virtualshelves` (`shelfnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
4993         CONSTRAINT `virtualshelfshares_ibfk_2` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE SET NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8");
4994
4995     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacAllowPublicListCreation',1,'If set, allows opac users to create public lists',NULL,'YesNo');");
4996     $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');");
4997
4998     print "Upgrade to $DBversion done (BZ7310: Improving list permissions)\n";
4999     SetVersion($DBversion);
5000 }
5001
5002 $DBversion = "3.07.00.033";
5003 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5004     $dbh->do("ALTER TABLE branches ADD opac_info text;");
5005     print "Upgrade to $DBversion done add opac_info to branches \n";
5006     SetVersion($DBversion);
5007 }
5008
5009 $DBversion = "3.07.00.034";
5010 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5011     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN category_code VARCHAR(10) NULL DEFAULT NULL AFTER `display_checkout`");
5012     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN class VARCHAR(255)  NOT NULL DEFAULT '' AFTER `category_code`");
5013     $dbh->do("ALTER TABLE borrower_attribute_types ADD CONSTRAINT category_code_fk FOREIGN KEY (category_code) REFERENCES categories(categorycode)");
5014     print "Upgrade to $DBversion done (New fields category_code and class in borrower_attribute_types table)\n";
5015     SetVersion($DBversion);
5016 }
5017
5018 $DBversion = "3.07.00.035";
5019 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5020     $dbh->do("ALTER TABLE issues CHANGE date_due date_due datetime");
5021     $dbh->do("UPDATE issues SET date_due = CONCAT(SUBSTR(date_due,1,11),'23:59:00')");
5022     $dbh->do("ALTER TABLE issues CHANGE returndate returndate datetime");
5023     $dbh->do("ALTER TABLE issues CHANGE lastreneweddate lastreneweddate datetime");
5024     $dbh->do("ALTER TABLE issues CHANGE issuedate issuedate datetime");
5025     $dbh->do("ALTER TABLE old_issues CHANGE date_due date_due datetime");
5026     $dbh->do("ALTER TABLE old_issues CHANGE returndate returndate datetime");
5027     $dbh->do("ALTER TABLE old_issues CHANGE lastreneweddate lastreneweddate datetime");
5028     $dbh->do("ALTER TABLE old_issues CHANGE issuedate issuedate datetime");
5029     print "Upgrade to $DBversion done (Setting up issues tables for hourly loans)\n";
5030     SetVersion($DBversion);
5031 }
5032
5033 $DBversion = "3.07.00.036";
5034 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5035     $dbh->do(qq{
5036        ALTER TABLE z3950servers ADD timeout INT( 11 ) NOT NULL DEFAULT '0' AFTER syntax;
5037     });
5038     print "Upgrade to $DBversion done (New timeout field in z3950servers)\n";
5039 }
5040
5041 $DBversion = "3.07.00.037";
5042 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5043     $dbh->do("
5044        ALTER TABLE  `marc_subfield_structure` ADD  `maxlength` INT( 4 ) NOT NULL DEFAULT  '9999';
5045        ");
5046        $dbh->do("
5047        UPDATE `marc_subfield_structure` SET maxlength=24 WHERE tagfield='000';
5048        ");
5049        $dbh->do("
5050        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='MARC21','40','9999') WHERE tagfield='008';
5051        ");
5052        $dbh->do("
5053        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='NORMARC','40','9999') WHERE tagfield='008';
5054        ");
5055        $dbh->do("
5056        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='UNIMARC','36','9999') WHERE tagfield='100';
5057        ");
5058     print "Upgrade to $DBversion done (Add new field maxlength to marc_subfield_structure)\n";
5059     SetVersion($DBversion);
5060 }
5061
5062 $DBversion = "3.07.00.038";
5063 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5064     $dbh->do(qq{
5065         INSERT INTO systempreferences(variable,value,explanation,options,type)
5066         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')
5067     });
5068     print "Upgrade to $DBversion done (Added system preference 'UniqueItemFields')\n";
5069     SetVersion($DBversion);
5070 }
5071
5072 $DBversion = "3.07.00.039";
5073 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5074     $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')} );
5075     $dbh->do( qq{CREATE TABLE IF NOT EXISTS social_data
5076       ( isbn VARCHAR(30),
5077         num_critics INT,
5078         num_critics_pro INT,
5079         num_quotations INT,
5080         num_videos INT,
5081         score_avg DECIMAL(5,2),
5082         num_scores INT,
5083         PRIMARY KEY  (isbn)
5084       ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5085     } );
5086     $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')} );
5087     print "Upgrade to $DBversion done (added syspref and table for babeltheque (Babeltheque_url_js, babeltheque))\n";
5088     SetVersion($DBversion);
5089 }
5090
5091 $DBversion = "3.07.00.040";
5092 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5093     $dbh->do( qq{INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('SocialNetworks','0','Enable/Disable social networks links in opac detail','','YesNo')} );
5094     print "Upgrade to $DBversion done (added syspref SocialNetworks, to display facebook/ggl+ and other buttons)\n";
5095     SetVersion($DBversion);
5096 }
5097
5098
5099
5100 $DBversion = "3.07.00.041";
5101 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5102     $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')");
5103     print "Upgrade to $DBversion done (Add system preference SubscriptionDuplicateDroppedInput)\n";
5104     SetVersion($DBversion);
5105 }
5106
5107 $DBversion = "3.07.00.042";
5108 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5109     $dbh->do("ALTER TABLE reserves ADD suspend BOOLEAN NOT NULL DEFAULT 0");
5110     $dbh->do("ALTER TABLE old_reserves ADD suspend BOOLEAN NOT NULL DEFAULT 0");
5111
5112     $dbh->do("ALTER TABLE reserves ADD suspend_until DATETIME NULL DEFAULT NULL");
5113     $dbh->do("ALTER TABLE old_reserves ADD suspend_until DATETIME NULL DEFAULT NULL");
5114
5115     $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')");
5116
5117     print "Upgrade to $DBversion done (Add suspend fields to reserves table, add syspref AutoResumeSuspendedHolds)\n";
5118     SetVersion ($DBversion);
5119 }
5120
5121 $DBversion = "3.07.00.043";
5122 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5123     my $countXSLTDetailsDisplay = 0;
5124     my $valueXSLTDetailsDisplay = "";
5125     my $valueXSLTResultsDisplay = "";
5126     my $valueOPACXSLTDetailsDisplay = "";
5127     my $valueOPACXSLTResultsDisplay = "";
5128     #the line below test if database comes from a BibLibre's branch
5129     $countXSLTDetailsDisplay = $dbh->do('SELECT 1 FROM systempreferences WHERE variable="IntranetXSLTDetailsDisplay"');
5130     if ($countXSLTDetailsDisplay > 0)
5131     {
5132         #the two lines below will only be used to update the databases from the BibLibre's branch. They will not affect the others
5133         $dbh->do(q|UPDATE systempreferences SET variable="XSLTDetailsDisplay" WHERE variable="IntranetXSLTDetailsDisplay"|);
5134         $dbh->do(q|UPDATE systempreferences SET variable="XSLTResultsDisplay" WHERE variable="IntranetXSLTResultsDisplay"|);
5135     }
5136     else
5137     {
5138         $valueXSLTDetailsDisplay = "default" if (C4::Context->preference("XSLTDetailsDisplay"));
5139         $valueXSLTResultsDisplay = "default" if (C4::Context->preference("XSLTResultsDisplay"));
5140         $valueOPACXSLTDetailsDisplay = "default" if (C4::Context->preference("OPACXSLTDetailsDisplay"));
5141         $valueOPACXSLTResultsDisplay = "default" if (C4::Context->preference("OPACXSLTResultsDisplay"));
5142         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueXSLTDetailsDisplay\" WHERE variable='XSLTDetailsDisplay'");
5143         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueXSLTResultsDisplay\" WHERE variable='XSLTResultsDisplay'");
5144         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueOPACXSLTDetailsDisplay\" WHERE variable='OPACXSLTDetailsDisplay'");
5145         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueOPACXSLTResultsDisplay\" WHERE variable='OPACXSLTResultsDisplay'");
5146     }
5147     print "Upgrade to $DBversion done (XSLT systempreference takes a path to file rather than YesNo)\n";
5148     SetVersion($DBversion);
5149 }
5150
5151 $DBversion = "3.07.00.044";
5152 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5153     $dbh->do("ALTER TABLE aqbooksellers ADD deliverytime INT DEFAULT NULL");
5154     print "Upgrade to $DBversion done (Add deliverytime field in aqbooksellers table)";
5155     SetVersion($DBversion);
5156 }
5157
5158 $DBversion = "3.07.00.045";
5159 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5160     $dbh->do("ALTER TABLE import_batches MODIFY COLUMN batch_type ENUM('batch','z3950','webservice') NOT NULL default 'batch'");
5161     print "Upgrade to $DBversion done (Add 'webservice' to batch_type enum)\n";
5162     SetVersion ($DBversion);
5163 }
5164
5165 $DBversion = "3.07.00.046";
5166 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5167     $dbh->do("ALTER TABLE issuingrules ADD COLUMN lengthunit varchar(10) DEFAULT 'days' AFTER issuelength");
5168     print "Upgrade to $DBversion done (Setting up issues tables for hourly loans (lengthunit fix))\n";
5169     SetVersion($DBversion);
5170 }
5171
5172 $DBversion = "3.07.00.047";
5173 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5174     $dbh->do("CREATE INDEX items_location ON items(location)");
5175     $dbh->do("CREATE INDEX items_ccode ON items(ccode)");
5176     print "Upgrade to $DBversion done (items_location and items_ccode indexes added for ShelfBrowser)\n";
5177     SetVersion($DBversion);
5178 }
5179
5180 $DBversion = "3.07.00.048";
5181 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5182     $dbh->do(
5183         q | CREATE TABLE ratings (
5184   borrowernumber int(11) NOT NULL,
5185   biblionumber int(11) NOT NULL,
5186   rating_value tinyint(1) NOT NULL,
5187   timestamp timestamp NOT NULL default CURRENT_TIMESTAMP,
5188   PRIMARY KEY  (borrowernumber,biblionumber),
5189   CONSTRAINT ratings_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE,
5190   CONSTRAINT ratings_ibfk_2 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
5191 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
5192     );
5193
5194     $dbh->do(
5195 q /INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OpacStarRatings','disable',NULL,'disable|all|details','Choice') /
5196     );
5197
5198     print
5199 "Upgrade to $DBversion done (Add 'ratings' table and 'OpacStarRatings' syspref)\n";
5200     SetVersion($DBversion);
5201 }
5202
5203 $DBversion = "3.07.00.049";
5204 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5205     $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')");
5206     print "Upgrade to $DBversion done (Add system preference OpacBrowseResults ))\n";
5207     SetVersion($DBversion);
5208 }
5209
5210 $DBversion = "3.08.00.000";
5211 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5212     print "Upgrade to $DBversion done\n";
5213     SetVersion($DBversion);
5214 }
5215
5216 $DBversion = "3.09.00.001";
5217 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5218     $dbh->do("ALTER TABLE borrower_attribute_types MODIFY category_code VARCHAR( 1 ) NULL DEFAULT NULL");
5219     print "Upgrade to $DBversion done. (Bug 8002: Update patron attribute types table to allow NULL category_code)\n";
5220     SetVersion($DBversion);
5221 }
5222
5223 $DBversion = "3.09.00.002";
5224 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5225     $dbh->do("ALTER TABLE saved_sql
5226         ADD (
5227             cache_expiry INT NOT NULL DEFAULT 300,
5228             public BOOLEAN NOT NULL DEFAULT FALSE
5229         );
5230     ");
5231     print "Upgrade to $DBversion done (Added cache_expiry and public fields in
5232 saved_reports table.)\n";
5233     SetVersion($DBversion);
5234 }
5235
5236 $DBversion = "3.09.00.003";
5237 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5238     $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');");
5239     print "Upgrade to $DBversion done (Added SvcMaxReportRows syspref)\n";
5240     SetVersion($DBversion);
5241 }
5242
5243 $DBversion = "3.09.00.004";
5244 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5245     $dbh->do("INSERT IGNORE INTO permissions (module_bit, code, description) VALUES('13', 'edit_patrons', 'Perform batch modifivation of patrons')");
5246     print "Upgrade to $DBversion done (Adds permissions flag for access to the patron modifications tool)\n";
5247     SetVersion($DBversion);
5248 }
5249
5250 $DBversion = "3.09.00.005";
5251 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5252     unless (TableExists('quotes')) {
5253         $dbh->do( qq{
5254             CREATE TABLE `quotes` (
5255               `id` int(11) NOT NULL AUTO_INCREMENT,
5256               `source` text DEFAULT NULL,
5257               `text` mediumtext NOT NULL,
5258               `timestamp` datetime NOT NULL,
5259               PRIMARY KEY (`id`)
5260             ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5261         });
5262     }
5263     $dbh->do( qq{
5264         INSERT IGNORE INTO permissions VALUES (13, "edit_quotes","Edit quotes for quote-of-the-day feature");
5265     });
5266     $dbh->do( qq{
5267         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');
5268     });
5269     print "Upgrade to $DBversion done (Adding Quote of the Day Option.)\n";
5270     SetVersion($DBversion);
5271 }
5272
5273 $DBversion = "3.09.00.006";
5274 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5275     $dbh->do("UPDATE systempreferences SET
5276                 variable = 'OPACShowHoldQueueDetails',
5277                 value = CASE value WHEN '1' THEN 'priority' ELSE 'none' END,
5278                 options = 'none|priority|holds|holds_priority',
5279                 explanation = 'Show holds details in OPAC',
5280                 type = 'Choice'
5281               WHERE variable = 'OPACDisplayRequestPriority'");
5282     print "Upgrade to $DBversion done (Changed system preference OPACDisplayRequestPriority -> OPACShowHoldQueueDetails)\n";
5283     SetVersion($DBversion);
5284 }
5285
5286 $DBversion = "3.09.00.007";
5287 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5288     unless(C4::Context->preference('ReservesControlBranch')){
5289         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('ReservesControlBranch','PatronLibrary','ItemHomeLibrary|PatronLibrary','Branch checked for members reservations rights.','Choice')");
5290     }
5291     print "Upgrade to $DBversion done (Insert ReservesControlBranch systempreference into systempreferences table )\n";
5292     SetVersion($DBversion);
5293 }
5294
5295 $DBversion = "3.09.00.008";
5296 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5297     $dbh->do("ALTER TABLE sessions ADD PRIMARY KEY (id);");
5298     $dbh->do("ALTER TABLE sessions DROP INDEX `id`;");
5299     print "Upgrade to $DBversion done (redefine the field id as PRIMARY KEY of sessions)\n";
5300     SetVersion($DBversion);
5301 }
5302
5303 $DBversion = "3.09.00.009";
5304 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5305     $dbh->do("ALTER TABLE branches ADD PRIMARY KEY (branchcode);");
5306     $dbh->do("ALTER TABLE branches DROP INDEX branchcode;");
5307     print "Upgrade to $DBversion done (redefine the field branchcode as PRIMARY KEY of branches)\n";
5308     SetVersion ($DBversion);
5309 }
5310
5311 $DBversion = "3.09.00.010";
5312 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5313     $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')");
5314     print "Upgrade to $DBversion done (Add system preference issuelostitem ))\n";
5315     SetVersion($DBversion);
5316 }
5317
5318 $DBversion = "3.09.00.011";
5319 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5320     $dbh->do("ALTER TABLE `biblioitems` ADD `ean` VARCHAR( 13 ) NULL AFTER issn");
5321     $dbh->do("CREATE INDEX `ean` ON biblioitems (`ean`) ");
5322     $dbh->do("ALTER TABLE `deletedbiblioitems` ADD `ean` VARCHAR( 13 ) NULL AFTER issn");
5323     if (C4::Context->preference("marcflavour") eq 'UNIMARC') {
5324          $dbh->do("UPDATE marc_subfield_structure SET kohafield='biblioitems.ean' WHERE tagfield='073' and tagsubfield='a'");
5325     }
5326     print "Upgrade to $DBversion done (Adding ean in biblioitems and deletedbiblioitems)\n";
5327     print "If you have records with ean, please run misc/batchRebuildBiblioTables.pl to populate bibliotems.ean\n" if (C4::Context->preference("marcflavour") eq 'UNIMARC');
5328     SetVersion($DBversion);
5329 }
5330
5331 $DBversion = "3.09.00.012";
5332 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5333     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('SuspendHoldsIntranet', '1', NULL , 'Allow holds to be suspended from the intranet.', 'YesNo')");
5334     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('SuspendHoldsOpac', '1', NULL , 'Allow holds to be suspended from the OPAC.', 'YesNo')");
5335     print "Upgrade to $DBversion done (Add system preference OpacBrowseResults ))\n";
5336     SetVersion($DBversion);
5337 }
5338
5339 $DBversion ="3.09.00.013";
5340 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5341     $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');");
5342     print "Upgrade to $DBversion done (Add system preference DefaultLanguageField008))\n";
5343     SetVersion($DBversion);
5344 }
5345
5346 $DBversion ="3.09.00.014";
5347 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5348     # add phone message transport type
5349     $dbh->do("INSERT INTO message_transport_types (message_transport_type) VALUES ('phone')");
5350     
5351     # adds HOLD_PHONE and PREDUE_PHONE letters (as placeholders)
5352     $dbh->do("INSERT INTO letter (module, code, name, title, content) VALUES
5353               ('reserves', 'HOLD_PHONE', 'Item Available for Pick-up (phone notice)', 'Item Available for Pick-up (phone notice)', 'Your item is available for pickup'),
5354               ('circulation', 'PREDUE_PHONE', 'Advance Notice of Item Due (phone notice)', 'Advance Notice of Item Due (phone notice)', 'Your item is due soon'),
5355               ('circulation', 'OVERDUE_PHONE', 'Overdue Notice (phone notice)', 'Overdue Notice (phone notice)', 'Your item is overdue')
5356               ");
5357     
5358     # add phone notifications to patron message preferences options
5359     $dbh->do("INSERT INTO message_transports
5360              (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) VALUES
5361              (4, 'phone', 0, 'reserves', 'HOLD_PHONE'),
5362              (2, 'phone', 0, 'circulation', 'PREDUE_PHONE')
5363              ");
5364     
5365     # add TalkingTechItivaPhoneNotification syspref
5366     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('TalkingTechItivaPhoneNotification',0,'If ON, enables Talking Tech I-tiva phone notifications',NULL,'YesNo');");
5367     
5368     print "Upgrade done (Support for Talking Tech i-tiva phone notification system)\n";
5369     SetVersion($DBversion);
5370 }
5371
5372 $DBversion = "3.09.00.015";
5373 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5374     $dbh->do(qq{
5375         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')
5376     });
5377     print "Upgrade to $DBversion done (Add System preference StatisticsFields)\n";
5378     SetVersion($DBversion);
5379 }
5380
5381 $DBversion = "3.09.00.016";
5382 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5383     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACShowBarcode','0','Show items barcode in holding tab','','YesNo')");
5384     print "Upgrade to $DBversion done (Add syspref OPACShowBarcode)\n";
5385     SetVersion ($DBversion);
5386 }
5387
5388 $DBversion = "3.09.00.017";
5389 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5390     $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');");
5391     print "Upgrade to $DBversion done (Add customizable OpacNavRight region to the OPAC main page)\n";
5392     SetVersion ($DBversion);
5393 }
5394
5395 $DBversion = "3.09.00.018";
5396 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5397     $dbh->do("DROP TABLE IF EXISTS aqbudgetborrowers");
5398     $dbh->do("
5399         CREATE TABLE aqbudgetborrowers (
5400           budget_id int(11) NOT NULL,
5401           borrowernumber int(11) NOT NULL,
5402           PRIMARY KEY (budget_id, borrowernumber),
5403           CONSTRAINT aqbudgetborrowers_ibfk_1 FOREIGN KEY (budget_id)
5404             REFERENCES aqbudgets (budget_id)
5405             ON DELETE CASCADE ON UPDATE CASCADE,
5406           CONSTRAINT aqbudgetborrowers_ibfk_2 FOREIGN KEY (borrowernumber)
5407             REFERENCES borrowers (borrowernumber)
5408             ON DELETE CASCADE ON UPDATE CASCADE
5409         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
5410     ");
5411     $dbh->do("
5412         INSERT INTO permissions (module_bit, code, description)
5413         VALUES (11, 'budget_manage_all', 'Manage all budgets')
5414     ");
5415     print "Upgrade to $DBversion done (Add aqbudgetborrowers table)\n";
5416     SetVersion($DBversion);
5417 }
5418
5419 $DBversion = "3.09.00.019";
5420 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5421     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('OPACShowUnusedAuthorities','1','','Show authorities that are not being used in the OPAC.','YesNo')");
5422     print "Upgrade to $DBversion done (Add OPACShowUnusedAuthorities system preference)\n";
5423     SetVersion ($DBversion);
5424 }
5425
5426 $DBversion = "3.09.00.020";
5427 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5428     $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')");
5429     $dbh->do("
5430 CREATE TABLE IF NOT EXISTS borrower_files (
5431   file_id int(11) NOT NULL AUTO_INCREMENT,
5432   borrowernumber int(11) NOT NULL,
5433   file_name varchar(255) NOT NULL,
5434   file_type varchar(255) NOT NULL,
5435   file_description varchar(255) DEFAULT NULL,
5436   file_content longblob NOT NULL,
5437   date_uploaded timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
5438   PRIMARY KEY (file_id),
5439   KEY borrowernumber (borrowernumber)
5440 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
5441     ");
5442     $dbh->do("ALTER TABLE borrower_files ADD CONSTRAINT borrower_files_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE");
5443
5444     print "Upgrade to $DBversion done (Added borrow_files table, EnableBorrowerFiles syspref)\n";
5445     SetVersion($DBversion);
5446 }
5447
5448 $DBversion = "3.09.00.021";
5449 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5450     $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');");
5451     print "Upgrade to $DBversion done (Add syspref UpdateTotalIssuesOnCirc)\n";
5452     SetVersion($DBversion);
5453 }
5454
5455 $DBversion = "3.09.00.022";
5456 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5457     $dbh->do("ALTER TABLE search_history MODIFY COLUMN query_cgi text NOT NULL");
5458     print "Upgrade to $DBversion done (Change search_history.query_cgi type to text. bug 5981)\n";
5459     SetVersion($DBversion);
5460 }
5461
5462 $DBversion = "3.09.00.023";
5463 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5464     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('SearchEngine','Zebra','Solr|Zebra','Search Engine','Choice')");
5465     print "Upgrade to $DBversion done (Add system preference SearchEngine )\n";
5466     SetVersion($DBversion);
5467 }
5468
5469 $DBversion ="3.09.00.024";
5470 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5471     $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')");
5472     print "Upgrade to $DBversion done (Add system preference IntranetSlipPrinterJS))\n";
5473     SetVersion($DBversion);
5474 }
5475
5476 $DBversion = "3.09.00.025";
5477 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5478     $dbh->do('START TRANSACTION');
5479     $dbh->do('CREATE TABLE tmp_reserves AS SELECT * FROM old_reserves LIMIT 0');
5480     $dbh->do('ALTER TABLE tmp_reserves ADD reserve_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
5481     $dbh->do("
5482         INSERT INTO tmp_reserves (
5483           borrowernumber, reservedate, biblionumber,
5484           constrainttype, branchcode, notificationdate,
5485           reminderdate, cancellationdate, reservenotes,
5486           priority, found, timestamp, itemnumber,
5487           waitingdate, expirationdate, lowestPriority
5488         ) SELECT
5489           borrowernumber, reservedate, biblionumber,
5490           constrainttype, branchcode, notificationdate,
5491           reminderdate, cancellationdate, reservenotes,
5492           priority, found, timestamp, itemnumber,
5493           waitingdate, expirationdate, lowestPriority
5494         FROM old_reserves ORDER BY reservedate
5495     ");
5496     $dbh->do('SET @ai = ( SELECT MAX( reserve_id ) FROM tmp_reserves )');
5497     $dbh->do('TRUNCATE old_reserves');
5498     $dbh->do('ALTER TABLE old_reserves ADD reserve_id INT( 11 ) NOT NULL PRIMARY KEY FIRST');
5499     $dbh->do('INSERT INTO old_reserves SELECT * FROM tmp_reserves WHERE reserve_id <= @ai');
5500     $dbh->do("
5501         INSERT INTO tmp_reserves (
5502           borrowernumber, reservedate, biblionumber,
5503           constrainttype, branchcode, notificationdate,
5504           reminderdate, cancellationdate, reservenotes,
5505           priority, found, timestamp, itemnumber,
5506           waitingdate, expirationdate, lowestPriority
5507         ) SELECT
5508           borrowernumber, reservedate, biblionumber,
5509           constrainttype, branchcode, notificationdate,
5510           reminderdate, cancellationdate, reservenotes,
5511           priority, found, timestamp, itemnumber,
5512           waitingdate, expirationdate, lowestPriority
5513         FROM reserves ORDER BY reservedate
5514     ");
5515     $dbh->do('TRUNCATE reserves');
5516     $dbh->do('ALTER TABLE reserves ADD reserve_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
5517     $dbh->do('INSERT INTO reserves SELECT * FROM tmp_reserves WHERE reserve_id > @ai');
5518     $dbh->do('DROP TABLE tmp_reserves');
5519     $dbh->do('COMMIT');
5520
5521     my $sth = $dbh->prepare("
5522         SELECT COUNT( * ) AS count
5523         FROM information_schema.COLUMNS
5524         WHERE COLUMN_NAME =  'reserve_id'
5525         AND (
5526           TABLE_NAME LIKE  'reserves'
5527           OR
5528           TABLE_NAME LIKE  'old_reserves'
5529         )
5530     ");
5531     $sth->execute();
5532     my $row = $sth->fetchrow_hashref();
5533     die("Failed to add reserve_id to reserves tables, please refresh the page to try again.") unless ( $row->{'count'} );
5534
5535     print "Upgrade to $DBversion done (add reserve_id to reserves & old_reserves tables)\n";
5536     SetVersion($DBversion);
5537 }
5538
5539 $DBversion = "3.09.00.026";
5540 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5541     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
5542         ( 3, 'parameters_remaining_permissions', 'Remaining system parameters permissions'),
5543         ( 3, 'manage_circ_rules', 'manage circulation rules')");
5544     $dbh->do("INSERT INTO user_permissions (borrowernumber, module_bit, code)
5545         SELECT borrowernumber, 3, 'parameters_remaining_permissions'
5546         FROM borrowers WHERE flags & (1 << 3)");
5547     # Give new subpermissions to all users that have 'parameters' permission flag (bit 3) set
5548     # see userflags table
5549     $dbh->do("INSERT INTO user_permissions (borrowernumber, module_bit, code)
5550         SELECT borrowernumber, 3, 'manage_circ_rules'
5551         FROM borrowers WHERE flags & (1 << 3)");
5552     print "Upgrade to $DBversion done (Added parameters subpermissions)\n";
5553     SetVersion($DBversion);
5554 }
5555
5556 $DBversion = '3.09.00.027';
5557 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5558     $dbh->do("ALTER TABLE issuingrules ADD overduefinescap decimal DEFAULT NULL");
5559     my $maxfine = C4::Context->preference('MaxFine');
5560     if ($maxfine && $maxfine < 900) { # an arbitrary value that tells us it's not "some huge value"
5561       $dbh->do("UPDATE issuingrules SET overduefinescap=?",undef,$maxfine);
5562       $dbh->do("UPDATE systempreferences SET value = NULL WHERE variable = 'MaxFine'");
5563     }
5564     $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'");
5565     print "Upgrade to $DBversion done (Bug 7420 add overduefinescap to circulation matrix)\n";
5566     SetVersion ($DBversion);
5567 }
5568
5569 $DBversion = "3.09.00.028";
5570 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5571     unless ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) {
5572         my %referencetypes = (  '00' => 'PERSO_CODE',
5573                                 '10' => 'ORGO_CODE',
5574                                 '11' => 'MEETI_NAME',
5575                                 '30' => 'UNIF_TITLE',
5576                                 '48' => 'CHRON_TERM',
5577                                 '50' => 'TOPIC_TERM',
5578                                 '51' => 'GEOGR_NAME',
5579                                 '55' => 'GENRE/FORM'
5580                 );
5581         my $query = q{SELECT DISTINCT authtypecode, tagfield
5582                     FROM auth_subfield_structure
5583                     WHERE (tagfield BETWEEN '400' AND '455' OR
5584                     tagfield BETWEEN '500' and '555') AND tagsubfield='a' AND
5585                     frameworkcode = '' AND ROW(authtypecode, tagfield) NOT IN
5586                     (SELECT authtypecode, tagfield FROM auth_subfield_structure
5587                     WHERE tagsubfield ='9' )};
5588         $sth = $dbh->prepare($query);
5589         $sth->execute;
5590         my $sth2 = $dbh->prepare(q{INSERT INTO auth_subfield_structure
5591                 (authtypecode, tagfield, tagsubfield, liblibrarian, libopac,
5592                  repeatable, mandatory, tab, authorised_value, value_builder,
5593                  seealso, isurl, hidden, linkid, kohafield, frameworkcode)
5594                 VALUES (?, ?, '9', '9 (RLIN)', '9 (RLIN)', 0, 0, ?, NULL, NULL,
5595                     NULL, 0, 1, '', '', '')});
5596         my $sth3 = $dbh->prepare(q{UPDATE auth_subfield_structure SET
5597                                     frameworkcode = ? WHERE authtypecode = ? AND
5598                                     tagfield = ? AND tagsubfield = 'a'});
5599         while (my $row = $sth->fetchrow_arrayref()) {
5600             my ($authtypecode, $field) = @$row;
5601             $sth2->execute($authtypecode, $field, substr($field, 0, 1));
5602             my $authtypemarker = substr $field, 1, 2;
5603             if ($authtypemarker && $referencetypes{$authtypemarker}) {
5604                 $sth3->execute($referencetypes{$authtypemarker}, $authtypecode, $field);
5605             }
5606         }
5607     }
5608
5609     print "Upgrade to $DBversion done (Add thesaurus links for MARC21/NORMARC)\n";
5610     SetVersion($DBversion);
5611 }
5612
5613 =head1 FUNCTIONS
5614
5615 =head2 TableExists($table)
5616
5617 =cut
5618
5619 sub TableExists {
5620     my $table = shift;
5621     eval {
5622                 local $dbh->{PrintError} = 0;
5623                 local $dbh->{RaiseError} = 1;
5624                 $dbh->do(qq{SELECT * FROM $table WHERE 1 = 0 });
5625             };
5626     return 1 unless $@;
5627     return 0;
5628 }
5629
5630 =head2 DropAllForeignKeys($table)
5631
5632 Drop all foreign keys of the table $table
5633
5634 =cut
5635
5636
5637 sub DropAllForeignKeys {
5638     my ($table) = @_;
5639     # get the table description
5640     my $sth = $dbh->prepare("SHOW CREATE TABLE $table");
5641     $sth->execute;
5642     my $vsc_structure = $sth->fetchrow;
5643     # split on CONSTRAINT keyword
5644     my @fks = split /CONSTRAINT /,$vsc_structure;
5645     # parse each entry
5646     foreach (@fks) {
5647         # isolate what is before FOREIGN KEY, if there is something, it's a foreign key to drop
5648         $_ = /(.*) FOREIGN KEY.*/;
5649         my $id = $1;
5650         if ($id) {
5651             # we have found 1 foreign, drop it
5652             $dbh->do("ALTER TABLE $table DROP FOREIGN KEY $id");
5653             $id="";
5654         }
5655     }
5656 }
5657
5658
5659 =head2 TransformToNum
5660
5661 Transform the Koha version from a 4 parts string
5662 to a number, with just 1 .
5663
5664 =cut
5665
5666 sub TransformToNum {
5667     my $version = shift;
5668     # remove the 3 last . to have a Perl number
5669     $version =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
5670     # three X's at the end indicate that you are testing patch with dbrev
5671     # change it into 999
5672     # prevents error on a < comparison between strings (should be: lt)
5673     $version =~ s/XXX$/999/;
5674     return $version;
5675 }
5676
5677 =head2 SetVersion
5678
5679 set the DBversion in the systempreferences
5680
5681 =cut
5682
5683 sub SetVersion {
5684     return if $_[0]=~ /XXX$/;
5685       #you are testing a patch with a db revision; do not change version
5686     my $kohaversion = TransformToNum($_[0]);
5687     if (C4::Context->preference('Version')) {
5688       my $finish=$dbh->prepare("UPDATE systempreferences SET value=? WHERE variable='Version'");
5689       $finish->execute($kohaversion);
5690     } else {
5691       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')");
5692       $finish->execute($kohaversion);
5693     }
5694     C4::Context::clear_syspref_cache(); # invalidate cached preferences
5695 }
5696 exit;
5697