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