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