--- loncom/lonnet/perl/lonnet.pm 2010/07/26 21:52:19 1.1078 +++ loncom/lonnet/perl/lonnet.pm 2020/10/23 21:52:59 1.1172.2.130 @@ -1,7 +1,7 @@ # The LearningOnline Network # TCP networking package # -# $Id: lonnet.pm,v 1.1078 2010/07/26 21:52:19 raeburn Exp $ +# $Id: lonnet.pm,v 1.1172.2.130 2020/10/23 21:52:59 raeburn Exp $ # # Copyright Michigan State University Board of Trustees # @@ -74,9 +74,11 @@ use strict; use LWP::UserAgent(); use HTTP::Date; use Image::Magick; +use CGI::Cookie; -use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir - $_64bit %env %protocol %loncaparevs %serverhomeIDs); +use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex + $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease + %managerstab $passwdmin); my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash, %userrolehash, $processmarker, $dumpcount, %coursedombuf, @@ -88,54 +90,61 @@ use GDBM_File; use HTML::LCParser; use Fcntl qw(:flock); use Storable qw(thaw nfreeze); -use Time::HiRes qw( gettimeofday tv_interval ); +use Time::HiRes qw( sleep gettimeofday tv_interval ); use Cache::Memcached; use Digest::MD5; use Math::Random; use File::MMagic; use LONCAPA qw(:DEFAULT :match); use LONCAPA::Configuration; +use LONCAPA::lonmetadata; +use LONCAPA::Lond; +use LONCAPA::transliterate; + +use File::Copy; my $readit; -my $max_connection_retries = 10; # Or some such value. +my $max_connection_retries = 20; # Or some such value. require Exporter; our @ISA = qw (Exporter); our @EXPORT = qw(%env); - -# --------------------------------------------------------------------- Logging +# ------------------------------------ Logging (parameters, docs, slots, roles) { my $logid; - sub instructor_log { - my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_; - if (($cnum eq '') || ($cdom eq '')) { - $cnum = $env{'course.'.$env{'request.course.id'}.'.num'}; - $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'}; + sub write_log { + my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_; + if ($context eq 'course') { + if (($cnum eq '') || ($cdom eq '')) { + $cnum = $env{'course.'.$env{'request.course.id'}.'.num'}; + $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'}; + } } - $logid++; + $logid ++; my $now = time(); my $id=$now.'00000'.$$.'00000'.$logid; - return &Apache::lonnet::put('nohist_'.$hash_name, - { $id => { - 'exe_uname' => $env{'user.name'}, - 'exe_udom' => $env{'user.domain'}, - 'exe_time' => $now, - 'exe_ip' => $ENV{'REMOTE_ADDR'}, - 'delflag' => $delflag, - 'logentry' => $storehash, - 'uname' => $uname, - 'udom' => $udom, - } - },$cdom,$cnum); + my $logentry = { + $id => { + 'exe_uname' => $env{'user.name'}, + 'exe_udom' => $env{'user.domain'}, + 'exe_time' => $now, + 'exe_ip' => $ENV{'REMOTE_ADDR'}, + 'delflag' => $delflag, + 'logentry' => $storehash, + 'uname' => $uname, + 'udom' => $udom, + } + }; + return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum); } } sub logtouch { my $execdir=$perlvar{'lonDaemons'}; unless (-e "$execdir/logs/lonnet.log") { - open(my $fh,">>$execdir/logs/lonnet.log"); + open(my $fh,">>","$execdir/logs/lonnet.log"); close $fh; } my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3]; @@ -147,7 +156,7 @@ sub logthis { my $execdir=$perlvar{'lonDaemons'}; my $now=time; my $local=localtime($now); - if (open(my $fh,">>$execdir/logs/lonnet.log")) { + if (open(my $fh,">>","$execdir/logs/lonnet.log")) { my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string. print $fh $logstring; close($fh); @@ -160,7 +169,7 @@ sub logperm { my $execdir=$perlvar{'lonDaemons'}; my $now=time; my $local=localtime($now); - if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) { + if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) { print $fh "$now:$message:$local\n"; close($fh); } @@ -195,6 +204,29 @@ sub get_server_timezone { } } +sub get_server_distarch { + my ($lonhost,$ignore_cache) = @_; + if (defined($lonhost)) { + if (!defined(&hostname($lonhost))) { + return; + } + my $cachetime = 12*3600; + if (!$ignore_cache) { + my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost); + if (defined($cached)) { + return $distarch; + } + } + my $rep = &reply('serverdistarch',$lonhost); + unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || + $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' || + $rep eq '') { + return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime); + } + } + return; +} + sub get_server_loncaparev { my ($dom,$lonhost,$ignore_cache,$caller) = @_; if (defined($lonhost)) { @@ -222,7 +254,7 @@ sub get_server_loncaparev { my @ids=¤t_machine_ids(); if (grep(/^\Q$lonhost\E$/,@ids)) { $answer = $perlvar{'lonVersion'}; - if ($answer =~ /^[\'\"]?([\d.\-]+)[\'\"]?$/) { + if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) { $loncaparev = $1; } } else { @@ -230,22 +262,23 @@ sub get_server_loncaparev { if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) { if ($caller eq 'loncron') { my $ua=new LWP::UserAgent; - $ua->timeout(20); + $ua->timeout(4); + my $hostname = &hostname($lonhost); my $protocol = $protocol{$lonhost}; $protocol = 'http' if ($protocol ne 'https'); - my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html'; + my $url = $protocol.'://'.$hostname.'/adm/about.html'; my $request=new HTTP::Request('GET',$url); my $response=$ua->request($request); unless ($response->is_error()) { my $content = $response->content; - if ($content =~ /
VERSION\:\s*([\d.\-]+)<\/p>/) { + if ($content =~ /
VERSION\:\s*([\w.\-]+)<\/p>/) {
$loncaparev = $1;
}
}
} else {
$loncaparev = $loncaparevs{$lonhost};
}
- } elsif ($answer =~ /^[\'\"]?([\d.\-]+)[\'\"]?$/) {
+ } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
$loncaparev = $1;
}
}
@@ -281,6 +314,54 @@ sub get_server_homeID {
return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
}
+sub get_remote_globals {
+ my ($lonhost,$whathash,$ignore_cache) = @_;
+ my ($result,%returnhash,%whatneeded);
+ if (ref($whathash) eq 'HASH') {
+ foreach my $what (sort(keys(%{$whathash}))) {
+ my $hashid = $lonhost.'-'.$what;
+ my ($response,$cached);
+ unless ($ignore_cache) {
+ ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
+ }
+ if (defined($cached)) {
+ $returnhash{$what} = $response;
+ } else {
+ $whatneeded{$what} = 1;
+ }
+ }
+ if (keys(%whatneeded) == 0) {
+ $result = 'ok';
+ } else {
+ my $requested = &freeze_escape(\%whatneeded);
+ my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
+ if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
+ ($rep eq 'unknown_cmd')) {
+ $result = $rep;
+ } else {
+ $result = 'ok';
+ my @pairs=split(/\&/,$rep);
+ foreach my $item (@pairs) {
+ my ($key,$value)=split(/=/,$item,2);
+ my $what = &unescape($key);
+ my $hashid = $lonhost.'-'.$what;
+ $returnhash{$what}=&thaw_unescape($value);
+ &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
+ }
+ }
+ }
+ }
+ return ($result,\%returnhash);
+}
+
+sub remote_devalidate_cache {
+ my ($lonhost,$cachekeys) = @_;
+ my $items;
+ return unless (ref($cachekeys) eq 'ARRAY');
+ my $cachestr = join('&',@{$cachekeys});
+ return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
+}
+
# -------------------------------------------------- Non-critical communication
sub subreply {
my ($cmd,$server)=@_;
@@ -292,7 +373,7 @@ sub subreply {
my $lockfile=$peerfile.".lock";
while (-e $lockfile) { # Need to wait for the lockfile to disappear.
- sleep(1);
+ sleep(0.1);
}
# At this point, either a loncnew parent is listening or an old lonc
# or loncnew child is listening so we can connect or everything's dead.
@@ -310,7 +391,7 @@ sub subreply {
} else {
&create_connection(&hostname($server),$server);
}
- sleep(1); # Try again later if failed connection.
+ sleep(0.1); # Try again later if failed connection.
}
my $answer;
if ($client) {
@@ -329,8 +410,26 @@ sub reply {
unless (defined(&hostname($server))) { return 'no_such_host'; }
my $answer=subreply($cmd,$server);
if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
- &logthis("WARNING:".
- " $cmd to $server returned $answer");
+ my $logged = $cmd;
+ if ($cmd =~ /^encrypt:([^:]+):/) {
+ my $subcmd = $1;
+ if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
+ ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
+ ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
+ (undef,undef,my @rest) = split(/:/,$cmd);
+ if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
+ splice(@rest,2,1,'Hidden');
+ } elsif ($subcmd eq 'passwd') {
+ splice(@rest,2,2,('Hidden','Hidden'));
+ } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
+ ($subcmd eq 'autoexportgrades')) {
+ splice(@rest,3,1,'Hidden');
+ }
+ $logged = join(':',('encrypt:'.$subcmd,@rest));
+ }
+ }
+ &logthis("WARNING:".
+ " $logged to $server returned $answer");
}
return $answer;
}
@@ -339,8 +438,8 @@ sub reply {
sub reconlonc {
my ($lonid) = @_;
- my $hostname = &hostname($lonid);
if ($lonid) {
+ my $hostname = &hostname($lonid);
my $peerfile="$perlvar{'lonSockDir'}/$hostname";
if ($hostname && -e $peerfile) {
&logthis("Trying to reconnect lonc for $lonid ($hostname)");
@@ -358,7 +457,7 @@ sub reconlonc {
&logthis("Trying to reconnect lonc");
my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
- if (open(my $fh,"<$loncfile")) {
+ if (open(my $fh,"<",$loncfile)) {
my $loncpid=<$fh>;
chomp($loncpid);
if (kill 0 => $loncpid) {
@@ -386,7 +485,7 @@ sub critical {
}
my $answer=reply($cmd,$server);
if ($answer eq 'con_lost') {
- &reconlonc("$perlvar{'lonSockDir'}/$server");
+ &reconlonc($server);
my $answer=reply($cmd,$server);
if ($answer eq 'con_lost') {
my $now=time;
@@ -398,16 +497,16 @@ sub critical {
$dumpcount++;
{
my $dfh;
- if (open($dfh,">$dfilename")) {
+ if (open($dfh,">",$dfilename)) {
print $dfh "$cmd\n";
close($dfh);
}
}
- sleep 2;
+ sleep 1;
my $wcmd='';
{
my $dfh;
- if (open($dfh,"<$dfilename")) {
+ if (open($dfh,"<",$dfilename)) {
$wcmd=<$dfh>;
close($dfh);
}
@@ -523,14 +622,52 @@ sub transfer_profile_to_env {
# ---------------------------------------------------- Check for valid session
sub check_for_valid_session {
- my ($r) = @_;
+ my ($r,$name,$userhashref,$domref) = @_;
my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
- my $lonid=$cookies{'lonID'};
+ my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
+ if ($name eq 'lonDAV') {
+ $lonidsdir=$r->dir_config('lonDAVsessDir');
+ } else {
+ $lonidsdir=$r->dir_config('lonIDsDir');
+ if ($name eq '') {
+ $name = 'lonID';
+ }
+ }
+ if ($name eq 'lonID') {
+ $secure = 'lonSID';
+ $linkname = 'lonLinkID';
+ $pubname = 'lonPubID';
+ if (exists($cookies{$secure})) {
+ $lonid=$cookies{$secure};
+ } elsif (exists($cookies{$name})) {
+ $lonid=$cookies{$name};
+ } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
+ $lonid=$cookies{$linkname};
+ } elsif (exists($cookies{$pubname})) {
+ $lonid=$cookies{$pubname};
+ }
+ } else {
+ $lonid=$cookies{$name};
+ }
return undef if (!$lonid);
my $handle=&LONCAPA::clean_handle($lonid->value);
- my $lonidsdir=$r->dir_config('lonIDsDir');
- return undef if (!-e "$lonidsdir/$handle.id");
+ if (-l "$lonidsdir/$handle.id") {
+ my $link = readlink("$lonidsdir/$handle.id");
+ if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
+ $handle = $1;
+ }
+ }
+ if (!-e "$lonidsdir/$handle.id") {
+ if ((ref($domref)) && ($name eq 'lonID') &&
+ ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
+ my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
+ if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
+ $$domref = $possudom;
+ }
+ }
+ return undef;
+ }
my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
return undef if (!$opened);
@@ -544,8 +681,16 @@ sub check_for_valid_session {
if (!defined($disk_env{'user.name'})
|| !defined($disk_env{'user.domain'})) {
+ untie(%disk_env);
return undef;
}
+
+ if (ref($userhashref) eq 'HASH') {
+ $userhashref->{'name'} = $disk_env{'user.name'};
+ $userhashref->{'domain'} = $disk_env{'user.domain'};
+ }
+ untie(%disk_env);
+
return $handle;
}
@@ -569,6 +714,37 @@ sub timed_flock {
}
}
+sub get_sessionfile_vars {
+ my ($handle,$lonidsdir,$storearr) = @_;
+ my %returnhash;
+ unless (ref($storearr) eq 'ARRAY') {
+ return %returnhash;
+ }
+ if (-l "$lonidsdir/$handle.id") {
+ my $link = readlink("$lonidsdir/$handle.id");
+ if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
+ $handle = $1;
+ }
+ }
+ if ((-e "$lonidsdir/$handle.id") &&
+ ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
+ my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
+ if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
+ if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
+ flock($idf,LOCK_SH);
+ if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
+ &GDBM_READER(),0640)) {
+ foreach my $item (@{$storearr}) {
+ $returnhash{$item} = $disk_env{$item};
+ }
+ untie(%disk_env);
+ }
+ }
+ }
+ }
+ return %returnhash;
+}
+
# ---------------------------------------------------------- Append Environment
sub appenv {
@@ -579,7 +755,7 @@ sub appenv {
if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
$refused = 1;
if (ref($roles) eq 'ARRAY') {
- my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
+ my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
if (grep(/^\Q$role\E$/,@{$roles})) {
$refused = 0;
}
@@ -594,16 +770,19 @@ sub appenv {
$env{$key}=$newenv->{$key};
}
}
- my $opened = open(my $env_file,'+<',$env{'user.environment'});
- if ($opened
- && &timed_flock($env_file,LOCK_EX)
- &&
- tie(my %disk_env,'GDBM_File',$env{'user.environment'},
- (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
- while (my ($key,$value) = each(%{$newenv})) {
- $disk_env{$key} = $value;
- }
- untie(%disk_env);
+ my $lonids = $perlvar{'lonIDsDir'};
+ if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
+ my $opened = open(my $env_file,'+<',$env{'user.environment'});
+ if ($opened
+ && &timed_flock($env_file,LOCK_EX)
+ &&
+ tie(my %disk_env,'GDBM_File',$env{'user.environment'},
+ (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
+ while (my ($key,$value) = each(%{$newenv})) {
+ $disk_env{$key} = $value;
+ }
+ untie(%disk_env);
+ }
}
}
return 'ok';
@@ -611,11 +790,20 @@ sub appenv {
# ----------------------------------------------------- Delete from Environment
sub delenv {
- my ($delthis,$regexp) = @_;
- if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
- &logthis("WARNING: ".
- "Attempt to delete from environment ".$delthis);
- return 'error';
+ my ($delthis,$regexp,$roles) = @_;
+ if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
+ my $refused = 1;
+ if (ref($roles) eq 'ARRAY') {
+ my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
+ if (grep(/^\Q$role\E$/,@{$roles})) {
+ $refused = 0;
+ }
+ }
+ if ($refused) {
+ &logthis("WARNING: ".
+ "Attempt to delete from environment ".$delthis);
+ return 'error';
+ }
}
my $opened = open(my $env_file,'+<',$env{'user.environment'});
if ($opened
@@ -710,6 +898,7 @@ sub userload {
while ($filename=readdir(LONIDS)) {
next if ($filename eq '.' || $filename eq '..');
next if ($filename =~ /publicuser_\d+\.id/);
+ next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
if ($curtime-$mtime < 1800) { $numusers++; }
}
@@ -727,34 +916,51 @@ sub userload {
# ------------------------------ Find server with least workload from spare.tab
sub spareserver {
- my ($loadpercent,$userloadpercent,$want_server_name) = @_;
+ my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
my $spare_server;
if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
: $userloadpercent;
-
- foreach my $try_server (@{ $spareid{'primary'} }) {
- ($spare_server, $lowest_load) =
- &compare_server_load($try_server, $spare_server, $lowest_load);
- }
-
- my $found_server = ($spare_server ne '' && $lowest_load < 100);
+ my ($uint_dom,$remotesessions);
+ if (($udom ne '') && (&domain($udom) ne '')) {
+ my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
+ $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
+ my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
+ $remotesessions = $udomdefaults{'remotesessions'};
+ }
+ my $spareshash = &this_host_spares($udom);
+ if (ref($spareshash) eq 'HASH') {
+ if (ref($spareshash->{'primary'}) eq 'ARRAY') {
+ foreach my $try_server (@{ $spareshash->{'primary'} }) {
+ next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
+ $try_server));
+ ($spare_server, $lowest_load) =
+ &compare_server_load($try_server, $spare_server, $lowest_load);
+ }
+ }
- if (!$found_server) {
- foreach my $try_server (@{ $spareid{'default'} }) {
- ($spare_server, $lowest_load) =
- &compare_server_load($try_server, $spare_server, $lowest_load);
- }
+ my $found_server = ($spare_server ne '' && $lowest_load < 100);
+
+ if (!$found_server) {
+ if (ref($spareshash->{'default'}) eq 'ARRAY') {
+ foreach my $try_server (@{ $spareshash->{'default'} }) {
+ next unless (&spare_can_host($udom,$uint_dom,
+ $remotesessions,$try_server));
+ ($spare_server, $lowest_load) =
+ &compare_server_load($try_server, $spare_server, $lowest_load);
+ }
+ }
+ }
}
if (!$want_server_name) {
- my $protocol = 'http';
- if ($protocol{$spare_server} eq 'https') {
- $protocol = $protocol{$spare_server};
- }
if (defined($spare_server)) {
my $hostname = &hostname($spare_server);
- if (defined($hostname)) {
+ if (defined($hostname)) {
+ my $protocol = 'http';
+ if ($protocol{$spare_server} eq 'https') {
+ $protocol = $protocol{$spare_server};
+ }
$spare_server = $protocol.'://'.$hostname;
}
}
@@ -763,13 +969,23 @@ sub spareserver {
}
sub compare_server_load {
- my ($try_server, $spare_server, $lowest_load) = @_;
+ my ($try_server, $spare_server, $lowest_load, $required) = @_;
+
+ if ($required) {
+ my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
+ my $remoterev = &get_server_loncaparev(undef,$try_server);
+ my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
+ if (($major eq '' && $minor eq '') ||
+ (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
+ return ($spare_server,$lowest_load);
+ }
+ }
my $loadans = &reply('load', $try_server);
my $userloadans = &reply('userload',$try_server);
if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
- return; #didn't get a number from the server
+ return ($spare_server, $lowest_load); #didn't get a number from the server
}
my $load;
@@ -795,13 +1011,106 @@ sub compare_server_load {
# --------------------------- ask offload servers if user already has a session
sub find_existing_session {
my ($udom,$uname) = @_;
- foreach my $try_server (@{ $spareid{'primary'} },
- @{ $spareid{'default'} }) {
- return $try_server if (&has_user_session($try_server, $udom, $uname));
+ my $spareshash = &this_host_spares($udom);
+ if (ref($spareshash) eq 'HASH') {
+ if (ref($spareshash->{'primary'}) eq 'ARRAY') {
+ foreach my $try_server (@{ $spareshash->{'primary'} }) {
+ return $try_server if (&has_user_session($try_server, $udom, $uname));
+ }
+ }
+ if (ref($spareshash->{'default'}) eq 'ARRAY') {
+ foreach my $try_server (@{ $spareshash->{'default'} }) {
+ return $try_server if (&has_user_session($try_server, $udom, $uname));
+ }
+ }
+ }
+ return;
+}
+
+# check if user's browser sent load balancer cookie and server still has session
+# and is not overloaded.
+sub check_for_balancer_cookie {
+ my ($r,$update_mtime) = @_;
+ my ($otherserver,$cookie);
+ my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
+ if (exists($cookies{'balanceID'})) {
+ my $balid = $cookies{'balanceID'};
+ $cookie=&LONCAPA::clean_handle($balid->value);
+ my $balancedir=$r->dir_config('lonBalanceDir');
+ if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
+ if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
+ my ($possudom,$possuname) = ($1,$2);
+ my $has_session = 0;
+ if ((&domain($possudom) ne '') &&
+ (&homeserver($possuname,$possudom) ne 'no_host')) {
+ my $try_server;
+ my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
+ if ($opened) {
+ flock($idf,LOCK_SH);
+ while (my $line = <$idf>) {
+ chomp($line);
+ if (&hostname($line) ne '') {
+ $try_server = $line;
+ last;
+ }
+ }
+ close($idf);
+ if (($try_server) &&
+ (&has_user_session($try_server,$possudom,$possuname))) {
+ my $lowest_load = 30000;
+ ($otherserver,$lowest_load) =
+ &compare_server_load($try_server,undef,$lowest_load);
+ if ($otherserver ne '' && $lowest_load < 100) {
+ $has_session = 1;
+ } else {
+ undef($otherserver);
+ }
+ }
+ }
+ }
+ if ($has_session) {
+ if ($update_mtime) {
+ my $atime = my $mtime = time;
+ utime($atime,$mtime,"$balancedir/$cookie.id");
+ }
+ } else {
+ unlink("$balancedir/$cookie.id");
+ }
+ }
+ }
+ }
+ return ($otherserver,$cookie);
+}
+
+sub updatebalcookie {
+ my ($cookie,$balancer,$lastentry)=@_;
+ if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
+ my ($udom,$uname) = ($1,$2);
+ my $uprimary_id = &domain($udom,'primary');
+ my $uintdom = &internet_dom($uprimary_id);
+ my $intdom = &internet_dom($balancer);
+ my $serverhomedom = &host_domain($balancer);
+ if (($uintdom ne '') && ($uintdom eq $intdom)) {
+ return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
+ }
}
return;
}
+sub delbalcookie {
+ my ($cookie,$balancer) =@_;
+ if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
+ my ($udom,$uname) = ($1,$2);
+ my $uprimary_id = &domain($udom,'primary');
+ my $uintdom = &internet_dom($uprimary_id);
+ my $intdom = &internet_dom($balancer);
+ my $serverhomedom = &host_domain($balancer);
+ if (($uintdom ne '') && ($uintdom eq $intdom)) {
+ return &reply('delbalcookie:'.&escape($cookie),$balancer);
+ }
+ }
+}
+
# -------------------------------- ask if server already has a session for user
sub has_user_session {
my ($lonid,$udom,$uname) = @_;
@@ -815,22 +1124,79 @@ sub has_user_session {
# --------- determine least loaded server in a user's domain which allows login
sub choose_server {
- my ($udom) = @_;
+ my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
my %domconfhash = &Apache::loncommon::get_domainconf($udom);
my %servers = &get_servers($udom);
my $lowest_load = 30000;
- my ($login_host,$hostname);
+ my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
+ if ($skiploadbal) {
+ ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
+ unless (defined($cached)) {
+ my $cachetime = 60*60*24;
+ my %domconfig =
+ &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
+ if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
+ $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
+ $cachetime);
+ }
+ }
+ }
foreach my $lonhost (keys(%servers)) {
- my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
- if ($loginvia eq '') {
+ my $loginvia;
+ if ($skiploadbal) {
+ if (ref($balancers) eq 'HASH') {
+ next if (exists($balancers->{$lonhost}));
+ }
+ }
+ if ($checkloginvia) {
+ $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
+ if ($loginvia) {
+ my ($server,$path) = split(/:/,$loginvia);
+ ($login_host, $lowest_load) =
+ &compare_server_load($server, $login_host, $lowest_load, $required);
+ if ($login_host eq $server) {
+ $portal_path = $path;
+ $isredirect = 1;
+ }
+ } else {
+ ($login_host, $lowest_load) =
+ &compare_server_load($lonhost, $login_host, $lowest_load, $required);
+ if ($login_host eq $lonhost) {
+ $portal_path = '';
+ $isredirect = '';
+ }
+ }
+ } else {
($login_host, $lowest_load) =
- &compare_server_load($lonhost, $login_host, $lowest_load);
+ &compare_server_load($lonhost, $login_host, $lowest_load, $required);
}
}
if ($login_host ne '') {
- $hostname = $servers{$login_host};
+ $hostname = &hostname($login_host);
+ }
+ return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
+}
+
+sub get_course_sessions {
+ my ($cnum,$cdom,$lastactivity) = @_;
+ my %servers = &internet_dom_servers($cdom);
+ my %returnhash;
+ foreach my $server (sort(keys(%servers))) {
+ my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
+ my @pairs=split(/\&/,$rep);
+ unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
+ foreach my $item (@pairs) {
+ my ($key,$value)=split(/=/,$item,2);
+ $key = &unescape($key);
+ next if ($key =~ /^error: 2 /);
+ if (exists($returnhash{$key})) {
+ next if ($value < $returnhash{$key});
+ }
+ $returnhash{$key}=$value;
+ }
+ }
}
- return ($login_host,$hostname);
+ return %returnhash;
}
# --------------------------------------------- Try to change a user's password
@@ -868,6 +1234,9 @@ sub changepass {
} elsif ($answer =~ "invalid_client") {
&logthis("$server refused to change $uname in $udom password because ".
"it was a reset by e-mail originating from an invalid server.");
+ } elsif ($answer =~ "^prioruse") {
+ &logthis("$server refused to change $uname in $udom password because ".
+ "the password had been used before");
}
return $answer;
}
@@ -971,15 +1340,19 @@ sub can_host_session {
}
if ($canhost) {
if (ref($hostedsessions) eq 'HASH') {
+ my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
+ my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
- if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
+ if (($uint_dom ne '') &&
+ (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
$canhost = 0;
} else {
$canhost = 1;
}
}
if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
- if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
+ if (($uint_dom ne '') &&
+ (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
$canhost = 1;
} else {
$canhost = 0;
@@ -990,6 +1363,379 @@ sub can_host_session {
return $canhost;
}
+sub spare_can_host {
+ my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
+ my $canhost=1;
+ my $try_server_hostname = &hostname($try_server);
+ my $serverhomeID = &get_server_homeID($try_server_hostname);
+ my $serverhomedom = &host_domain($serverhomeID);
+ my %defdomdefaults = &get_domain_defaults($serverhomedom);
+ if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
+ if ($defdomdefaults{'offloadnow'}{$try_server}) {
+ $canhost = 0;
+ }
+ }
+ if (($canhost) && ($uint_dom)) {
+ my @intdoms;
+ my $internet_names = &get_internet_names($try_server);
+ if (ref($internet_names) eq 'ARRAY') {
+ @intdoms = @{$internet_names};
+ }
+ unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
+ my $remoterev = &get_server_loncaparev(undef,$try_server);
+ $canhost = &can_host_session($udom,$try_server,$remoterev,
+ $remotesessions,
+ $defdomdefaults{'hostedsessions'});
+ }
+ }
+ return $canhost;
+}
+
+sub this_host_spares {
+ my ($dom) = @_;
+ my ($dom_in_use,$lonhost_in_use,$result);
+ my @hosts = ¤t_machine_ids();
+ foreach my $lonhost (@hosts) {
+ if (&host_domain($lonhost) eq $dom) {
+ $dom_in_use = $dom;
+ $lonhost_in_use = $lonhost;
+ last;
+ }
+ }
+ if ($dom_in_use ne '') {
+ $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
+ }
+ if (ref($result) ne 'HASH') {
+ $lonhost_in_use = $perlvar{'lonHostID'};
+ $dom_in_use = &host_domain($lonhost_in_use);
+ $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
+ if (ref($result) ne 'HASH') {
+ $result = \%spareid;
+ }
+ }
+ return $result;
+}
+
+sub spares_for_offload {
+ my ($dom_in_use,$lonhost_in_use) = @_;
+ my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
+ if (defined($cached)) {
+ return $result;
+ } else {
+ my $cachetime = 60*60*24;
+ my %domconfig =
+ &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
+ if (ref($domconfig{'usersessions'}) eq 'HASH') {
+ if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
+ if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
+ return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
+ }
+ }
+ }
+ }
+ return;
+}
+
+sub get_lonbalancer_config {
+ my ($servers) = @_;
+ my ($currbalancer,$currtargets);
+ if (ref($servers) eq 'HASH') {
+ foreach my $server (keys(%{$servers})) {
+ my %what = (
+ spareid => 1,
+ perlvar => 1,
+ );
+ my ($result,$returnhash) = &get_remote_globals($server,\%what);
+ if ($result eq 'ok') {
+ if (ref($returnhash) eq 'HASH') {
+ if (ref($returnhash->{'perlvar'}) eq 'HASH') {
+ if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
+ $currbalancer = $server;
+ $currtargets = {};
+ if (ref($returnhash->{'spareid'}) eq 'HASH') {
+ if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
+ $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
+ }
+ if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
+ $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
+ }
+ }
+ last;
+ }
+ }
+ }
+ }
+ }
+ }
+ return ($currbalancer,$currtargets);
+}
+
+sub check_loadbalancing {
+ my ($uname,$udom,$caller) = @_;
+ my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
+ $rule_in_effect,$offloadto,$otherserver,$setcookie);
+ my $lonhost = $perlvar{'lonHostID'};
+ my @hosts = ¤t_machine_ids();
+ my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
+ my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
+ my $intdom = &Apache::lonnet::internet_dom($lonhost);
+ my $serverhomedom = &host_domain($lonhost);
+ my $domneedscache;
+ my $cachetime = 60*60*24;
+
+ if (($uintdom ne '') && ($uintdom eq $intdom)) {
+ $dom_in_use = $udom;
+ $homeintdom = 1;
+ } else {
+ $dom_in_use = $serverhomedom;
+ }
+ my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
+ unless (defined($cached)) {
+ my %domconfig =
+ &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
+ if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
+ $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
+ } else {
+ $domneedscache = $dom_in_use;
+ }
+ }
+ if (ref($result) eq 'HASH') {
+ ($is_balancer,$currtargets,$currrules,$setcookie) =
+ &check_balancer_result($result,@hosts);
+ if ($is_balancer) {
+ if (ref($currrules) eq 'HASH') {
+ if ($homeintdom) {
+ if ($uname ne '') {
+ if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
+ my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
+ if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
+ $rule_in_effect = $currrules->{'_LC_author'};
+ } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
+ $rule_in_effect = $currrules->{'_LC_adv'}
+ }
+ }
+ if ($rule_in_effect eq '') {
+ my %userenv = &userenvironment($udom,$uname,'inststatus');
+ if ($userenv{'inststatus'} ne '') {
+ my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
+ my ($othertitle,$usertypes,$types) =
+ &Apache::loncommon::sorted_inst_types($udom);
+ if (ref($types) eq 'ARRAY') {
+ foreach my $type (@{$types}) {
+ if (grep(/^\Q$type\E$/,@statuses)) {
+ if (exists($currrules->{$type})) {
+ $rule_in_effect = $currrules->{$type};
+ }
+ }
+ }
+ }
+ } else {
+ if (exists($currrules->{'default'})) {
+ $rule_in_effect = $currrules->{'default'};
+ }
+ }
+ }
+ } else {
+ if (exists($currrules->{'default'})) {
+ $rule_in_effect = $currrules->{'default'};
+ }
+ }
+ } else {
+ if ($currrules->{'_LC_external'} ne '') {
+ $rule_in_effect = $currrules->{'_LC_external'};
+ }
+ }
+ $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
+ $uname,$udom);
+ }
+ }
+ } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
+ ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
+ unless (defined($cached)) {
+ my %domconfig =
+ &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
+ if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
+ $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
+ } else {
+ $domneedscache = $serverhomedom;
+ }
+ }
+ if (ref($result) eq 'HASH') {
+ ($is_balancer,$currtargets,$currrules,$setcookie) =
+ &check_balancer_result($result,@hosts);
+ if ($is_balancer) {
+ if (ref($currrules) eq 'HASH') {
+ if ($currrules->{'_LC_internetdom'} ne '') {
+ $rule_in_effect = $currrules->{'_LC_internetdom'};
+ }
+ }
+ $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
+ $uname,$udom);
+ }
+ } else {
+ if ($perlvar{'lonBalancer'} eq 'yes') {
+ $is_balancer = 1;
+ $offloadto = &this_host_spares($dom_in_use);
+ }
+ unless (defined($cached)) {
+ $domneedscache = $serverhomedom;
+ }
+ }
+ } else {
+ if ($perlvar{'lonBalancer'} eq 'yes') {
+ $is_balancer = 1;
+ $offloadto = &this_host_spares($dom_in_use);
+ }
+ unless (defined($cached)) {
+ $domneedscache = $serverhomedom;
+ }
+ }
+ if ($domneedscache) {
+ &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
+ }
+ if (($is_balancer) && ($caller ne 'switchserver')) {
+ my $lowest_load = 30000;
+ if (ref($offloadto) eq 'HASH') {
+ if (ref($offloadto->{'primary'}) eq 'ARRAY') {
+ foreach my $try_server (@{$offloadto->{'primary'}}) {
+ ($otherserver,$lowest_load) =
+ &compare_server_load($try_server,$otherserver,$lowest_load);
+ }
+ }
+ my $found_server = ($otherserver ne '' && $lowest_load < 100);
+
+ if (!$found_server) {
+ if (ref($offloadto->{'default'}) eq 'ARRAY') {
+ foreach my $try_server (@{$offloadto->{'default'}}) {
+ ($otherserver,$lowest_load) =
+ &compare_server_load($try_server,$otherserver,$lowest_load);
+ }
+ }
+ }
+ } elsif (ref($offloadto) eq 'ARRAY') {
+ if (@{$offloadto} == 1) {
+ $otherserver = $offloadto->[0];
+ } elsif (@{$offloadto} > 1) {
+ foreach my $try_server (@{$offloadto}) {
+ ($otherserver,$lowest_load) =
+ &compare_server_load($try_server,$otherserver,$lowest_load);
+ }
+ }
+ }
+ unless ($caller eq 'login') {
+ if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
+ $is_balancer = 0;
+ if ($uname ne '' && $udom ne '') {
+ if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
+ &appenv({'user.loadbalexempt' => $lonhost,
+ 'user.loadbalcheck.time' => time});
+ }
+ }
+ }
+ }
+ }
+ if (($is_balancer) && (!$homeintdom)) {
+ undef($setcookie);
+ }
+ return ($is_balancer,$otherserver,$setcookie);
+}
+
+sub check_balancer_result {
+ my ($result,@hosts) = @_;
+ my ($is_balancer,$currtargets,$currrules,$setcookie);
+ if (ref($result) eq 'HASH') {
+ if ($result->{'lonhost'} ne '') {
+ my $currbalancer = $result->{'lonhost'};
+ if (grep(/^\Q$currbalancer\E$/,@hosts)) {
+ $is_balancer = 1;
+ $currtargets = $result->{'targets'};
+ $currrules = $result->{'rules'};
+ }
+ } else {
+ foreach my $key (keys(%{$result})) {
+ if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
+ (ref($result->{$key}) eq 'HASH')) {
+ $is_balancer = 1;
+ $currrules = $result->{$key}{'rules'};
+ $currtargets = $result->{$key}{'targets'};
+ $setcookie = $result->{$key}{'cookie'};
+ last;
+ }
+ }
+ }
+ }
+ return ($is_balancer,$currtargets,$currrules,$setcookie);
+}
+
+sub get_loadbalancer_targets {
+ my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
+ my $offloadto;
+ if ($rule_in_effect eq 'none') {
+ return [$perlvar{'lonHostID'}];
+ } elsif ($rule_in_effect eq '') {
+ $offloadto = $currtargets;
+ } else {
+ if ($rule_in_effect eq 'homeserver') {
+ my $homeserver = &homeserver($uname,$udom);
+ if ($homeserver ne 'no_host') {
+ $offloadto = [$homeserver];
+ }
+ } elsif ($rule_in_effect eq 'externalbalancer') {
+ my %domconfig =
+ &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
+ if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
+ if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
+ if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
+ $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
+ }
+ }
+ } else {
+ my %servers = &internet_dom_servers($udom);
+ my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
+ if (&hostname($remotebalancer) ne '') {
+ $offloadto = [$remotebalancer];
+ }
+ }
+ } elsif (&hostname($rule_in_effect) ne '') {
+ $offloadto = [$rule_in_effect];
+ }
+ }
+ return $offloadto;
+}
+
+sub internet_dom_servers {
+ my ($dom) = @_;
+ my (%uniqservers,%servers);
+ my $primaryserver = &hostname(&domain($dom,'primary'));
+ my @machinedoms = &machine_domains($primaryserver);
+ foreach my $mdom (@machinedoms) {
+ my %currservers = %servers;
+ my %server = &get_servers($mdom);
+ %servers = (%currservers,%server);
+ }
+ my %by_hostname;
+ foreach my $id (keys(%servers)) {
+ push(@{$by_hostname{$servers{$id}}},$id);
+ }
+ foreach my $hostname (sort(keys(%by_hostname))) {
+ if (@{$by_hostname{$hostname}} > 1) {
+ my $match = 0;
+ foreach my $id (@{$by_hostname{$hostname}}) {
+ if (&host_domain($id) eq $dom) {
+ $uniqservers{$id} = $hostname;
+ $match = 1;
+ }
+ }
+ unless ($match) {
+ $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
+ }
+ } else {
+ $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
+ }
+ }
+ return %uniqservers;
+}
+
# ---------------------- Find the homebase for a user from domain's lib servers
my %homecache;
@@ -1023,7 +1769,7 @@ sub idget {
my %servers = &get_servers($udom,'library');
foreach my $tryserver (keys(%servers)) {
- my $idlist=join('&',@ids);
+ my $idlist=join('&', map { &escape($_); } @ids);
$idlist=~tr/A-Z/a-z/;
my $reply=&reply("idget:$udom:".$idlist,$tryserver);
my @answer=();
@@ -1033,7 +1779,7 @@ sub idget {
my $i;
for ($i=0;$i<=$#ids;$i++) {
if ($answer[$i]) {
- $returnhash{$ids[$i]}=$answer[$i];
+ $returnhash{$ids[$i]}=&unescape($answer[$i]);
}
}
}
@@ -1075,24 +1821,52 @@ sub idput {
}
}
-# ------------------------------dump from db file owned by domainconfig user
-sub dump_dom {
- my ($namespace,$udom,$regexp,$range)=@_;
- if (!$udom) {
- $udom=$env{'user.domain'};
+# ---------------------------------------- Delete unwanted IDs from ids.db file
+
+sub iddel {
+ my ($udom,$idshashref,$uhome)=@_;
+ my %result=();
+ unless (ref($idshashref) eq 'HASH') {
+ return %result;
}
- my %returnhash;
- if ($udom) {
- my $uname = &get_domainconfiguser($udom);
- %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
+ my %servers=();
+ while (my ($id,$uname) = each(%{$idshashref})) {
+ my $uhom;
+ if ($uhome) {
+ $uhom = $uhome;
+ } else {
+ $uhom=&homeserver($uname,$udom);
+ }
+ if ($uhom ne 'no_host') {
+ if ($servers{$uhom}) {
+ $servers{$uhom}.='&'.&escape($id);
+ } else {
+ $servers{$uhom}=&escape($id);
+ }
+ }
}
- return %returnhash;
+ foreach my $server (keys(%servers)) {
+ $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
+ }
+ return %result;
+}
+
+# ------------------------------dump from db file owned by domainconfig user
+sub dump_dom {
+ my ($namespace, $udom, $regexp) = @_;
+
+ $udom ||= $env{'user.domain'};
+
+ return () unless $udom;
+
+ return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
}
# ------------------------------------------ get items from domain db files
sub get_dom {
my ($namespace,$storearr,$udom,$uhome)=@_;
+ return if ($udom eq 'public');
my $items='';
foreach my $item (@$storearr) {
$items.=&escape($item).'&';
@@ -1100,6 +1874,7 @@ sub get_dom {
$items=~s/\&$//;
if (!$udom) {
$udom=$env{'user.domain'};
+ return if ($udom eq 'public');
if (defined(&domain($udom,'primary'))) {
$uhome=&domain($udom,'primary');
} else {
@@ -1203,14 +1978,13 @@ sub retrieve_inst_usertypes {
my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
(ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
- %returnhash = %{$domdefs{'inststatustypes'}};
- @order = @{$domdefs{'inststatusorder'}};
+ return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
} else {
if (defined(&domain($udom,'primary'))) {
my $uhome=&domain($udom,'primary');
my $rep=&reply("inst_usertypes:$udom",$uhome);
if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
- &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
+ &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
return (\%returnhash,\@order);
}
my ($hashitems,$orderitems) = split(/:/,$rep);
@@ -1226,15 +2000,15 @@ sub retrieve_inst_usertypes {
push(@order,&unescape($item));
}
} else {
- &logthis("get_dom failed - no primary domain server for $udom");
+ &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
}
+ return (\%returnhash,\@order);
}
- return (\%returnhash,\@order);
}
sub is_domainimage {
my ($url) = @_;
- if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
+ if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
if (&domain($1) ne '') {
return '1';
}
@@ -1249,13 +2023,24 @@ sub inst_directory_query {
my $homeserver = &domain($udom,'primary');
my $outcome;
if ($homeserver ne '') {
+ unless ($homeserver eq $perlvar{'lonHostID'}) {
+ if ($srch->{'srchby'} eq 'email') {
+ my $lcrev = &get_server_loncaparev($udom,$homeserver);
+ my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
+ if (($major eq '' && $minor eq '') || ($major < 2) ||
+ (($major == 2) && ($minor < 11)) ||
+ (($major == 2) && ($minor == 11) && ($subver < 3))) {
+ return;
+ }
+ }
+ }
my $queryid=&reply("querysend:instdirsearch:".
&escape($srch->{'srchby'}).':'.
&escape($srch->{'srchterm'}).':'.
&escape($srch->{'srchtype'}),$homeserver);
my $host=&hostname($homeserver);
if ($queryid !~/^\Q$host\E\_/) {
- &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
+ &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
return;
}
my $response = &get_query_reply($queryid);
@@ -1290,6 +2075,15 @@ sub usersearch {
my $query = 'usersearch';
foreach my $tryserver (keys(%libserv)) {
if (&host_domain($tryserver) eq $dom) {
+ unless ($tryserver eq $perlvar{'lonHostID'}) {
+ if ($srch->{'srchby'} eq 'email') {
+ my $lcrev = &get_server_loncaparev($dom,$tryserver);
+ my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
+ next if (($major eq '' && $minor eq '') || ($major < 2) ||
+ (($major == 2) && ($minor < 11)) ||
+ (($major == 2) && ($minor == 11) && ($subver < 3)));
+ }
+ }
my $host=&hostname($tryserver);
my $queryid=
&reply("querysend:".&escape($query).':'.
@@ -1375,6 +2169,63 @@ sub get_instuser {
return ($outcome,%userinfo);
}
+sub get_multiple_instusers {
+ my ($udom,$users,$caller) = @_;
+ my ($outcome,$results);
+ if (ref($users) eq 'HASH') {
+ my $count = keys(%{$users});
+ my $requested = &freeze_escape($users);
+ my $homeserver = &domain($udom,'primary');
+ if ($homeserver ne '') {
+ my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
+ my $host=&hostname($homeserver);
+ if ($queryid !~/^\Q$host\E\_/) {
+ &logthis('get_multiple_instusers invalid queryid: '.$queryid.
+ ' for host: '.$homeserver.'in domain '.$udom);
+ return ($outcome,$results);
+ }
+ my $response = &get_query_reply($queryid);
+ my $maxtries = 5;
+ if ($count > 100) {
+ $maxtries = 1+int($count/20);
+ }
+ my $tries = 1;
+ while (($response=~/^timeout/) && ($tries <= $maxtries)) {
+ $response = &get_query_reply($queryid);
+ $tries ++;
+ }
+ if ($response eq '') {
+ $results = {};
+ foreach my $key (keys(%{$users})) {
+ my ($uname,$id);
+ if ($caller eq 'id') {
+ $id = $key;
+ } else {
+ $uname = $key;
+ }
+ my ($resp,%info) = &get_instuser($udom,$uname,$id);
+ $outcome = $resp;
+ if ($resp eq 'ok') {
+ %{$results} = (%{$results}, %info);
+ } else {
+ last;
+ }
+ }
+ } elsif(!&error($response) && ($response ne 'refused')) {
+ if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
+ $outcome = $response;
+ } else {
+ ($outcome,my $userdata) = split(/=/,$response,2);
+ if ($outcome eq 'ok') {
+ $results = &thaw_unescape($userdata);
+ }
+ }
+ }
+ }
+ }
+ return ($outcome,$results);
+}
+
sub inst_rulecheck {
my ($udom,$uname,$id,$item,$rules) = @_;
my %returnhash;
@@ -1454,25 +2305,36 @@ sub inst_userrules {
# ------------- Get Authentication, Language and User Tools Defaults for Domain
sub get_domain_defaults {
- my ($domain) = @_;
+ my ($domain,$ignore_cache) = @_;
+ return if (($domain eq '') || ($domain eq 'public'));
my $cachetime = 60*60*24;
- my ($result,$cached)=&is_cached_new('domdefaults',$domain);
- if (defined($cached)) {
- if (ref($result) eq 'HASH') {
- return %{$result};
+ unless ($ignore_cache) {
+ my ($result,$cached)=&is_cached_new('domdefaults',$domain);
+ if (defined($cached)) {
+ if (ref($result) eq 'HASH') {
+ return %{$result};
+ }
}
}
my %domdefaults;
my %domconfig =
&Apache::lonnet::get_dom('configuration',['defaults','quotas',
'requestcourses','inststatus',
- 'coursedefaults','usersessions'],$domain);
+ 'coursedefaults','usersessions',
+ 'requestauthor','selfenrollment',
+ 'coursecategories','autoenroll',
+ 'helpsettings'],$domain);
+ my @coursetypes = ('official','unofficial','community','textbook');
if (ref($domconfig{'defaults'}) eq 'HASH') {
$domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
$domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
$domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
$domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
$domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
+ $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
+ $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
+ $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
+ $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
} else {
$domdefaults{'lang_def'} = &domain($domain,'lang_def');
$domdefaults{'auth_def'} = &domain($domain,'auth_def');
@@ -1483,27 +2345,64 @@ sub get_domain_defaults {
$domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
} else {
$domdefaults{'defaultquota'} = $domconfig{'quotas'};
- }
- my @usertools = ('aboutme','blog','portfolio');
+ }
+ my @usertools = ('aboutme','blog','webdav','portfolio');
foreach my $item (@usertools) {
if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
$domdefaults{$item} = $domconfig{'quotas'}{$item};
}
}
+ if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
+ $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
+ }
}
if (ref($domconfig{'requestcourses'}) eq 'HASH') {
- foreach my $item ('official','unofficial','community') {
+ foreach my $item ('official','unofficial','community','textbook') {
$domdefaults{$item} = $domconfig{'requestcourses'}{$item};
}
}
+ if (ref($domconfig{'requestauthor'}) eq 'HASH') {
+ $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
+ }
if (ref($domconfig{'inststatus'}) eq 'HASH') {
- foreach my $item ('inststatustypes','inststatusorder') {
+ foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
$domdefaults{$item} = $domconfig{'inststatus'}{$item};
}
}
if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
- foreach my $item ('canuse_pdfforms') {
- $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
+ $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
+ $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
+ if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
+ $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
+ }
+ foreach my $type (@coursetypes) {
+ if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
+ unless ($type eq 'community') {
+ $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
+ }
+ }
+ if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
+ $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
+ }
+ if ($domdefaults{'postsubmit'} eq 'on') {
+ if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
+ $domdefaults{$type.'postsubtimeout'} =
+ $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
+ }
+ }
+ }
+ if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
+ if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
+ my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
+ if (@clonecodes) {
+ $domdefaults{'canclone'} = join('+',@clonecodes);
+ }
+ }
+ } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
+ $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
+ }
+ if ($domconfig{'coursedefaults'}{'texengine'}) {
+ $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
}
}
if (ref($domconfig{'usersessions'}) eq 'HASH') {
@@ -1513,12 +2412,143 @@ sub get_domain_defaults {
if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
$domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
}
+ if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
+ $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
+ }
+ }
+ if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
+ if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
+ my @settings = ('types','registered','enroll_dates','access_dates','section',
+ 'approval','limit');
+ foreach my $type (@coursetypes) {
+ if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
+ my @mgrdc = ();
+ foreach my $item (@settings) {
+ if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
+ push(@mgrdc,$item);
+ }
+ }
+ if (@mgrdc) {
+ $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
+ }
+ }
+ }
+ }
+ if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
+ foreach my $type (@coursetypes) {
+ if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
+ foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
+ $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
+ }
+ }
+ }
+ }
+ }
+ if (ref($domconfig{'coursecategories'}) eq 'HASH') {
+ $domdefaults{'catauth'} = 'std';
+ $domdefaults{'catunauth'} = 'std';
+ if ($domconfig{'coursecategories'}{'auth'}) {
+ $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
+ }
+ if ($domconfig{'coursecategories'}{'unauth'}) {
+ $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
+ }
+ }
+ if (ref($domconfig{'autoenroll'}) eq 'HASH') {
+ $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
}
- &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
- $cachetime);
+ if (ref($domconfig{'helpsettings'}) eq 'HASH') {
+ $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
+ if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
+ $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
+ }
+ }
+ &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
return %domdefaults;
}
+sub get_dom_cats {
+ my ($dom) = @_;
+ return unless (&domain($dom));
+ my ($cats,$cached)=&is_cached_new('cats',$dom);
+ unless (defined($cached)) {
+ my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
+ if (ref($domconfig{'coursecategories'}) eq 'HASH') {
+ if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
+ %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
+ } else {
+ $cats = {};
+ }
+ } else {
+ $cats = {};
+ }
+ &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
+ }
+ return $cats;
+}
+
+sub get_dom_instcats {
+ my ($dom) = @_;
+ return unless (&domain($dom));
+ my ($instcats,$cached)=&is_cached_new('instcats',$dom);
+ unless (defined($cached)) {
+ my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
+ my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
+ if ($totcodes > 0) {
+ my $caller = 'global';
+ if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
+ \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
+ $instcats = {
+ codes => \%codes,
+ codetitles => \@codetitles,
+ cat_titles => \%cat_titles,
+ cat_order => \%cat_order,
+ };
+ &do_cache_new('instcats',$dom,$instcats,3600);
+ }
+ }
+ }
+ return $instcats;
+}
+
+sub retrieve_instcodes {
+ my ($coursecodes,$dom) = @_;
+ my $totcodes;
+ my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
+ foreach my $course (keys(%courses)) {
+ if (ref($courses{$course}) eq 'HASH') {
+ if ($courses{$course}{'inst_code'} ne '') {
+ $$coursecodes{$course} = $courses{$course}{'inst_code'};
+ $totcodes ++;
+ }
+ }
+ }
+ return $totcodes;
+}
+
+# --------------------------------------------- Get domain config for passwords
+
+sub get_passwdconf {
+ my ($dom) = @_;
+ my (%passwdconf,$gotconf,$lookup);
+ my ($result,$cached)=&is_cached_new('passwdconf',$dom);
+ if (defined($cached)) {
+ if (ref($result) eq 'HASH') {
+ %passwdconf = %{$result};
+ $gotconf = 1;
+ }
+ }
+ unless ($gotconf) {
+ my %domconfig = &get_dom('configuration',['passwords'],$dom);
+ if (ref($domconfig{'passwords'}) eq 'HASH') {
+ %passwdconf = %{$domconfig{'passwords'}};
+ }
+ my $cachetime = 24*60*60;
+ &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
+ }
+ return %passwdconf;
+}
+
# --------------------------------------------------- Assign a key to a student
sub assign_access_key {
@@ -1755,21 +2785,25 @@ sub make_key {
sub devalidate_cache_new {
my ($name,$id,$debug) = @_;
if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
+ my $remembered_id=$name.':'.$id;
$id=&make_key($name,$id);
$memcache->delete($id);
- delete($remembered{$id});
- delete($accessed{$id});
+ delete($remembered{$remembered_id});
+ delete($accessed{$remembered_id});
}
sub is_cached_new {
my ($name,$id,$debug) = @_;
- $id=&make_key($name,$id);
- if (exists($remembered{$id})) {
- if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
- $accessed{$id}=[&gettimeofday()];
+ my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for
+ # keys in %remembered hash, which persists for
+ # duration of request (no restriction on key length).
+ if (exists($remembered{$remembered_id})) {
+ if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
+ $accessed{$remembered_id}=[&gettimeofday()];
$hits++;
- return ($remembered{$id},1);
+ return ($remembered{$remembered_id},1);
}
+ $id=&make_key($name,$id);
my $value = $memcache->get($id);
if (!(defined($value))) {
if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
@@ -1779,13 +2813,14 @@ sub is_cached_new {
if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
$value=undef;
}
- &make_room($id,$value,$debug);
+ &make_room($remembered_id,$value,$debug);
if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
return ($value,1);
}
sub do_cache_new {
my ($name,$id,$value,$time,$debug) = @_;
+ my $remembered_id=$name.':'.$id;
$id=&make_key($name,$id);
my $setvalue=$value;
if (!defined($setvalue)) {
@@ -1801,17 +2836,17 @@ sub do_cache_new {
$memcache->disconnect_all();
}
# need to make a copy of $value
- &make_room($id,$value,$debug);
+ &make_room($remembered_id,$value,$debug);
return $value;
}
sub make_room {
- my ($id,$value,$debug)=@_;
+ my ($remembered_id,$value,$debug)=@_;
- $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
+ $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
: $value;
if ($to_remember<0) { return; }
- $accessed{$id}=[&gettimeofday()];
+ $accessed{$remembered_id}=[&gettimeofday()];
if (scalar(keys(%remembered)) <= $to_remember) { return; }
my $to_kick;
my $max_time=0;
@@ -1925,26 +2960,35 @@ sub chatsend {
sub getversion {
my $fname=&clutter(shift);
- unless ($fname=~/^\/res\//) { return -1; }
+ unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
return ¤tversion(&filelocation('',$fname));
}
sub currentversion {
my $fname=shift;
- my ($result,$cached)=&is_cached_new('resversion',$fname);
- if (defined($cached)) { return $result; }
my $author=$fname;
$author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
my ($udom,$uname)=split(/\//,$author);
- my $home=homeserver($uname,$udom);
+ my $home=&homeserver($uname,$udom);
if ($home eq 'no_host') {
return -1;
}
- my $answer=reply("currentversion:$fname",$home);
+ my $answer=&reply("currentversion:$fname",$home);
if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
return -1;
}
- return &do_cache_new('resversion',$fname,$answer,600);
+ return $answer;
+}
+
+#
+# Return special version number of resource if set by override, empty otherwise
+#
+sub usedversion {
+ my $fname=shift;
+ unless ($fname) { $fname=$env{'request.uri'}; }
+ my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
+ if ($urlversion) { return $urlversion; }
+ return '';
}
# ----------------------------- Subscribe to a resource, return URL if possible
@@ -1972,10 +3016,11 @@ sub subscribe {
sub repcopy {
my $filename=shift;
$filename=~s/\/+/\//g;
- if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
- if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
- if ($filename=~m|^/home/httpd/html/userfiles/| or
- $filename=~m -^/*(uploaded|editupload)/-) {
+ my $londocroot = $perlvar{'lonDocRoot'};
+ if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
+ if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
+ if ($filename=~m{^\Q$londocroot/userfiles/\E} or
+ $filename=~m{^/*(uploaded|editupload)/}) {
return &repcopy_userfile($filename);
}
$filename=~s/[\n\r]//g;
@@ -2002,7 +3047,7 @@ sub repcopy {
unless ($home eq $perlvar{'lonHostID'}) {
my @parts=split(/\//,$filename);
my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
- if ($path ne "$perlvar{'lonDocRoot'}/res") {
+ if ($path ne "$londocroot/res") {
&logthis("Malconfiguration for replication: $filename");
return 'bad_request';
}
@@ -2039,6 +3084,27 @@ sub repcopy {
}
}
+# ------------------------------------------------- Unsubscribe from a resource
+
+sub unsubscribe {
+ my ($fname) = @_;
+ my $answer;
+ if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
+ $fname=~s/[\n\r]//g;
+ my $author=$fname;
+ $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
+ my ($udom,$uname)=split(/\//,$author);
+ my $home=homeserver($uname,$udom);
+ if ($home eq 'no_host') {
+ $answer = 'no_host';
+ } elsif (grep { $_ eq $home } ¤t_machine_ids()) {
+ $answer = 'home';
+ } else {
+ $answer = reply("unsub:$fname",$home);
+ }
+ return $answer;
+}
+
# ------------------------------------------------ Get server side include body
sub ssi_body {
my ($filelink,%form)=@_;
@@ -2088,21 +3154,47 @@ sub absolute_url {
sub ssi {
my ($fn,%form)=@_;
- my $ua=new LWP::UserAgent;
- my $request;
+ my ($request,$response);
$form{'no_update_last_known'}=1;
&Apache::lonenc::check_encrypt(\$fn);
if (%form) {
$request=new HTTP::Request('POST',&absolute_url().$fn);
- $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
+ $request->content(join('&',map {
+ my $name = escape($_);
+ "$name=" . ( ref($form{$_}) eq 'ARRAY'
+ ? join("&$name=", map {escape($_) } @{$form{$_}})
+ : &escape($form{$_}) );
+ } keys(%form)));
} else {
$request=new HTTP::Request('GET',&absolute_url().$fn);
}
$request->header(Cookie => $ENV{'HTTP_COOKIE'});
- my $response=$ua->request($request);
+ if (($env{'request.course.id'}) &&
+ ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
+ ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
+ ($form{'grade_symb'} ne '') &&
+ (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
+ ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
+ if (LWP::UserAgent->VERSION >= 5.834) {
+ my $ua=new LWP::UserAgent;
+ $ua->local_address('127.0.0.1');
+ $response = $ua->request($request);
+ } else {
+ {
+ require LWP::Protocol::http;
+ local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
+ my $ua=new LWP::UserAgent;
+ $response = $ua->request($request);
+ @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
+ }
+ }
+ } else {
+ my $ua=new LWP::UserAgent;
+ $response = $ua->request($request);
+ }
if (wantarray) {
return ($response->content, $response);
} else {
@@ -2122,6 +3214,78 @@ sub externalssi {
}
}
+# If the local copy of a replicated resource is outdated, trigger a
+# connection from the homeserver to flush the delayed queue. If no update
+# happens, remove local copies of outdated resource (and corresponding
+# metadata file).
+
+sub remove_stale_resfile {
+ my ($url) = @_;
+ my $removed;
+ if ($url=~m{^/res/($match_domain)/($match_username)/}) {
+ my $audom = $1;
+ my $auname = $2;
+ unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
+ my $homeserver = &homeserver($auname,$audom);
+ unless (($homeserver eq 'no_host') ||
+ (grep { $_ eq $homeserver } ¤t_machine_ids())) {
+ my $fname = &filelocation('',$url);
+ if (-e $fname) {
+ my $hostname = &hostname($homeserver);
+ if ($hostname) {
+ my $protocol = $protocol{$homeserver};
+ $protocol = 'http' if ($protocol ne 'https');
+ my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
+ my $ua=new LWP::UserAgent;
+ $ua->timeout(5);
+ my $request=new HTTP::Request('HEAD',$uri);
+ my $response=$ua->request($request);
+ if ($response->is_success()) {
+ my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
+ my $locmodtime = (stat($fname))[9];
+ if ($locmodtime < $remmodtime) {
+ my $stale;
+ my $answer = &reply('pong',$homeserver);
+ if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
+ sleep(0.2);
+ $locmodtime = (stat($fname))[9];
+ if ($locmodtime < $remmodtime) {
+ my $posstransfer = $fname.'.in.transfer';
+ if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
+ $removed = 1;
+ } else {
+ $stale = 1;
+ }
+ } else {
+ $removed = 1;
+ }
+ } else {
+ $stale = 1;
+ }
+ if ($stale) {
+ if (unlink($fname)) {
+ if ($uri!~/\.meta$/) {
+ if (-e $fname.'.meta') {
+ unlink($fname.'.meta');
+ }
+ }
+ my $unsubresult = &unsubscribe($fname);
+ unless ($unsubresult eq 'ok') {
+ &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
+ }
+ $removed = 1;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ return $removed;
+}
+
# -------------------------------- Allow a /uploaded/ URI to be vouched for
sub allowuploaded {
@@ -2135,11 +3299,283 @@ sub allowuploaded {
&Apache::lonnet::appenv(\%httpref);
}
+#
+# Determine if the current user should be able to edit a particular resource,
+# when viewing in course context.
+# (a) When viewing resource used to determine if "Edit" item is included in
+# Functions.
+# (b) When displaying folder contents in course editor, used to determine if
+# "Edit" link will be displayed alongside resource.
+#
+# input: six args -- filename (decluttered), course number, course domain,
+# url, symb (if registered) and group (if this is a group
+# item -- e.g., bulletin board, group page etc.).
+# output: array of five scalars --
+# $cfile -- url for file editing if editable on current server
+# $home -- homeserver of resource (i.e., for author if published,
+# or course if uploaded.).
+# $switchserver -- 1 if server switch will be needed.
+# $forceedit -- 1 if icon/link should be to go to edit mode
+# $forceview -- 1 if icon/link should be to go to view mode
+#
+
+sub can_edit_resource {
+ my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
+ my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
+#
+# For aboutme pages user can only edit his/her own.
+#
+ if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
+ my ($sdom,$sname) = ($1,$2);
+ if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
+ $home = $env{'user.home'};
+ $cfile = $resurl;
+ if ($env{'form.forceedit'}) {
+ $forceview = 1;
+ } else {
+ $forceedit = 1;
+ }
+ return ($cfile,$home,$switchserver,$forceedit,$forceview);
+ } else {
+ return;
+ }
+ }
+
+ if ($env{'request.course.id'}) {
+ my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
+ if ($group ne '') {
+# if this is a group homepage or group bulletin board, check group privs
+ my $allowed = 0;
+ if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
+ if ((&allowed('mdg',$env{'request.course.id'}.
+ ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
+ (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
+ $allowed = 1;
+ }
+ } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
+ if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
+ (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
+ $allowed = 1;
+ }
+ }
+ if ($allowed) {
+ $home=&homeserver($cnum,$cdom);
+ if ($env{'form.forceedit'}) {
+ $forceview = 1;
+ } else {
+ $forceedit = 1;
+ }
+ $cfile = $resurl;
+ } else {
+ return;
+ }
+ } else {
+ if ($resurl =~ m{^/?adm/viewclasslist$}) {
+ unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
+ return;
+ }
+ } elsif (!$crsedit) {
+#
+# No edit allowed where CC has switched to student role.
+#
+ return;
+ }
+ }
+ }
+
+ if ($file ne '') {
+ if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
+ if (&is_course_upload($file,$cnum,$cdom)) {
+ $uploaded = 1;
+ $incourse = 1;
+ if ($file =~/\.(htm|html|css|js|txt)$/) {
+ $cfile = &hreflocation('',$file);
+ if ($env{'form.forceedit'}) {
+ $forceview = 1;
+ } else {
+ $forceedit = 1;
+ }
+ }
+ } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
+ $incourse = 1;
+ if ($env{'form.forceedit'}) {
+ $forceview = 1;
+ } else {
+ $forceedit = 1;
+ }
+ $cfile = $resurl;
+ } elsif (($resurl ne '') && (&is_on_map($resurl))) {
+ if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
+ $incourse = 1;
+ if ($env{'form.forceedit'}) {
+ $forceview = 1;
+ } else {
+ $forceedit = 1;
+ }
+ $cfile = $resurl;
+ } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
+ $incourse = 1;
+ $cfile = $resurl.'/smpedit';
+ } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
+ $incourse = 1;
+ if ($env{'form.forceedit'}) {
+ $forceview = 1;
+ } else {
+ $forceedit = 1;
+ }
+ $cfile = $resurl;
+ } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
+ my ($map,$id,$res) = &decode_symb($symb);
+ if ($map =~ /\.page$/) {
+ $incourse = 1;
+ if ($env{'form.forceedit'}) {
+ $forceview = 1;
+ $cfile = $map;
+ } else {
+ $forceedit = 1;
+ $cfile = '/adm/wrapper'.$resurl;
+ }
+ }
+ } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
+ $incourse = 1;
+ if ($env{'form.forceedit'}) {
+ $forceview = 1;
+ } else {
+ $forceedit = 1;
+ }
+ $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
+ }
+ } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
+ my $template = '/res/lib/templates/simpleproblem.problem';
+ if (&is_on_map($template)) {
+ $incourse = 1;
+ $forceview = 1;
+ $cfile = $template;
+ }
+ } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
+ $incourse = 1;
+ if ($env{'form.forceedit'}) {
+ $forceview = 1;
+ } else {
+ $forceedit = 1;
+ }
+ $cfile = $resurl;
+ } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
+ $incourse = 1;
+ $forceview = 1;
+ if ($symb) {
+ my ($map,$id,$res)=&decode_symb($symb);
+ $env{'request.symb'} = $symb;
+ $cfile = &clutter($res);
+ } else {
+ $cfile = $env{'form.suppurl'};
+ $cfile =~ s{^http://}{};
+ $cfile = '/adm/wrapper/ext/'.$cfile;
+ }
+ } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
+ if ($env{'form.forceedit'}) {
+ $forceview = 1;
+ } else {
+ $forceedit = 1;
+ }
+ $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
+ }
+ }
+ if ($uploaded || $incourse) {
+ $home=&homeserver($cnum,$cdom);
+ } elsif ($file !~ m{/$}) {
+ $file=~s{^(priv/$match_domain/$match_username)}{/$1};
+ $file=~s{^($match_domain/$match_username)}{/priv/$1};
+ # Check that the user has permission to edit this resource
+ my $setpriv = 1;
+ my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
+ if (defined($cfudom)) {
+ $home=&homeserver($cfuname,$cfudom);
+ $cfile=$file;
+ }
+ }
+ if (($cfile ne '') && (!$incourse || $uploaded) &&
+ (($home ne '') && ($home ne 'no_host'))) {
+ my @ids=¤t_machine_ids();
+ unless (grep(/^\Q$home\E$/,@ids)) {
+ $switchserver=1;
+ }
+ }
+ }
+ return ($cfile,$home,$switchserver,$forceedit,$forceview);
+}
+
+sub is_course_upload {
+ my ($file,$cnum,$cdom) = @_;
+ my $uploadpath = &LONCAPA::propath($cdom,$cnum);
+ $uploadpath =~ s{^\/}{};
+ if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
+ ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
+ return 1;
+ }
+ return;
+}
+
+sub in_course {
+ my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
+ if ($hideprivileged) {
+ my $skipuser;
+ my %coursehash = &coursedescription($cdom.'_'.$cnum);
+ my @possdoms = ($cdom);
+ if ($coursehash{'checkforpriv'}) {
+ push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
+ }
+ if (&privileged($uname,$udom,\@possdoms)) {
+ $skipuser = 1;
+ if ($coursehash{'nothideprivileged'}) {
+ foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
+ my $user;
+ if ($item =~ /:/) {
+ $user = $item;
+ } else {
+ $user = join(':',split(/[\@]/,$item));
+ }
+ if ($user eq $uname.':'.$udom) {
+ undef($skipuser);
+ last;
+ }
+ }
+ }
+ if ($skipuser) {
+ return 0;
+ }
+ }
+ }
+ $type ||= 'any';
+ if (!defined($cdom) || !defined($cnum)) {
+ my $cid = $env{'request.course.id'};
+ $cdom = $env{'course.'.$cid.'.domain'};
+ $cnum = $env{'course.'.$cid.'.num'};
+ }
+ my $typesref;
+ if (($type eq 'any') || ($type eq 'all')) {
+ $typesref = ['active','previous','future'];
+ } elsif ($type eq 'previous' || $type eq 'future') {
+ $typesref = [$type];
+ }
+ my %roles = &get_my_roles($uname,$udom,'userroles',
+ $typesref,undef,[$cdom]);
+ my ($tmp) = keys(%roles);
+ return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
+ my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
+ if (@course_roles > 0) {
+ return 1;
+ }
+ return 0;
+}
+
# --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
# input: action, courseID, current domain, intended
# path to file, source of file, instruction to parse file for objects,
# ref to hash for embedded objects,
# ref to hash for codebase of java objects.
+# reference to scalar to accommodate mime type determined
+# from File::MMagic if $parser = parse.
#
# output: url to file (if action was uploaddoc),
# ok if successful, or diagnostic message otherwise (if action was propagate or copy)
@@ -2166,7 +3602,8 @@ sub allowuploaded {
#
sub process_coursefile {
- my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
+ my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
+ $mimetype)=@_;
my $fetchresult;
my $home=&homeserver($docuname,$docudom);
if ($action eq 'propagate') {
@@ -2189,18 +3626,21 @@ sub process_coursefile {
$home);
}
} elsif ($action eq 'uploaddoc') {
- open(my $fh,'>'.$filepath.'/'.$fname);
+ open(my $fh,'>',$filepath.'/'.$fname);
print $fh $env{'form.'.$source};
close($fh);
if ($parser eq 'parse') {
my $mm = new File::MMagic;
- my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
- if ($mime_type eq 'text/html') {
+ my $type = $mm->checktype_filename($filepath.'/'.$fname);
+ if ($type eq 'text/html') {
my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
unless ($parse_result eq 'ok') {
&logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
}
}
+ if (ref($mimetype)) {
+ $$mimetype = $type;
+ }
}
$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
$home);
@@ -2244,7 +3684,7 @@ sub store_edited_file {
($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
$fpath=$docudom.'/'.$docuname.'/'.$fpath;
my $filepath = &build_filepath($fpath);
- open(my $fh,'>'.$filepath.'/'.$fname);
+ open(my $fh,'>',$filepath.'/'.$fname);
print $fh $content;
close($fh);
my $home=&homeserver($docuname,$docudom);
@@ -2269,6 +3709,9 @@ sub clean_filename {
}
# Replace spaces by underscores
$fname=~s/\s+/\_/g;
+# Transliterate non-ascii text to ascii
+ my $lang = &Apache::lonlocal::current_language();
+ $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
# Replace all other weird characters by nothing
$fname=~s{[^/\w\.\-]}{}g;
# Replace all .\d. sequences with _\d. so they no longer look like version
@@ -2276,6 +3719,7 @@ sub clean_filename {
$fname=~s/\.(\d+)(?=\.)/_$1/g;
return $fname;
}
+
# This Function checks if an Image's dimensions exceed either $resizewidth (width)
# or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
# image with the same aspect ratio as the original, but with dimensions which do
@@ -2316,11 +3760,18 @@ sub resizeImage {
# --------------- Take an uploaded file and put it into the userfiles directory
# input: $formname - the contents of the file are in $env{"form.$formname"}
-# the desired filenam is in $env{"form.$formname.filename"}
-# $coursedoc - if true up to the current course
-# if false
+# the desired filename is in $env{"form.$formname.filename"}
+# $context - possible values: coursedoc, existingfile, overwrite,
+# canceloverwrite, scantron or ''.
+# if 'coursedoc': upload to the current course
+# if 'existingfile': write file to tmp/overwrites directory
+# if 'canceloverwrite': delete file written to tmp/overwrites directory
+# $context is passed as argument to &finishuserfileupload
# $subdir - directory in userfile to store the file into
-# $parser - instruction to parse file for objects ($parser = parse)
+# $parser - instruction to parse file for objects ($parser = parse) or
+# if context is 'scantron', $parser is hashref of csv column mapping
+# (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
+# Section => 4, CODE => 5, FirstQuestion => 9 }).
# $allfiles - reference to hash for embedded objects
# $codebase - reference to hash for codebase of java objects
# $desuname - username for permanent storage of uploaded file
@@ -2329,37 +3780,68 @@ sub resizeImage {
# $thumbheight - height (pixels) of thumbnail to make for uploaded image
# $resizewidth - width (pixels) to which to resize uploaded image
# $resizeheight - height (pixels) to which to resize uploaded image
+# $mimetype - reference to scalar to accommodate mime type determined
+# from File::MMagic.
#
# output: url of file in userspace, or error:
'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
@@ -8303,17 +11763,18 @@ sub add_prefix_and_part {
my %metaentry;
my %importedpartids;
+my %importedrespids;
sub metadata {
my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
$uri=&declutter($uri);
# if it is a non metadata possible uri return quickly
if (($uri eq '') ||
(($uri =~ m|^/*adm/|) &&
- ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
- ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
+ ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
+ ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
return undef;
}
- if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
+ if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
return undef;
}
@@ -8330,9 +11791,11 @@ sub metadata {
}
{
# Imported parts would go here
- my %importedids=();
- my @origfileimportpartids=();
+ my @origfiletagids=();
my $importedparts=0;
+
+# Imported responseids would go here
+ my $importedresponses=0;
#
# Is this a recursive call for a library?
#
@@ -8350,13 +11813,14 @@ sub metadata {
my %metathesekeys=();
unless ($filename=~/\.meta$/) { $filename.='.meta'; }
my $metastring;
- if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
+ if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
my $which = &hreflocation('','/'.($liburi || $uri));
$metastring =
&Apache::lonnet::ssi_body($which,
('grade_target' => 'meta'));
$cachetime = 1; # only want this cached in the child not long term
- } elsif ($uri !~ m -^(editupload)/-) {
+ } elsif (($uri !~ m -^(editupload)/-) &&
+ ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
my $file=&filelocation('',&clutter($filename));
#push(@{$metaentry{$uri.'.file'}},$file);
$metastring=&getfile($file);
@@ -8426,8 +11890,37 @@ sub metadata {
my $dir=$filename;
$dir=~s|[^/]*$||;
$location=&filelocation($dir,$location);
-
+
+ my $importid=$token->[2]->{'id'};
my $importmode=$token->[2]->{'importmode'};
+#
+# Check metadata for imported file to
+# see if it contained response items
+#
+ my %currmetaentry = %metaentry;
+ my $libresponseorder = &metadata($location,'responseorder');
+ my $origfile;
+ if ($libresponseorder ne '') {
+ if ($#origfiletagids<0) {
+ undef(%importedrespids);
+ undef(%importedpartids);
+ }
+ @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
+ if (@{$importedrespids{$importid}} > 0) {
+ $importedresponses = 1;
+# We need to get the original file and the imported file to get the response order correct
+# Load and inspect original file
+ if ($#origfiletagids<0) {
+ my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
+ $origfile=&getfile($origfilelocation);
+ @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
+ }
+ }
+ }
+# Do not overwrite contents of %metaentry hash for resource itself with
+# hash populated for imported library file
+ %metaentry = %currmetaentry;
+ undef(%currmetaentry);
if ($importmode eq 'problem') {
# Import as problem/response
$unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
@@ -8436,12 +11929,15 @@ sub metadata {
$importedparts=1;
# We need to get the original file and the imported file to get the part order correct
# Good news: we do not need to worry about nested libraries, since parts cannot be nested
-# Load and inspect original file
- if ($#origfileimportpartids<0) {
- undef(%importedpartids);
- my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
- my $origfile=&getfile($origfilelocation);
- @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
+# Load and inspect original file if we didn't do that already
+ if ($#origfiletagids<0) {
+ undef(%importedrespids);
+ undef(%importedpartids);
+ if ($origfile eq '') {
+ my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
+ $origfile=&getfile($origfilelocation);
+ @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
+ }
}
# Load and inspect imported file
@@ -8555,25 +12051,53 @@ sub metadata {
grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
$metaentry{':packages'} = join(',',@uniq_packages);
- if ($importedparts) {
+ if (($importedresponses) || ($importedparts)) {
+ if ($importedparts) {
# We had imported parts and need to rebuild partorder
- $metaentry{':partorder'}='';
- $metathesekeys{'partorder'}=1;
- for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
- if ($origfileimportpartids[$index] eq 'part') {
-# original part, part of the problem
- $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
- } else {
-# we have imported parts at this position
- $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
- }
- }
- $metaentry{':partorder'}=~s/^\,//;
+ $metaentry{':partorder'}='';
+ $metathesekeys{'partorder'}=1;
+ }
+ if ($importedresponses) {
+# We had imported responses and need to rebuild responseorder
+ $metaentry{':responseorder'}='';
+ $metathesekeys{'responseorder'}=1;
+ }
+ for (my $index=0;$index<$#origfiletagids;$index+=2) {
+ my $origid = $origfiletagids[$index+1];
+ if ($origfiletagids[$index] eq 'part') {
+# Original part, part of the problem
+ if ($importedparts) {
+ $metaentry{':partorder'}.=','.$origid;
+ }
+ } elsif ($origfiletagids[$index] eq 'import') {
+ if ($importedparts) {
+# We have imported parts at this position
+ $metaentry{':partorder'}.=','.$importedpartids{$origid};
+ }
+ if ($importedresponses) {
+# We have imported responses at this position
+ if (ref($importedrespids{$origid}) eq 'ARRAY') {
+ $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
+ }
+ }
+ } else {
+# Original response item, part of the problem
+ if ($importedresponses) {
+ $metaentry{':responseorder'}.=','.$origid;
+ }
+ }
+ }
+ if ($importedparts) {
+ $metaentry{':partorder'}=~s/^\,//;
+ }
+ if ($importedresponses) {
+ $metaentry{':responseorder'}=~s/^\,//;
+ }
}
$metaentry{':keys'} = join(',',keys(%metathesekeys));
&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
- $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
+ $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
&do_cache_new('meta',$uri,\%metaentry,$cachetime);
# this is the end of "was not already recently cached
}
@@ -8673,6 +12197,10 @@ sub gettitle {
}
$title=~s/\&colon\;/\:/gs;
if ($title) {
+# Remember both $symb and $title for dynamic metadata
+ $accesshash{$symb.'___crstitle'}=$title;
+ $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
+# Cache this title and then return it
return &do_cache_new('title',$key,$title,600);
}
$urlsymb=$url;
@@ -8705,6 +12233,84 @@ sub get_slot {
}
return $slotinfo{$which};
}
+
+sub get_reservable_slots {
+ my ($cnum,$cdom,$uname,$udom) = @_;
+ my $now = time;
+ my $reservable_info;
+ my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
+ if (exists($remembered{$key})) {
+ $reservable_info = $remembered{$key};
+ } else {
+ my %resv;
+ ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
+ &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
+ $reservable_info = \%resv;
+ $remembered{$key} = $reservable_info;
+ }
+ return $reservable_info;
+}
+
+sub get_course_slots {
+ my ($cnum,$cdom) = @_;
+ my $hashid=$cnum.':'.$cdom;
+ my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
+ if (defined($cached)) {
+ if (ref($result) eq 'HASH') {
+ return %{$result};
+ }
+ } else {
+ my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
+ my ($tmp) = keys(%slots);
+ if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
+ &do_cache_new('allslots',$hashid,\%slots,600);
+ return %slots;
+ }
+ }
+ return;
+}
+
+sub devalidate_slots_cache {
+ my ($cnum,$cdom)=@_;
+ my $hashid=$cnum.':'.$cdom;
+ &devalidate_cache_new('allslots',$hashid);
+}
+
+sub get_coursechange {
+ my ($cdom,$cnum) = @_;
+ if ($cdom eq '' || $cnum eq '') {
+ return unless ($env{'request.course.id'});
+ $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
+ $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
+ }
+ my $hashid=$cdom.'_'.$cnum;
+ my ($change,$cached)=&is_cached_new('crschange',$hashid);
+ if ((defined($cached)) && ($change ne '')) {
+ return $change;
+ } else {
+ my %crshash;
+ %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
+ if ($crshash{'internal.contentchange'} eq '') {
+ $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
+ if ($change eq '') {
+ %crshash = &get('environment',['internal.created'],$cdom,$cnum);
+ $change = $crshash{'internal.created'};
+ }
+ } else {
+ $change = $crshash{'internal.contentchange'};
+ }
+ my $cachetime = 600;
+ &do_cache_new('crschange',$hashid,$change,$cachetime);
+ }
+ return $change;
+}
+
+sub devalidate_coursechange_cache {
+ my ($cnum,$cdom)=@_;
+ my $hashid=$cnum.':'.$cdom;
+ &devalidate_cache_new('crschange',$hashid);
+}
+
# ------------------------------------------------- Update symbolic store links
sub symblist {
@@ -8732,7 +12338,7 @@ sub symblist {
# --------------------------------------------------------------- Verify a symb
sub symbverify {
- my ($symb,$thisurl)=@_;
+ my ($symb,$thisurl,$encstate)=@_;
my $thisfn=$thisurl;
$thisfn=&declutter($thisfn);
# direct jump to resource in page or to a sequence - will construct own symbs
@@ -8753,27 +12359,42 @@ sub symbverify {
&GDBM_READER(),0640)) {
if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
$thisurl =~ s/\?.+$//;
+ if ($map =~ m{^uploaded/.+\.page$}) {
+ $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
+ $thisurl =~ s{^\Qhttp://https://\E}{https://};
+ }
}
- my $ids=$bighash{'ids_'.&clutter($thisurl)};
- unless ($ids) {
- $ids=$bighash{'ids_/'.$thisurl};
+ my $ids;
+ if ($map =~ m{^uploaded/.+\.page$}) {
+ $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
+ } else {
+ $ids=$bighash{'ids_'.&clutter($thisurl)};
+ }
+ unless ($ids) {
+ my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
+ $ids=$bighash{$idkey};
}
if ($ids) {
# ------------------------------------------------------------------- Has ID(s)
+ if ($thisfn =~ m{^/adm/wrapper/ext/}) {
+ $symb =~ s/\?.+$//;
+ }
foreach my $id (split(/\,/,$ids)) {
my ($mapid,$resid)=split(/\./,$id);
- if ($thisfn =~ m{^/adm/wrapper/ext/}) {
- $symb =~ s/\?.+$//;
- }
if (
&symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
- eq $symb) {
- if (($env{'request.role.adv'}) ||
- $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
- $okay=1;
- }
- }
- }
+ eq $symb) {
+ if (ref($encstate)) {
+ $$encstate = $bighash{'encrypted_'.$id};
+ }
+ if (($env{'request.role.adv'}) ||
+ ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
+ ($thisurl eq '/adm/navmaps')) {
+ $okay=1;
+ last;
+ }
+ }
+ }
}
untie(%bighash);
}
@@ -8845,15 +12466,24 @@ sub deversion {
# ------------------------------------------------------ Return symb list entry
sub symbread {
- my ($thisfn,$donotrecurse)=@_;
+ my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
+ $ignoresymbdb,$noenccheck)=@_;
my $cache_str='request.symbread.cached.'.$thisfn;
- if (defined($env{$cache_str})) { return $env{$cache_str}; }
+ if (defined($env{$cache_str})) {
+ unless (ref($possibles) eq 'HASH') {
+ if ($ignorecachednull) {
+ return $env{$cache_str} unless ($env{$cache_str} eq '');
+ } else {
+ return $env{$cache_str};
+ }
+ }
+ }
# no filename provided? try from environment
unless ($thisfn) {
if ($env{'request.symb'}) {
- return $env{$cache_str}=&symbclean($env{'request.symb'});
- }
- $thisfn=$env{'request.filename'};
+ return $env{$cache_str}=&symbclean($env{'request.symb'});
+ }
+ $thisfn=$env{'request.filename'};
}
if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
# is that filename actually a symb? Verify, clean, and return
@@ -8874,10 +12504,18 @@ sub symbread {
if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
$targetfn=$1;
}
- if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
- &GDBM_READER(),0640)) {
- $syval=$hash{$targetfn};
- untie(%hash);
+ unless ($ignoresymbdb) {
+ if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
+ &GDBM_READER(),0640)) {
+ $syval=$hash{$targetfn};
+ untie(%hash);
+ }
+ if ($syval && $checkforblock) {
+ my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
+ if (@blockers) {
+ $syval='';
+ }
+ }
}
# ---------------------------------------------------------- There was an entry
if ($syval) {
@@ -8909,18 +12547,57 @@ sub symbread {
my ($mapid,$resid)=split(/\./,$ids);
$syval=&encode_symb($bighash{'map_id_'.$mapid},
$resid,$thisfn);
- } elsif (!$donotrecurse) {
+ if (ref($possibles) eq 'HASH') {
+ unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
+ $possibles->{$syval} = 1;
+ }
+ }
+ if ($checkforblock) {
+ unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
+ my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
+ if (@blockers) {
+ $syval = '';
+ untie(%bighash);
+ return $env{$cache_str}='';
+ }
+ }
+ }
+ } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
# ------------------------------------------ There is more than one possibility
my $realpossible=0;
foreach my $id (@possibilities) {
my $file=$bighash{'src_'.$id};
- if (&allowed('bre',$file)) {
- my ($mapid,$resid)=split(/\./,$id);
- if ($bighash{'map_type_'.$mapid} ne 'page') {
- $realpossible++;
- $syval=&encode_symb($bighash{'map_id_'.$mapid},
- $resid,$thisfn);
- }
+ my $canaccess;
+ if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
+ $canaccess = 1;
+ } else {
+ $canaccess = &allowed('bre',$file);
+ }
+ if ($canaccess) {
+ my ($mapid,$resid)=split(/\./,$id);
+ if ($bighash{'map_type_'.$mapid} ne 'page') {
+ my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
+ $resid,$thisfn);
+ next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
+ next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
+ if ($checkforblock) {
+ my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
+ if (@blockers > 0) {
+ $syval = '';
+ } else {
+ $syval = $poss_syval;
+ $realpossible++;
+ }
+ } else {
+ $syval = $poss_syval;
+ $realpossible++;
+ }
+ if ($syval) {
+ if (ref($possibles) eq 'HASH') {
+ $possibles->{$syval} = 1;
+ }
+ }
+ }
}
}
if ($realpossible!=1) { $syval=''; }
@@ -8928,7 +12605,7 @@ sub symbread {
$syval='';
}
}
- untie(%bighash)
+ untie(%bighash);
}
}
if ($syval) {
@@ -9044,18 +12721,42 @@ sub getCODE {
}
return undef;
}
-
+#
+# Determines the random seed for a specific context:
+#
+# parameters:
+# symb - in course context the symb for the seed.
+# course_id - The course id of the form domain_coursenum.
+# domain - Domain for the user.
+# course - Course for the user.
+# cenv - environment of the course.
+#
+# NOTE:
+# All parameters are picked out of the environment if missing
+# or not defined.
+# If a symb cannot be determined the current time is used instead.
+#
+# For a given well defined symb, courside, domain, username,
+# and course environment, the seed is reproducible.
+#
sub rndseed {
- my ($symb,$courseid,$domain,$username)=@_;
+ my ($symb,$courseid,$domain,$username, $cenv)=@_;
my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
if (!defined($symb)) {
unless ($symb=$wsymb) { return time; }
}
- if (!$courseid) { $courseid=$wcourseid; }
- if (!$domain) { $domain=$wdomain; }
- if (!$username) { $username=$wusername }
- my $which=&get_rand_alg();
+ if (!defined $courseid) {
+ $courseid=$wcourseid;
+ }
+ if (!defined $domain) { $domain=$wdomain; }
+ if (!defined $username) { $username=$wusername }
+ my $which;
+ if (defined($cenv->{'rndseed'})) {
+ $which = $cenv->{'rndseed'};
+ } else {
+ $which =&get_rand_alg($courseid);
+ }
if (defined(&getCODE())) {
if ($which eq '64bit5') {
return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
@@ -9242,8 +12943,12 @@ sub rndseed_CODE_64bit5 {
sub setup_random_from_rndseed {
my ($rndseed)=@_;
if ($rndseed =~/([,:])/) {
- my ($num1,$num2)=split(/[,:]/,$rndseed);
- &Math::Random::random_set_seed(abs($num1),abs($num2));
+ my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
+ if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
+ &Math::Random::random_set_seed_from_phrase($rndseed);
+ } else {
+ &Math::Random::random_set_seed($num1,$num2);
+ }
} else {
&Math::Random::random_set_seed_from_phrase($rndseed);
}
@@ -9380,8 +13085,9 @@ sub getfile {
sub repcopy_userfile {
my ($file)=@_;
- if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
- if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
+ my $londocroot = $perlvar{'lonDocRoot'};
+ if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
+ if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
my ($cdom,$cnum,$filename) =
($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
my $uri="/uploaded/$cdom/$cnum/$filename";
@@ -9428,9 +13134,10 @@ sub repcopy_userfile {
my $request;
$uri=~s/^\///;
my $homeserver = &homeserver($cnum,$cdom);
+ my $hostname = &hostname($homeserver);
my $protocol = $protocol{$homeserver};
$protocol = 'http' if ($protocol ne 'https');
- $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
+ $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
my $response=$ua->request($request,$transferfile);
# did it work?
if ($response->is_error()) {
@@ -9454,9 +13161,10 @@ sub tokenwrapper {
$file=~s|(\?\.*)*$||;
&appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
my $homeserver = &homeserver($uname,$udom);
+ my $hostname = &hostname($homeserver);
my $protocol = $protocol{$homeserver};
$protocol = 'http' if ($protocol ne 'https');
- return $protocol.'://'.&hostname($homeserver).'/'.$uri.
+ return $protocol.'://'.$hostname.'/'.$uri.
(($uri=~/\?/)?'&':'?').'token='.$token.
'&tokenissued='.$perlvar{'lonHostID'};
} else {
@@ -9472,9 +13180,10 @@ sub getuploaded {
my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
$uri=~s/^\///;
my $homeserver = &homeserver($cnum,$cdom);
+ my $hostname = &hostname($homeserver);
my $protocol = $protocol{$homeserver};
$protocol = 'http' if ($protocol ne 'https');
- $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
+ $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
my $ua=new LWP::UserAgent;
my $request=new HTTP::Request($reqtype,$uri);
my $response=$ua->request($request);
@@ -9494,7 +13203,7 @@ sub readfile {
my $file = shift;
if ( (! -e $file ) || ($file eq '') ) { return -1; };
my $fh;
- open($fh,"<$file");
+ open($fh,"<",$file);
my $a='';
while (my $line = <$fh>) { $a .= $line; }
return $a;
@@ -9510,13 +13219,7 @@ sub filelocation {
$file=~s-^/adm/coursedocs/showdoc/-/-;
}
- if ($file=~m:^/~:) { # is a contruction space reference
- $location = $file;
- $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
- } elsif ($file=~m{^/home/$match_username/public_html/}) {
- # is a correct contruction space reference
- $location = $file;
- } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
+ if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
$location = $file;
} elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
my ($udom,$uname,$filename)=
@@ -9526,7 +13229,7 @@ sub filelocation {
my @ids=¤t_machine_ids();
foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
if ($is_me) {
- $location=&propath($udom,$uname).'/userfiles/'.$filename;
+ $location=propath($udom,$uname).'/userfiles/'.$filename;
} else {
$location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
$udom.'/'.$uname.'/'.$filename;
@@ -9535,11 +13238,12 @@ sub filelocation {
$location = $perlvar{'lonDocRoot'}.'/'.$file;
} else {
$file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
- $file=~s:^/res/:/:;
+ $file=~s:^/(res|priv)/:/:;
+ my $space=$1;
if ( !( $file =~ m:^/:) ) {
$location = $dir. '/'.$file;
} else {
- $location = '/home/httpd/html/res'.$file;
+ $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
}
}
$location=~s://+:/:g; # remove duplicate /
@@ -9564,11 +13268,9 @@ sub hreflocation {
}
if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
- } elsif ($file=~m-/home/($match_username)/public_html/-) {
- $file=~s-^/home/($match_username)/public_html/-/~$1/-;
} elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
- $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
- -/uploaded/$1/$2/-x;
+ $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
+ {/uploaded/$1/$2/}x;
}
if ($file=~ m{^/userfiles/}) {
$file =~ s{^/userfiles/}{/uploaded/};
@@ -9576,6 +13278,10 @@ sub hreflocation {
return $file;
}
+
+
+
+
sub current_machine_domains {
return &machine_domains(&hostname($perlvar{'lonHostID'}));
}
@@ -9610,7 +13316,7 @@ sub machine_ids {
sub additional_machine_domains {
my @domains;
- open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
+ open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
while( my $line = <$fh>) {
$line =~ s/\s//g;
push(@domains,$line);
@@ -9631,16 +13337,79 @@ sub default_login_domain {
return $domain;
}
+sub shared_institution {
+ my ($dom) = @_;
+ my $same_intdom;
+ my $hostintdom = &internet_dom($perlvar{'lonHostID'});
+ if ($hostintdom ne '') {
+ my %iphost = &get_iphost();
+ my $primary_id = &domain($dom,'primary');
+ my $primary_ip = &get_host_ip($primary_id);
+ if (ref($iphost{$primary_ip}) eq 'ARRAY') {
+ foreach my $id (@{$iphost{$primary_ip}}) {
+ my $intdom = &internet_dom($id);
+ if ($intdom eq $hostintdom) {
+ $same_intdom = 1;
+ last;
+ }
+ }
+ }
+ }
+ return $same_intdom;
+}
+
+sub uses_sts {
+ my ($ignore_cache) = @_;
+ my $lonhost = $perlvar{'lonHostID'};
+ my $hostname = &hostname($lonhost);
+ my $sts_on;
+ if ($protocol{$lonhost} eq 'https') {
+ my $cachetime = 12*3600;
+ if (!$ignore_cache) {
+ ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
+ if (defined($cached)) {
+ return $sts_on;
+ }
+ }
+ my $ua=new LWP::UserAgent;
+ my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
+ my $request=new HTTP::Request('HEAD',$url);
+ my $response=$ua->request($request);
+ if ($response->is_success) {
+ my $has_sts = $response->header('Strict-Transport-Security');
+ if ($has_sts eq '') {
+ $sts_on = 0;
+ } else {
+ if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
+ my $maxage = $1;
+ if ($maxage) {
+ $sts_on = 1;
+ } else {
+ $sts_on = 0;
+ }
+ } else {
+ $sts_on = 0;
+ }
+ }
+ return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
+ }
+ }
+ return;
+}
+
# ------------------------------------------------------------- Declutters URLs
sub declutter {
my $thisfn=shift;
if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
- $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
+ unless ($thisfn=~m{^/home/httpd/html/priv/}) {
+ $thisfn=~s{^/home/httpd/html}{};
+ }
$thisfn=~s/^\///;
$thisfn=~s|^adm/wrapper/||;
$thisfn=~s|^adm/coursedocs/showdoc/||;
$thisfn=~s/^res\///;
+ $thisfn=~s/^priv\///;
unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
$thisfn=~s/\?.+$//;
}
@@ -9740,47 +13509,109 @@ sub goodbye {
}
sub get_dns {
- my ($url,$func,$ignore_cache) = @_;
+ my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
if (!$ignore_cache) {
my ($content,$cached)=
&Apache::lonnet::is_cached_new('dns',$url);
if ($cached) {
- &$func($content);
+ &$func($content,$hashref);
return;
}
}
my %alldns;
- open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
- foreach my $dns (<$config>) {
- next if ($dns !~ /^\^(\S*)/x);
- my $line = $1;
- my ($host,$protocol) = split(/:/,$line);
- if ($protocol ne 'https') {
- $protocol = 'http';
+ if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
+ foreach my $dns (<$config>) {
+ next if ($dns !~ /^\^(\S*)/x);
+ my $line = $1;
+ my ($host,$protocol) = split(/:/,$line);
+ if ($protocol ne 'https') {
+ $protocol = 'http';
+ }
+ $alldns{$host} = $protocol;
}
- $alldns{$host} = $protocol;
+ close($config);
}
while (%alldns) {
- my ($dns) = keys(%alldns);
+ my ($dns) = sort { $b cmp $a } keys(%alldns);
my $ua=new LWP::UserAgent;
+ $ua->timeout(30);
my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
my $response=$ua->request($request);
delete($alldns{$dns});
next if ($response->is_error());
my @content = split("\n",$response->content);
- &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
- &$func(\@content);
+ unless ($nocache) {
+ &do_cache_new('dns',$url,\@content,30*24*60*60);
+ }
+ &$func(\@content,$hashref);
return;
}
- close($config);
my $which = (split('/',$url))[3];
&logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
- open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
- my @content = <$config>;
- &$func(\@content);
+ if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
+ my @content = <$config>;
+ &$func(\@content,$hashref);
+ }
+ return;
+}
+
+# ------------------------------------------------------Get DNS checksums file
+sub parse_dns_checksums_tab {
+ my ($lines,$hashref) = @_;
+ my $lonhost = $perlvar{'lonHostID'};
+ my $machine_dom = &Apache::lonnet::host_domain($lonhost);
+ my $loncaparev = &get_server_loncaparev($machine_dom);
+ my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
+ my $webconfdir = '/etc/httpd/conf';
+ if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
+ $webconfdir = '/etc/apache2';
+ } elsif ($distro =~ /^sles(\d+)$/) {
+ if ($1 >= 10) {
+ $webconfdir = '/etc/apache2';
+ }
+ } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
+ if ($1 >= 10.0) {
+ $webconfdir = '/etc/apache2';
+ }
+ }
+ my ($release,$timestamp) = split(/\-/,$loncaparev);
+ my (%chksum,%revnum);
+ if (ref($lines) eq 'ARRAY') {
+ chomp(@{$lines});
+ my $version = shift(@{$lines});
+ if ($version eq $release) {
+ foreach my $line (@{$lines}) {
+ my ($file,$version,$shasum) = split(/,/,$line);
+ if ($file =~ m{^/etc/httpd/conf}) {
+ if ($webconfdir eq '/etc/apache2') {
+ $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
+ }
+ }
+ $chksum{$file} = $shasum;
+ $revnum{$file} = $version;
+ }
+ if (ref($hashref) eq 'HASH') {
+ %{$hashref} = (
+ sums => \%chksum,
+ versions => \%revnum,
+ );
+ }
+ }
+ }
return;
}
+
+sub fetch_dns_checksums {
+ my %checksums;
+ my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
+ my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
+ my ($release,$timestamp) = split(/\-/,$loncaparev);
+ &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
+ \%checksums);
+ return \%checksums;
+}
+
# ------------------------------------------------------------ Read domain file
{
my $loaded;
@@ -9809,10 +13640,10 @@ sub get_dns {
}
sub load_domain_tab {
- my ($ignore_cache) = @_;
- &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
+ my ($ignore_cache,$nocache) = @_;
+ &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
my $fh;
- if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
+ if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
my @lines = <$fh>;
&parse_domain_tab(\@lines);
}
@@ -9848,18 +13679,39 @@ sub get_dns {
my $loaded;
my %name_to_host;
my %internetdom;
+ my %LC_dns_serv;
sub parse_hosts_tab {
my ($file) = @_;
foreach my $configline (@$file) {
next if ($configline =~ /^(\#|\s*$ )/x);
- next if ($configline =~ /^\^/);
- chomp($configline);
+ chomp($configline);
+ if ($configline =~ /^\^/) {
+ if ($configline =~ /^\^([\w.\-]+)/) {
+ $LC_dns_serv{$1} = 1;
+ }
+ next;
+ }
my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
$name=~s/\s//g;
if ($id && $domain && $role && $name) {
+ if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
+ my $curr = $hostname{$id};
+ my $skip;
+ if (ref($name_to_host{$curr}) eq 'ARRAY') {
+ if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
+ $skip = 1;
+ } else {
+ @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
+ }
+ }
+ unless ($skip) {
+ push(@{$name_to_host{$name}},$id);
+ }
+ } else {
+ push(@{$name_to_host{$name}},$id);
+ }
$hostname{$id}=$name;
- push(@{$name_to_host{$name}}, $id);
$hostdom{$id}=$domain;
if ($role eq 'library') { $libserv{$id}=$name; }
if (defined($protocol)) {
@@ -9890,9 +13742,9 @@ sub get_dns {
}
sub load_hosts_tab {
- my ($ignore_cache) = @_;
- &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
- open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
+ my ($ignore_cache,$nocache) = @_;
+ &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
+ open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
my @config = <$config>;
&parse_hosts_tab(\@config);
close($config);
@@ -9913,7 +13765,8 @@ sub get_dns {
}
sub all_names {
- &load_hosts_tab() if (!$loaded);
+ my ($ignore_cache,$nocache) = @_;
+ &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
return %name_to_host;
}
@@ -9990,6 +13843,14 @@ sub get_dns {
my ($lonid) = @_;
return $internetdom{$lonid};
}
+
+ sub is_LC_dns {
+ &load_hosts_tab() if (!$loaded);
+
+ my ($hostname) = @_;
+ return exists($LC_dns_serv{$hostname});
+ }
+
}
{
@@ -10027,7 +13888,7 @@ sub get_dns {
}
sub get_iphost {
- my ($ignore_cache) = @_;
+ my ($ignore_cache,$nocache) = @_;
if (!$ignore_cache) {
if (%iphost) {
@@ -10051,7 +13912,7 @@ sub get_dns {
%old_name_to_ip = %{$ip_info->[1]};
}
- my %name_to_host = &all_names();
+ my %name_to_host = &all_names($ignore_cache,$nocache);
foreach my $name (keys(%name_to_host)) {
my $ip;
if (!exists($name_to_ip{$name})) {
@@ -10076,9 +13937,11 @@ sub get_dns {
}
push(@{$iphost{$ip}},@{$name_to_host{$name}});
}
- &Apache::lonnet::do_cache_new('iphost','iphost',
- [\%iphost,\%name_to_ip,\%lonid_to_ip],
- 48*60*60);
+ unless ($nocache) {
+ &do_cache_new('iphost','iphost',
+ [\%iphost,\%name_to_ip,\%lonid_to_ip],
+ 48*60*60);
+ }
return %iphost;
}
@@ -10134,11 +13997,48 @@ sub get_dns {
}
$seen{$prim_ip} = 1;
}
- return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
+ return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
}
}
+sub all_loncaparevs {
+ return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 2.11);
+}
+
+# ------------------------------------------------------- Read loncaparev table
+{
+ sub load_loncaparevs {
+ if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
+ if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
+ while (my $configline=<$config>) {
+ chomp($configline);
+ my ($hostid,$loncaparev)=split(/:/,$configline);
+ $loncaparevs{$hostid}=$loncaparev;
+ }
+ close($config);
+ }
+ }
+ }
+}
+
+# ----------------------------------------------------- Read serverhostID table
+{
+ sub load_serverhomeIDs {
+ if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
+ if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
+ while (my $configline=<$config>) {
+ chomp($configline);
+ my ($name,$id)=split(/:/,$configline);
+ $serverhomeIDs{$name}=$id;
+ }
+ close($config);
+ }
+ }
+ }
+}
+
+
BEGIN {
# ----------------------------------- Read loncapa.conf and loncapa_apache.conf
@@ -10151,7 +14051,7 @@ BEGIN {
# ------------------------------------------------------ Read spare server file
{
- open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
+ open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
while (my $configline=<$config>) {
chomp($configline);
@@ -10165,7 +14065,7 @@ BEGIN {
}
# ------------------------------------------------------------ Read permissions
{
- open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
+ open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
while (my $configline=<$config>) {
chomp($configline);
@@ -10179,7 +14079,7 @@ BEGIN {
# -------------------------------------------- Read plain texts for permissions
{
- open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
+ open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
while (my $configline=<$config>) {
chomp($configline);
@@ -10199,7 +14099,7 @@ BEGIN {
# ---------------------------------------------------------- Read package table
{
- open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
+ open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
while (my $configline=<$config>) {
if ($configline !~ /\S/ || $configline=~/^#/) { next; }
@@ -10214,42 +14114,64 @@ BEGIN {
close($config);
}
-# ---------------------------------------------------------- Read loncaparev table
+# --------------------------------------------------------- Read loncaparev table
+
+&load_loncaparevs();
+
+# ------------------------------------------------------- Read serverhostID table
+
+&load_serverhomeIDs();
+
+# ---------------------------------------------------------- Read releaseslist XML
{
- if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
- if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
- while (my $configline=<$config>) {
- chomp($configline);
- my ($hostid,$loncaparev)=split(/:/,$configline);
- $loncaparevs{$hostid}=$loncaparev;
+ my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
+ if (-e $file) {
+ my $parser = HTML::LCParser->new($file);
+ while (my $token = $parser->get_token()) {
+ if ($token->[0] eq 'S') {
+ my $item = $token->[1];
+ my $name = $token->[2]{'name'};
+ my $value = $token->[2]{'value'};
+ if ($item ne '' && $name ne '' && $value ne '') {
+ my $release = $parser->get_text();
+ $release =~ s/(^\s*|\s*$ )//gx;
+ $needsrelease{$item.':'.$name.':'.$value} = $release;
+ }
}
- close($config);
}
}
}
-# ---------------------------------------------------------- Read serverhostID table
+# ---------------------------------------------------------- Read managers table
{
- if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
- if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
+ if (-e "$perlvar{'lonTabDir'}/managers.tab") {
+ if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
while (my $configline=<$config>) {
chomp($configline);
- my ($name,$id)=split(/:/,$configline);
- $serverhomeIDs{$name}=$id;
+ next if ($configline =~ /^\#/);
+ if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
+ $managerstab{$configline} = 1;
+ }
}
close($config);
}
}
}
-sub all_loncaparevs {
- return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10);
+# ------------- set up temporary directory
+{
+ $tmpdir = LONCAPA::tempdir();
+
}
-# ------------- set up temporary directory
+# ------------- set default texengine (domain default overrides this)
{
- $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
+ $deftex = LONCAPA::texengine();
+}
+# ------------- set default minimum length for passwords for internal auth users
+{
+ $passwdmin = LONCAPA::passwd_min();
}
$memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
@@ -10409,8 +14331,8 @@ were new keys. I.E. 1:foo will become 1:
Calling convention:
- my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
- &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
+ my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
+ &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
For more detailed information, see lonnet specific documentation.
@@ -10509,7 +14431,13 @@ B