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