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