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