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