--- loncom/lonnet/perl/lonnet.pm 2004/08/25 16:03:17 1.532 +++ loncom/lonnet/perl/lonnet.pm 2005/10/27 17:01:35 1.668 @@ -1,7 +1,7 @@ # The LearningOnline Network # TCP networking package # -# $Id: lonnet.pm,v 1.532 2004/08/25 16:03:17 albertel Exp $ +# $Id: lonnet.pm,v 1.668 2005/10/27 17:01:35 raeburn Exp $ # # Copyright Michigan State University Board of Trustees # @@ -35,23 +35,31 @@ use HTTP::Headers; use HTTP::Date; # use Date::Parse; use vars -qw(%perlvar %hostname %homecache %badServerCache %hostip %iphost %spareid %hostdom - %libserv %pr %prp %metacache %packagetab %titlecache %courseresversioncache %resversioncache - %courselogs %accesshash %userrolehash $processmarker $dumpcount - %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseresdatacache - %userresdatacache %usectioncache %domaindescription %domain_auth_def %domain_auth_arg_def - %domain_lang_def %domain_city %domain_longi %domain_lati $tmpdir); +qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom + %libserv %pr %prp $memcache %packagetab + %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount + %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf + %domaindescription %domain_auth_def %domain_auth_arg_def + %domain_lang_def %domain_city %domain_longi %domain_lati $tmpdir $_64bit + %env); use IO::Socket; use GDBM_File; use Apache::Constants qw(:common :http); use HTML::LCParser; +use HTML::Parser; use Fcntl qw(:flock); -use Apache::loncoursedata; use Apache::lonlocal; -use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw); -use Time::HiRes(); +use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze); +use Time::HiRes qw( gettimeofday tv_interval ); +use Cache::Memcached; my $readit; +my $max_connection_retries = 10; # Or some such value. + +require Exporter; + +our @ISA = qw (Exporter); +our @EXPORT = qw(%env); =pod @@ -116,14 +124,40 @@ sub logperm { sub subreply { my ($cmd,$server)=@_; my $peerfile="$perlvar{'lonSockDir'}/$server"; - my $client=IO::Socket::UNIX->new(Peer =>"$peerfile", - Type => SOCK_STREAM, - Timeout => 10) - or return "con_lost"; - print $client "$cmd\n"; - my $answer=<$client>; - if (!$answer) { $answer="con_lost"; } - chomp($answer); + # + # With loncnew process trimming, there's a timing hole between lonc server + # process exit and the master server picking up the listen on the AF_UNIX + # socket. In that time interval, a lock file will exist: + + my $lockfile=$peerfile.".lock"; + while (-e $lockfile) { # Need to wait for the lockfile to disappear. + sleep(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. + # + # We'll give the connection a few tries before abandoning it. If + # connection is not possible, we'll con_lost back to the client. + # + my $client; + for (my $retries = 0; $retries < $max_connection_retries; $retries++) { + $client=IO::Socket::UNIX->new(Peer =>"$peerfile", + Type => SOCK_STREAM, + Timeout => 10); + if($client) { + last; # Connected! + } + sleep(1); # Try again later if failed connection. + } + my $answer; + if ($client) { + print $client "$cmd\n"; + $answer=<$client>; + if (!$answer) { $answer="con_lost"; } + chomp($answer); + } else { + $answer = 'con_lost'; # Failed connection. + } return $answer; } @@ -131,22 +165,6 @@ sub reply { my ($cmd,$server)=@_; unless (defined($hostname{$server})) { return 'no_such_host'; } my $answer=subreply($cmd,$server); - if ($answer eq 'con_lost') { - #sleep 5; - #$answer=subreply($cmd,$server); - #if ($answer eq 'con_lost') { - # &logthis("Second attempt con_lost on $server"); - # my $peerfile="$perlvar{'lonSockDir'}/$server"; - # my $client=IO::Socket::UNIX->new(Peer =>"$peerfile", - # Type => SOCK_STREAM, - # Timeout => 10) - # or return "con_lost"; - # &logthis("Killing socket"); - # print $client "close_connection_exit\n"; - #sleep 5; - # $answer=subreply($cmd,$server); - #} - } if (($answer=~/^refused/) || ($answer=~/^rejected/)) { &logthis("WARNING:". " $cmd to $server returned $answer"); @@ -194,11 +212,8 @@ sub critical { } my $answer=reply($cmd,$server); if ($answer eq 'con_lost') { - my $pingreply=reply('ping',$server); &reconlonc("$perlvar{'lonSockDir'}/$server"); - my $pongreply=reply('pong',$server); - &logthis("Ping/Pong for $server: $pingreply/$pongreply"); - $answer=reply($cmd,$server); + my $answer=reply($cmd,$server); if ($answer eq 'con_lost') { my $now=time; my $middlename=$cmd; @@ -240,20 +255,6 @@ sub critical { return $answer; } -# -# -------------- Remove all key from the env that start witha lowercase letter -# (Which is always a lon-capa value) - -sub cleanenv { -# unless (defined(&Apache::exists_config_define("MODPERL2"))) { return; } -# unless (&Apache::exists_config_define("MODPERL2")) { return; } - foreach my $key (keys(%ENV)) { - if ($key =~ /^[a-z]/) { - delete($ENV{$key}); - } - } -} - # ------------------------------------------- Transfer profile into environment sub transfer_profile_to_env { @@ -270,14 +271,14 @@ sub transfer_profile_to_env { for ($envi=0;$envi<=$#profile;$envi++) { chomp($profile[$envi]); my ($envname,$envvalue)=split(/=/,$profile[$envi]); - $ENV{$envname} = $envvalue; + $env{$envname} = $envvalue; if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) { if ($time < time-300) { $Remove{$key}++; } } } - $ENV{'user.environment'} = "$lonidsdir/$handle.id"; + $env{'user.environment'} = "$lonidsdir/$handle.id"; foreach my $expired_key (keys(%Remove)) { &delenv($expired_key); } @@ -294,12 +295,12 @@ sub appenv { .''); delete($newenv{$_}); } else { - $ENV{$_}=$newenv{$_}; + $env{$_}=$newenv{$_}; } } my $lockfh; - unless (open($lockfh,"$ENV{'user.environment'}")) { + unless (open($lockfh,"$env{'user.environment'}")) { return 'error: '.$!; } unless (flock($lockfh,LOCK_EX)) { @@ -312,7 +313,7 @@ sub appenv { my @oldenv; { my $fh; - unless (open($fh,"$ENV{'user.environment'}")) { + unless (open($fh,"$env{'user.environment'}")) { return 'error: '.$!; } @oldenv=<$fh>; @@ -329,7 +330,7 @@ sub appenv { } { my $fh; - unless (open($fh,">$ENV{'user.environment'}")) { + unless (open($fh,">$env{'user.environment'}")) { return 'error'; } my $newname; @@ -355,7 +356,7 @@ sub delenv { my @oldenv; { my $fh; - unless (open($fh,"$ENV{'user.environment'}")) { + unless (open($fh,"$env{'user.environment'}")) { return 'error'; } unless (flock($fh,LOCK_SH)) { @@ -369,7 +370,7 @@ sub delenv { } { my $fh; - unless (open($fh,">$ENV{'user.environment'}")) { + unless (open($fh,">$env{'user.environment'}")) { return 'error'; } unless (flock($fh,LOCK_EX)) { @@ -381,7 +382,7 @@ sub delenv { foreach (@oldenv) { if ($_=~/^$delthis/) { my ($key,undef) = split('=',$_); - delete($ENV{$key}); + delete($env{$key}); } else { print $fh $_; } @@ -434,7 +435,7 @@ sub overloaderror { if ($overload>0) { $r->err_headers_out->{'Retry-After'}=$overload; $r->log_error('Overload of '.$overload.' on '.$checkserver); - return 409; + return 413; } return ''; } @@ -551,12 +552,12 @@ sub authenticate { # ---------------------- Find the homebase for a user from domain's lib servers +my %homecache; sub homeserver { my ($uname,$udom,$ignoreBadCache)=@_; my $index="$uname:$udom"; - my ($result,$cached)=&is_cached(\%homecache,$index,'home',86400); - if (defined($cached)) { return $result; } + if (exists($homecache{$index})) { return $homecache{$index}; } my $tryserver; foreach $tryserver (keys %libserv) { next if ($ignoreBadCache ne 'true' && @@ -564,7 +565,7 @@ sub homeserver { if ($hostdom{$tryserver} eq $udom) { my $answer=reply("home:$udom:$uname",$tryserver); if ($answer eq 'found') { - return &do_cache(\%homecache,$index,$tryserver,'home'); + return $homecache{$index}=$tryserver; } elsif ($answer eq 'no_host') { $badServerCache{$tryserver}=1; } @@ -644,15 +645,15 @@ sub assign_access_key { # my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_; $kdom= - $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($kdom)); + $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom)); $knum= - $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($knum)); + $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum)); $cdom= - $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom)); + $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom)); $cnum= - $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum)); - $udom=$ENV{'user.name'} unless (defined($udom)); - $uname=$ENV{'user.domain'} unless (defined($uname)); + $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum)); + $udom=$env{'user.name'} unless (defined($udom)); + $uname=$env{'user.domain'} unless (defined($uname)); my %existing=&get('accesskeys',[$ckey],$kdom,$knum); if (($existing{$ckey}=~/^\#(.*)$/) || # - new key ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { @@ -694,9 +695,9 @@ sub comment_access_key { # my ($ckey,$cdom,$cnum,$logentry)=@_; $cdom= - $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom)); + $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom)); $cnum= - $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum)); + $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum)); my %existing=&get('accesskeys',[$ckey],$cdom,$cnum); if ($existing{$ckey}) { $existing{$ckey}.='; '.$logentry; @@ -718,9 +719,9 @@ sub comment_access_key { sub generate_access_keys { my ($number,$cdom,$cnum,$logentry)=@_; $cdom= - $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom)); + $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom)); $cnum= - $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum)); + $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum)); unless (&allowed('mky',$cdom)) { return 0; } unless (($cdom) && ($cnum)) { return 0; } if ($number>10000) { return 0; } @@ -739,14 +740,14 @@ sub generate_access_keys { } else { if (&put('accesskeys', { $newkey => '# generated '.localtime(). - ' by '.$ENV{'user.name'}.'@'.$ENV{'user.domain'}. + ' by '.$env{'user.name'}.'@'.$env{'user.domain'}. '; '.$logentry }, $cdom,$cnum) eq 'ok') { $total++; } } } - &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'}, + &log($env{'user.domain'},$env{'user.name'},$env{'user.home'}, 'Generated '.$total.' keys for '.$cnum.' at '.$cdom); return $total; } @@ -756,21 +757,34 @@ sub generate_access_keys { sub validate_access_key { my ($ckey,$cdom,$cnum,$udom,$uname)=@_; $cdom= - $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom)); + $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom)); $cnum= - $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum)); - $udom=$ENV{'user.domain'} unless (defined($udom)); - $uname=$ENV{'user.name'} unless (defined($uname)); + $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum)); + $udom=$env{'user.domain'} unless (defined($udom)); + $uname=$env{'user.name'} unless (defined($uname)); my %existing=&get('accesskeys',[$ckey],$cdom,$cnum); return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/); } # ------------------------------------- Find the section of student in a course +sub devalidate_getsection_cache { + my ($udom,$unam,$courseid)=@_; + $courseid=~s/\_/\//g; + $courseid=~s/^(\w)/\/$1/; + my $hashid="$udom:$unam:$courseid"; + &devalidate_cache_new('getsection',$hashid); +} sub getsection { my ($udom,$unam,$courseid)=@_; + my $cachetime=1800; $courseid=~s/\_/\//g; $courseid=~s/^(\w)/\/$1/; + + my $hashid="$udom:$unam:$courseid"; + my ($result,$cached)=&is_cached_new('getsection',$hashid); + if (defined($cached)) { return $result; } + my %Pending; my %Expired; # @@ -795,200 +809,120 @@ sub getsection { if ($key eq $courseid.'_st') { $section=''; } my ($dummy,$end,$start)=split(/\_/,&unescape($value)); my $now=time; - if (defined($end) && ($now > $end)) { + if (defined($end) && $end && ($now > $end)) { $Expired{$end}=$section; next; } - if (defined($start) && ($now < $start)) { + if (defined($start) && $start && ($now < $start)) { $Pending{$start}=$section; next; } - return $section; + return &do_cache_new('getsection',$hashid,$section,$cachetime); } # # Presumedly there will be few matching roles from the above # loop and the sorting time will be negligible. if (scalar(keys(%Pending))) { my ($time) = sort {$a <=> $b} keys(%Pending); - return $Pending{$time}; + return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime); } if (scalar(keys(%Expired))) { my @sorted = sort {$a <=> $b} keys(%Expired); my $time = pop(@sorted); - return $Expired{$time}; + return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime); } - return '-1'; + return &do_cache_new('getsection',$hashid,'-1',$cachetime); } - -my $disk_caching_disabled=1; - -sub devalidate_cache { - my ($cache,$id,$name) = @_; - delete $$cache{$id.'.time'}; - delete $$cache{$id}; - if ($disk_caching_disabled) { return; } - my $filename=$perlvar{'lonDaemons'}.'/tmp/lonnet_internal_cache_'.$name.".db"; - open(DB,"$filename.lock"); - flock(DB,LOCK_EX); - my %hash; - if (tie(%hash,'GDBM_File',$filename,&GDBM_WRCREAT(),0640)) { - eval <<'EVALBLOCK'; - delete($hash{$id}); - delete($hash{$id.'.time'}); -EVALBLOCK - if ($@) { - &logthis("devalidate_cache blew up :$@:$name"); - unlink($filename); - } - } else { - if (-e $filename) { - &logthis("Unable to tie hash (devalidate cache): $name"); - unlink($filename); - } - } - untie(%hash); - flock(DB,LOCK_UN); - close(DB); -} - -sub is_cached { - my ($cache,$id,$name,$time) = @_; - if (!$time) { $time=300; } - if (!exists($$cache{$id.'.time'})) { - &load_cache_item($cache,$name,$id); - } - if (!exists($$cache{$id.'.time'})) { -# &logthis("Didn't find $id"); +sub save_cache { + my ($r)=@_; + if (! $r->is_initial_req()) { return DECLINED; } + &purge_remembered(); + undef(%env); + return OK; +} + +my $to_remember=-1; +my %remembered; +my %accessed; +my $kicks=0; +my $hits=0; +sub devalidate_cache_new { + my ($name,$id,$debug) = @_; + if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); } + $id=&escape($name.':'.$id); + $memcache->delete($id); + delete($remembered{$id}); + delete($accessed{$id}); +} + +sub is_cached_new { + my ($name,$id,$debug) = @_; + $id=&escape($name.':'.$id); + if (exists($remembered{$id})) { + if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); } + $accessed{$id}=[&gettimeofday()]; + $hits++; + return ($remembered{$id},1); + } + my $value = $memcache->get($id); + if (!(defined($value))) { + if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); } return (undef,undef); - } else { - if (time-($$cache{$id.'.time'})>$time) { -# &logthis("Devalidating $id - ".time-($$cache{$id.'.time'})); - &devalidate_cache($cache,$id,$name); - return (undef,undef); - } - } - return ($$cache{$id},1); -} - -sub do_cache { - my ($cache,$id,$value,$name) = @_; - $$cache{$id.'.time'}=time; - $$cache{$id}=$value; -# &logthis("Caching $id as :$value:"); - &save_cache_item($cache,$name,$id); - # do_cache implictly return the set value - $$cache{$id}; -} - -sub save_cache_item { - my ($cache,$name,$id)=@_; - if ($disk_caching_disabled) { return; } - my $starttime=&Time::HiRes::time(); -# &logthis("Saving :$name:$id"); - my %hash; - my $filename=$perlvar{'lonDaemons'}.'/tmp/lonnet_internal_cache_'.$name.".db"; - open(DB,"$filename.lock"); - flock(DB,LOCK_EX); - if (tie(%hash,'GDBM_File',$filename,&GDBM_WRCREAT(),0640)) { - eval <<'EVALBLOCK'; - $hash{$id.'.time'}=$$cache{$id.'.time'}; - $hash{$id}=freeze({'item'=>$$cache{$id}}); -EVALBLOCK - if ($@) { - &logthis("save_cache blew up :$@:$name"); - unlink($filename); - } - } else { - if (-e $filename) { - &logthis("Unable to tie hash (save cache item): $name ($!)"); - unlink($filename); - } - } - untie(%hash); - flock(DB,LOCK_UN); - close(DB); -# &logthis("save_cache_item $name took ".(&Time::HiRes::time()-$starttime)); -} - -sub load_cache_item { - my ($cache,$name,$id)=@_; - if ($disk_caching_disabled) { return; } - my $starttime=&Time::HiRes::time(); -# &logthis("Before Loading $name for $id size is ".scalar(%$cache)); - my %hash; - my $filename=$perlvar{'lonDaemons'}.'/tmp/lonnet_internal_cache_'.$name.".db"; - open(DB,"$filename.lock"); - flock(DB,LOCK_SH); - if (tie(%hash,'GDBM_File',$filename,&GDBM_READER(),0640)) { - eval <<'EVALBLOCK'; - if (!%$cache) { - my $count; - while (my ($key,$value)=each(%hash)) { - $count++; - if ($key =~ /\.time$/) { - $$cache{$key}=$value; - } else { - my $hashref=thaw($value); - $$cache{$key}=$hashref->{'item'}; - } - } -# &logthis("Initial load: $count"); - } else { - my $hashref=thaw($hash{$id}); - $$cache{$id}=$hashref->{'item'}; - $$cache{$id.'.time'}=$hash{$id.'.time'}; - } -EVALBLOCK - if ($@) { - &logthis("load_cache blew up :$@:$name"); - unlink($filename); - } - } else { - if (-e $filename) { - &logthis("Unable to tie hash (load cache item): $name ($!)"); - unlink($filename); - } } - untie(%hash); - flock(DB,LOCK_UN); - close(DB); -# &logthis("After Loading $name size is ".scalar(%$cache)); -# &logthis("load_cache_item $name took ".(&Time::HiRes::time()-$starttime)); + if ($value eq '__undef__') { + if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); } + $value=undef; + } + &make_room($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) = @_; + $id=&escape($name.':'.$id); + my $setvalue=$value; + if (!defined($setvalue)) { + $setvalue='__undef__'; + } + if (!defined($time) ) { + $time=600; + } + if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); } + $memcache->set($id,$setvalue,$time); + # need to make a copy of $value + #&make_room($id,$value,$debug); + return $value; +} + +sub make_room { + my ($id,$value,$debug)=@_; + $remembered{$id}=$value; + if ($to_remember<0) { return; } + $accessed{$id}=[&gettimeofday()]; + if (scalar(keys(%remembered)) <= $to_remember) { return; } + my $to_kick; + my $max_time=0; + foreach my $other (keys(%accessed)) { + if (&tv_interval($accessed{$other}) > $max_time) { + $to_kick=$other; + $max_time=&tv_interval($accessed{$other}); + } + } + delete($remembered{$to_kick}); + delete($accessed{$to_kick}); + $kicks++; + if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); } + return; +} + +sub purge_remembered { + #&logthis("Tossing ".scalar(keys(%remembered))); + #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered)))); + undef(%remembered); + undef(%accessed); } - -sub usection { - my ($udom,$unam,$courseid)=@_; - my $hashid="$udom:$unam:$courseid"; - - my ($result,$cached)=&is_cached(\%usectioncache,$hashid,'usection'); - if (defined($cached)) { return $result; } - $courseid=~s/\_/\//g; - $courseid=~s/^(\w)/\/$1/; - foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles', - &homeserver($unam,$udom)))) { - my ($key,$value)=split(/\=/,$_); - $key=&unescape($key); - if ($key=~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/) { - my $section=$1; - if ($key eq $courseid.'_st') { $section=''; } - my ($dummy,$end,$start)=split(/\_/,&unescape($value)); - my $now=time; - my $notactive=0; - if ($start) { - if ($now<$start) { $notactive=1; } - } - if ($end) { - if ($now>$end) { $notactive=1; } - } - unless ($notactive) { - return &do_cache(\%usectioncache,$hashid,$section,'usection'); - } - } - } - return &do_cache(\%usectioncache,$hashid,'-1','usection'); -} - # ------------------------------------- Read an entry from a user's environment sub userenvironment { @@ -1004,15 +938,28 @@ sub userenvironment { return %returnhash; } +# ---------------------------------------------------------- Get a studentphoto +sub studentphoto { + my ($udom,$unam,$ext) = @_; + my $home=&Apache::lonnet::homeserver($unam,$udom); + my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext",$home); + my $url="/uploaded/$udom/$unam/internal/studentphoto.".$ext; + if ($ret ne 'ok') { + return '/adm/lonKaputt/lonlogo_broken.gif'; + } + my $tokenurl=&Apache::lonnet::tokenwrapper($url); + return $tokenurl; +} + # -------------------------------------------------------------------- New chat sub chatsend { my ($newentry,$anon)=@_; - my $cnum=$ENV{'course.'.$ENV{'request.course.id'}.'.num'}; - my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'}; - my $chome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'}; + my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'}; + my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'}; + my $chome=$env{'course.'.$env{'request.course.id'}.'.home'}; &reply('chatsend:'.$cdom.':'.$cnum.':'. - &escape($ENV{'user.domain'}.':'.$ENV{'user.name'}.':'.$anon.':'. + &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'. &escape($newentry)),$chome); } @@ -1026,7 +973,7 @@ sub getversion { sub currentversion { my $fname=shift; - my ($result,$cached)=&is_cached(\%resversioncache,$fname,'resversion',600); + my ($result,$cached)=&is_cached_new('resversion',$fname); if (defined($cached)) { return $result; } my $author=$fname; $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/; @@ -1039,7 +986,7 @@ sub currentversion { if (($answer eq 'con_lost') || ($answer eq 'rejected')) { return -1; } - return &do_cache(\%resversioncache,$fname,$answer,'resversion'); + return &do_cache_new('resversion',$fname,$answer,600); } # ----------------------------- Subscribe to a resource, return URL if possible @@ -1067,22 +1014,27 @@ sub subscribe { sub repcopy { my $filename=shift; $filename=~s/\/+/\//g; - if ($filename=~/^\/home\/httpd\/html\/adm\//) { return OK; } + 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)/-) { + return &repcopy_userfile($filename); + } $filename=~s/[\n\r]//g; my $transname="$filename.in.transfer"; - if ((-e $filename) || (-e $transname)) { return OK; } + if ((-e $filename) || (-e $transname)) { return 'ok'; } my $remoteurl=subscribe($filename); if ($remoteurl =~ /^con_lost by/) { &logthis("Subscribe returned $remoteurl: $filename"); - return HTTP_SERVICE_UNAVAILABLE; + return 'unavailable'; } elsif ($remoteurl eq 'not_found') { #&logthis("Subscribe returned not_found: $filename"); - return HTTP_NOT_FOUND; + return 'not_found'; } elsif ($remoteurl =~ /^rejected by/) { &logthis("Subscribe returned $remoteurl: $filename"); - return FORBIDDEN; + return 'forbidden'; } elsif ($remoteurl eq 'directory') { - return OK; + return 'ok'; } else { my $author=$filename; $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/; @@ -1093,7 +1045,7 @@ sub repcopy { my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]"; if ($path ne "$perlvar{'lonDocRoot'}/res") { &logthis("Malconfiguration for replication: $filename"); - return HTTP_BAD_REQUEST; + return 'bad_request'; } my $count; for ($count=5;$count<$#parts;$count++) { @@ -1110,7 +1062,7 @@ sub repcopy { my $message=$response->status_line; &logthis("WARNING:" ." LWP get: $message: $filename"); - return HTTP_SERVICE_UNAVAILABLE; + return 'unavailable'; } else { if ($remoteurl!~/\.meta$/) { my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta'); @@ -1122,7 +1074,7 @@ sub repcopy { } } rename($transname,$filename); - return OK; + return 'ok'; } } } @@ -1131,10 +1083,12 @@ sub repcopy { # ------------------------------------------------ Get server side include body sub ssi_body { my ($filelink,%form)=@_; + if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) { + $form{'LONCAPA_INTERNAL_no_discussion'}='true'; + } my $output=($filelink=~/^http\:/?&externalssi($filelink): &ssi($filelink,%form)); - $output=~ - s/\/\/ BEGIN LON\-CAPA Internal.+\/\/ END LON\-CAPA Internal\s//gs; + $output=~s|//(\s*)?\s||gs; $output=~s/^.*?\
]*\>//si; $output=~s/(.*)\<\/body\s*\>.*?$/$1/si; return $output; @@ -1185,8 +1139,11 @@ sub allowuploaded { } # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course -# input: action, courseID, current domain, home server for course, intended -# path to file, source of file. +# 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. +# # output: url to file (if action was uploaddoc), # ok if successful, or diagnostic message otherwise (if action was propagate or copy) # @@ -1205,34 +1162,25 @@ sub allowuploaded { # course's home server. # # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file -# will be retrived from $ENV{form.uploaddoc} (from DOCS interface) to +# will be retrived from $env{form.uploaddoc} (from DOCS interface) to # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file # in course's home server. - +# sub process_coursefile { - my ($action,$docuname,$docudom,$docuhome,$file,$source)=@_; + my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_; my $fetchresult; + my $home=&homeserver($docuname,$docudom); if ($action eq 'propagate') { - $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file - ,$docuhome); + $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file, + $home); } else { - my $fetchresult = ''; my $fpath = ''; my $fname = $file; ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|); $fpath=$docudom.'/'.$docuname.'/'.$fpath; - my $filepath=$perlvar{'lonDocRoot'}.'/userfiles'; - unless ($fpath eq '') { - my @parts=split('/',$fpath); - foreach my $part (@parts) { - $filepath.= '/'.$part; - if ((-e $filepath)!=1) { - mkdir($filepath,0777); - } - } - } + my $filepath = &build_filepath($fpath); if ($action eq 'copy') { if ($source eq '') { $fetchresult = 'no source file'; @@ -1241,33 +1189,74 @@ sub process_coursefile { my $destination = $filepath.'/'.$fname; rename($source,$destination); $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file, - $docuhome); + $home); } } elsif ($action eq 'uploaddoc') { open(my $fh,'>'.$filepath.'/'.$fname); - print $fh $ENV{'form.'.$source}; + print $fh $env{'form.'.$source}; close($fh); + if ($parser eq 'parse') { + 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); + } + } $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file, - $docuhome); + $home); if ($fetchresult eq 'ok') { return '/uploaded/'.$fpath.'/'.$fname; } else { &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file. - ' to host '.$docuhome.': '.$fetchresult); + ' to host '.$home.': '.$fetchresult); return '/adm/notfound.html'; } } } unless ( $fetchresult eq 'ok') { &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file. - ' to host '.$docuhome.': '.$fetchresult); + ' to host '.$home.': '.$fetchresult); } return $fetchresult; } -# --------------- Take an uploaded file and put it into the userfiles directory -# input: name of form element, coursedoc=1 means this is for the course -# output: url of file in userspace +sub build_filepath { + my ($fpath) = @_; + my $filepath=$perlvar{'lonDocRoot'}.'/userfiles'; + unless ($fpath eq '') { + my @parts=split('/',$fpath); + foreach my $part (@parts) { + $filepath.= '/'.$part; + if ((-e $filepath)!=1) { + mkdir($filepath,0777); + } + } + } + return $filepath; +} + +sub store_edited_file { + my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_; + my $file = $primary_url; + $file =~ s#^/uploaded/$docudom/$docuname/##; + my $fpath = ''; + my $fname = $file; + ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|); + $fpath=$docudom.'/'.$docuname.'/'.$fpath; + my $filepath = &build_filepath($fpath); + open(my $fh,'>'.$filepath.'/'.$fname); + print $fh $content; + close($fh); + my $home=&homeserver($docuname,$docudom); + $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file, + $home); + if ($$fetchresult eq 'ok') { + return '/uploaded/'.$fpath.'/'.$fname; + } else { + &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file. + ' to host '.$home.': '.$$fetchresult); + return '/adm/notfound.html'; + } +} sub clean_filename { my ($fname)=@_; @@ -1279,17 +1268,25 @@ sub clean_filename { $fname=~s/\s+/\_/g; # Replace all other weird characters by nothing $fname=~s/[^\w\.\-]//g; +# Replace all .\d. sequences with _\d. so they no longer look like version +# numbers + $fname=~s/\.(\d+)(?=\.)/_$1/g; return $fname; } +# --------------- Take an uploaded file and put it into the userfiles directory +# input: name of form element, coursedoc=1 means this is for the course +# output: url of file in userspace + + sub userfileupload { - my ($formname,$coursedoc,$subdir)=@_; + my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase)=@_; if (!defined($subdir)) { $subdir='unknown'; } - my $fname=$ENV{'form.'.$formname.'.filename'}; + my $fname=$env{'form.'.$formname.'.filename'}; $fname=&clean_filename($fname); # See if there is anything left unless ($fname) { return 'error: no uploaded file'; } - chop($ENV{'form.'.$formname}); + chop($env{'form.'.$formname}); if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently my $now = time; my $filepath = 'tmp/helprequests/'.$now; @@ -1302,35 +1299,35 @@ sub userfileupload { } } open(my $fh,'>'.$fullpath.'/'.$fname); - print $fh $ENV{'form.'.$formname}; + print $fh $env{'form.'.$formname}; close($fh); return $fullpath.'/'.$fname; } # Create the directory if not present - my $docuname=''; - my $docudom=''; - my $docuhome=''; $fname="$subdir/$fname"; if ($coursedoc) { - $docuname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'}; - $docudom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'}; - $docuhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'}; - if ($ENV{'form.folder'} =~ m/^default/) { - return &finishuserfileupload($docuname,$docudom,$docuhome,$formname,$fname); + my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'}; + my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'}; + if ($env{'form.folder'} =~ m/^(default|supplemental)/) { + return &finishuserfileupload($docuname,$docudom, + $formname,$fname,$parser,$allfiles, + $codebase); } else { - $fname=$ENV{'form.folder'}.'/'.$fname; - return &process_coursefile('uploaddoc',$docuname,$docudom,$docuhome,$fname,$formname); + $fname=$env{'form.folder'}.'/'.$fname; + return &process_coursefile('uploaddoc',$docuname,$docudom, + $fname,$formname,$parser, + $allfiles,$codebase); } } else { - $docuname=$ENV{'user.name'}; - $docudom=$ENV{'user.domain'}; - $docuhome=$ENV{'user.home'}; - return &finishuserfileupload($docuname,$docudom,$docuhome,$formname,$fname); + my $docuname=$env{'user.name'}; + my $docudom=$env{'user.domain'}; + return &finishuserfileupload($docuname,$docudom,$formname, + $fname,$parser,$allfiles,$codebase); } } sub finishuserfileupload { - my ($docuname,$docudom,$docuhome,$formname,$fname)=@_; + my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_; my $path=$docudom.'/'.$docuname.'/'; my $filepath=$perlvar{'lonDocRoot'}; my ($fnamepath,$file); @@ -1349,13 +1346,21 @@ sub finishuserfileupload { } # Save the file { - #&Apache::lonnet::logthis("Saving to $filepath $file"); - open(my $fh,'>'.$filepath.'/'.$file); - print $fh $ENV{'form.'.$formname}; - close($fh); + open(FH,'>'.$filepath.'/'.$file); + print FH $env{'form.'.$formname}; + close(FH); + } + if ($parser eq 'parse') { + my $parse_result = &extract_embedded_items($filepath,$file,$allfiles, + $codebase); + unless ($parse_result eq 'ok') { + &logthis('Failed to parse '.$filepath.$file. + ' for embedded media: '.$parse_result); + } } # Notify homeserver to grep it # + my $docuhome=&homeserver($docuname,$docudom); my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome); if ($fetchresult eq 'ok') { # @@ -1368,10 +1373,118 @@ sub finishuserfileupload { } } +sub extract_embedded_items { + my ($filepath,$file,$allfiles,$codebase,$content) = @_; + my @state = (); + my %javafiles = ( + codebase => '', + code => '', + archive => '' + ); + my %mediafiles = ( + src => '', + movie => '', + ); + my $p; + if ($content) { + $p = HTML::LCParser->new($content); + } else { + $p = HTML::LCParser->new($filepath.'/'.$file); + } + while (my $t=$p->get_token()) { + if ($t->[0] eq 'S') { + my ($tagname, $attr) = ($t->[1],$t->[2]); + push (@state, $tagname); + if (lc($tagname) eq 'allow') { + &add_filetype($allfiles,$attr->{'src'},'src'); + } + if (lc($tagname) eq 'img') { + &add_filetype($allfiles,$attr->{'src'},'src'); + } + if (lc($tagname) eq 'script') { + if ($attr->{'archive'} =~ /\.jar$/i) { + &add_filetype($allfiles,$attr->{'archive'},'archive'); + } else { + &add_filetype($allfiles,$attr->{'src'},'src'); + } + } + if (lc($tagname) eq 'link') { + if (lc($attr->{'rel'}) eq 'stylesheet') { + &add_filetype($allfiles,$attr->{'href'},'href'); + } + } + if (lc($tagname) eq 'object' || + (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) { + foreach my $item (keys(%javafiles)) { + $javafiles{$item} = ''; + } + } + if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') { + my $name = lc($attr->{'name'}); + foreach my $item (keys(%javafiles)) { + if ($name eq $item) { + $javafiles{$item} = $attr->{'value'}; + last; + } + } + foreach my $item (keys(%mediafiles)) { + if ($name eq $item) { + &add_filetype($allfiles, $attr->{'value'}, 'value'); + last; + } + } + } + if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') { + foreach my $item (keys(%javafiles)) { + if ($attr->{$item}) { + $javafiles{$item} = $attr->{$item}; + last; + } + } + foreach my $item (keys(%mediafiles)) { + if ($attr->{$item}) { + &add_filetype($allfiles,$attr->{$item},$item); + last; + } + } + } + } elsif ($t->[0] eq 'E') { + my ($tagname) = ($t->[1]); + if ($javafiles{'codebase'} ne '') { + $javafiles{'codebase'} .= '/'; + } + if (lc($tagname) eq 'applet' || + lc($tagname) eq 'object' || + (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object') + ) { + foreach my $item (keys(%javafiles)) { + if ($item ne 'codebase' && $javafiles{$item} ne '') { + my $file=$javafiles{'codebase'}.$javafiles{$item}; + &add_filetype($allfiles,$file,$item); + } + } + } + pop @state; + } + } + return 'ok'; +} + +sub add_filetype { + my ($allfiles,$file,$type)=@_; + if (exists($allfiles->{$file})) { + unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) { + push(@{$allfiles->{$file}}, &escape($type)); + } + } else { + @{$allfiles->{$file}} = (&escape($type)); + } +} + sub removeuploadedurl { my ($url)=@_; my (undef,undef,$udom,$uname,$fname)=split('/',$url,5); - return &Apache::lonnet::removeuserfile($uname,$udom,$fname); + return &removeuserfile($uname,$udom,$fname); } sub removeuserfile { @@ -1433,12 +1546,12 @@ sub flushcourselogs { if ($courseidbuffer{$coursehombuf{$crsid}}) { $courseidbuffer{$coursehombuf{$crsid}}.='&'. &escape($crsid).'='.&escape($coursedescrbuf{$crsid}). - '='.&escape($courseinstcodebuf{$crsid}); + ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}); } else { $courseidbuffer{$coursehombuf{$crsid}}= &escape($crsid).'='.&escape($coursedescrbuf{$crsid}). - '='.&escape($courseinstcodebuf{$crsid}); - } + ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}); + } } # # Write course id database (reverse lookup) to homeserver of courses @@ -1457,9 +1570,9 @@ sub flushcourselogs { ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:); if (! defined($dom) || $dom eq '' || ! defined($name) || $name eq '') { - my $cid = $ENV{'request.course.id'}; - $dom = $ENV{'request.'.$cid.'.domain'}; - $name = $ENV{'request.'.$cid.'.num'}; + my $cid = $env{'request.course.id'}; + $dom = $env{'request.'.$cid.'.domain'}; + $name = $env{'request.'.$cid.'.num'}; } my $value = $accesshash{$entry}; my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/); @@ -1496,42 +1609,81 @@ sub flushcourselogs { delete $userrolehash{$entry}; } } +# +# Reverse lookup of domain roles (dc, ad, li, sc, au) +# + my %domrolebuffer = (); + foreach my $entry (keys %domainrolehash) { + my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry; + if ($domrolebuffer{$rudom}) { + $domrolebuffer{$rudom}.='&'.&escape($entry). + '='.&escape($domainrolehash{$entry}); + } else { + $domrolebuffer{$rudom}.=&escape($entry). + '='.&escape($domainrolehash{$entry}); + } + delete $domainrolehash{$entry}; + } + foreach my $dom (keys(%domrolebuffer)) { + foreach my $tryserver (keys %libserv) { + if ($hostdom{$tryserver} eq $dom) { + unless (&reply('domroleput:'.$dom.':'. + $domrolebuffer{$dom},$tryserver) eq 'ok') { + &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver); + } + } + } + } $dumpcount++; } sub courselog { my $what=shift; $what=time.':'.$what; - unless ($ENV{'request.course.id'}) { return ''; } - $coursedombuf{$ENV{'request.course.id'}}= - $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}; - $coursenumbuf{$ENV{'request.course.id'}}= - $ENV{'course.'.$ENV{'request.course.id'}.'.num'}; - $coursehombuf{$ENV{'request.course.id'}}= - $ENV{'course.'.$ENV{'request.course.id'}.'.home'}; - $coursedescrbuf{$ENV{'request.course.id'}}= - $ENV{'course.'.$ENV{'request.course.id'}.'.description'}; - $courseinstcodebuf{$ENV{'request.course.id'}}= - $ENV{'course.'.$ENV{'request.course.id'}.'.internal.coursecode'}; - if (defined $courselogs{$ENV{'request.course.id'}}) { - $courselogs{$ENV{'request.course.id'}}.='&'.$what; + unless ($env{'request.course.id'}) { return ''; } + $coursedombuf{$env{'request.course.id'}}= + $env{'course.'.$env{'request.course.id'}.'.domain'}; + $coursenumbuf{$env{'request.course.id'}}= + $env{'course.'.$env{'request.course.id'}.'.num'}; + $coursehombuf{$env{'request.course.id'}}= + $env{'course.'.$env{'request.course.id'}.'.home'}; + $coursedescrbuf{$env{'request.course.id'}}= + $env{'course.'.$env{'request.course.id'}.'.description'}; + $courseinstcodebuf{$env{'request.course.id'}}= + $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'}; + $courseownerbuf{$env{'request.course.id'}}= + $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'}; + if (defined $courselogs{$env{'request.course.id'}}) { + $courselogs{$env{'request.course.id'}}.='&'.$what; } else { - $courselogs{$ENV{'request.course.id'}}.=$what; + $courselogs{$env{'request.course.id'}}.=$what; } - if (length($courselogs{$ENV{'request.course.id'}})>4048) { + if (length($courselogs{$env{'request.course.id'}})>4048) { &flushcourselogs(); } } sub courseacclog { my $fnsymb=shift; - unless ($ENV{'request.course.id'}) { return ''; } - my $what=$fnsymb.':'.$ENV{'user.name'}.':'.$ENV{'user.domain'}; - if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|page)$/) { + unless ($env{'request.course.id'}) { return ''; } + my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'}; + if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) { $what.=':POST'; - foreach (keys %ENV) { + # FIXME: Probably ought to escape things.... + foreach (keys %env) { if ($_=~/^form\.(.*)/) { - $what.=':'.$1.'='.$ENV{$_}; + $what.=':'.$1.'='.$env{$_}; + } + } + } elsif ($fnsymb =~ m:^/adm/searchcat:) { + # FIXME: We should not be depending on a form parameter that someone + # editing lonsearchcat.pm might change in the future. + if ($env{'form.phase'} eq 'course_search') { + $what.= ':POST'; + # FIXME: Probably ought to escape things.... + foreach my $element ('courseexp','crsfulltext','crsrelated', + 'crsdiscuss') { + $what.=':'.$element.'='.$env{'form.'.$element}; } } } @@ -1541,8 +1693,8 @@ sub courseacclog { sub countacc { my $url=&declutter(shift); return if (! defined($url) || $url eq ''); - unless ($ENV{'request.course.id'}) { return ''; } - $accesshash{$ENV{'request.course.id'}.'___'.$url.'___course'}=1; + unless ($env{'request.course.id'}) { return ''; } + $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1; my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count'; $accesshash{$key}++; } @@ -1557,19 +1709,29 @@ sub linklog { sub userrolelog { my ($trole,$username,$domain,$area,$tstart,$tend)=@_; - if (($trole=~/^ca/) || ($trole=~/^in/) || - ($trole=~/^cc/) || ($trole=~/^ep/) || - ($trole=~/^cr/) || ($trole=~/^ta/)) { + if (($trole=~/^ca/) || ($trole=~/^aa/) || + ($trole=~/^in/) || ($trole=~/^cc/) || + ($trole=~/^ep/) || ($trole=~/^cr/) || + ($trole=~/^ta/)) { my (undef,$rudom,$runame,$rsec)=split(/\//,$area); $userrolehash {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec} =$tend.':'.$tstart; - } + } + if (($trole=~/^dc/) || ($trole=~/^ad/) || + ($trole=~/^li/) || ($trole=~/^li/) || + ($trole=~/^au/) || ($trole=~/^dg/) || + ($trole=~/^sc/)) { + my (undef,$rudom,$runame,$rsec)=split(/\//,$area); + $domainrolehash + {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec} + = $tend.':'.$tstart; + } } sub get_course_adv_roles { my $cid=shift; - $cid=$ENV{'request.course.id'} unless (defined($cid)); + $cid=$env{'request.course.id'} unless (defined($cid)); my %coursehash=&coursedescription($cid); my %nothide=(); foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) { @@ -1585,9 +1747,14 @@ sub get_course_adv_roles { if (($tend) && ($tend<$now)) { next; } if (($tstart) && ($now<$tstart)) { next; } my ($role,$username,$domain,$section)=split(/\:/,$_); + if ($username eq '' || $domain eq '') { next; } if ((&privileged($username,$domain)) && (!$nothide{$username.':'.$domain})) { next; } + if ($role eq 'cr') { next; } my $key=&plaintext($role); + if ($role =~ /^cr/) { + $key=(split('/',$role))[3]; + } if ($section) { $key.=' (Sec/Grp '.$section.')'; } if ($returnhash{$key}) { $returnhash{$key}.=','.$username.':'.$domain; @@ -1600,8 +1767,8 @@ sub get_course_adv_roles { sub get_my_roles { my ($uname,$udom)=@_; - unless (defined($uname)) { $uname=$ENV{'user.name'}; } - unless (defined($udom)) { $udom=$ENV{'user.domain'}; } + unless (defined($uname)) { $uname=$env{'user.name'}; } + unless (defined($udom)) { $udom=$env{'user.domain'}; } my %dumphash= &dump('nohist_userroles',$udom,$uname); my %returnhash=(); @@ -1656,7 +1823,7 @@ sub courseidput { } sub courseiddump { - my ($domfilter,$descfilter,$sincefilter,$hostidflag,$hostidref)=@_; + my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref)=@_; my %returnhash=(); unless ($domfilter) { $domfilter=''; } foreach my $tryserver (keys %libserv) { @@ -1664,7 +1831,8 @@ sub courseiddump { if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) { foreach ( split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'. - $sincefilter.':'.&escape($descfilter), + $sincefilter.':'.&escape($descfilter).':'. + &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter), $tryserver))) { my ($key,$value)=split(/\=/,$_); if (($key) && ($value)) { @@ -1677,7 +1845,65 @@ sub courseiddump { return %returnhash; } -# +# ---------------------------------------------------------- DC e-mail + +sub dcmailput { + my ($domain,$msgid,$contents,$server)=@_; + my $status = &Apache::lonnet::critical( + 'dcmailput:'.$domain.':'.&Apache::lonnet::escape($msgid).'='. + &Apache::lonnet::escape($$contents{$server}),$server); + return $status; +} + +sub dcmaildump { + my ($dom,$startdate,$enddate,$senders) = @_; + my %returnhash=(); + foreach my $tryserver (keys(%libserv)) { + if ($hostdom{$tryserver} eq $dom) { + %{$returnhash{$tryserver}}=(); + my $cmd='dcmaildump:'.$dom.':'. + &escape($startdate).':'.&escape($enddate).':'; + my @esc_senders=map { &escape($_)} @$senders; + $cmd.=&escape(join('&',@esc_senders)); + foreach (split(/\&/,&reply($cmd,$tryserver))) { + my ($key,$value) = split(/\=/,$_); + if (($key) && ($value)) { + $returnhash{$tryserver}{&unescape($key)} = &unescape($value); + } + } + } + } + return %returnhash; +} +# ---------------------------------------------------------- Domain roles + +sub get_domain_roles { + my ($dom,$roles,$startdate,$enddate)=@_; + if (undef($startdate) || $startdate eq '') { + $startdate = '.'; + } + if (undef($enddate) || $enddate eq '') { + $enddate = '.'; + } + my $rolelist = join(':',@{$roles}); + my %personnel = (); + foreach my $tryserver (keys(%libserv)) { + if ($hostdom{$tryserver} eq $dom) { + %{$personnel{$tryserver}}=(); + foreach ( + split(/\&/,&reply('domrolesdump:'.$dom.':'. + &escape($startdate).':'.&escape($enddate).':'. + &escape($rolelist), $tryserver))) { + my($key,$value) = split(/\=/,$_); + if (($key) && ($value)) { + $personnel{$tryserver}{&unescape($key)} = &unescape($value); + } + } + } + } + return %personnel; +} + # ----------------------------------------------------------- Check out an item sub get_first_access { @@ -1685,19 +1911,27 @@ sub get_first_access { my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser(); if ($argsymb) { $symb=$argsymb; } my ($map,$id,$res)=&decode_symb($symb); - if ($type eq 'map') { $res=$map; } - my %times=&get('firstaccesstimes',[$res],$udom,$uname); - return $times{$res}; + if ($type eq 'map') { + $res=&symbread($map); + } else { + $res=$symb; + } + my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname); + return $times{"$courseid\0$res"}; } sub set_first_access { my ($type)=@_; my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser(); my ($map,$id,$res)=&decode_symb($symb); - if ($type eq 'map') { $res=$map; } - my $firstaccess=&get_first_access($type); + if ($type eq 'map') { + $res=&symbread($map); + } else { + $res=$symb; + } + my $firstaccess=&get_first_access($type,$symb); if (!$firstaccess) { - return &put('firstaccesstimes',{$res=>time},$udom,$uname); + return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname); } return 'already_set'; } @@ -1755,7 +1989,7 @@ sub checkin { my $now=time; my ($ta,$tb,$lonhost)=split(/\*/,$token); $lonhost=~tr/A-Z/a-z/; - my $dtoken=$ta.'_'.$hostip{$lonhost}.'_'.$tb; + my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb; $dtoken=~s/\W/\_/g; my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)= split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost))); @@ -1767,7 +2001,7 @@ sub checkin { unless (&allowed('mgr',$tcrsid)) { &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '. - $ENV{'user.name'}.' - '.$ENV{'user.domain'}); + $env{'user.name'}.' - '.$env{'user.domain'}); return ''; } @@ -1791,15 +2025,15 @@ sub checkin { sub expirespread { my ($uname,$udom,$stype,$usymb)=@_; - my $cid=$ENV{'request.course.id'}; + my $cid=$env{'request.course.id'}; if ($cid) { my $now=time; my $key=$uname.':'.$udom.':'.$stype.':'.$usymb; - return &reply('put:'.$ENV{'course.'.$cid.'.domain'}.':'. - $ENV{'course.'.$cid.'.num'}. + return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'. + $env{'course.'.$cid.'.num'}. ':nohist_expirationdates:'. &escape($key).'='.$now, - $ENV{'course.'.$cid.'.home'}) + $env{'course.'.$cid.'.home'}) } return 'ok'; } @@ -1808,18 +2042,19 @@ sub expirespread { sub devalidate { my ($symb,$uname,$udom)=@_; - my $cid=$ENV{'request.course.id'}; + my $cid=$env{'request.course.id'}; if ($cid) { # delete the stored spreadsheets for # - the student level sheet of this user in course's homespace # - the assessment level sheet for this resource # for this user in user's homespace + # - current conditional state info my $key=$uname.':'.$udom.':'; my $status= &del('nohist_calculatedsheets', [$key.'studentcalc:'], - $ENV{'course.'.$cid.'.domain'}, - $ENV{'course.'.$cid.'.num'}) + $env{'course.'.$cid.'.domain'}, + $env{'course.'.$cid.'.num'}) .' '. &del('nohist_calculatedsheets_'.$cid, [$key.'assesscalc:'.$symb],$udom,$uname); @@ -1828,6 +2063,7 @@ sub devalidate { $uname.' at '.$udom.' for '. $symb.': '.$status); } + &delenv('user.state.'.$cid); } } @@ -2028,17 +2264,19 @@ sub tmpreset { my ($symb,$namespace,$domain,$stuname) = @_; if (!$symb) { $symb=&symbread(); - if (!$symb) { $symb= $ENV{'request.url'}; } + if (!$symb) { $symb= $env{'request.url'}; } } $symb=escape($symb); - if (!$namespace) { $namespace=$ENV{'request.state'}; } + if (!$namespace) { $namespace=$env{'request.state'}; } $namespace=~s/\//\_/g; $namespace=~s/\W//g; - #FIXME needs to do something for /pub resources - if (!$domain) { $domain=$ENV{'user.domain'}; } - if (!$stuname) { $stuname=$ENV{'user.name'}; } + if (!$domain) { $domain=$env{'user.domain'}; } + if (!$stuname) { $stuname=$env{'user.name'}; } + if ($domain eq 'public' && $stuname eq 'public') { + $stuname=$ENV{'REMOTE_ADDR'}; + } my $path=$perlvar{'lonDaemons'}.'/tmp'; my %hash; if (tie(%hash,'GDBM_File', @@ -2057,23 +2295,25 @@ sub tmpstore { if (!$symb) { $symb=&symbread(); - if (!$symb) { $symb= $ENV{'request.url'}; } + if (!$symb) { $symb= $env{'request.url'}; } } $symb=escape($symb); if (!$namespace) { # I don't think we would ever want to store this for a course. # it seems this will only be used if we don't have a course. - #$namespace=$ENV{'request.course.id'}; + #$namespace=$env{'request.course.id'}; #if (!$namespace) { - $namespace=$ENV{'request.state'}; + $namespace=$env{'request.state'}; #} } $namespace=~s/\//\_/g; $namespace=~s/\W//g; -#FIXME needs to do something for /pub resources - if (!$domain) { $domain=$ENV{'user.domain'}; } - if (!$stuname) { $stuname=$ENV{'user.name'}; } + if (!$domain) { $domain=$env{'user.domain'}; } + if (!$stuname) { $stuname=$env{'user.name'}; } + if ($domain eq 'public' && $stuname eq 'public') { + $stuname=$ENV{'REMOTE_ADDR'}; + } my $now=time; my %hash; my $path=$perlvar{'lonDaemons'}.'/tmp'; @@ -2085,7 +2325,7 @@ sub tmpstore { my $allkeys=''; foreach my $key (keys(%$storehash)) { $allkeys.=$key.':'; - $hash{"$version:$symb:$key"}=$$storehash{$key}; + $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key}); } $hash{"$version:$symb:timestamp"}=$now; $allkeys.='timestamp'; @@ -2107,15 +2347,17 @@ sub tmprestore { if (!$symb) { $symb=&symbread(); - if (!$symb) { $symb= $ENV{'request.url'}; } + if (!$symb) { $symb= $env{'request.url'}; } } $symb=escape($symb); - if (!$namespace) { $namespace=$ENV{'request.state'}; } - #FIXME needs to do something for /pub resources - if (!$domain) { $domain=$ENV{'user.domain'}; } - if (!$stuname) { $stuname=$ENV{'user.name'}; } + if (!$namespace) { $namespace=$env{'request.state'}; } + if (!$domain) { $domain=$env{'user.domain'}; } + if (!$stuname) { $stuname=$env{'user.name'}; } + if ($domain eq 'public' && $stuname eq 'public') { + $stuname=$ENV{'REMOTE_ADDR'}; + } my %returnhash; $namespace=~s/\//\_/g; $namespace=~s/\W//g; @@ -2133,8 +2375,8 @@ sub tmprestore { my $key; $returnhash{"$scope:keys"}=$vkeys; foreach $key (@keys) { - $returnhash{"$scope:$key"}=$hash{"$scope:$symb:$key"}; - $returnhash{"$key"}=$hash{"$scope:$symb:$key"}; + $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"}); + $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"}); } } if (!(untie(%hash))) { @@ -2157,25 +2399,25 @@ sub store { $symb=&symbclean($symb); if (!$symb) { unless ($symb=&symbread()) { return ''; } } - if (!$domain) { $domain=$ENV{'user.domain'}; } - if (!$stuname) { $stuname=$ENV{'user.name'}; } + if (!$domain) { $domain=$env{'user.domain'}; } + if (!$stuname) { $stuname=$env{'user.name'}; } &devalidate($symb,$stuname,$domain); $symb=escape($symb); if (!$namespace) { - unless ($namespace=$ENV{'request.course.id'}) { + unless ($namespace=$env{'request.course.id'}) { return ''; } } - if (!$home) { $home=$ENV{'user.home'}; } + if (!$home) { $home=$env{'user.home'}; } $$storehash{'ip'}=$ENV{'REMOTE_ADDR'}; $$storehash{'host'}=$perlvar{'lonHostID'}; my $namevalue=''; foreach (keys %$storehash) { - $namevalue.=escape($_).'='.escape($$storehash{$_}).'&'; + $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&'; } $namevalue=~s/\&$//; &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue); @@ -2193,25 +2435,25 @@ sub cstore { $symb=&symbclean($symb); if (!$symb) { unless ($symb=&symbread()) { return ''; } } - if (!$domain) { $domain=$ENV{'user.domain'}; } - if (!$stuname) { $stuname=$ENV{'user.name'}; } + if (!$domain) { $domain=$env{'user.domain'}; } + if (!$stuname) { $stuname=$env{'user.name'}; } &devalidate($symb,$stuname,$domain); $symb=escape($symb); if (!$namespace) { - unless ($namespace=$ENV{'request.course.id'}) { + unless ($namespace=$env{'request.course.id'}) { return ''; } } - if (!$home) { $home=$ENV{'user.home'}; } + if (!$home) { $home=$env{'user.home'}; } $$storehash{'ip'}=$ENV{'REMOTE_ADDR'}; $$storehash{'host'}=$perlvar{'lonHostID'}; my $namevalue=''; foreach (keys %$storehash) { - $namevalue.=escape($_).'='.escape($$storehash{$_}).'&'; + $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&'; } $namevalue=~s/\&$//; &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue); @@ -2233,19 +2475,19 @@ sub restore { $symb=&escape(&symbclean($symb)); } if (!$namespace) { - unless ($namespace=$ENV{'request.course.id'}) { + unless ($namespace=$env{'request.course.id'}) { return ''; } } - if (!$domain) { $domain=$ENV{'user.domain'}; } - if (!$stuname) { $stuname=$ENV{'user.name'}; } - if (!$home) { $home=$ENV{'user.home'}; } + if (!$domain) { $domain=$env{'user.domain'}; } + if (!$stuname) { $stuname=$env{'user.name'}; } + if (!$home) { $home=$env{'user.home'}; } my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home"); my %returnhash=(); foreach (split(/\&/,$answer)) { my ($name,$value)=split(/\=/,$_); - $returnhash{&unescape($name)}=&unescape($value); + $returnhash{&unescape($name)}=&thaw_unescape($value); } my $version; for ($version=1;$version<=$returnhash{'version'};$version++) { @@ -2281,7 +2523,7 @@ sub coursedescription { } $returnhash{'url'}=&clutter($returnhash{'url'}); $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'. - $ENV{'user.name'}.'_'.$cdomain.'_'.$cnum; + $env{'user.name'}.'_'.$cdomain.'_'.$cnum; $envhash{'course.'.$normalid.'.home'}=$chome; $envhash{'course.'.$normalid.'.domain'}=$cdomain; $envhash{'course.'.$normalid.'.num'}=$cnum; @@ -2301,7 +2543,7 @@ sub privileged { my $now=time; if ($rolesdump ne '') { foreach (split(/&/,$rolesdump)) { - if ($_!~/^rolesdef\&/) { + if ($_!~/^rolesdef_/) { my ($area,$role)=split(/=/,$_); $area=~s/\_\w\w$//; my ($trole,$tend,$tstart)=split(/_/,$role); @@ -2328,112 +2570,125 @@ sub rolesinit { my $rolesdump=reply("dump:$domain:$username:roles",$authhost); if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; } my %allroles=(); - my %thesepriv=(); my $now=time; my $userroles="user.login.time=$now\n"; - my $thesestr; if ($rolesdump ne '') { foreach (split(/&/,$rolesdump)) { - if ($_!~/^rolesdef\&/) { + if ($_!~/^rolesdef_/) { my ($area,$role)=split(/=/,$_); - $area=~s/\_\w\w$//; - my ($trole,$tend,$tstart)=split(/_/,$role); - $userroles.='user.role.'.$trole.'.'.$area.'='. - $tstart.'.'.$tend."\n"; -# log the associated role with the area - &userrolelog($trole,$username,$domain,$area,$tstart,$tend); - if ($tend!=0) { - if ($tend<$now) { - $trole=''; - } - } - if ($tstart!=0) { - if ($tstart>$now) { - $trole=''; - } - } + $area=~s/\_\w\w$//; + my ($trole,$tend,$tstart); + if ($role=~/^cr/) { + if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) { + ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|); + ($tend,$tstart)=split('_',$trest); + } else { + $trole=$role; + } + } else { + ($trole,$tend,$tstart)=split(/_/,$role); + } + $userroles.=&set_arearole($trole,$area,$tstart,$tend,$domain,$username); + if (($tend!=0) && ($tend<$now)) { $trole=''; } + if (($tstart!=0) && ($tstart>$now)) { $trole=''; } if (($area ne '') && ($trole ne '')) { my $spec=$trole.'.'.$area; my ($tdummy,$tdomain,$trest)=split(/\//,$area); if ($trole =~ /^cr\//) { - my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole); - my $homsvr=homeserver($rauthor,$rdomain); - if ($hostname{$homsvr} ne '') { - my ($rdummy,$roledef)= - &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor); - - if (($rdummy ne 'con_lost') && ($roledef ne '')) { - my ($syspriv,$dompriv,$coursepriv)= - split(/\_/,$roledef); - if (defined($syspriv)) { - $allroles{'cm./'}.=':'.$syspriv; - $allroles{$spec.'./'}.=':'.$syspriv; - } - if ($tdomain ne '') { - if (defined($dompriv)) { - $allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv; - $allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv; - } - if ($trest ne '') { - if (defined($coursepriv)) { - $allroles{'cm.'.$area}.=':'.$coursepriv; - $allroles{$spec.'.'.$area}.=':'.$coursepriv; - } - } - } - } - } + &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area); } else { - if (defined($pr{$trole.':s'})) { - $allroles{'cm./'}.=':'.$pr{$trole.':s'}; - $allroles{$spec.'./'}.=':'.$pr{$trole.':s'}; - } - if ($tdomain ne '') { - if (defined($pr{$trole.':d'})) { - $allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'}; - $allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'}; - } - if ($trest ne '') { - if (defined($pr{$trole.':c'})) { - $allroles{'cm.'.$area}.=':'.$pr{$trole.':c'}; - $allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'}; - } - } - } + &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area); } } - } - } - my $adv=0; - my $author=0; - foreach (keys %allroles) { - %thesepriv=(); - if (($_!~/^st/) && ($_!~/^ta/) && ($_!~/^cm/)) { $adv=1; } - if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; } - foreach (split(/:/,$allroles{$_})) { - if ($_ ne '') { - my ($privilege,$restrictions)=split(/&/,$_); - if ($restrictions eq '') { - $thesepriv{$privilege}='F'; - } else { - if ($thesepriv{$privilege} ne 'F') { - $thesepriv{$privilege}.=$restrictions; - } - } - } - } - $thesestr=''; - foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; } - $userroles.='user.priv.'.$_.'='.$thesestr."\n"; + } } + my ($author,$adv) = &set_userprivs(\$userroles,\%allroles); $userroles.='user.adv='.$adv."\n". 'user.author='.$author."\n"; - $ENV{'user.adv'}=$adv; + $env{'user.adv'}=$adv; } return $userroles; } +sub set_arearole { + my ($trole,$area,$tstart,$tend,$domain,$username) = @_; +# log the associated role with the area + &userrolelog($trole,$username,$domain,$area,$tstart,$tend); + return 'user.role.'.$trole.'.'.$area.'='.$tstart.'.'.$tend."\n"; +} + +sub custom_roleprivs { + my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_; + my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole); + my $homsvr=homeserver($rauthor,$rdomain); + if ($hostname{$homsvr} ne '') { + my ($rdummy,$roledef)= + &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor); + if (($rdummy ne 'con_lost') && ($roledef ne '')) { + my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef); + if (defined($syspriv)) { + $$allroles{'cm./'}.=':'.$syspriv; + $$allroles{$spec.'./'}.=':'.$syspriv; + } + if ($tdomain ne '') { + if (defined($dompriv)) { + $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv; + $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv; + } + if (($trest ne '') && (defined($coursepriv))) { + $$allroles{'cm.'.$area}.=':'.$coursepriv; + $$allroles{$spec.'.'.$area}.=':'.$coursepriv; + } + } + } + } +} + + +sub standard_roleprivs { + my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_; + if (defined($pr{$trole.':s'})) { + $$allroles{'cm./'}.=':'.$pr{$trole.':s'}; + $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'}; + } + if ($tdomain ne '') { + if (defined($pr{$trole.':d'})) { + $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'}; + $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'}; + } + if (($trest ne '') && (defined($pr{$trole.':c'}))) { + $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'}; + $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'}; + } + } +} + +sub set_userprivs { + my ($userroles,$allroles) = @_; + my $author=0; + my $adv=0; + foreach (keys %{$allroles}) { + my %thesepriv=(); + if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; } + foreach (split(/:/,$$allroles{$_})) { + if ($_ ne '') { + my ($privilege,$restrictions)=split(/&/,$_); + if ($restrictions eq '') { + $thesepriv{$privilege}='F'; + } elsif ($thesepriv{$privilege} ne 'F') { + $thesepriv{$privilege}.=$restrictions; + } + if ($thesepriv{'adv'} eq 'F') { $adv=1; } + } + } + my $thesestr=''; + foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; } + $$userroles.='user.priv.'.$_.'='.$thesestr."\n"; + } + return ($author,$adv); +} + # --------------------------------------------------------------- get interface sub get { @@ -2443,8 +2698,8 @@ sub get { $items.=escape($_).'&'; } $items=~s/\&$//; - if (!$udomain) { $udomain=$ENV{'user.domain'}; } - if (!$uname) { $uname=$ENV{'user.name'}; } + if (!$udomain) { $udomain=$env{'user.domain'}; } + if (!$uname) { $uname=$env{'user.name'}; } my $uhome=&homeserver($uname,$udomain); my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome); @@ -2455,7 +2710,7 @@ sub get { my %returnhash=(); my $i=0; foreach (@$storearr) { - $returnhash{$_}=unescape($pairs[$i]); + $returnhash{$_}=&thaw_unescape($pairs[$i]); $i++; } return %returnhash; @@ -2470,8 +2725,8 @@ sub del { $items.=escape($_).'&'; } $items=~s/\&$//; - if (!$udomain) { $udomain=$ENV{'user.domain'}; } - if (!$uname) { $uname=$ENV{'user.name'}; } + if (!$udomain) { $udomain=$env{'user.domain'}; } + if (!$uname) { $uname=$env{'user.name'}; } my $uhome=&homeserver($uname,$udomain); return &reply("del:$udomain:$uname:$namespace:$items",$uhome); @@ -2481,8 +2736,8 @@ sub del { sub dump { my ($namespace,$udomain,$uname,$regexp)=@_; - if (!$udomain) { $udomain=$ENV{'user.domain'}; } - if (!$uname) { $uname=$ENV{'user.name'}; } + if (!$udomain) { $udomain=$env{'user.domain'}; } + if (!$uname) { $uname=$env{'user.name'}; } my $uhome=&homeserver($uname,$udomain); if ($regexp) { $regexp=&escape($regexp); @@ -2494,7 +2749,7 @@ sub dump { my %returnhash=(); foreach (@pairs) { my ($key,$value)=split(/=/,$_); - $returnhash{unescape($key)}=unescape($value); + $returnhash{unescape($key)}=&thaw_unescape($value); } return %returnhash; } @@ -2503,8 +2758,8 @@ sub dump { sub getkeys { my ($namespace,$udomain,$uname)=@_; - if (!$udomain) { $udomain=$ENV{'user.domain'}; } - if (!$uname) { $uname=$ENV{'user.name'}; } + if (!$udomain) { $udomain=$env{'user.domain'}; } + if (!$uname) { $uname=$env{'user.name'}; } my $uhome=&homeserver($uname,$udomain); my $rep=reply("keys:$udomain:$uname:$namespace",$uhome); my @keyarray=(); @@ -2517,9 +2772,9 @@ sub getkeys { # --------------------------------------------------------------- currentdump sub currentdump { my ($courseid,$sdom,$sname)=@_; - $courseid = $ENV{'request.course.id'} if (! defined($courseid)); - $sdom = $ENV{'user.domain'} if (! defined($sdom)); - $sname = $ENV{'user.name'} if (! defined($sname)); + $courseid = $env{'request.course.id'} if (! defined($courseid)); + $sdom = $env{'user.domain'} if (! defined($sdom)); + $sname = $env{'user.name'} if (! defined($sname)); my $uhome = &homeserver($sname,$sdom); my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome); return if ($rep =~ /^(error:|no_such_host)/); @@ -2540,7 +2795,7 @@ sub currentdump { my ($key,$value)=split(/=/,$_); my ($symb,$param) = split(/:/,$key); $returnhash{&unescape($symb)}->{&unescape($param)} = - &unescape($value); + &thaw_unescape($value); } } return %returnhash; @@ -2573,12 +2828,18 @@ sub convert_dump_to_currentdump{ return \%returnhash; } +# ------------------------------------------------------ critical inc interface + +sub cinc { + return &inc(@_,'critical'); +} + # --------------------------------------------------------------- inc interface sub inc { - my ($namespace,$store,$udomain,$uname) = @_; - if (!$udomain) { $udomain=$ENV{'user.domain'}; } - if (!$uname) { $uname=$ENV{'user.name'}; } + my ($namespace,$store,$udomain,$uname,$critical) = @_; + if (!$udomain) { $udomain=$env{'user.domain'}; } + if (!$uname) { $uname=$env{'user.name'}; } my $uhome=&homeserver($uname,$udomain); my $items=''; if (! ref($store)) { @@ -2594,30 +2855,49 @@ sub inc { } } $items=~s/\&$//; - return &reply("inc:$udomain:$uname:$namespace:$items",$uhome); + if ($critical) { + return &critical("inc:$udomain:$uname:$namespace:$items",$uhome); + } else { + return &reply("inc:$udomain:$uname:$namespace:$items",$uhome); + } } # --------------------------------------------------------------- put interface sub put { my ($namespace,$storehash,$udomain,$uname)=@_; - if (!$udomain) { $udomain=$ENV{'user.domain'}; } - if (!$uname) { $uname=$ENV{'user.name'}; } + if (!$udomain) { $udomain=$env{'user.domain'}; } + if (!$uname) { $uname=$env{'user.name'}; } my $uhome=&homeserver($uname,$udomain); my $items=''; foreach (keys %$storehash) { - $items.=&escape($_).'='.&escape($$storehash{$_}).'&'; + $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&'; } $items=~s/\&$//; return &reply("put:$udomain:$uname:$namespace:$items",$uhome); } -# ---------------------------------------------------------- putstore interface - +# ------------------------------------------------------------ newput interface + +sub newput { + my ($namespace,$storehash,$udomain,$uname)=@_; + if (!$udomain) { $udomain=$env{'user.domain'}; } + if (!$uname) { $uname=$env{'user.name'}; } + my $uhome=&homeserver($uname,$udomain); + my $items=''; + foreach my $key (keys(%$storehash)) { + $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&'; + } + $items=~s/\&$//; + return &reply("newput:$udomain:$uname:$namespace:$items",$uhome); +} + +# --------------------------------------------------------- putstore interface + sub putstore { my ($namespace,$storehash,$udomain,$uname)=@_; - if (!$udomain) { $udomain=$ENV{'user.domain'}; } - if (!$uname) { $uname=$ENV{'user.name'}; } + if (!$udomain) { $udomain=$env{'user.domain'}; } + if (!$uname) { $uname=$env{'user.name'}; } my $uhome=&homeserver($uname,$udomain); my $items=''; my %allitems = (); @@ -2626,7 +2906,7 @@ sub putstore { my $key = $1.':keys:'.$2; $allitems{$key} .= $3.':'; } - $items.=$_.'='.&escape($$storehash{$_}).'&'; + $items.=$_.'='.&freeze_escape($$storehash{$_}).'&'; } foreach (keys %allitems) { $allitems{$_} =~ s/\:$//; @@ -2640,12 +2920,12 @@ sub putstore { sub cput { my ($namespace,$storehash,$udomain,$uname)=@_; - if (!$udomain) { $udomain=$ENV{'user.domain'}; } - if (!$uname) { $uname=$ENV{'user.name'}; } + if (!$udomain) { $udomain=$env{'user.domain'}; } + if (!$uname) { $uname=$env{'user.name'}; } my $uhome=&homeserver($uname,$udomain); my $items=''; foreach (keys %$storehash) { - $items.=escape($_).'='.escape($$storehash{$_}).'&'; + $items.=escape($_).'='.&freeze_escape($$storehash{$_}).'&'; } $items=~s/\&$//; return &critical("put:$udomain:$uname:$namespace:$items",$uhome); @@ -2660,25 +2940,48 @@ sub eget { $items.=escape($_).'&'; } $items=~s/\&$//; - if (!$udomain) { $udomain=$ENV{'user.domain'}; } - if (!$uname) { $uname=$ENV{'user.name'}; } + if (!$udomain) { $udomain=$env{'user.domain'}; } + if (!$uname) { $uname=$env{'user.name'}; } my $uhome=&homeserver($uname,$udomain); my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome); my @pairs=split(/\&/,$rep); my %returnhash=(); my $i=0; foreach (@$storearr) { - $returnhash{$_}=unescape($pairs[$i]); + $returnhash{$_}=&thaw_unescape($pairs[$i]); $i++; } return %returnhash; } +# ------------------------------------------------------------ tmpput interface +sub tmpput { + my ($storehash,$server)=@_; + my $items=''; + foreach (keys(%$storehash)) { + $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&'; + } + $items=~s/\&$//; + return &reply("tmpput:$items",$server); +} + +# ------------------------------------------------------------ tmpget interface +sub tmpget { + my ($token)=@_; + my $rep=&reply("tmpget:$token",$perlvar{'lonHostID'}); + my %returnhash; + foreach my $item (split(/\&/,$rep)) { + my ($key,$value)=split(/=/,$item); + $returnhash{&unescape($key)}=&thaw_unescape($value); + } + return %returnhash; +} + # ---------------------------------------------- Custom access rule evaluation sub customaccess { my ($priv,$uri)=@_; - my ($urole,$urealm)=split(/\./,$ENV{'request.role'}); + my ($urole,$urealm)=split(/\./,$env{'request.role'}); $urealm=~s/^\W//; my ($udom,$ucrs,$usec)=split(/\//,$urealm); my $access=0; @@ -2711,39 +3014,48 @@ sub customaccess { # ------------------------------------------------- Check for a user privilege sub allowed { - my ($priv,$uri)=@_; + my ($priv,$uri,$symb)=@_; $uri=&deversion($uri); my $orguri=$uri; $uri=&declutter($uri); - - if (defined($ENV{'allowed.'.$priv})) { return $ENV{'allowed.'.$priv}; } + + + + if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; } # Free bre access to adm and meta resources if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|)) || ($uri=~/\.meta$/)) && ($priv eq 'bre')) { return 'F'; } +# Free bre access to user's own portfolio contents + my ($space,$domain,$name,$dir)=split('/',$uri); + if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && + ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir)) { + return 'F'; + } + # Free bre to public access if ($priv eq 'bre') { my $copyright=&metadata($uri,'copyright'); - if (($copyright eq 'public') && (!$ENV{'request.course.id'})) { + if (($copyright eq 'public') && (!$env{'request.course.id'})) { return 'F'; } if ($copyright eq 'priv') { $uri=~/([^\/]+)\/([^\/]+)\//; - unless (($ENV{'user.name'} eq $2) && ($ENV{'user.domain'} eq $1)) { + unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) { return ''; } } if ($copyright eq 'domain') { $uri=~/([^\/]+)\/([^\/]+)\//; - unless (($ENV{'user.domain'} eq $1) || - ($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $1)) { + unless (($env{'user.domain'} eq $1) || + ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) { return ''; } } - if ($ENV{'request.role'}=~ /li\.\//) { + if ($env{'request.role'}=~ /li\.\//) { # Library role, so allow browsing of resources in this domain. return 'F'; } @@ -2752,11 +3064,11 @@ sub allowed { } } # Domain coordinator is trying to create a course - if (($priv eq 'ccc') && ($ENV{'request.role'} =~ /^dc\./)) { + if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) { # uri is the requested domain in this case. # comparison to 'request.role.domain' shows if the user has selected # a role of dc for the domain in question. - return 'F' if ($uri eq $ENV{'request.role.domain'}); + return 'F' if ($uri eq $env{'request.role.domain'}); } my $thisallowed=''; @@ -2765,13 +3077,13 @@ sub allowed { # Course - if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) { + if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) { $thisallowed.=$1; } # Domain - if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.(split(/\//,$uri))[0].'/'} + if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'} =~/\Q$priv\E\&([^\:]*)/) { $thisallowed.=$1; } @@ -2781,15 +3093,16 @@ sub allowed { $courseuri=~s/\_(\d)/\/$1/; $courseuri=~s/^([^\/])/\/$1/; - if ($ENV{'user.priv.'.$ENV{'request.role'}.'.'.$courseuri} + if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri} =~/\Q$priv\E\&([^\:]*)/) { $thisallowed.=$1; } -# URI is an uploaded document for this course - +# URI is an uploaded document for this course, default permissions don't matter +# not allowing 'edit' access (editupload) to uploaded course docs if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) { - my $refuri=$ENV{'httpref.'.$orguri}; + $thisallowed=''; + my $refuri=$env{'httpref.'.$orguri}; if ($refuri) { if ($refuri =~ m|^/adm/|) { $thisallowed='F'; @@ -2805,7 +3118,16 @@ sub allowed { # If this is generating or modifying users, exit with special codes - if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:\Q$priv\E\:/) { + if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) { + if (($priv eq 'cca') || ($priv eq 'caa')) { + my ($audom,$auname)=split('/',$uri); +# no author name given, so this just checks on the general right to make a co-author in this domain + unless ($auname) { return $thisallowed; } +# an author name is given, so we are about to actually make a co-author for a certain account + if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) || + (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) && + ($audom ne $env{'request.role.domain'}))) { return ''; } + } return $thisallowed; } # @@ -2814,18 +3136,18 @@ sub allowed { # Course: See if uri or referer is an individual resource that is part of # the course - if ($ENV{'request.course.id'}) { + if ($env{'request.course.id'}) { - $courseprivid=$ENV{'request.course.id'}; - if ($ENV{'request.course.sec'}) { - $courseprivid.='/'.$ENV{'request.course.sec'}; + $courseprivid=$env{'request.course.id'}; + if ($env{'request.course.sec'}) { + $courseprivid.='/'.$env{'request.course.sec'}; } $courseprivid=~s/\_/\//; my $checkreferer=1; my ($match,$cond)=&is_on_map($uri); if ($match) { $statecond=$cond; - if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid} + if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid} =~/\Q$priv\E\&([^\:]*)/) { $thisallowed.=$1; $checkreferer=0; @@ -2833,16 +3155,16 @@ sub allowed { } if ($checkreferer) { - my $refuri=$ENV{'httpref.'.$orguri}; + my $refuri=$env{'httpref.'.$orguri}; unless ($refuri) { - foreach (keys %ENV) { + foreach (keys %env) { if ($_=~/^httpref\..*\*/) { my $pattern=$_; $pattern=~s/^httpref\.\/res\///; $pattern=~s/\*/\[\^\/\]\+/g; $pattern=~s/\//\\\//g; if ($orguri=~/$pattern/) { - $refuri=$ENV{$_}; + $refuri=$env{$_}; } } } @@ -2853,7 +3175,7 @@ sub allowed { my ($match,$cond)=&is_on_map($refuri); if ($match) { my $refstatecond=$cond; - if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid} + if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid} =~/\Q$priv\E\&([^\:]*)/) { $thisallowed.=$1; $uri=$refuri; @@ -2893,39 +3215,39 @@ sub allowed { my $envkey; if ($thisallowed=~/L/) { - foreach $envkey (keys %ENV) { + foreach $envkey (keys %env) { if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) { my $courseid=$2; my $roleid=$1.'.'.$2; $courseid=~s/^\///; my $expiretime=600; - if ($ENV{'request.role'} eq $roleid) { + if ($env{'request.role'} eq $roleid) { $expiretime=120; } my ($cdom,$cnum,$csec)=split(/\//,$courseid); my $prefix='course.'.$cdom.'_'.$cnum.'.'; - if ((time-$ENV{$prefix.'last_cache'})>$expiretime) { + if ((time-$env{$prefix.'last_cache'})>$expiretime) { &coursedescription($courseid); } - if (($ENV{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/) - || ($ENV{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) { - if ($ENV{$prefix.'res.'.$uri.'.lock.expire'}>time) { - &log($ENV{'user.domain'},$ENV{'user.name'}, - $ENV{'user.home'}, + if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/) + || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) { + if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) { + &log($env{'user.domain'},$env{'user.name'}, + $env{'user.home'}, 'Locked by res: '.$priv.' for '.$uri.' due to '. $cdom.'/'.$cnum.'/'.$csec.' expire '. - $ENV{$prefix.'priv.'.$priv.'.lock.expire'}); + $env{$prefix.'priv.'.$priv.'.lock.expire'}); return ''; } } - if (($ENV{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/) - || ($ENV{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) { - if ($ENV{'priv.'.$priv.'.lock.expire'}>time) { - &log($ENV{'user.domain'},$ENV{'user.name'}, - $ENV{'user.home'}, + if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/) + || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) { + if ($env{'priv.'.$priv.'.lock.expire'}>time) { + &log($env{'user.domain'},$env{'user.name'}, + $env{'user.home'}, 'Locked by priv: '.$priv.' for '.$uri.' due to '. $cdom.'/'.$cnum.'/'.$csec.' expire '. - $ENV{$prefix.'priv.'.$priv.'.lock.expire'}); + $env{$prefix.'priv.'.$priv.'.lock.expire'}); return ''; } } @@ -2937,7 +3259,7 @@ sub allowed { # Rest of the restrictions depend on selected course # - unless ($ENV{'request.course.id'}) { + unless ($env{'request.course.id'}) { return '1'; } @@ -2949,21 +3271,21 @@ sub allowed { # Course preferences if ($thisallowed=~/C/) { - my $rolecode=(split(/\./,$ENV{'request.role'}))[0]; - my $unamedom=$ENV{'user.name'}.':'.$ENV{'user.domain'}; - if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.roles.denied'} + my $rolecode=(split(/\./,$env{'request.role'}))[0]; + my $unamedom=$env{'user.name'}.':'.$env{'user.domain'}; + if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'} =~/\Q$rolecode\E/) { - &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'}, + &log($env{'user.domain'},$env{'user.name'},$env{'user.host'}, 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '. - $ENV{'request.course.id'}); + $env{'request.course.id'}); return ''; } - if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.users.denied'} + if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'} =~/\Q$unamedom\E/) { - &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'}, + &log($env{'user.domain'},$env{'user.name'},$env{'user.host'}, 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '. - $ENV{'request.course.id'}); + $env{'request.course.id'}); return ''; } } @@ -2971,9 +3293,9 @@ sub allowed { # Resource preferences if ($thisallowed=~/R/) { - my $rolecode=(split(/\./,$ENV{'request.role'}))[0]; + my $rolecode=(split(/\./,$env{'request.role'}))[0]; if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) { - &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'}, + &log($env{'user.domain'},$env{'user.name'},$env{'user.host'}, 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode); return ''; } @@ -2982,9 +3304,9 @@ sub allowed { # Restricted by state or randomout? if ($thisallowed=~/X/) { - if ($ENV{'acc.randomout'}) { - my $symb=&symbread($uri,1); - if (($symb) && ($ENV{'acc.randomout'}=~/\&\Q$symb\E\&/)) { + if ($env{'acc.randomout'}) { + if (!$symb) { $symb=&symbread($uri,1); } + if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { return ''; } } @@ -3001,15 +3323,14 @@ sub allowed { # --------------------------------------------------- Is a resource on the map? sub is_on_map { - my $uri=&declutter(shift); - $uri=~s/\.\d+\.(\w+)$/\.$1/; + my $uri=&deversion(&declutter(shift)); my @uriparts=split(/\//,$uri); my $filename=$uriparts[$#uriparts]; my $pathname=$uri; $pathname=~s|/\Q$filename\E$||; $pathname=~s/^adm\/wrapper\///; #Trying to find the conditional for the file - my $match=($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~ + my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~ /\&\Q$filename\E\:([\d\|]+)\&/); if ($match) { return (1,$1); @@ -3028,7 +3349,7 @@ sub get_symb_from_alias { # Must be an alias my $aliassymb=''; my %bighash; - if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db', + if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db', &GDBM_READER(),0640)) { my $rid=$bighash{'mapalias_'.$symb}; if ($rid) { @@ -3073,11 +3394,11 @@ sub definerole { } } } - my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:". - "$ENV{'user.domain'}:$ENV{'user.name'}:". + my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:". + "$env{'user.domain'}:$env{'user.name'}:". "rolesdef_$rolename=". escape($sysrole.'_'.$domrole.'_'.$courole); - return reply($command,$ENV{'user.home'}); + return reply($command,$env{'user.home'}); } else { return 'refused'; } @@ -3124,8 +3445,10 @@ sub log_query { sub fetch_enrollment_query { my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_; my $homeserver; + my $maxtries = 1; if ($context eq 'automated') { $homeserver = $perlvar{'lonHostID'}; + $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout } else { $homeserver = &homeserver($cnum,$dom); } @@ -3137,14 +3460,19 @@ sub fetch_enrollment_query { $cmd =~ s/%%$//; $cmd = &escape($cmd); my $query = 'fetchenrollment'; - my $queryid=&reply("querysend:".$query.':'.$dom.':'.$ENV{'user.name'}.':'.$cmd,$homeserver); + my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver); unless ($queryid=~/^\Q$host\E\_/) { &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); return 'error: '.$queryid; } my $reply = &get_query_reply($queryid); + my $tries = 1; + while (($reply=~/^timeout/) && ($tries < $maxtries)) { + $reply = &get_query_reply($queryid); + $tries ++; + } if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) { - &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$ENV{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum); + &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries); } else { my @responses = split/:/,$reply; if ($homeserver eq $perlvar{'lonHostID'}) { @@ -3209,14 +3537,14 @@ sub courselog_query { # end: timestamp # my (%filters)=@_; - unless ($ENV{'request.course.id'}) { return 'no_course'; } + unless ($env{'request.course.id'}) { return 'no_course'; } if ($filters{'url'}) { $filters{'url'}=&symbclean(&declutter($filters{'url'})); $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/; $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/; } - my $cname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'}; - my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'}; + my $cname=$env{'course.'.$env{'request.course.id'}.'.num'}; + my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'}; return &log_query($cname,$cdom,'courselog',%filters); } @@ -3278,11 +3606,18 @@ sub auto_instcode_format { my $courses = ''; my $homeserver; if ($caller eq 'global') { - $homeserver = $perlvar{'lonHostID'}; + foreach my $tryserver (keys %libserv) { + if ($hostdom{$tryserver} eq $codedom) { + $homeserver = $tryserver; + last; + } + } + if (($env{'user.name'}) && ($env{'user.domain'} eq $codedom)) { + $homeserver = &homeserver($env{'user.name'},$codedom); + } } else { $homeserver = &homeserver($caller,$codedom); } - my $host=$hostname{$homeserver}; foreach (keys %{$instcodes}) { $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&'; } @@ -3317,7 +3652,7 @@ sub assignrole { unless (&allowed('ccr',$cwosec)) { &logthis('Refused custom assignrole: '. $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '. - $ENV{'user.name'}.' at '.$ENV{'user.domain'}); + $env{'user.name'}.' at '.$env{'user.domain'}); return 'refused'; } $mrole='cr'; @@ -3327,12 +3662,12 @@ sub assignrole { unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { &logthis('Refused assignrole: '. $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '. - $ENV{'user.name'}.' at '.$ENV{'user.domain'}); + $env{'user.name'}.' at '.$env{'user.domain'}); return 'refused'; } $mrole=$role; } - my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:". + my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:". "$udom:$uname:$url".'_'."$mrole=$role"; if ($end) { $command.='_'.$end; } if ($start) { @@ -3346,9 +3681,9 @@ sub assignrole { if ($deleteflag) { if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) { # modify command to delete the role - $command="encrypt:rolesdel:$ENV{'user.domain'}:$ENV{'user.name'}:". + $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:". "$udom:$uname:$url".'_'."$mrole"; - &logthis("$ENV{'user.name'} at $ENV{'user.domain'} deletes $mrole in $url for $uname at $udom"); + &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); # set start and finish to negative values for userrolelog $start=-1; $end=-1; @@ -3358,7 +3693,7 @@ sub assignrole { my $answer=&reply($command,&homeserver($uname,$udom)); # log new user role if status is ok if ($answer eq 'ok') { - &userrolelog($mrole,$uname,$udom,$url,$start,$end); + &userrolelog($role,$uname,$udom,$url,$start,$end); } return $answer; } @@ -3371,16 +3706,16 @@ sub modifyuserauth { my $uhome=&homeserver($uname,$udom); unless (&allowed('mau',$udom)) { return 'refused'; } &logthis('Call to modify user authentication '.$udom.', '.$uname.', '. - $umode.' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}. - ' in domain '.$ENV{'request.role.domain'}); + $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}. + ' in domain '.$env{'request.role.domain'}); my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'. &escape($upass),$uhome); - &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'}, + &log($env{'user.domain'},$env{'user.name'},$env{'user.home'}, 'Authentication changed for '.$udom.', '.$uname.', '.$umode. '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply); &log($udom,,$uname,$uhome, - 'Authentication changed by '.$ENV{'user.domain'}.', '. - $ENV{'user.name'}.', '.$umode. + 'Authentication changed by '.$env{'user.domain'}.', '. + $env{'user.name'}.', '.$umode. '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply); unless ($reply eq 'ok') { &logthis('Authentication mode error: '.$reply); @@ -3403,8 +3738,8 @@ sub modifyuser { $last.', '.$gene.'(forceid: '.$forceid.')'. (defined($desiredhome) ? ' desiredhome = '.$desiredhome : ' desiredhome not specified'). - ' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}. - ' in domain '.$ENV{'request.role.domain'}); + ' by '.$env{'user.name'}.' at '.$env{'user.domain'}. + ' in domain '.$env{'request.role.domain'}); my $uhome=&homeserver($uname,$udom,'true'); # ----------------------------------------------------------------- Create User if (($uhome eq 'no_host') && @@ -3412,8 +3747,8 @@ sub modifyuser { my $unhome=''; if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { $unhome = $desiredhome; - } elsif($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $udom) { - $unhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'}; + } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) { + $unhome=$env{'course.'.$env{'request.course.id'}.'.home'}; } else { # load balancing routine for determining $unhome my $tryserver; my $loadm=10000000; @@ -3473,15 +3808,18 @@ sub modifyuser { if (defined($middle)) { $names{'middlename'} = $middle; } if ($last) { $names{'lastname'} = $last; } if (defined($gene)) { $names{'generation'} = $gene; } - if ($email) { $names{'notification'} = $email; - $names{'critnotification'} = $email; } - + if ($email) { + $email=~s/[^\w\@\.\-\,]//gs; + if ($email=~/\@/) { $names{'notification'} = $email; + $names{'critnotification'} = $email; + $names{'permanentemail'} = $email; } + } my $reply = &put('environment', \%names, $udom,$uname); if ($reply ne 'ok') { return 'error: '.$reply; } &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '. $umode.', '.$first.', '.$middle.', '. $last.', '.$gene.' by '. - $ENV{'user.name'}.' at '.$ENV{'user.domain'}); + $env{'user.name'}.' at '.$env{'user.domain'}); return 'ok'; } @@ -3491,7 +3829,7 @@ sub modifystudent { my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec, $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_; if (!$cid) { - unless ($cid=$ENV{'request.course.id'}) { + unless ($cid=$env{'request.course.id'}) { return 'not_in_class'; } } @@ -3512,15 +3850,15 @@ sub modify_student_enrollment { my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_; my ($cdom,$cnum,$chome); if (!$cid) { - unless ($cid=$ENV{'request.course.id'}) { + unless ($cid=$env{'request.course.id'}) { return 'not_in_class'; } - $cdom=$ENV{'course.'.$cid.'.domain'}; - $cnum=$ENV{'course.'.$cid.'.num'}; + $cdom=$env{'course.'.$cid.'.domain'}; + $cnum=$env{'course.'.$cid.'.num'}; } else { ($cdom,$cnum)=split(/_/,$cid); } - $chome=$ENV{'course.'.$cid.'.home'}; + $chome=$env{'course.'.$cid.'.home'}; if (!$chome) { $chome=&homeserver($cnum,$cdom); } @@ -3551,14 +3889,15 @@ sub modify_student_enrollment { $gene = $tmp{'generation'} if (!defined($gene) || $gene eq ''); $uid = $tmp{'id'} if (!defined($uid) || $uid eq ''); } - my $fullname = &Apache::loncoursedata::ProcessFullName($last,$gene, - $first,$middle); + my $fullname = &format_name($first,$middle,$last,$gene,'lastname'); my $reply=cput('classlist', {"$uname:$udom" => join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) }, $cdom,$cnum); unless (($reply eq 'ok') || ($reply eq 'delayed')) { return 'error: '.$reply; + } else { + &devalidate_getsection_cache($udom,$uname,$cid); } # Add student role to user my $uurl='/'.$cid; @@ -3569,6 +3908,25 @@ sub modify_student_enrollment { return &assignrole($udom,$uname,$uurl,'st',$end,$start); } +sub format_name { + my ($firstname,$middlename,$lastname,$generation,$first)=@_; + my $name; + if ($first ne 'lastname') { + $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation; + } else { + if ($lastname=~/\S/) { + $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename; + $name=~s/\s+,/,/; + } else { + $name.= $firstname.' '.$middlename.' '.$generation; + } + } + $name=~s/^\s+//; + $name=~s/\s+$//; + $name=~s/\s+/ /g; + return $name; +} + # ------------------------------------------------- Write to course preferences sub writecoursepref { @@ -3591,7 +3949,7 @@ sub writecoursepref { # ---------------------------------------------------------- Make/modify course sub createcourse { - my ($udom,$description,$url,$course_server,$nonstandard,$inst_code)=@_; + my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner)=@_; $url=&declutter($url); my $cid=''; unless (&allowed('ccc',$udom)) { @@ -3611,7 +3969,7 @@ sub createcourse { } } # ------------------------------------------------ Check supplied server name - $course_server = $ENV{'user.homeserver'} if (! defined($course_server)); + $course_server = $env{'user.homeserver'} if (! defined($course_server)); if (! exists($libserv{$course_server})) { return 'error:bad server name '.$course_server; } @@ -3626,7 +3984,7 @@ sub createcourse { # ----------------------------------------------------------------- Course made # log existence &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description). - '='.&escape($inst_code),$uhome); + ':'.&escape($inst_code).':'.&escape($course_owner),$uhome); &flushcourselogs(); # set toplevel url my $topurl=$url; @@ -3634,7 +3992,7 @@ sub createcourse { # ------------------------------------------ For standard courses, make top url my $mapurl=&clutter($url); if ($mapurl eq '/res/') { $mapurl=''; } - $ENV{'form.initmap'}=(<