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