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