Fixing record.abs for authorities and MARC21
[koha.git] / C4 / Context.pm
blobdcf1f0dd4cfef264f3d7edc3a8f0e9aff79daef5
1 package C4::Context;
2 # Copyright 2002 Katipo Communications
4 # This file is part of Koha.
6 # Koha is free software; you can redistribute it and/or modify it under the
7 # terms of the GNU General Public License as published by the Free Software
8 # Foundation; either version 2 of the License, or (at your option) any later
9 # version.
11 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
12 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License along with
16 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
17 # Suite 330, Boston, MA 02111-1307 USA
19 use strict;
20 use warnings;
21 use vars qw($VERSION $AUTOLOAD $context @context_stack);
23 BEGIN {
24 if ($ENV{'HTTP_USER_AGENT'}) {
25 require CGI::Carp;
26 # FIXME for future reference, CGI::Carp doc says
27 # "Note that fatalsToBrowser does not work with mod_perl version 2.0 and higher."
28 import CGI::Carp qw(fatalsToBrowser);
29 sub handle_errors {
30 my $msg = shift;
31 my $debug_level;
32 eval {C4::Context->dbh();};
33 if ($@){
34 $debug_level = 1;
36 else {
37 $debug_level = C4::Context->preference("DebugLevel");
40 print q(<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
41 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
42 <html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
43 <head><title>Koha Error</title></head>
44 <body>
46 if ($debug_level eq "2"){
47 # debug 2 , print extra info too.
48 my %versions = get_versions();
50 # a little example table with various version info";
51 print "
52 <h1>Koha error</h1>
53 <p>The following fatal error has occurred:</p>
54 <pre><code>$msg</code></pre>
55 <table>
56 <tr><th>Apache</th><td> $versions{apacheVersion}</td></tr>
57 <tr><th>Koha</th><td> $versions{kohaVersion}</td></tr>
58 <tr><th>Koha DB</th><td> $versions{kohaDbVersion}</td></tr>
59 <tr><th>MySQL</th><td> $versions{mysqlVersion}</td></tr>
60 <tr><th>OS</th><td> $versions{osVersion}</td></tr>
61 <tr><th>Perl</th><td> $versions{perlVersion}</td></tr>
62 </table>";
64 } elsif ($debug_level eq "1"){
65 print "
66 <h1>Koha error</h1>
67 <p>The following fatal error has occurred:</p>
68 <pre><code>$msg</code></pre>";
69 } else {
70 print "<p>production mode - trapped fatal error</p>";
72 print "</body></html>";
74 #CGI::Carp::set_message(\&handle_errors);
75 ## give a stack backtrace if KOHA_BACKTRACES is set
76 ## can't rely on DebugLevel for this, as we're not yet connected
77 if ($ENV{KOHA_BACKTRACES}) {
78 $main::SIG{__DIE__} = \&CGI::Carp::confess;
80 } # else there is no browser to send fatals to!
81 $VERSION = '3.00.00.036';
84 use DBI;
85 use ZOOM;
86 use XML::Simple;
87 use C4::Boolean;
88 use C4::Debug;
89 use POSIX ();
91 =head1 NAME
93 C4::Context - Maintain and manipulate the context of a Koha script
95 =head1 SYNOPSIS
97 use C4::Context;
99 use C4::Context("/path/to/koha-conf.xml");
101 $config_value = C4::Context->config("config_variable");
103 $koha_preference = C4::Context->preference("preference");
105 $db_handle = C4::Context->dbh;
107 $Zconn = C4::Context->Zconn;
109 $stopwordhash = C4::Context->stopwords;
111 =head1 DESCRIPTION
113 When a Koha script runs, it makes use of a certain number of things:
114 configuration settings in F</etc/koha/koha-conf.xml>, a connection to the Koha
115 databases, and so forth. These things make up the I<context> in which
116 the script runs.
118 This module takes care of setting up the context for a script:
119 figuring out which configuration file to load, and loading it, opening
120 a connection to the right database, and so forth.
122 Most scripts will only use one context. They can simply have
124 use C4::Context;
126 at the top.
128 Other scripts may need to use several contexts. For instance, if a
129 library has two databases, one for a certain collection, and the other
130 for everything else, it might be necessary for a script to use two
131 different contexts to search both databases. Such scripts should use
132 the C<&set_context> and C<&restore_context> functions, below.
134 By default, C4::Context reads the configuration from
135 F</etc/koha/koha-conf.xml>. This may be overridden by setting the C<$KOHA_CONF>
136 environment variable to the pathname of a configuration file to use.
138 =head1 METHODS
140 =over 2
142 =cut
145 # In addition to what is said in the POD above, a Context object is a
146 # reference-to-hash with the following fields:
148 # config
149 # A reference-to-hash whose keys and values are the
150 # configuration variables and values specified in the config
151 # file (/etc/koha/koha-conf.xml).
152 # dbh
153 # A handle to the appropriate database for this context.
154 # dbh_stack
155 # Used by &set_dbh and &restore_dbh to hold other database
156 # handles for this context.
157 # Zconn
158 # A connection object for the Zebra server
160 # Koha's main configuration file koha-conf.xml
161 # is searched for according to this priority list:
163 # 1. Path supplied via use C4::Context '/path/to/koha-conf.xml'
164 # 2. Path supplied in KOHA_CONF environment variable.
165 # 3. Path supplied in INSTALLED_CONFIG_FNAME, as long
166 # as value has changed from its default of
167 # '__KOHA_CONF_DIR__/koha-conf.xml', as happens
168 # when Koha is installed in 'standard' or 'single'
169 # mode.
170 # 4. Path supplied in CONFIG_FNAME.
172 # The first entry that refers to a readable file is used.
174 use constant CONFIG_FNAME => "/etc/koha/koha-conf.xml";
175 # Default config file, if none is specified
177 my $INSTALLED_CONFIG_FNAME = '__KOHA_CONF_DIR__/koha-conf.xml';
178 # path to config file set by installer
179 # __KOHA_CONF_DIR__ is set by rewrite-confg.PL
180 # when Koha is installed in 'standard' or 'single'
181 # mode. If Koha was installed in 'dev' mode,
182 # __KOHA_CONF_DIR__ is *not* rewritten; instead
183 # developers should set the KOHA_CONF environment variable
185 $context = undef; # Initially, no context is set
186 @context_stack = (); # Initially, no saved contexts
189 =item KOHAVERSION
190 returns the kohaversion stored in kohaversion.pl file
192 =cut
194 sub KOHAVERSION {
195 my $cgidir = C4::Context->intranetdir;
197 # Apparently the GIT code does not run out of a CGI-BIN subdirectory
198 # but distribution code does? (Stan, 1jan08)
199 if(-d $cgidir . "/cgi-bin"){
200 my $cgidir .= "/cgi-bin";
203 do $cgidir."/kohaversion.pl" || die "NO $cgidir/kohaversion.pl";
204 return kohaversion();
206 =item read_config_file
208 =over 4
210 Reads the specified Koha config file.
212 Returns an object containing the configuration variables. The object's
213 structure is a bit complex to the uninitiated ... take a look at the
214 koha-conf.xml file as well as the XML::Simple documentation for details. Or,
215 here are a few examples that may give you what you need:
217 The simple elements nested within the <config> element:
219 my $pass = $koha->{'config'}->{'pass'};
221 The <listen> elements:
223 my $listen = $koha->{'listen'}->{'biblioserver'}->{'content'};
225 The elements nested within the <server> element:
227 my $ccl2rpn = $koha->{'server'}->{'biblioserver'}->{'cql2rpn'};
229 Returns undef in case of error.
231 =back
233 =cut
235 sub read_config_file { # Pass argument naming config file to read
236 my $koha = XMLin(shift, keyattr => ['id'], forcearray => ['listen', 'server', 'serverinfo'], suppressempty => '');
237 return $koha; # Return value: ref-to-hash holding the configuration
240 # db_scheme2dbi
241 # Translates the full text name of a database into de appropiate dbi name
243 sub db_scheme2dbi {
244 my $name = shift;
246 for ($name) {
247 # FIXME - Should have other databases.
248 if (/mysql/i) { return("mysql"); }
249 if (/Postgres|Pg|PostgresSQL/) { return("Pg"); }
250 if (/oracle/i) { return("Oracle"); }
252 return undef; # Just in case
255 sub import {
256 # Create the default context ($C4::Context::Context)
257 # the first time the module is called
258 # (a config file can be optionaly passed)
260 # default context allready exists?
261 return if $context;
263 # no ? so load it!
264 my ($pkg,$config_file) = @_ ;
265 my $new_ctx = __PACKAGE__->new($config_file);
266 return unless $new_ctx;
268 # if successfully loaded, use it by default
269 $new_ctx->set_context;
273 =item new
275 $context = new C4::Context;
276 $context = new C4::Context("/path/to/koha-conf.xml");
278 Allocates a new context. Initializes the context from the specified
279 file, which defaults to either the file given by the C<$KOHA_CONF>
280 environment variable, or F</etc/koha/koha-conf.xml>.
282 C<&new> does not set this context as the new default context; for
283 that, use C<&set_context>.
285 =cut
288 # Revision History:
289 # 2004-08-10 A. Tarallo: Added check if the conf file is not empty
290 sub new {
291 my $class = shift;
292 my $conf_fname = shift; # Config file to load
293 my $self = {};
295 # check that the specified config file exists and is not empty
296 undef $conf_fname unless
297 (defined $conf_fname && -s $conf_fname);
298 # Figure out a good config file to load if none was specified.
299 if (!defined($conf_fname))
301 # If the $KOHA_CONF environment variable is set, use
302 # that. Otherwise, use the built-in default.
303 if (exists $ENV{"KOHA_CONF"} and $ENV{'KOHA_CONF'} and -s $ENV{"KOHA_CONF"}) {
304 $conf_fname = $ENV{"KOHA_CONF"};
305 } elsif ($INSTALLED_CONFIG_FNAME !~ /__KOHA_CONF_DIR/ and -s $INSTALLED_CONFIG_FNAME) {
306 # NOTE: be careful -- don't change __KOHA_CONF_DIR in the above
307 # regex to anything else -- don't want installer to rewrite it
308 $conf_fname = $INSTALLED_CONFIG_FNAME;
309 } elsif (-s CONFIG_FNAME) {
310 $conf_fname = CONFIG_FNAME;
311 } else {
312 warn "unable to locate Koha configuration file koha-conf.xml";
313 return undef;
316 # Load the desired config file.
317 $self = read_config_file($conf_fname);
318 $self->{"config_file"} = $conf_fname;
320 warn "read_config_file($conf_fname) returned undef" if !defined($self->{"config"});
321 return undef if !defined($self->{"config"});
323 $self->{"dbh"} = undef; # Database handle
324 $self->{"Zconn"} = undef; # Zebra Connections
325 $self->{"stopwords"} = undef; # stopwords list
326 $self->{"marcfromkohafield"} = undef; # the hash with relations between koha table fields and MARC field/subfield
327 $self->{"userenv"} = undef; # User env
328 $self->{"activeuser"} = undef; # current active user
329 $self->{"shelves"} = undef;
331 bless $self, $class;
332 return $self;
335 =item set_context
337 $context = new C4::Context;
338 $context->set_context();
340 set_context C4::Context $context;
343 restore_context C4::Context;
345 In some cases, it might be necessary for a script to use multiple
346 contexts. C<&set_context> saves the current context on a stack, then
347 sets the context to C<$context>, which will be used in future
348 operations. To restore the previous context, use C<&restore_context>.
350 =cut
353 sub set_context
355 my $self = shift;
356 my $new_context; # The context to set
358 # Figure out whether this is a class or instance method call.
360 # We're going to make the assumption that control got here
361 # through valid means, i.e., that the caller used an instance
362 # or class method call, and that control got here through the
363 # usual inheritance mechanisms. The caller can, of course,
364 # break this assumption by playing silly buggers, but that's
365 # harder to do than doing it properly, and harder to check
366 # for.
367 if (ref($self) eq "")
369 # Class method. The new context is the next argument.
370 $new_context = shift;
371 } else {
372 # Instance method. The new context is $self.
373 $new_context = $self;
376 # Save the old context, if any, on the stack
377 push @context_stack, $context if defined($context);
379 # Set the new context
380 $context = $new_context;
383 =item restore_context
385 &restore_context;
387 Restores the context set by C<&set_context>.
389 =cut
392 sub restore_context
394 my $self = shift;
396 if ($#context_stack < 0)
398 # Stack underflow.
399 die "Context stack underflow";
402 # Pop the old context and set it.
403 $context = pop @context_stack;
405 # FIXME - Should this return something, like maybe the context
406 # that was current when this was called?
409 =item config
411 $value = C4::Context->config("config_variable");
413 $value = C4::Context->config_variable;
415 Returns the value of a variable specified in the configuration file
416 from which the current context was created.
418 The second form is more compact, but of course may conflict with
419 method names. If there is a configuration variable called "new", then
420 C<C4::Config-E<gt>new> will not return it.
422 =cut
424 sub _common_config ($$) {
425 my $var = shift;
426 my $term = shift;
427 return undef if !defined($context->{$term});
428 # Presumably $self->{$term} might be
429 # undefined if the config file given to &new
430 # didn't exist, and the caller didn't bother
431 # to check the return value.
433 # Return the value of the requested config variable
434 return $context->{$term}->{$var};
437 sub config {
438 return _common_config($_[1],'config');
440 sub zebraconfig {
441 return _common_config($_[1],'server');
443 sub ModZebrations {
444 return _common_config($_[1],'serverinfo');
447 =item preference
449 $sys_preference = C4::Context->preference('some_variable');
451 Looks up the value of the given system preference in the
452 systempreferences table of the Koha database, and returns it. If the
453 variable is not set or does not exist, undef is returned.
455 In case of an error, this may return 0.
457 Note: It is impossible to tell the difference between system
458 preferences which do not exist, and those whose values are set to NULL
459 with this method.
461 =cut
463 # FIXME: running this under mod_perl will require a means of
464 # flushing the caching mechanism.
466 my %sysprefs;
468 sub preference {
469 my $self = shift;
470 my $var = shift; # The system preference to return
472 if (exists $sysprefs{$var}) {
473 return $sysprefs{$var};
476 my $dbh = C4::Context->dbh or return 0;
478 # Look up systempreferences.variable==$var
479 my $sql = <<'END_SQL';
480 SELECT value
481 FROM systempreferences
482 WHERE variable=?
483 LIMIT 1
484 END_SQL
485 $sysprefs{$var} = $dbh->selectrow_array( $sql, {}, $var );
486 return $sysprefs{$var};
489 sub boolean_preference ($) {
490 my $self = shift;
491 my $var = shift; # The system preference to return
492 my $it = preference($self, $var);
493 return defined($it)? C4::Boolean::true_p($it): undef;
496 =item clear_syspref_cache
498 C4::Context->clear_syspref_cache();
500 cleans the internal cache of sysprefs. Please call this method if
501 you update the systempreferences table. Otherwise, your new changes
502 will not be seen by this process.
504 =cut
506 sub clear_syspref_cache {
507 %sysprefs = ();
510 # AUTOLOAD
511 # This implements C4::Config->foo, and simply returns
512 # C4::Context->config("foo"), as described in the documentation for
513 # &config, above.
515 # FIXME - Perhaps this should be extended to check &config first, and
516 # then &preference if that fails. OTOH, AUTOLOAD could lead to crappy
517 # code, so it'd probably be best to delete it altogether so as not to
518 # encourage people to use it.
519 sub AUTOLOAD
521 my $self = shift;
523 $AUTOLOAD =~ s/.*:://; # Chop off the package name,
524 # leaving only the function name.
525 return $self->config($AUTOLOAD);
528 =item Zconn
530 $Zconn = C4::Context->Zconn
532 Returns a connection to the Zebra database for the current
533 context. If no connection has yet been made, this method
534 creates one and connects.
536 C<$self>
538 C<$server> one of the servers defined in the koha-conf.xml file
540 C<$async> whether this is a asynchronous connection
542 C<$auth> whether this connection has rw access (1) or just r access (0 or NULL)
545 =cut
547 sub Zconn {
548 my $self=shift;
549 my $server=shift;
550 my $async=shift;
551 my $auth=shift;
552 my $piggyback=shift;
553 my $syntax=shift;
554 if ( defined($context->{"Zconn"}->{$server}) && (0 == $context->{"Zconn"}->{$server}->errcode()) ) {
555 return $context->{"Zconn"}->{$server};
556 # No connection object or it died. Create one.
557 }else {
558 # release resources if we're closing a connection and making a new one
559 # FIXME: this needs to be smarter -- an error due to a malformed query or
560 # a missing index does not necessarily require us to close the connection
561 # and make a new one, particularly for a batch job. However, at
562 # first glance it does not look like there's a way to easily check
563 # the basic health of a ZOOM::Connection
564 $context->{"Zconn"}->{$server}->destroy() if defined($context->{"Zconn"}->{$server});
566 $context->{"Zconn"}->{$server} = &_new_Zconn($server,$async,$auth,$piggyback,$syntax);
567 return $context->{"Zconn"}->{$server};
571 =item _new_Zconn
573 $context->{"Zconn"} = &_new_Zconn($server,$async);
575 Internal function. Creates a new database connection from the data given in the current context and returns it.
577 C<$server> one of the servers defined in the koha-conf.xml file
579 C<$async> whether this is a asynchronous connection
581 C<$auth> whether this connection has rw access (1) or just r access (0 or NULL)
583 =cut
585 sub _new_Zconn {
586 my ($server,$async,$auth,$piggyback,$syntax) = @_;
588 my $tried=0; # first attempt
589 my $Zconn; # connection object
590 $server = "biblioserver" unless $server;
591 $syntax = "usmarc" unless $syntax;
593 my $host = $context->{'listen'}->{$server}->{'content'};
594 my $servername = $context->{"config"}->{$server};
595 my $user = $context->{"serverinfo"}->{$server}->{"user"};
596 my $password = $context->{"serverinfo"}->{$server}->{"password"};
597 $auth = 1 if($user && $password);
598 retry:
599 eval {
600 # set options
601 my $o = new ZOOM::Options();
602 $o->option(user=>$user) if $auth;
603 $o->option(password=>$password) if $auth;
604 $o->option(async => 1) if $async;
605 $o->option(count => $piggyback) if $piggyback;
606 $o->option(cqlfile=> $context->{"server"}->{$server}->{"cql2rpn"});
607 $o->option(cclfile=> $context->{"serverinfo"}->{$server}->{"ccl2rpn"});
608 $o->option(preferredRecordSyntax => $syntax);
609 $o->option(elementSetName => "F"); # F for 'full' as opposed to B for 'brief'
610 $o->option(databaseName => ($servername?$servername:"biblios"));
612 # create a new connection object
613 $Zconn= create ZOOM::Connection($o);
615 # forge to server
616 $Zconn->connect($host, 0);
618 # check for errors and warn
619 if ($Zconn->errcode() !=0) {
620 warn "something wrong with the connection: ". $Zconn->errmsg();
624 # if ($@) {
625 # # Koha manages the Zebra server -- this doesn't work currently for me because of permissions issues
626 # # Also, I'm skeptical about whether it's the best approach
627 # warn "problem with Zebra";
628 # if ( C4::Context->preference("ManageZebra") ) {
629 # if ($@->code==10000 && $tried==0) { ##No connection try restarting Zebra
630 # $tried=1;
631 # warn "trying to restart Zebra";
632 # my $res=system("zebrasrv -f $ENV{'KOHA_CONF'} >/koha/log/zebra-error.log");
633 # goto "retry";
634 # } else {
635 # warn "Error ", $@->code(), ": ", $@->message(), "\n";
636 # $Zconn="error";
637 # return $Zconn;
641 return $Zconn;
644 # _new_dbh
645 # Internal helper function (not a method!). This creates a new
646 # database connection from the data given in the current context, and
647 # returns it.
648 sub _new_dbh
651 ## $context
652 ## correct name for db_schme
653 my $db_driver;
654 if ($context->config("db_scheme")){
655 $db_driver=db_scheme2dbi($context->config("db_scheme"));
656 }else{
657 $db_driver="mysql";
660 my $db_name = $context->config("database");
661 my $db_host = $context->config("hostname");
662 my $db_port = $context->config("port") || '';
663 my $db_user = $context->config("user");
664 my $db_passwd = $context->config("pass");
665 # MJR added or die here, as we can't work without dbh
666 my $dbh= DBI->connect("DBI:$db_driver:dbname=$db_name;host=$db_host;port=$db_port",
667 $db_user, $db_passwd) or die $DBI::errstr;
668 my $tz = $ENV{TZ};
669 if ( $db_driver eq 'mysql' ) {
670 # Koha 3.0 is utf-8, so force utf8 communication between mySQL and koha, whatever the mysql default config.
671 # this is better than modifying my.cnf (and forcing all communications to be in utf8)
672 $dbh->{'mysql_enable_utf8'}=1; #enable
673 $dbh->do("set NAMES 'utf8'");
674 ($tz) and $dbh->do(qq(SET time_zone = "$tz"));
676 elsif ( $db_driver eq 'Pg' ) {
677 $dbh->do( "set client_encoding = 'UTF8';" );
678 ($tz) and $dbh->do(qq(SET TIME ZONE = "$tz"));
680 return $dbh;
683 =item dbh
685 $dbh = C4::Context->dbh;
687 Returns a database handle connected to the Koha database for the
688 current context. If no connection has yet been made, this method
689 creates one, and connects to the database.
691 This database handle is cached for future use: if you call
692 C<C4::Context-E<gt>dbh> twice, you will get the same handle both
693 times. If you need a second database handle, use C<&new_dbh> and
694 possibly C<&set_dbh>.
696 =cut
699 sub dbh
701 my $self = shift;
702 my $sth;
704 if (defined($context->{"dbh"}) && $context->{"dbh"}->ping()) {
705 return $context->{"dbh"};
708 # No database handle or it died . Create one.
709 $context->{"dbh"} = &_new_dbh();
711 return $context->{"dbh"};
714 =item new_dbh
716 $dbh = C4::Context->new_dbh;
718 Creates a new connection to the Koha database for the current context,
719 and returns the database handle (a C<DBI::db> object).
721 The handle is not saved anywhere: this method is strictly a
722 convenience function; the point is that it knows which database to
723 connect to so that the caller doesn't have to know.
725 =cut
728 sub new_dbh
730 my $self = shift;
732 return &_new_dbh();
735 =item set_dbh
737 $my_dbh = C4::Connect->new_dbh;
738 C4::Connect->set_dbh($my_dbh);
740 C4::Connect->restore_dbh;
742 C<&set_dbh> and C<&restore_dbh> work in a manner analogous to
743 C<&set_context> and C<&restore_context>.
745 C<&set_dbh> saves the current database handle on a stack, then sets
746 the current database handle to C<$my_dbh>.
748 C<$my_dbh> is assumed to be a good database handle.
750 =cut
753 sub set_dbh
755 my $self = shift;
756 my $new_dbh = shift;
758 # Save the current database handle on the handle stack.
759 # We assume that $new_dbh is all good: if the caller wants to
760 # screw himself by passing an invalid handle, that's fine by
761 # us.
762 push @{$context->{"dbh_stack"}}, $context->{"dbh"};
763 $context->{"dbh"} = $new_dbh;
766 =item restore_dbh
768 C4::Context->restore_dbh;
770 Restores the database handle saved by an earlier call to
771 C<C4::Context-E<gt>set_dbh>.
773 =cut
776 sub restore_dbh
778 my $self = shift;
780 if ($#{$context->{"dbh_stack"}} < 0)
782 # Stack underflow
783 die "DBH stack underflow";
786 # Pop the old database handle and set it.
787 $context->{"dbh"} = pop @{$context->{"dbh_stack"}};
789 # FIXME - If it is determined that restore_context should
790 # return something, then this function should, too.
793 =item marcfromkohafield
795 $dbh = C4::Context->marcfromkohafield;
797 Returns a hash with marcfromkohafield.
799 This hash is cached for future use: if you call
800 C<C4::Context-E<gt>marcfromkohafield> twice, you will get the same hash without real DB access
802 =cut
805 sub marcfromkohafield
807 my $retval = {};
809 # If the hash already exists, return it.
810 return $context->{"marcfromkohafield"} if defined($context->{"marcfromkohafield"});
812 # No hash. Create one.
813 $context->{"marcfromkohafield"} = &_new_marcfromkohafield();
815 return $context->{"marcfromkohafield"};
818 # _new_marcfromkohafield
819 # Internal helper function (not a method!). This creates a new
820 # hash with stopwords
821 sub _new_marcfromkohafield
823 my $dbh = C4::Context->dbh;
824 my $marcfromkohafield;
825 my $sth = $dbh->prepare("select frameworkcode,kohafield,tagfield,tagsubfield from marc_subfield_structure where kohafield > ''");
826 $sth->execute;
827 while (my ($frameworkcode,$kohafield,$tagfield,$tagsubfield) = $sth->fetchrow) {
828 my $retval = {};
829 $marcfromkohafield->{$frameworkcode}->{$kohafield} = [$tagfield,$tagsubfield];
831 return $marcfromkohafield;
834 =item stopwords
836 $dbh = C4::Context->stopwords;
838 Returns a hash with stopwords.
840 This hash is cached for future use: if you call
841 C<C4::Context-E<gt>stopwords> twice, you will get the same hash without real DB access
843 =cut
846 sub stopwords
848 my $retval = {};
850 # If the hash already exists, return it.
851 return $context->{"stopwords"} if defined($context->{"stopwords"});
853 # No hash. Create one.
854 $context->{"stopwords"} = &_new_stopwords();
856 return $context->{"stopwords"};
859 # _new_stopwords
860 # Internal helper function (not a method!). This creates a new
861 # hash with stopwords
862 sub _new_stopwords
864 my $dbh = C4::Context->dbh;
865 my $stopwordlist;
866 my $sth = $dbh->prepare("select word from stopwords");
867 $sth->execute;
868 while (my $stopword = $sth->fetchrow_array) {
869 $stopwordlist->{$stopword} = uc($stopword);
871 $stopwordlist->{A} = "A" unless $stopwordlist;
872 return $stopwordlist;
875 =item userenv
877 C4::Context->userenv;
879 Retrieves a hash for user environment variables.
881 This hash shall be cached for future use: if you call
882 C<C4::Context-E<gt>userenv> twice, you will get the same hash without real DB access
884 =cut
887 sub userenv {
888 my $var = $context->{"activeuser"};
889 return $context->{"userenv"}->{$var} if (defined $var and defined $context->{"userenv"}->{$var});
890 # insecure=1 management
891 if ($context->{"dbh"} && $context->preference('insecure')) {
892 my %insecure;
893 $insecure{flags} = '16382';
894 $insecure{branchname} ='Insecure';
895 $insecure{number} ='0';
896 $insecure{cardnumber} ='0';
897 $insecure{id} = 'insecure';
898 $insecure{branch} = 'INS';
899 $insecure{emailaddress} = 'test@mode.insecure.com';
900 return \%insecure;
901 } else {
902 return;
906 =item set_userenv
908 C4::Context->set_userenv($usernum, $userid, $usercnum, $userfirstname, $usersurname, $userbranch, $userflags, $emailaddress);
910 Establish a hash of user environment variables.
912 set_userenv is called in Auth.pm
914 =cut
917 sub set_userenv {
918 my ($usernum, $userid, $usercnum, $userfirstname, $usersurname, $userbranch, $branchname, $userflags, $emailaddress, $branchprinter)= @_;
919 my $var=$context->{"activeuser"};
920 my $cell = {
921 "number" => $usernum,
922 "id" => $userid,
923 "cardnumber" => $usercnum,
924 "firstname" => $userfirstname,
925 "surname" => $usersurname,
926 #possibly a law problem
927 "branch" => $userbranch,
928 "branchname" => $branchname,
929 "flags" => $userflags,
930 "emailaddress" => $emailaddress,
931 "branchprinter" => $branchprinter
933 $context->{userenv}->{$var} = $cell;
934 return $cell;
937 sub set_shelves_userenv ($$) {
938 my ($type, $shelves) = @_ or return undef;
939 my $activeuser = $context->{activeuser} or return undef;
940 $context->{userenv}->{$activeuser}->{barshelves} = $shelves if $type eq 'bar';
941 $context->{userenv}->{$activeuser}->{pubshelves} = $shelves if $type eq 'pub';
942 $context->{userenv}->{$activeuser}->{totshelves} = $shelves if $type eq 'tot';
945 sub get_shelves_userenv () {
946 my $active;
947 unless ($active = $context->{userenv}->{$context->{activeuser}}) {
948 $debug and warn "get_shelves_userenv cannot retrieve context->{userenv}->{context->{activeuser}}";
949 return undef;
951 my $totshelves = $active->{totshelves} or undef;
952 my $pubshelves = $active->{pubshelves} or undef;
953 my $barshelves = $active->{barshelves} or undef;
954 return ($totshelves, $pubshelves, $barshelves);
957 =item _new_userenv
959 C4::Context->_new_userenv($session); # FIXME: This calling style is wrong for what looks like an _internal function
961 Builds a hash for user environment variables.
963 This hash shall be cached for future use: if you call
964 C<C4::Context-E<gt>userenv> twice, you will get the same hash without real DB access
966 _new_userenv is called in Auth.pm
968 =cut
971 sub _new_userenv
973 shift; # Useless except it compensates for bad calling style
974 my ($sessionID)= @_;
975 $context->{"activeuser"}=$sessionID;
978 =item _unset_userenv
980 C4::Context->_unset_userenv;
982 Destroys the hash for activeuser user environment variables.
984 =cut
988 sub _unset_userenv
990 my ($sessionID)= @_;
991 undef $context->{"activeuser"} if ($context->{"activeuser"} eq $sessionID);
995 =item get_versions
997 C4::Context->get_versions
999 Gets various version info, for core Koha packages, Currently called from carp handle_errors() sub, to send to browser if 'DebugLevel' syspref is set to '2'.
1001 =cut
1005 # A little example sub to show more debugging info for CGI::Carp
1006 sub get_versions {
1007 my %versions;
1008 $versions{kohaVersion} = KOHAVERSION();
1009 $versions{kohaDbVersion} = C4::Context->preference('version');
1010 $versions{osVersion} = join(" ", POSIX::uname());
1011 $versions{perlVersion} = $];
1013 no warnings qw(exec); # suppress warnings if unable to find a program in $PATH
1014 $versions{mysqlVersion} = `mysql -V`;
1015 $versions{apacheVersion} = `httpd -v`;
1016 $versions{apacheVersion} = `httpd2 -v` unless $versions{apacheVersion} ;
1017 $versions{apacheVersion} = `apache2 -v` unless $versions{apacheVersion} ;
1018 $versions{apacheVersion} = `/usr/sbin/apache2 -v` unless $versions{apacheVersion} ;
1020 return %versions;
1025 __END__
1027 =back
1029 =head1 ENVIRONMENT
1031 =over 4
1033 =item C<KOHA_CONF>
1035 Specifies the configuration file to read.
1037 =back
1039 =head1 SEE ALSO
1041 XML::Simple
1043 =head1 AUTHORS
1045 Andrew Arensburger <arensb at ooblick dot com>
1047 Joshua Ferraro <jmf at liblime dot com>
1049 =cut
1051 # Revision 1.57 2007/05/22 09:13:55 tipaul
1052 # Bugfixes & improvements (various and minor) :
1053 # - updating templates to have tmpl_process3.pl running without any errors
1054 # - adding a drupal-like css for prog templates (with 3 small images)
1055 # - fixing some bugs in circulation & other scripts
1056 # - updating french translation
1057 # - fixing some typos in templates
1059 # Revision 1.56 2007/04/23 15:21:17 tipaul
1060 # renaming currenttransfers to transferstoreceive
1062 # Revision 1.55 2007/04/17 08:48:00 tipaul
1063 # circulation cleaning continued: bufixing
1065 # Revision 1.54 2007/03/29 16:45:53 tipaul
1066 # Code cleaning of Biblio.pm (continued)
1068 # All subs have be cleaned :
1069 # - removed useless
1070 # - merged some
1071 # - reordering Biblio.pm completly
1072 # - using only naming conventions
1074 # Seems to have broken nothing, but it still has to be heavily tested.
1075 # Note that Biblio.pm is now much more efficient than previously & probably more reliable as well.
1077 # Revision 1.53 2007/03/29 13:30:31 tipaul
1078 # Code cleaning :
1079 # == Biblio.pm cleaning (useless) ==
1080 # * some sub declaration dropped
1081 # * removed modbiblio sub
1082 # * removed moditem sub
1083 # * removed newitems. It was used only in finishrecieve. Replaced by a TransformKohaToMarc+AddItem, that is better.
1084 # * removed MARCkoha2marcItem
1085 # * removed MARCdelsubfield declaration
1086 # * removed MARCkoha2marcBiblio
1088 # == Biblio.pm cleaning (naming conventions) ==
1089 # * MARCgettagslib renamed to GetMarcStructure
1090 # * MARCgetitems renamed to GetMarcItem
1091 # * MARCfind_frameworkcode renamed to GetFrameworkCode
1092 # * MARCmarc2koha renamed to TransformMarcToKoha
1093 # * MARChtml2marc renamed to TransformHtmlToMarc
1094 # * MARChtml2xml renamed to TranformeHtmlToXml
1095 # * zebraop renamed to ModZebra
1097 # == MARC=OFF ==
1098 # * removing MARC=OFF related scripts (in cataloguing directory)
1099 # * removed checkitems (function related to MARC=off feature, that is completly broken in head. If someone want to reintroduce it, hard work coming...)
1100 # * removed getitemsbybiblioitem (used only by MARC=OFF scripts, that is removed as well)
1102 # Revision 1.52 2007/03/16 01:25:08 kados
1103 # Using my precrash CVS copy I did the following:
1105 # cvs -z3 -d:ext:kados@cvs.savannah.nongnu.org:/sources/koha co -P koha
1106 # find koha.precrash -type d -name "CVS" -exec rm -v {} \;
1107 # cp -r koha.precrash/* koha/
1108 # cd koha/
1109 # cvs commit
1111 # This should in theory put us right back where we were before the crash
1113 # Revision 1.52 2007/03/12 21:17:05 rych
1114 # add server, serverinfo as arrays from config
1116 # Revision 1.51 2007/03/09 14:31:47 tipaul
1117 # rel_3_0 moved to HEAD
1119 # Revision 1.43.2.10 2007/02/09 17:17:56 hdl
1120 # Managing a little better database absence.
1121 # (preventing from BIG 550)
1123 # Revision 1.43.2.9 2006/12/20 16:50:48 tipaul
1124 # improving "insecure" management
1126 # WARNING KADOS :
1127 # you told me that you had some libraries with insecure=ON (behind a firewall).
1128 # In this commit, I created a "fake" user when insecure=ON. It has a fake branch. You may find better to have the 1st branch in branch table instead of a fake one.
1130 # Revision 1.43.2.8 2006/12/19 16:48:16 alaurin
1131 # reident programs, and adding branchcode value in reserves
1133 # Revision 1.43.2.7 2006/12/06 21:55:38 hdl
1134 # Adding ModZebrations for servers to get serverinfos in Context.pm
1135 # Using this function in rebuild_zebra.pl
1137 # Revision 1.43.2.6 2006/11/24 21:18:31 kados
1138 # very minor changes, no functional ones, just comments, etc.
1140 # Revision 1.43.2.5 2006/10/30 13:24:16 toins
1141 # fix some minor POD error.
1143 # Revision 1.43.2.4 2006/10/12 21:42:49 hdl
1144 # Managing multiple zebra connections
1146 # Revision 1.43.2.3 2006/10/11 14:27:26 tipaul
1147 # removing a warning
1149 # Revision 1.43.2.2 2006/10/10 15:28:16 hdl
1150 # BUG FIXING : using database name in Zconn if defined and not hard coded value
1152 # Revision 1.43.2.1 2006/10/06 13:47:28 toins
1153 # Synch with dev_week.
1154 # /!\ WARNING :: Please now use the new version of koha.xml.
1156 # Revision 1.18.2.5.2.14 2006/09/24 15:24:06 kados
1157 # remove Zebraauth routine, fold the functionality into Zconn
1158 # Zconn can now take several arguments ... this will probably
1159 # change soon as I'm not completely happy with the readability
1160 # of the current format ... see the POD for details.
1162 # cleaning up Biblio.pm, removing unnecessary routines.
1164 # DeleteBiblio - used to delete a biblio from zebra and koha tables
1165 # -- checks to make sure there are no existing issues
1166 # -- saves backups of biblio,biblioitems,items in deleted* tables
1167 # -- does commit operation
1169 # getRecord - used to retrieve one record from zebra in piggyback mode using biblionumber
1170 # brought back z3950_extended_services routine
1172 # Lots of modifications to Context.pm, you can now store user and pass info for
1173 # multiple servers (for federated searching) using the <serverinfo> element.
1174 # I'll commit my koha.xml to demonstrate this or you can refer to the POD in
1175 # Context.pm (which I also expanded on).
1177 # Revision 1.18.2.5.2.13 2006/08/10 02:10:21 kados
1178 # Turned warnings on, and running a search turned up lots of warnings.
1179 # Cleaned up those ...
1181 # removed getitemtypes from Koha.pm (one in Search.pm looks newer)
1182 # removed itemcount from Biblio.pm
1184 # made some local subs local with a _ prefix (as they were redefined
1185 # elsewhere)
1187 # Add two new search subs to Search.pm the start of a new search API
1188 # that's a bit more scalable
1190 # Revision 1.18.2.5.2.10 2006/07/21 17:50:51 kados
1191 # moving the *.properties files to intranetdir/etc dir
1193 # Revision 1.18.2.5.2.9 2006/07/17 08:05:20 tipaul
1194 # there was a hardcoded link to /koha/etc/ I replaced it with intranetdir config value
1196 # Revision 1.18.2.5.2.8 2006/07/11 12:20:37 kados
1197 # adding ccl and cql files ... Tumer, if you want to fit these into the
1198 # config file by all means do.
1200 # Revision 1.18.2.5.2.7 2006/06/04 22:50:33 tgarip1957
1201 # We do not hard code cql2rpn conversion file in context.pm our koha.xml configuration file already describes the path for this file.
1202 # At cql searching we use method CQL not CQL2RPN as the cql2rpn conversion file is defined at server level
1204 # Revision 1.18.2.5.2.6 2006/06/02 23:11:24 kados
1205 # Committing my working dev_week. It's been tested only with
1206 # searching, and there's quite a lot of config stuff to set up
1207 # beforehand. As things get closer to a release, we'll be making
1208 # some scripts to do it for us
1210 # Revision 1.18.2.5.2.5 2006/05/28 18:49:12 tgarip1957
1211 # This is an unusual commit. The main purpose is a working model of Zebra on a modified rel2_2.
1212 # Any questions regarding these commits should be asked to Joshua Ferraro unless you are Joshua whom I'll report to
1214 # Revision 1.36 2006/05/09 13:28:08 tipaul
1215 # adding the branchname and the librarian name in every page :
1216 # - modified userenv to add branchname
1217 # - modifier menus.inc to have the librarian name & userenv displayed on every page. they are in a librarian_information div.
1219 # Revision 1.35 2006/04/13 08:40:11 plg
1220 # bug fixed: typo on Zconnauth name
1222 # Revision 1.34 2006/04/10 21:40:23 tgarip1957
1223 # A new handler defined for zebra Zconnauth with read/write permission. Zconnauth should only be called in biblio.pm where write operations are. Use of this handler will break things unless koha.conf contains new variables:
1224 # zebradb=localhost
1225 # zebraport=<your port>
1226 # zebrauser=<username>
1227 # zebrapass=<password>
1229 # The zebra.cfg file should read:
1230 # perm.anonymous:r
1231 # perm.username:rw
1232 # passw.c:<yourpasswordfile>
1234 # Password file should be prepared with Apaches htpasswd utility in encrypted mode and should exist in a folder zebra.cfg can read
1236 # Revision 1.33 2006/03/15 11:21:56 plg
1237 # bug fixed: utf-8 data where not displayed correctly in screens. Supposing
1238 # your data are truely utf-8 encoded in your database, they should be
1239 # correctly displayed. "set names 'UTF8'" on mysql connection (C4/Context.pm)
1240 # is mandatory and "binmode" to utf8 (C4/Interface/CGI/Output.pm) seemed to
1241 # converted data twice, so it was removed.
1243 # Revision 1.32 2006/03/03 17:25:01 hdl
1244 # Bug fixing : a line missed a comment sign.
1246 # Revision 1.31 2006/03/03 16:45:36 kados
1247 # Remove the search that tests the Zconn -- warning, still no fault
1248 # tollerance
1250 # Revision 1.30 2006/02/22 00:56:59 kados
1251 # First go at a connection object for Zebra. You can now get a
1252 # connection object by doing:
1254 # my $Zconn = C4::Context->Zconn;
1256 # My initial tests indicate that as soon as your funcion ends
1257 # (ie, when you're done doing something) the connection will be
1258 # closed automatically. There may be some other way to make the
1259 # connection more stateful, I'm not sure...
1261 # Local Variables:
1262 # tab-width: 4
1263 # End: