Bug 17600: Standardize our EXPORT_OK
[srvgit] / C4 / Context.pm
1 package C4::Context;
2
3 # Copyright 2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21
22 use vars qw($AUTOLOAD $context @context_stack);
23 BEGIN {
24     if ( $ENV{'HTTP_USER_AGENT'} ) { # Only hit when plack is not enabled
25
26         # Redefine multi_param if cgi version is < 4.08
27         # Remove the "CGI::param called in list context" warning in this case
28         require CGI;    # Can't check version without the require.
29         if ( !defined($CGI::VERSION) || $CGI::VERSION < 4.08 ) {
30             no warnings 'redefine';
31             *CGI::multi_param = \&CGI::param;
32             use warnings 'redefine';
33             $CGI::LIST_CONTEXT_WARN = 0;
34         }
35     }
36 };
37
38 use Carp qw( carp );
39 use DateTime::TimeZone;
40 use Encode;
41 use File::Spec;
42 use POSIX;
43 use YAML::XS;
44 use ZOOM;
45
46 use Koha::Caches;
47 use Koha::Config::SysPref;
48 use Koha::Config::SysPrefs;
49 use Koha::Config;
50 use Koha;
51
52 =head1 NAME
53
54 C4::Context - Maintain and manipulate the context of a Koha script
55
56 =head1 SYNOPSIS
57
58   use C4::Context;
59
60   use C4::Context("/path/to/koha-conf.xml");
61
62   $config_value = C4::Context->config("config_variable");
63
64   $koha_preference = C4::Context->preference("preference");
65
66   $db_handle = C4::Context->dbh;
67
68   $Zconn = C4::Context->Zconn;
69
70 =head1 DESCRIPTION
71
72 When a Koha script runs, it makes use of a certain number of things:
73 configuration settings in F</etc/koha/koha-conf.xml>, a connection to the Koha
74 databases, and so forth. These things make up the I<context> in which
75 the script runs.
76
77 This module takes care of setting up the context for a script:
78 figuring out which configuration file to load, and loading it, opening
79 a connection to the right database, and so forth.
80
81 Most scripts will only use one context. They can simply have
82
83   use C4::Context;
84
85 at the top.
86
87 Other scripts may need to use several contexts. For instance, if a
88 library has two databases, one for a certain collection, and the other
89 for everything else, it might be necessary for a script to use two
90 different contexts to search both databases. Such scripts should use
91 the C<&set_context> and C<&restore_context> functions, below.
92
93 By default, C4::Context reads the configuration from
94 F</etc/koha/koha-conf.xml>. This may be overridden by setting the C<$KOHA_CONF>
95 environment variable to the pathname of a configuration file to use.
96
97 =head1 METHODS
98
99 =cut
100
101 #'
102 # In addition to what is said in the POD above, a Context object is a
103 # reference-to-hash with the following fields:
104 #
105 # config
106 #    A reference-to-hash whose keys and values are the
107 #    configuration variables and values specified in the config
108 #    file (/etc/koha/koha-conf.xml).
109 # dbh
110 #    A handle to the appropriate database for this context.
111 # dbh_stack
112 #    Used by &set_dbh and &restore_dbh to hold other database
113 #    handles for this context.
114 # Zconn
115 #     A connection object for the Zebra server
116
117 $context = undef;        # Initially, no context is set
118 @context_stack = ();        # Initially, no saved contexts
119
120 =head2 db_scheme2dbi
121
122     my $dbd_driver_name = C4::Context::db_schema2dbi($scheme);
123
124 This routines translates a database type to part of the name
125 of the appropriate DBD driver to use when establishing a new
126 database connection.  It recognizes 'mysql' and 'Pg'; if any
127 other scheme is supplied it defaults to 'mysql'.
128
129 =cut
130
131 sub db_scheme2dbi {
132     my $scheme = shift // '';
133     return $scheme eq 'Pg' ? $scheme : 'mysql';
134 }
135
136 sub import {
137     # Create the default context ($C4::Context::Context)
138     # the first time the module is called
139     # (a config file can be optionaly passed)
140
141     # default context already exists?
142     return if $context;
143
144     # no ? so load it!
145     my ($pkg,$config_file) = @_ ;
146     my $new_ctx = __PACKAGE__->new($config_file);
147     return unless $new_ctx;
148
149     # if successfully loaded, use it by default
150     $new_ctx->set_context;
151     1;
152 }
153
154 =head2 new
155
156   $context = C4::Context->new;
157   $context = C4::Context->new("/path/to/koha-conf.xml");
158
159 Allocates a new context. Initializes the context from the specified
160 file, which defaults to either the file given by the C<$KOHA_CONF>
161 environment variable, or F</etc/koha/koha-conf.xml>.
162
163 It saves the koha-conf.xml values in the declared memcached server(s)
164 if currently available and uses those values until them expire and
165 re-reads them.
166
167 C<&new> does not set this context as the new default context; for
168 that, use C<&set_context>.
169
170 =cut
171
172 #'
173 # Revision History:
174 # 2004-08-10 A. Tarallo: Added check if the conf file is not empty
175 sub new {
176     my $class = shift;
177     my $conf_fname = shift;        # Config file to load
178
179     # check that the specified config file exists and is not empty
180     undef $conf_fname unless 
181         (defined $conf_fname && -s $conf_fname);
182     # Figure out a good config file to load if none was specified.
183     unless ( defined $conf_fname ) {
184         $conf_fname = Koha::Config->guess_koha_conf;
185         unless ( $conf_fname ) {
186             warn "unable to locate Koha configuration file koha-conf.xml";
187             return;
188         }
189     }
190
191     my $self = Koha::Config->read_from_file($conf_fname);
192     unless ( exists $self->{config} or defined $self->{config} ) {
193         warn "The config file ($conf_fname) has not been parsed correctly";
194         return;
195     }
196
197     $self->{"Zconn"} = undef;    # Zebra Connections
198     $self->{"userenv"} = undef;        # User env
199     $self->{"activeuser"} = undef;        # current active user
200     $self->{"shelves"} = undef;
201     $self->{tz} = undef; # local timezone object
202
203     bless $self, $class;
204     $self->{db_driver} = db_scheme2dbi($self->config('db_scheme'));  # cache database driver
205     return $self;
206 }
207
208 =head2 set_context
209
210   $context = new C4::Context;
211   $context->set_context();
212 or
213   set_context C4::Context $context;
214
215   ...
216   restore_context C4::Context;
217
218 In some cases, it might be necessary for a script to use multiple
219 contexts. C<&set_context> saves the current context on a stack, then
220 sets the context to C<$context>, which will be used in future
221 operations. To restore the previous context, use C<&restore_context>.
222
223 =cut
224
225 #'
226 sub set_context
227 {
228     my $self = shift;
229     my $new_context;    # The context to set
230
231     # Figure out whether this is a class or instance method call.
232     #
233     # We're going to make the assumption that control got here
234     # through valid means, i.e., that the caller used an instance
235     # or class method call, and that control got here through the
236     # usual inheritance mechanisms. The caller can, of course,
237     # break this assumption by playing silly buggers, but that's
238     # harder to do than doing it properly, and harder to check
239     # for.
240     if (ref($self) eq "")
241     {
242         # Class method. The new context is the next argument.
243         $new_context = shift;
244     } else {
245         # Instance method. The new context is $self.
246         $new_context = $self;
247     }
248
249     # Save the old context, if any, on the stack
250     push @context_stack, $context if defined($context);
251
252     # Set the new context
253     $context = $new_context;
254 }
255
256 =head2 restore_context
257
258   &restore_context;
259
260 Restores the context set by C<&set_context>.
261
262 =cut
263
264 #'
265 sub restore_context
266 {
267     my $self = shift;
268
269     if ($#context_stack < 0)
270     {
271         # Stack underflow.
272         die "Context stack underflow";
273     }
274
275     # Pop the old context and set it.
276     $context = pop @context_stack;
277
278     # FIXME - Should this return something, like maybe the context
279     # that was current when this was called?
280 }
281
282 =head2 config
283
284   $value = C4::Context->config("config_variable");
285
286   $value = C4::Context->config_variable;
287
288 Returns the value of a variable specified in the configuration file
289 from which the current context was created.
290
291 The second form is more compact, but of course may conflict with
292 method names. If there is a configuration variable called "new", then
293 C<C4::Config-E<gt>new> will not return it.
294
295 =cut
296
297 sub _common_config {
298         my $var = shift;
299         my $term = shift;
300     return unless defined $context and defined $context->{$term};
301        # Presumably $self->{$term} might be
302        # undefined if the config file given to &new
303        # didn't exist, and the caller didn't bother
304        # to check the return value.
305
306     # Return the value of the requested config variable
307     return $context->{$term}->{$var};
308 }
309
310 sub config {
311         return _common_config($_[1],'config');
312 }
313 sub zebraconfig {
314         return _common_config($_[1],'server');
315 }
316
317 =head2 preference
318
319   $sys_preference = C4::Context->preference('some_variable');
320
321 Looks up the value of the given system preference in the
322 systempreferences table of the Koha database, and returns it. If the
323 variable is not set or does not exist, undef is returned.
324
325 In case of an error, this may return 0.
326
327 Note: It is impossible to tell the difference between system
328 preferences which do not exist, and those whose values are set to NULL
329 with this method.
330
331 =cut
332
333 my $use_syspref_cache = 1;
334 sub preference {
335     my $self = shift;
336     my $var  = shift;    # The system preference to return
337
338     return Encode::decode_utf8($ENV{"OVERRIDE_SYSPREF_$var"})
339         if defined $ENV{"OVERRIDE_SYSPREF_$var"};
340
341     $var = lc $var;
342
343     if ($use_syspref_cache) {
344         my $syspref_cache = Koha::Caches->get_instance('syspref');
345         my $cached_var = $syspref_cache->get_from_cache("syspref_$var");
346         return $cached_var if defined $cached_var;
347     }
348
349     my $syspref;
350     eval { $syspref = Koha::Config::SysPrefs->find( lc $var ) };
351     my $value = $syspref ? $syspref->value() : undef;
352
353     if ( $use_syspref_cache ) {
354         my $syspref_cache = Koha::Caches->get_instance('syspref');
355         $syspref_cache->set_in_cache("syspref_$var", $value);
356     }
357     return $value;
358 }
359
360 =head2 yaml_preference
361
362 Retrieves the required system preference value, and converts it
363 from YAML into a Perl data structure. It throws an exception if
364 the value cannot be properly decoded as YAML.
365
366 =cut
367
368 sub yaml_preference {
369     my ( $self, $preference ) = @_;
370
371     my $yaml = eval { YAML::XS::Load( Encode::encode_utf8( $self->preference( $preference ) ) ); };
372     if ($@) {
373         warn "Unable to parse $preference syspref : $@";
374         return;
375     }
376
377     return $yaml;
378 }
379
380 =head2 enable_syspref_cache
381
382   C4::Context->enable_syspref_cache();
383
384 Enable the in-memory syspref cache used by C4::Context. This is the
385 default behavior.
386
387 =cut
388
389 sub enable_syspref_cache {
390     my ($self) = @_;
391     $use_syspref_cache = 1;
392     # We need to clear the cache to have it up-to-date
393     $self->clear_syspref_cache();
394 }
395
396 =head2 disable_syspref_cache
397
398   C4::Context->disable_syspref_cache();
399
400 Disable the in-memory syspref cache used by C4::Context. This should be
401 used with Plack and other persistent environments.
402
403 =cut
404
405 sub disable_syspref_cache {
406     my ($self) = @_;
407     $use_syspref_cache = 0;
408     $self->clear_syspref_cache();
409 }
410
411 =head2 clear_syspref_cache
412
413   C4::Context->clear_syspref_cache();
414
415 cleans the internal cache of sysprefs. Please call this method if
416 you update the systempreferences table. Otherwise, your new changes
417 will not be seen by this process.
418
419 =cut
420
421 sub clear_syspref_cache {
422     return unless $use_syspref_cache;
423     my $syspref_cache = Koha::Caches->get_instance('syspref');
424     $syspref_cache->flush_all;
425 }
426
427 =head2 set_preference
428
429   C4::Context->set_preference( $variable, $value, [ $explanation, $type, $options ] );
430
431 This updates a preference's value both in the systempreferences table and in
432 the sysprefs cache. If the optional parameters are provided, then the query
433 becomes a create. It won't update the parameters (except value) for an existing
434 preference.
435
436 =cut
437
438 sub set_preference {
439     my ( $self, $variable, $value, $explanation, $type, $options ) = @_;
440
441     my $variable_case = $variable;
442     $variable = lc $variable;
443
444     my $syspref = Koha::Config::SysPrefs->find($variable);
445     $type =
446         $type    ? $type
447       : $syspref ? $syspref->type
448       :            undef;
449
450     $value = 0 if ( $type && $type eq 'YesNo' && $value eq '' );
451
452     # force explicit protocol on OPACBaseURL
453     if ( $variable eq 'opacbaseurl' && $value && substr( $value, 0, 4 ) !~ /http/ ) {
454         $value = 'http://' . $value;
455     }
456
457     if ($syspref) {
458         $syspref->set(
459             {   ( defined $value ? ( value       => $value )       : () ),
460                 ( $explanation   ? ( explanation => $explanation ) : () ),
461                 ( $type          ? ( type        => $type )        : () ),
462                 ( $options       ? ( options     => $options )     : () ),
463             }
464         )->store;
465     } else {
466         $syspref = Koha::Config::SysPref->new(
467             {   variable    => $variable_case,
468                 value       => $value,
469                 explanation => $explanation || undef,
470                 type        => $type,
471                 options     => $options || undef,
472             }
473         )->store();
474     }
475
476     if ( $use_syspref_cache ) {
477         my $syspref_cache = Koha::Caches->get_instance('syspref');
478         $syspref_cache->set_in_cache( "syspref_$variable", $value );
479     }
480
481     return $syspref;
482 }
483
484 =head2 delete_preference
485
486     C4::Context->delete_preference( $variable );
487
488 This deletes a system preference from the database. Returns a true value on
489 success. Failure means there was an issue with the database, not that there
490 was no syspref of the name.
491
492 =cut
493
494 sub delete_preference {
495     my ( $self, $var ) = @_;
496
497     if ( Koha::Config::SysPrefs->find( $var )->delete ) {
498         if ( $use_syspref_cache ) {
499             my $syspref_cache = Koha::Caches->get_instance('syspref');
500             $syspref_cache->clear_from_cache("syspref_$var");
501         }
502
503         return 1;
504     }
505     return 0;
506 }
507
508 =head2 Zconn
509
510   $Zconn = C4::Context->Zconn
511
512 Returns a connection to the Zebra database
513
514 C<$self> 
515
516 C<$server> one of the servers defined in the koha-conf.xml file
517
518 C<$async> whether this is a asynchronous connection
519
520 =cut
521
522 sub Zconn {
523     my ($self, $server, $async ) = @_;
524     my $cache_key = join ('::', (map { $_ // '' } ($server, $async )));
525     if ( (!defined($ENV{GATEWAY_INTERFACE})) && defined($context->{"Zconn"}->{$cache_key}) && (0 == $context->{"Zconn"}->{$cache_key}->errcode()) ) {
526         # if we are running the script from the commandline, lets try to use the caching
527         return $context->{"Zconn"}->{$cache_key};
528     }
529     $context->{"Zconn"}->{$cache_key}->destroy() if defined($context->{"Zconn"}->{$cache_key}); #destroy old connection before making a new one
530     $context->{"Zconn"}->{$cache_key} = &_new_Zconn( $server, $async );
531     return $context->{"Zconn"}->{$cache_key};
532 }
533
534 =head2 _new_Zconn
535
536 $context->{"Zconn"} = &_new_Zconn($server,$async);
537
538 Internal function. Creates a new database connection from the data given in the current context and returns it.
539
540 C<$server> one of the servers defined in the koha-conf.xml file
541
542 C<$async> whether this is a asynchronous connection
543
544 C<$auth> whether this connection has rw access (1) or just r access (0 or NULL)
545
546 =cut
547
548 sub _new_Zconn {
549     my ( $server, $async ) = @_;
550
551     my $tried=0; # first attempt
552     my $Zconn; # connection object
553     my $elementSetName;
554     my $syntax;
555
556     $server //= "biblioserver";
557
558     $syntax = 'xml';
559     $elementSetName = 'marcxml';
560
561     my $host = $context->{'listen'}->{$server}->{'content'};
562     my $user = $context->{"serverinfo"}->{$server}->{"user"};
563     my $password = $context->{"serverinfo"}->{$server}->{"password"};
564     eval {
565         # set options
566         my $o = ZOOM::Options->new();
567         $o->option(user => $user) if $user && $password;
568         $o->option(password => $password) if $user && $password;
569         $o->option(async => 1) if $async;
570         $o->option(cqlfile=> $context->{"server"}->{$server}->{"cql2rpn"});
571         $o->option(cclfile=> $context->{"serverinfo"}->{$server}->{"ccl2rpn"});
572         $o->option(preferredRecordSyntax => $syntax);
573         $o->option(elementSetName => $elementSetName) if $elementSetName;
574         $o->option(databaseName => $context->{"config"}->{$server}||"biblios");
575
576         # create a new connection object
577         $Zconn= create ZOOM::Connection($o);
578
579         # forge to server
580         $Zconn->connect($host, 0);
581
582         # check for errors and warn
583         if ($Zconn->errcode() !=0) {
584             warn "something wrong with the connection: ". $Zconn->errmsg();
585         }
586     };
587     return $Zconn;
588 }
589
590 # _new_dbh
591 # Internal helper function (not a method!). This creates a new
592 # database connection from the data given in the current context, and
593 # returns it.
594 sub _new_dbh
595 {
596
597     Koha::Database->schema({ new => 1 })->storage->dbh;
598 }
599
600 =head2 dbh
601
602   $dbh = C4::Context->dbh;
603
604 Returns a database handle connected to the Koha database for the
605 current context. If no connection has yet been made, this method
606 creates one, and connects to the database.
607
608 This database handle is cached for future use: if you call
609 C<C4::Context-E<gt>dbh> twice, you will get the same handle both
610 times. If you need a second database handle, use C<&new_dbh> and
611 possibly C<&set_dbh>.
612
613 =cut
614
615 #'
616 sub dbh
617 {
618     my $self = shift;
619     my $params = shift;
620
621     unless ( $params->{new} ) {
622         return Koha::Database->schema->storage->dbh;
623     }
624
625     return Koha::Database->schema({ new => 1 })->storage->dbh;
626 }
627
628 =head2 new_dbh
629
630   $dbh = C4::Context->new_dbh;
631
632 Creates a new connection to the Koha database for the current context,
633 and returns the database handle (a C<DBI::db> object).
634
635 The handle is not saved anywhere: this method is strictly a
636 convenience function; the point is that it knows which database to
637 connect to so that the caller doesn't have to know.
638
639 =cut
640
641 #'
642 sub new_dbh
643 {
644     my $self = shift;
645
646     return &dbh({ new => 1 });
647 }
648
649 =head2 set_dbh
650
651   $my_dbh = C4::Connect->new_dbh;
652   C4::Connect->set_dbh($my_dbh);
653   ...
654   C4::Connect->restore_dbh;
655
656 C<&set_dbh> and C<&restore_dbh> work in a manner analogous to
657 C<&set_context> and C<&restore_context>.
658
659 C<&set_dbh> saves the current database handle on a stack, then sets
660 the current database handle to C<$my_dbh>.
661
662 C<$my_dbh> is assumed to be a good database handle.
663
664 =cut
665
666 #'
667 sub set_dbh
668 {
669     my $self = shift;
670     my $new_dbh = shift;
671
672     # Save the current database handle on the handle stack.
673     # We assume that $new_dbh is all good: if the caller wants to
674     # screw himself by passing an invalid handle, that's fine by
675     # us.
676     push @{$context->{"dbh_stack"}}, $context->{"dbh"};
677     $context->{"dbh"} = $new_dbh;
678 }
679
680 =head2 restore_dbh
681
682   C4::Context->restore_dbh;
683
684 Restores the database handle saved by an earlier call to
685 C<C4::Context-E<gt>set_dbh>.
686
687 =cut
688
689 #'
690 sub restore_dbh
691 {
692     my $self = shift;
693
694     if ($#{$context->{"dbh_stack"}} < 0)
695     {
696         # Stack underflow
697         die "DBH stack underflow";
698     }
699
700     # Pop the old database handle and set it.
701     $context->{"dbh"} = pop @{$context->{"dbh_stack"}};
702
703     # FIXME - If it is determined that restore_context should
704     # return something, then this function should, too.
705 }
706
707 =head2 userenv
708
709   C4::Context->userenv;
710
711 Retrieves a hash for user environment variables.
712
713 This hash shall be cached for future use: if you call
714 C<C4::Context-E<gt>userenv> twice, you will get the same hash without real DB access
715
716 =cut
717
718 #'
719 sub userenv {
720     my $var = $context->{"activeuser"};
721     if (defined $var and defined $context->{"userenv"}->{$var}) {
722         return $context->{"userenv"}->{$var};
723     } else {
724         return;
725     }
726 }
727
728 =head2 set_userenv
729
730   C4::Context->set_userenv($usernum, $userid, $usercnum,
731                            $userfirstname, $usersurname,
732                            $userbranch, $branchname, $userflags,
733                            $emailaddress, $shibboleth
734                            $desk_id, $desk_name,
735                            $register_id, $register_name);
736
737 Establish a hash of user environment variables.
738
739 set_userenv is called in Auth.pm
740
741 =cut
742
743 #'
744 sub set_userenv {
745     shift @_;
746     my (
747         $usernum,      $userid,     $usercnum,   $userfirstname,
748         $usersurname,  $userbranch, $branchname, $userflags,
749         $emailaddress, $shibboleth, $desk_id,    $desk_name,
750         $register_id,  $register_name
751     ) = @_;
752
753     my $var=$context->{"activeuser"} || '';
754     my $cell = {
755         "number"     => $usernum,
756         "id"         => $userid,
757         "cardnumber" => $usercnum,
758         "firstname"  => $userfirstname,
759         "surname"    => $usersurname,
760
761         #possibly a law problem
762         "branch"        => $userbranch,
763         "branchname"    => $branchname,
764         "flags"         => $userflags,
765         "emailaddress"  => $emailaddress,
766         "shibboleth"    => $shibboleth,
767         "desk_id"       => $desk_id,
768         "desk_name"     => $desk_name,
769         "register_id"   => $register_id,
770         "register_name" => $register_name
771     };
772     $context->{userenv}->{$var} = $cell;
773     return $cell;
774 }
775
776 =head2 _new_userenv
777
778   C4::Context->_new_userenv($session);  # FIXME: This calling style is wrong for what looks like an _internal function
779
780 Builds a hash for user environment variables.
781
782 This hash shall be cached for future use: if you call
783 C<C4::Context-E<gt>userenv> twice, you will get the same hash without real DB access
784
785 _new_userenv is called in Auth.pm
786
787 =cut
788
789 #'
790 sub _new_userenv
791 {
792     shift;  # Useless except it compensates for bad calling style
793     my ($sessionID)= @_;
794      $context->{"activeuser"}=$sessionID;
795 }
796
797 =head2 _unset_userenv
798
799   C4::Context->_unset_userenv;
800
801 Destroys the hash for activeuser user environment variables.
802
803 =cut
804
805 #'
806
807 sub _unset_userenv
808 {
809     my ($sessionID)= @_;
810     undef $context->{"activeuser"} if ($context->{"activeuser"} eq $sessionID);
811 }
812
813
814 =head2 get_versions
815
816   C4::Context->get_versions
817
818 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'.
819
820 =cut
821
822 #'
823
824 # A little example sub to show more debugging info for CGI::Carp
825 sub get_versions {
826     my %versions;
827     $versions{kohaVersion}  = Koha::version();
828     $versions{kohaDbVersion} = C4::Context->preference('version');
829     $versions{osVersion} = join(" ", POSIX::uname());
830     $versions{perlVersion} = $];
831     {
832         no warnings qw(exec); # suppress warnings if unable to find a program in $PATH
833         $versions{mysqlVersion}  = `mysql -V`;
834         $versions{apacheVersion} = (`apache2ctl -v`)[0];
835         $versions{apacheVersion} = `httpd -v`             unless  $versions{apacheVersion} ;
836         $versions{apacheVersion} = `httpd2 -v`            unless  $versions{apacheVersion} ;
837         $versions{apacheVersion} = `apache2 -v`           unless  $versions{apacheVersion} ;
838         $versions{apacheVersion} = `/usr/sbin/apache2 -v` unless  $versions{apacheVersion} ;
839     }
840     return %versions;
841 }
842
843 =head2 timezone
844
845   my $C4::Context->timzone
846
847   Returns a timezone code for the instance of Koha
848
849 =cut
850
851 sub timezone {
852     my $self = shift;
853
854     my $timezone = C4::Context->config('timezone') || $ENV{TZ} || 'local';
855     if ( !DateTime::TimeZone->is_valid_name( $timezone ) ) {
856         warn "Invalid timezone in koha-conf.xml ($timezone)";
857         $timezone = 'local';
858     }
859
860     return $timezone;
861 }
862
863 =head2 tz
864
865   C4::Context->tz
866
867   Returns a DateTime::TimeZone object for the system timezone
868
869 =cut
870
871 sub tz {
872     my $self = shift;
873     if (!defined $context->{tz}) {
874         my $timezone = $self->timezone;
875         $context->{tz} = DateTime::TimeZone->new(name => $timezone);
876     }
877     return $context->{tz};
878 }
879
880
881 =head2 IsSuperLibrarian
882
883     C4::Context->IsSuperLibrarian();
884
885 =cut
886
887 sub IsSuperLibrarian {
888     my $userenv = C4::Context->userenv;
889
890     unless ( $userenv and exists $userenv->{flags} ) {
891         # If we reach this without a user environment,
892         # assume that we're running from a command-line script,
893         # and act as a superlibrarian.
894         carp("C4::Context->userenv not defined!");
895         return 1;
896     }
897
898     return ($userenv->{flags}//0) % 2;
899 }
900
901 =head2 interface
902
903 Sets the current interface for later retrieval in any Perl module
904
905     C4::Context->interface('opac');
906     C4::Context->interface('intranet');
907     my $interface = C4::Context->interface;
908
909 =cut
910
911 sub interface {
912     my ($class, $interface) = @_;
913
914     if (defined $interface) {
915         $interface = lc $interface;
916         if (   $interface eq 'api'
917             || $interface eq 'opac'
918             || $interface eq 'intranet'
919             || $interface eq 'sip'
920             || $interface eq 'cron'
921             || $interface eq 'commandline' )
922         {
923             $context->{interface} = $interface;
924         } else {
925             warn "invalid interface : '$interface'";
926         }
927     }
928
929     return $context->{interface} // 'opac';
930 }
931
932 # always returns a string for OK comparison via "eq" or "ne"
933 sub mybranch {
934     C4::Context->userenv           or return '';
935     return C4::Context->userenv->{branch} || '';
936 }
937
938 =head2 only_my_library
939
940     my $test = C4::Context->only_my_library;
941
942     Returns true if you enabled IndependentBranches and the current user
943     does not have superlibrarian permissions.
944
945 =cut
946
947 sub only_my_library {
948     return
949          C4::Context->preference('IndependentBranches')
950       && C4::Context->userenv
951       && !C4::Context->IsSuperLibrarian()
952       && C4::Context->userenv->{branch};
953 }
954
955 =head3 temporary_directory
956
957 Returns root directory for temporary storage
958
959 =cut
960
961 sub temporary_directory {
962     my ( $class ) = @_;
963     return C4::Context->config('tmp_path') || File::Spec->tmpdir;
964 }
965
966 =head3 set_remote_address
967
968 set_remote_address should be called at the beginning of every script
969 that is *not* running under plack in order to the REMOTE_ADDR environment
970 variable to be set correctly.
971
972 =cut
973
974 sub set_remote_address {
975     if ( C4::Context->config('koha_trusted_proxies') ) {
976         require CGI;
977         my $header = CGI->http('HTTP_X_FORWARDED_FOR');
978
979         if ($header) {
980             require Koha::Middleware::RealIP;
981             $ENV{REMOTE_ADDR} = Koha::Middleware::RealIP::get_real_ip( $ENV{REMOTE_ADDR}, $header );
982         }
983     }
984 }
985
986 =head3 https_enabled
987
988 https_enabled should be called when checking if a HTTPS connection
989 is used.
990
991 Note that this depends on a HTTPS environmental variable being defined
992 by the web server. This function may not return the expected result,
993 if your web server or reverse proxies are not setting the correct
994 X-Forwarded-Proto headers and HTTPS environmental variable.
995
996 Note too that the HTTPS value can vary from web server to web server.
997 We are relying on the convention of the value being "on" or "ON" here.
998
999 =cut
1000
1001 sub https_enabled {
1002     my $https_enabled = 0;
1003     my $env_https = $ENV{HTTPS};
1004     if ($env_https){
1005         if ($env_https =~ /^ON$/i){
1006             $https_enabled = 1;
1007         }
1008     }
1009     return $https_enabled;
1010 }
1011
1012 1;
1013
1014 =head3 needs_install
1015
1016     if ( $context->needs_install ) { ... }
1017
1018 This method returns a boolean representing the install status of the Koha instance.
1019
1020 =cut
1021
1022 sub needs_install {
1023     my ($self) = @_;
1024     return ($self->preference('Version')) ? 0 : 1;
1025 }
1026
1027 __END__
1028
1029 =head1 ENVIRONMENT
1030
1031 =head2 C<KOHA_CONF>
1032
1033 Specifies the configuration file to read.
1034
1035 =head1 AUTHORS
1036
1037 Andrew Arensburger <arensb at ooblick dot com>
1038
1039 Joshua Ferraro <jmf at liblime dot com>
1040