Bug 5669: Adding a system preference to control whether a user can select a pick...
[koha.git] / installer / data / mysql / updatedatabase.pl
1 #!/usr/bin/perl
2
3
4 # Database Updater
5 # This script checks for required updates to the database.
6
7 # Parts copyright Catalyst IT 2011
8
9 # Part of the Koha Library Software www.koha-community.org
10 # Koha is free software; you can redistribute it and/or modify it under the
11 # terms of the GNU General Public License as published by the Free Software
12 # Foundation; either version 2 of the License, or (at your option) any later
13 # version.
14 #
15 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
16 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License along with
20 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
21 # Suite 330, Boston, MA  02111-1307 USA
22 #
23
24 # Bugs/ToDo:
25 # - Would also be a good idea to offer to do a backup at this time...
26
27 # NOTE:  If you do something more than once in here, make it table driven.
28
29 # NOTE: Please keep the version in kohaversion.pl up-to-date!
30
31 use strict;
32 use warnings;
33
34 # CPAN modules
35 use DBI;
36 use Getopt::Long;
37 # Koha modules
38 use C4::Context;
39 use C4::Installer;
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 # Deal with virtualshelves
69
70 my $DBversion = "3.00.00.001";
71 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
72     # update virtualshelves table to
73     #
74     $dbh->do("ALTER TABLE `bookshelf` RENAME `virtualshelves`");
75     $dbh->do("ALTER TABLE `shelfcontents` RENAME `virtualshelfcontents`");
76     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD `biblionumber` INT( 11 ) NOT NULL default '0' AFTER shelfnumber");
77     $dbh->do("UPDATE `virtualshelfcontents` SET biblionumber=(SELECT biblionumber FROM items WHERE items.itemnumber=virtualshelfcontents.itemnumber)");
78     # drop all foreign keys : otherwise, we can't drop itemnumber field.
79     DropAllForeignKeys('virtualshelfcontents');
80     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD KEY biblionumber (biblionumber)");
81     # create the new foreign keys (on biblionumber)
82     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD CONSTRAINT `virtualshelfcontents_ibfk_1` FOREIGN KEY (`shelfnumber`) REFERENCES `virtualshelves` (`shelfnumber`) ON DELETE CASCADE ON UPDATE CASCADE");
83     # re-create the foreign key on virtualshelf
84     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD CONSTRAINT `shelfcontents_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE");
85     $dbh->do("ALTER TABLE `virtualshelfcontents` DROP `itemnumber`");
86     print "Upgrade to $DBversion done (virtualshelves)\n";
87     SetVersion ($DBversion);
88 }
89
90
91 $DBversion = "3.00.00.002";
92 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
93     $dbh->do("DROP TABLE sessions");
94     $dbh->do("CREATE TABLE `sessions` (
95   `id` varchar(32) NOT NULL,
96   `a_session` text NOT NULL,
97   UNIQUE KEY `id` (`id`)
98 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
99     print "Upgrade to $DBversion done (sessions uses CGI::session, new table structure for sessions)\n";
100     SetVersion ($DBversion);
101 }
102
103
104 $DBversion = "3.00.00.003";
105 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
106     if (C4::Context->preference("opaclanguages") eq "fr") {
107         $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')");
108     } else {
109         $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')");
110     }
111     print "Upgrade to $DBversion done (adding ReservesNeedReturns systempref, in circulation)\n";
112     SetVersion ($DBversion);
113 }
114
115
116 $DBversion = "3.00.00.004";
117 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
118     $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')");
119     print "Upgrade to $DBversion done (adding DebugLevel systempref, in 'Admin' tab)\n";
120     SetVersion ($DBversion);
121 }
122
123 $DBversion = "3.00.00.005";
124 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
125     $dbh->do("CREATE TABLE `tags` (
126                     `entry` varchar(255) NOT NULL default '',
127                     `weight` bigint(20) NOT NULL default 0,
128                     PRIMARY KEY  (`entry`)
129                     ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
130                 ");
131         $dbh->do("CREATE TABLE `nozebra` (
132                 `server` varchar(20)     NOT NULL,
133                 `indexname` varchar(40)  NOT NULL,
134                 `value` varchar(250)     NOT NULL,
135                 `biblionumbers` longtext NOT NULL,
136                 KEY `indexname` (`server`,`indexname`),
137                 KEY `value` (`server`,`value`))
138                 ENGINE=InnoDB DEFAULT CHARSET=utf8;
139                 ");
140     print "Upgrade to $DBversion done (adding tags and nozebra tables )\n";
141     SetVersion ($DBversion);
142 }
143
144 $DBversion = "3.00.00.006";
145 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
146     $dbh->do("UPDATE issues SET issuedate=timestamp WHERE issuedate='0000-00-00'");
147     print "Upgrade to $DBversion done (filled issues.issuedate with timestamp)\n";
148     SetVersion ($DBversion);
149 }
150
151 $DBversion = "3.00.00.007";
152 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
153     $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')");
154     print "Upgrade to $DBversion done (set SessionStorage variable)\n";
155     SetVersion ($DBversion);
156 }
157
158 $DBversion = "3.00.00.008";
159 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
160     $dbh->do("ALTER TABLE `biblio` ADD `datecreated` DATE NOT NULL AFTER `timestamp` ;");
161     $dbh->do("UPDATE biblio SET datecreated=timestamp");
162     print "Upgrade to $DBversion done (biblio creation date)\n";
163     SetVersion ($DBversion);
164 }
165
166 $DBversion = "3.00.00.009";
167 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
168
169     # Create backups of call number columns
170     # in case default migration needs to be customized
171     #
172     # UPGRADE NOTE: temp_upg_biblioitems_call_num should be dropped
173     #               after call numbers have been transformed to the new structure
174     #
175     # Not bothering to do the same with deletedbiblioitems -- assume
176     # default is good enough.
177     $dbh->do("CREATE TABLE `temp_upg_biblioitems_call_num` AS
178               SELECT `biblioitemnumber`, `biblionumber`,
179                      `classification`, `dewey`, `subclass`,
180                      `lcsort`, `ccode`
181               FROM `biblioitems`");
182
183     # biblioitems changes
184     $dbh->do("ALTER TABLE `biblioitems` CHANGE COLUMN `volumeddesc` `volumedesc` TEXT,
185                                     ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
186                                     ADD `cn_class` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
187                                     ADD `cn_item` VARCHAR(10) DEFAULT NULL AFTER `cn_class`,
188                                     ADD `cn_suffix` VARCHAR(10) DEFAULT NULL AFTER `cn_item`,
189                                     ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_suffix`,
190                                     ADD `totalissues` INT(10) AFTER `cn_sort`");
191
192     # default mapping of call number columns:
193     #   cn_class = concatentation of classification + dewey,
194     #              trimmed to fit -- assumes that most users do not
195     #              populate both classification and dewey in a single record
196     #   cn_item  = subclass
197     #   cn_source = left null
198     #   cn_sort = lcsort
199     #
200     # After upgrade, cn_sort will have to be set based on whatever
201     # default call number scheme user sets as a preference.  Misc
202     # script will be added at some point to do that.
203     #
204     $dbh->do("UPDATE `biblioitems`
205               SET cn_class = SUBSTR(TRIM(CONCAT_WS(' ', `classification`, `dewey`)), 1, 30),
206                     cn_item = subclass,
207                     `cn_sort` = `lcsort`
208             ");
209
210     # Now drop the old call number columns
211     $dbh->do("ALTER TABLE `biblioitems` DROP COLUMN `classification`,
212                                         DROP COLUMN `dewey`,
213                                         DROP COLUMN `subclass`,
214                                         DROP COLUMN `lcsort`,
215                                         DROP COLUMN `ccode`");
216
217     # deletedbiblio changes
218     $dbh->do("ALTER TABLE `deletedbiblio` ALTER COLUMN `frameworkcode` SET DEFAULT '',
219                                         DROP COLUMN `marc`,
220                                         ADD `datecreated` DATE NOT NULL AFTER `timestamp`");
221     $dbh->do("UPDATE deletedbiblio SET datecreated = timestamp");
222
223     # deletedbiblioitems changes
224     $dbh->do("ALTER TABLE `deletedbiblioitems`
225                         MODIFY `publicationyear` TEXT,
226                         CHANGE `volumeddesc` `volumedesc` TEXT,
227                         MODIFY `collectiontitle` MEDIUMTEXT DEFAULT NULL AFTER `volumedesc`,
228                         MODIFY `collectionissn` TEXT DEFAULT NULL AFTER `collectiontitle`,
229                         MODIFY `collectionvolume` MEDIUMTEXT DEFAULT NULL AFTER `collectionissn`,
230                         MODIFY `editionstatement` TEXT DEFAULT NULL AFTER `collectionvolume`,
231                         MODIFY `editionresponsibility` TEXT DEFAULT NULL AFTER `editionstatement`,
232                         MODIFY `place` VARCHAR(255) DEFAULT NULL AFTER `size`,
233                         MODIFY `marc` LONGBLOB,
234                         ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `url`,
235                         ADD `cn_class` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
236                         ADD `cn_item` VARCHAR(10) DEFAULT NULL AFTER `cn_class`,
237                         ADD `cn_suffix` VARCHAR(10) DEFAULT NULL AFTER `cn_item`,
238                         ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_suffix`,
239                         ADD `totalissues` INT(10) AFTER `cn_sort`,
240                         ADD `marcxml` LONGTEXT NOT NULL AFTER `totalissues`,
241                         ADD KEY `isbn` (`isbn`),
242                         ADD KEY `publishercode` (`publishercode`)
243                     ");
244
245     $dbh->do("UPDATE `deletedbiblioitems`
246                 SET `cn_class` = SUBSTR(TRIM(CONCAT_WS(' ', `classification`, `dewey`)), 1, 30),
247                `cn_item` = `subclass`,
248                 `cn_sort` = `lcsort`
249             ");
250     $dbh->do("ALTER TABLE `deletedbiblioitems`
251                         DROP COLUMN `classification`,
252                         DROP COLUMN `dewey`,
253                         DROP COLUMN `subclass`,
254                         DROP COLUMN `lcsort`,
255                         DROP COLUMN `ccode`
256             ");
257
258     # deleteditems changes
259     $dbh->do("ALTER TABLE `deleteditems`
260                         MODIFY `barcode` VARCHAR(20) DEFAULT NULL,
261                         MODIFY `price` DECIMAL(8,2) DEFAULT NULL,
262                         MODIFY `replacementprice` DECIMAL(8,2) DEFAULT NULL,
263                         DROP `bulk`,
264                         MODIFY `itemcallnumber` VARCHAR(30) DEFAULT NULL AFTER `wthdrawn`,
265                         MODIFY `holdingbranch` VARCHAR(10) DEFAULT NULL,
266                         DROP `interim`,
267                         MODIFY `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP AFTER `paidfor`,
268                         DROP `cutterextra`,
269                         ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `onloan`,
270                         ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
271                         ADD `ccode` VARCHAR(10) DEFAULT NULL AFTER `cn_sort`,
272                         ADD `materials` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
273                         ADD `uri` VARCHAR(255) DEFAULT NULL AFTER `materials`,
274                         MODIFY `marc` LONGBLOB AFTER `uri`,
275                         DROP KEY `barcode`,
276                         DROP KEY `itembarcodeidx`,
277                         DROP KEY `itembinoidx`,
278                         DROP KEY `itembibnoidx`,
279                         ADD UNIQUE KEY `delitembarcodeidx` (`barcode`),
280                         ADD KEY `delitembinoidx` (`biblioitemnumber`),
281                         ADD KEY `delitembibnoidx` (`biblionumber`),
282                         ADD KEY `delhomebranch` (`homebranch`),
283                         ADD KEY `delholdingbranch` (`holdingbranch`)");
284     $dbh->do("UPDATE deleteditems SET `ccode` = `itype`");
285     $dbh->do("ALTER TABLE deleteditems DROP `itype`");
286     $dbh->do("UPDATE `deleteditems` SET `cn_sort` = `itemcallnumber`");
287
288     # items changes
289     $dbh->do("ALTER TABLE `items` ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `onloan`,
290                                 ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
291                                 ADD `ccode` VARCHAR(10) DEFAULT NULL AFTER `cn_sort`,
292                                 ADD `materials` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
293                                 ADD `uri` VARCHAR(255) DEFAULT NULL AFTER `materials`
294             ");
295     $dbh->do("ALTER TABLE `items`
296                         DROP KEY `itembarcodeidx`,
297                         ADD UNIQUE KEY `itembarcodeidx` (`barcode`)");
298
299     # map items.itype to items.ccode and
300     # set cn_sort to itemcallnumber -- as with biblioitems.cn_sort,
301     # will have to be subsequently updated per user's default
302     # classification scheme
303     $dbh->do("UPDATE `items` SET `cn_sort` = `itemcallnumber`,
304                             `ccode` = `itype`");
305
306     $dbh->do("ALTER TABLE `items` DROP `cutterextra`,
307                                 DROP `itype`");
308
309     print "Upgrade to $DBversion done (major changes to biblio, biblioitems, items, and deleted* versions of same\n";
310     SetVersion ($DBversion);
311 }
312
313 $DBversion = "3.00.00.010";
314 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
315     $dbh->do("CREATE INDEX `userid` ON borrowers (`userid`) ");
316     print "Upgrade to $DBversion done (userid index added)\n";
317     SetVersion ($DBversion);
318 }
319
320 $DBversion = "3.00.00.011";
321 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
322     $dbh->do("ALTER TABLE `branchcategories` CHANGE `categorycode` `categorycode` varchar(10) ");
323     $dbh->do("ALTER TABLE `branchcategories` CHANGE `categoryname` `categoryname` varchar(32) ");
324     $dbh->do("ALTER TABLE `branchcategories` ADD COLUMN `categorytype` varchar(16) ");
325     $dbh->do("UPDATE `branchcategories` SET `categorytype` = 'properties'");
326     $dbh->do("ALTER TABLE `branchrelations` CHANGE `categorycode` `categorycode` varchar(10) ");
327     print "Upgrade to $DBversion done (added branchcategory type)\n";
328     SetVersion ($DBversion);
329 }
330
331 $DBversion = "3.00.00.012";
332 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
333     $dbh->do("CREATE TABLE `class_sort_rules` (
334                                `class_sort_rule` varchar(10) NOT NULL default '',
335                                `description` mediumtext,
336                                `sort_routine` varchar(30) NOT NULL default '',
337                                PRIMARY KEY (`class_sort_rule`),
338                                UNIQUE KEY `class_sort_rule_idx` (`class_sort_rule`)
339                              ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
340     $dbh->do("CREATE TABLE `class_sources` (
341                                `cn_source` varchar(10) NOT NULL default '',
342                                `description` mediumtext,
343                                `used` tinyint(4) NOT NULL default 0,
344                                `class_sort_rule` varchar(10) NOT NULL default '',
345                                PRIMARY KEY (`cn_source`),
346                                UNIQUE KEY `cn_source_idx` (`cn_source`),
347                                KEY `used_idx` (`used`),
348                                CONSTRAINT `class_source_ibfk_1` FOREIGN KEY (`class_sort_rule`)
349                                           REFERENCES `class_sort_rules` (`class_sort_rule`)
350                              ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
351     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type)
352               VALUES('DefaultClassificationSource','ddc',
353                      'Default classification scheme used by the collection. E.g., Dewey, LCC, etc.', NULL,'free')");
354     $dbh->do("INSERT INTO `class_sort_rules` (`class_sort_rule`, `description`, `sort_routine`) VALUES
355                                ('dewey', 'Default filing rules for DDC', 'Dewey'),
356                                ('lcc', 'Default filing rules for LCC', 'LCC'),
357                                ('generic', 'Generic call number filing rules', 'Generic')");
358     $dbh->do("INSERT INTO `class_sources` (`cn_source`, `description`, `used`, `class_sort_rule`) VALUES
359                             ('ddc', 'Dewey Decimal Classification', 1, 'dewey'),
360                             ('lcc', 'Library of Congress Classification', 1, 'lcc'),
361                             ('udc', 'Universal Decimal Classification', 0, 'generic'),
362                             ('sudocs', 'SuDoc Classification (U.S. GPO)', 0, 'generic'),
363                             ('z', 'Other/Generic Classification Scheme', 0, 'generic')");
364     print "Upgrade to $DBversion done (classification sources added)\n";
365     SetVersion ($DBversion);
366 }
367
368 $DBversion = "3.00.00.013";
369 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
370     $dbh->do("CREATE TABLE `import_batches` (
371               `import_batch_id` int(11) NOT NULL auto_increment,
372               `template_id` int(11) default NULL,
373               `branchcode` varchar(10) default NULL,
374               `num_biblios` int(11) NOT NULL default 0,
375               `num_items` int(11) NOT NULL default 0,
376               `upload_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
377               `overlay_action` enum('replace', 'create_new', 'use_template') NOT NULL default 'create_new',
378               `import_status` enum('staging', 'staged', 'importing', 'imported', 'reverting', 'reverted', 'cleaned') NOT NULL default 'staging',
379               `batch_type` enum('batch', 'z3950') NOT NULL default 'batch',
380               `file_name` varchar(100),
381               `comments` mediumtext,
382               PRIMARY KEY (`import_batch_id`),
383               KEY `branchcode` (`branchcode`)
384               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
385     $dbh->do("CREATE TABLE `import_records` (
386               `import_record_id` int(11) NOT NULL auto_increment,
387               `import_batch_id` int(11) NOT NULL,
388               `branchcode` varchar(10) default NULL,
389               `record_sequence` int(11) NOT NULL default 0,
390               `upload_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
391               `import_date` DATE default NULL,
392               `marc` longblob NOT NULL,
393               `marcxml` longtext NOT NULL,
394               `marcxml_old` longtext NOT NULL,
395               `record_type` enum('biblio', 'auth', 'holdings') NOT NULL default 'biblio',
396               `overlay_status` enum('no_match', 'auto_match', 'manual_match', 'match_applied') NOT NULL default 'no_match',
397               `status` enum('error', 'staged', 'imported', 'reverted', 'items_reverted') NOT NULL default 'staged',
398               `import_error` mediumtext,
399               `encoding` varchar(40) NOT NULL default '',
400               `z3950random` varchar(40) default NULL,
401               PRIMARY KEY (`import_record_id`),
402               CONSTRAINT `import_records_ifbk_1` FOREIGN KEY (`import_batch_id`)
403                           REFERENCES `import_batches` (`import_batch_id`) ON DELETE CASCADE ON UPDATE CASCADE,
404               KEY `branchcode` (`branchcode`),
405               KEY `batch_sequence` (`import_batch_id`, `record_sequence`)
406               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
407     $dbh->do("CREATE TABLE `import_record_matches` (
408               `import_record_id` int(11) NOT NULL,
409               `candidate_match_id` int(11) NOT NULL,
410               `score` int(11) NOT NULL default 0,
411               CONSTRAINT `import_record_matches_ibfk_1` FOREIGN KEY (`import_record_id`)
412                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
413               KEY `record_score` (`import_record_id`, `score`)
414               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
415     $dbh->do("CREATE TABLE `import_biblios` (
416               `import_record_id` int(11) NOT NULL,
417               `matched_biblionumber` int(11) default NULL,
418               `control_number` varchar(25) default NULL,
419               `original_source` varchar(25) default NULL,
420               `title` varchar(128) default NULL,
421               `author` varchar(80) default NULL,
422               `isbn` varchar(14) default NULL,
423               `issn` varchar(9) default NULL,
424               `has_items` tinyint(1) NOT NULL default 0,
425               CONSTRAINT `import_biblios_ibfk_1` FOREIGN KEY (`import_record_id`)
426                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
427               KEY `matched_biblionumber` (`matched_biblionumber`),
428               KEY `title` (`title`),
429               KEY `isbn` (`isbn`)
430               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
431     $dbh->do("CREATE TABLE `import_items` (
432               `import_items_id` int(11) NOT NULL auto_increment,
433               `import_record_id` int(11) NOT NULL,
434               `itemnumber` int(11) default NULL,
435               `branchcode` varchar(10) default NULL,
436               `status` enum('error', 'staged', 'imported', 'reverted') NOT NULL default 'staged',
437               `marcxml` longtext NOT NULL,
438               `import_error` mediumtext,
439               PRIMARY KEY (`import_items_id`),
440               CONSTRAINT `import_items_ibfk_1` FOREIGN KEY (`import_record_id`)
441                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
442               KEY `itemnumber` (`itemnumber`),
443               KEY `branchcode` (`branchcode`)
444               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
445
446     $dbh->do("INSERT INTO `import_batches`
447                 (`overlay_action`, `import_status`, `batch_type`, `file_name`)
448               SELECT distinct 'create_new', 'staged', 'z3950', `file`
449               FROM   `marc_breeding`");
450
451     $dbh->do("INSERT INTO `import_records`
452                 (`import_batch_id`, `import_record_id`, `record_sequence`, `marc`, `record_type`, `status`,
453                 `encoding`, `z3950random`, `marcxml`, `marcxml_old`)
454               SELECT `import_batch_id`, `id`, 1, `marc`, 'biblio', 'staged', `encoding`, `z3950random`, '', ''
455               FROM `marc_breeding`
456               JOIN `import_batches` ON (`file_name` = `file`)");
457
458     $dbh->do("INSERT INTO `import_biblios`
459                 (`import_record_id`, `title`, `author`, `isbn`)
460               SELECT `import_record_id`, `title`, `author`, `isbn`
461               FROM   `marc_breeding`
462               JOIN   `import_records` ON (`import_record_id` = `id`)");
463
464     $dbh->do("UPDATE `import_batches`
465               SET `num_biblios` = (
466               SELECT COUNT(*)
467               FROM `import_records`
468               WHERE `import_batch_id` = `import_batches`.`import_batch_id`
469               )");
470
471     $dbh->do("DROP TABLE `marc_breeding`");
472
473     print "Upgrade to $DBversion done (import_batches et al. added)\n";
474     SetVersion ($DBversion);
475 }
476
477 $DBversion = "3.00.00.014";
478 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
479     $dbh->do("ALTER TABLE subscription ADD lastbranch VARCHAR(4)");
480     print "Upgrade to $DBversion done (userid index added)\n";
481     SetVersion ($DBversion);
482 }
483
484 $DBversion = "3.00.00.015";
485 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
486     $dbh->do("CREATE TABLE `saved_sql` (
487            `id` int(11) NOT NULL auto_increment,
488            `borrowernumber` int(11) default NULL,
489            `date_created` datetime default NULL,
490            `last_modified` datetime default NULL,
491            `savedsql` text,
492            `last_run` datetime default NULL,
493            `report_name` varchar(255) default NULL,
494            `type` varchar(255) default NULL,
495            `notes` text,
496            PRIMARY KEY  (`id`),
497            KEY boridx (`borrowernumber`)
498         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
499     $dbh->do("CREATE TABLE `saved_reports` (
500            `id` int(11) NOT NULL auto_increment,
501            `report_id` int(11) default NULL,
502            `report` longtext,
503            `date_run` datetime default NULL,
504            PRIMARY KEY  (`id`)
505         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
506     print "Upgrade to $DBversion done (saved_sql and saved_reports added)\n";
507     SetVersion ($DBversion);
508 }
509
510 $DBversion = "3.00.00.016";
511 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
512     $dbh->do(" CREATE TABLE reports_dictionary (
513           id int(11) NOT NULL auto_increment,
514           name varchar(255) default NULL,
515           description text,
516           date_created datetime default NULL,
517           date_modified datetime default NULL,
518           saved_sql text,
519           area int(11) default NULL,
520           PRIMARY KEY  (id)
521         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
522     print "Upgrade to $DBversion done (reports_dictionary) added)\n";
523     SetVersion ($DBversion);
524 }
525
526 $DBversion = "3.00.00.017";
527 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
528     $dbh->do("ALTER TABLE action_logs DROP PRIMARY KEY");
529     $dbh->do("ALTER TABLE action_logs ADD KEY  timestamp (timestamp,user)");
530     $dbh->do("ALTER TABLE action_logs ADD action_id INT(11) NOT NULL FIRST");
531     $dbh->do("UPDATE action_logs SET action_id = if (\@a, \@a:=\@a+1, \@a:=1)");
532     $dbh->do("ALTER TABLE action_logs MODIFY action_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY");
533     print "Upgrade to $DBversion done (added column to action_logs)\n";
534     SetVersion ($DBversion);
535 }
536
537 $DBversion = "3.00.00.018";
538 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
539     $dbh->do("ALTER TABLE `zebraqueue`
540                     ADD `done` INT NOT NULL DEFAULT '0',
541                     ADD `time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ;
542             ");
543     print "Upgrade to $DBversion done (adding timestamp and done columns to zebraque table to improve problem tracking) added)\n";
544     SetVersion ($DBversion);
545 }
546
547 $DBversion = "3.00.00.019";
548 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
549     $dbh->do("ALTER TABLE biblio MODIFY biblionumber INT(11) NOT NULL AUTO_INCREMENT");
550     $dbh->do("ALTER TABLE biblioitems MODIFY biblioitemnumber INT(11) NOT NULL AUTO_INCREMENT");
551     $dbh->do("ALTER TABLE items MODIFY itemnumber INT(11) NOT NULL AUTO_INCREMENT");
552     print "Upgrade to $DBversion done (made bib/item PKs auto_increment)\n";
553     SetVersion ($DBversion);
554 }
555
556 $DBversion = "3.00.00.020";
557 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
558     $dbh->do("ALTER TABLE deleteditems
559               DROP KEY `delitembarcodeidx`,
560               ADD KEY `delitembarcodeidx` (`barcode`)");
561     print "Upgrade to $DBversion done (dropped uniqueness of key on deleteditems.barcode)\n";
562     SetVersion ($DBversion);
563 }
564
565 $DBversion = "3.00.00.021";
566 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
567     $dbh->do("ALTER TABLE items CHANGE homebranch homebranch VARCHAR(10)");
568     $dbh->do("ALTER TABLE deleteditems CHANGE homebranch homebranch VARCHAR(10)");
569     $dbh->do("ALTER TABLE statistics CHANGE branch branch VARCHAR(10)");
570     $dbh->do("ALTER TABLE subscription CHANGE lastbranch lastbranch VARCHAR(10)");
571     print "Upgrade to $DBversion done (extended missed branchcode columns to 10 chars)\n";
572     SetVersion ($DBversion);
573 }
574
575 $DBversion = "3.00.00.022";
576 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
577     $dbh->do("ALTER TABLE items
578                 ADD `damaged` tinyint(1) default NULL AFTER notforloan");
579     $dbh->do("ALTER TABLE deleteditems
580                 ADD `damaged` tinyint(1) default NULL AFTER notforloan");
581     print "Upgrade to $DBversion done (adding damaged column to items table)\n";
582     SetVersion ($DBversion);
583 }
584
585 $DBversion = "3.00.00.023";
586 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
587      $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
588          VALUES ('yuipath','http://yui.yahooapis.com/2.3.1/build','Insert the path to YUI libraries','','free')");
589     print "Upgrade to $DBversion done (adding new system preference for controlling YUI path)\n";
590     SetVersion ($DBversion);
591 }
592 $DBversion = "3.00.00.024";
593 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
594     $dbh->do("ALTER TABLE biblioitems CHANGE  itemtype itemtype VARCHAR(10)");
595     print "Upgrade to $DBversion done (changing itemtype to (10))\n";
596     SetVersion ($DBversion);
597 }
598
599 $DBversion = "3.00.00.025";
600 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
601     $dbh->do("ALTER TABLE items ADD COLUMN itype VARCHAR(10)");
602     $dbh->do("ALTER TABLE deleteditems ADD COLUMN itype VARCHAR(10) AFTER uri");
603     if(C4::Context->preference('item-level_itypes')){
604         $dbh->do('update items,biblioitems set items.itype=biblioitems.itemtype where items.biblionumber=biblioitems.biblionumber and itype is null');
605     }
606     print "Upgrade to $DBversion done (reintroduce items.itype - fill from itemtype)\n ";
607     SetVersion ($DBversion);
608 }
609
610 $DBversion = "3.00.00.026";
611 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
612     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
613        VALUES ('HomeOrHoldingBranch','homebranch','homebranch|holdingbranch','With independent branches turned on this decides whether to check the items holdingbranch or homebranch at circulatilon','choice')");
614     print "Upgrade to $DBversion done (adding new system preference for choosing whether homebranch or holdingbranch is checked in circulation)\n";
615     SetVersion ($DBversion);
616 }
617
618 $DBversion = "3.00.00.027";
619 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
620     $dbh->do("CREATE TABLE `marc_matchers` (
621                 `matcher_id` int(11) NOT NULL auto_increment,
622                 `code` varchar(10) NOT NULL default '',
623                 `description` varchar(255) NOT NULL default '',
624                 `record_type` varchar(10) NOT NULL default 'biblio',
625                 `threshold` int(11) NOT NULL default 0,
626                 PRIMARY KEY (`matcher_id`),
627                 KEY `code` (`code`),
628                 KEY `record_type` (`record_type`)
629               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
630     $dbh->do("CREATE TABLE `matchpoints` (
631                 `matcher_id` int(11) NOT NULL,
632                 `matchpoint_id` int(11) NOT NULL auto_increment,
633                 `search_index` varchar(30) NOT NULL default '',
634                 `score` int(11) NOT NULL default 0,
635                 PRIMARY KEY (`matchpoint_id`),
636                 CONSTRAINT `matchpoints_ifbk_1` FOREIGN KEY (`matcher_id`)
637                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE
638               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
639     $dbh->do("CREATE TABLE `matchpoint_components` (
640                 `matchpoint_id` int(11) NOT NULL,
641                 `matchpoint_component_id` int(11) NOT NULL auto_increment,
642                 sequence int(11) NOT NULL default 0,
643                 tag varchar(3) NOT NULL default '',
644                 subfields varchar(40) NOT NULL default '',
645                 offset int(4) NOT NULL default 0,
646                 length int(4) NOT NULL default 0,
647                 PRIMARY KEY (`matchpoint_component_id`),
648                 KEY `by_sequence` (`matchpoint_id`, `sequence`),
649                 CONSTRAINT `matchpoint_components_ifbk_1` FOREIGN KEY (`matchpoint_id`)
650                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
651               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
652     $dbh->do("CREATE TABLE `matchpoint_component_norms` (
653                 `matchpoint_component_id` int(11) NOT NULL,
654                 `sequence`  int(11) NOT NULL default 0,
655                 `norm_routine` varchar(50) NOT NULL default '',
656                 KEY `matchpoint_component_norms` (`matchpoint_component_id`, `sequence`),
657                 CONSTRAINT `matchpoint_component_norms_ifbk_1` FOREIGN KEY (`matchpoint_component_id`)
658                            REFERENCES `matchpoint_components` (`matchpoint_component_id`) ON DELETE CASCADE ON UPDATE CASCADE
659               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
660     $dbh->do("CREATE TABLE `matcher_matchpoints` (
661                 `matcher_id` int(11) NOT NULL,
662                 `matchpoint_id` int(11) NOT NULL,
663                 CONSTRAINT `matcher_matchpoints_ifbk_1` FOREIGN KEY (`matcher_id`)
664                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE,
665                 CONSTRAINT `matcher_matchpoints_ifbk_2` FOREIGN KEY (`matchpoint_id`)
666                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
667               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
668     $dbh->do("CREATE TABLE `matchchecks` (
669                 `matcher_id` int(11) NOT NULL,
670                 `matchcheck_id` int(11) NOT NULL auto_increment,
671                 `source_matchpoint_id` int(11) NOT NULL,
672                 `target_matchpoint_id` int(11) NOT NULL,
673                 PRIMARY KEY (`matchcheck_id`),
674                 CONSTRAINT `matcher_matchchecks_ifbk_1` FOREIGN KEY (`matcher_id`)
675                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE,
676                 CONSTRAINT `matcher_matchchecks_ifbk_2` FOREIGN KEY (`source_matchpoint_id`)
677                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE,
678                 CONSTRAINT `matcher_matchchecks_ifbk_3` FOREIGN KEY (`target_matchpoint_id`)
679                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
680               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
681     print "Upgrade to $DBversion done (added C4::Matcher serialization tables)\n ";
682     SetVersion ($DBversion);
683 }
684
685 $DBversion = "3.00.00.028";
686 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
687     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
688        VALUES ('canreservefromotherbranches','1','','With Independent branches on, can a user from one library reserve an item from another library','YesNo')");
689     print "Upgrade to $DBversion done (adding new system preference for changing reserve/holds behaviour with independent branches)\n";
690     SetVersion ($DBversion);
691 }
692
693
694 $DBversion = "3.00.00.029";
695 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
696     $dbh->do("ALTER TABLE `import_batches` ADD `matcher_id` int(11) NULL AFTER `import_batch_id`");
697     print "Upgrade to $DBversion done (adding matcher_id to import_batches)\n";
698     SetVersion ($DBversion);
699 }
700
701 $DBversion = "3.00.00.030";
702 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
703     $dbh->do("
704 CREATE TABLE services_throttle (
705   service_type varchar(10) NOT NULL default '',
706   service_count varchar(45) default NULL,
707   PRIMARY KEY  (service_type)
708 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
709 ");
710     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
711        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')");
712  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
713        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')");
714  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
715        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')");
716  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
717        VALUES ('XISBNDailyLimit',499,'','The xISBN Web service is free for non-commercial use when usage does not exceed 500 requests per day','free')");
718  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
719        VALUES ('PINESISBN',0,'','Use with FRBRizeEditions. If ON, Koha will use PINES OISBN web service in the Editions tab on the detail pages.','YesNo')");
720  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
721        VALUES ('ThingISBN',0,'','Use with FRBRizeEditions. If ON, Koha will use the ThingISBN web service in the Editions tab on the detail pages.','YesNo')");
722     print "Upgrade to $DBversion done (adding services throttle table and sysprefs for xISBN)\n";
723     SetVersion ($DBversion);
724 }
725
726 $DBversion = "3.00.00.031";
727 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
728
729 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryStemming',1,'If ON, enables query stemming',NULL,'YesNo')");
730 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryFuzzy',1,'If ON, enables fuzzy option for searches',NULL,'YesNo')");
731 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryWeightFields',1,'If ON, enables field weighting',NULL,'YesNo')");
732 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('WebBasedSelfCheck',0,'If ON, enables the web-based self-check system',NULL,'YesNo')");
733 $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')");
734 $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')");
735 $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')");
736 $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')");
737 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('defaultSortOrder',NULL,'Specify the default sort order','asc|dsc|az|za','Choice')");
738 $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')");
739 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACdefaultSortOrder',NULL,'Specify the default sort order','asc|dsc|za|az','Choice')");
740 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('staffClientBaseURL','','Specify the base URL of the staff client',NULL,'free')");
741 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('minPasswordLength',3,'Specify the minimum length of a patron/staff password',NULL,'free')");
742 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('noItemTypeImages',0,'If ON, disables item-type images',NULL,'YesNo')");
743 $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')");
744 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('holdCancelLength','','Specify how many days before a hold is canceled',NULL,'free')");
745 $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')");
746 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('finesMode','test','Choose the fines mode, test or production','test|production','Choice')");
747 $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')");
748 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('itemBarcodeInputFilter','','If set, allows specification of a item barcode input filter','cuecat','Choice')");
749 $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')");
750 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('URLLinkText','','Text to display as the link anchor in the OPAC',NULL,'free')");
751 $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')");
752 $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')");
753 $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')");
754 $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')");
755 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACUserCSS',0,'Add CSS to be included in the OPAC',NULL,'free')");
756
757     print "Upgrade to $DBversion done (adding additional system preference)\n";
758     SetVersion ($DBversion);
759 }
760
761 $DBversion = "3.00.00.032";
762 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
763     $dbh->do("UPDATE `marc_subfield_structure` SET `kohafield` = 'items.wthdrawn' WHERE `kohafield` = 'items.withdrawn'");
764     print "Upgrade to $DBversion done (fixed MARC framework references to items.withdrawn)\n";
765     SetVersion ($DBversion);
766 }
767
768 $DBversion = "3.00.00.033";
769 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
770     $dbh->do("INSERT INTO `userflags` VALUES(17,'staffaccess','Modify login / permissions for staff users',0)");
771     print "Upgrade to $DBversion done (Adding permissions flag for staff member access modification.  )\n";
772     SetVersion ($DBversion);
773 }
774
775 $DBversion = "3.00.00.034";
776 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
777     $dbh->do("ALTER TABLE `virtualshelves` ADD COLUMN `sortfield` VARCHAR(16) ");
778     print "Upgrade to $DBversion done (Adding sortfield for Virtual Shelves.  )\n";
779     SetVersion ($DBversion);
780 }
781
782 $DBversion = "3.00.00.035";
783 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
784     $dbh->do("UPDATE marc_subfield_structure
785               SET authorised_value = 'cn_source'
786               WHERE kohafield IN ('items.cn_source', 'biblioitems.cn_source')
787               AND (authorised_value is NULL OR authorised_value = '')");
788     print "Upgrade to $DBversion done (MARC frameworks: make classification source a drop-down)\n";
789     SetVersion ($DBversion);
790 }
791
792 $DBversion = "3.00.00.036";
793 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
794     $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');");
795     print "Upgrade to $DBversion done (OPACItemsResultsDisplay systempreference added)\n";
796     SetVersion ($DBversion);
797 }
798
799 $DBversion = "3.00.00.037";
800 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
801     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactfirstname` varchar(255)");
802     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactsurname` varchar(255)");
803     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress1` varchar(255)");
804     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress2` varchar(255)");
805     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress3` varchar(255)");
806     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactzipcode` varchar(50)");
807     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactphone` varchar(50)");
808     print "Upgrade to $DBversion done (Adding Alternative Contact Person information to borrowers table)\n";
809     SetVersion ($DBversion);
810 }
811
812 $DBversion = "3.00.00.038";
813 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
814     $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'");
815     $dbh->do("DELETE FROM `systempreferences` WHERE variable='hideBiblioNumber'");
816     print "Upgrade to $DBversion done ('alter finesMode systempreference, remove superfluous syspref.')\n";
817     SetVersion ($DBversion);
818 }
819
820 $DBversion = "3.00.00.039";
821 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
822     $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')");
823     $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')");
824     $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')");
825     # $dbh->do("DELETE FROM `systempreferences` WHERE variable='HomeOrHoldingBranch'"); # Bug #2752
826     print "Upgrade to $DBversion done ('add circ sysprefs CircControl, finesCalendar, and uppercasesurnames, and delete HomeOrHoldingBranch.')\n";
827     SetVersion ($DBversion);
828 }
829
830 $DBversion = "3.00.00.040";
831 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
832         $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')");
833         $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')");
834         print "Upgrade to $DBversion done ('add circ sysprefs todaysIssuesDefaultSortOrder and previousIssuesDefaultSortOrder.')\n";
835     SetVersion ($DBversion);
836 }
837
838
839 $DBversion = "3.00.00.041";
840 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
841     # Strictly speaking it is not necessary to explicitly change
842     # NULL values to 0, because the ALTER TABLE statement will do that.
843     # However, setting them first avoids a warning.
844     $dbh->do("UPDATE items SET notforloan = 0 WHERE notforloan IS NULL");
845     $dbh->do("UPDATE items SET damaged = 0 WHERE damaged IS NULL");
846     $dbh->do("UPDATE items SET itemlost = 0 WHERE itemlost IS NULL");
847     $dbh->do("UPDATE items SET wthdrawn = 0 WHERE wthdrawn IS NULL");
848     $dbh->do("ALTER TABLE items
849                 MODIFY notforloan tinyint(1) NOT NULL default 0,
850                 MODIFY damaged    tinyint(1) NOT NULL default 0,
851                 MODIFY itemlost   tinyint(1) NOT NULL default 0,
852                 MODIFY wthdrawn   tinyint(1) NOT NULL default 0");
853     $dbh->do("UPDATE deleteditems SET notforloan = 0 WHERE notforloan IS NULL");
854     $dbh->do("UPDATE deleteditems SET damaged = 0 WHERE damaged IS NULL");
855     $dbh->do("UPDATE deleteditems SET itemlost = 0 WHERE itemlost IS NULL");
856     $dbh->do("UPDATE deleteditems SET wthdrawn = 0 WHERE wthdrawn IS NULL");
857     $dbh->do("ALTER TABLE deleteditems
858                 MODIFY notforloan tinyint(1) NOT NULL default 0,
859                 MODIFY damaged    tinyint(1) NOT NULL default 0,
860                 MODIFY itemlost   tinyint(1) NOT NULL default 0,
861                 MODIFY wthdrawn   tinyint(1) NOT NULL default 0");
862         print "Upgrade to $DBversion done (disallow NULL in several item status columns)\n";
863     SetVersion ($DBversion);
864 }
865
866 $DBversion = "3.00.00.042";
867 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
868     $dbh->do("ALTER TABLE aqbooksellers CHANGE name name mediumtext NOT NULL");
869         print "Upgrade to $DBversion done (disallow NULL in aqbooksellers.name; part of fix for bug 1251)\n";
870     SetVersion ($DBversion);
871 }
872
873 $DBversion = "3.00.00.043";
874 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
875     $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");
876         print "Upgrade to $DBversion done (currency table: add symbol and timestamp columns)\n";
877     SetVersion ($DBversion);
878 }
879
880 $DBversion = "3.00.00.044";
881 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
882     $dbh->do("ALTER TABLE deletedborrowers
883   ADD `altcontactfirstname` varchar(255) default NULL,
884   ADD `altcontactsurname` varchar(255) default NULL,
885   ADD `altcontactaddress1` varchar(255) default NULL,
886   ADD `altcontactaddress2` varchar(255) default NULL,
887   ADD `altcontactaddress3` varchar(255) default NULL,
888   ADD `altcontactzipcode` varchar(50) default NULL,
889   ADD `altcontactphone` varchar(50) default NULL
890   ");
891   $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES
892 ('OPACBaseURL',NULL,'Specify the Base URL of the OPAC, e.g., opac.mylibrary.com, the http:// will be added automatically by Koha.',NULL,'Free'),
893 ('language','en','Set the default language in the staff client.',NULL,'Languages'),
894 ('QueryAutoTruncate',1,'If ON, query truncation is enabled by default',NULL,'YesNo'),
895 ('QueryRemoveStopwords',0,'If ON, stopwords listed in the Administration area will be removed from queries',NULL,'YesNo')
896   ");
897         print "Upgrade to $DBversion done (syncing deletedborrowers table with borrowers table)\n";
898     SetVersion ($DBversion);
899 }
900
901 #-- http://www.w3.org/International/articles/language-tags/
902
903 #-- RFC4646
904 $DBversion = "3.00.00.045";
905 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
906     $dbh->do("
907 CREATE TABLE language_subtag_registry (
908         subtag varchar(25),
909         type varchar(25), -- language-script-region-variant-extension-privateuse
910         description varchar(25), -- only one of the possible descriptions for ease of reference, see language_descriptions for the complete list
911         added date,
912         KEY `subtag` (`subtag`)
913 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
914
915 #-- TODO: add suppress_scripts
916 #-- this maps three letter codes defined in iso639.2 back to their
917 #-- two letter equivilents in rfc4646 (LOC maintains iso639+)
918  $dbh->do("CREATE TABLE language_rfc4646_to_iso639 (
919         rfc4646_subtag varchar(25),
920         iso639_2_code varchar(25),
921         KEY `rfc4646_subtag` (`rfc4646_subtag`)
922 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
923
924  $dbh->do("CREATE TABLE language_descriptions (
925         subtag varchar(25),
926         type varchar(25),
927         lang varchar(25),
928         description varchar(255),
929         KEY `lang` (`lang`)
930 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
931
932 #-- bi-directional support, keyed by script subcode
933  $dbh->do("CREATE TABLE language_script_bidi (
934         rfc4646_subtag varchar(25), -- script subtag, Arab, Hebr, etc.
935         bidi varchar(3), -- rtl ltr
936         KEY `rfc4646_subtag` (`rfc4646_subtag`)
937 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
938
939 #-- BIDI Stuff, Arabic and Hebrew
940  $dbh->do("INSERT INTO language_script_bidi(rfc4646_subtag,bidi)
941 VALUES( 'Arab', 'rtl')");
942  $dbh->do("INSERT INTO language_script_bidi(rfc4646_subtag,bidi)
943 VALUES( 'Hebr', 'rtl')");
944
945 #-- TODO: need to map language subtags to script subtags for detection
946 #-- of bidi when script is not specified (like ar, he)
947  $dbh->do("CREATE TABLE language_script_mapping (
948         language_subtag varchar(25),
949         script_subtag varchar(25),
950         KEY `language_subtag` (`language_subtag`)
951 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
952
953 #-- Default mappings between script and language subcodes
954  $dbh->do("INSERT INTO language_script_mapping(language_subtag,script_subtag)
955 VALUES( 'ar', 'Arab')");
956  $dbh->do("INSERT INTO language_script_mapping(language_subtag,script_subtag)
957 VALUES( 'he', 'Hebr')");
958
959         print "Upgrade to $DBversion done (adding language subtag registry and basic BiDi support NOTE: You should import the subtag registry SQL)\n";
960     SetVersion ($DBversion);
961 }
962
963 $DBversion = "3.00.00.046";
964 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
965     $dbh->do("ALTER TABLE `subscription` CHANGE `numberlength` `numberlength` int(11) default '0' ,
966                  CHANGE `weeklength` `weeklength` int(11) default '0'");
967     $dbh->do("CREATE TABLE `serialitems` (`serialid` int(11) NOT NULL, `itemnumber` int(11) NOT NULL, UNIQUE KEY `serialididx` (`serialid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
968     $dbh->do("INSERT INTO `serialitems` SELECT `serialid`,`itemnumber` from serial where NOT ISNULL(itemnumber) && itemnumber <> '' && itemnumber NOT LIKE '%,%'");
969         print "Upgrade to $DBversion done (Add serialitems table to link serial issues to items. )\n";
970     SetVersion ($DBversion);
971 }
972
973 $DBversion = "3.00.00.047";
974 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
975     $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');");
976         print "Upgrade to $DBversion done ( Added OpacRenewalAllowed syspref )\n";
977     SetVersion ($DBversion);
978 }
979
980 $DBversion = "3.00.00.048";
981 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
982     $dbh->do("ALTER TABLE `items` ADD `more_subfields_xml` longtext default NULL AFTER `itype`");
983         print "Upgrade to $DBversion done (added items.more_subfields_xml)\n";
984     SetVersion ($DBversion);
985 }
986
987 $DBversion = "3.00.00.049";
988 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
989         $dbh->do("ALTER TABLE `z3950servers` ADD `encoding` text default NULL AFTER type ");
990         print "Upgrade to $DBversion done ( Added encoding field to z3950servers table )\n";
991     SetVersion ($DBversion);
992 }
993
994 $DBversion = "3.00.00.050";
995 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
996     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacHighlightedWords','0','If Set, query matched terms are highlighted in OPAC',NULL,'YesNo');");
997         print "Upgrade to $DBversion done ( Added OpacHighlightedWords syspref )\n";
998     SetVersion ($DBversion);
999 }
1000
1001 $DBversion = "3.00.00.051";
1002 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1003     $dbh->do("UPDATE systempreferences SET explanation = 'Define the current theme for the OPAC interface.' WHERE variable = 'opacthemes';");
1004         print "Upgrade to $DBversion done ( Corrected opacthemes explanation. )\n";
1005     SetVersion ($DBversion);
1006 }
1007
1008 $DBversion = "3.00.00.052";
1009 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1010     $dbh->do("ALTER TABLE `deleteditems` ADD `more_subfields_xml` LONGTEXT DEFAULT NULL AFTER `itype`");
1011         print "Upgrade to $DBversion done ( Adding missing column to deleteditems table. )\n";
1012     SetVersion ($DBversion);
1013 }
1014
1015 $DBversion = "3.00.00.053";
1016 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1017     $dbh->do("CREATE TABLE `printers_profile` (
1018             `prof_id` int(4) NOT NULL auto_increment,
1019             `printername` varchar(40) NOT NULL,
1020             `tmpl_id` int(4) NOT NULL,
1021             `paper_bin` varchar(20) NOT NULL,
1022             `offset_horz` float default NULL,
1023             `offset_vert` float default NULL,
1024             `creep_horz` float default NULL,
1025             `creep_vert` float default NULL,
1026             `unit` char(20) NOT NULL default 'POINT',
1027             PRIMARY KEY  (`prof_id`),
1028             UNIQUE KEY `printername` (`printername`,`tmpl_id`,`paper_bin`),
1029             CONSTRAINT `printers_profile_pnfk_1` FOREIGN KEY (`tmpl_id`) REFERENCES `labels_templates` (`tmpl_id`) ON DELETE CASCADE ON UPDATE CASCADE
1030             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1031     $dbh->do("CREATE TABLE `labels_profile` (
1032             `tmpl_id` int(4) NOT NULL,
1033             `prof_id` int(4) NOT NULL,
1034             UNIQUE KEY `tmpl_id` (`tmpl_id`),
1035             UNIQUE KEY `prof_id` (`prof_id`)
1036             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1037     print "Upgrade to $DBversion done ( Printer Profile tables added )\n";
1038     SetVersion ($DBversion);
1039 }
1040
1041 $DBversion = "3.00.00.054";
1042 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1043     $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';");
1044         print "Upgrade to $DBversion done ( Added another barcode autogeneration sequence to barcode.pl. )\n";
1045     SetVersion ($DBversion);
1046 }
1047
1048 $DBversion = "3.00.00.055";
1049 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1050     $dbh->do("ALTER TABLE `zebraqueue` ADD KEY `zebraqueue_lookup` (`server`, `biblio_auth_number`, `operation`, `done`)");
1051         print "Upgrade to $DBversion done ( Added index on zebraqueue. )\n";
1052     SetVersion ($DBversion);
1053 }
1054 $DBversion = "3.00.00.056";
1055 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1056     if (C4::Context->preference("marcflavour") eq 'UNIMARC') {
1057         $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) ");
1058     } else {
1059         $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) ");
1060     }
1061     $dbh->do("ALTER TABLE `items` ADD `enumchron` VARCHAR(80) DEFAULT NULL;");
1062     print "Upgrade to $DBversion done ( Added item.enumchron column, and framework map to 952h )\n";
1063     SetVersion ($DBversion);
1064 }
1065
1066 $DBversion = "3.00.00.057";
1067 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1068     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH','0','if ON, OAI-PMH server is enabled',NULL,'YesNo');");
1069     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH:archiveID','KOHA-OAI-TEST','OAI-PMH archive identification',NULL,'Free');");
1070     $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');");
1071     $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');");
1072     $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');");
1073     SetVersion ($DBversion);
1074 }
1075
1076 $DBversion = "3.00.00.058";
1077 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1078     $dbh->do("ALTER TABLE `opac_news`
1079                 CHANGE `lang` `lang` VARCHAR( 25 )
1080                 CHARACTER SET utf8
1081                 COLLATE utf8_general_ci
1082                 NOT NULL default ''");
1083         print "Upgrade to $DBversion done ( lang field in opac_news made longer )\n";
1084     SetVersion ($DBversion);
1085 }
1086
1087 $DBversion = "3.00.00.059";
1088 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1089
1090     $dbh->do("CREATE TABLE IF NOT EXISTS `labels_templates` (
1091             `tmpl_id` int(4) NOT NULL auto_increment,
1092             `tmpl_code` char(100)  default '',
1093             `tmpl_desc` char(100) default '',
1094             `page_width` float default '0',
1095             `page_height` float default '0',
1096             `label_width` float default '0',
1097             `label_height` float default '0',
1098             `topmargin` float default '0',
1099             `leftmargin` float default '0',
1100             `cols` int(2) default '0',
1101             `rows` int(2) default '0',
1102             `colgap` float default '0',
1103             `rowgap` float default '0',
1104             `active` int(1) default NULL,
1105             `units` char(20)  default 'PX',
1106             `fontsize` int(4) NOT NULL default '3',
1107             PRIMARY KEY  (`tmpl_id`)
1108             ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1109     $dbh->do("CREATE TABLE  IF NOT EXISTS `printers_profile` (
1110             `prof_id` int(4) NOT NULL auto_increment,
1111             `printername` varchar(40) NOT NULL,
1112             `tmpl_id` int(4) NOT NULL,
1113             `paper_bin` varchar(20) NOT NULL,
1114             `offset_horz` float default NULL,
1115             `offset_vert` float default NULL,
1116             `creep_horz` float default NULL,
1117             `creep_vert` float default NULL,
1118             `unit` char(20) NOT NULL default 'POINT',
1119             PRIMARY KEY  (`prof_id`),
1120             UNIQUE KEY `printername` (`printername`,`tmpl_id`,`paper_bin`),
1121             CONSTRAINT `printers_profile_pnfk_1` FOREIGN KEY (`tmpl_id`) REFERENCES `labels_templates` (`tmpl_id`) ON DELETE CASCADE ON UPDATE CASCADE
1122             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1123     print "Upgrade to $DBversion done ( Added labels_templates table if it did not exist. )\n";
1124     SetVersion ($DBversion);
1125 }
1126
1127 $DBversion = "3.00.00.060";
1128 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1129     $dbh->do("CREATE TABLE IF NOT EXISTS `patronimage` (
1130             `cardnumber` varchar(16) NOT NULL,
1131             `mimetype` varchar(15) NOT NULL,
1132             `imagefile` mediumblob NOT NULL,
1133             PRIMARY KEY  (`cardnumber`),
1134             CONSTRAINT `patronimage_fk1` FOREIGN KEY (`cardnumber`) REFERENCES `borrowers` (`cardnumber`) ON DELETE CASCADE ON UPDATE CASCADE
1135             ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1136         print "Upgrade to $DBversion done ( Added patronimage table. )\n";
1137     SetVersion ($DBversion);
1138 }
1139
1140 $DBversion = "3.00.00.061";
1141 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1142     $dbh->do("ALTER TABLE labels_templates ADD COLUMN font char(10) NOT NULL DEFAULT 'TR';");
1143         print "Upgrade to $DBversion done ( Added font column to labels_templates )\n";
1144     SetVersion ($DBversion);
1145 }
1146
1147 $DBversion = "3.00.00.062";
1148 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1149     $dbh->do("CREATE TABLE `old_issues` (
1150                 `borrowernumber` int(11) default NULL,
1151                 `itemnumber` int(11) default NULL,
1152                 `date_due` date default NULL,
1153                 `branchcode` varchar(10) default NULL,
1154                 `issuingbranch` varchar(18) default NULL,
1155                 `returndate` date default NULL,
1156                 `lastreneweddate` date default NULL,
1157                 `return` varchar(4) default NULL,
1158                 `renewals` tinyint(4) default NULL,
1159                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1160                 `issuedate` date default NULL,
1161                 KEY `old_issuesborridx` (`borrowernumber`),
1162                 KEY `old_issuesitemidx` (`itemnumber`),
1163                 KEY `old_bordate` (`borrowernumber`,`timestamp`),
1164                 CONSTRAINT `old_issues_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1165                     ON DELETE SET NULL ON UPDATE SET NULL,
1166                 CONSTRAINT `old_issues_ibfk_2` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`)
1167                     ON DELETE SET NULL ON UPDATE SET NULL
1168                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1169     $dbh->do("CREATE TABLE `old_reserves` (
1170                 `borrowernumber` int(11) default NULL,
1171                 `reservedate` date default NULL,
1172                 `biblionumber` int(11) default NULL,
1173                 `constrainttype` varchar(1) default NULL,
1174                 `branchcode` varchar(10) default NULL,
1175                 `notificationdate` date default NULL,
1176                 `reminderdate` date default NULL,
1177                 `cancellationdate` date default NULL,
1178                 `reservenotes` mediumtext,
1179                 `priority` smallint(6) default NULL,
1180                 `found` varchar(1) default NULL,
1181                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1182                 `itemnumber` int(11) default NULL,
1183                 `waitingdate` date default NULL,
1184                 KEY `old_reserves_borrowernumber` (`borrowernumber`),
1185                 KEY `old_reserves_biblionumber` (`biblionumber`),
1186                 KEY `old_reserves_itemnumber` (`itemnumber`),
1187                 KEY `old_reserves_branchcode` (`branchcode`),
1188                 CONSTRAINT `old_reserves_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1189                     ON DELETE SET NULL ON UPDATE SET NULL,
1190                 CONSTRAINT `old_reserves_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`)
1191                     ON DELETE SET NULL ON UPDATE SET NULL,
1192                 CONSTRAINT `old_reserves_ibfk_3` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`)
1193                     ON DELETE SET NULL ON UPDATE SET NULL
1194                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1195
1196     # move closed transactions to old_* tables
1197     $dbh->do("INSERT INTO old_issues SELECT * FROM issues WHERE returndate IS NOT NULL");
1198     $dbh->do("DELETE FROM issues WHERE returndate IS NOT NULL");
1199     $dbh->do("INSERT INTO old_reserves SELECT * FROM reserves WHERE cancellationdate IS NOT NULL OR found = 'F'");
1200     $dbh->do("DELETE FROM reserves WHERE cancellationdate IS NOT NULL OR found = 'F'");
1201
1202         print "Upgrade to $DBversion done ( Added old_issues and old_reserves tables )\n";
1203     SetVersion ($DBversion);
1204 }
1205
1206 $DBversion = "3.00.00.063";
1207 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1208     $dbh->do("ALTER TABLE deleteditems
1209                 CHANGE COLUMN booksellerid booksellerid MEDIUMTEXT DEFAULT NULL,
1210                 ADD COLUMN enumchron VARCHAR(80) DEFAULT NULL AFTER more_subfields_xml,
1211                 ADD COLUMN copynumber SMALLINT(6) DEFAULT NULL AFTER enumchron;");
1212     $dbh->do("ALTER TABLE items
1213                 CHANGE COLUMN booksellerid booksellerid MEDIUMTEXT,
1214                 ADD COLUMN copynumber SMALLINT(6) DEFAULT NULL AFTER enumchron;");
1215         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";
1216     SetVersion ($DBversion);
1217 }
1218
1219 $DBversion = "3.00.00.064";
1220 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1221     $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');");
1222     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AWSAccessKeyID','','See:  http://aws.amazon.com','','free');");
1223     $dbh->do("DELETE FROM `systempreferences` WHERE variable='AmazonDevKey';");
1224     $dbh->do("DELETE FROM `systempreferences` WHERE variable='XISBNAmazonSimilarItems';");
1225     $dbh->do("DELETE FROM `systempreferences` WHERE variable='OPACXISBNAmazonSimilarItems';");
1226     print "Upgrade to $DBversion done (IMPORTANT: Upgrading to Amazon.com Associates Web Service 4.0 ) \n";
1227     SetVersion ($DBversion);
1228 }
1229
1230 $DBversion = "3.00.00.065";
1231 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1232     $dbh->do("CREATE TABLE `patroncards` (
1233                 `cardid` int(11) NOT NULL auto_increment,
1234                 `batch_id` varchar(10) NOT NULL default '1',
1235                 `borrowernumber` int(11) NOT NULL,
1236                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1237                 PRIMARY KEY  (`cardid`),
1238                 KEY `patroncards_ibfk_1` (`borrowernumber`),
1239                 CONSTRAINT `patroncards_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE
1240                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1241     print "Upgrade to $DBversion done (Adding patroncards table for patroncards generation feature. ) \n";
1242     SetVersion ($DBversion);
1243 }
1244
1245 $DBversion = "3.00.00.066";
1246 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1247     $dbh->do("ALTER TABLE `virtualshelfcontents` MODIFY `dateadded` timestamp NOT NULL
1248 DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP;
1249 ");
1250     print "Upgrade to $DBversion done (fix for bug 1873: virtualshelfcontents dateadded column empty. ) \n";
1251     SetVersion ($DBversion);
1252 }
1253
1254 $DBversion = "3.00.00.067";
1255 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1256     $dbh->do("UPDATE systempreferences SET explanation = 'Enable patron images for the Staff Client', type = 'YesNo' WHERE variable = 'patronimages'");
1257     print "Upgrade to $DBversion done (Updating patronimages syspref to reflect current kohastructure.sql. ) \n";
1258     SetVersion ($DBversion);
1259 }
1260
1261 $DBversion = "3.00.00.068";
1262 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1263     $dbh->do("CREATE TABLE `permissions` (
1264                 `module_bit` int(11) NOT NULL DEFAULT 0,
1265                 `code` varchar(30) DEFAULT NULL,
1266                 `description` varchar(255) DEFAULT NULL,
1267                 PRIMARY KEY  (`module_bit`, `code`),
1268                 CONSTRAINT `permissions_ibfk_1` FOREIGN KEY (`module_bit`) REFERENCES `userflags` (`bit`)
1269                     ON DELETE CASCADE ON UPDATE CASCADE
1270               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1271     $dbh->do("CREATE TABLE `user_permissions` (
1272                 `borrowernumber` int(11) NOT NULL DEFAULT 0,
1273                 `module_bit` int(11) NOT NULL DEFAULT 0,
1274                 `code` varchar(30) DEFAULT NULL,
1275                 CONSTRAINT `user_permissions_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1276                     ON DELETE CASCADE ON UPDATE CASCADE,
1277                 CONSTRAINT `user_permissions_ibfk_2` FOREIGN KEY (`module_bit`, `code`)
1278                     REFERENCES `permissions` (`module_bit`, `code`)
1279                     ON DELETE CASCADE ON UPDATE CASCADE
1280               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1281
1282     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
1283     (13, 'edit_news', 'Write news for the OPAC and staff interfaces'),
1284     (13, 'label_creator', 'Create printable labels and barcodes from catalog and patron data'),
1285     (13, 'edit_calendar', 'Define days when the library is closed'),
1286     (13, 'moderate_comments', 'Moderate patron comments'),
1287     (13, 'edit_notices', 'Define notices'),
1288     (13, 'edit_notice_status_triggers', 'Set notice/status triggers for overdue items'),
1289     (13, 'view_system_logs', 'Browse the system logs'),
1290     (13, 'inventory', 'Perform inventory (stocktaking) of your catalogue'),
1291     (13, 'stage_marc_import', 'Stage MARC records into the reservoir'),
1292     (13, 'manage_staged_marc', 'Managed staged MARC records, including completing and reversing imports'),
1293     (13, 'export_catalog', 'Export bibliographic and holdings data'),
1294     (13, 'import_patrons', 'Import patron data'),
1295     (13, 'delete_anonymize_patrons', 'Delete old borrowers and anonymize circulation history (deletes borrower reading history)'),
1296     (13, 'batch_upload_patron_images', 'Upload patron images in batch or one at a time'),
1297     (13, 'schedule_tasks', 'Schedule tasks to run')");
1298
1299     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('GranularPermissions','0','Use detailed staff user permissions',NULL,'YesNo')");
1300
1301     print "Upgrade to $DBversion done (adding permissions and user_permissions tables and GranularPermissions syspref) \n";
1302     SetVersion ($DBversion);
1303 }
1304 $DBversion = "3.00.00.069";
1305 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1306     $dbh->do("ALTER TABLE labels_conf CHANGE COLUMN class classification int(1) DEFAULT NULL;");
1307         print "Upgrade to $DBversion done ( Correcting columname in labels_conf )\n";
1308     SetVersion ($DBversion);
1309 }
1310
1311 $DBversion = "3.00.00.070";
1312 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1313     $sth = $dbh->prepare("SELECT value FROM systempreferences WHERE variable='yuipath'");
1314     $sth->execute;
1315     my ($value) = $sth->fetchrow;
1316     $value =~ s/2.3.1/2.5.1/;
1317     $dbh->do("UPDATE systempreferences SET value='$value' WHERE variable='yuipath';");
1318         print "Update yuipath syspref to 2.5.1 if necessary\n";
1319     SetVersion ($DBversion);
1320 }
1321
1322 $DBversion = "3.00.00.071";
1323 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1324     $dbh->do(" ALTER TABLE `subscription` ADD `serialsadditems` TINYINT( 1 ) NOT NULL DEFAULT '0';");
1325     # fill the new field with the previous systempreference value, then drop the syspref
1326     my $sth = $dbh->prepare("SELECT value FROM systempreferences WHERE variable='serialsadditems'");
1327     $sth->execute;
1328     my ($serialsadditems) = $sth->fetchrow();
1329     $dbh->do("UPDATE subscription SET serialsadditems=$serialsadditems");
1330     $dbh->do("DELETE FROM systempreferences WHERE variable='serialsadditems'");
1331     print "Upgrade to $DBversion done ( moving serialsadditems from syspref to subscription )\n";
1332     SetVersion ($DBversion);
1333 }
1334
1335 $DBversion = "3.00.00.072";
1336 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1337     $dbh->do("ALTER TABLE labels_conf ADD COLUMN formatstring mediumtext DEFAULT NULL AFTER printingtype");
1338         print "Upgrade to $DBversion done ( Adding format string to labels generator. )\n";
1339     SetVersion ($DBversion);
1340 }
1341
1342 $DBversion = "3.00.00.073";
1343 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1344         $dbh->do("DROP TABLE IF EXISTS `tags_all`;");
1345         $dbh->do(q#
1346         CREATE TABLE `tags_all` (
1347           `tag_id`         int(11) NOT NULL auto_increment,
1348           `borrowernumber` int(11) NOT NULL,
1349           `biblionumber`   int(11) NOT NULL,
1350           `term`      varchar(255) NOT NULL,
1351           `language`       int(4) default NULL,
1352           `date_created` datetime  NOT NULL,
1353           PRIMARY KEY  (`tag_id`),
1354           KEY `tags_borrowers_fk_1` (`borrowernumber`),
1355           KEY `tags_biblionumber_fk_1` (`biblionumber`),
1356           CONSTRAINT `tags_borrowers_fk_1` FOREIGN KEY (`borrowernumber`)
1357                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1358           CONSTRAINT `tags_biblionumber_fk_1` FOREIGN KEY (`biblionumber`)
1359                 REFERENCES `biblio`     (`biblionumber`)  ON DELETE CASCADE ON UPDATE CASCADE
1360         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1361         #);
1362         $dbh->do("DROP TABLE IF EXISTS `tags_approval`;");
1363         $dbh->do(q#
1364         CREATE TABLE `tags_approval` (
1365           `term`   varchar(255) NOT NULL,
1366           `approved`     int(1) NOT NULL default '0',
1367           `date_approved` datetime       default NULL,
1368           `approved_by` int(11)          default NULL,
1369           `weight_total` int(9) NOT NULL default '1',
1370           PRIMARY KEY  (`term`),
1371           KEY `tags_approval_borrowers_fk_1` (`approved_by`),
1372           CONSTRAINT `tags_approval_borrowers_fk_1` FOREIGN KEY (`approved_by`)
1373                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE
1374         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1375         #);
1376         $dbh->do("DROP TABLE IF EXISTS `tags_index`;");
1377         $dbh->do(q#
1378         CREATE TABLE `tags_index` (
1379           `term`    varchar(255) NOT NULL,
1380           `biblionumber` int(11) NOT NULL,
1381           `weight`        int(9) NOT NULL default '1',
1382           PRIMARY KEY  (`term`,`biblionumber`),
1383           KEY `tags_index_biblionumber_fk_1` (`biblionumber`),
1384           CONSTRAINT `tags_index_term_fk_1` FOREIGN KEY (`term`)
1385                 REFERENCES `tags_approval` (`term`)  ON DELETE CASCADE ON UPDATE CASCADE,
1386           CONSTRAINT `tags_index_biblionumber_fk_1` FOREIGN KEY (`biblionumber`)
1387                 REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
1388         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1389         #);
1390         $dbh->do(q#
1391         INSERT INTO `systempreferences` VALUES
1392                 ('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=',''),
1393                 ('BakerTaylorEnabled','0','','Enable or disable all Baker & Taylor features.','YesNo'),
1394                 ('BakerTaylorPassword','','','Baker & Taylor Password for Content Cafe (external content)','Textarea'),
1395                 ('BakerTaylorUsername','','','Baker & Taylor Username for Content Cafe (external content)','Textarea'),
1396                 ('TagsEnabled','1','','Enables or disables all tagging features.  This is the main switch for tags.','YesNo'),
1397                 ('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.',''),
1398                 ('TagsInputOnDetail','1','','Allow users to input tags from the detail page.',         'YesNo'),
1399                 ('TagsInputOnList',  '0','','Allow users to input tags from the search results list.', 'YesNo'),
1400                 ('TagsModeration',  NULL,'','Require tags from patrons to be approved before becoming visible.','YesNo'),
1401                 ('TagsShowOnDetail','10','','Number of tags to display on detail page.  0 is off.',        'Integer'),
1402                 ('TagsShowOnList',   '6','','Number of tags to display on search results list.  0 is off.','Integer')
1403         #);
1404         print "Upgrade to $DBversion done (Baker/Taylor,Tags: sysprefs and tables (tags_all, tags_index, tags_approval)) \n";
1405         SetVersion ($DBversion);
1406 }
1407
1408 $DBversion = "3.00.00.074";
1409 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1410     $dbh->do( q(update itemtypes set imageurl = concat( 'npl/', imageurl )
1411                   where imageurl not like 'http%'
1412                     and imageurl is not NULL
1413                     and imageurl != '') );
1414     print "Upgrade to $DBversion done (updating imagetype.imageurls to reflect new icon locations.)\n";
1415     SetVersion ($DBversion);
1416 }
1417
1418 $DBversion = "3.00.00.075";
1419 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1420     $dbh->do( q(alter table authorised_values add imageurl varchar(200) default NULL) );
1421     print "Upgrade to $DBversion done (adding imageurl field to authorised_values table)\n";
1422     SetVersion ($DBversion);
1423 }
1424
1425 $DBversion = "3.00.00.076";
1426 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1427     $dbh->do("ALTER TABLE import_batches
1428               ADD COLUMN nomatch_action enum('create_new', 'ignore') NOT NULL default 'create_new' AFTER overlay_action");
1429     $dbh->do("ALTER TABLE import_batches
1430               ADD COLUMN item_action enum('always_add', 'add_only_for_matches', 'add_only_for_new', 'ignore')
1431                   NOT NULL default 'always_add' AFTER nomatch_action");
1432     $dbh->do("ALTER TABLE import_batches
1433               MODIFY overlay_action  enum('replace', 'create_new', 'use_template', 'ignore')
1434                   NOT NULL default 'create_new'");
1435     $dbh->do("ALTER TABLE import_records
1436               MODIFY status  enum('error', 'staged', 'imported', 'reverted', 'items_reverted',
1437                                   'ignored') NOT NULL default 'staged'");
1438     $dbh->do("ALTER TABLE import_items
1439               MODIFY status enum('error', 'staged', 'imported', 'reverted', 'ignored') NOT NULL default 'staged'");
1440
1441         print "Upgrade to $DBversion done (changes to import_batches and import_records)\n";
1442         SetVersion ($DBversion);
1443 }
1444
1445 $DBversion = "3.00.00.077";
1446 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1447     # drop these tables only if they exist and none of them are empty
1448     # these tables are not defined in the packaged 2.2.9, but since it is believed
1449     # that at least one library may be using them in a post-2.2.9 but pre-3.0 Koha,
1450     # some care is taken.
1451     my ($print_error) = $dbh->{PrintError};
1452     $dbh->{PrintError} = 0;
1453     my ($raise_error) = $dbh->{RaiseError};
1454     $dbh->{RaiseError} = 1;
1455
1456     my $count = 0;
1457     my $do_drop = 1;
1458     eval { $count = $dbh->do("SELECT 1 FROM categorytable"); };
1459     if ($count > 0) {
1460         $do_drop = 0;
1461     }
1462     eval { $count = $dbh->do("SELECT 1 FROM mediatypetable"); };
1463     if ($count > 0) {
1464         $do_drop = 0;
1465     }
1466     eval { $count = $dbh->do("SELECT 1 FROM subcategorytable"); };
1467     if ($count > 0) {
1468         $do_drop = 0;
1469     }
1470
1471     if ($do_drop) {
1472         $dbh->do("DROP TABLE IF EXISTS `categorytable`");
1473         $dbh->do("DROP TABLE IF EXISTS `mediatypetable`");
1474         $dbh->do("DROP TABLE IF EXISTS `subcategorytable`");
1475     }
1476
1477     $dbh->{PrintError} = $print_error;
1478     $dbh->{RaiseError} = $raise_error;
1479         print "Upgrade to $DBversion done (drop categorytable, subcategorytable, and mediatypetable)\n";
1480         SetVersion ($DBversion);
1481 }
1482
1483 $DBversion = "3.00.00.078";
1484 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1485     my ($print_error) = $dbh->{PrintError};
1486     $dbh->{PrintError} = 0;
1487
1488     unless ($dbh->do("SELECT 1 FROM browser")) {
1489         $dbh->{PrintError} = $print_error;
1490         $dbh->do("CREATE TABLE `browser` (
1491                     `level` int(11) NOT NULL,
1492                     `classification` varchar(20) NOT NULL,
1493                     `description` varchar(255) NOT NULL,
1494                     `number` bigint(20) NOT NULL,
1495                     `endnode` tinyint(4) NOT NULL
1496                   ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1497     }
1498     $dbh->{PrintError} = $print_error;
1499         print "Upgrade to $DBversion done (add browser table if not already present)\n";
1500         SetVersion ($DBversion);
1501 }
1502
1503 $DBversion = "3.00.00.079";
1504 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1505  my ($print_error) = $dbh->{PrintError};
1506     $dbh->{PrintError} = 0;
1507
1508     $dbh->do("INSERT INTO `systempreferences` (variable, value,options,type, explanation)VALUES
1509         ('AddPatronLists','categorycode','categorycode|category_type','Choice','Allow user to choose what list to pick up from when adding patrons')");
1510     print "Upgrade to $DBversion done (add browser table if not already present)\n";
1511         SetVersion ($DBversion);
1512 }
1513
1514 $DBversion = "3.00.00.080";
1515 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1516     $dbh->do("ALTER TABLE subscription CHANGE monthlength monthlength int(11) default '0'");
1517     $dbh->do("ALTER TABLE deleteditems MODIFY marc LONGBLOB AFTER copynumber");
1518     $dbh->do("ALTER TABLE aqbooksellers CHANGE name name mediumtext NOT NULL");
1519         print "Upgrade to $DBversion done (catch up on DB schema changes since alpha and beta)\n";
1520         SetVersion ($DBversion);
1521 }
1522
1523 $DBversion = "3.00.00.081";
1524 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1525     $dbh->do("CREATE TABLE `borrower_attribute_types` (
1526                 `code` varchar(10) NOT NULL,
1527                 `description` varchar(255) NOT NULL,
1528                 `repeatable` tinyint(1) NOT NULL default 0,
1529                 `unique_id` tinyint(1) NOT NULL default 0,
1530                 `opac_display` tinyint(1) NOT NULL default 0,
1531                 `password_allowed` tinyint(1) NOT NULL default 0,
1532                 `staff_searchable` tinyint(1) NOT NULL default 0,
1533                 `authorised_value_category` varchar(10) default NULL,
1534                 PRIMARY KEY  (`code`)
1535               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1536     $dbh->do("CREATE TABLE `borrower_attributes` (
1537                 `borrowernumber` int(11) NOT NULL,
1538                 `code` varchar(10) NOT NULL,
1539                 `attribute` varchar(30) default NULL,
1540                 `password` varchar(30) default NULL,
1541                 KEY `borrowernumber` (`borrowernumber`),
1542                 KEY `code_attribute` (`code`, `attribute`),
1543                 CONSTRAINT `borrower_attributes_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1544                     ON DELETE CASCADE ON UPDATE CASCADE,
1545                 CONSTRAINT `borrower_attributes_ibfk_2` FOREIGN KEY (`code`) REFERENCES `borrower_attribute_types` (`code`)
1546                     ON DELETE CASCADE ON UPDATE CASCADE
1547             ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1548     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('ExtendedPatronAttributes','0','Use extended patron IDs and attributes',NULL,'YesNo')");
1549     print "Upgrade to $DBversion done (added borrower_attributes and  borrower_attribute_types)\n";
1550  SetVersion ($DBversion);
1551 }
1552
1553 $DBversion = "3.00.00.082";
1554 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1555     $dbh->do( q(alter table accountlines add column lastincrement decimal(28,6) default NULL) );
1556     print "Upgrade to $DBversion done (adding lastincrement column to accountlines table)\n";
1557     SetVersion ($DBversion);
1558 }
1559
1560 $DBversion = "3.00.00.083";
1561 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1562     $dbh->do( qq(UPDATE systempreferences SET value='local' where variable='yuipath' and value like "%/intranet-tmpl/prog/%"));
1563     print "Upgrade to $DBversion done (Changing yuipath behaviour in managing a local value)\n";
1564     SetVersion ($DBversion);
1565 }
1566 $DBversion = "3.00.00.084";
1567     if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1568     $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')");
1569     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('GoogleJackets','0','if ON, displays jacket covers from Google Books API',NULL,'YesNo')");
1570     print "Upgrade to $DBversion done (add new sysprefs)\n";
1571     SetVersion ($DBversion);
1572 }
1573
1574 $DBversion = "3.00.00.085";
1575 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1576     if (C4::Context->preference("marcflavour") eq 'MARC21') {
1577         $dbh->do("UPDATE marc_subfield_structure SET tab = 0 WHERE tab =  9 AND tagfield = '037'");
1578         $dbh->do("UPDATE marc_subfield_structure SET tab = 1 WHERE tab =  6 AND tagfield in ('100', '110', '111', '130')");
1579         $dbh->do("UPDATE marc_subfield_structure SET tab = 2 WHERE tab =  6 AND tagfield in ('240', '243')");
1580         $dbh->do("UPDATE marc_subfield_structure SET tab = 4 WHERE tab =  6 AND tagfield in ('400', '410', '411', '440')");
1581         $dbh->do("UPDATE marc_subfield_structure SET tab = 5 WHERE tab =  9 AND tagfield = '584'");
1582         $dbh->do("UPDATE marc_subfield_structure SET tab = 7 WHERE tab = -6 AND tagfield = '760'");
1583     }
1584     print "Upgrade to $DBversion done (move editing tab of various MARC21 subfields)\n";
1585     SetVersion ($DBversion);
1586 }
1587
1588 $DBversion = "3.00.00.086";
1589 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1590         $dbh->do(
1591         "CREATE TABLE `tmp_holdsqueue` (
1592         `biblionumber` int(11) default NULL,
1593         `itemnumber` int(11) default NULL,
1594         `barcode` varchar(20) default NULL,
1595         `surname` mediumtext NOT NULL,
1596         `firstname` text,
1597         `phone` text,
1598         `borrowernumber` int(11) NOT NULL,
1599         `cardnumber` varchar(16) default NULL,
1600         `reservedate` date default NULL,
1601         `title` mediumtext,
1602         `itemcallnumber` varchar(30) default NULL,
1603         `holdingbranch` varchar(10) default NULL,
1604         `pickbranch` varchar(10) default NULL,
1605         `notes` text
1606         ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1607
1608         $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')");
1609         $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')");
1610
1611         print "Upgrade to $DBversion done (Table structure for table `tmp_holdsqueue`)\n";
1612         SetVersion ($DBversion);
1613 }
1614
1615 $DBversion = "3.00.00.087";
1616 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1617     $dbh->do("INSERT INTO `systempreferences` VALUES ('AutoEmailOpacUser','0','','Sends notification emails containing new account details to patrons - when account is created.','YesNo')" );
1618     $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')");
1619     print "Upgrade to $DBversion done (added 2 new 'AutoEmailOpacUser' sysprefs)\n";
1620     SetVersion ($DBversion);
1621 }
1622
1623 $DBversion = "3.00.00.088";
1624 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1625         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('OPACShelfBrowser','1','','Enable/disable Shelf Browser on item details page','YesNo')");
1626         $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')");
1627         $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')");
1628         $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')");
1629         print "Upgrade to $DBversion done (added 2 new 'AutoEmailOpacUser' sysprefs)\n";
1630     SetVersion ($DBversion);
1631 }
1632
1633 $DBversion = "3.00.00.089";
1634 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1635         $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')");
1636         print "Upgrade to $DBversion done (added new AdvancedSearchTypes syspref)\n";
1637     SetVersion ($DBversion);
1638 }
1639
1640 $DBversion = "3.00.00.090";
1641 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1642     $dbh->do("
1643         CREATE TABLE `branch_borrower_circ_rules` (
1644           `branchcode` VARCHAR(10) NOT NULL,
1645           `categorycode` VARCHAR(10) NOT NULL,
1646           `maxissueqty` int(4) default NULL,
1647           PRIMARY KEY (`categorycode`, `branchcode`),
1648           CONSTRAINT `branch_borrower_circ_rules_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
1649             ON DELETE CASCADE ON UPDATE CASCADE,
1650           CONSTRAINT `branch_borrower_circ_rules_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`)
1651             ON DELETE CASCADE ON UPDATE CASCADE
1652         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1653     ");
1654     $dbh->do("
1655         CREATE TABLE `default_borrower_circ_rules` (
1656           `categorycode` VARCHAR(10) NOT NULL,
1657           `maxissueqty` int(4) default NULL,
1658           PRIMARY KEY (`categorycode`),
1659           CONSTRAINT `borrower_borrower_circ_rules_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
1660             ON DELETE CASCADE ON UPDATE CASCADE
1661         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1662     ");
1663     $dbh->do("
1664         CREATE TABLE `default_branch_circ_rules` (
1665           `branchcode` VARCHAR(10) NOT NULL,
1666           `maxissueqty` int(4) default NULL,
1667           PRIMARY KEY (`branchcode`),
1668           CONSTRAINT `default_branch_circ_rules_ibfk_1` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`)
1669             ON DELETE CASCADE ON UPDATE CASCADE
1670         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1671     ");
1672     $dbh->do("
1673         CREATE TABLE `default_circ_rules` (
1674             `singleton` enum('singleton') NOT NULL default 'singleton',
1675             `maxissueqty` int(4) default NULL,
1676             PRIMARY KEY (`singleton`)
1677         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1678     ");
1679     print "Upgrade to $DBversion done (added several circ rules tables)\n";
1680     SetVersion ($DBversion);
1681 }
1682
1683
1684 $DBversion = "3.00.00.091";
1685 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1686     $dbh->do(<<'END_SQL');
1687 ALTER TABLE borrowers
1688 ADD `smsalertnumber` varchar(50) default NULL
1689 END_SQL
1690
1691     $dbh->do(<<'END_SQL');
1692 CREATE TABLE `message_attributes` (
1693   `message_attribute_id` int(11) NOT NULL auto_increment,
1694   `message_name` varchar(20) NOT NULL default '',
1695   `takes_days` tinyint(1) NOT NULL default '0',
1696   PRIMARY KEY  (`message_attribute_id`),
1697   UNIQUE KEY `message_name` (`message_name`)
1698 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1699 END_SQL
1700
1701     $dbh->do(<<'END_SQL');
1702 CREATE TABLE `message_transport_types` (
1703   `message_transport_type` varchar(20) NOT NULL,
1704   PRIMARY KEY  (`message_transport_type`)
1705 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1706 END_SQL
1707
1708     $dbh->do(<<'END_SQL');
1709 CREATE TABLE `message_transports` (
1710   `message_attribute_id` int(11) NOT NULL,
1711   `message_transport_type` varchar(20) NOT NULL,
1712   `is_digest` tinyint(1) NOT NULL default '0',
1713   `letter_module` varchar(20) NOT NULL default '',
1714   `letter_code` varchar(20) NOT NULL default '',
1715   PRIMARY KEY  (`message_attribute_id`,`message_transport_type`,`is_digest`),
1716   KEY `message_transport_type` (`message_transport_type`),
1717   KEY `letter_module` (`letter_module`,`letter_code`),
1718   CONSTRAINT `message_transports_ibfk_1` FOREIGN KEY (`message_attribute_id`) REFERENCES `message_attributes` (`message_attribute_id`) ON DELETE CASCADE ON UPDATE CASCADE,
1719   CONSTRAINT `message_transports_ibfk_2` FOREIGN KEY (`message_transport_type`) REFERENCES `message_transport_types` (`message_transport_type`) ON DELETE CASCADE ON UPDATE CASCADE,
1720   CONSTRAINT `message_transports_ibfk_3` FOREIGN KEY (`letter_module`, `letter_code`) REFERENCES `letter` (`module`, `code`) ON DELETE CASCADE ON UPDATE CASCADE
1721 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1722 END_SQL
1723
1724     $dbh->do(<<'END_SQL');
1725 CREATE TABLE `borrower_message_preferences` (
1726   `borrower_message_preference_id` int(11) NOT NULL auto_increment,
1727   `borrowernumber` int(11) NOT NULL default '0',
1728   `message_attribute_id` int(11) default '0',
1729   `days_in_advance` int(11) default '0',
1730   `wants_digets` tinyint(1) NOT NULL default '0',
1731   PRIMARY KEY  (`borrower_message_preference_id`),
1732   KEY `borrowernumber` (`borrowernumber`),
1733   KEY `message_attribute_id` (`message_attribute_id`),
1734   CONSTRAINT `borrower_message_preferences_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1735   CONSTRAINT `borrower_message_preferences_ibfk_2` FOREIGN KEY (`message_attribute_id`) REFERENCES `message_attributes` (`message_attribute_id`) ON DELETE CASCADE ON UPDATE CASCADE
1736 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1737 END_SQL
1738
1739     $dbh->do(<<'END_SQL');
1740 CREATE TABLE `borrower_message_transport_preferences` (
1741   `borrower_message_preference_id` int(11) NOT NULL default '0',
1742   `message_transport_type` varchar(20) NOT NULL default '0',
1743   PRIMARY KEY  (`borrower_message_preference_id`,`message_transport_type`),
1744   KEY `message_transport_type` (`message_transport_type`),
1745   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,
1746   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
1747 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1748 END_SQL
1749
1750     $dbh->do(<<'END_SQL');
1751 CREATE TABLE `message_queue` (
1752   `message_id` int(11) NOT NULL auto_increment,
1753   `borrowernumber` int(11) NOT NULL,
1754   `subject` text,
1755   `content` text,
1756   `message_transport_type` varchar(20) NOT NULL,
1757   `status` enum('sent','pending','failed','deleted') NOT NULL default 'pending',
1758   `time_queued` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1759   KEY `message_id` (`message_id`),
1760   KEY `borrowernumber` (`borrowernumber`),
1761   KEY `message_transport_type` (`message_transport_type`),
1762   CONSTRAINT `messageq_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1763   CONSTRAINT `messageq_ibfk_2` FOREIGN KEY (`message_transport_type`) REFERENCES `message_transport_types` (`message_transport_type`) ON DELETE RESTRICT ON UPDATE CASCADE
1764 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1765 END_SQL
1766
1767     $dbh->do(<<'END_SQL');
1768 INSERT INTO `systempreferences`
1769   (variable,value,explanation,options,type)
1770 VALUES
1771 ('EnhancedMessagingPreferences',0,'If ON, allows patrons to select to receive additional messages about items due or nearly due.','','YesNo')
1772 END_SQL
1773
1774     $dbh->do( <<'END_SQL');
1775 INSERT INTO `letter`
1776 (module, code, name, title, content)
1777 VALUES
1778 ('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>>'),
1779 ('circulation','DUEDGST','Item Due Reminder (Digest)','Item Due Reminder','You have <<count>> items due'),
1780 ('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>>'),
1781 ('circulation','PREDUEDGST','Advance Notice of Item Due (Digest)','Advance Notice of Item Due','You have <<count>> items due soon'),
1782 ('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.');
1783 END_SQL
1784
1785     my @sql_scripts = (
1786         'installer/data/mysql/en/mandatory/message_transport_types.sql',
1787         'installer/data/mysql/en/optional/sample_notices_message_attributes.sql',
1788         'installer/data/mysql/en/optional/sample_notices_message_transports.sql',
1789     );
1790
1791     my $installer = C4::Installer->new();
1792     foreach my $script ( @sql_scripts ) {
1793         my $full_path = $installer->get_file_path_from_name($script);
1794         my $error = $installer->load_sql($full_path);
1795         warn $error if $error;
1796     }
1797
1798     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";
1799     SetVersion ($DBversion);
1800 }
1801
1802 $DBversion = "3.00.00.092";
1803 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1804     $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')");
1805     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES('AllowHoldsOnDamagedItems', '1', '', 'Allow hold requests to be placed on damaged items', 'YesNo')");
1806         print "Upgrade to $DBversion done (added new AllowOnShelfHolds syspref)\n";
1807     SetVersion ($DBversion);
1808 }
1809
1810 $DBversion = "3.00.00.093";
1811 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1812     $dbh->do("ALTER TABLE `items` MODIFY COLUMN `copynumber` VARCHAR(32) DEFAULT NULL");
1813     $dbh->do("ALTER TABLE `deleteditems` MODIFY COLUMN `copynumber` VARCHAR(32) DEFAULT NULL");
1814         print "Upgrade to $DBversion done (Change data type of items.copynumber to allow free text)\n";
1815     SetVersion ($DBversion);
1816 }
1817
1818 $DBversion = "3.00.00.094";
1819 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1820     $dbh->do("ALTER TABLE `marc_subfield_structure` MODIFY `tagsubfield` VARCHAR(1) NOT NULL DEFAULT '' COLLATE utf8_bin");
1821         print "Upgrade to $DBversion done (Change Collation of marc_subfield_structure to allow mixed case in subfield labels.)\n";
1822     SetVersion ($DBversion);
1823 }
1824
1825 $DBversion = "3.00.00.095";
1826 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1827     if (C4::Context->preference("marcflavour") eq 'MARC21') {
1828         $dbh->do("UPDATE marc_subfield_structure SET authtypecode = 'MEETI_NAME' WHERE authtypecode = 'Meeting Name'");
1829         $dbh->do("UPDATE marc_subfield_structure SET authtypecode = 'CORPO_NAME' WHERE authtypecode = 'CORP0_NAME'");
1830     }
1831         print "Upgrade to $DBversion done (fix invalid authority types in MARC21 frameworks [bug 2254])\n";
1832     SetVersion ($DBversion);
1833 }
1834
1835 $DBversion = "3.00.00.096";
1836 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1837     $sth = $dbh->prepare("SHOW COLUMNS FROM borrower_message_preferences LIKE 'wants_digets'");
1838     $sth->execute();
1839     if (my $row = $sth->fetchrow_hashref) {
1840         $dbh->do("ALTER TABLE borrower_message_preferences CHANGE wants_digets wants_digest tinyint(1) NOT NULL default 0");
1841     }
1842         print "Upgrade to $DBversion done (fix name borrower_message_preferences.wants_digest)\n";
1843     SetVersion ($DBversion);
1844 }
1845
1846 $DBversion = '3.00.00.097';
1847 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1848
1849     $dbh->do('ALTER TABLE message_queue ADD to_address   mediumtext default NULL');
1850     $dbh->do('ALTER TABLE message_queue ADD from_address mediumtext default NULL');
1851     $dbh->do('ALTER TABLE message_queue ADD content_type text');
1852     $dbh->do('ALTER TABLE message_queue CHANGE borrowernumber borrowernumber int(11) default NULL');
1853
1854     print "Upgrade to $DBversion done (updating 4 fields in message_queue table)\n";
1855     SetVersion($DBversion);
1856 }
1857
1858 $DBversion = '3.00.00.098';
1859 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1860
1861     $dbh->do(q(DELETE FROM message_transport_types WHERE message_transport_type = 'rss'));
1862     $dbh->do(q(DELETE FROM message_transports WHERE message_transport_type = 'rss'));
1863
1864     print "Upgrade to $DBversion done (removing unused RSS message_transport_type)\n";
1865     SetVersion($DBversion);
1866 }
1867
1868 $DBversion = '3.00.00.099';
1869 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1870     $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')");
1871     print "Upgrade to $DBversion done (Adding OpacSuppression syspref)\n";
1872     SetVersion($DBversion);
1873 }
1874
1875 $DBversion = '3.00.00.100';
1876 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1877         $dbh->do('ALTER TABLE virtualshelves ADD COLUMN lastmodified timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP');
1878     print "Upgrade to $DBversion done (Adding lastmodified column to virtualshelves)\n";
1879     SetVersion($DBversion);
1880 }
1881
1882 $DBversion = '3.00.00.101';
1883 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1884         $dbh->do('ALTER TABLE `overduerules` CHANGE `categorycode` `categorycode` VARCHAR(10) NOT NULL');
1885         $dbh->do('ALTER TABLE `deletedborrowers` CHANGE `categorycode` `categorycode` VARCHAR(10) NOT NULL');
1886     print "Upgrade to $DBversion done (Updating columnd definitions for patron category codes in notice/statsu triggers and deletedborrowers tables.)\n";
1887     SetVersion($DBversion);
1888 }
1889
1890 $DBversion = '3.00.00.102';
1891 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1892         $dbh->do('ALTER TABLE serialitems MODIFY `serialid` int(11) NOT NULL AFTER itemnumber' );
1893         $dbh->do('ALTER TABLE serialitems DROP KEY serialididx' );
1894         $dbh->do('ALTER TABLE serialitems ADD CONSTRAINT UNIQUE KEY serialitemsidx (itemnumber)' );
1895         # before setting constraint, delete any unvalid data
1896         $dbh->do('DELETE from serialitems WHERE serialid not in (SELECT serial.serialid FROM serial)');
1897         $dbh->do('ALTER TABLE serialitems ADD CONSTRAINT serialitems_sfk_1 FOREIGN KEY (serialid) REFERENCES serial (serialid) ON DELETE CASCADE ON UPDATE CASCADE' );
1898     print "Upgrade to $DBversion done (Updating serialitems table to allow for multiple items per serial fixing kohabug 2380)\n";
1899     SetVersion($DBversion);
1900 }
1901
1902 $DBversion = "3.00.00.103";
1903 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1904     $dbh->do("DELETE FROM systempreferences WHERE variable='serialsadditems'");
1905     print "Upgrade to $DBversion done ( Verifying the removal of serialsadditems from syspref fixing kohabug 2219)\n";
1906     SetVersion ($DBversion);
1907 }
1908
1909 $DBversion = "3.00.00.104";
1910 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1911     $dbh->do("DELETE FROM systempreferences WHERE variable='noOPACHolds'");
1912     print "Upgrade to $DBversion done (remove superseded 'noOPACHolds' system preference per bug 2413)\n";
1913     SetVersion ($DBversion);
1914 }
1915
1916 $DBversion = '3.00.00.105';
1917 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
1918
1919     # it is possible that this syspref is already defined since the feature was added some time ago.
1920     unless ( $dbh->do(q(SELECT variable FROM systempreferences WHERE variable = 'SMSSendDriver')) ) {
1921         $dbh->do(<<'END_SQL');
1922 INSERT INTO `systempreferences`
1923   (variable,value,explanation,options,type)
1924 VALUES
1925 ('SMSSendDriver','','Sets which SMS::Send driver is used to send SMS messages.','','free')
1926 END_SQL
1927     }
1928     print "Upgrade to $DBversion done (added SMSSendDriver system preference)\n";
1929     SetVersion($DBversion);
1930 }
1931
1932 $DBversion = "3.00.00.106";
1933 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1934     $dbh->do("DELETE FROM systempreferences WHERE variable='noOPACHolds'");
1935
1936 # db revision 105 didn't apply correctly, so we're rolling this into 106
1937         $dbh->do("INSERT INTO `systempreferences`
1938    (variable,value,explanation,options,type)
1939         VALUES
1940         ('SMSSendDriver','','Sets which SMS::Send driver is used to send SMS messages.','','free')");
1941
1942     print "Upgrade to $DBversion done (remove default '0000-00-00' in subscriptionhistory.enddate field)\n";
1943     $dbh->do("ALTER TABLE `subscriptionhistory` CHANGE `enddate` `enddate` DATE NULL DEFAULT NULL ");
1944     $dbh->do("UPDATE subscriptionhistory SET enddate=NULL WHERE enddate='0000-00-00'");
1945     SetVersion ($DBversion);
1946 }
1947
1948 $DBversion = '3.00.00.107';
1949 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1950     $dbh->do(<<'END_SQL');
1951 UPDATE systempreferences
1952   SET explanation = CONCAT( explanation, '. WARNING: this feature is very resource consuming on collections with large numbers of items.' )
1953   WHERE variable = 'OPACShelfBrowser'
1954     AND explanation NOT LIKE '%WARNING%'
1955 END_SQL
1956     $dbh->do(<<'END_SQL');
1957 UPDATE systempreferences
1958   SET explanation = CONCAT( explanation, '. WARNING: this feature is very resource consuming.' )
1959   WHERE variable = 'CataloguingLog'
1960     AND explanation NOT LIKE '%WARNING%'
1961 END_SQL
1962     $dbh->do(<<'END_SQL');
1963 UPDATE systempreferences
1964   SET explanation = CONCAT( explanation, '. WARNING: using NoZebra on even modest sized collections is very slow.' )
1965   WHERE variable = 'NoZebra'
1966     AND explanation NOT LIKE '%WARNING%'
1967 END_SQL
1968     print "Upgrade to $DBversion done (warning added to OPACShelfBrowser system preference)\n";
1969     SetVersion ($DBversion);
1970 }
1971
1972 $DBversion = '3.01.00.000';
1973 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1974     print "Upgrade to $DBversion done (start of 3.1)\n";
1975     SetVersion ($DBversion);
1976 }
1977
1978 $DBversion = '3.01.00.001';
1979 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1980     $dbh->do("
1981         CREATE TABLE hold_fill_targets (
1982             `borrowernumber` int(11) NOT NULL,
1983             `biblionumber` int(11) NOT NULL,
1984             `itemnumber` int(11) NOT NULL,
1985             `source_branchcode`  varchar(10) default NULL,
1986             `item_level_request` tinyint(4) NOT NULL default 0,
1987             PRIMARY KEY `itemnumber` (`itemnumber`),
1988             KEY `bib_branch` (`biblionumber`, `source_branchcode`),
1989             CONSTRAINT `hold_fill_targets_ibfk_1` FOREIGN KEY (`borrowernumber`)
1990                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1991             CONSTRAINT `hold_fill_targets_ibfk_2` FOREIGN KEY (`biblionumber`)
1992                 REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1993             CONSTRAINT `hold_fill_targets_ibfk_3` FOREIGN KEY (`itemnumber`)
1994                 REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1995             CONSTRAINT `hold_fill_targets_ibfk_4` FOREIGN KEY (`source_branchcode`)
1996                 REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
1997         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1998     ");
1999     $dbh->do("
2000         ALTER TABLE tmp_holdsqueue
2001             ADD item_level_request tinyint(4) NOT NULL default 0
2002     ");
2003
2004     print "Upgrade to $DBversion done (add hold_fill_targets table and a column to tmp_holdsqueue)\n";
2005     SetVersion($DBversion);
2006 }
2007
2008 $DBversion = '3.01.00.002';
2009 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2010     # use statistics where available
2011     $dbh->do("
2012         ALTER TABLE statistics ADD KEY  tmp_stats (type, itemnumber, borrowernumber)
2013     ");
2014     $dbh->do("
2015         UPDATE issues iss
2016         SET issuedate = (
2017             SELECT max(datetime)
2018             FROM statistics
2019             WHERE type = 'issue'
2020             AND itemnumber = iss.itemnumber
2021             AND borrowernumber = iss.borrowernumber
2022         )
2023         WHERE issuedate IS NULL;
2024     ");
2025     $dbh->do("ALTER TABLE statistics DROP KEY tmp_stats");
2026
2027     # default to last renewal date
2028     $dbh->do("
2029         UPDATE issues
2030         SET issuedate = lastreneweddate
2031         WHERE issuedate IS NULL
2032         and lastreneweddate IS NOT NULL
2033     ");
2034
2035     my $num_bad_issuedates = $dbh->selectrow_array("SELECT COUNT(*) FROM issues WHERE issuedate IS NULL");
2036     if ($num_bad_issuedates > 0) {
2037         print STDERR "After the upgrade to $DBversion, there are still $num_bad_issuedates loan(s) with a NULL (blank) loan date. ",
2038                      "Please check the issues table in your database.";
2039     }
2040     print "Upgrade to $DBversion done (bug 2582: set null issues.issuedate to lastreneweddate)\n";
2041     SetVersion($DBversion);
2042 }
2043
2044 $DBversion = "3.01.00.003";
2045 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2046     $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')");
2047     print "Upgrade to $DBversion done (add new syspref)\n";
2048     SetVersion ($DBversion);
2049 }
2050
2051 $DBversion = '3.01.00.004';
2052 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2053     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACDisplayRequestPriority','0','Show patrons the priority level on holds in the OPAC','','YesNo')");
2054     print "Upgrade to $DBversion done (added OPACDisplayRequestPriority system preference)\n";
2055     SetVersion ($DBversion);
2056 }
2057
2058 $DBversion = '3.01.00.005';
2059 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2060     $dbh->do("
2061         INSERT INTO `letter` (module, code, name, title, content)
2062         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>>')
2063     ");
2064     $dbh->do("INSERT INTO `message_attributes` (message_attribute_id, message_name, takes_days) values(4, 'Hold Filled', 0)");
2065     $dbh->do("INSERT INTO `message_transports` (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) values(4, 'sms', 0, 'reserves', 'HOLD')");
2066     $dbh->do("INSERT INTO `message_transports` (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) values(4, 'email', 0, 'reserves', 'HOLD')");
2067     print "Upgrade to $DBversion done (Add letter for holds notifications)\n";
2068     SetVersion ($DBversion);
2069 }
2070
2071 $DBversion = '3.01.00.006';
2072 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2073     $dbh->do("ALTER TABLE `biblioitems` ADD KEY issn (issn)");
2074     print "Upgrade to $DBversion done (add index on biblioitems.issn)\n";
2075     SetVersion ($DBversion);
2076 }
2077
2078 $DBversion = "3.01.00.007";
2079 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2080     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='intranetmainUserblock'");
2081     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='intranetuserjs'");
2082     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='opacheader'");
2083     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='OpacMainUserBlock'");
2084     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='OpacNav'");
2085     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='opacuserjs'");
2086     $dbh->do("UPDATE `systempreferences` SET options='30|10', type='Textarea' WHERE variable='OAI-PMH:Set'");
2087     $dbh->do("UPDATE `systempreferences` SET options='50' WHERE variable='intranetstylesheet'");
2088     $dbh->do("UPDATE `systempreferences` SET options='50' WHERE variable='intranetcolorstylesheet'");
2089     $dbh->do("UPDATE `systempreferences` SET options='10' WHERE variable='globalDueDate'");
2090     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='numSearchResults'");
2091     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='OPACnumSearchResults'");
2092     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='ReservesMaxPickupDelay'");
2093     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='TransfersMaxDaysWarning'");
2094     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='StaticHoldsQueueWeight'");
2095     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='holdCancelLength'");
2096     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='XISBNDailyLimit'");
2097     $dbh->do("UPDATE `systempreferences` SET type='Float' WHERE variable='gist'");
2098     $dbh->do("UPDATE `systempreferences` SET type='Free' WHERE variable='BakerTaylorUsername'");
2099     $dbh->do("UPDATE `systempreferences` SET type='Free' WHERE variable='BakerTaylorPassword'");
2100     $dbh->do("UPDATE `systempreferences` SET type='Textarea', options='70|10' WHERE variable='ISBD'");
2101     $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'");
2102     print "Upgrade to $DBversion done (fix display of many sysprefs)\n";
2103     SetVersion ($DBversion);
2104 }
2105
2106 $DBversion = '3.01.00.008';
2107 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2108
2109     $dbh->do("CREATE TABLE branch_transfer_limits (
2110                           limitId int(8) NOT NULL auto_increment,
2111                           toBranch varchar(4) NOT NULL,
2112                           fromBranch varchar(4) NOT NULL,
2113                           itemtype varchar(4) NOT NULL,
2114                           PRIMARY KEY  (limitId)
2115                           ) ENGINE=InnoDB DEFAULT CHARSET=utf8"
2116                         );
2117
2118     $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')");
2119
2120     print "Upgrade to $DBversion done (added branch_transfer_limits table and UseBranchTransferLimits system preference)\n";
2121     SetVersion ($DBversion);
2122 }
2123
2124 $DBversion = "3.01.00.009";
2125 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2126     $dbh->do("ALTER TABLE permissions MODIFY `code` varchar(64) DEFAULT NULL");
2127     $dbh->do("ALTER TABLE user_permissions MODIFY `code` varchar(64) DEFAULT NULL");
2128     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'circulate_remaining_permissions', 'Remaining circulation permissions')");
2129     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'override_renewals', 'Override blocked renewals')");
2130     print "Upgrade to $DBversion done (added subpermissions for circulate permission)\n";
2131 }
2132
2133 $DBversion = '3.01.00.010';
2134 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2135     $dbh->do("ALTER TABLE `borrower_attributes` MODIFY COLUMN `attribute` VARCHAR(64) DEFAULT NULL");
2136     $dbh->do("ALTER TABLE `borrower_attributes` MODIFY COLUMN `password` VARCHAR(64) DEFAULT NULL");
2137     print "Upgrade to $DBversion done (bug 2687: increase length of borrower attribute fields)\n";
2138     SetVersion ($DBversion);
2139 }
2140
2141 $DBversion = '3.01.00.011';
2142 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2143
2144     # Yes, the old value was ^M terminated.
2145     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);";
2146
2147     my $intranetuserjs = C4::Context->preference('intranetuserjs');
2148     if ($intranetuserjs  and  $intranetuserjs eq $bad_value) {
2149         my $sql = <<'END_SQL';
2150 UPDATE systempreferences
2151 SET value = ''
2152 WHERE variable = 'intranetuserjs'
2153 END_SQL
2154         $dbh->do($sql);
2155     }
2156     print "Upgrade to $DBversion done (removed bogus intranetuserjs syspref)\n";
2157     SetVersion($DBversion);
2158 }
2159
2160 $DBversion = "3.01.00.012";
2161 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2162     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowHoldPolicyOverride', '0', 'Allow staff to override hold policies when placing holds',NULL,'YesNo')");
2163     $dbh->do("
2164         CREATE TABLE `branch_item_rules` (
2165           `branchcode` varchar(10) NOT NULL,
2166           `itemtype` varchar(10) NOT NULL,
2167           `holdallowed` tinyint(1) default NULL,
2168           PRIMARY KEY  (`itemtype`,`branchcode`),
2169           KEY `branch_item_rules_ibfk_2` (`branchcode`),
2170           CONSTRAINT `branch_item_rules_ibfk_1` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE,
2171           CONSTRAINT `branch_item_rules_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
2172         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2173     ");
2174     $dbh->do("
2175         CREATE TABLE `default_branch_item_rules` (
2176           `itemtype` varchar(10) NOT NULL,
2177           `holdallowed` tinyint(1) default NULL,
2178           PRIMARY KEY  (`itemtype`),
2179           CONSTRAINT `default_branch_item_rules_ibfk_1` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE
2180         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2181     ");
2182     $dbh->do("
2183         ALTER TABLE default_branch_circ_rules
2184             ADD COLUMN holdallowed tinyint(1) NULL
2185     ");
2186     $dbh->do("
2187         ALTER TABLE default_circ_rules
2188             ADD COLUMN holdallowed tinyint(1) NULL
2189     ");
2190     print "Upgrade to $DBversion done (Add tables and system preferences for holds policies)\n";
2191     SetVersion ($DBversion);
2192 }
2193
2194 $DBversion = '3.01.00.013';
2195 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2196     $dbh->do("
2197         CREATE TABLE item_circulation_alert_preferences (
2198             id           int(11) AUTO_INCREMENT,
2199             branchcode   varchar(10) NOT NULL,
2200             categorycode varchar(10) NOT NULL,
2201             item_type    varchar(10) NOT NULL,
2202             notification varchar(16) NOT NULL,
2203             PRIMARY KEY (id),
2204             KEY (branchcode, categorycode, item_type, notification)
2205         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2206     ");
2207
2208     $dbh->do(q{ ALTER TABLE `message_queue` ADD metadata text DEFAULT NULL           AFTER content;  });
2209     $dbh->do(q{ ALTER TABLE `message_queue` ADD letter_code varchar(64) DEFAULT NULL AFTER metadata; });
2210
2211     $dbh->do(q{
2212         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
2213         ('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.');
2214     });
2215     $dbh->do(q{
2216         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
2217         ('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>>.');
2218     });
2219
2220     $dbh->do(q{INSERT INTO message_attributes (message_attribute_id, message_name, takes_days) VALUES (5, 'Item Check-in', 0);});
2221     $dbh->do(q{INSERT INTO message_attributes (message_attribute_id, message_name, takes_days) VALUES (6, 'Item Checkout', 0);});
2222
2223     $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');});
2224     $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');});
2225     $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');});
2226     $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');});
2227
2228     print "Upgrade to $DBversion done (data for Email Checkout Slips project)\n";
2229          SetVersion ($DBversion);
2230 }
2231
2232 $DBversion = "3.01.00.014";
2233 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2234     $dbh->do("ALTER TABLE `branch_transfer_limits` CHANGE `itemtype` `itemtype` VARCHAR( 4 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL");
2235     $dbh->do("ALTER TABLE `branch_transfer_limits` ADD `ccode` VARCHAR( 10 ) NULL ;");
2236     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2237     VALUES (
2238     'BranchTransferLimitsType', 'ccode', 'itemtype|ccode', 'When using branch transfer limits, choose whether to limit by itemtype or collection code.', 'Choice'
2239     );");
2240
2241     print "Upgrade to $DBversion done ( Updated table for Branch Transfer Limits)\n";
2242     SetVersion ($DBversion);
2243 }
2244
2245 $DBversion = '3.01.00.015';
2246 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2247     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsClientCode', '0', 'Client Code for using Syndetics Solutions content','','free')");
2248
2249     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsEnabled', '0', 'Turn on Syndetics Enhanced Content','','YesNo')");
2250
2251     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsCoverImages', '0', 'Display Cover Images from Syndetics','','YesNo')");
2252
2253     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsTOC', '0', 'Display Table of Content information from Syndetics','','YesNo')");
2254
2255     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsSummary', '0', 'Display Summary Information from Syndetics','','YesNo')");
2256
2257     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsEditions', '0', 'Display Editions from Syndetics','','YesNo')");
2258
2259     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsExcerpt', '0', 'Display Excerpts and first chapters on OPAC from Syndetics','','YesNo')");
2260
2261     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsReviews', '0', 'Display Reviews on OPAC from Syndetics','','YesNo')");
2262
2263     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsAuthorNotes', '0', 'Display Notes about the Author on OPAC from Syndetics','','YesNo')");
2264
2265     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsAwards', '0', 'Display Awards on OPAC from Syndetics','','YesNo')");
2266
2267     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsSeries', '0', 'Display Series information on OPAC from Syndetics','','YesNo')");
2268
2269     $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')");
2270
2271     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAmazonCoverImages', '0', 'Display cover images on OPAC from Amazon Web Services','','YesNo')");
2272
2273     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AmazonCoverImages', '0', 'Display Cover Images in Staff Client from Amazon Web Services','','YesNo')");
2274
2275     $dbh->do("UPDATE systempreferences SET variable='AmazonEnabled' WHERE variable = 'AmazonContent'");
2276
2277     $dbh->do("UPDATE systempreferences SET variable='OPACAmazonEnabled' WHERE variable = 'OPACAmazonContent'");
2278
2279     print "Upgrade to $DBversion done (added Syndetics Enhanced Content system preferences)\n";
2280     SetVersion ($DBversion);
2281 }
2282
2283 $DBversion = "3.01.00.016";
2284 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2285     $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')");
2286     print "Upgrade to $DBversion done (Added Babeltheque syspref)\n";
2287     SetVersion ($DBversion);
2288 }
2289
2290 $DBversion = "3.01.00.017";
2291 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2292     $dbh->do("ALTER TABLE `subscription` ADD `staffdisplaycount` VARCHAR(10) NULL;");
2293     $dbh->do("ALTER TABLE `subscription` ADD `opacdisplaycount` VARCHAR(10) NULL;");
2294     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2295     VALUES (
2296     'StaffSerialIssueDisplayCount', '3', '', 'Number of serial issues to display per subscription in the Staff client', 'Integer'
2297     );");
2298         $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2299     VALUES (
2300     'OPACSerialIssueDisplayCount', '3', '', 'Number of serial issues to display per subscription in the OPAC', 'Integer'
2301     );");
2302
2303     print "Upgrade to $DBversion done ( Updated table for Serials Display)\n";
2304     SetVersion ($DBversion);
2305 }
2306
2307 $DBversion = "3.01.00.018";
2308 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2309     $dbh->do("ALTER TABLE deletedborrowers ADD `smsalertnumber` varchar(50) default NULL");
2310     print "Upgrade to $DBversion done (added deletedborrowers.smsalertnumber, missed in 3.00.00.091)\n";
2311     SetVersion ($DBversion);
2312 }
2313
2314 $DBversion = "3.01.00.019";
2315 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2316         $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')");
2317     print "Upgrade to $DBversion done (adding OPACShowCheckoutName systempref)\n";
2318     SetVersion ($DBversion);
2319 }
2320
2321 $DBversion = "3.01.00.020";
2322 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2323     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesID','','See:http://librarything.com/forlibraries/','','free')");
2324     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesEnabled','0','Enable or Disable Library Thing for Libraries Features','','YesNo')");
2325     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesTabbedView','0','Put LibraryThingForLibraries Content in Tabs.','','YesNo')");
2326     print "Upgrade to $DBversion done (adding LibraryThing for Libraries sysprefs)\n";
2327     SetVersion ($DBversion);
2328 }
2329
2330 $DBversion = "3.01.00.021";
2331 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2332     my $enable_reviews = C4::Context->preference('OPACAmazonEnabled') ? '1' : '0';
2333     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAmazonReviews', '$enable_reviews', 'Display Amazon readers reviews on OPAC','','YesNo')");
2334     print "Upgrade to $DBversion done (adding OPACAmazonReviews syspref)\n";
2335     SetVersion ($DBversion);
2336 }
2337
2338 $DBversion = '3.01.00.022';
2339 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2340     $dbh->do("ALTER TABLE `labels_conf` MODIFY COLUMN `formatstring` mediumtext DEFAULT NULL");
2341     print "Upgrade to $DBversion done (bug 2945: increase size of labels_conf.formatstring)\n";
2342     SetVersion ($DBversion);
2343 }
2344
2345 $DBversion = '3.01.00.023';
2346 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2347     $dbh->do("ALTER TABLE biblioitems        MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2348     $dbh->do("ALTER TABLE deletedbiblioitems MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2349     $dbh->do("ALTER TABLE import_biblios     MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2350     $dbh->do("ALTER TABLE suggestions        MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2351     print "Upgrade to $DBversion done (bug 2765: increase width of isbn column in several tables)\n";
2352     SetVersion ($DBversion);
2353 }
2354
2355 $DBversion = "3.01.00.024";
2356 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2357     $dbh->do("ALTER TABLE labels MODIFY COLUMN batch_id int(10) NOT NULL default 1;");
2358     print "Upgrade to $DBversion done (change labels.batch_id from varchar to int)\n";
2359     SetVersion ($DBversion);
2360 }
2361
2362 $DBversion = '3.01.00.025';
2363 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2364     $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')");
2365
2366     print "Upgrade to $DBversion done (added ceilingDueDate system preference)\n";
2367     SetVersion ($DBversion);
2368 }
2369
2370 $DBversion = '3.01.00.026';
2371 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2372     $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')");
2373
2374     print "Upgrade to $DBversion done (added numReturnedItemsToShow system preference)\n";
2375     SetVersion ($DBversion);
2376 }
2377
2378 $DBversion = '3.01.00.027';
2379 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2380     $dbh->do("ALTER TABLE zebraqueue CHANGE `biblio_auth_number` `biblio_auth_number` bigint(20) unsigned NOT NULL default 0");
2381     print "Upgrade to $DBversion done (Increased size of zebraqueue biblio_auth_number to address bug 3148.)\n";
2382     SetVersion ($DBversion);
2383 }
2384
2385 $DBversion = '3.01.00.028';
2386 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2387     my $enable_reviews = C4::Context->preference('AmazonEnabled') ? '1' : '0';
2388     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AmazonReviews', '$enable_reviews', 'Display Amazon reviews on staff interface','','YesNo')");
2389     print "Upgrade to $DBversion done (added AmazonReviews)\n";
2390     SetVersion ($DBversion);
2391 }
2392
2393 $DBversion = '3.01.00.029';
2394 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2395     $dbh->do(q( UPDATE language_rfc4646_to_iso639
2396                 SET iso639_2_code = 'spa'
2397                 WHERE rfc4646_subtag = 'es'
2398                 AND   iso639_2_code = 'rus' )
2399             );
2400     print "Upgrade to $DBversion done (fixed bug 2599: using Spanish search limit retrieves Russian results)\n";
2401     SetVersion ($DBversion);
2402 }
2403
2404 $DBversion = "3.01.00.030";
2405 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2406     $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')");
2407     print "Upgrade to $DBversion done (added AllowNotForLoanOverride system preference)\n";
2408     SetVersion ($DBversion);
2409 }
2410
2411 $DBversion = "3.01.00.031";
2412 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2413     $dbh->do("ALTER TABLE branch_transfer_limits
2414               MODIFY toBranch   varchar(10) NOT NULL,
2415               MODIFY fromBranch varchar(10) NOT NULL,
2416               MODIFY itemtype   varchar(10) NULL");
2417     print "Upgrade to $DBversion done (fix column widths in branch_transfer_limits)\n";
2418     SetVersion ($DBversion);
2419 }
2420
2421 $DBversion = "3.01.00.032";
2422 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2423     $dbh->do(<<ENDOFRENEWAL);
2424 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');
2425 ENDOFRENEWAL
2426     print "Upgrade to $DBversion done (Change the field)\n";
2427     SetVersion ($DBversion);
2428 }
2429
2430 $DBversion = "3.01.00.033";
2431 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2432     $dbh->do(q/
2433         ALTER TABLE borrower_message_preferences
2434         MODIFY borrowernumber int(11) default NULL,
2435         ADD    categorycode varchar(10) default NULL AFTER borrowernumber,
2436         ADD KEY `categorycode` (`categorycode`),
2437         ADD CONSTRAINT `borrower_message_preferences_ibfk_3`
2438                        FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
2439                        ON DELETE CASCADE ON UPDATE CASCADE
2440     /);
2441     print "Upgrade to $DBversion done (DB changes to allow patron category defaults for messaging preferences)\n";
2442     SetVersion ($DBversion);
2443 }
2444
2445 $DBversion = "3.01.00.034";
2446 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2447     $dbh->do("ALTER TABLE `subscription` ADD COLUMN `graceperiod` INT(11) NOT NULL default '0';");
2448     print "Upgrade to $DBversion done (Adding graceperiod column to subscription table)\n";
2449     SetVersion ($DBversion);
2450 }
2451
2452 $DBversion = '3.01.00.035';
2453 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2454     $dbh->do(q{ ALTER TABLE `subscription` ADD location varchar(80) NULL DEFAULT '' AFTER callnumber; });
2455    print "Upgrade to $DBversion done (Adding location to subscription table)\n";
2456     SetVersion ($DBversion);
2457 }
2458
2459 $DBversion = '3.01.00.036';
2460 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2461     $dbh->do("UPDATE systempreferences SET explanation = 'Choose the default detail view in the staff interface; choose between normal, labeled_marc, marc or isbd'
2462               WHERE variable = 'IntranetBiblioDefaultView'
2463               AND   explanation = 'IntranetBiblioDefaultView'");
2464     $dbh->do("UPDATE systempreferences SET type = 'Choice', options = 'normal|marc|isbd|labeled_marc'
2465               WHERE variable = 'IntranetBiblioDefaultView'");
2466     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewISBD','1','Allow display of ISBD view of bibiographic records','','YesNo')");
2467     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewLabeledMARC','0','Allow display of labeled MARC view of bibiographic records','','YesNo')");
2468     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewMARC','1','Allow display of MARC view of bibiographic records','','YesNo')");
2469     print "Upgrade to $DBversion done (new viewISBD, viewLabeledMARC, viewMARC sysprefs and tweak IntranetBiblioDefaultView)\n";
2470     SetVersion ($DBversion);
2471 }
2472
2473 $DBversion = '3.01.00.037';
2474 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2475     $dbh->do('ALTER TABLE authorised_values ADD KEY `lib` (`lib`)');
2476     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('FilterBeforeOverdueReport','0','Do not run overdue report until filter selected','','YesNo')");
2477     SetVersion ($DBversion);
2478     print "Upgrade to $DBversion done (added FilterBeforeOverdueReport syspref and new index on authorised_values)\n";
2479 }
2480
2481 $DBversion = "3.01.00.038";
2482 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2483     # update branches table
2484     #
2485     $dbh->do("ALTER TABLE branches ADD `branchzip` varchar(25) default NULL AFTER `branchaddress3`");
2486     $dbh->do("ALTER TABLE branches ADD `branchcity` mediumtext AFTER `branchzip`");
2487     $dbh->do("ALTER TABLE branches ADD `branchcountry` text AFTER `branchcity`");
2488     $dbh->do("ALTER TABLE branches ADD `branchurl` mediumtext AFTER `branchemail`");
2489     $dbh->do("ALTER TABLE branches ADD `branchnotes` mediumtext AFTER `branchprinter`");
2490     print "Upgrade to $DBversion done (add ZIP, city, country, URL, and notes column to branches)\n";
2491     SetVersion ($DBversion);
2492 }
2493
2494 $DBversion = '3.01.00.039';
2495 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2496     $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')");
2497     $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')");
2498     SetVersion ($DBversion);
2499     print "Upgrade to $DBversion done (added SpineLabelFormat and SpineLabelAutoPrint sysprefs)\n";
2500 }
2501
2502 $DBversion = '3.01.00.040';
2503 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2504     $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')");
2505     $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')");
2506     SetVersion ($DBversion);
2507     print "Upgrade to $DBversion done (AllowHoldDateInFuture and OPACAllowHoldDateInFuture sysprefs)\n";
2508 }
2509
2510 $DBversion = '3.01.00.041';
2511 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2512     $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')");
2513     SetVersion ($DBversion);
2514     print "Upgrade to $DBversion done (added AWSPrivateKey syspref - note that if you use enhanced content from Amazon, this should be set right away.)\n";
2515 }
2516
2517 $DBversion = '3.01.00.042';
2518 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2519     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACFineNoRenewals','99999','Fine Limit above which user canmot renew books via OPAC','','Integer')");
2520     SetVersion ($DBversion);
2521     print "Upgrade to $DBversion done (added OPACFineNoRenewals syspref)\n";
2522 }
2523
2524 $DBversion = '3.01.00.043';
2525 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2526     $dbh->do('ALTER TABLE items ADD COLUMN permanent_location VARCHAR(80) DEFAULT NULL AFTER location');
2527     $dbh->do('UPDATE items SET permanent_location = location');
2528     $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 )', '')");
2529     $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')");
2530     $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')");
2531     SetVersion ($DBversion);
2532     print "Upgrade to $DBversion done (amended Item added NewItemsDefaultLocation, InProcessingToShelvingCart, ReturnToShelvingCart sysprefs)\n";
2533 }
2534
2535 $DBversion = '3.01.00.044';
2536 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2537     $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')");
2538     SetVersion ($DBversion);
2539     print "Upgrade to $DBversion done (added DisplayClearScreenButton system preference)\n";
2540 }
2541
2542 $DBversion = '3.01.00.045';
2543 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2544     $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')");
2545     SetVersion ($DBversion);
2546     print "Upgrade to $DBversion done (added a preference to hide the patrons name in the staff catalog)";
2547 }
2548
2549 $DBversion = "3.01.00.046";
2550 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2551     # update borrowers table
2552     #
2553     $dbh->do("ALTER TABLE borrowers ADD `country` text AFTER zipcode");
2554     $dbh->do("ALTER TABLE borrowers ADD `B_country` text AFTER B_zipcode");
2555     $dbh->do("ALTER TABLE deletedborrowers ADD `country` text AFTER zipcode");
2556     $dbh->do("ALTER TABLE deletedborrowers ADD `B_country` text AFTER B_zipcode");
2557     print "Upgrade to $DBversion done (add country and B_country to borrowers)\n";
2558     SetVersion ($DBversion);
2559 }
2560
2561 $DBversion = '3.01.00.047';
2562 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2563     $dbh->do("ALTER TABLE items MODIFY itemcallnumber varchar(255);");
2564     $dbh->do("ALTER TABLE deleteditems MODIFY itemcallnumber varchar(255);");
2565     $dbh->do("ALTER TABLE tmp_holdsqueue MODIFY itemcallnumber varchar(255);");
2566     SetVersion ($DBversion);
2567     print " Upgrade to $DBversion done (bug 2761: change max length of itemcallnumber to 255 from 30)\n";
2568 }
2569
2570 $DBversion = '3.01.00.048';
2571 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2572     $dbh->do("UPDATE userflags SET flagdesc='View Catalog (Librarian Interface)' WHERE bit=2;");
2573     $dbh->do("UPDATE userflags SET flagdesc='Edit Catalog (Modify bibliographic/holdings data)' WHERE bit=9;");
2574     $dbh->do("UPDATE userflags SET flagdesc='Allow to edit authorities' WHERE bit=14;");
2575     $dbh->do("UPDATE userflags SET flagdesc='Allow to access to the reports module' WHERE bit=16;");
2576     $dbh->do("UPDATE userflags SET flagdesc='Allow to manage serials subscriptions' WHERE bit=15;");
2577     SetVersion ($DBversion);
2578     print " Upgrade to $DBversion done (bug 2611: fix spelling/capitalization in permission flag descriptions)\n";
2579 }
2580
2581 $DBversion = '3.01.00.049';
2582 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2583     $dbh->do("UPDATE permissions SET description = 'Perform inventory (stocktaking) of your catalog' WHERE code = 'inventory';");
2584      SetVersion ($DBversion);
2585     print "Upgrade to $DBversion done (bug 2611: changed catalogue to catalog per the standard)\n";
2586 }
2587
2588 $DBversion = '3.01.00.050';
2589 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2590     $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');");
2591     SetVersion ($DBversion);
2592     print "Upgrade to $DBversion done (bug 1934: Add OPACSearchForTitleIn syspref)\n";
2593 }
2594
2595 $DBversion = '3.01.00.051';
2596 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2597     $dbh->do("UPDATE systempreferences SET explanation='Fine limit above which user cannot renew books via OPAC' WHERE variable='OPACFineNoRenewals';");
2598     $dbh->do("UPDATE systempreferences SET explanation='If set to ON, a clear screen button will appear on the circulation page.' WHERE variable='DisplayClearScreenButton';");
2599     SetVersion ($DBversion);
2600     print "Upgrade to $DBversion done (fixed typos in new sysprefs)\n";
2601 }
2602
2603 $DBversion = '3.01.00.052';
2604 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2605     $dbh->do('ALTER TABLE deleteditems ADD COLUMN permanent_location VARCHAR(80) DEFAULT NULL AFTER location');
2606     SetVersion ($DBversion);
2607     print "Upgrade to $DBversion done (bug 3481: add permanent_location column to deleteditems)\n";
2608 }
2609
2610 $DBversion = '3.01.00.053';
2611 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2612     my $upgrade_script = C4::Context->config("intranetdir") . "/installer/data/mysql/labels_upgrade.pl";
2613     system("perl $upgrade_script");
2614     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";
2615     SetVersion ($DBversion);
2616 }
2617
2618 $DBversion = '3.01.00.054';
2619 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2620     $dbh->do("ALTER TABLE borrowers ADD `B_address2` text AFTER B_address");
2621     $dbh->do("ALTER TABLE borrowers ADD `altcontactcountry` text AFTER altcontactzipcode");
2622     $dbh->do("ALTER TABLE deletedborrowers ADD `B_address2` text AFTER B_address");
2623     $dbh->do("ALTER TABLE deletedborrowers ADD `altcontactcountry` text AFTER altcontactzipcode");
2624     SetVersion ($DBversion);
2625     print "Upgrade to $DBversion done (bug 1600, bug 3454: add altcontactcountry and B_address2 to borrowers and deletedborrowers)\n";
2626 }
2627
2628 $DBversion = '3.01.00.055';
2629 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2630     $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'|);
2631     SetVersion ($DBversion);
2632     print "Upgrade to $DBversion done (changed OPACSearchForTitleIn per requests in bug 1934)\n";
2633 }
2634
2635 $DBversion = '3.01.00.056';
2636 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2637     $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');");
2638     SetVersion ($DBversion);
2639     print "Upgrade to $DBversion done (Bug 1172 : Add OPACPatronDetails syspref)\n";
2640 }
2641
2642 $DBversion = '3.01.00.057';
2643 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2644     $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');");
2645     SetVersion ($DBversion);
2646     print "Upgrade to $DBversion done (Bug 2576 : Add OPACFinesTab syspref)\n";
2647 }
2648
2649 $DBversion = '3.01.00.058';
2650 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2651     $dbh->do("ALTER TABLE `language_subtag_registry` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2652     $dbh->do("ALTER TABLE `language_rfc4646_to_iso639` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2653     $dbh->do("ALTER TABLE `language_descriptions` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2654     SetVersion ($DBversion);
2655     print "Upgrade to $DBversion done (Added primary keys to language tables)\n";
2656 }
2657
2658 $DBversion = '3.01.00.059';
2659 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2660     $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')");
2661     SetVersion ($DBversion);
2662     print "Upgrade to $DBversion done (added DisplayOPACiconsXSLT sysprefs)\n";
2663 }
2664
2665 $DBversion = '3.01.00.060';
2666 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2667     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowAllMessageDeletion','0','Allow any Library to delete any message','','YesNo');");
2668     $dbh->do('DROP TABLE IF EXISTS messages');
2669     $dbh->do("CREATE TABLE messages ( `message_id` int(11) NOT NULL auto_increment,
2670         `borrowernumber` int(11) NOT NULL,
2671         `branchcode` varchar(4) default NULL,
2672         `message_type` varchar(1) NOT NULL,
2673         `message` text NOT NULL,
2674         `message_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
2675         PRIMARY KEY (`message_id`)
2676         ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
2677
2678         print "Upgrade to $DBversion done ( Added AllowAllMessageDeletion syspref and messages table )\n";
2679     SetVersion ($DBversion);
2680 }
2681
2682 $DBversion = '3.01.00.061';
2683 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2684     $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')");
2685         print "Upgrade to $DBversion done ( Added ShowPatronImageInWebBasedSelfCheck system preference )\n";
2686     SetVersion ($DBversion);
2687 }
2688
2689 $DBversion = "3.01.00.062";
2690 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2691     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'manage_csv_profiles', 'Manage CSV export profiles')");
2692     $dbh->do(q/
2693         CREATE TABLE `export_format` (
2694           `export_format_id` int(11) NOT NULL auto_increment,
2695           `profile` varchar(255) NOT NULL,
2696           `description` mediumtext NOT NULL,
2697           `marcfields` mediumtext NOT NULL,
2698           PRIMARY KEY  (`export_format_id`)
2699         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Used for CSV export';
2700     /);
2701     print "Upgrade to $DBversion done (added csv export profiles)\n";
2702 }
2703
2704 $DBversion = "3.01.00.063";
2705 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2706     $dbh->do("
2707         CREATE TABLE `fieldmapping` (
2708           `id` int(11) NOT NULL auto_increment,
2709           `field` varchar(255) NOT NULL,
2710           `frameworkcode` char(4) NOT NULL default '',
2711           `fieldcode` char(3) NOT NULL,
2712           `subfieldcode` char(1) NOT NULL,
2713           PRIMARY KEY  (`id`)
2714         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2715              ");
2716     SetVersion ($DBversion);
2717 }
2718
2719 $DBversion = '3.01.00.065';
2720 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2721     $dbh->do('ALTER TABLE issuingrules ADD COLUMN `renewalsallowed` smallint(6) NOT NULL default "0" AFTER `issuelength`;');
2722     $sth = $dbh->prepare("SELECT itemtype, renewalsallowed FROM itemtypes");
2723     $sth->execute();
2724
2725     my $sthupd = $dbh->prepare("UPDATE issuingrules SET renewalsallowed = ? WHERE itemtype = ?");
2726
2727     while(my $row = $sth->fetchrow_hashref){
2728         $sthupd->execute($row->{renewalsallowed}, $row->{itemtype});
2729     }
2730
2731     $dbh->do('ALTER TABLE itemtypes DROP COLUMN `renewalsallowed`;');
2732
2733     SetVersion ($DBversion);
2734     print "Upgrade to $DBversion done (Moving allowed renewals from itemtypes to issuingrule)\n";
2735 }
2736
2737 $DBversion = '3.01.00.066';
2738 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2739     $dbh->do('ALTER TABLE issuingrules ADD COLUMN `reservesallowed` smallint(6) NOT NULL default "0" AFTER `renewalsallowed`;');
2740     
2741     my $maxreserves = C4::Context->preference('maxreserves');
2742     $sth = $dbh->prepare('UPDATE issuingrules SET reservesallowed = ?;');
2743     $sth->execute($maxreserves);
2744
2745     $dbh->do('DELETE FROM systempreferences WHERE variable = "maxreserves";');
2746
2747     $dbh->do("INSERT INTO systempreferences (variable,value, options, explanation, type) VALUES('ReservesControlBranch','PatronLibrary','ItemHomeLibrary|PatronLibrary','Branch checked for members reservations rights','Choice')");
2748
2749     SetVersion ($DBversion);
2750     print "Upgrade to $DBversion done (Moving max allowed reserves from system preference to issuingrule)\n";
2751 }
2752
2753 $DBversion = "3.01.00.067";
2754 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2755     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'batchmod', 'Perform batch modification of items')");
2756     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'batchdel', 'Perform batch deletion of items')");
2757     print "Upgrade to $DBversion done (added permissions for batch modification and deletion)\n";
2758     SetVersion ($DBversion);
2759 }
2760
2761 $DBversion = "3.01.00.068";
2762 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2763         $dbh->do("ALTER TABLE issuingrules ADD COLUMN `finedays` int(11) default NULL AFTER `fine` ");
2764         print "Upgrade done (Adding finedays in issuingrules table)\n";
2765     SetVersion ($DBversion);
2766 }
2767
2768
2769 $DBversion = "3.01.00.069";
2770 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2771         $dbh->do("INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('EnableOpacSearchHistory', '1', '', 'Enable or disable opac search history', 'YesNo')");
2772
2773         my $create = <<SEARCHHIST;
2774 CREATE TABLE IF NOT EXISTS `search_history` (
2775   `userid` int(11) NOT NULL,
2776   `sessionid` varchar(32) NOT NULL,
2777   `query_desc` varchar(255) NOT NULL,
2778   `query_cgi` varchar(255) NOT NULL,
2779   `total` int(11) NOT NULL,
2780   `time` timestamp NOT NULL default CURRENT_TIMESTAMP,
2781   KEY `userid` (`userid`),
2782   KEY `sessionid` (`sessionid`)
2783 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Opac search history results';
2784 SEARCHHIST
2785         $dbh->do($create);
2786
2787         print "Upgrade done (added OPAC search history preference and table)\n";
2788 }
2789
2790 $DBversion = "3.01.00.070";
2791 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2792         $dbh->do("ALTER TABLE authorised_values ADD COLUMN `lib_opac` VARCHAR(80) default NULL AFTER `lib`");
2793         print "Upgrade done (Added a lib_opac field in authorised_values table)\n";
2794 }
2795
2796 $DBversion = "3.01.00.071";
2797 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2798         $dbh->do("ALTER TABLE `subscription` ADD `enddate` date default NULL");
2799         $dbh->do("ALTER TABLE subscriptionhistory CHANGE enddate histenddate DATE default NULL");
2800         print "Upgrade to $DBversion done ( Adding enddate to subscription)\n";
2801 }
2802
2803 # Acquisitions update
2804
2805 $DBversion = "3.01.00.072";
2806 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2807     $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')");
2808     # create a new syspref for the 'Mr anonymous' patron
2809     $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,'')");
2810     # fill AnonymousPatron with AnonymousSuggestion value (copy)
2811     my $sth=$dbh->prepare("SELECT value FROM systempreferences WHERE variable='AnonSuggestions'");
2812     $sth->execute;
2813     my ($value) = $sth->fetchrow() || 0;
2814     $dbh->do("UPDATE systempreferences SET value='$value' WHERE variable='AnonymousPatron'");
2815     # set AnonymousSuggestion do YesNo
2816     # 1st, set the value (1/True if it had a borrowernumber)
2817     $dbh->do("UPDATE systempreferences SET value=1 WHERE variable='AnonSuggestions' AND value>0");
2818     # 2nd, change the type to Choice
2819     $dbh->do("UPDATE systempreferences SET type='YesNo' WHERE variable='AnonSuggestions'");
2820         # borrower reading record privacy : 0 : forever, 1 : laws, 2 : don't keep at all
2821     $dbh->do("ALTER TABLE `borrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
2822     print "Upgrade to $DBversion done (add new syspref and column in borrowers)\n";
2823     SetVersion ($DBversion);
2824 }
2825
2826 $DBversion = '3.01.00.073';
2827 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2828     $dbh->do('SET FOREIGN_KEY_CHECKS=0 ');
2829     $dbh->do(<<'END_SQL');
2830 CREATE TABLE IF NOT EXISTS `aqcontract` (
2831   `contractnumber` int(11) NOT NULL auto_increment,
2832   `contractstartdate` date default NULL,
2833   `contractenddate` date default NULL,
2834   `contractname` varchar(50) default NULL,
2835   `contractdescription` mediumtext,
2836   `booksellerid` int(11) not NULL,
2837     PRIMARY KEY  (`contractnumber`),
2838         CONSTRAINT `booksellerid_fk1` FOREIGN KEY (`booksellerid`)
2839         REFERENCES `aqbooksellers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
2840 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
2841 END_SQL
2842     $dbh->do('SET FOREIGN_KEY_CHECKS=1 ');
2843     print "Upgrade to $DBversion done (adding aqcontract table)\n";
2844     SetVersion ($DBversion);
2845 }
2846
2847 $DBversion = '3.01.00.074';
2848 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2849     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `basketname` varchar(50) default NULL AFTER `basketno`");
2850     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `note` mediumtext AFTER `basketname`");
2851     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `booksellernote` mediumtext AFTER `note`");
2852     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `contractnumber` int(11) AFTER `booksellernote`");
2853     $dbh->do("ALTER TABLE `aqbasket` ADD FOREIGN KEY (`contractnumber`) REFERENCES `aqcontract` (`contractnumber`)");
2854     print "Upgrade to $DBversion done (edit aqbasket table done)\n";
2855     SetVersion ($DBversion);
2856 }
2857
2858 $DBversion = '3.01.00.075';
2859 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2860     $dbh->do("ALTER TABLE `aqorders` ADD COLUMN `uncertainprice` tinyint(1)");
2861
2862     print "Upgrade to $DBversion done (adding uncertainprices)\n";
2863     SetVersion ($DBversion);
2864 }
2865
2866 $DBversion = '3.01.00.076';
2867 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2868     $dbh->do('SET FOREIGN_KEY_CHECKS=0 ');
2869     $dbh->do("CREATE TABLE IF NOT EXISTS `aqbasketgroups` (
2870                          `id` int(11) NOT NULL auto_increment,
2871                          `name` varchar(50) default NULL,
2872                          `closed` tinyint(1) default NULL,
2873                          `booksellerid` int(11) NOT NULL,
2874                          PRIMARY KEY (`id`),
2875                          KEY `booksellerid` (`booksellerid`),
2876                          CONSTRAINT `aqbasketgroups_ibfk_1` FOREIGN KEY (`booksellerid`) REFERENCES `aqbooksellers` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
2877                          ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
2878     $dbh->do("ALTER TABLE aqbasket ADD COLUMN `basketgroupid` int(11)");
2879     $dbh->do("ALTER TABLE aqbasket ADD FOREIGN KEY (`basketgroupid`) REFERENCES `aqbasketgroups` (`id`) ON UPDATE CASCADE ON DELETE SET NULL");
2880     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('pdfformat','pdfformat::layout2pages','Controls what script is used for printing (basketgroups)','','free')");
2881     $dbh->do('SET FOREIGN_KEY_CHECKS=1 ');
2882     print "Upgrade to $DBversion done (adding basketgroups)\n";
2883     SetVersion ($DBversion);
2884 }
2885 $DBversion = '3.01.00.077';
2886 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2887
2888     $dbh->do("SET FOREIGN_KEY_CHECKS=0 ");
2889     # create a mapping table holding the info we need to match orders to budgets
2890     $dbh->do('DROP TABLE IF EXISTS fundmapping');
2891     $dbh->do(
2892         q|CREATE TABLE fundmapping AS
2893         SELECT aqorderbreakdown.ordernumber, branchcode, bookfundid, budgetdate, entrydate
2894         FROM aqorderbreakdown JOIN aqorders ON aqorderbreakdown.ordernumber = aqorders.ordernumber|);
2895     # match the new type of the corresponding field
2896     $dbh->do('ALTER TABLE fundmapping modify column bookfundid varchar(30)');
2897     # System did not ensure budgetdate was valid historically
2898     $dbh->do(q|UPDATE fundmapping SET budgetdate = entrydate WHERE budgetdate = '0000-00-00' OR budgetdate IS NULL|);
2899     # We save the map in fundmapping in case you need later processing
2900     $dbh->do(q|ALTER TABLE fundmapping add column aqbudgetid integer|);
2901     # these can speed processing up
2902     $dbh->do(q|CREATE INDEX fundmaporder ON fundmapping (ordernumber)|);
2903     $dbh->do(q|CREATE INDEX fundmapid ON fundmapping (bookfundid)|);
2904
2905     $dbh->do("DROP TABLE IF EXISTS `aqbudgetperiods` ");
2906
2907     $dbh->do(qq|
2908                     CREATE TABLE `aqbudgetperiods` (
2909                     `budget_period_id` int(11) NOT NULL auto_increment,
2910                     `budget_period_startdate` date NOT NULL,
2911                     `budget_period_enddate` date NOT NULL,
2912                     `budget_period_active` tinyint(1) default '0',
2913                     `budget_period_description` mediumtext,
2914                     `budget_period_locked` tinyint(1) default NULL,
2915                     `sort1_authcat` varchar(10) default NULL,
2916                     `sort2_authcat` varchar(10) default NULL,
2917                     PRIMARY KEY  (`budget_period_id`)
2918                     ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 |);
2919
2920    $dbh->do(<<ADDPERIODS);
2921 INSERT INTO aqbudgetperiods (budget_period_startdate,budget_period_enddate,budget_period_active,budget_period_description,budget_period_locked)
2922 SELECT DISTINCT startdate, enddate, NOW() BETWEEN startdate and enddate, concat(startdate," ",enddate),NOT NOW() BETWEEN startdate AND enddate from aqbudget
2923 ADDPERIODS
2924 # SORRY , NO AQBUDGET/AQBOOKFUND -> AQBUDGETS IMPORT JUST YET,
2925 # BUT A NEW CLEAN AQBUDGETS TABLE CREATE FOR NOW..
2926 # DROP TABLE IF EXISTS `aqbudget`;
2927 #CREATE TABLE `aqbudget` (
2928 #  `bookfundid` varchar(10) NOT NULL default ',
2929 #    `startdate` date NOT NULL default 0,
2930 #         `enddate` date default NULL,
2931 #           `budgetamount` decimal(13,2) default NULL,
2932 #                 `aqbudgetid` tinyint(4) NOT NULL auto_increment,
2933 #                   `branchcode` varchar(10) default NULL,
2934     DropAllForeignKeys('aqbudget');
2935   #$dbh->do("drop table aqbudget;");
2936
2937
2938     my $maxbudgetid = $dbh->selectcol_arrayref(<<IDsBUDGET);
2939 SELECT MAX(aqbudgetid) from aqbudget
2940 IDsBUDGET
2941
2942 $$maxbudgetid[0] = 0 if !$$maxbudgetid[0];
2943
2944     $dbh->do(<<BUDGETAUTOINCREMENT);
2945 ALTER TABLE aqbudget AUTO_INCREMENT=$$maxbudgetid[0]
2946 BUDGETAUTOINCREMENT
2947     
2948     $dbh->do(<<BUDGETNAME);
2949 ALTER TABLE aqbudget RENAME `aqbudgets`
2950 BUDGETNAME
2951
2952     $dbh->do(<<BUDGETS);
2953 ALTER TABLE `aqbudgets`
2954    CHANGE  COLUMN aqbudgetid `budget_id` int(11) NOT NULL AUTO_INCREMENT,
2955    CHANGE  COLUMN branchcode `budget_branchcode` varchar(10) default NULL,
2956    CHANGE  COLUMN budgetamount `budget_amount` decimal(28,6) NOT NULL default '0.00',
2957    CHANGE  COLUMN bookfundid   `budget_code` varchar(30) default NULL,
2958    ADD     COLUMN `budget_parent_id` int(11) default NULL,
2959    ADD     COLUMN `budget_name` varchar(80) default NULL,
2960    ADD     COLUMN `budget_encumb` decimal(28,6) default '0.00',
2961    ADD     COLUMN `budget_expend` decimal(28,6) default '0.00',
2962    ADD     COLUMN `budget_notes` mediumtext,
2963    ADD     COLUMN `budget_description` mediumtext,
2964    ADD     COLUMN `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
2965    ADD     COLUMN `budget_amount_sublevel`  decimal(28,6) AFTER `budget_amount`,
2966    ADD     COLUMN `budget_period_id` int(11) default NULL,
2967    ADD     COLUMN `sort1_authcat` varchar(80) default NULL,
2968    ADD     COLUMN `sort2_authcat` varchar(80) default NULL,
2969    ADD     COLUMN `budget_owner_id` int(11) default NULL,
2970    ADD     COLUMN `budget_permission` int(1) default '0';
2971 BUDGETS
2972
2973     $dbh->do(<<BUDGETCONSTRAINTS);
2974 ALTER TABLE `aqbudgets`
2975    ADD CONSTRAINT `aqbudgets_ifbk_1` FOREIGN KEY (`budget_period_id`) REFERENCES `aqbudgetperiods` (`budget_period_id`) ON DELETE CASCADE ON UPDATE CASCADE
2976 BUDGETCONSTRAINTS
2977 #    $dbh->do(<<BUDGETPKDROP);
2978 #ALTER TABLE `aqbudgets`
2979 #   DROP PRIMARY KEY
2980 #BUDGETPKDROP
2981 #    $dbh->do(<<BUDGETPKADD);
2982 #ALTER TABLE `aqbudgets`
2983 #   ADD PRIMARY KEY budget_id
2984 #BUDGETPKADD
2985
2986
2987         my $query_period= $dbh->prepare(qq|SELECT budget_period_id from aqbudgetperiods where budget_period_startdate=? and budget_period_enddate=?|);
2988         my $query_bookfund= $dbh->prepare(qq|SELECT * from aqbookfund where bookfundid=?|);
2989         my $selectbudgets=$dbh->prepare(qq|SELECT * from aqbudgets|);
2990         my $updatebudgets=$dbh->prepare(qq|UPDATE aqbudgets SET budget_period_id= ? , budget_name=?, budget_branchcode=? where budget_id=?|);
2991         $selectbudgets->execute;
2992         while (my $databudget=$selectbudgets->fetchrow_hashref){
2993                 $query_period->execute ($$databudget{startdate},$$databudget{enddate});
2994                 my ($budgetperiodid)=$query_period->fetchrow;
2995                 $query_bookfund->execute ($$databudget{budget_code});
2996                 my $databf=$query_bookfund->fetchrow_hashref;
2997                 my $branchcode=$$databudget{budget_branchcode}||$$databf{branchcode};
2998                 $updatebudgets->execute($budgetperiodid,$$databf{bookfundname},$branchcode,$$databudget{budget_id});
2999         }
3000     $dbh->do(<<BUDGETDROPDATES);
3001 ALTER TABLE `aqbudgets`
3002    DROP startdate,
3003    DROP enddate
3004 BUDGETDROPDATES
3005
3006
3007     $dbh->do("DROP TABLE IF EXISTS `aqbudgets_planning` ");
3008     $dbh->do("CREATE TABLE  `aqbudgets_planning` (
3009                     `plan_id` int(11) NOT NULL auto_increment,
3010                     `budget_id` int(11) NOT NULL,
3011                     `budget_period_id` int(11) NOT NULL,
3012                     `estimated_amount` decimal(28,6) default NULL,
3013                     `authcat` varchar(30) NOT NULL,
3014                     `authvalue` varchar(30) NOT NULL,
3015                                         `display` tinyint(1) DEFAULT 1,
3016                         PRIMARY KEY  (`plan_id`),
3017                         CONSTRAINT `aqbudgets_planning_ifbk_1` FOREIGN KEY (`budget_id`) REFERENCES `aqbudgets` (`budget_id`) ON DELETE CASCADE ON UPDATE CASCADE
3018                         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
3019
3020     $dbh->do("ALTER TABLE `aqorders`
3021                     ADD COLUMN `budget_id` tinyint(4) NOT NULL,
3022                     ADD COLUMN `budgetgroup_id` int(11) NOT NULL,
3023                     ADD COLUMN  `sort1_authcat` varchar(10) default NULL,
3024                     ADD COLUMN  `sort2_authcat` varchar(10) default NULL" );
3025                 # We need to map the orders to the budgets
3026                 # For Historic reasons this is more complex than it should be on occasions
3027                 my $budg_arr = $dbh->selectall_arrayref(
3028                     q|SELECT aqbudgets.budget_id, aqbudgets.budget_code, aqbudgetperiods.budget_period_startdate,
3029                     aqbudgetperiods.budget_period_enddate
3030                     FROM aqbudgets JOIN aqbudgetperiods ON aqbudgets.budget_period_id = aqbudgetperiods.budget_period_id
3031                     ORDER BY budget_code, budget_period_startdate|, { Slice => {} });
3032                 # We arbitarily order on start date, this means if you have overlapping periods the order will be
3033                 # linked to the latest matching budget YMMV
3034                 my $b_sth = $dbh->prepare(
3035                     'UPDATE fundmapping set aqbudgetid = ? where bookfundid =? AND budgetdate >= ? AND budgetdate <= ?');
3036                 for my $b ( @{$budg_arr}) {
3037                     $b_sth->execute($b->{budget_id}, $b->{budget_code}, $b->{budget_period_startdate}, $b->{budget_period_enddate});
3038                 }
3039                 # move the budgetids to aqorders
3040                 $dbh->do(q|UPDATE aqorders, fundmapping SET aqorders.budget_id = fundmapping.aqbudgetid
3041                     WHERE aqorders.ordernumber = fundmapping.ordernumber AND fundmapping.aqbudgetid IS NOT NULL|);
3042                 # NB fundmapping is left as an accontants trail also if you have budgetids that werent set
3043                 # you can decide what to do with them
3044
3045      $dbh->do(
3046          q|UPDATE aqorders, aqbudgets SET aqorders.budgetgroup_id = aqbudgets.budget_period_id
3047          WHERE aqorders.budget_id = aqbudgets.budget_id|);
3048                 # cannot do until aqorderbreakdown removed
3049 #    $dbh->do("DROP TABLE aqbookfund ");
3050 #    $dbh->do("ALTER TABLE aqorders  ADD FOREIGN KEY (`budget_id`) REFERENCES `aqbudgets` (`budget_id`) ON UPDATE CASCADE  " ); ????
3051     $dbh->do("SET FOREIGN_KEY_CHECKS=1 ");
3052
3053     print "Upgrade to $DBversion done (Adding new aqbudgetperiods, aqbudgets and aqbudget_planning tables  )\n";
3054     SetVersion ($DBversion);
3055 }
3056
3057
3058
3059 $DBversion = '3.01.00.078';
3060 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3061     $dbh->do("ALTER TABLE aqbudgetperiods ADD COLUMN budget_period_total decimal(28,6)");
3062     print "Upgrade to $DBversion done (adds 'budget_period_total' column to aqbudgetperiods table)\n";
3063     SetVersion($DBversion);
3064 }
3065
3066
3067 $DBversion = '3.01.00.079';
3068 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3069     $dbh->do("ALTER TABLE currency ADD COLUMN active  tinyint(1)");
3070
3071     print "Upgrade to $DBversion done (adds 'active' column to currencies table)\n";
3072     SetVersion($DBversion);
3073 }
3074
3075 $DBversion = '3.01.00.080';
3076 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3077     $dbh->do(<<BUDG_PERM );
3078 INSERT INTO permissions (module_bit, code, description) VALUES
3079             (11, 'vendors_manage', 'Manage vendors'),
3080             (11, 'contracts_manage', 'Manage contracts'),
3081             (11, 'period_manage', 'Manage periods'),
3082             (11, 'budget_manage', 'Manage budgets'),
3083             (11, 'budget_modify', "Modify budget (can't create lines but can modify existing ones)"),
3084             (11, 'planning_manage', 'Manage budget plannings'),
3085             (11, 'order_manage', 'Manage orders & basket'),
3086             (11, 'group_manage', 'Manage orders & basketgroups'),
3087             (11, 'order_receive', 'Manage orders & basket'),
3088             (11, 'budget_add_del', "Add and delete budgets (but can't modify budgets)");
3089 BUDG_PERM
3090
3091     print "Upgrade to $DBversion done (adds permissions for the acquisitions module)\n";
3092     SetVersion($DBversion);
3093 }
3094
3095
3096 $DBversion = '3.01.00.081';
3097 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3098     $dbh->do("ALTER TABLE aqbooksellers ADD COLUMN `gstrate` decimal(6,4) default NULL");
3099     if (my $gist=C4::Context->preference("gist")){
3100                 my $sql=$dbh->prepare("UPDATE aqbooksellers set `gstrate`=? ");
3101         $sql->execute($gist) ;
3102         }
3103     print "Upgrade to $DBversion done (added per-supplier gstrate setting)\n";
3104     SetVersion($DBversion);
3105 }
3106
3107 $DBversion = "3.01.00.082";
3108 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3109     if (C4::Context->preference("opaclanguages") eq "fr") {
3110         $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')#);
3111     } else {
3112         $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')");
3113     }
3114     print "Upgrade to $DBversion done (adding ReservesNeedReturns systempref, in circulation)\n";
3115     SetVersion ($DBversion);
3116 }
3117
3118 $DBversion = "3.01.00.083";
3119 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3120     $dbh->do(qq|
3121  CREATE TABLE `aqorders_items` (
3122   `ordernumber` int(11) NOT NULL,
3123   `itemnumber` int(11) NOT NULL,
3124   `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
3125   PRIMARY KEY  (`itemnumber`),
3126   KEY `ordernumber` (`ordernumber`)
3127 ) ENGINE=InnoDB DEFAULT CHARSET=utf8   |
3128     );
3129
3130     $dbh->do(qq| DROP TABLE aqorderbreakdown |);
3131     $dbh->do('DROP TABLE aqbookfund');
3132     print "Upgrade to $DBversion done (New aqorders_items table for acqui)\n";
3133     SetVersion ($DBversion);
3134 }
3135
3136 $DBversion = "3.01.00.084";
3137 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3138     $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')  #);
3139
3140     print "Upgrade to $DBversion done (CurrencyFormat syspref added)\n";
3141     SetVersion ($DBversion);
3142 }
3143
3144 $DBversion = "3.01.00.085";
3145 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3146     $dbh->do("ALTER table aqorders drop column title");
3147     $dbh->do("ALTER TABLE `aqorders` CHANGE `budget_id` `budget_id` INT( 11 ) NOT NULL");
3148     print "Upgrade to $DBversion done update budget_id size that should not be a tinyint\n";
3149     SetVersion ($DBversion);
3150 }
3151
3152 $DBversion = "3.01.00.086";
3153 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3154     $dbh->do(<<SUGGESTIONS);
3155 ALTER table suggestions
3156     ADD budgetid INT(11),
3157     ADD branchcode VARCHAR(10) default NULL,
3158     ADD acceptedby INT(11) default NULL,
3159     ADD accepteddate date default NULL,
3160     ADD suggesteddate date default NULL,
3161     ADD manageddate date default NULL,
3162     ADD rejectedby INT(11) default NULL,
3163     ADD rejecteddate date default NULL,
3164     ADD collectiontitle text default NULL,
3165     ADD itemtype VARCHAR(30) default NULL
3166     ;
3167 SUGGESTIONS
3168     print "Upgrade to $DBversion done Suggestions";
3169     SetVersion ($DBversion);
3170 }
3171
3172 $DBversion = "3.01.00.087";
3173 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3174     $dbh->do("ALTER table aqbudgets drop column budget_amount_sublevel;");
3175     print "Upgrade to $DBversion done drop column budget_amount_sublevel from aqbudgets\n";
3176     SetVersion ($DBversion);
3177 }
3178
3179 $DBversion = "3.01.00.088";
3180 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3181     $dbh->do(  qq# INSERT INTO `systempreferences` VALUES ('intranetbookbag','1','','If ON, enables display of Cart feature in the intranet','YesNo')  #);
3182
3183     print "Upgrade to $DBversion done (intranetbookbag syspref added)\n";
3184     SetVersion ($DBversion);
3185 }
3186
3187 $DBversion = "3.01.00.090";
3188 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3189 $dbh->do("
3190        INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3191                 (16, 'execute_reports', 'Execute SQL reports'),
3192                 (16, 'create_reports', 'Create SQL Reports')
3193         ");
3194
3195     print "Upgrade to $DBversion done (granular permissions for guided reports added)\n";
3196     SetVersion ($DBversion);
3197 }
3198
3199 $DBversion = "3.01.00.091";
3200 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3201 $dbh->do("
3202         UPDATE `systempreferences` SET `options` = 'holdings|serialcollection|subscriptions'
3203         WHERE `systempreferences`.`variable` = 'opacSerialDefaultTab' LIMIT 1
3204         ");
3205
3206     print "Upgrade to $DBversion done (opac-detail default tag updated)\n";
3207     SetVersion ($DBversion);
3208 }
3209
3210 $DBversion = "3.01.00.092";
3211 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3212     if (C4::Context->preference("opaclanguages") =~ /fr/) {
3213         $dbh->do(qq{
3214 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');
3215         });
3216         }else{
3217         $dbh->do(qq{
3218 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');
3219         });
3220         }
3221     print "Upgrade to $DBversion done (Added RoutingListAddReserves syspref)\n";
3222     SetVersion ($DBversion);
3223 }
3224
3225 $DBversion = "3.01.00.093";
3226 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3227         $dbh->do(qq{
3228         ALTER TABLE biblioitems ADD INDEX issn_idx (issn);
3229         });
3230     print "Upgrade to $DBversion done (added index to ISSN)\n";
3231     SetVersion ($DBversion);
3232 }
3233
3234 $DBversion = "3.01.00.094";
3235 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3236         $dbh->do(qq{
3237         ALTER TABLE aqbasketgroups ADD deliveryplace VARCHAR(10) default NULL, ADD deliverycomment VARCHAR(255) default NULL;
3238         });
3239
3240     print "Upgrade to $DBversion done (adding deliveryplace deliverycomment to basketgroups)\n";
3241     SetVersion ($DBversion);
3242 }
3243
3244 $DBversion = "3.01.00.095";
3245 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3246         $dbh->do(qq{
3247         ALTER TABLE items ADD stocknumber VARCHAR(32) DEFAULT NULL COMMENT "stores the inventory number";
3248         });
3249         $dbh->do(qq{
3250         ALTER TABLE items ADD UNIQUE INDEX itemsstocknumberidx (stocknumber);
3251         });
3252         $dbh->do(qq{
3253         ALTER TABLE deleteditems ADD stocknumber VARCHAR(32) DEFAULT NULL COMMENT "stores the inventory number of deleted items";
3254         });
3255         $dbh->do(qq{
3256         ALTER TABLE deleteditems ADD UNIQUE INDEX deleteditemsstocknumberidx (stocknumber);
3257         });
3258         if (C4::Context->preference('marcflavour') eq 'UNIMARC'){
3259                 $dbh->do(qq{
3260         INSERT IGNORE INTO marc_subfield_structure (frameworkcode,tagfield, tagsubfield, tab, repeatable, mandatory,kohafield)
3261         SELECT DISTINCT (frameworkcode),995,"j",10,0,0,"items.stocknumber" from biblio_framework ;
3262                 });
3263                 #Previously, copynumber was used as stocknumber
3264                 $dbh->do(qq{
3265         UPDATE items set stocknumber=copynumber;
3266                 });
3267                 $dbh->do(qq{
3268         UPDATE items set copynumber=NULL;
3269                 });
3270         }
3271     print "Upgrade to $DBversion done (stocknumber field added)\n";
3272     SetVersion ($DBversion);
3273 }
3274
3275 $DBversion = "3.01.00.096";
3276 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3277     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OrderPdfTemplate','','Uploads a PDF template to use for printing baskets','NULL','Upload')");
3278     $dbh->do("UPDATE systempreferences SET variable='OrderPdfFormat' WHERE variable='pdfformat'");
3279     print "Upgrade to $DBversion done (PDF orders system preferences added and updated)\n";
3280     SetVersion ($DBversion);
3281 }
3282
3283 $DBversion = "3.01.00.097";
3284 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3285         $dbh->do(qq{
3286         ALTER TABLE aqbasketgroups ADD billingplace VARCHAR(10) NOT NULL AFTER deliverycomment;
3287         });
3288
3289     print "Upgrade to $DBversion done (Adding billingplace to aqbasketgroups)\n";
3290     SetVersion ($DBversion);
3291 }
3292
3293 $DBversion = "3.01.00.098";
3294 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3295         $dbh->do(qq{
3296         ALTER TABLE auth_subfield_structure MODIFY frameworkcode VARCHAR(10) NULL;
3297         });
3298
3299     print "Upgrade to $DBversion done (changing frameworkcode length in auth_subfield_structure)\n";
3300     SetVersion ($DBversion);
3301 }
3302
3303 $DBversion = "3.01.00.099";
3304 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3305         $dbh->do(qq{
3306                 INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3307                 (9, 'edit_catalogue', 'Edit catalogue'),
3308                 (9, 'fast_cataloging', 'Fast cataloging')
3309         });
3310
3311     print "Upgrade to $DBversion done (granular permissions for cataloging added)\n";
3312     SetVersion ($DBversion);
3313 }
3314
3315 $DBversion = "3.01.00.100";
3316 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3317         $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')");
3318         print "Upgrade done (added CAS authentication system preferences)\n";
3319     SetVersion ($DBversion);
3320 }
3321
3322 $DBversion = "3.01.00.101";
3323 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3324         $dbh->do(
3325         "INSERT INTO systempreferences 
3326            (variable, value, options, explanation, type)
3327          VALUES (
3328             'OverdueNoticeBcc', '', '', 
3329             'Email address to Bcc outgoing notices sent by email',
3330             'free')
3331          ");
3332         print "Upgrade to $DBversion done (added OverdueNoticeBcc system preferences)\n";
3333     SetVersion ($DBversion);
3334 }
3335 $DBversion = "3.01.00.102";
3336 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3337     $dbh->do(
3338     "UPDATE permissions set description = 'Edit catalog (Modify bibliographic/holdings data)' where module_bit = 9 and code = 'edit_catalogue'"
3339     );
3340         print "Upgrade done (fixed spelling error in edit_catalogue permission)\n";
3341     SetVersion ($DBversion);
3342 }
3343
3344 $DBversion = "3.01.00.103";
3345 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3346         $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES (13, 'moderate_tags', 'Moderate patron tags')");
3347         print "Upgrade done (adding patron permissions for tags tool)\n";
3348     SetVersion ($DBversion);
3349 }
3350
3351 $DBversion = "3.01.00.104";
3352 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3353
3354     my ($maninv_count, $borrnotes_count);
3355     eval { $maninv_count = $dbh->do("SELECT 1 FROM authorised_values WHERE category='MANUAL_INV'"); };
3356     if ($maninv_count == 0) {
3357         $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('MANUAL_INV','Copier Fees','.25')");
3358     }
3359     eval { $borrnotes_count = $dbh->do("SELECT 1 FROM authorised_values WHERE category='BOR_NOTES'"); };
3360     if ($borrnotes_count == 0) {
3361         $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('BOR_NOTES','ADDR','Address Notes')");
3362     }
3363     
3364     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('LOC','CART','Book Cart')");
3365     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('LOC','PROC','Processing Center')");
3366
3367         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";
3368         SetVersion ($DBversion);
3369 }
3370
3371
3372 $DBversion = "3.01.00.105";
3373 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3374     $dbh->do("
3375       CREATE TABLE `collections` (
3376         `colId` int(11) NOT NULL auto_increment,
3377         `colTitle` varchar(100) NOT NULL default '',
3378         `colDesc` text NOT NULL,
3379         `colBranchcode` varchar(4) default NULL COMMENT 'branchcode for branch where item should be held.',
3380         PRIMARY KEY  (`colId`)
3381       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3382     ");
3383        
3384     $dbh->do("
3385       CREATE TABLE `collections_tracking` (
3386         `ctId` int(11) NOT NULL auto_increment,
3387         `colId` int(11) NOT NULL default '0' COMMENT 'collections.colId',
3388         `itemnumber` int(11) NOT NULL default '0' COMMENT 'items.itemnumber',
3389         PRIMARY KEY  (`ctId`)
3390       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3391     ");
3392     $dbh->do("
3393         INSERT INTO permissions (module_bit, code, description) 
3394         VALUES ( 13, 'rotating_collections', 'Manage Rotating collections')" );
3395         print "Upgrade to $DBversion done (added collection and collection_tracking tables for rotating collections functionality)\n";
3396     SetVersion ($DBversion);
3397 }
3398 $DBversion = "3.01.00.106";
3399 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3400         $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' )");
3401         print "Upgrade done (added OpacAddMastheadLibraryPulldown system preferences)\n";
3402     SetVersion ($DBversion);
3403 }
3404
3405 $DBversion = '3.01.00.107';
3406 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3407     my $upgrade_script = C4::Context->config("intranetdir") . "/installer/data/mysql/patroncards_upgrade.pl";
3408     system("perl $upgrade_script");
3409     print "Upgrade to $DBversion done (Migrated labels and patroncards tables and data to new schema.)\n";
3410     SetVersion ($DBversion);
3411 }
3412
3413 $DBversion = '3.01.00.108';
3414 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3415         $dbh->do(qq{
3416         ALTER TABLE `export_format` ADD `csv_separator` VARCHAR( 2 ) NOT NULL AFTER `marcfields` ,
3417         ADD `field_separator` VARCHAR( 2 ) NOT NULL AFTER `csv_separator` ,
3418         ADD `subfield_separator` VARCHAR( 2 ) NOT NULL AFTER `field_separator` 
3419         });
3420         print "Upgrade done (added separators for csv export)\n";
3421     SetVersion ($DBversion);
3422 }
3423
3424 $DBversion = "3.01.00.109";
3425 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3426         $dbh->do(qq{
3427         ALTER TABLE `export_format` ADD `encoding` VARCHAR(255) NOT NULL AFTER `subfield_separator`
3428         });
3429         print "Upgrade done (added encoding for csv export)\n";
3430     SetVersion ($DBversion);
3431 }
3432
3433 $DBversion = '3.01.00.110';
3434 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3435     $dbh->do('ALTER TABLE `categories` ADD COLUMN `enrolmentperioddate` DATE NULL DEFAULT NULL AFTER `enrolmentperiod`');
3436     print "Upgrade done (Add enrolment period date support)\n";
3437     SetVersion ($DBversion);
3438 }
3439
3440 $DBversion = '3.01.00.111';
3441 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3442     print "Upgrade done (mark DBrev for 3.2-alpha release)\n";
3443     SetVersion ($DBversion);
3444 }
3445
3446 $DBversion = '3.01.00.112';
3447 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3448         $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');");
3449         print "Upgrade done ( added Show Spine Label Printer on Bib Items Details preferences )\n";
3450     SetVersion ($DBversion);
3451 }
3452
3453 $DBversion = '3.01.00.113';
3454 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3455     my $value = C4::Context->preference("XSLTResultsDisplay");
3456     $dbh->do(
3457         "INSERT INTO systempreferences (variable,value,type)
3458          VALUES('OPACXSLTResultsDisplay',?,'YesNo')", {}, $value ? 1 : 0);
3459     $value = C4::Context->preference("XSLTDetailsDisplay");
3460     $dbh->do(
3461         "INSERT INTO systempreferences (variable,value,type)
3462          VALUES('OPACXSLTDetailsDisplay',?,'YesNo')", {}, $value ? 1 : 0);
3463     print "Upgrade 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     ";
3464     SetVersion ($DBversion);
3465 }
3466
3467 $DBversion = '3.01.00.114';
3468 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3469     $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')");
3470     $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')");
3471     $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')");
3472         print "Upgrade to $DBversion done ( Added AutoSelfCheckAllowed, AutoSelfCheckID, and AutoShelfCheckPass system preference )\n";
3473     SetVersion ($DBversion);
3474 }
3475
3476 $DBversion = '3.01.00.115';
3477 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3478     $dbh->do('UPDATE aqorders SET quantityreceived = 0 WHERE quantityreceived IS NULL');
3479     $dbh->do('ALTER TABLE aqorders MODIFY COLUMN quantityreceived smallint(6) NOT NULL DEFAULT 0');
3480         print "Upgrade to $DBversion done ( Default aqorders.quantityreceived to 0 )\n";
3481     SetVersion ($DBversion);
3482 }
3483
3484 $DBversion = '3.01.00.116';
3485 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3486         if (C4::Context->preference('OrderPdfFormat') eq 'pdfformat::example'){
3487                 $dbh->do("UPDATE `systempreferences` set value='pdfformat::layout2pages' WHERE variable='OrderPdfFormat'");
3488         }
3489         print "Upgrade done ( corrected default OrderPdfFormat value if still set wrong )\n";
3490     SetVersion ($DBversion);
3491 }
3492
3493 $DBversion = '3.01.00.117';
3494 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3495     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'por' WHERE rfc4646_subtag='pt' ");
3496     print "Upgrade to $DBversion done (corrected ISO 639-2 language code for Portuguese)\n";
3497     SetVersion ($DBversion);
3498 }
3499
3500 $DBversion = '3.01.00.118';
3501 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3502     my ($count) = $dbh->selectrow_array("SELECT count(*) FROM information_schema.columns
3503                                          WHERE table_name = 'aqbudgets_planning'
3504                                          AND column_name = 'display'");
3505     if ($count < 1) {
3506         $dbh->do("ALTER TABLE aqbudgets_planning ADD COLUMN display tinyint(1) DEFAULT 1");
3507     }
3508     print "Upgrade to $DBversion done (bug 4203: add display column to aqbudgets_planning if missing)\n";
3509     SetVersion ($DBversion);
3510 }
3511
3512 $DBversion = '3.01.00.119';
3513 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3514     eval{require Locale::Currency::Format};
3515     if (!$@) {
3516         print "Upgrade to $DBversion done (Locale::Currency::Format installed.)\n";
3517         SetVersion ($DBversion);
3518     }
3519     else {
3520         print "Upgrade to $DBversion done.\n";
3521         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";
3522         SetVersion ($DBversion);
3523     }
3524 }
3525
3526 $DBversion = '3.01.00.120';
3527 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3528     $dbh->do(q{
3529 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');
3530 });
3531     print "Upgrade to $DBversion done (bug 1080: add soundon system preference for circulation sounds)\n";
3532     SetVersion ($DBversion);
3533 }
3534
3535 $DBversion = '3.01.00.121';
3536 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3537     $dbh->do("ALTER TABLE `reserves` ADD `expirationdate` DATE DEFAULT NULL");
3538     $dbh->do("ALTER TABLE `reserves` ADD `lowestPriority` tinyint(1) NOT NULL");
3539     $dbh->do("ALTER TABLE `old_reserves` ADD `expirationdate` DATE DEFAULT NULL");
3540     $dbh->do("ALTER TABLE `old_reserves` ADD `lowestPriority` tinyint(1) NOT NULL");
3541     print "Upgrade to $DBversion done ( Added Additional Fields to Reserves tables )\n";
3542     SetVersion ($DBversion);
3543 }
3544
3545 $DBversion = '3.01.00.122';
3546 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3547     $dbh->do(q{
3548       INSERT INTO systempreferences (variable,value,explanation,options,type)
3549       VALUES ('OAI-PMH:ConfFile', '', 'If empty, Koha OAI Server operates in normal mode, otherwise it operates in extended mode.','','File');
3550 });
3551     print "Upgrade to $DBversion done. — Add a new system preference OAI-PMF:ConfFile\n";
3552     SetVersion ($DBversion);
3553 }
3554
3555 $DBversion = "3.01.00.123";
3556 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3557     $dbh->do("INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3558         (6, 'place_holds', 'Place holds for patrons')");
3559     $dbh->do("INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3560         (6, 'modify_holds_priority', 'Modify holds priority')");
3561     $dbh->do("UPDATE `userflags` SET `flagdesc` = 'Place and modify holds for patrons' WHERE `flag` = 'reserveforothers'");
3562     print "Upgrade to $DBversion done (Add granular permission for holds modification and update description of reserveforothers permission)\n";
3563     SetVersion ($DBversion);
3564 }
3565
3566 $DBversion = '3.01.00.124';
3567 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3568     $dbh->do("
3569         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>>).');
3570     ");
3571     print "Upgrade to $DBversion done (bug 3242: add HOLDPLACED letter template, which is used when emailLibrarianWhenHoldIsPlaced is enabled)\n";
3572     SetVersion ($DBversion);
3573 }
3574
3575 $DBversion = '3.01.00.125';
3576 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3577     $dbh->do("
3578         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' );
3579     ");
3580     $dbh->do("
3581         INSERT INTO message_transport_types (message_transport_type) values ('print');
3582     ");
3583     print "Upgrade to $DBversion done (bug 3482: Printable hold and overdue notices)\n";
3584     SetVersion ($DBversion);
3585 }
3586
3587 $DBversion = "3.01.00.126";
3588 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3589         $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')");
3590         $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')");
3591         
3592     print "Upgrade to $DBversion done (Adding ILS-DI updates and ILS-DI:AuthorizedIPs)\n";
3593     SetVersion ($DBversion);
3594 }
3595
3596 $DBversion = '3.01.00.127';
3597 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3598     $dbh->do("ALTER TABLE messages CHANGE branchcode branchcode varchar(10);");
3599     print "Upgrade to $DBversion done (bug 4190: messages in patron account did not work with branchcodes > 4)\n";
3600     SetVersion ($DBversion);
3601 }
3602
3603 $DBversion = '3.01.00.128';
3604 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3605     $dbh->do('CREATE INDEX budget_id ON aqorders (budget_id );');
3606     print "Upgrade to $DBversion done (bug 4331: index orders by budget_id)\n";
3607     SetVersion ($DBversion);
3608 }
3609
3610 $DBversion = "3.01.00.129";
3611 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3612         $dbh->do("UPDATE `permissions` SET `code` = 'items_batchdel' WHERE `permissions`.`module_bit` =13 AND `permissions`.`code` = 'batchdel' LIMIT 1 ;");
3613         $dbh->do("UPDATE `permissions` SET `code` = 'items_batchmod' WHERE `permissions`.`module_bit` =13 AND `permissions`.`code` = 'batchmod' LIMIT 1 ;");
3614         print "Upgrade done (Change permissions names for item batch modification / deletion)\n";
3615
3616     SetVersion ($DBversion);
3617 }
3618
3619 $DBversion = "3.01.00.130";
3620 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3621     $dbh->do("UPDATE reserves SET expirationdate = NULL WHERE expirationdate = '0000-00-00'");
3622     print "Upgrade done (change reserves.expirationdate values of 0000-00-00 to NULL (bug 1532)"; 
3623     SetVersion ($DBversion);
3624 }
3625
3626 $DBversion = "3.01.00.131";
3627 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3628         $dbh->do(q{
3629 INSERT IGNORE INTO message_transport_types (message_transport_type) VALUES ('print'),('feed');
3630     });
3631     print "Upgrade to $DBversion done (adding print and feed message transport types)\n";
3632     SetVersion ($DBversion);
3633 }
3634
3635 $DBversion = "3.01.00.132";
3636 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3637         $dbh->do(q{
3638     ALTER TABLE language_descriptions ADD INDEX subtag_type_lang (subtag, type, lang);
3639     });
3640     print "Upgrade to $DBversion done (Adding index to language_descriptions table)\n";
3641     SetVersion ($DBversion);
3642 }
3643
3644 $DBversion = '3.01.00.133';
3645 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3646     $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')");
3647     print "Upgrade to $DBversion done (bug 4405: added OverduesBlockCirc syspref to control whether circulation is blocked if a borrower has overdues)\n";
3648     SetVersion ($DBversion);
3649 }
3650
3651 $DBversion = '3.01.00.134';
3652 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3653     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('DisplayMultiPlaceHold','1','Display the ability to place multiple holds or not','','YesNo')");
3654     print "Upgrade to $DBversion done adding syspref DisplayMultiPlaceHold to control whether multiple holds can be placed from the search results page";
3655     SetVersion ($DBversion);
3656 }
3657
3658 $DBversion = '3.01.00.135';
3659 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3660     $dbh->do("
3661         INSERT INTO `letter` (module, code, name, title, content) VALUES
3662 ('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')
3663 ");
3664     print "Upgrade to $DBversion done (bug 4377: added HOLD_PRINT message template)";
3665     SetVersion ($DBversion);
3666 }
3667
3668 $DBversion = '3.01.00.136';
3669 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3670     $dbh->do(qq{
3671 INSERT INTO permissions (module_bit, code, description) VALUES
3672    ( 9, 'edit_items', 'Edit Items');});
3673     print "Upgrade to $DBversion done Adding a new permission to edit items";
3674     SetVersion ($DBversion);
3675 }
3676
3677 $DBversion = "3.01.00.137";
3678 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3679         $dbh->do("
3680           INSERT INTO permissions (module_bit, code, description) VALUES
3681           (15, 'check_expiration', 'Check the expiration of a serial'),
3682           (15, 'claim_serials', 'Claim missing serials'),
3683           (15, 'create_subscription', 'Create a new subscription'),
3684           (15, 'delete_subscription', 'Delete an existing subscription'),
3685           (15, 'edit_subscription', 'Edit an existing subscription'),
3686           (15, 'receive_serials', 'Serials receiving'),
3687           (15, 'renew_subscription', 'Renew a subscription'),
3688           (15, 'routing', 'Routing');
3689                  ");
3690     print "Upgrade to $DBversion done (adding granular permissions for serials)";
3691     SetVersion ($DBversion);
3692 }
3693
3694 $DBversion = "3.01.00.138";
3695 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3696     $dbh->do("DELETE FROM systempreferences WHERE variable = 'GranularPermissions'");
3697     print "Upgrade to $DBversion done (bug 4896: removing GranularPermissions syspref; use of granular permissions is now the default)";
3698     SetVersion ($DBversion);
3699 }
3700
3701 $DBversion = '3.01.00.139';
3702 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3703     $dbh->do("ALTER TABLE message_attributes CHANGE message_name message_name varchar(40);");
3704     print "Upgrade to $DBversion done (bug 3682: change message_name from varchar(20) to varchar(40))\n";
3705     SetVersion ($DBversion);
3706 }
3707
3708 $DBversion = '3.01.00.140';
3709 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3710     $dbh->do("UPDATE systempreferences SET value = '0' WHERE variable = 'TagsModeration' AND value is NULL");
3711     print "Upgrade to $DBversion done (bug 4312 TagsModeration changed from NULL to 0)\n";
3712     SetVersion ($DBversion);
3713 }
3714
3715 $DBversion = '3.01.00.141';
3716 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3717     $dbh->do(qq{DELETE FROM message_attributes WHERE message_attribute_id=3;});
3718     $dbh->do(qq{DELETE FROM letter WHERE code='EVENT' AND title='Upcoming Library Event';});
3719     print "Upgrade to $DBversion done Remove upcoming events messaging option (bug 2434)";
3720     SetVersion ($DBversion);
3721 }
3722
3723 $DBversion = '3.01.00.142';
3724 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3725     $dbh->do(qq{DELETE FROM message_transports WHERE message_attribute_id=3;});
3726     print "Upgrade to $DBversion done Remove upcoming events messaging option part 2 (bug 2434)";
3727     SetVersion ($DBversion);
3728 }
3729
3730 $DBversion = '3.01.00.143';
3731 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3732     $dbh->do(qq{CREATE INDEX auth_value_idx ON authorised_values (authorised_value)});
3733     $dbh->do(qq{CREATE INDEX auth_val_cat_idx ON borrower_attribute_types (authorised_value_category)});
3734     print "Create index on authorised_values and borrower_attribute_types (bug 4139)";
3735     SetVersion ($DBversion);
3736 }
3737
3738 $DBversion = '3.01.00.144';
3739 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3740     $dbh->do(qq{UPDATE systempreferences SET value='normal' where value='default' and variable='IntranetBiblioDefaultView'});
3741     print "Update the 'default' to 'normal' for the IntranetBiblioDefaultView syspref (bug 5007)";
3742     SetVersion ($DBversion);
3743 }
3744
3745 $DBversion = "3.01.00.145";
3746 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3747     $dbh->do("ALTER TABLE borrowers ADD KEY `guarantorid` (guarantorid);");
3748     print "Upgrade to $DBversion done (Add index on guarantorid)\n";
3749     SetVersion ($DBversion);
3750 }
3751
3752 $DBversion = '3.01.00.999';
3753 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3754     print "Upgrade to $DBversion done (3.2.0 release candidate)\n";
3755     SetVersion ($DBversion);
3756 }
3757
3758 $DBversion = "3.02.00.000";
3759 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3760     my $value = $dbh->selectrow_array("SELECT value FROM systempreferences WHERE variable = 'HomeOrHoldingBranch'");
3761     $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');");
3762     print "Upgrade to $DBversion done (Add HomeOrHoldingBranchReturn system preference)\n";
3763     SetVersion ($DBversion);
3764 }
3765
3766 $DBversion = "3.02.00.001";
3767 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3768     $dbh->do(q{DELETE FROM systempreferences WHERE variable IN (
3769                 'holdCancelLength',
3770                 'PINESISBN',
3771                 'sortbynonfiling',
3772                 'TemplateEncoding',
3773                 'OPACSubscriptionDisplay',
3774                 'OPACDisplayExtendedSubInfo',
3775                 'OAI-PMH:Set',
3776                 'OAI-PMH:Subset',
3777                 'libraryAddress',
3778                 'kohaspsuggest',
3779                 'OrderPdfTemplate',
3780                 'marc',
3781                 'acquisitions',
3782                 'MIME')
3783                }
3784     );
3785     print "Upgrade to $DBversion done (bug 3756: remove disused system preferences)\n";
3786     SetVersion ($DBversion);
3787 }
3788
3789 $DBversion = "3.02.00.002";
3790 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3791     $dbh->do(q{DELETE FROM systempreferences WHERE variable = 'OpacPrivacy'});
3792     print "Upgrade to $DBversion done (bug 3881: remove unused OpacPrivacy system preference)\n";
3793     SetVersion ($DBversion);
3794 }
3795
3796 $DBversion = "3.02.00.003";
3797 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3798     $dbh->do(q{UPDATE systempreferences SET variable = 'ILS-DI:AuthorizedIPs' WHERE variable = 'ILS-DI:Authorized_IPs'});
3799     print "Upgrade to $DBversion done (correct ILS-DI:AuthorizedIPs)\n";
3800     SetVersion ($DBversion);
3801 }
3802
3803 $DBversion = "3.02.00.004";
3804 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3805     print "Upgrade to $DBversion done (3.2.0 general release)\n";
3806     SetVersion ($DBversion);
3807 }
3808
3809 $DBversion = "3.03.00.001";
3810 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3811     $dbh->do("DELETE FROM subscriptionroutinglist WHERE borrowernumber IS NULL;");
3812     $dbh->do("ALTER TABLE subscriptionroutinglist MODIFY COLUMN `borrowernumber` int(11) NOT NULL;");
3813     $dbh->do("DELETE FROM subscriptionroutinglist WHERE subscriptionid IS NULL;");
3814     $dbh->do("ALTER TABLE subscriptionroutinglist MODIFY COLUMN `subscriptionid` int(11) NOT NULL;");
3815     $dbh->do("CREATE TEMPORARY TABLE del_subscriptionroutinglist 
3816               SELECT s1.routingid FROM subscriptionroutinglist s1
3817               WHERE EXISTS (SELECT * FROM subscriptionroutinglist s2
3818                             WHERE s2.borrowernumber = s1.borrowernumber
3819                             AND   s2.subscriptionid = s1.subscriptionid 
3820                             AND   s2.routingid < s1.routingid);");
3821     $dbh->do("DELETE FROM subscriptionroutinglist
3822               WHERE routingid IN (SELECT routingid FROM del_subscriptionroutinglist);");
3823     $dbh->do("ALTER TABLE subscriptionroutinglist ADD UNIQUE (subscriptionid, borrowernumber);");
3824     $dbh->do("ALTER TABLE subscriptionroutinglist 
3825                 ADD CONSTRAINT `subscriptionroutinglist_ibfk_1` FOREIGN KEY (`borrowernumber`) 
3826                 REFERENCES `borrowers` (`borrowernumber`)
3827                 ON DELETE CASCADE ON UPDATE CASCADE");
3828     $dbh->do("ALTER TABLE subscriptionroutinglist 
3829                 ADD CONSTRAINT `subscriptionroutinglist_ibfk_2` FOREIGN KEY (`subscriptionid`) 
3830                 REFERENCES `subscription` (`subscriptionid`)
3831                 ON DELETE CASCADE ON UPDATE CASCADE");
3832     print "Upgrade to $DBversion done (Make subscriptionroutinglist more strict)\n";
3833     SetVersion ($DBversion);
3834 }
3835
3836 $DBversion = '3.03.00.002';
3837 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3838     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='arm' WHERE rfc4646_subtag='hy';");
3839     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='eng' WHERE rfc4646_subtag='en';");
3840     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'fi','fin');");
3841     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='fre' WHERE rfc4646_subtag='fr';");
3842     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'lo','lao');");
3843     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='ita' WHERE rfc4646_subtag='it';");
3844     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'sr','srp');");
3845     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'tet','tet');");
3846     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'ur','urd');");
3847
3848     print "Upgrade to $DBversion done (Correct language mappings)\n";
3849     SetVersion ($DBversion);
3850 }
3851
3852 $DBversion = '3.03.00.003';
3853 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3854     $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');");
3855     print "Upgrade to $DBversion done (Add UseTablesortForCirc syspref)\n";
3856     SetVersion ($DBversion);
3857 }
3858
3859 $DBversion = '3.03.00.004';
3860 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3861     my $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'ACCEPTED');
3862     $dbh->do(q/
3863 INSERT INTO `letter`
3864 (module, code, name, title, content)
3865 VALUES
3866 ('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>>')
3867 /) unless $count > 0;
3868     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'AVAILABLE');
3869     $dbh->do(q/
3870 INSERT INTO `letter`
3871 (module, code, name, title, content)
3872 VALUES
3873 ('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>>')
3874 /) unless $count > 0;
3875     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'ORDERED');
3876     $dbh->do(q/
3877 INSERT INTO `letter`
3878 (module, code, name, title, content)
3879 VALUES
3880 ('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>>')
3881 /) unless $count > 0;
3882     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'REJECTED');
3883     $dbh->do(q/
3884 INSERT INTO `letter`
3885 (module, code, name, title, content)
3886 VALUES
3887 ('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>>')
3888 /) unless $count > 0;
3889     print "Upgrade to $DBversion done (bug 5127: add default templates for suggestion status change notifications)\n";
3890     SetVersion ($DBversion);
3891 };
3892
3893 $DBversion = '3.03.00.005';
3894 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3895     $dbh->do("update `systempreferences` set options='whitespace|T-prefix|cuecat|libsuite8' where variable='itemBarcodeInputFilter'");
3896     print "Upgrade to $DBversion done (Add itemBarcodeInputFilter choice libsuite8)\n";
3897 }
3898
3899 $DBversion = '3.03.00.006';
3900 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3901     $dbh->do("ALTER TABLE deletedborrowers ADD `privacy` int(11) AFTER smsalertnumber;");
3902     $dbh->do("ALTER TABLE deletedborrowers CHANGE `cardnumber` `cardnumber` varchar(16);");
3903     print "Upgrade to $DBversion done (Fix differences between borrowers and deletedborrowers)\n";
3904     SetVersion ($DBversion);
3905 }
3906
3907 $DBversion = '3.03.00.007';
3908 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3909     $dbh->do("ALTER table suggestions ADD quantity SMALLINT(6) default NULL,
3910                 ADD currency VARCHAR(3) default NULL,
3911                 ADD price DECIMAL(28,6) default NULL,
3912                 ADD total DECIMAL(28,6) default NULL;
3913                 ");
3914     print "Upgrade to $DBversion done (Added acq related columns to suggestions)\n";
3915     SetVersion ($DBversion);
3916 }
3917
3918 $DBversion = '3.03.00.008';
3919 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3920     $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')");
3921     print "Upgrade to $DBversion done adding syspref OPACNoResultsFound to control what displays when no results are found for a search in the OPAC.";
3922     SetVersion ($DBversion);
3923 }
3924
3925 $DBversion = '3.03.00.009';
3926 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3927     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('IntranetUserCSS','','Add CSS to be included in the Intranet',NULL,'free')");
3928     print "Upgrade to $DBversion done (Add IntranetUserCSS syspref)\n";
3929     SetVersion ($DBversion);
3930 }
3931
3932 $DBversion = "3.03.00.010";
3933 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3934     $dbh->do("UPDATE `marc_subfield_structure` SET liblibrarian = 'Distance from earth' WHERE liblibrarian = 'Distrance from earth' AND tagfield = '034' AND tagsubfield = 'r';");
3935     $dbh->do("UPDATE `marc_subfield_structure` SET libopac = 'Distance from earth' WHERE libopac = 'Distrance from earth' AND tagfield = '034' AND tagsubfield = 'r';");
3936     print "Upgrade to $DBversion done (Fix misspelled 034r subfield in MARC21 Frameworks)\n";
3937     SetVersion ($DBversion);
3938 }
3939
3940 $DBversion = "3.03.00.011";
3941 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3942     $dbh->do("UPDATE aqbooksellers SET gstrate=NULL WHERE gstrate=0.0");
3943     print "Upgrade to $DBversion done (Bug 5186: allow GST rate to be set to 0)\n";
3944     SetVersion ($DBversion);
3945 }
3946
3947 $DBversion = "3.03.00.012";
3948 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3949    $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')");
3950    print "Upgrade to $DBversion done (Bug 2142: maxItemsInSearchResults syspref resurrected)\n";
3951    SetVersion ($DBversion);
3952 }
3953
3954 $DBversion = "3.03.00.013";
3955 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3956     $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')");
3957     print "Upgrade to $DBversion done (added 'OpacPublic' syspref)\n";
3958    SetVersion ($DBversion);
3959 }
3960
3961 $DBversion = "3.03.00.014";
3962 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3963     $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')");
3964     $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')");
3965     $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')");
3966     print "Upgrade to $DBversion done (Add flexible shelf browser constraints)\n";
3967     SetVersion ($DBversion);
3968 }
3969
3970 $DBversion = "3.03.00.015";
3971 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3972     my $sth = $dbh->prepare("INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`, 
3973                              `tab`, `authorised_value`, `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`)
3974                              VALUES ( ?, '9', '9 (RLIN)', '9 (RLIN)', 0, 0, '', 6, '', '', '', 0, -5, '', '', '', NULL)");
3975     $sth->execute('648');
3976     $sth->execute('654');
3977     $sth->execute('655');
3978     $sth->execute('656');
3979     $sth->execute('657');
3980     $sth->execute('658');
3981     $sth->execute('662');
3982     $sth->finish;
3983     print "Upgrade to $DBversion done (Bug 5619: Add subfield 9 to marc21 648,654,655,656,657,658,662)\n";
3984     SetVersion ($DBversion);
3985 }
3986
3987 $DBversion = '3.03.00.016';
3988 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3989     # reimplement OpacPrivacy system preference
3990     $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')");
3991     $dbh->do("ALTER TABLE `borrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
3992     $dbh->do("ALTER TABLE `deletedborrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
3993     print "Upgrade to $DBversion done (OpacPrivacy reimplementation)\n";
3994     SetVersion($DBversion);
3995 };
3996
3997 $DBversion = '3.03.00.017';
3998 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3999     $dbh->do("ALTER TABLE  `currency` CHANGE `rate` `rate` FLOAT( 15, 5 ) NULL DEFAULT NULL;");
4000     print "Upgrade to $DBversion done (Enable currency rates >= 100)\n";
4001     SetVersion ($DBversion);
4002 }
4003
4004 $DBversion = '3.03.00.018';
4005 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4006     $dbh->do( q|update language_descriptions set description = 'Nederlands' where lang = 'nl' and subtag = 'nl'|);
4007     $dbh->do( q|update language_descriptions set description = 'Dansk' where lang = 'da' and subtag = 'da'|);
4008     print "Upgrade to $DBversion done (Correct language descriptions)\n";
4009     SetVersion ($DBversion);
4010 }
4011
4012 $DBversion = '3.03.00.019';
4013 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4014     # Fix bokmål
4015     $dbh->do("UPDATE language_subtag_registry SET description = 'Norwegian bokm&#229;l' WHERE subtag = 'nb';");
4016     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'nb','nob');");
4017     $dbh->do("UPDATE language_descriptions SET description = 'Norsk bokm&#229;l' WHERE subtag = 'nb' AND lang = 'nb';");
4018     $dbh->do("UPDATE language_descriptions SET description = 'Norwegian bokm&#229;l' WHERE subtag = 'nb' AND lang = 'en';");
4019     $dbh->do("UPDATE language_descriptions SET description = 'Norvégien bokm&#229;l' WHERE subtag = 'nb' AND lang = 'fr';");
4020     # Add nynorsk
4021     $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'nn', 'language', 'Norwegian nynorsk','2011-02-14' )");
4022     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'nn','nno')");
4023     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'nb', 'Norsk nynorsk')");
4024     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'nn', 'Norsk nynorsk')");
4025     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'en', 'Norwegian nynorsk')");
4026     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'fr', 'Norvégien nynorsk')");
4027     print "Upgrade to $DBversion done (Correct language descriptions for Norwegian)\n";
4028     SetVersion ($DBversion);
4029 }
4030
4031 $DBversion = '3.03.00.020';
4032 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4033     $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')");
4034     $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')");
4035     print "Upgrade to $DBversion done (Bug 5811: Add sysprefs controlling overriding fines)\n";
4036     SetVersion($DBversion);
4037 };
4038
4039 $DBversion = '3.03.00.021';
4040 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4041     $dbh->do("ALTER TABLE items MODIFY enumchron TEXT");
4042     $dbh->do("ALTER TABLE deleteditems MODIFY enumchron TEXT");
4043     print "Upgrade to $DBversion done (bug 5642: longer serial enumeration)\n";
4044     SetVersion ($DBversion);
4045 }
4046
4047 $DBversion = '3.03.00.022';
4048 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4049     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('AuthoritiesLog','0','If ON, log edit/create/delete actions on authorities.','','YesNo');");
4050     print "Upgrade to $DBversion done (Add AuthoritiesLog syspref)\n";
4051     SetVersion ($DBversion);
4052 }
4053
4054 # due to a mismatch in kohastructure.sql some koha will have missing columns in aqbasketgroup
4055 # this attempts to fix that
4056 $DBversion = '3.03.00.023';
4057 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4058     my $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'billingplace'");
4059     $sth->execute;
4060     $dbh->do("ALTER TABLE aqbasketgroups ADD billingplace VARCHAR(10)") if ! $sth->fetchrow_hashref;
4061     $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'deliveryplace'");
4062     $sth->execute;
4063     $dbh->do("ALTER TABLE aqbasketgroups ADD deliveryplace VARCHAR(10)") if ! $sth->fetchrow_hashref;
4064     $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'deliverycomment'");
4065     $sth->execute;
4066     $dbh->do("ALTER TABLE aqbasketgroups ADD deliverycomment VARCHAR(255)") if ! $sth->fetchrow_hashref;
4067     print "Upgrade to $DBversion done (Reconcile aqbasketgroups)\n";
4068     SetVersion ($DBversion);
4069 }
4070
4071 $DBversion = '3.03.00.024';
4072 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4073     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('TraceCompleteSubfields','0','Force subject tracings to only match complete subfields.','0','YesNo')");
4074     $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')");
4075     print "Upgrade to $DBversion done (Add syspref to force whole-subfield matching on subject tracings)\n";
4076     SetVersion($DBversion);
4077 };
4078
4079 $DBversion = "3.03.00.XXX";
4080 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4081     $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')");
4082     print "Upgrade to $DBversion done (Add syspref to control if user can choose pickup branch for holds)\n";
4083     SetVersion ($DBversion);
4084 }
4085
4086 =head1 FUNCTIONS
4087
4088 =head2 DropAllForeignKeys($table)
4089
4090 Drop all foreign keys of the table $table
4091
4092 =cut
4093
4094
4095 sub DropAllForeignKeys {
4096     my ($table) = @_;
4097     # get the table description
4098     my $sth = $dbh->prepare("SHOW CREATE TABLE $table");
4099     $sth->execute;
4100     my $vsc_structure = $sth->fetchrow;
4101     # split on CONSTRAINT keyword
4102     my @fks = split /CONSTRAINT /,$vsc_structure;
4103     # parse each entry
4104     foreach (@fks) {
4105         # isolate what is before FOREIGN KEY, if there is something, it's a foreign key to drop
4106         $_ = /(.*) FOREIGN KEY.*/;
4107         my $id = $1;
4108         if ($id) {
4109             # we have found 1 foreign, drop it
4110             $dbh->do("ALTER TABLE $table DROP FOREIGN KEY $id");
4111             $id="";
4112         }
4113     }
4114 }
4115
4116
4117 =head2 TransformToNum
4118
4119 Transform the Koha version from a 4 parts string
4120 to a number, with just 1 .
4121
4122 =cut
4123
4124 sub TransformToNum {
4125     my $version = shift;
4126     # remove the 3 last . to have a Perl number
4127     $version =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
4128     return $version;
4129 }
4130
4131 =head2 SetVersion
4132
4133 set the DBversion in the systempreferences
4134
4135 =cut
4136
4137 sub SetVersion {
4138     my $kohaversion = TransformToNum(shift);
4139     if (C4::Context->preference('Version')) {
4140       my $finish=$dbh->prepare("UPDATE systempreferences SET value=? WHERE variable='Version'");
4141       $finish->execute($kohaversion);
4142     } else {
4143       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')");
4144       $finish->execute($kohaversion);
4145     }
4146 }
4147 exit;
4148