File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1172.2.146.2.2: download - view: text, annotated - select for diffs
Wed Jan 5 01:50:06 2022 UTC (2 years, 5 months ago) by raeburn
Branches: version_2_11_4_msu
- For 2.11.4 (modified)
  Fix typo in rev. 1.1172.2.146.2.1 backport of 1.1302 (part)

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1172.2.146.2.2 2022/01/05 01:50:06 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: use CGI::Cookie;
   78: 
   79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
   80:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   81:             %managerstab $passwdmin);
   82: 
   83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   84:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   85:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   86:     %courseownerbuf, %coursetypebuf,$locknum);
   87: 
   88: use IO::Socket;
   89: use GDBM_File;
   90: use HTML::LCParser;
   91: use Fcntl qw(:flock);
   92: use Storable qw(thaw nfreeze);
   93: use Time::HiRes qw( sleep gettimeofday tv_interval );
   94: use Cache::Memcached;
   95: use Digest::MD5;
   96: use Math::Random;
   97: use File::MMagic;
   98: use Net::CIDR;
   99: use Sys::Hostname::FQDN();
  100: use LONCAPA qw(:DEFAULT :match);
  101: use LONCAPA::Configuration;
  102: use LONCAPA::lonmetadata;
  103: use LONCAPA::Lond;
  104: use LONCAPA::transliterate;
  105: 
  106: use File::Copy;
  107: 
  108: my $readit;
  109: my $max_connection_retries = 20;     # Or some such value.
  110: 
  111: require Exporter;
  112: 
  113: our @ISA = qw (Exporter);
  114: our @EXPORT = qw(%env);
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $ip = &get_requestor_ip();
  131:         my $logentry = {
  132:                          $id => {
  133:                                   'exe_uname' => $env{'user.name'},
  134:                                   'exe_udom'  => $env{'user.domain'},
  135:                                   'exe_time'  => $now,
  136:                                   'exe_ip'    => $ip,
  137:                                   'delflag'   => $delflag,
  138:                                   'logentry'  => $storehash,
  139:                                   'uname'     => $uname,
  140:                                   'udom'      => $udom,
  141:                                 }
  142:                        };
  143:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  144:     }
  145: }
  146: 
  147: sub logtouch {
  148:     my $execdir=$perlvar{'lonDaemons'};
  149:     unless (-e "$execdir/logs/lonnet.log") {	
  150: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  151: 	close $fh;
  152:     }
  153:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  154:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  155: }
  156: 
  157: sub logthis {
  158:     my $message=shift;
  159:     my $execdir=$perlvar{'lonDaemons'};
  160:     my $now=time;
  161:     my $local=localtime($now);
  162:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  163: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  164: 	print $fh $logstring;
  165: 	close($fh);
  166:     }
  167:     return 1;
  168: }
  169: 
  170: sub logperm {
  171:     my $message=shift;
  172:     my $execdir=$perlvar{'lonDaemons'};
  173:     my $now=time;
  174:     my $local=localtime($now);
  175:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  176: 	print $fh "$now:$message:$local\n";
  177: 	close($fh);
  178:     }
  179:     return 1;
  180: }
  181: 
  182: sub create_connection {
  183:     my ($hostname,$lonid) = @_;
  184:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  185: 				     Type    => SOCK_STREAM,
  186: 				     Timeout => 10);
  187:     return 0 if (!$client);
  188:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  189:     my $result = <$client>;
  190:     chomp($result);
  191:     return 1 if ($result eq 'done');
  192:     return 0;
  193: }
  194: 
  195: sub get_server_timezone {
  196:     my ($cnum,$cdom) = @_;
  197:     my $home=&homeserver($cnum,$cdom);
  198:     if ($home ne 'no_host') {
  199:         my $cachetime = 24*3600;
  200:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  201:         if (defined($cached)) {
  202:             return $timezone;
  203:         } else {
  204:             my $timezone = &reply('servertimezone',$home);
  205:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  206:         }
  207:     }
  208: }
  209: 
  210: sub get_server_distarch {
  211:     my ($lonhost,$ignore_cache) = @_;
  212:     if (defined($lonhost)) {
  213:         if (!defined(&hostname($lonhost))) {
  214:             return;
  215:         }
  216:         my $cachetime = 12*3600;
  217:         if (!$ignore_cache) {
  218:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  219:             if (defined($cached)) {
  220:                 return $distarch;
  221:             }
  222:         }
  223:         my $rep = &reply('serverdistarch',$lonhost);
  224:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  225:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  226:                 $rep eq '') {
  227:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  228:         }
  229:     }
  230:     return;
  231: }
  232: 
  233: sub get_server_loncaparev {
  234:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  235:     if (defined($lonhost)) {
  236:         if (!defined(&hostname($lonhost))) {
  237:             undef($lonhost);
  238:         }
  239:     }
  240:     if (!defined($lonhost)) {
  241:         if (defined(&domain($dom,'primary'))) {
  242:             $lonhost=&domain($dom,'primary');
  243:             if ($lonhost eq 'no_host') {
  244:                 undef($lonhost);
  245:             }
  246:         }
  247:     }
  248:     if (defined($lonhost)) {
  249:         my $cachetime = 12*3600;
  250:         if (!$ignore_cache) {
  251:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  252:             if (defined($cached)) {
  253:                 return $loncaparev;
  254:             }
  255:         }
  256:         my ($answer,$loncaparev);
  257:         my @ids=&current_machine_ids();
  258:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  259:             $answer = $perlvar{'lonVersion'};
  260:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  261:                 $loncaparev = $1;
  262:             }
  263:         } else {
  264:             $answer = &reply('serverloncaparev',$lonhost);
  265:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  266:                 if ($caller eq 'loncron') {
  267:                     my $ua=new LWP::UserAgent;
  268:                     $ua->timeout(4);
  269:                     my $hostname = &hostname($lonhost);
  270:                     my $protocol = $protocol{$lonhost};
  271:                     $protocol = 'http' if ($protocol ne 'https');
  272:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
  273:                     my $request=new HTTP::Request('GET',$url);
  274:                     my $response=$ua->request($request);
  275:                     unless ($response->is_error()) {
  276:                         my $content = $response->content;
  277:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  278:                             $loncaparev = $1;
  279:                         }
  280:                     }
  281:                 } else {
  282:                     $loncaparev = $loncaparevs{$lonhost};
  283:                 }
  284:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  285:                 $loncaparev = $1;
  286:             }
  287:         }
  288:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  289:     }
  290: }
  291: 
  292: sub get_server_homeID {
  293:     my ($hostname,$ignore_cache,$caller) = @_;
  294:     unless ($ignore_cache) {
  295:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  296:         if (defined($cached)) {
  297:             return $serverhomeID;
  298:         }
  299:     }
  300:     my $cachetime = 12*3600;
  301:     my $serverhomeID;
  302:     if ($caller eq 'loncron') { 
  303:         my @machine_ids = &machine_ids($hostname);
  304:         foreach my $id (@machine_ids) {
  305:             my $response = &reply('serverhomeID',$id);
  306:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  307:                 $serverhomeID = $response;
  308:                 last;
  309:             }
  310:         }
  311:         if ($serverhomeID eq '') {
  312:             $serverhomeID = $machine_ids[-1];
  313:         }
  314:     } else {
  315:         $serverhomeID = $serverhomeIDs{$hostname};
  316:     }
  317:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  318: }
  319: 
  320: sub get_remote_globals {
  321:     my ($lonhost,$whathash,$ignore_cache) = @_;
  322:     my ($result,%returnhash,%whatneeded);
  323:     if (ref($whathash) eq 'HASH') {
  324:         foreach my $what (sort(keys(%{$whathash}))) {
  325:             my $hashid = $lonhost.'-'.$what;
  326:             my ($response,$cached);
  327:             unless ($ignore_cache) {
  328:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  329:             }
  330:             if (defined($cached)) {
  331:                 $returnhash{$what} = $response;
  332:             } else {
  333:                 $whatneeded{$what} = 1;
  334:             }
  335:         }
  336:         if (keys(%whatneeded) == 0) {
  337:             $result = 'ok';
  338:         } else {
  339:             my $requested = &freeze_escape(\%whatneeded);
  340:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  341:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  342:                 ($rep eq 'unknown_cmd')) {
  343:                 $result = $rep;
  344:             } else {
  345:                 $result = 'ok';
  346:                 my @pairs=split(/\&/,$rep);
  347:                 foreach my $item (@pairs) {
  348:                     my ($key,$value)=split(/=/,$item,2);
  349:                     my $what = &unescape($key);
  350:                     my $hashid = $lonhost.'-'.$what;
  351:                     $returnhash{$what}=&thaw_unescape($value);
  352:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  353:                 }
  354:             }
  355:         }
  356:     }
  357:     return ($result,\%returnhash);
  358: }
  359: 
  360: sub remote_devalidate_cache {
  361:     my ($lonhost,$cachekeys) = @_;
  362:     my $items;
  363:     return unless (ref($cachekeys) eq 'ARRAY');
  364:     my $cachestr = join('&',@{$cachekeys});
  365:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  366: }
  367: 
  368: # -------------------------------------------------- Non-critical communication
  369: sub subreply {
  370:     my ($cmd,$server)=@_;
  371:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  372:     #
  373:     #  With loncnew process trimming, there's a timing hole between lonc server
  374:     #  process exit and the master server picking up the listen on the AF_UNIX
  375:     #  socket.  In that time interval, a lock file will exist:
  376: 
  377:     my $lockfile=$peerfile.".lock";
  378:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  379: 	sleep(0.1);
  380:     }
  381:     # At this point, either a loncnew parent is listening or an old lonc
  382:     # or loncnew child is listening so we can connect or everything's dead.
  383:     #
  384:     #   We'll give the connection a few tries before abandoning it.  If
  385:     #   connection is not possible, we'll con_lost back to the client.
  386:     #   
  387:     my $client;
  388:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  389: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  390: 				      Type    => SOCK_STREAM,
  391: 				      Timeout => 10);
  392: 	if ($client) {
  393: 	    last;		# Connected!
  394: 	} else {
  395: 	    &create_connection(&hostname($server),$server);
  396: 	}
  397:         sleep(0.1);		# Try again later if failed connection.
  398:     }
  399:     my $answer;
  400:     if ($client) {
  401: 	print $client "sethost:$server:$cmd\n";
  402: 	$answer=<$client>;
  403: 	if (!$answer) { $answer="con_lost"; }
  404: 	chomp($answer);
  405:     } else {
  406: 	$answer = 'con_lost';	# Failed connection.
  407:     }
  408:     return $answer;
  409: }
  410: 
  411: sub reply {
  412:     my ($cmd,$server)=@_;
  413:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  414:     my $answer=subreply($cmd,$server);
  415:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  416:         my $logged = $cmd;
  417:         if ($cmd =~ /^encrypt:([^:]+):/) {
  418:             my $subcmd = $1;
  419:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
  420:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  421:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
  422:                 (undef,undef,my @rest) = split(/:/,$cmd);
  423:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
  424:                     splice(@rest,2,1,'Hidden');
  425:                 } elsif ($subcmd eq 'passwd') {
  426:                     splice(@rest,2,2,('Hidden','Hidden'));
  427:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  428:                          ($subcmd eq 'autoexportgrades')) {
  429:                     splice(@rest,3,1,'Hidden');
  430:                 }
  431:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
  432:             }
  433:         }
  434:         &logthis("<font color=\"blue\">WARNING:".
  435:                  " $logged to $server returned $answer</font>");
  436:     }
  437:     return $answer;
  438: }
  439: 
  440: # ----------------------------------------------------------- Send USR1 to lonc
  441: 
  442: sub reconlonc {
  443:     my ($lonid) = @_;
  444:     if ($lonid) {
  445:         my $hostname = &hostname($lonid);
  446: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  447: 	if ($hostname && -e $peerfile) {
  448: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  449: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  450: 					     Type    => SOCK_STREAM,
  451: 					     Timeout => 10);
  452: 	    if ($client) {
  453: 		print $client ("reset_retries\n");
  454: 		my $answer=<$client>;
  455: 		#reset just this one.
  456: 	    }
  457: 	}
  458: 	return;
  459:     }
  460: 
  461:     &logthis("Trying to reconnect lonc");
  462:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  463:     if (open(my $fh,"<",$loncfile)) {
  464: 	my $loncpid=<$fh>;
  465:         chomp($loncpid);
  466:         if (kill 0 => $loncpid) {
  467: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  468:             kill USR1 => $loncpid;
  469:             sleep 1;
  470:          } else {
  471: 	    &logthis(
  472:                "<font color=\"blue\">WARNING:".
  473:                " lonc at pid $loncpid not responding, giving up</font>");
  474:         }
  475:     } else {
  476: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  477:     }
  478: }
  479: 
  480: # ------------------------------------------------------ Critical communication
  481: 
  482: sub critical {
  483:     my ($cmd,$server)=@_;
  484:     unless (&hostname($server)) {
  485:         &logthis("<font color=\"blue\">WARNING:".
  486:                " Critical message to unknown server ($server)</font>");
  487:         return 'no_such_host';
  488:     }
  489:     my $answer=reply($cmd,$server);
  490:     if ($answer eq 'con_lost') {
  491: 	&reconlonc($server);
  492: 	my $answer=reply($cmd,$server);
  493:         if ($answer eq 'con_lost') {
  494:             my $now=time;
  495:             my $middlename=$cmd;
  496:             $middlename=substr($middlename,0,16);
  497:             $middlename=~s/\W//g;
  498:             my $dfilename=
  499:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  500:             $dumpcount++;
  501:             {
  502: 		my $dfh;
  503: 		if (open($dfh,">",$dfilename)) {
  504: 		    print $dfh "$cmd\n"; 
  505: 		    close($dfh);
  506: 		}
  507:             }
  508:             sleep 1;
  509:             my $wcmd='';
  510:             {
  511: 		my $dfh;
  512: 		if (open($dfh,"<",$dfilename)) {
  513: 		    $wcmd=<$dfh>; 
  514: 		    close($dfh);
  515: 		}
  516:             }
  517:             chomp($wcmd);
  518:             if ($wcmd eq $cmd) {
  519: 		&logthis("<font color=\"blue\">WARNING: ".
  520:                          "Connection buffer $dfilename: $cmd</font>");
  521:                 &logperm("D:$server:$cmd");
  522: 	        return 'con_delayed';
  523:             } else {
  524:                 &logthis("<font color=\"red\">CRITICAL:"
  525:                         ." Critical connection failed: $server $cmd</font>");
  526:                 &logperm("F:$server:$cmd");
  527:                 return 'con_failed';
  528:             }
  529:         }
  530:     }
  531:     return $answer;
  532: }
  533: 
  534: # ------------------------------------------- check if return value is an error
  535: 
  536: sub error {
  537:     my ($result) = @_;
  538:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  539: 	if ($2 == 2) { return undef; }
  540: 	return $1;
  541:     }
  542:     return undef;
  543: }
  544: 
  545: sub convert_and_load_session_env {
  546:     my ($lonidsdir,$handle)=@_;
  547:     my @profile;
  548:     {
  549: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  550: 	if (!$opened) {
  551: 	    return 0;
  552: 	}
  553: 	flock($idf,LOCK_SH);
  554: 	@profile=<$idf>;
  555: 	close($idf);
  556:     }
  557:     my %temp_env;
  558:     foreach my $line (@profile) {
  559: 	if ($line !~ m/=/) {
  560: 	    return 0;
  561: 	}
  562: 	chomp($line);
  563: 	my ($envname,$envvalue)=split(/=/,$line,2);
  564: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  565:     }
  566:     unlink("$lonidsdir/$handle.id");
  567:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  568: 	    0640)) {
  569: 	%disk_env = %temp_env;
  570: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  571: 	untie(%disk_env);
  572:     }
  573:     return 1;
  574: }
  575: 
  576: # ------------------------------------------- Transfer profile into environment
  577: my $env_loaded;
  578: sub transfer_profile_to_env {
  579:     my ($lonidsdir,$handle,$force_transfer) = @_;
  580:     if (!$force_transfer && $env_loaded) { return; } 
  581: 
  582:     if (!defined($lonidsdir)) {
  583: 	$lonidsdir = $perlvar{'lonIDsDir'};
  584:     }
  585:     if (!defined($handle)) {
  586:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  587:     }
  588: 
  589:     my $convert;
  590:     {
  591:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  592: 	if (!$opened) {
  593: 	    return;
  594: 	}
  595: 	flock($idf,LOCK_SH);
  596: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  597: 		&GDBM_READER(),0640)) {
  598: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  599: 	    untie(%disk_env);
  600: 	} else {
  601: 	    $convert = 1;
  602: 	}
  603:     }
  604:     if ($convert) {
  605: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  606: 	    &logthis("Failed to load session, or convert session.");
  607: 	}
  608:     }
  609: 
  610:     my %remove;
  611:     while ( my $envname = each(%env) ) {
  612:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  613:             if ($time < time-300) {
  614:                 $remove{$key}++;
  615:             }
  616:         }
  617:     }
  618: 
  619:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  620:     $env_loaded=1;
  621:     foreach my $expired_key (keys(%remove)) {
  622:         &delenv($expired_key);
  623:     }
  624: }
  625: 
  626: # ---------------------------------------------------- Check for valid session 
  627: sub check_for_valid_session {
  628:     my ($r,$name,$userhashref,$domref) = @_;
  629:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  630:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  631:     if ($name eq 'lonDAV') {
  632:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  633:     } else {
  634:         $lonidsdir=$r->dir_config('lonIDsDir');
  635:         if ($name eq '') {
  636:             $name = 'lonID';
  637:         }
  638:     }
  639:     if ($name eq 'lonID') {
  640:         $secure = 'lonSID';
  641:         $linkname = 'lonLinkID';
  642:         $pubname = 'lonPubID';
  643:         if (exists($cookies{$secure})) {
  644:             $lonid=$cookies{$secure};
  645:         } elsif (exists($cookies{$name})) {
  646:             $lonid=$cookies{$name};
  647:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
  648:             $lonid=$cookies{$linkname};
  649:         } elsif (exists($cookies{$pubname})) {
  650:             $lonid=$cookies{$pubname};
  651:         }
  652:     } else {
  653:         $lonid=$cookies{$name};
  654:     }
  655:     return undef if (!$lonid);
  656: 
  657:     my $handle=&LONCAPA::clean_handle($lonid->value);
  658:     if (-l "$lonidsdir/$handle.id") {
  659:         my $link = readlink("$lonidsdir/$handle.id");
  660:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  661:             $handle = $1;
  662:         }
  663:     }
  664:     if (!-e "$lonidsdir/$handle.id") {
  665:         if ((ref($domref)) && ($name eq 'lonID') &&
  666:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  667:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  668:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  669:                 $$domref = $possudom;
  670:             }
  671:         }
  672:         return undef;
  673:     }
  674: 
  675:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  676:     return undef if (!$opened);
  677: 
  678:     flock($idf,LOCK_SH);
  679:     my %disk_env;
  680:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  681: 	    &GDBM_READER(),0640)) {
  682: 	return undef;	
  683:     }
  684: 
  685:     if (!defined($disk_env{'user.name'})
  686: 	|| !defined($disk_env{'user.domain'})) {
  687:         untie(%disk_env);
  688: 	return undef;
  689:     }
  690: 
  691:     if (ref($userhashref) eq 'HASH') {
  692:         $userhashref->{'name'} = $disk_env{'user.name'};
  693:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  694:         if ($disk_env{'request.role'}) {
  695:             $userhashref->{'role'} = $disk_env{'request.role'};
  696:         }
  697:     }
  698:     untie(%disk_env);
  699: 
  700:     return $handle;
  701: }
  702: 
  703: sub timed_flock {
  704:     my ($file,$lock_type) = @_;
  705:     my $failed=0;
  706:     eval {
  707: 	local $SIG{__DIE__}='DEFAULT';
  708: 	local $SIG{ALRM}=sub {
  709: 	    $failed=1;
  710: 	    die("failed lock");
  711: 	};
  712: 	alarm(13);
  713: 	flock($file,$lock_type);
  714: 	alarm(0);
  715:     };
  716:     if ($failed) {
  717: 	return undef;
  718:     } else {
  719: 	return 1;
  720:     }
  721: }
  722: 
  723: sub get_sessionfile_vars {
  724:     my ($handle,$lonidsdir,$storearr) = @_;
  725:     my %returnhash;
  726:     unless (ref($storearr) eq 'ARRAY') {
  727:         return %returnhash;
  728:     }
  729:     if (-l "$lonidsdir/$handle.id") {
  730:         my $link = readlink("$lonidsdir/$handle.id");
  731:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  732:             $handle = $1;
  733:         }
  734:     }
  735:     if ((-e "$lonidsdir/$handle.id") &&
  736:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  737:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  738:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  739:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  740:                 flock($idf,LOCK_SH);
  741:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  742:                         &GDBM_READER(),0640)) {
  743:                     foreach my $item (@{$storearr}) {
  744:                         $returnhash{$item} = $disk_env{$item};
  745:                     }
  746:                     untie(%disk_env);
  747:                 }
  748:             }
  749:         }
  750:     }
  751:     return %returnhash;
  752: }
  753: 
  754: # ---------------------------------------------------------- Append Environment
  755: 
  756: sub appenv {
  757:     my ($newenv,$roles) = @_;
  758:     if (ref($newenv) eq 'HASH') {
  759:         foreach my $key (keys(%{$newenv})) {
  760:             my $refused = 0;
  761: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  762:                 $refused = 1;
  763:                 if (ref($roles) eq 'ARRAY') {
  764:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  765:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  766:                         $refused = 0;
  767:                     }
  768:                 }
  769:             }
  770:             if ($refused) {
  771:                 &logthis("<font color=\"blue\">WARNING: ".
  772:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  773:                          .'</font>');
  774: 	        delete($newenv->{$key});
  775:             } else {
  776:                 $env{$key}=$newenv->{$key};
  777:             }
  778:         }
  779:         my $lonids = $perlvar{'lonIDsDir'};
  780:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  781:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  782:             if ($opened
  783: 	        && &timed_flock($env_file,LOCK_EX)
  784: 	        &&
  785: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  786: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  787: 	        while (my ($key,$value) = each(%{$newenv})) {
  788: 	            $disk_env{$key} = $value;
  789: 	        }
  790: 	        untie(%disk_env);
  791:             }
  792:         }
  793:     }
  794:     return 'ok';
  795: }
  796: # ----------------------------------------------------- Delete from Environment
  797: 
  798: sub delenv {
  799:     my ($delthis,$regexp,$roles) = @_;
  800:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  801:         my $refused = 1;
  802:         if (ref($roles) eq 'ARRAY') {
  803:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  804:             if (grep(/^\Q$role\E$/,@{$roles})) {
  805:                 $refused = 0;
  806:             }
  807:         }
  808:         if ($refused) {
  809:             &logthis("<font color=\"blue\">WARNING: ".
  810:                      "Attempt to delete from environment ".$delthis);
  811:             return 'error';
  812:         }
  813:     }
  814:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  815:     if ($opened
  816: 	&& &timed_flock($env_file,LOCK_EX)
  817: 	&&
  818: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  819: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  820: 	foreach my $key (keys(%disk_env)) {
  821: 	    if ($regexp) {
  822:                 if ($key=~/^$delthis/) {
  823:                     delete($env{$key});
  824:                     delete($disk_env{$key});
  825:                 } 
  826:             } else {
  827:                 if ($key=~/^\Q$delthis\E/) {
  828: 		    delete($env{$key});
  829: 		    delete($disk_env{$key});
  830: 	        }
  831:             }
  832: 	}
  833: 	untie(%disk_env);
  834:     }
  835:     return 'ok';
  836: }
  837: 
  838: sub get_env_multiple {
  839:     my ($name) = @_;
  840:     my @values;
  841:     if (defined($env{$name})) {
  842:         # exists is it an array
  843:         if (ref($env{$name})) {
  844:             @values=@{ $env{$name} };
  845:         } else {
  846:             $values[0]=$env{$name};
  847:         }
  848:     }
  849:     return(@values);
  850: }
  851: 
  852: # ------------------------------------------------------------------- Locking
  853: 
  854: sub set_lock {
  855:     my ($text)=@_;
  856:     $locknum++;
  857:     my $id=$$.'-'.$locknum;
  858:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  859:              'session.lock.'.$id => $text});
  860:     return $id;
  861: }
  862: 
  863: sub get_locks {
  864:     my $num=0;
  865:     my %texts=();
  866:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  867:        if ($lock=~/\w/) {
  868:           $num++;
  869:           $texts{$lock}=$env{'session.lock.'.$lock};
  870:        }
  871:    }
  872:    return ($num,%texts);
  873: }
  874: 
  875: sub remove_lock {
  876:     my ($id)=@_;
  877:     my $newlocks='';
  878:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  879:        if (($lock=~/\w/) && ($lock ne $id)) {
  880:           $newlocks.=','.$lock;
  881:        }
  882:     }
  883:     &appenv({'session.locks' => $newlocks});
  884:     &delenv('session.lock.'.$id);
  885: }
  886: 
  887: sub remove_all_locks {
  888:     my $activelocks=$env{'session.locks'};
  889:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  890:        if ($lock=~/\w/) {
  891:           &remove_lock($lock);
  892:        }
  893:     }
  894: }
  895: 
  896: 
  897: # ------------------------------------------ Find out current server userload
  898: sub userload {
  899:     my $numusers=0;
  900:     {
  901: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  902: 	my $filename;
  903: 	my $curtime=time;
  904: 	while ($filename=readdir(LONIDS)) {
  905: 	    next if ($filename eq '.' || $filename eq '..');
  906: 	    next if ($filename =~ /publicuser_\d+\.id/);
  907:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
  908: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  909: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  910: 	}
  911: 	closedir(LONIDS);
  912:     }
  913:     my $userloadpercent=0;
  914:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  915:     if ($maxuserload) {
  916: 	$userloadpercent=100*$numusers/$maxuserload;
  917:     }
  918:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  919:     return $userloadpercent;
  920: }
  921: 
  922: # ------------------------------ Find server with least workload from spare.tab
  923: 
  924: sub spareserver {
  925:     my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  926:     my $spare_server;
  927:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  928:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  929:                                                      :  $userloadpercent;
  930:     my ($uint_dom,$remotesessions);
  931:     if (($udom ne '') && (&domain($udom) ne '')) {
  932:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  933:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  934:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  935:         $remotesessions = $udomdefaults{'remotesessions'};
  936:     }
  937:     my $spareshash = &this_host_spares($udom);
  938:     if (ref($spareshash) eq 'HASH') {
  939:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  940:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  941:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  942:                                              $try_server));
  943: 	        ($spare_server, $lowest_load) =
  944: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  945:             }
  946:         }
  947: 
  948:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  949: 
  950:         if (!$found_server) {
  951:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  952: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  953:                     next unless (&spare_can_host($udom,$uint_dom,
  954:                                                  $remotesessions,$try_server));
  955: 	            ($spare_server, $lowest_load) =
  956: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  957:                 }
  958: 	    }
  959:         }
  960:     }
  961: 
  962:     if (!$want_server_name) {
  963:         if (defined($spare_server)) {
  964:             my $hostname = &hostname($spare_server);
  965:             if (defined($hostname)) {
  966:                 my $protocol = 'http';
  967:                 if ($protocol{$spare_server} eq 'https') {
  968:                     $protocol = $protocol{$spare_server};
  969:                 }
  970:                 my $alias = &Apache::lonnet::use_proxy_alias($r,$spare_server);
  971:                 $hostname = $alias if ($alias ne '');
  972: 	        $spare_server = $protocol.'://'.$hostname;
  973:             }
  974:         }
  975:     }
  976:     return $spare_server;
  977: }
  978: 
  979: sub compare_server_load {
  980:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
  981: 
  982:     if ($required) {
  983:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  984:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  985:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  986:         if (($major eq '' && $minor eq '') ||
  987:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  988:             return ($spare_server,$lowest_load);
  989:         }
  990:     }
  991: 
  992:     my $loadans     = &reply('load',    $try_server);
  993:     my $userloadans = &reply('userload',$try_server);
  994: 
  995:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  996: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  997:     }
  998: 
  999:     my $load;
 1000:     if ($loadans =~ /\d/) {
 1001: 	if ($userloadans =~ /\d/) {
 1002: 	    #both are numbers, pick the bigger one
 1003: 	    $load = ($loadans > $userloadans) ? $loadans 
 1004: 		                              : $userloadans;
 1005: 	} else {
 1006: 	    $load = $loadans;
 1007: 	}
 1008:     } else {
 1009: 	$load = $userloadans;
 1010:     }
 1011: 
 1012:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1013: 	$spare_server = $try_server;
 1014: 	$lowest_load  = $load;
 1015:     }
 1016:     return ($spare_server,$lowest_load);
 1017: }
 1018: 
 1019: # --------------------------- ask offload servers if user already has a session
 1020: sub find_existing_session {
 1021:     my ($udom,$uname) = @_;
 1022:     my $spareshash = &this_host_spares($udom);
 1023:     if (ref($spareshash) eq 'HASH') {
 1024:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1025:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1026:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1027:             }
 1028:         }
 1029:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1030:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1031:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1032:             }
 1033:         }
 1034:     }
 1035:     return;
 1036: }
 1037: 
 1038: # check if user's browser sent load balancer cookie and server still has session
 1039: # and is not overloaded.
 1040: sub check_for_balancer_cookie {
 1041:     my ($r,$update_mtime) = @_;
 1042:     my ($otherserver,$cookie);
 1043:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1044:     if (exists($cookies{'balanceID'})) {
 1045:         my $balid = $cookies{'balanceID'};
 1046:         $cookie=&LONCAPA::clean_handle($balid->value);
 1047:         my $balancedir=$r->dir_config('lonBalanceDir');
 1048:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1049:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1050:                 my ($possudom,$possuname) = ($1,$2);
 1051:                 my $has_session = 0;
 1052:                 if ((&domain($possudom) ne '') &&
 1053:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1054:                     my $try_server;
 1055:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1056:                     if ($opened) {
 1057:                         flock($idf,LOCK_SH);
 1058:                         while (my $line = <$idf>) {
 1059:                             chomp($line);
 1060:                             if (&hostname($line) ne '') {
 1061:                                 $try_server = $line;
 1062:                                 last;
 1063:                             }
 1064:                         }
 1065:                         close($idf);
 1066:                         if (($try_server) &&
 1067:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1068:                             my $lowest_load = 30000;
 1069:                             ($otherserver,$lowest_load) =
 1070:                                 &compare_server_load($try_server,undef,$lowest_load);
 1071:                             if ($otherserver ne '' && $lowest_load < 100) {
 1072:                                 $has_session = 1;
 1073:                             } else {
 1074:                                 undef($otherserver);
 1075:                             }
 1076:                         }
 1077:                     }
 1078:                 }
 1079:                 if ($has_session) {
 1080:                     if ($update_mtime) {
 1081:                         my $atime = my $mtime = time;
 1082:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1083:                     }
 1084:                 } else {
 1085:                     unlink("$balancedir/$cookie.id");
 1086:                 }
 1087:             }
 1088:         }
 1089:     }
 1090:     return ($otherserver,$cookie);
 1091: }
 1092: 
 1093: sub updatebalcookie {
 1094:     my ($cookie,$balancer,$lastentry)=@_;
 1095:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1096:         my ($udom,$uname) = ($1,$2);
 1097:         my $uprimary_id = &domain($udom,'primary');
 1098:         my $uintdom = &internet_dom($uprimary_id);
 1099:         my $intdom = &internet_dom($balancer);
 1100:         my $serverhomedom = &host_domain($balancer);
 1101:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1102:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
 1103:         }
 1104:     }
 1105:     return;
 1106: }
 1107: 
 1108: sub delbalcookie {
 1109:     my ($cookie,$balancer) =@_;
 1110:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1111:         my ($udom,$uname) = ($1,$2);
 1112:         my $uprimary_id = &domain($udom,'primary');
 1113:         my $uintdom = &internet_dom($uprimary_id);
 1114:         my $intdom = &internet_dom($balancer);
 1115:         my $serverhomedom = &host_domain($balancer);
 1116:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1117:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
 1118:         }
 1119:     }
 1120: }
 1121: 
 1122: # -------------------------------- ask if server already has a session for user
 1123: sub has_user_session {
 1124:     my ($lonid,$udom,$uname) = @_;
 1125:     my $result = &reply(join(':','userhassession',
 1126: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1127:     return 1 if ($result eq 'ok');
 1128: 
 1129:     return 0;
 1130: }
 1131: 
 1132: # --------- determine least loaded server in a user's domain which allows login
 1133: 
 1134: sub choose_server {
 1135:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1136:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1137:     my %servers = &get_servers($udom);
 1138:     my $lowest_load = 30000;
 1139:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1140:     if ($skiploadbal) {
 1141:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1142:         unless (defined($cached)) {
 1143:             my $cachetime = 60*60*24;
 1144:             my %domconfig =
 1145:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1146:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1147:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1148:                                            $cachetime);
 1149:             }
 1150:         }
 1151:     }
 1152:     foreach my $lonhost (keys(%servers)) {
 1153:         my $loginvia;
 1154:         if ($skiploadbal) {
 1155:             if (ref($balancers) eq 'HASH') {
 1156:                 next if (exists($balancers->{$lonhost}));
 1157:             }
 1158:         }
 1159:         if ($checkloginvia) {
 1160:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1161:             if ($loginvia) {
 1162:                 my ($server,$path) = split(/:/,$loginvia);
 1163:                 ($login_host, $lowest_load) =
 1164:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1165:                 if ($login_host eq $server) {
 1166:                     $portal_path = $path;
 1167:                     $isredirect = 1;
 1168:                 }
 1169:             } else {
 1170:                 ($login_host, $lowest_load) =
 1171:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1172:                 if ($login_host eq $lonhost) {
 1173:                     $portal_path = '';
 1174:                     $isredirect = ''; 
 1175:                 }
 1176:             }
 1177:         } else {
 1178:             ($login_host, $lowest_load) =
 1179:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1180:         }
 1181:     }
 1182:     if ($login_host ne '') {
 1183:         $hostname = &hostname($login_host);
 1184:     }
 1185:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1186: }
 1187: 
 1188: sub get_course_sessions {
 1189:     my ($cnum,$cdom,$lastactivity) = @_;
 1190:     my %servers = &internet_dom_servers($cdom);
 1191:     my %returnhash;
 1192:     foreach my $server (sort(keys(%servers))) {
 1193:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
 1194:         my @pairs=split(/\&/,$rep);
 1195:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
 1196:             foreach my $item (@pairs) {
 1197:                 my ($key,$value)=split(/=/,$item,2);
 1198:                 $key = &unescape($key);
 1199:                 next if ($key =~ /^error: 2 /);
 1200:                 if (exists($returnhash{$key})) {
 1201:                     next if ($value < $returnhash{$key});
 1202:                 }
 1203:                 $returnhash{$key}=$value;
 1204:             }
 1205:         }
 1206:     }
 1207:     return %returnhash;
 1208: }
 1209: 
 1210: # --------------------------------------------- Try to change a user's password
 1211: 
 1212: sub changepass {
 1213:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1214:     $currentpass = &escape($currentpass);
 1215:     $newpass     = &escape($newpass);
 1216:     my $lonhost = $perlvar{'lonHostID'};
 1217:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1218: 		       $server);
 1219:     if (! $answer) {
 1220: 	&logthis("No reply on password change request to $server ".
 1221: 		 "by $uname in domain $udom.");
 1222:     } elsif ($answer =~ "^ok") {
 1223:         &logthis("$uname in $udom successfully changed their password ".
 1224: 		 "on $server.");
 1225:     } elsif ($answer =~ "^pwchange_failure") {
 1226: 	&logthis("$uname in $udom was unable to change their password ".
 1227: 		 "on $server.  The action was blocked by either lcpasswd ".
 1228: 		 "or pwchange");
 1229:     } elsif ($answer =~ "^non_authorized") {
 1230:         &logthis("$uname in $udom did not get their password correct when ".
 1231: 		 "attempting to change it on $server.");
 1232:     } elsif ($answer =~ "^auth_mode_error") {
 1233:         &logthis("$uname in $udom attempted to change their password despite ".
 1234: 		 "not being locally or internally authenticated on $server.");
 1235:     } elsif ($answer =~ "^unknown_user") {
 1236:         &logthis("$uname in $udom attempted to change their password ".
 1237: 		 "on $server but were unable to because $server is not ".
 1238: 		 "their home server.");
 1239:     } elsif ($answer =~ "^refused") {
 1240: 	&logthis("$server refused to change $uname in $udom password because ".
 1241: 		 "it was sent an unencrypted request to change the password.");
 1242:     } elsif ($answer =~ "invalid_client") {
 1243:         &logthis("$server refused to change $uname in $udom password because ".
 1244:                  "it was a reset by e-mail originating from an invalid server.");
 1245:     } elsif ($answer =~ "^prioruse") {
 1246:        &logthis("$server refused to change $uname in $udom password because ".
 1247:                 "the password had been used before");
 1248:     }
 1249:     return $answer;
 1250: }
 1251: 
 1252: # ----------------------- Try to determine user's current authentication scheme
 1253: 
 1254: sub queryauthenticate {
 1255:     my ($uname,$udom)=@_;
 1256:     my $uhome=&homeserver($uname,$udom);
 1257:     if (!$uhome) {
 1258: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1259: 	return 'no_host';
 1260:     }
 1261:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1262:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1263: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1264:     }
 1265:     return $answer;
 1266: }
 1267: 
 1268: # --------- Try to authenticate user from domain's lib servers (first this one)
 1269: 
 1270: sub authenticate {
 1271:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1272:     $upass=&escape($upass);
 1273:     $uname= &LONCAPA::clean_username($uname);
 1274:     my $uhome=&homeserver($uname,$udom,1);
 1275:     my $newhome;
 1276:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1277: # Maybe the machine was offline and only re-appeared again recently?
 1278:         &reconlonc();
 1279: # One more
 1280: 	$uhome=&homeserver($uname,$udom,1);
 1281:         if (($uhome eq 'no_host') && $checkdefauth) {
 1282:             if (defined(&domain($udom,'primary'))) {
 1283:                 $newhome=&domain($udom,'primary');
 1284:             }
 1285:             if ($newhome ne '') {
 1286:                 $uhome = $newhome;
 1287:             }
 1288:         }
 1289: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1290: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1291: 	    return 'no_host';
 1292:         }
 1293:     }
 1294:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1295:     if ($answer eq 'authorized') {
 1296:         if ($newhome) {
 1297:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1298:             return 'no_account_on_host'; 
 1299:         } else {
 1300:             &logthis("User $uname at $udom authorized by $uhome");
 1301:             return $uhome;
 1302:         }
 1303:     }
 1304:     if ($answer eq 'non_authorized') {
 1305: 	&logthis("User $uname at $udom rejected by $uhome");
 1306: 	return 'no_host'; 
 1307:     }
 1308:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1309:     return 'no_host';
 1310: }
 1311: 
 1312: sub can_host_session {
 1313:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1314:     my $canhost = 1;
 1315:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1316:     if (ref($remotesessions) eq 'HASH') {
 1317:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1318:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1319:                 $canhost = 0;
 1320:             } else {
 1321:                 $canhost = 1;
 1322:             }
 1323:         }
 1324:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1325:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1326:                 $canhost = 1;
 1327:             } else {
 1328:                 $canhost = 0;
 1329:             }
 1330:         }
 1331:         if ($canhost) {
 1332:             if ($remotesessions->{'version'} ne '') {
 1333:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1334:                 if ($reqmajor ne '' && $reqminor ne '') {
 1335:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1336:                         my $major = $1;
 1337:                         my $minor = $2;
 1338:                         if (($major < $reqmajor ) ||
 1339:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1340:                             $canhost = 0;
 1341:                         }
 1342:                     } else {
 1343:                         $canhost = 0;
 1344:                     }
 1345:                 }
 1346:             }
 1347:         }
 1348:     }
 1349:     if ($canhost) {
 1350:         if (ref($hostedsessions) eq 'HASH') {
 1351:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1352:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1353:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1354:                 if (($uint_dom ne '') && 
 1355:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1356:                     $canhost = 0;
 1357:                 } else {
 1358:                     $canhost = 1;
 1359:                 }
 1360:             }
 1361:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1362:                 if (($uint_dom ne '') && 
 1363:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1364:                     $canhost = 1;
 1365:                 } else {
 1366:                     $canhost = 0;
 1367:                 }
 1368:             }
 1369:         }
 1370:     }
 1371:     return $canhost;
 1372: }
 1373: 
 1374: sub spare_can_host {
 1375:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1376:     my $canhost=1;
 1377:     my $try_server_hostname = &hostname($try_server);
 1378:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1379:     my $serverhomedom = &host_domain($serverhomeID);
 1380:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1381:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1382:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1383:             $canhost = 0;
 1384:         }
 1385:     }
 1386:     if ($canhost) {
 1387:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
 1388:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
 1389:                 unless (&shared_institution($udom,$try_server)) {
 1390:                     $canhost = 0;
 1391:                 }
 1392:             }
 1393:         }
 1394:     }
 1395:     if (($canhost) && ($uint_dom)) {
 1396:         my @intdoms;
 1397:         my $internet_names = &get_internet_names($try_server);
 1398:         if (ref($internet_names) eq 'ARRAY') {
 1399:             @intdoms = @{$internet_names};
 1400:         }
 1401:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1402:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1403:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1404:                                          $remotesessions,
 1405:                                          $defdomdefaults{'hostedsessions'});
 1406:         }
 1407:     }
 1408:     return $canhost;
 1409: }
 1410: 
 1411: sub this_host_spares {
 1412:     my ($dom) = @_;
 1413:     my ($dom_in_use,$lonhost_in_use,$result);
 1414:     my @hosts = &current_machine_ids();
 1415:     foreach my $lonhost (@hosts) {
 1416:         if (&host_domain($lonhost) eq $dom) {
 1417:             $dom_in_use = $dom;
 1418:             $lonhost_in_use = $lonhost;
 1419:             last;
 1420:         }
 1421:     }
 1422:     if ($dom_in_use ne '') {
 1423:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1424:     }
 1425:     if (ref($result) ne 'HASH') {
 1426:         $lonhost_in_use = $perlvar{'lonHostID'};
 1427:         $dom_in_use = &host_domain($lonhost_in_use);
 1428:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1429:         if (ref($result) ne 'HASH') {
 1430:             $result = \%spareid;
 1431:         }
 1432:     }
 1433:     return $result;
 1434: }
 1435: 
 1436: sub spares_for_offload  {
 1437:     my ($dom_in_use,$lonhost_in_use) = @_;
 1438:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1439:     if (defined($cached)) {
 1440:         return $result;
 1441:     } else {
 1442:         my $cachetime = 60*60*24;
 1443:         my %domconfig =
 1444:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1445:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1446:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1447:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1448:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1449:                 }
 1450:             }
 1451:         }
 1452:     }
 1453:     return;
 1454: }
 1455: 
 1456: sub get_lonbalancer_config {
 1457:     my ($servers) = @_;
 1458:     my ($currbalancer,$currtargets);
 1459:     if (ref($servers) eq 'HASH') {
 1460:         foreach my $server (keys(%{$servers})) {
 1461:             my %what = (
 1462:                          spareid => 1,
 1463:                          perlvar => 1,
 1464:                        );
 1465:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1466:             if ($result eq 'ok') {
 1467:                 if (ref($returnhash) eq 'HASH') {
 1468:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1469:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1470:                             $currbalancer = $server;
 1471:                             $currtargets = {};
 1472:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1473:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1474:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1475:                                 }
 1476:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1477:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1478:                                 }
 1479:                             }
 1480:                             last;
 1481:                         }
 1482:                     }
 1483:                 }
 1484:             }
 1485:         }
 1486:     }
 1487:     return ($currbalancer,$currtargets);
 1488: }
 1489: 
 1490: sub check_loadbalancing {
 1491:     my ($uname,$udom,$caller) = @_;
 1492:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1493:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
 1494:     my $lonhost = $perlvar{'lonHostID'};
 1495:     my @hosts = &current_machine_ids();
 1496:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1497:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1498:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1499:     my $serverhomedom = &host_domain($lonhost);
 1500:     my $domneedscache; 
 1501:     my $cachetime = 60*60*24;
 1502: 
 1503:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1504:         $dom_in_use = $udom;
 1505:         $homeintdom = 1;
 1506:     } else {
 1507:         $dom_in_use = $serverhomedom;
 1508:     }
 1509:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1510:     unless (defined($cached)) {
 1511:         my %domconfig =
 1512:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1513:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1514:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1515:         } else {
 1516:             $domneedscache = $dom_in_use;
 1517:         }
 1518:     }
 1519:     if (ref($result) eq 'HASH') {
 1520:         ($is_balancer,$currtargets,$currrules,$setcookie) =
 1521:             &check_balancer_result($result,@hosts);
 1522:         if ($is_balancer) {
 1523:             if (ref($currrules) eq 'HASH') {
 1524:                 if ($homeintdom) {
 1525:                     if ($uname ne '') {
 1526:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1527:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1528:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1529:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1530:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1531:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1532:                             }
 1533:                         }
 1534:                         if ($rule_in_effect eq '') {
 1535:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1536:                             if ($userenv{'inststatus'} ne '') {
 1537:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1538:                                 my ($othertitle,$usertypes,$types) =
 1539:                                     &Apache::loncommon::sorted_inst_types($udom);
 1540:                                 if (ref($types) eq 'ARRAY') {
 1541:                                     foreach my $type (@{$types}) {
 1542:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1543:                                             if (exists($currrules->{$type})) {
 1544:                                                 $rule_in_effect = $currrules->{$type};
 1545:                                             }
 1546:                                         }
 1547:                                     }
 1548:                                 }
 1549:                             } else {
 1550:                                 if (exists($currrules->{'default'})) {
 1551:                                     $rule_in_effect = $currrules->{'default'};
 1552:                                 }
 1553:                             }
 1554:                         }
 1555:                     } else {
 1556:                         if (exists($currrules->{'default'})) {
 1557:                             $rule_in_effect = $currrules->{'default'};
 1558:                         }
 1559:                     }
 1560:                 } else {
 1561:                     if ($currrules->{'_LC_external'} ne '') {
 1562:                         $rule_in_effect = $currrules->{'_LC_external'};
 1563:                     }
 1564:                 }
 1565:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1566:                                                        $uname,$udom);
 1567:             }
 1568:         }
 1569:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1570:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1571:         unless (defined($cached)) {
 1572:             my %domconfig =
 1573:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1574:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1575:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1576:             } else {
 1577:                 $domneedscache = $serverhomedom;
 1578:             }
 1579:         }
 1580:         if (ref($result) eq 'HASH') {
 1581:             ($is_balancer,$currtargets,$currrules,$setcookie) =
 1582:                 &check_balancer_result($result,@hosts);
 1583:             if ($is_balancer) {
 1584:                 if (ref($currrules) eq 'HASH') {
 1585:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1586:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1587:                     }
 1588:                 }
 1589:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1590:                                                        $uname,$udom);
 1591:             }
 1592:         } else {
 1593:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1594:                 $is_balancer = 1;
 1595:                 $offloadto = &this_host_spares($dom_in_use);
 1596:             }
 1597:             unless (defined($cached)) {
 1598:                 $domneedscache = $serverhomedom;
 1599:             }
 1600:         }
 1601:     } else {
 1602:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1603:             $is_balancer = 1;
 1604:             $offloadto = &this_host_spares($dom_in_use);
 1605:         }
 1606:         unless (defined($cached)) {
 1607:             $domneedscache = $serverhomedom;
 1608:         }
 1609:     }
 1610:     if ($domneedscache) {
 1611:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1612:     }
 1613:     if (($is_balancer) && ($caller ne 'switchserver')) {
 1614:         my $lowest_load = 30000;
 1615:         if (ref($offloadto) eq 'HASH') {
 1616:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1617:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1618:                     ($otherserver,$lowest_load) =
 1619:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1620:                 }
 1621:             }
 1622:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1623: 
 1624:             if (!$found_server) {
 1625:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1626:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1627:                         ($otherserver,$lowest_load) =
 1628:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1629:                     }
 1630:                 }
 1631:             }
 1632:         } elsif (ref($offloadto) eq 'ARRAY') {
 1633:             if (@{$offloadto} == 1) {
 1634:                 $otherserver = $offloadto->[0];
 1635:             } elsif (@{$offloadto} > 1) {
 1636:                 foreach my $try_server (@{$offloadto}) {
 1637:                     ($otherserver,$lowest_load) =
 1638:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1639:                 }
 1640:             }
 1641:         }
 1642:         unless ($caller eq 'login') {
 1643:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1644:                 $is_balancer = 0;
 1645:                 if ($uname ne '' && $udom ne '') {
 1646:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1647:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1648:                                  'user.loadbalcheck.time' => time});
 1649:                     }
 1650:                 }
 1651:             }
 1652:         }
 1653:     }
 1654:     if (($is_balancer) && (!$homeintdom)) {
 1655:         undef($setcookie);
 1656:     }
 1657:     return ($is_balancer,$otherserver,$setcookie);
 1658: }
 1659: 
 1660: sub check_balancer_result {
 1661:     my ($result,@hosts) = @_;
 1662:     my ($is_balancer,$currtargets,$currrules,$setcookie);
 1663:     if (ref($result) eq 'HASH') {
 1664:         if ($result->{'lonhost'} ne '') {
 1665:             my $currbalancer = $result->{'lonhost'};
 1666:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1667:                 $is_balancer = 1;
 1668:                 $currtargets = $result->{'targets'};
 1669:                 $currrules = $result->{'rules'};
 1670:             }
 1671:         } else {
 1672:             foreach my $key (keys(%{$result})) {
 1673:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1674:                     (ref($result->{$key}) eq 'HASH')) {
 1675:                     $is_balancer = 1;
 1676:                     $currrules = $result->{$key}{'rules'};
 1677:                     $currtargets = $result->{$key}{'targets'};
 1678:                     $setcookie = $result->{$key}{'cookie'};
 1679:                     last;
 1680:                 }
 1681:             }
 1682:         }
 1683:     }
 1684:     return ($is_balancer,$currtargets,$currrules,$setcookie);
 1685: }
 1686: 
 1687: sub get_loadbalancer_targets {
 1688:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1689:     my $offloadto;
 1690:     if ($rule_in_effect eq 'none') {
 1691:         return [$perlvar{'lonHostID'}];
 1692:     } elsif ($rule_in_effect eq '') {
 1693:         $offloadto = $currtargets;
 1694:     } else {
 1695:         if ($rule_in_effect eq 'homeserver') {
 1696:             my $homeserver = &homeserver($uname,$udom);
 1697:             if ($homeserver ne 'no_host') {
 1698:                 $offloadto = [$homeserver];
 1699:             }
 1700:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1701:             my %domconfig =
 1702:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1703:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1704:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1705:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1706:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1707:                     }
 1708:                 }
 1709:             } else {
 1710:                 my %servers = &internet_dom_servers($udom);
 1711:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1712:                 if (&hostname($remotebalancer) ne '') {
 1713:                     $offloadto = [$remotebalancer];
 1714:                 }
 1715:             }
 1716:         } elsif (&hostname($rule_in_effect) ne '') {
 1717:             $offloadto = [$rule_in_effect];
 1718:         }
 1719:     }
 1720:     return $offloadto;
 1721: }
 1722: 
 1723: sub internet_dom_servers {
 1724:     my ($dom) = @_;
 1725:     my (%uniqservers,%servers);
 1726:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1727:     my @machinedoms = &machine_domains($primaryserver);
 1728:     foreach my $mdom (@machinedoms) {
 1729:         my %currservers = %servers;
 1730:         my %server = &get_servers($mdom);
 1731:         %servers = (%currservers,%server);
 1732:     }
 1733:     my %by_hostname;
 1734:     foreach my $id (keys(%servers)) {
 1735:         push(@{$by_hostname{$servers{$id}}},$id);
 1736:     }
 1737:     foreach my $hostname (sort(keys(%by_hostname))) {
 1738:         if (@{$by_hostname{$hostname}} > 1) {
 1739:             my $match = 0;
 1740:             foreach my $id (@{$by_hostname{$hostname}}) {
 1741:                 if (&host_domain($id) eq $dom) {
 1742:                     $uniqservers{$id} = $hostname;
 1743:                     $match = 1;
 1744:                 }
 1745:             }
 1746:             unless ($match) {
 1747:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1748:             }
 1749:         } else {
 1750:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1751:         }
 1752:     }
 1753:     return %uniqservers;
 1754: }
 1755: 
 1756: # ---------------------- Find the homebase for a user from domain's lib servers
 1757: 
 1758: my %homecache;
 1759: sub homeserver {
 1760:     my ($uname,$udom,$ignoreBadCache)=@_;
 1761:     my $index="$uname:$udom";
 1762: 
 1763:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1764: 
 1765:     my %servers = &get_servers($udom,'library');
 1766:     foreach my $tryserver (keys(%servers)) {
 1767:         next if ($ignoreBadCache ne 'true' && 
 1768: 		 exists($badServerCache{$tryserver}));
 1769: 
 1770: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1771: 	if ($answer eq 'found') {
 1772: 	    delete($badServerCache{$tryserver}); 
 1773: 	    return $homecache{$index}=$tryserver;
 1774: 	} elsif ($answer eq 'no_host') {
 1775: 	    $badServerCache{$tryserver}=1;
 1776: 	}
 1777:     }    
 1778:     return 'no_host';
 1779: }
 1780: 
 1781: # ------------------------------------- Find the usernames behind a list of IDs
 1782: 
 1783: sub idget {
 1784:     my ($udom,@ids)=@_;
 1785:     my %returnhash=();
 1786:     
 1787:     my %servers = &get_servers($udom,'library');
 1788:     foreach my $tryserver (keys(%servers)) {
 1789: 	my $idlist=join('&', map { &escape($_); } @ids);
 1790: 	$idlist=~tr/A-Z/a-z/; 
 1791: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1792: 	my @answer=();
 1793: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1794: 	    @answer=split(/\&/,$reply);
 1795: 	}                    ;
 1796: 	my $i;
 1797: 	for ($i=0;$i<=$#ids;$i++) {
 1798: 	    if ($answer[$i]) {
 1799: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1800: 	    } 
 1801: 	}
 1802:     } 
 1803:     return %returnhash;
 1804: }
 1805: 
 1806: # ------------------------------------- Find the IDs behind a list of usernames
 1807: 
 1808: sub idrget {
 1809:     my ($udom,@unames)=@_;
 1810:     my %returnhash=();
 1811:     foreach my $uname (@unames) {
 1812:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1813:     }
 1814:     return %returnhash;
 1815: }
 1816: 
 1817: # ------------------------------- Store away a list of names and associated IDs
 1818: 
 1819: sub idput {
 1820:     my ($udom,%ids)=@_;
 1821:     my %servers=();
 1822:     foreach my $uname (keys(%ids)) {
 1823: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1824:         my $uhom=&homeserver($uname,$udom);
 1825:         if ($uhom ne 'no_host') {
 1826:             my $id=&escape($ids{$uname});
 1827:             $id=~tr/A-Z/a-z/;
 1828:             my $esc_unam=&escape($uname);
 1829: 	    if ($servers{$uhom}) {
 1830: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1831:             } else {
 1832:                 $servers{$uhom}=$id.'='.$esc_unam;
 1833:             }
 1834:         }
 1835:     }
 1836:     foreach my $server (keys(%servers)) {
 1837:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1838:     }
 1839: }
 1840: 
 1841: # ---------------------------------------- Delete unwanted IDs from ids.db file
 1842: 
 1843: sub iddel {
 1844:     my ($udom,$idshashref,$uhome)=@_;
 1845:     my %result=();
 1846:     unless (ref($idshashref) eq 'HASH') {
 1847:         return %result;
 1848:     }
 1849:     my %servers=();
 1850:     while (my ($id,$uname) = each(%{$idshashref})) {
 1851:         my $uhom;
 1852:         if ($uhome) {
 1853:             $uhom = $uhome;
 1854:         } else {
 1855:             $uhom=&homeserver($uname,$udom);
 1856:         }
 1857:         if ($uhom ne 'no_host') {
 1858:             if ($servers{$uhom}) {
 1859:                 $servers{$uhom}.='&'.&escape($id);
 1860:             } else {
 1861:                 $servers{$uhom}=&escape($id);
 1862:             }
 1863:         }
 1864:     }
 1865:     foreach my $server (keys(%servers)) {
 1866:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1867:     }
 1868:     return %result;
 1869: }
 1870: 
 1871: # ------------------------------dump from db file owned by domainconfig user
 1872: sub dump_dom {
 1873:     my ($namespace, $udom, $regexp) = @_;
 1874: 
 1875:     $udom ||= $env{'user.domain'};
 1876: 
 1877:     return () unless $udom;
 1878: 
 1879:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1880: }
 1881: 
 1882: # ------------------------------------------ get items from domain db files   
 1883: 
 1884: sub get_dom {
 1885:     my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
 1886:     return if ($udom eq 'public');
 1887:     my $items='';
 1888:     foreach my $item (@$storearr) {
 1889:         $items.=&escape($item).'&';
 1890:     }
 1891:     $items=~s/\&$//;
 1892:     if (!$udom) {
 1893:         $udom=$env{'user.domain'};
 1894:         return if ($udom eq 'public');
 1895:         if (defined(&domain($udom,'primary'))) {
 1896:             $uhome=&domain($udom,'primary');
 1897:         } else {
 1898:             undef($uhome);
 1899:         }
 1900:     } else {
 1901:         if (!$uhome) {
 1902:             if (defined(&domain($udom,'primary'))) {
 1903:                 $uhome=&domain($udom,'primary');
 1904:             }
 1905:         }
 1906:     }
 1907:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1908:         my $rep;
 1909:         if (grep { $_ eq $uhome } &current_machine_ids()) {
 1910:             # domain information is hosted on this machine
 1911:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
 1912:         } else {
 1913:             if ($encrypt) {
 1914:                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 1915:             } else {
 1916:                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1917:             }
 1918:         }
 1919:         my %returnhash;
 1920:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1921:             return %returnhash;
 1922:         }
 1923:         my @pairs=split(/\&/,$rep);
 1924:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1925:             return @pairs;
 1926:         }
 1927:         my $i=0;
 1928:         foreach my $item (@$storearr) {
 1929:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1930:             $i++;
 1931:         }
 1932:         return %returnhash;
 1933:     } else {
 1934:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1935:     }
 1936: }
 1937: 
 1938: # -------------------------------------------- put items in domain db files 
 1939: 
 1940: sub put_dom {
 1941:     my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
 1942:     if (!$udom) {
 1943:         $udom=$env{'user.domain'};
 1944:         if (defined(&domain($udom,'primary'))) {
 1945:             $uhome=&domain($udom,'primary');
 1946:         } else {
 1947:             undef($uhome);
 1948:         }
 1949:     } else {
 1950:         if (!$uhome) {
 1951:             if (defined(&domain($udom,'primary'))) {
 1952:                 $uhome=&domain($udom,'primary');
 1953:             }
 1954:         }
 1955:     } 
 1956:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1957:         my $items='';
 1958:         foreach my $item (keys(%$storehash)) {
 1959:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1960:         }
 1961:         $items=~s/\&$//;
 1962:         if ($encrypt) {
 1963:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 1964:         } else {
 1965:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 1966:         }
 1967:     } else {
 1968:         &logthis("put_dom failed - no homeserver and/or domain");
 1969:     }
 1970: }
 1971: 
 1972: # --------------------- newput for items in db file owned by domainconfig user
 1973: sub newput_dom {
 1974:     my ($namespace,$storehash,$udom) = @_;
 1975:     my $result;
 1976:     if (!$udom) {
 1977:         $udom=$env{'user.domain'};
 1978:     }
 1979:     if ($udom) {
 1980:         my $uname = &get_domainconfiguser($udom);
 1981:         $result = &newput($namespace,$storehash,$udom,$uname);
 1982:     }
 1983:     return $result;
 1984: }
 1985: 
 1986: # --------------------- delete for items in db file owned by domainconfig user
 1987: sub del_dom {
 1988:     my ($namespace,$storearr,$udom)=@_;
 1989:     if (ref($storearr) eq 'ARRAY') {
 1990:         if (!$udom) {
 1991:             $udom=$env{'user.domain'};
 1992:         }
 1993:         if ($udom) {
 1994:             my $uname = &get_domainconfiguser($udom); 
 1995:             return &del($namespace,$storearr,$udom,$uname);
 1996:         }
 1997:     }
 1998: }
 1999: 
 2000: # ----------------------------------construct domainconfig user for a domain 
 2001: sub get_domainconfiguser {
 2002:     my ($udom) = @_;
 2003:     return $udom.'-domainconfig';
 2004: }
 2005: 
 2006: sub retrieve_inst_usertypes {
 2007:     my ($udom) = @_;
 2008:     my (%returnhash,@order);
 2009:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2010:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2011:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2012:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2013:     } else {
 2014:         if (defined(&domain($udom,'primary'))) {
 2015:             my $uhome=&domain($udom,'primary');
 2016:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2017:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2018:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2019:                 return (\%returnhash,\@order);
 2020:             }
 2021:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2022:             my @pairs=split(/\&/,$hashitems);
 2023:             foreach my $item (@pairs) {
 2024:                 my ($key,$value)=split(/=/,$item,2);
 2025:                 $key = &unescape($key);
 2026:                 next if ($key =~ /^error: 2 /);
 2027:                 $returnhash{$key}=&thaw_unescape($value);
 2028:             }
 2029:             my @esc_order = split(/\&/,$orderitems);
 2030:             foreach my $item (@esc_order) {
 2031:                 push(@order,&unescape($item));
 2032:             }
 2033:         } else {
 2034:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2035:         }
 2036:         return (\%returnhash,\@order);
 2037:     }
 2038: }
 2039: 
 2040: sub is_domainimage {
 2041:     my ($url) = @_;
 2042:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
 2043:         if (&domain($1) ne '') {
 2044:             return '1';
 2045:         }
 2046:     }
 2047:     return;
 2048: }
 2049: 
 2050: sub inst_directory_query {
 2051:     my ($srch) = @_;
 2052:     my $udom = $srch->{'srchdomain'};
 2053:     my %results;
 2054:     my $homeserver = &domain($udom,'primary');
 2055:     my $outcome;
 2056:     if ($homeserver ne '') {
 2057:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2058:             if ($srch->{'srchby'} eq 'email') {
 2059:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
 2060:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
 2061:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2062:                     (($major == 2) && ($minor < 11)) ||
 2063:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
 2064:                     return;
 2065:                 }
 2066:             }
 2067:         }
 2068: 	my $queryid=&reply("querysend:instdirsearch:".
 2069: 			   &escape($srch->{'srchby'}).':'.
 2070: 			   &escape($srch->{'srchterm'}).':'.
 2071: 			   &escape($srch->{'srchtype'}),$homeserver);
 2072: 	my $host=&hostname($homeserver);
 2073: 	if ($queryid !~/^\Q$host\E\_/) {
 2074: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2075: 	    return;
 2076: 	}
 2077: 	my $response = &get_query_reply($queryid);
 2078: 	my $maxtries = 5;
 2079: 	my $tries = 1;
 2080: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2081: 	    $response = &get_query_reply($queryid);
 2082: 	    $tries ++;
 2083: 	}
 2084: 
 2085:         if (!&error($response) && $response ne 'refused') {
 2086:             if ($response eq 'unavailable') {
 2087:                 $outcome = $response;
 2088:             } else {
 2089:                 $outcome = 'ok';
 2090:                 my @matches = split(/\n/,$response);
 2091:                 foreach my $match (@matches) {
 2092:                     my ($key,$value) = split(/=/,$match);
 2093:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2094:                 }
 2095:             }
 2096:         }
 2097:     }
 2098:     return ($outcome,%results);
 2099: }
 2100: 
 2101: sub usersearch {
 2102:     my ($srch) = @_;
 2103:     my $dom = $srch->{'srchdomain'};
 2104:     my %results;
 2105:     my %libserv = &all_library();
 2106:     my $query = 'usersearch';
 2107:     foreach my $tryserver (keys(%libserv)) {
 2108:         if (&host_domain($tryserver) eq $dom) {
 2109:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2110:                 if ($srch->{'srchby'} eq 'email') {
 2111:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
 2112:                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
 2113:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2114:                              (($major == 2) && ($minor < 11)) ||
 2115:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
 2116:                 }
 2117:             }
 2118:             my $host=&hostname($tryserver);
 2119:             my $queryid=
 2120:                 &reply("querysend:".&escape($query).':'.
 2121:                        &escape($srch->{'srchby'}).':'.
 2122:                        &escape($srch->{'srchtype'}).':'.
 2123:                        &escape($srch->{'srchterm'}),$tryserver);
 2124:             if ($queryid !~/^\Q$host\E\_/) {
 2125:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2126:                 next;
 2127:             }
 2128:             my $reply = &get_query_reply($queryid);
 2129:             my $maxtries = 1;
 2130:             my $tries = 1;
 2131:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2132:                 $reply = &get_query_reply($queryid);
 2133:                 $tries ++;
 2134:             }
 2135:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2136:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2137:             } else {
 2138:                 my @matches;
 2139:                 if ($reply =~ /\n/) {
 2140:                     @matches = split(/\n/,$reply);
 2141:                 } else {
 2142:                     @matches = split(/\&/,$reply);
 2143:                 }
 2144:                 foreach my $match (@matches) {
 2145:                     my ($uname,$udom,%userhash);
 2146:                     foreach my $entry (split(/:/,$match)) {
 2147:                         my ($key,$value) =
 2148:                             map {&unescape($_);} split(/=/,$entry);
 2149:                         $userhash{$key} = $value;
 2150:                         if ($key eq 'username') {
 2151:                             $uname = $value;
 2152:                         } elsif ($key eq 'domain') {
 2153:                             $udom = $value;
 2154:                         }
 2155:                     }
 2156:                     $results{$uname.':'.$udom} = \%userhash;
 2157:                 }
 2158:             }
 2159:         }
 2160:     }
 2161:     return %results;
 2162: }
 2163: 
 2164: sub get_instuser {
 2165:     my ($udom,$uname,$id) = @_;
 2166:     my $homeserver = &domain($udom,'primary');
 2167:     my ($outcome,%results);
 2168:     if ($homeserver ne '') {
 2169:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2170:                            &escape($id).':'.&escape($udom),$homeserver);
 2171:         my $host=&hostname($homeserver);
 2172:         if ($queryid !~/^\Q$host\E\_/) {
 2173:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2174:             return;
 2175:         }
 2176:         my $response = &get_query_reply($queryid);
 2177:         my $maxtries = 5;
 2178:         my $tries = 1;
 2179:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2180:             $response = &get_query_reply($queryid);
 2181:             $tries ++;
 2182:         }
 2183:         if (!&error($response) && $response ne 'refused') {
 2184:             if ($response eq 'unavailable') {
 2185:                 $outcome = $response;
 2186:             } else {
 2187:                 $outcome = 'ok';
 2188:                 my @matches = split(/\n/,$response);
 2189:                 foreach my $match (@matches) {
 2190:                     my ($key,$value) = split(/=/,$match);
 2191:                     $results{&unescape($key)} = &thaw_unescape($value);
 2192:                 }
 2193:             }
 2194:         }
 2195:     }
 2196:     my %userinfo;
 2197:     if (ref($results{$uname}) eq 'HASH') {
 2198:         %userinfo = %{$results{$uname}};
 2199:     } 
 2200:     return ($outcome,%userinfo);
 2201: }
 2202: 
 2203: sub get_multiple_instusers {
 2204:     my ($udom,$users,$caller) = @_;
 2205:     my ($outcome,$results);
 2206:     if (ref($users) eq 'HASH') {
 2207:         my $count = keys(%{$users});
 2208:         my $requested = &freeze_escape($users);
 2209:         my $homeserver = &domain($udom,'primary');
 2210:         if ($homeserver ne '') {
 2211:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2212:             my $host=&hostname($homeserver);
 2213:             if ($queryid !~/^\Q$host\E\_/) {
 2214:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2215:                          ' for host: '.$homeserver.'in domain '.$udom);
 2216:                 return ($outcome,$results);
 2217:             }
 2218:             my $response = &get_query_reply($queryid);
 2219:             my $maxtries = 5;
 2220:             if ($count > 100) {
 2221:                 $maxtries = 1+int($count/20);
 2222:             }
 2223:             my $tries = 1;
 2224:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2225:                 $response = &get_query_reply($queryid);
 2226:                 $tries ++;
 2227:             }
 2228:             if ($response eq '') {
 2229:                 $results = {};
 2230:                 foreach my $key (keys(%{$users})) {
 2231:                     my ($uname,$id);
 2232:                     if ($caller eq 'id') {
 2233:                         $id = $key;
 2234:                     } else {
 2235:                         $uname = $key;
 2236:                     }
 2237:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2238:                     $outcome = $resp;
 2239:                     if ($resp eq 'ok') {
 2240:                         %{$results} = (%{$results}, %info);
 2241:                     } else {
 2242:                         last;
 2243:                     }
 2244:                 }
 2245:             } elsif(!&error($response) && ($response ne 'refused')) {
 2246:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2247:                     $outcome = $response;
 2248:                 } else {
 2249:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2250:                     if ($outcome eq 'ok') {
 2251:                         $results = &thaw_unescape($userdata);
 2252:                     }
 2253:                 }
 2254:             }
 2255:         }
 2256:     }
 2257:     return ($outcome,$results);
 2258: }
 2259: 
 2260: sub inst_rulecheck {
 2261:     my ($udom,$uname,$id,$item,$rules) = @_;
 2262:     my %returnhash;
 2263:     if ($udom ne '') {
 2264:         if (ref($rules) eq 'ARRAY') {
 2265:             @{$rules} = map {&escape($_);} (@{$rules});
 2266:             my $rulestr = join(':',@{$rules});
 2267:             my $homeserver=&domain($udom,'primary');
 2268:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2269:                 my $response;
 2270:                 if ($item eq 'username') {                
 2271:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2272:                                               ':'.&escape($uname).':'.$rulestr,
 2273:                                               $homeserver));
 2274:                 } elsif ($item eq 'id') {
 2275:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2276:                                               ':'.&escape($id).':'.$rulestr,
 2277:                                               $homeserver));
 2278:                 } elsif ($item eq 'selfcreate') {
 2279:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2280:                                                &escape($udom).':'.&escape($uname).
 2281:                                               ':'.$rulestr,$homeserver));
 2282:                 }
 2283:                 if ($response ne 'refused') {
 2284:                     my @pairs=split(/\&/,$response);
 2285:                     foreach my $item (@pairs) {
 2286:                         my ($key,$value)=split(/=/,$item,2);
 2287:                         $key = &unescape($key);
 2288:                         next if ($key =~ /^error: 2 /);
 2289:                         $returnhash{$key}=&thaw_unescape($value);
 2290:                     }
 2291:                 }
 2292:             }
 2293:         }
 2294:     }
 2295:     return %returnhash;
 2296: }
 2297: 
 2298: sub inst_userrules {
 2299:     my ($udom,$check) = @_;
 2300:     my (%ruleshash,@ruleorder);
 2301:     if ($udom ne '') {
 2302:         my $homeserver=&domain($udom,'primary');
 2303:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2304:             my $response;
 2305:             if ($check eq 'id') {
 2306:                 $response=&reply('instidrules:'.&escape($udom),
 2307:                                  $homeserver);
 2308:             } elsif ($check eq 'email') {
 2309:                 $response=&reply('instemailrules:'.&escape($udom),
 2310:                                  $homeserver);
 2311:             } else {
 2312:                 $response=&reply('instuserrules:'.&escape($udom),
 2313:                                  $homeserver);
 2314:             }
 2315:             if (($response ne 'refused') && ($response ne 'error') && 
 2316:                 ($response ne 'unknown_cmd') && 
 2317:                 ($response ne 'no_such_host')) {
 2318:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2319:                 my @pairs=split(/\&/,$hashitems);
 2320:                 foreach my $item (@pairs) {
 2321:                     my ($key,$value)=split(/=/,$item,2);
 2322:                     $key = &unescape($key);
 2323:                     next if ($key =~ /^error: 2 /);
 2324:                     $ruleshash{$key}=&thaw_unescape($value);
 2325:                 }
 2326:                 my @esc_order = split(/\&/,$orderitems);
 2327:                 foreach my $item (@esc_order) {
 2328:                     push(@ruleorder,&unescape($item));
 2329:                 }
 2330:             }
 2331:         }
 2332:     }
 2333:     return (\%ruleshash,\@ruleorder);
 2334: }
 2335: 
 2336: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2337: 
 2338: sub get_domain_defaults {
 2339:     my ($domain,$ignore_cache) = @_;
 2340:     return if (($domain eq '') || ($domain eq 'public'));
 2341:     my $cachetime = 60*60*24;
 2342:     unless ($ignore_cache) {
 2343:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2344:         if (defined($cached)) {
 2345:             if (ref($result) eq 'HASH') {
 2346:                 return %{$result};
 2347:             }
 2348:         }
 2349:     }
 2350:     my %domdefaults;
 2351:     my %domconfig =
 2352:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2353:                                   'requestcourses','inststatus',
 2354:                                   'coursedefaults','usersessions',
 2355:                                   'requestauthor','selfenrollment',
 2356:                                   'coursecategories','autoenroll',
 2357:                                   'helpsettings','wafproxy'],$domain);
 2358:     my @coursetypes = ('official','unofficial','community','textbook');
 2359:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2360:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2361:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2362:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2363:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2364:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2365:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2366:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2367:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2368:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2369:     } else {
 2370:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2371:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2372:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2373:     }
 2374:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2375:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2376:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2377:         } else {
 2378:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2379:         }
 2380:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2381:         foreach my $item (@usertools) {
 2382:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2383:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2384:             }
 2385:         }
 2386:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2387:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2388:         }
 2389:     }
 2390:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2391:         foreach my $item ('official','unofficial','community','textbook') {
 2392:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2393:         }
 2394:     }
 2395:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2396:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2397:     }
 2398:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2399:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2400:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2401:         }
 2402:     }
 2403:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2404:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2405:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
 2406:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2407:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2408:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2409:         }
 2410:         foreach my $type (@coursetypes) {
 2411:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2412:                 unless ($type eq 'community') {
 2413:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2414:                 }
 2415:             }
 2416:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2417:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2418:             }
 2419:             if ($domdefaults{'postsubmit'} eq 'on') {
 2420:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2421:                     $domdefaults{$type.'postsubtimeout'} =
 2422:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
 2423:                 }
 2424:             }
 2425:         }
 2426:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2427:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2428:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2429:                 if (@clonecodes) {
 2430:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2431:                 }
 2432:             }
 2433:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2434:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2435:         }
 2436:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2437:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2438:         }
 2439:     }
 2440:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2441:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2442:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2443:         }
 2444:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2445:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2446:         }
 2447:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2448:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2449:         }
 2450:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
 2451:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
 2452:         }
 2453:     }
 2454:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2455:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2456:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2457:                             'approval','limit');
 2458:             foreach my $type (@coursetypes) {
 2459:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2460:                     my @mgrdc = ();
 2461:                     foreach my $item (@settings) {
 2462:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2463:                             push(@mgrdc,$item);
 2464:                         }
 2465:                     }
 2466:                     if (@mgrdc) {
 2467:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2468:                     }
 2469:                 }
 2470:             }
 2471:         }
 2472:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2473:             foreach my $type (@coursetypes) {
 2474:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2475:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2476:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2477:                     }
 2478:                 }
 2479:             }
 2480:         }
 2481:     }
 2482:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2483:         $domdefaults{'catauth'} = 'std';
 2484:         $domdefaults{'catunauth'} = 'std';
 2485:         if ($domconfig{'coursecategories'}{'auth'}) {
 2486:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2487:         }
 2488:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2489:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2490:         }
 2491:     }
 2492:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2493:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2494:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
 2495:     }
 2496:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2497:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2498:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2499:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2500:         }
 2501:     }
 2502:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
 2503:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
 2504:             if ($domconfig{'wafproxy'}{$item}) {
 2505:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
 2506:             }
 2507:         }
 2508:     }
 2509:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2510:     return %domdefaults;
 2511: }
 2512: 
 2513: sub get_dom_cats {
 2514:     my ($dom) = @_;
 2515:     return unless (&domain($dom));
 2516:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 2517:     unless (defined($cached)) {
 2518:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 2519:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2520:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 2521:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 2522:             } else {
 2523:                 $cats = {};
 2524:             }
 2525:         } else {
 2526:             $cats = {};
 2527:         }
 2528:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
 2529:     }
 2530:     return $cats;
 2531: }
 2532: 
 2533: sub get_dom_instcats {
 2534:     my ($dom) = @_;
 2535:     return unless (&domain($dom));
 2536:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 2537:     unless (defined($cached)) {
 2538:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 2539:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 2540:         if ($totcodes > 0) {
 2541:             my $caller = 'global';
 2542:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 2543:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 2544:                 $instcats = {
 2545:                                 codes => \%codes,
 2546:                                 codetitles => \@codetitles,
 2547:                                 cat_titles => \%cat_titles,
 2548:                                 cat_order => \%cat_order,
 2549:                             };
 2550:                 &do_cache_new('instcats',$dom,$instcats,3600);
 2551:             }
 2552:         }
 2553:     }
 2554:     return $instcats;
 2555: }
 2556: 
 2557: sub retrieve_instcodes {
 2558:     my ($coursecodes,$dom) = @_;
 2559:     my $totcodes;
 2560:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 2561:     foreach my $course (keys(%courses)) {
 2562:         if (ref($courses{$course}) eq 'HASH') {
 2563:             if ($courses{$course}{'inst_code'} ne '') {
 2564:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 2565:                 $totcodes ++;
 2566:             }
 2567:         }
 2568:     }
 2569:     return $totcodes;
 2570: }
 2571: 
 2572: # --------------------------------------------- Get domain config for passwords
 2573: 
 2574: sub get_passwdconf {
 2575:     my ($dom) = @_;
 2576:     my (%passwdconf,$gotconf,$lookup);
 2577:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 2578:     if (defined($cached)) {
 2579:         if (ref($result) eq 'HASH') {
 2580:             %passwdconf = %{$result};
 2581:             $gotconf = 1;
 2582:         }
 2583:     }
 2584:     unless ($gotconf) {
 2585:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 2586:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 2587:             %passwdconf = %{$domconfig{'passwords'}};
 2588:         }
 2589:         my $cachetime = 24*60*60;
 2590:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 2591:     }
 2592:     return %passwdconf;
 2593: }
 2594: 
 2595: sub course_portal_url {
 2596:     my ($cnum,$cdom,$r) = @_;
 2597:     my $chome = &homeserver($cnum,$cdom);
 2598:     my $hostname = &hostname($chome);
 2599:     my $protocol = $protocol{$chome};
 2600:     $protocol = 'http' if ($protocol ne 'https');
 2601:     my %domdefaults = &get_domain_defaults($cdom);
 2602:     my $firsturl;
 2603:     if ($domdefaults{'portal_def'}) {
 2604:         $firsturl = $domdefaults{'portal_def'};
 2605:     } else {
 2606:         my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
 2607:         $hostname = $alias if ($alias ne '');
 2608:         $firsturl = $protocol.'://'.$hostname;
 2609:     }
 2610:     return $firsturl;
 2611: }
 2612: 
 2613: # --------------------------------------------------- Assign a key to a student
 2614: 
 2615: sub assign_access_key {
 2616: #
 2617: # a valid key looks like uname:udom#comments
 2618: # comments are being appended
 2619: #
 2620:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2621:     $kdom=
 2622:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2623:     $knum=
 2624:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2625:     $cdom=
 2626:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2627:     $cnum=
 2628:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2629:     $udom=$env{'user.name'} unless (defined($udom));
 2630:     $uname=$env{'user.domain'} unless (defined($uname));
 2631:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2632:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2633:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2634:                                                   # assigned to this person
 2635:                                                   # - this should not happen,
 2636:                                                   # unless something went wrong
 2637:                                                   # the first time around
 2638: # ready to assign
 2639:         $logentry=$1.'; '.$logentry;
 2640:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2641:                                                  $kdom,$knum) eq 'ok') {
 2642: # key now belongs to user
 2643: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2644:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2645:                 &appenv({'environment.'.$envkey => $ckey});
 2646:                 return 'ok';
 2647:             } else {
 2648:                 return 
 2649:   'error: Count not permanently assign key, will need to be re-entered later.';
 2650: 	    }
 2651:         } else {
 2652:             return 'error: Could not assign key, try again later.';
 2653:         }
 2654:     } elsif (!$existing{$ckey}) {
 2655: # the key does not exist
 2656: 	return 'error: The key does not exist';
 2657:     } else {
 2658: # the key is somebody else's
 2659: 	return 'error: The key is already in use';
 2660:     }
 2661: }
 2662: 
 2663: # ------------------------------------------ put an additional comment on a key
 2664: 
 2665: sub comment_access_key {
 2666: #
 2667: # a valid key looks like uname:udom#comments
 2668: # comments are being appended
 2669: #
 2670:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2671:     $cdom=
 2672:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2673:     $cnum=
 2674:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2675:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2676:     if ($existing{$ckey}) {
 2677:         $existing{$ckey}.='; '.$logentry;
 2678: # ready to assign
 2679:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2680:                                                  $cdom,$cnum) eq 'ok') {
 2681: 	    return 'ok';
 2682:         } else {
 2683: 	    return 'error: Count not store comment.';
 2684:         }
 2685:     } else {
 2686: # the key does not exist
 2687: 	return 'error: The key does not exist';
 2688:     }
 2689: }
 2690: 
 2691: # ------------------------------------------------------ Generate a set of keys
 2692: 
 2693: sub generate_access_keys {
 2694:     my ($number,$cdom,$cnum,$logentry)=@_;
 2695:     $cdom=
 2696:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2697:     $cnum=
 2698:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2699:     unless (&allowed('mky',$cdom)) { return 0; }
 2700:     unless (($cdom) && ($cnum)) { return 0; }
 2701:     if ($number>10000) { return 0; }
 2702:     sleep(2); # make sure don't get same seed twice
 2703:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2704:     my $total=0;
 2705:     for (my $i=1;$i<=$number;$i++) {
 2706:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2707:                   sprintf("%lx",int(100000*rand)).'-'.
 2708:                   sprintf("%lx",int(100000*rand));
 2709:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2710:        $newkey=~s/0/h/g; # and also 0 and O
 2711:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2712:        if ($existing{$newkey}) {
 2713:            $i--;
 2714:        } else {
 2715: 	  if (&put('accesskeys',
 2716:               { $newkey => '# generated '.localtime().
 2717:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2718:                            '; '.$logentry },
 2719: 		   $cdom,$cnum) eq 'ok') {
 2720:               $total++;
 2721: 	  }
 2722:        }
 2723:     }
 2724:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2725:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2726:     return $total;
 2727: }
 2728: 
 2729: # ------------------------------------------------------- Validate an accesskey
 2730: 
 2731: sub validate_access_key {
 2732:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2733:     $cdom=
 2734:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2735:     $cnum=
 2736:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2737:     $udom=$env{'user.domain'} unless (defined($udom));
 2738:     $uname=$env{'user.name'} unless (defined($uname));
 2739:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2740:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2741: }
 2742: 
 2743: # ------------------------------------- Find the section of student in a course
 2744: sub devalidate_getsection_cache {
 2745:     my ($udom,$unam,$courseid)=@_;
 2746:     my $hashid="$udom:$unam:$courseid";
 2747:     &devalidate_cache_new('getsection',$hashid);
 2748: }
 2749: 
 2750: sub courseid_to_courseurl {
 2751:     my ($courseid) = @_;
 2752:     #already url style courseid
 2753:     return $courseid if ($courseid =~ m{^/});
 2754: 
 2755:     if (exists($env{'course.'.$courseid.'.num'})) {
 2756: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2757: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2758: 	return "/$cdom/$cnum";
 2759:     }
 2760: 
 2761:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2762:     if (exists($courseinfo{'num'})) {
 2763: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2764:     }
 2765: 
 2766:     return undef;
 2767: }
 2768: 
 2769: sub getsection {
 2770:     my ($udom,$unam,$courseid)=@_;
 2771:     my $cachetime=1800;
 2772: 
 2773:     my $hashid="$udom:$unam:$courseid";
 2774:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2775:     if (defined($cached)) { return $result; }
 2776: 
 2777:     my %Pending; 
 2778:     my %Expired;
 2779:     #
 2780:     # Each role can either have not started yet (pending), be active, 
 2781:     #    or have expired.
 2782:     #
 2783:     # If there is an active role, we are done.
 2784:     #
 2785:     # If there is more than one role which has not started yet, 
 2786:     #     choose the one which will start sooner
 2787:     # If there is one role which has not started yet, return it.
 2788:     #
 2789:     # If there is more than one expired role, choose the one which ended last.
 2790:     # If there is a role which has expired, return it.
 2791:     #
 2792:     $courseid = &courseid_to_courseurl($courseid);
 2793:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2794:     foreach my $key (keys(%roleshash)) {
 2795:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2796:         my $section=$1;
 2797:         if ($key eq $courseid.'_st') { $section=''; }
 2798:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2799:         my $now=time;
 2800:         if (defined($end) && $end && ($now > $end)) {
 2801:             $Expired{$end}=$section;
 2802:             next;
 2803:         }
 2804:         if (defined($start) && $start && ($now < $start)) {
 2805:             $Pending{$start}=$section;
 2806:             next;
 2807:         }
 2808:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2809:     }
 2810:     #
 2811:     # Presumedly there will be few matching roles from the above
 2812:     # loop and the sorting time will be negligible.
 2813:     if (scalar(keys(%Pending))) {
 2814:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2815:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2816:     } 
 2817:     if (scalar(keys(%Expired))) {
 2818:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2819:         my $time = pop(@sorted);
 2820:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2821:     }
 2822:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2823: }
 2824: 
 2825: sub save_cache {
 2826:     &purge_remembered();
 2827:     #&Apache::loncommon::validate_page();
 2828:     undef(%env);
 2829:     undef($env_loaded);
 2830: }
 2831: 
 2832: my $to_remember=-1;
 2833: my %remembered;
 2834: my %accessed;
 2835: my $kicks=0;
 2836: my $hits=0;
 2837: sub make_key {
 2838:     my ($name,$id) = @_;
 2839:     if (length($id) > 65 
 2840: 	&& length(&escape($id)) > 200) {
 2841: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2842:     }
 2843:     return &escape($name.':'.$id);
 2844: }
 2845: 
 2846: sub devalidate_cache_new {
 2847:     my ($name,$id,$debug) = @_;
 2848:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2849:     my $remembered_id=$name.':'.$id;
 2850:     $id=&make_key($name,$id);
 2851:     $memcache->delete($id);
 2852:     delete($remembered{$remembered_id});
 2853:     delete($accessed{$remembered_id});
 2854: }
 2855: 
 2856: sub is_cached_new {
 2857:     my ($name,$id,$debug) = @_;
 2858:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
 2859:                                      # keys in %remembered hash, which persists for
 2860:                                      # duration of request (no restriction on key length).
 2861:     if (exists($remembered{$remembered_id})) {
 2862: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2863: 	$accessed{$remembered_id}=[&gettimeofday()];
 2864: 	$hits++;
 2865: 	return ($remembered{$remembered_id},1);
 2866:     }
 2867:     $id=&make_key($name,$id);
 2868:     my $value = $memcache->get($id);
 2869:     if (!(defined($value))) {
 2870: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2871: 	return (undef,undef);
 2872:     }
 2873:     if ($value eq '__undef__') {
 2874: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2875: 	$value=undef;
 2876:     }
 2877:     &make_room($remembered_id,$value,$debug);
 2878:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2879:     return ($value,1);
 2880: }
 2881: 
 2882: sub do_cache_new {
 2883:     my ($name,$id,$value,$time,$debug) = @_;
 2884:     my $remembered_id=$name.':'.$id;
 2885:     $id=&make_key($name,$id);
 2886:     my $setvalue=$value;
 2887:     if (!defined($setvalue)) {
 2888: 	$setvalue='__undef__';
 2889:     }
 2890:     if (!defined($time) ) {
 2891: 	$time=600;
 2892:     }
 2893:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2894:     my $result = $memcache->set($id,$setvalue,$time);
 2895:     if (! $result) {
 2896: 	&logthis("caching of id -> $id  failed");
 2897: 	$memcache->disconnect_all();
 2898:     }
 2899:     # need to make a copy of $value
 2900:     &make_room($remembered_id,$value,$debug);
 2901:     return $value;
 2902: }
 2903: 
 2904: sub make_room {
 2905:     my ($remembered_id,$value,$debug)=@_;
 2906: 
 2907:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 2908:                                     : $value;
 2909:     if ($to_remember<0) { return; }
 2910:     $accessed{$remembered_id}=[&gettimeofday()];
 2911:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2912:     my $to_kick;
 2913:     my $max_time=0;
 2914:     foreach my $other (keys(%accessed)) {
 2915: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2916: 	    $to_kick=$other;
 2917: 	    $max_time=&tv_interval($accessed{$other});
 2918: 	}
 2919:     }
 2920:     delete($remembered{$to_kick});
 2921:     delete($accessed{$to_kick});
 2922:     $kicks++;
 2923:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2924:     return;
 2925: }
 2926: 
 2927: sub purge_remembered {
 2928:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2929:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2930:     undef(%remembered);
 2931:     undef(%accessed);
 2932: }
 2933: # ------------------------------------- Read an entry from a user's environment
 2934: 
 2935: sub userenvironment {
 2936:     my ($udom,$unam,@what)=@_;
 2937:     my $items;
 2938:     foreach my $item (@what) {
 2939:         $items.=&escape($item).'&';
 2940:     }
 2941:     $items=~s/\&$//;
 2942:     my %returnhash=();
 2943:     my $uhome = &homeserver($unam,$udom);
 2944:     unless ($uhome eq 'no_host') {
 2945:         my @answer=split(/\&/, 
 2946:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2947:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2948:             return %returnhash;
 2949:         }
 2950:         my $i;
 2951:         for ($i=0;$i<=$#what;$i++) {
 2952: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2953:         }
 2954:     }
 2955:     return %returnhash;
 2956: }
 2957: 
 2958: # ---------------------------------------------------------- Get a studentphoto
 2959: sub studentphoto {
 2960:     my ($udom,$unam,$ext) = @_;
 2961:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2962:     if (defined($env{'request.course.id'})) {
 2963:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2964:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2965:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2966:             } else {
 2967:                 my ($result,$perm_reqd)=
 2968: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2969:                 if ($result eq 'ok') {
 2970:                     if (!($perm_reqd eq 'yes')) {
 2971:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2972:                     }
 2973:                 }
 2974:             }
 2975:         }
 2976:     } else {
 2977:         my ($result,$perm_reqd) = 
 2978: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2979:         if ($result eq 'ok') {
 2980:             if (!($perm_reqd eq 'yes')) {
 2981:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2982:             }
 2983:         }
 2984:     }
 2985:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2986: }
 2987: 
 2988: sub retrievestudentphoto {
 2989:     my ($udom,$unam,$ext,$type) = @_;
 2990:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2991:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2992:     if ($ret eq 'ok') {
 2993:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2994:         if ($type eq 'thumbnail') {
 2995:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2996:         }
 2997:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2998:         return $tokenurl;
 2999:     } else {
 3000:         if ($type eq 'thumbnail') {
 3001:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3002:         } else { 
 3003:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3004:         }
 3005:     }
 3006: }
 3007: 
 3008: # -------------------------------------------------------------------- New chat
 3009: 
 3010: sub chatsend {
 3011:     my ($newentry,$anon,$group)=@_;
 3012:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3013:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3014:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3015:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3016: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3017: 		   &escape($newentry)).':'.$group,$chome);
 3018: }
 3019: 
 3020: # ------------------------------------------ Find current version of a resource
 3021: 
 3022: sub getversion {
 3023:     my $fname=&clutter(shift);
 3024:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3025:     return &currentversion(&filelocation('',$fname));
 3026: }
 3027: 
 3028: sub currentversion {
 3029:     my $fname=shift;
 3030:     my $author=$fname;
 3031:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3032:     my ($udom,$uname)=split(/\//,$author);
 3033:     my $home=&homeserver($uname,$udom);
 3034:     if ($home eq 'no_host') { 
 3035:         return -1; 
 3036:     }
 3037:     my $answer=&reply("currentversion:$fname",$home);
 3038:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3039: 	return -1;
 3040:     }
 3041:     return $answer;
 3042: }
 3043: 
 3044: #
 3045: # Return special version number of resource if set by override, empty otherwise
 3046: #
 3047: sub usedversion {
 3048:     my $fname=shift;
 3049:     unless ($fname) { $fname=$env{'request.uri'}; }
 3050:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3051:     if ($urlversion) { return $urlversion; }
 3052:     return '';
 3053: }
 3054: 
 3055: # ----------------------------- Subscribe to a resource, return URL if possible
 3056: 
 3057: sub subscribe {
 3058:     my $fname=shift;
 3059:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3060:     $fname=~s/[\n\r]//g;
 3061:     my $author=$fname;
 3062:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3063:     my ($udom,$uname)=split(/\//,$author);
 3064:     my $home=homeserver($uname,$udom);
 3065:     if ($home eq 'no_host') {
 3066:         return 'not_found';
 3067:     }
 3068:     my $answer=reply("sub:$fname",$home);
 3069:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3070: 	$answer.=' by '.$home;
 3071:     }
 3072:     return $answer;
 3073: }
 3074:     
 3075: # -------------------------------------------------------------- Replicate file
 3076: 
 3077: sub repcopy {
 3078:     my $filename=shift;
 3079:     $filename=~s/\/+/\//g;
 3080:     my $londocroot = $perlvar{'lonDocRoot'};
 3081:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3082:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3083:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3084: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3085: 	return &repcopy_userfile($filename);
 3086:     }
 3087:     $filename=~s/[\n\r]//g;
 3088:     my $transname="$filename.in.transfer";
 3089: # FIXME: this should flock
 3090:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3091:     my $remoteurl=subscribe($filename);
 3092:     if ($remoteurl =~ /^con_lost by/) {
 3093: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3094:            return 'unavailable';
 3095:     } elsif ($remoteurl eq 'not_found') {
 3096: 	   #&logthis("Subscribe returned not_found: $filename");
 3097: 	   return 'not_found';
 3098:     } elsif ($remoteurl =~ /^rejected by/) {
 3099: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3100:            return 'forbidden';
 3101:     } elsif ($remoteurl eq 'directory') {
 3102:            return 'ok';
 3103:     } else {
 3104:         my $author=$filename;
 3105:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3106:         my ($udom,$uname)=split(/\//,$author);
 3107:         my $home=homeserver($uname,$udom);
 3108:         unless ($home eq $perlvar{'lonHostID'}) {
 3109:            my @parts=split(/\//,$filename);
 3110:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3111:            if ($path ne "$londocroot/res") {
 3112:                &logthis("Malconfiguration for replication: $filename");
 3113: 	       return 'bad_request';
 3114:            }
 3115:            my $count;
 3116:            for ($count=5;$count<$#parts;$count++) {
 3117:                $path.="/$parts[$count]";
 3118:                if ((-e $path)!=1) {
 3119: 		   mkdir($path,0777);
 3120:                }
 3121:            }
 3122:            my $ua=new LWP::UserAgent;
 3123:            my $request=new HTTP::Request('GET',"$remoteurl");
 3124:            my $response=$ua->request($request,$transname);
 3125:            if ($response->is_error()) {
 3126: 	       unlink($transname);
 3127:                my $message=$response->status_line;
 3128:                &logthis("<font color=\"blue\">WARNING:"
 3129:                        ." LWP get: $message: $filename</font>");
 3130:                return 'unavailable';
 3131:            } else {
 3132: 	       if ($remoteurl!~/\.meta$/) {
 3133:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3134:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 3135:                   if ($mresponse->is_error()) {
 3136: 		      unlink($filename.'.meta');
 3137:                       &logthis(
 3138:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3139:                   }
 3140: 	       }
 3141:                rename($transname,$filename);
 3142:                return 'ok';
 3143:            }
 3144:        }
 3145:     }
 3146: }
 3147: 
 3148: # ------------------------------------------------- Unsubscribe from a resource
 3149: 
 3150: sub unsubscribe {
 3151:     my ($fname) = @_;
 3152:     my $answer;
 3153:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3154:     $fname=~s/[\n\r]//g;
 3155:     my $author=$fname;
 3156:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3157:     my ($udom,$uname)=split(/\//,$author);
 3158:     my $home=homeserver($uname,$udom);
 3159:     if ($home eq 'no_host') {
 3160:         $answer = 'no_host';
 3161:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3162:         $answer = 'home';
 3163:     } else {
 3164:         $answer = reply("unsub:$fname",$home);
 3165:     }
 3166:     return $answer;
 3167: }
 3168: 
 3169: # ------------------------------------------------ Get server side include body
 3170: sub ssi_body {
 3171:     my ($filelink,%form)=@_;
 3172:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3173:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3174:     }
 3175:     my $output='';
 3176:     my $response;
 3177:     if ($filelink=~/^https?\:/) {
 3178:        ($output,$response)=&externalssi($filelink);
 3179:     } else {
 3180:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3181:        $filelink .= 'inhibitmenu=yes';
 3182:        ($output,$response)=&ssi($filelink,%form);
 3183:     }
 3184:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3185:     $output=~s/^.*?\<body[^\>]*\>//si;
 3186:     $output=~s/\<\/body\s*\>.*?$//si;
 3187:     if (wantarray) {
 3188:         return ($output, $response);
 3189:     } else {
 3190:         return $output;
 3191:     }
 3192: }
 3193: 
 3194: # --------------------------------------------------------- Server Side Include
 3195: 
 3196: sub absolute_url {
 3197:     my ($host_name,$unalias,$keep_proto) = @_;
 3198:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3199:     if ($host_name eq '') {
 3200: 	$host_name = $ENV{'SERVER_NAME'};
 3201:     }
 3202:     if ($unalias) {
 3203:         my $alias = &get_proxy_alias();
 3204:         if ($alias eq $host_name) {
 3205:             my $lonhost = $perlvar{'lonHostID'};
 3206:             my $hostname = &hostname($lonhost);
 3207:             my $lcproto;
 3208:             if (($keep_proto) || ($hostname eq '')) {
 3209:                 $lcproto = $protocol;
 3210:             } else {
 3211:                 $lcproto = $protocol{$lonhost};
 3212:                 $lcproto = 'http' if ($lcproto ne 'https');
 3213:                 $lcproto .= '://';
 3214:             }
 3215:             unless ($hostname eq '') {
 3216:                 return $lcproto.$hostname;
 3217:             }
 3218:         }
 3219:     } 
 3220:     return $protocol.$host_name;
 3221: }
 3222: 
 3223: #
 3224: #   Server side include.
 3225: # Parameters:
 3226: #  fn     Possibly encrypted resource name/id.
 3227: #  form   Hash that describes how the rendering should be done
 3228: #         and other things.
 3229: # Returns:
 3230: #   Scalar context: The content of the response.
 3231: #   Array context:  2 element list of the content and the full response object.
 3232: #     
 3233: sub ssi {
 3234: 
 3235:     my ($fn,%form)=@_;
 3236:     my ($host,$request,$response);
 3237:     $host = &absolute_url('',1);
 3238: 
 3239:     $form{'no_update_last_known'}=1;
 3240:     &Apache::lonenc::check_encrypt(\$fn);
 3241:     if (%form) {
 3242:       $request=new HTTP::Request('POST',$host.$fn);
 3243:       $request->content(join('&',map {
 3244:             my $name = escape($_);
 3245:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
 3246:             ? join("&$name=", map {escape($_) } @{$form{$_}})
 3247:             : &escape($form{$_}) );
 3248:         } keys(%form)));
 3249:     } else {
 3250:       $request=new HTTP::Request('GET',$host.$fn);
 3251:     }
 3252: 
 3253:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3254: 
 3255:     if (($env{'request.course.id'}) &&
 3256:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3257:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3258:         ($form{'grade_symb'} ne '') &&
 3259:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3260:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3261:         if (LWP::UserAgent->VERSION >= 5.834) {
 3262:             my $ua=new LWP::UserAgent;
 3263:             $ua->local_address('127.0.0.1');
 3264:             $response = $ua->request($request);
 3265:         } else {
 3266:             {
 3267:                 require LWP::Protocol::http;
 3268:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
 3269:                 my $ua=new LWP::UserAgent;
 3270:                 $response = $ua->request($request);
 3271:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
 3272:             }
 3273:         }
 3274:     } else {
 3275:         my $ua=new LWP::UserAgent;
 3276:         $response = $ua->request($request);
 3277:     }
 3278:     if (wantarray) {
 3279: 	return ($response->content, $response);
 3280:     } else {
 3281: 	return $response->content;
 3282:     }
 3283: }
 3284: 
 3285: sub externalssi {
 3286:     my ($url)=@_;
 3287:     my $ua=new LWP::UserAgent;
 3288:     my $request=new HTTP::Request('GET',$url);
 3289:     my $response=$ua->request($request);
 3290:     if (wantarray) {
 3291:         return ($response->content, $response);
 3292:     } else {
 3293:         return $response->content;
 3294:     }
 3295: }
 3296: 
 3297: # If the local copy of a replicated resource is outdated, trigger a
 3298: # connection from the homeserver to flush the delayed queue. If no update
 3299: # happens, remove local copies of outdated resource (and corresponding
 3300: # metadata file).
 3301: 
 3302: sub remove_stale_resfile {
 3303:     my ($url) = @_;
 3304:     my $removed;
 3305:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3306:         my $audom = $1;
 3307:         my $auname = $2;
 3308:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3309:             my $homeserver = &homeserver($auname,$audom);
 3310:             unless (($homeserver eq 'no_host') ||
 3311:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3312:                 my $fname = &filelocation('',$url);
 3313:                 if (-e $fname) {
 3314:                     my $hostname = &hostname($homeserver);
 3315:                     if ($hostname) {
 3316:                         my $protocol = $protocol{$homeserver};
 3317:                         $protocol = 'http' if ($protocol ne 'https');
 3318:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
 3319:                         my $ua=new LWP::UserAgent;
 3320:                         $ua->timeout(5);
 3321:                         my $request=new HTTP::Request('HEAD',$uri);
 3322:                         my $response=$ua->request($request);
 3323:                         if ($response->is_success()) {
 3324:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3325:                             my $locmodtime = (stat($fname))[9];
 3326:                             if ($locmodtime < $remmodtime) {
 3327:                                 my $stale;
 3328:                                 my $answer = &reply('pong',$homeserver);
 3329:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3330:                                     sleep(0.2);
 3331:                                     $locmodtime = (stat($fname))[9];
 3332:                                     if ($locmodtime < $remmodtime) {
 3333:                                         my $posstransfer = $fname.'.in.transfer';
 3334:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3335:                                             $removed = 1;
 3336:                                         } else {
 3337:                                             $stale = 1;
 3338:                                         }
 3339:                                     } else {
 3340:                                         $removed = 1;
 3341:                                     }
 3342:                                 } else {
 3343:                                     $stale = 1;
 3344:                                 }
 3345:                                 if ($stale) {
 3346:                                     if (unlink($fname)) {
 3347:                                         if ($uri!~/\.meta$/) {
 3348:                                             if (-e $fname.'.meta') {
 3349:                                                 unlink($fname.'.meta');
 3350:                                             }
 3351:                                         }
 3352:                                         my $unsubresult = &unsubscribe($fname);
 3353:                                         unless ($unsubresult eq 'ok') {
 3354:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3355:                                         }
 3356:                                         $removed = 1;
 3357:                                     }
 3358:                                 }
 3359:                             }
 3360:                         }
 3361:                     }
 3362:                 }
 3363:             }
 3364:         }
 3365:     }
 3366:     return $removed;
 3367: }
 3368: 
 3369: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3370: 
 3371: sub allowuploaded {
 3372:     my ($srcurl,$url)=@_;
 3373:     $url=&clutter(&declutter($url));
 3374:     my $dir=$url;
 3375:     $dir=~s/\/[^\/]+$//;
 3376:     my %httpref=();
 3377:     my $httpurl=&hreflocation('',$url);
 3378:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3379:     &Apache::lonnet::appenv(\%httpref);
 3380: }
 3381: 
 3382: #
 3383: # Determine if the current user should be able to edit a particular resource,
 3384: # when viewing in course context.
 3385: # (a) When viewing resource used to determine if "Edit" item is included in
 3386: #     Functions.
 3387: # (b) When displaying folder contents in course editor, used to determine if
 3388: #     "Edit" link will be displayed alongside resource.
 3389: #
 3390: #  input: six args -- filename (decluttered), course number, course domain,
 3391: #                   url, symb (if registered) and group (if this is a group
 3392: #                   item -- e.g., bulletin board, group page etc.).
 3393: #  output: array of five scalars --
 3394: #          $cfile -- url for file editing if editable on current server
 3395: #          $home -- homeserver of resource (i.e., for author if published,
 3396: #                                           or course if uploaded.).
 3397: #          $switchserver --  1 if server switch will be needed.
 3398: #          $forceedit -- 1 if icon/link should be to go to edit mode
 3399: #          $forceview -- 1 if icon/link should be to go to view mode
 3400: #
 3401: 
 3402: sub can_edit_resource {
 3403:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3404:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3405: #
 3406: # For aboutme pages user can only edit his/her own.
 3407: #
 3408:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3409:         my ($sdom,$sname) = ($1,$2);
 3410:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3411:             $home = $env{'user.home'};
 3412:             $cfile = $resurl;
 3413:             if ($env{'form.forceedit'}) {
 3414:                 $forceview = 1;
 3415:             } else {
 3416:                 $forceedit = 1;
 3417:             }
 3418:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3419:         } else {
 3420:             return;
 3421:         }
 3422:     }
 3423: 
 3424:     if ($env{'request.course.id'}) {
 3425:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3426:         if ($group ne '') {
 3427: # if this is a group homepage or group bulletin board, check group privs
 3428:             my $allowed = 0;
 3429:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3430:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3431:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3432:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3433:                     $allowed = 1;
 3434:                 }
 3435:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3436:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3437:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3438:                     $allowed = 1;
 3439:                 }
 3440:             }
 3441:             if ($allowed) {
 3442:                 $home=&homeserver($cnum,$cdom);
 3443:                 if ($env{'form.forceedit'}) {
 3444:                     $forceview = 1;
 3445:                 } else {
 3446:                     $forceedit = 1;
 3447:                 }
 3448:                 $cfile = $resurl;
 3449:             } else {
 3450:                 return;
 3451:             }
 3452:         } else {
 3453:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3454:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3455:                     return;
 3456:                 }
 3457:             } elsif (!$crsedit) {
 3458: #
 3459: # No edit allowed where CC has switched to student role.
 3460: #
 3461:                 return;
 3462:             }
 3463:         }
 3464:     }
 3465: 
 3466:     if ($file ne '') {
 3467:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3468:             if (&is_course_upload($file,$cnum,$cdom)) {
 3469:                 $uploaded = 1;
 3470:                 $incourse = 1;
 3471:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3472:                     $cfile = &hreflocation('',$file);
 3473:                     if ($env{'form.forceedit'}) {
 3474:                         $forceview = 1;
 3475:                     } else {
 3476:                         $forceedit = 1;
 3477:                     }
 3478:                 }
 3479:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3480:                 $incourse = 1;
 3481:                 if ($env{'form.forceedit'}) {
 3482:                     $forceview = 1;
 3483:                 } else {
 3484:                     $forceedit = 1;
 3485:                 }
 3486:                 $cfile = $resurl;
 3487:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
 3488:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3489:                     $incourse = 1;
 3490:                     if ($env{'form.forceedit'}) {
 3491:                         $forceview = 1;
 3492:                     } else {
 3493:                         $forceedit = 1;
 3494:                     }
 3495:                     $cfile = $resurl;
 3496:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3497:                     $incourse = 1;
 3498:                     $cfile = $resurl.'/smpedit';
 3499:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3500:                     $incourse = 1;
 3501:                     if ($env{'form.forceedit'}) {
 3502:                         $forceview = 1;
 3503:                     } else {
 3504:                         $forceedit = 1;
 3505:                     }
 3506:                     $cfile = $resurl;
 3507:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 3508:                     my ($map,$id,$res) = &decode_symb($symb);
 3509:                     if ($map =~ /\.page$/) {
 3510:                         $incourse = 1;
 3511:                         if ($env{'form.forceedit'}) {
 3512:                             $forceview = 1;
 3513:                             $cfile = $map;
 3514:                         } else {
 3515:                             $forceedit = 1;
 3516:                             $cfile =  '/adm/wrapper'.$resurl;
 3517:                         }
 3518:                     }
 3519:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3520:                     $incourse = 1;
 3521:                     if ($env{'form.forceedit'}) {
 3522:                         $forceview = 1;
 3523:                     } else {
 3524:                         $forceedit = 1;
 3525:                     }
 3526:                     $cfile = $resurl;
 3527:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3528:                     $incourse = 1;
 3529:                     if ($env{'form.forceedit'}) {
 3530:                         $forceview = 1;
 3531:                     } else {
 3532:                         $forceedit = 1;
 3533:                     }
 3534:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3535:                 }
 3536:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3537:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3538:                 if (&is_on_map($template)) {
 3539:                     $incourse = 1;
 3540:                     $forceview = 1;
 3541:                     $cfile = $template;
 3542:                 }
 3543:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3544:                 $incourse = 1;
 3545:                 if ($env{'form.forceedit'}) {
 3546:                     $forceview = 1;
 3547:                 } else {
 3548:                     $forceedit = 1;
 3549:                 }
 3550:                 $cfile = $resurl;
 3551:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3552:                 $incourse = 1;
 3553:                 if ($env{'form.forceedit'}) {
 3554:                     $forceview = 1;
 3555:                 } else {
 3556:                     $forceedit = 1;
 3557:                 }
 3558:                 $cfile = $resurl;
 3559:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3560:                 $incourse = 1;
 3561:                 $forceview = 1;
 3562:                 if ($symb) {
 3563:                     my ($map,$id,$res)=&decode_symb($symb);
 3564:                     $env{'request.symb'} = $symb;
 3565:                     $cfile = &clutter($res);
 3566:                 } else {
 3567:                     $cfile = $env{'form.suppurl'};
 3568:                     my $escfile = &unescape($cfile);
 3569:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3570:                         $cfile = '/adm/wrapper'.$escfile;
 3571:                     } else {
 3572:                         $escfile =~ s{^http://}{};
 3573:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3574:                     }
 3575:                 }
 3576:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3577:                 if ($env{'form.forceedit'}) {
 3578:                     $forceview = 1;
 3579:                 } else {
 3580:                     $forceedit = 1;
 3581:                 }
 3582:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3583:             }
 3584:         }
 3585:         if ($uploaded || $incourse) {
 3586:             $home=&homeserver($cnum,$cdom);
 3587:         } elsif ($file !~ m{/$}) {
 3588:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3589:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3590:             # Check that the user has permission to edit this resource
 3591:             my $setpriv = 1;
 3592:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3593:             if (defined($cfudom)) {
 3594:                 $home=&homeserver($cfuname,$cfudom);
 3595:                 $cfile=$file;
 3596:             }
 3597:         }
 3598:         if (($cfile ne '') && (!$incourse || $uploaded) &&
 3599:             (($home ne '') && ($home ne 'no_host'))) {
 3600:             my @ids=&current_machine_ids();
 3601:             unless (grep(/^\Q$home\E$/,@ids)) {
 3602:                 $switchserver=1;
 3603:             }
 3604:         }
 3605:     }
 3606:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3607: }
 3608: 
 3609: sub is_course_upload {
 3610:     my ($file,$cnum,$cdom) = @_;
 3611:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3612:     $uploadpath =~ s{^\/}{};
 3613:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3614:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3615:         return 1;
 3616:     }
 3617:     return;
 3618: }
 3619: 
 3620: sub in_course {
 3621:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3622:     if ($hideprivileged) {
 3623:         my $skipuser;
 3624:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3625:         my @possdoms = ($cdom);
 3626:         if ($coursehash{'checkforpriv'}) {
 3627:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 3628:         }
 3629:         if (&privileged($uname,$udom,\@possdoms)) {
 3630:             $skipuser = 1;
 3631:             if ($coursehash{'nothideprivileged'}) {
 3632:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3633:                     my $user;
 3634:                     if ($item =~ /:/) {
 3635:                         $user = $item;
 3636:                     } else {
 3637:                         $user = join(':',split(/[\@]/,$item));
 3638:                     }
 3639:                     if ($user eq $uname.':'.$udom) {
 3640:                         undef($skipuser);
 3641:                         last;
 3642:                     }
 3643:                 }
 3644:             }
 3645:             if ($skipuser) {
 3646:                 return 0;
 3647:             }
 3648:         }
 3649:     }
 3650:     $type ||= 'any';
 3651:     if (!defined($cdom) || !defined($cnum)) {
 3652:         my $cid  = $env{'request.course.id'};
 3653:         $cdom = $env{'course.'.$cid.'.domain'};
 3654:         $cnum = $env{'course.'.$cid.'.num'};
 3655:     }
 3656:     my $typesref;
 3657:     if (($type eq 'any') || ($type eq 'all')) {
 3658:         $typesref = ['active','previous','future'];
 3659:     } elsif ($type eq 'previous' || $type eq 'future') {
 3660:         $typesref = [$type];
 3661:     }
 3662:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3663:                               $typesref,undef,[$cdom]);
 3664:     my ($tmp) = keys(%roles);
 3665:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3666:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3667:     if (@course_roles > 0) {
 3668:         return 1;
 3669:     }
 3670:     return 0;
 3671: }
 3672: 
 3673: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3674: # input: action, courseID, current domain, intended
 3675: #        path to file, source of file, instruction to parse file for objects,
 3676: #        ref to hash for embedded objects,
 3677: #        ref to hash for codebase of java objects.
 3678: #        reference to scalar to accommodate mime type determined
 3679: #          from File::MMagic if $parser = parse.
 3680: #
 3681: # output: url to file (if action was uploaddoc), 
 3682: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3683: #
 3684: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3685: # course.
 3686: #
 3687: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3688: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3689: #          course's home server.
 3690: #
 3691: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3692: #          be copied from $source (current location) to 
 3693: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3694: #         and will then be copied to
 3695: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3696: #         course's home server.
 3697: #
 3698: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3699: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3700: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3701: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3702: #         in course's home server.
 3703: #
 3704: 
 3705: sub process_coursefile {
 3706:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3707:         $mimetype)=@_;
 3708:     my $fetchresult;
 3709:     my $home=&homeserver($docuname,$docudom);
 3710:     if ($action eq 'propagate') {
 3711:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3712: 			     $home);
 3713:     } else {
 3714:         my $fpath = '';
 3715:         my $fname = $file;
 3716:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3717:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3718:         my $filepath = &build_filepath($fpath);
 3719:         if ($action eq 'copy') {
 3720:             if ($source eq '') {
 3721:                 $fetchresult = 'no source file';
 3722:                 return $fetchresult;
 3723:             } else {
 3724:                 my $destination = $filepath.'/'.$fname;
 3725:                 rename($source,$destination);
 3726:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3727:                                  $home);
 3728:             }
 3729:         } elsif ($action eq 'uploaddoc') {
 3730:             open(my $fh,'>',$filepath.'/'.$fname);
 3731:             print $fh $env{'form.'.$source};
 3732:             close($fh);
 3733:             if ($parser eq 'parse') {
 3734:                 my $mm = new File::MMagic;
 3735:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3736:                 if ($type eq 'text/html') {
 3737:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3738:                     unless ($parse_result eq 'ok') {
 3739:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3740:                     }
 3741:                 }
 3742:                 if (ref($mimetype)) {
 3743:                     $$mimetype = $type;
 3744:                 } 
 3745:             }
 3746:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3747:                                  $home);
 3748:             if ($fetchresult eq 'ok') {
 3749:                 return '/uploaded/'.$fpath.'/'.$fname;
 3750:             } else {
 3751:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3752:                         ' to host '.$home.': '.$fetchresult);
 3753:                 return '/adm/notfound.html';
 3754:             }
 3755:         }
 3756:     }
 3757:     unless ( $fetchresult eq 'ok') {
 3758:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3759:              ' to host '.$home.': '.$fetchresult);
 3760:     }
 3761:     return $fetchresult;
 3762: }
 3763: 
 3764: sub build_filepath {
 3765:     my ($fpath) = @_;
 3766:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3767:     unless ($fpath eq '') {
 3768:         my @parts=split('/',$fpath);
 3769:         foreach my $part (@parts) {
 3770:             $filepath.= '/'.$part;
 3771:             if ((-e $filepath)!=1) {
 3772:                 mkdir($filepath,0777);
 3773:             }
 3774:         }
 3775:     }
 3776:     return $filepath;
 3777: }
 3778: 
 3779: sub store_edited_file {
 3780:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3781:     my $file = $primary_url;
 3782:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3783:     my $fpath = '';
 3784:     my $fname = $file;
 3785:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3786:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3787:     my $filepath = &build_filepath($fpath);
 3788:     open(my $fh,'>',$filepath.'/'.$fname);
 3789:     print $fh $content;
 3790:     close($fh);
 3791:     my $home=&homeserver($docuname,$docudom);
 3792:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3793: 			  $home);
 3794:     if ($$fetchresult eq 'ok') {
 3795:         return '/uploaded/'.$fpath.'/'.$fname;
 3796:     } else {
 3797:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3798: 		 ' to host '.$home.': '.$$fetchresult);
 3799:         return '/adm/notfound.html';
 3800:     }
 3801: }
 3802: 
 3803: sub clean_filename {
 3804:     my ($fname,$args)=@_;
 3805: # Replace Windows backslashes by forward slashes
 3806:     $fname=~s/\\/\//g;
 3807:     if (!$args->{'keep_path'}) {
 3808:         # Get rid of everything but the actual filename
 3809: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3810:     }
 3811: # Replace spaces by underscores
 3812:     $fname=~s/\s+/\_/g;
 3813: # Transliterate non-ascii text to ascii
 3814:     my $lang = &Apache::lonlocal::current_language();
 3815:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 3816: # Replace all other weird characters by nothing
 3817:     $fname=~s{[^/\w\.\-]}{}g;
 3818: # Replace all .\d. sequences with _\d. so they no longer look like version
 3819: # numbers
 3820:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3821: # Replace three or more adjacent underscores with one for consistency
 3822: # with loncfile::filename_check() so complete url can be extracted by
 3823: # lonnet::decode_symb()
 3824:     $fname=~s/_{3,}/_/g;
 3825:     return $fname;
 3826: }
 3827: 
 3828: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3829: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3830: # image with the same aspect ratio as the original, but with dimensions which do 
 3831: # not exceed $resizewidth and $resizeheight.
 3832:  
 3833: sub resizeImage {
 3834:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3835:     my $ima = Image::Magick->new;
 3836:     my $resized;
 3837:     if (-e $img_path) {
 3838:         $ima->Read($img_path);
 3839:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3840:             my $width = $ima->Get('width');
 3841:             my $height = $ima->Get('height');
 3842:             if ($width > $resizewidth) {
 3843: 	        my $factor = $width/$resizewidth;
 3844:                 my $newheight = $height/$factor;
 3845:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3846:                 $resized = 1;
 3847:             }
 3848:         }
 3849:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3850:             my $width = $ima->Get('width');
 3851:             my $height = $ima->Get('height');
 3852:             if ($height > $resizeheight) {
 3853:                 my $factor = $height/$resizeheight;
 3854:                 my $newwidth = $width/$factor;
 3855:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3856:                 $resized = 1;
 3857:             }
 3858:         }
 3859:         if ($resized) {
 3860:             $ima->Write($img_path);
 3861:         }
 3862:     }
 3863:     return;
 3864: }
 3865: 
 3866: # --------------- Take an uploaded file and put it into the userfiles directory
 3867: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3868: #                    the desired filename is in $env{"form.$formname.filename"}
 3869: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3870: #                                    canceloverwrite, scantron or ''. 
 3871: #                   if 'coursedoc': upload to the current course
 3872: #                   if 'existingfile': write file to tmp/overwrites directory 
 3873: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3874: #                   $context is passed as argument to &finishuserfileupload
 3875: #        $subdir - directory in userfile to store the file into
 3876: #        $parser - instruction to parse file for objects ($parser = parse) or
 3877: #                  if context is 'scantron', $parser is hashref of csv column mapping
 3878: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
 3879: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 3880: #        $allfiles - reference to hash for embedded objects
 3881: #        $codebase - reference to hash for codebase of java objects
 3882: #        $desuname - username for permanent storage of uploaded file
 3883: #        $dsetudom - domain for permanaent storage of uploaded file
 3884: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3885: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3886: #        $resizewidth - width (pixels) to which to resize uploaded image
 3887: #        $resizeheight - height (pixels) to which to resize uploaded image
 3888: #        $mimetype - reference to scalar to accommodate mime type determined
 3889: #                    from File::MMagic.
 3890: # 
 3891: # output: url of file in userspace, or error: <message> 
 3892: #             or /adm/notfound.html if failure to upload occurse
 3893: 
 3894: sub userfileupload {
 3895:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3896:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3897:     if (!defined($subdir)) { $subdir='unknown'; }
 3898:     my $fname=$env{'form.'.$formname.'.filename'};
 3899:     $fname=&clean_filename($fname);
 3900:     # See if there is anything left
 3901:     unless ($fname) { return 'error: no uploaded file'; }
 3902:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 3903:     if ($fname =~ /^\./) {
 3904:         my ($s,$usec) = &gettimeofday();
 3905:         while (length($usec) < 6) {
 3906:             $usec = '0'.$usec;
 3907:         }
 3908:         $fname = $s.'_'.substr($usec,0,3).$fname;
 3909:     }
 3910:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3911:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3912:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3913:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3914:         my $now = time;
 3915:         my $filepath;
 3916:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3917:              $filepath = 'tmp/helprequests/'.$now;
 3918:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3919:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3920:                          '_'.$env{'user.domain'}.'/pending';
 3921:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3922:             my ($docuname,$docudom);
 3923:             if ($destudom =~ /^$match_domain$/) {
 3924:                 $docudom = $destudom;
 3925:             } else {
 3926:                 $docudom = $env{'user.domain'};
 3927:             }
 3928:             if ($destuname =~ /^$match_username$/) { 
 3929:                 $docuname = $destuname;
 3930:             } else {
 3931:                 $docuname = $env{'user.name'};
 3932:             }
 3933:             if (exists($env{'form.group'})) {
 3934:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3935:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3936:             }
 3937:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3938:             if ($context eq 'canceloverwrite') {
 3939:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3940:                 if (-e  $tempfile) {
 3941:                     my @info = stat($tempfile);
 3942:                     if ($info[9] eq $env{'form.timestamp'}) {
 3943:                         unlink($tempfile);
 3944:                     }
 3945:                 }
 3946:                 return;
 3947:             }
 3948:         }
 3949:         # Create the directory if not present
 3950:         my @parts=split(/\//,$filepath);
 3951:         my $fullpath = $perlvar{'lonDaemons'};
 3952:         for (my $i=0;$i<@parts;$i++) {
 3953:             $fullpath .= '/'.$parts[$i];
 3954:             if ((-e $fullpath)!=1) {
 3955:                 mkdir($fullpath,0777);
 3956:             }
 3957:         }
 3958:         open(my $fh,'>',$fullpath.'/'.$fname);
 3959:         print $fh $env{'form.'.$formname};
 3960:         close($fh);
 3961:         if ($context eq 'existingfile') {
 3962:             my @info = stat($fullpath.'/'.$fname);
 3963:             return ($fullpath.'/'.$fname,$info[9]);
 3964:         } else {
 3965:             return $fullpath.'/'.$fname;
 3966:         }
 3967:     }
 3968:     if ($subdir eq 'scantron') {
 3969:         $fname = 'scantron_orig_'.$fname;
 3970:     } else {
 3971:         $fname="$subdir/$fname";
 3972:     }
 3973:     if ($context eq 'coursedoc') {
 3974: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3975: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3976:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3977:             return &finishuserfileupload($docuname,$docudom,
 3978: 					 $formname,$fname,$parser,$allfiles,
 3979: 					 $codebase,$thumbwidth,$thumbheight,
 3980:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3981:         } else {
 3982:             if ($env{'form.folder'}) {
 3983:                 $fname=$env{'form.folder'}.'/'.$fname;
 3984:             }
 3985:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3986: 				       $fname,$formname,$parser,
 3987: 				       $allfiles,$codebase,$mimetype);
 3988:         }
 3989:     } elsif (defined($destuname)) {
 3990:         my $docuname=$destuname;
 3991:         my $docudom=$destudom;
 3992: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3993: 				     $parser,$allfiles,$codebase,
 3994:                                      $thumbwidth,$thumbheight,
 3995:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3996:     } else {
 3997:         my $docuname=$env{'user.name'};
 3998:         my $docudom=$env{'user.domain'};
 3999:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4000:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4001:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4002:         }
 4003: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4004: 				     $parser,$allfiles,$codebase,
 4005:                                      $thumbwidth,$thumbheight,
 4006:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4007:     }
 4008: }
 4009: 
 4010: sub finishuserfileupload {
 4011:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4012:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4013:     my $path=$docudom.'/'.$docuname.'/';
 4014:     my $filepath=$perlvar{'lonDocRoot'};
 4015:   
 4016:     my ($fnamepath,$file,$fetchthumb);
 4017:     $file=$fname;
 4018:     if ($fname=~m|/|) {
 4019:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4020: 	$path.=$fnamepath.'/';
 4021:     }
 4022:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4023:     my $count;
 4024:     for ($count=4;$count<=$#parts;$count++) {
 4025:         $filepath.="/$parts[$count]";
 4026:         if ((-e $filepath)!=1) {
 4027: 	    mkdir($filepath,0777);
 4028:         }
 4029:     }
 4030: 
 4031: # Save the file
 4032:     {
 4033: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4034: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4035: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4036: 	    return '/adm/notfound.html';
 4037: 	}
 4038:         if ($context eq 'overwrite') {
 4039:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4040:             my $target = $filepath.'/'.$file;
 4041:             if (-e $source) {
 4042:                 my @info = stat($source);
 4043:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4044:                     unless (&File::Copy::move($source,$target)) {
 4045:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4046:                         return "Moving from $source failed";
 4047:                     }
 4048:                 } else {
 4049:                     return "Temporary file: $source had unexpected date/time for last modification";
 4050:                 }
 4051:             } else {
 4052:                 return "Temporary file: $source missing";
 4053:             }
 4054:         } elsif (!print FH ($env{'form.'.$formname})) {
 4055: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4056: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4057: 	    return '/adm/notfound.html';
 4058: 	}
 4059: 	close(FH);
 4060:         if ($resizewidth && $resizeheight) {
 4061:             my $mm = new File::MMagic;
 4062:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4063:             if ($mime_type =~ m{^image/}) {
 4064: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4065:             }  
 4066: 	}
 4067:     }
 4068:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4069:         if (ref($mimetype)) {
 4070:             if ($$mimetype eq '') {
 4071:                 my $mm = new File::MMagic;
 4072:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4073:                 $$mimetype = $type;
 4074:             }
 4075:         }
 4076:     }
 4077:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4078:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4079:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4080:                                                        $allfiles,$codebase);
 4081:             unless ($parse_result eq 'ok') {
 4082:                 &logthis('Failed to parse '.$filepath.$file.
 4083: 	   	         ' for embedded media: '.$parse_result); 
 4084:             }
 4085:         }
 4086:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4087:         my $format = $env{'form.scantron_format'};
 4088:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4089:     }
 4090:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4091:         my $input = $filepath.'/'.$file;
 4092:         my $output = $filepath.'/'.'tn-'.$file;
 4093:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4094:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4095:         system({$args[0]} @args);
 4096:         if (-e $filepath.'/'.'tn-'.$file) {
 4097:             $fetchthumb  = 1; 
 4098:         }
 4099:     }
 4100:  
 4101: # Notify homeserver to grep it
 4102: #
 4103:     my $docuhome=&homeserver($docuname,$docudom);	
 4104:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4105:     if ($fetchresult eq 'ok') {
 4106:         if ($fetchthumb) {
 4107:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4108:             if ($thumbresult ne 'ok') {
 4109:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4110:                          $docuhome.': '.$thumbresult);
 4111:             }
 4112:         }
 4113: #
 4114: # Return the URL to it
 4115:         return '/uploaded/'.$path.$file;
 4116:     } else {
 4117:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4118: 		 ': '.$fetchresult);
 4119:         return '/adm/notfound.html';
 4120:     }
 4121: }
 4122: 
 4123: sub extract_embedded_items {
 4124:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4125:     my @state = ();
 4126:     my (%lastids,%related,%shockwave,%flashvars);
 4127:     my %javafiles = (
 4128:                       codebase => '',
 4129:                       code => '',
 4130:                       archive => ''
 4131:                     );
 4132:     my %mediafiles = (
 4133:                       src => '',
 4134:                       movie => '',
 4135:                      );
 4136:     my $p;
 4137:     if ($content) {
 4138:         $p = HTML::LCParser->new($content);
 4139:     } else {
 4140:         $p = HTML::LCParser->new($fullpath);
 4141:     }
 4142:     while (my $t=$p->get_token()) {
 4143: 	if ($t->[0] eq 'S') {
 4144: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4145: 	    push(@state, $tagname);
 4146:             if (lc($tagname) eq 'allow') {
 4147:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4148:             }
 4149: 	    if (lc($tagname) eq 'img') {
 4150: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4151: 	    }
 4152: 	    if (lc($tagname) eq 'a') {
 4153:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4154: 		    &add_filetype($allfiles,$attr->{'href'},'href');
 4155:                 }
 4156: 	    }
 4157:             if (lc($tagname) eq 'script') {
 4158:                 my $src;
 4159:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4160:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4161:                 } else {
 4162:                     if ($attr->{'src'} ne '') {
 4163:                         $src = $attr->{'src'};
 4164:                         &add_filetype($allfiles,$src,'src');
 4165:                     }
 4166:                 }
 4167:                 my $text = $p->get_trimmed_text();
 4168:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4169:                     my @swfargs = split(/,/,$1);
 4170:                     foreach my $item (@swfargs) {
 4171:                         $item =~ s/["']//g;
 4172:                         $item =~ s/^\s+//;
 4173:                         $item =~ s/\s+$//;
 4174:                     }
 4175:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4176:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4177:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4178:                         } else {
 4179:                             $related{$swfargs[0]} = [$swfargs[2]];
 4180:                         }
 4181:                     }
 4182:                 }
 4183:             }
 4184:             if (lc($tagname) eq 'link') {
 4185:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4186:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4187:                 }
 4188:             }
 4189: 	    if (lc($tagname) eq 'object' ||
 4190: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4191: 		foreach my $item (keys(%javafiles)) {
 4192: 		    $javafiles{$item} = '';
 4193: 		}
 4194:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4195:                     $lastids{lc($tagname)} = $attr->{'id'};
 4196:                 }
 4197: 	    }
 4198: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4199: 		my $name = lc($attr->{'name'});
 4200: 		foreach my $item (keys(%javafiles)) {
 4201: 		    if ($name eq $item) {
 4202: 			$javafiles{$item} = $attr->{'value'};
 4203: 			last;
 4204: 		    }
 4205: 		}
 4206:                 my $pathfrom;
 4207: 		foreach my $item (keys(%mediafiles)) {
 4208: 		    if ($name eq $item) {
 4209:                         $pathfrom = $attr->{'value'};
 4210:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4211: 			&add_filetype($allfiles,$pathfrom,$name);
 4212: 			last;
 4213: 		    }
 4214: 		}
 4215:                 if ($name eq 'flashvars') {
 4216:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4217:                 }
 4218:                 if ($pathfrom ne '') {
 4219:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4220:                                          $pathfrom);
 4221:                 }
 4222: 	    }
 4223: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4224: 		foreach my $item (keys(%javafiles)) {
 4225: 		    if ($attr->{$item}) {
 4226: 			$javafiles{$item} = $attr->{$item};
 4227: 			last;
 4228: 		    }
 4229: 		}
 4230: 		foreach my $item (keys(%mediafiles)) {
 4231: 		    if ($attr->{$item}) {
 4232: 			&add_filetype($allfiles,$attr->{$item},$item);
 4233: 			last;
 4234: 		    }
 4235: 		}
 4236:                 if (lc($tagname) eq 'embed') {
 4237:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4238:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4239:                                              $attr->{'src'});
 4240:                     }
 4241:                 }
 4242: 	    }
 4243:             if (lc($tagname) eq 'iframe') {
 4244:                 my $src = $attr->{'src'} ;
 4245:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4246:                     &add_filetype($allfiles,$src,'src');
 4247:                 } elsif ($src =~ m{^/}) {
 4248:                     if ($env{'request.course.id'}) {
 4249:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4250:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4251:                         my $url = &hreflocation('',$fullpath);
 4252:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4253:                             my $relpath = $1;
 4254:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4255:                                 &add_filetype($allfiles,$1,'src');
 4256:                             }
 4257:                         }
 4258:                     }
 4259:                 }
 4260:             }
 4261:             if ($t->[4] =~ m{/>$}) {
 4262:                 pop(@state);
 4263:             }
 4264: 	} elsif ($t->[0] eq 'E') {
 4265: 	    my ($tagname) = ($t->[1]);
 4266: 	    if ($javafiles{'codebase'} ne '') {
 4267: 		$javafiles{'codebase'} .= '/';
 4268: 	    }  
 4269: 	    if (lc($tagname) eq 'applet' ||
 4270: 		lc($tagname) eq 'object' ||
 4271: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4272: 		) {
 4273: 		foreach my $item (keys(%javafiles)) {
 4274: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4275: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4276: 			&add_filetype($allfiles,$file,$item);
 4277: 		    }
 4278: 		}
 4279: 	    } 
 4280: 	    pop @state;
 4281: 	}
 4282:     }
 4283:     foreach my $id (sort(keys(%flashvars))) {
 4284:         if ($shockwave{$id} ne '') {
 4285:             my @pairs = split(/\&/,$flashvars{$id});
 4286:             foreach my $pair (@pairs) {
 4287:                 my ($key,$value) = split(/\=/,$pair);
 4288:                 if ($key eq 'thumb') {
 4289:                     &add_filetype($allfiles,$value,$key);
 4290:                 } elsif ($key eq 'content') {
 4291:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4292:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4293:                     if ($ext ne '') {
 4294:                         &add_filetype($allfiles,$path.$value,$ext);
 4295:                     }
 4296:                 }
 4297:             }
 4298:         }
 4299:     }
 4300:     return 'ok';
 4301: }
 4302: 
 4303: sub add_filetype {
 4304:     my ($allfiles,$file,$type)=@_;
 4305:     if (exists($allfiles->{$file})) {
 4306: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4307: 	    push(@{$allfiles->{$file}}, &escape($type));
 4308: 	}
 4309:     } else {
 4310: 	@{$allfiles->{$file}} = (&escape($type));
 4311:     }
 4312: }
 4313: 
 4314: sub embedded_dependency {
 4315:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4316:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4317:         if (($identifier ne '') &&
 4318:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4319:             ($pathfrom ne '')) {
 4320:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4321:             foreach my $dep (@{$related->{$identifier}}) {
 4322:                 &add_filetype($allfiles,$path.$dep,'object');
 4323:             }
 4324:         }
 4325:     }
 4326:     return;
 4327: }
 4328: 
 4329: sub bubblesheet_converter {
 4330:     my ($cdom,$fullpath,$config,$format) = @_;
 4331:     if ((&domain($cdom) ne '') &&
 4332:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4333:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4334:         my (%csvcols,%csvoptions);
 4335:         if (ref($config->{'fields'}) eq 'HASH') {
 4336:             %csvcols = %{$config->{'fields'}};
 4337:         }
 4338:         if (ref($config->{'options'}) eq 'HASH') {
 4339:             %csvoptions = %{$config->{'options'}};
 4340:         }
 4341:         my %csvbynum = reverse(%csvcols);
 4342:         my %scantronconf = &get_scantron_config($format,$cdom);
 4343:         if (keys(%scantronconf)) {
 4344:             my %bynum = (
 4345:                           $scantronconf{CODEstart} => 'CODEstart',
 4346:                           $scantronconf{IDstart}   => 'IDstart',
 4347:                           $scantronconf{PaperID}   => 'PaperID',
 4348:                           $scantronconf{FirstName} => 'FirstName',
 4349:                           $scantronconf{LastName}  => 'LastName',
 4350:                           $scantronconf{Qstart}    => 'Qstart',
 4351:                         );
 4352:             my @ordered;
 4353:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4354:                 push(@ordered,$bynum{$item});
 4355:             }
 4356:             my %mapstart = (
 4357:                               CODEstart => 'CODE',
 4358:                               IDstart   => 'ID',
 4359:                               PaperID   => 'PaperID',
 4360:                               FirstName => 'FirstName',
 4361:                               LastName  => 'LastName',
 4362:                               Qstart    => 'FirstQuestion',
 4363:                            );
 4364:             my %maplength = (
 4365:                               CODEstart => 'CODElength',
 4366:                               IDstart   => 'IDlength',
 4367:                               PaperID   => 'PaperIDlength',
 4368:                               FirstName => 'FirstNamelength',
 4369:                               LastName  => 'LastNamelength',
 4370:             );
 4371:             if (open(my $fh,'<',$fullpath)) {
 4372:                 my $output;
 4373:                 my %lettdig = &letter_to_digits();
 4374:                 my %diglett = reverse(%lettdig);
 4375:                 my $numletts = scalar(keys(%lettdig));
 4376:                 my $num = 0;
 4377:                 while (my $line=<$fh>) {
 4378:                     $num ++;
 4379:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4380:                     $line =~ s{[\r\n]+$}{};
 4381:                     my %found;
 4382:                     my @values = split(/,/,$line,-1);
 4383:                     my ($qstart,$record);
 4384:                     for (my $i=0; $i<@values; $i++) {
 4385:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4386:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4387:                             if ($values[$i] eq '') {
 4388:                                 $values[$i] = $scantronconf{'Qoff'};
 4389:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4390:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4391:                                     $values[$i] = $lettdig{uc($values[$i])};
 4392:                                 }
 4393:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4394:                                 if ($values[$i] =~ /^[0-9]$/) {
 4395:                                     $values[$i] = $diglett{$values[$i]};
 4396:                                 }
 4397:                             } else {
 4398:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4399:                                     my $digit;
 4400:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4401:                                         $digit = $lettdig{uc($values[$i])}-1;
 4402:                                         if ($values[$i] eq 'J') {
 4403:                                             $digit += $numletts;
 4404:                                         }
 4405:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4406:                                         $digit = $values[$i]-1;
 4407:                                         if ($values[$i] eq '0') {
 4408:                                             $digit += $numletts;
 4409:                                         }
 4410:                                     }
 4411:                                     my $qval='';
 4412:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4413:                                         if ($j == $digit) {
 4414:                                             $qval .= $scantronconf{'Qon'};
 4415:                                         } else {
 4416:                                             $qval .= $scantronconf{'Qoff'};
 4417:                                         }
 4418:                                     }
 4419:                                     $values[$i] = $qval;
 4420:                                 }
 4421:                             }
 4422:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4423:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4424:                             }
 4425:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4426:                             if ($numblank > 0) {
 4427:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4428:                             }
 4429:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4430:                                 $qstart = $i;
 4431:                                 $found{$csvbynum{$i}} = $values[$i];
 4432:                             } else {
 4433:                                 $found{'FirstQuestion'} .= $values[$i];
 4434:                             }
 4435:                         } elsif (exists($csvbynum{$i})) {
 4436:                             if ($csvoptions{'rem'}) {
 4437:                                 $values[$i] =~ s/^\s+//;
 4438:                             }
 4439:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4440:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4441:                                     $values[$i] = '0'.$values[$i];
 4442:                                 }
 4443:                             }
 4444:                             $found{$csvbynum{$i}} = $values[$i];
 4445:                         }
 4446:                     }
 4447:                     foreach my $item (@ordered) {
 4448:                         my $currlength = 1+length($record);
 4449:                         my $numspaces = $scantronconf{$item} - $currlength;
 4450:                         if ($numspaces > 0) {
 4451:                             $record .= (' ' x $numspaces);
 4452:                         }
 4453:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4454:                             unless ($item eq 'Qstart') {
 4455:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4456:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4457:                                 }
 4458:                             }
 4459:                             $record .= $found{$mapstart{$item}};
 4460:                         }
 4461:                     }
 4462:                     $output .= "$record\n";
 4463:                 }
 4464:                 close($fh);
 4465:                 if ($output) {
 4466:                     if (open(my $fh,'>',$fullpath)) {
 4467:                         print $fh $output;
 4468:                         close($fh);
 4469:                     }
 4470:                 }
 4471:             }
 4472:         }
 4473:         return;
 4474:     }
 4475: }
 4476: 
 4477: sub letter_to_digits {
 4478:     my %lettdig = (
 4479:                     A => 1,
 4480:                     B => 2,
 4481:                     C => 3,
 4482:                     D => 4,
 4483:                     E => 5,
 4484:                     F => 6,
 4485:                     G => 7,
 4486:                     H => 8,
 4487:                     I => 9,
 4488:                     J => 0,
 4489:                   );
 4490:     return %lettdig;
 4491: }
 4492: 
 4493: sub get_scantron_config {
 4494:     my ($which,$cdom) = @_;
 4495:     my @lines = &get_scantronformat_file($cdom);
 4496:     my %config;
 4497:     #FIXME probably should move to XML it has already gotten a bit much now
 4498:     foreach my $line (@lines) {
 4499:         my ($name,$descrip)=split(/:/,$line);
 4500:         if ($name ne $which ) { next; }
 4501:         chomp($line);
 4502:         my @config=split(/:/,$line);
 4503:         $config{'name'}=$config[0];
 4504:         $config{'description'}=$config[1];
 4505:         $config{'CODElocation'}=$config[2];
 4506:         $config{'CODEstart'}=$config[3];
 4507:         $config{'CODElength'}=$config[4];
 4508:         $config{'IDstart'}=$config[5];
 4509:         $config{'IDlength'}=$config[6];
 4510:         $config{'Qstart'}=$config[7];
 4511:         $config{'Qlength'}=$config[8];
 4512:         $config{'Qoff'}=$config[9];
 4513:         $config{'Qon'}=$config[10];
 4514:         $config{'PaperID'}=$config[11];
 4515:         $config{'PaperIDlength'}=$config[12];
 4516:         $config{'FirstName'}=$config[13];
 4517:         $config{'FirstNamelength'}=$config[14];
 4518:         $config{'LastName'}=$config[15];
 4519:         $config{'LastNamelength'}=$config[16];
 4520:         $config{'BubblesPerRow'}=$config[17];
 4521:         last;
 4522:     }
 4523:     return %config;
 4524: }
 4525: 
 4526: sub get_scantronformat_file {
 4527:     my ($cdom) = @_;
 4528:     if ($cdom eq '') {
 4529:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4530:     }
 4531:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4532:     my $gottab = 0;
 4533:     my @lines;
 4534:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4535:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4536:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4537:             if ($formatfile ne '-1') {
 4538:                 @lines = split("\n",$formatfile,-1);
 4539:                 $gottab = 1;
 4540:             }
 4541:         }
 4542:     }
 4543:     if (!$gottab) {
 4544:         my $confname = $cdom.'-domainconfig';
 4545:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4546:         my $formatfile = &getfile($default);
 4547:         if ($formatfile ne '-1') {
 4548:             @lines = split("\n",$formatfile,-1);
 4549:             $gottab = 1;
 4550:         }
 4551:     }
 4552:     if (!$gottab) {
 4553:         my @domains = &current_machine_domains();
 4554:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4555:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4556:                 @lines = <$fh>;
 4557:                 close($fh);
 4558:             }
 4559:         } else {
 4560:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4561:                 @lines = <$fh>;
 4562:                 close($fh);
 4563:             }
 4564:         }
 4565:     }
 4566:     return @lines;
 4567: }
 4568: 
 4569: sub removeuploadedurl {
 4570:     my ($url)=@_;	
 4571:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4572:     return &removeuserfile($uname,$udom,$fname);
 4573: }
 4574: 
 4575: sub removeuserfile {
 4576:     my ($docuname,$docudom,$fname)=@_;
 4577:     my $home=&homeserver($docuname,$docudom);    
 4578:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4579:     if ($result eq 'ok') {	
 4580:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4581:             my $metafile = $fname.'.meta';
 4582:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4583: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4584:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4585:             my $sqlresult = 
 4586:                 &update_portfolio_table($docuname,$docudom,$file,
 4587:                                         'portfolio_metadata',$group,
 4588:                                         'delete');
 4589:         }
 4590:     }
 4591:     return $result;
 4592: }
 4593: 
 4594: sub mkdiruserfile {
 4595:     my ($docuname,$docudom,$dir)=@_;
 4596:     my $home=&homeserver($docuname,$docudom);
 4597:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4598: }
 4599: 
 4600: sub renameuserfile {
 4601:     my ($docuname,$docudom,$old,$new)=@_;
 4602:     my $home=&homeserver($docuname,$docudom);
 4603:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4604:                         &escape("$old").':'.&escape("$new"),$home);
 4605:     if ($result eq 'ok') {
 4606:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4607:             my $oldmeta = $old.'.meta';
 4608:             my $newmeta = $new.'.meta';
 4609:             my $metaresult = 
 4610:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4611: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4612:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4613:             my $sqlresult = 
 4614:                 &update_portfolio_table($docuname,$docudom,$file,
 4615:                                         'portfolio_metadata',$group,
 4616:                                         'delete');
 4617:         }
 4618:     }
 4619:     return $result;
 4620: }
 4621: 
 4622: # ------------------------------------------------------------------------- Log
 4623: 
 4624: sub log {
 4625:     my ($dom,$nam,$hom,$what)=@_;
 4626:     return critical("log:$dom:$nam:$what",$hom);
 4627: }
 4628: 
 4629: # ------------------------------------------------------------------ Course Log
 4630: #
 4631: # This routine flushes several buffers of non-mission-critical nature
 4632: #
 4633: 
 4634: sub flushcourselogs {
 4635:     &logthis('Flushing log buffers');
 4636: #
 4637: # course logs
 4638: # This is a log of all transactions in a course, which can be used
 4639: # for data mining purposes
 4640: #
 4641: # It also collects the courseid database, which lists last transaction
 4642: # times and course titles for all courseids
 4643: #
 4644:     my %courseidbuffer=();
 4645:     foreach my $crsid (keys(%courselogs)) {
 4646:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4647: 		          &escape($courselogs{$crsid}),
 4648: 		          $coursehombuf{$crsid}) eq 'ok') {
 4649: 	    delete $courselogs{$crsid};
 4650:         } else {
 4651:             &logthis('Failed to flush log buffer for '.$crsid);
 4652:             if (length($courselogs{$crsid})>40000) {
 4653:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4654:                         " exceeded maximum size, deleting.</font>");
 4655:                delete $courselogs{$crsid};
 4656:             }
 4657:         }
 4658:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4659:             'description' => $coursedescrbuf{$crsid},
 4660:             'inst_code'    => $courseinstcodebuf{$crsid},
 4661:             'type'        => $coursetypebuf{$crsid},
 4662:             'owner'       => $courseownerbuf{$crsid},
 4663:         };
 4664:     }
 4665: #
 4666: # Write course id database (reverse lookup) to homeserver of courses 
 4667: # Is used in pickcourse
 4668: #
 4669:     foreach my $crs_home (keys(%courseidbuffer)) {
 4670:         my $response = &courseidput(&host_domain($crs_home),
 4671:                                     $courseidbuffer{$crs_home},
 4672:                                     $crs_home,'timeonly');
 4673:     }
 4674: #
 4675: # File accesses
 4676: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4677: #
 4678:     foreach my $entry (keys(%accesshash)) {
 4679:         if ($entry =~ /___count$/) {
 4680:             my ($dom,$name);
 4681:             ($dom,$name,undef)=
 4682: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4683:             if (! defined($dom) || $dom eq '' || 
 4684:                 ! defined($name) || $name eq '') {
 4685:                 my $cid = $env{'request.course.id'};
 4686: #
 4687: # FIXME 11/29/2021
 4688: # Typo in rev. 1.458 (2003/12/09)??
 4689: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
 4690: #
 4691: # While these ramain as  $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
 4692: # $dom and $name will always be null, so the &inc() call will default to storing this data
 4693: # in a nohist_accesscount.db file for the user rather than the course.
 4694: #
 4695: # That said there is a lot of noise in the data being stored.
 4696: # So counts for prtspool/  and adm/ etc. are recorded.
 4697: #
 4698: # A review of which items ending '___count' are written to %accesshash should likely be
 4699: # made before deciding whether to set these to 'course.' instead of 'request.'
 4700: #
 4701: # Under the current scheme each user receives a nohist_accesscount.db file listing
 4702: # accesses for things which are not published resources, regardless of course, and
 4703: # there is not a nohist_accesscount.db file in a course, which might log accesses from
 4704: # anyone in the course for things which are not published resources.
 4705: #
 4706: # For an author, nohist_accesscount.db ends up having records for other items
 4707: # mixed up with the legitimate access counts for the author's published resources.
 4708: #
 4709:                 $dom  = $env{'request.'.$cid.'.domain'};
 4710:                 $name = $env{'request.'.$cid.'.num'};
 4711:             }
 4712:             my $value = $accesshash{$entry};
 4713:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4714:             my %temphash=($url => $value);
 4715:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4716:             if ($result eq 'ok') {
 4717:                 delete $accesshash{$entry};
 4718:             }
 4719:         } else {
 4720:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4721:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4722:             my %temphash=($entry => $accesshash{$entry});
 4723:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4724:                 delete $accesshash{$entry};
 4725:             }
 4726:         }
 4727:     }
 4728: #
 4729: # Roles
 4730: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4731: #
 4732:     foreach my $entry (keys(%userrolehash)) {
 4733:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4734: 	    split(/\:/,$entry);
 4735:         if (&Apache::lonnet::put('nohist_userroles',
 4736:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4737:                 $rudom,$runame) eq 'ok') {
 4738: 	    delete $userrolehash{$entry};
 4739:         }
 4740:     }
 4741: #
 4742: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4743: #
 4744:     my %domrolebuffer = ();
 4745:     foreach my $entry (keys(%domainrolehash)) {
 4746:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4747:         if ($domrolebuffer{$rudom}) {
 4748:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4749:                       '='.&escape($domainrolehash{$entry});
 4750:         } else {
 4751:             $domrolebuffer{$rudom}.=&escape($entry).
 4752:                       '='.&escape($domainrolehash{$entry});
 4753:         }
 4754:         delete $domainrolehash{$entry};
 4755:     }
 4756:     foreach my $dom (keys(%domrolebuffer)) {
 4757:         my %servers;
 4758:         if (defined(&domain($dom,'primary'))) {
 4759:             my $primary=&domain($dom,'primary');
 4760:             my $hostname=&hostname($primary);
 4761:             $servers{$primary} = $hostname;
 4762:         } else {
 4763:             %servers = &get_servers($dom,'library');
 4764:         }
 4765: 	foreach my $tryserver (keys(%servers)) {
 4766: 	    if (&reply('domroleput:'.$dom.':'.
 4767: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4768: 	        last;
 4769: 	    } else {
 4770: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4771: 	    }
 4772:         }
 4773:     }
 4774:     $dumpcount++;
 4775: }
 4776: 
 4777: sub courselog {
 4778:     my $what=shift;
 4779:     $what=time.':'.$what;
 4780:     unless ($env{'request.course.id'}) { return ''; }
 4781:     $coursedombuf{$env{'request.course.id'}}=
 4782:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4783:     $coursenumbuf{$env{'request.course.id'}}=
 4784:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4785:     $coursehombuf{$env{'request.course.id'}}=
 4786:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4787:     $coursedescrbuf{$env{'request.course.id'}}=
 4788:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4789:     $courseinstcodebuf{$env{'request.course.id'}}=
 4790:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4791:     $courseownerbuf{$env{'request.course.id'}}=
 4792:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4793:     $coursetypebuf{$env{'request.course.id'}}=
 4794:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4795:     if (defined $courselogs{$env{'request.course.id'}}) {
 4796: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4797:     } else {
 4798: 	$courselogs{$env{'request.course.id'}}.=$what;
 4799:     }
 4800:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4801: 	&flushcourselogs();
 4802:     }
 4803: }
 4804: 
 4805: sub courseacclog {
 4806:     my $fnsymb=shift;
 4807:     unless ($env{'request.course.id'}) { return ''; }
 4808:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4809:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4810:         $what.=':POST';
 4811:         # FIXME: Probably ought to escape things....
 4812: 	foreach my $key (keys(%env)) {
 4813:             if ($key=~/^form\.(.*)/) {
 4814:                 my $formitem = $1;
 4815:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4816:                     $what.=':'.$formitem.'='.$env{$key};
 4817:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4818:                     if ($formitem eq 'proctorpassword') {
 4819:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 4820:                     } else {
 4821:                         $what.=':'.$formitem.'='.$env{$key};
 4822:                     }
 4823:                 }
 4824:             }
 4825:         }
 4826:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4827:         # FIXME: We should not be depending on a form parameter that someone
 4828:         # editing lonsearchcat.pm might change in the future.
 4829:         if ($env{'form.phase'} eq 'course_search') {
 4830:             $what.= ':POST';
 4831:             # FIXME: Probably ought to escape things....
 4832:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4833:                                  'crsdiscuss') {
 4834:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4835:             }
 4836:         }
 4837:     }
 4838:     &courselog($what);
 4839: }
 4840: 
 4841: sub countacc {
 4842:     my $url=&declutter(shift);
 4843:     return if (! defined($url) || $url eq '');
 4844:     unless ($env{'request.course.id'}) { return ''; }
 4845: #
 4846: # Mark that this url was used in this course
 4847: #
 4848:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4849: #
 4850: # Increase the access count for this resource in this child process
 4851: #
 4852:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4853:     $accesshash{$key}++;
 4854: }
 4855: 
 4856: sub linklog {
 4857:     my ($from,$to)=@_;
 4858:     $from=&declutter($from);
 4859:     $to=&declutter($to);
 4860:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4861:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4862: }
 4863: 
 4864: sub statslog {
 4865:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4866:     if ($users<2) { return; }
 4867:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4868:             'course'       => $env{'request.course.id'},
 4869:             'sections'     => '"all"',
 4870:             'num_students' => $users,
 4871:             'part'         => $part,
 4872:             'symb'         => $symb,
 4873:             'mean_tries'   => $av_attempts,
 4874:             'deg_of_diff'  => $degdiff});
 4875:     foreach my $key (keys(%dynstore)) {
 4876:         $accesshash{$key}=$dynstore{$key};
 4877:     }
 4878: }
 4879:   
 4880: sub userrolelog {
 4881:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4882:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4883:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4884:        $userrolehash
 4885:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4886:                     =$tend.':'.$tstart;
 4887:     }
 4888:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4889:        $userrolehash
 4890:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4891:                     =$tend.':'.$tstart;
 4892:     }
 4893:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4894:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4895:        $domainrolehash
 4896:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4897:                     = $tend.':'.$tstart;
 4898:     }
 4899: }
 4900: 
 4901: sub courserolelog {
 4902:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4903:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4904:         my $cdom = $1;
 4905:         my $cnum = $2;
 4906:         my $sec = $3;
 4907:         my $namespace = 'rolelog';
 4908:         my %storehash = (
 4909:                            role    => $trole,
 4910:                            start   => $tstart,
 4911:                            end     => $tend,
 4912:                            selfenroll => $selfenroll,
 4913:                            context    => $context,
 4914:                         );
 4915:         if ($trole eq 'gr') {
 4916:             $namespace = 'groupslog';
 4917:             $storehash{'group'} = $sec;
 4918:         } else {
 4919:             $storehash{'section'} = $sec;
 4920:         }
 4921:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4922:                    $domain,$cnum,$cdom);
 4923:         if (($trole ne 'st') || ($sec ne '')) {
 4924:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4925:         }
 4926:     }
 4927:     return;
 4928: }
 4929: 
 4930: sub domainrolelog {
 4931:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4932:     if ($area =~ m{^/($match_domain)/$}) {
 4933:         my $cdom = $1;
 4934:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4935:         my $namespace = 'rolelog';
 4936:         my %storehash = (
 4937:                            role    => $trole,
 4938:                            start   => $tstart,
 4939:                            end     => $tend,
 4940:                            context => $context,
 4941:                         );
 4942:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4943:                    $domain,$domconfiguser,$cdom);
 4944:     }
 4945:     return;
 4946: 
 4947: }
 4948: 
 4949: sub coauthorrolelog {
 4950:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4951:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4952:         my $audom = $1;
 4953:         my $auname = $2;
 4954:         my $namespace = 'rolelog';
 4955:         my %storehash = (
 4956:                            role    => $trole,
 4957:                            start   => $tstart,
 4958:                            end     => $tend,
 4959:                            context => $context,
 4960:                         );
 4961:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4962:                    $domain,$auname,$audom);
 4963:     }
 4964:     return;
 4965: }
 4966: 
 4967: sub get_course_adv_roles {
 4968:     my ($cid,$codes) = @_;
 4969:     $cid=$env{'request.course.id'} unless (defined($cid));
 4970:     my %coursehash=&coursedescription($cid);
 4971:     my $crstype = &Apache::loncommon::course_type($cid);
 4972:     my %nothide=();
 4973:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4974:         if ($user !~ /:/) {
 4975: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4976:         } else {
 4977:             $nothide{$user}=1;
 4978:         }
 4979:     }
 4980:     my @possdoms = ($coursehash{'domain'});
 4981:     if ($coursehash{'checkforpriv'}) {
 4982:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4983:     }
 4984:     my %returnhash=();
 4985:     my %dumphash=
 4986:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4987:     my $now=time;
 4988:     my %privileged;
 4989:     foreach my $entry (keys(%dumphash)) {
 4990: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4991:         if (($tstart) && ($tstart<0)) { next; }
 4992:         if (($tend) && ($tend<$now)) { next; }
 4993:         if (($tstart) && ($now<$tstart)) { next; }
 4994:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4995: 	if ($username eq '' || $domain eq '') { next; }
 4996:         if ((&privileged($username,$domain,\@possdoms)) &&
 4997:             (!$nothide{$username.':'.$domain})) { next; }
 4998: 	if ($role eq 'cr') { next; }
 4999:         if ($codes) {
 5000:             if ($section) { $role .= ':'.$section; }
 5001:             if ($returnhash{$role}) {
 5002:                 $returnhash{$role}.=','.$username.':'.$domain;
 5003:             } else {
 5004:                 $returnhash{$role}=$username.':'.$domain;
 5005:             }
 5006:         } else {
 5007:             my $key=&plaintext($role,$crstype);
 5008:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5009:             if ($returnhash{$key}) {
 5010: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5011:             } else {
 5012:                 $returnhash{$key}=$username.':'.$domain;
 5013:             }
 5014:         }
 5015:     }
 5016:     return %returnhash;
 5017: }
 5018: 
 5019: sub get_my_roles {
 5020:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5021:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5022:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5023:     my (%dumphash,%nothide);
 5024:     if ($context eq 'userroles') {
 5025:         %dumphash = &dump('roles',$udom,$uname);
 5026:     } else {
 5027:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5028:         if ($hidepriv) {
 5029:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5030:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5031:                 if ($user !~ /:/) {
 5032:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5033:                 } else {
 5034:                     $nothide{$user} = 1;
 5035:                 }
 5036:             }
 5037:         }
 5038:     }
 5039:     my %returnhash=();
 5040:     my $now=time;
 5041:     my %privileged;
 5042:     foreach my $entry (keys(%dumphash)) {
 5043:         my ($role,$tend,$tstart);
 5044:         if ($context eq 'userroles') {
 5045:             next if ($entry =~ /^rolesdef/);
 5046: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5047:         } else {
 5048:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5049:         }
 5050:         if (($tstart) && ($tstart<0)) { next; }
 5051:         my $status = 'active';
 5052:         if (($tend) && ($tend<=$now)) {
 5053:             $status = 'previous';
 5054:         } 
 5055:         if (($tstart) && ($now<$tstart)) {
 5056:             $status = 'future';
 5057:         }
 5058:         if (ref($types) eq 'ARRAY') {
 5059:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5060:                 next;
 5061:             } 
 5062:         } else {
 5063:             if ($status ne 'active') {
 5064:                 next;
 5065:             }
 5066:         }
 5067:         my ($rolecode,$username,$domain,$section,$area);
 5068:         if ($context eq 'userroles') {
 5069:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5070:             (undef,$domain,$username,$section) = split(/\//,$area);
 5071:         } else {
 5072:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5073:         }
 5074:         if (ref($roledoms) eq 'ARRAY') {
 5075:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5076:                 next;
 5077:             }
 5078:         }
 5079:         if (ref($roles) eq 'ARRAY') {
 5080:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5081:                 if ($role =~ /^cr\//) {
 5082:                     if (!grep(/^cr$/,@{$roles})) {
 5083:                         next;
 5084:                     }
 5085:                 } elsif ($role =~ /^gr\//) {
 5086:                     if (!grep(/^gr$/,@{$roles})) {
 5087:                         next;
 5088:                     }
 5089:                 } else {
 5090:                     next;
 5091:                 }
 5092:             }
 5093:         }
 5094:         if ($hidepriv) {
 5095:             my @privroles = ('dc','su');
 5096:             if ($context eq 'userroles') {
 5097:                 next if (grep(/^\Q$role\E$/,@privroles));
 5098:             } else {
 5099:                 my $possdoms = [$domain];
 5100:                 if (ref($roledoms) eq 'ARRAY') {
 5101:                    push(@{$possdoms},@{$roledoms});
 5102:                 }
 5103:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5104:                     if (!$nothide{$username.':'.$domain}) {
 5105:                         next;
 5106:                     }
 5107:                 }
 5108:             }
 5109:         }
 5110:         if ($withsec) {
 5111:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5112:                 $tstart.':'.$tend;
 5113:         } else {
 5114:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5115:         }
 5116:     }
 5117:     return %returnhash;
 5118: }
 5119: 
 5120: sub get_all_adhocroles {
 5121:     my ($dom) = @_;
 5122:     my @roles_by_num = ();
 5123:     my %domdefaults = &get_domain_defaults($dom);
 5124:     my (%description,%access_in_dom,%access_info);
 5125:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5126:         my $count = 0;
 5127:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5128:         my %ordered;
 5129:         foreach my $role (sort(keys(%domcurrent))) {
 5130:             my ($order,$desc,$access_in_dom);
 5131:             if (ref($domcurrent{$role}) eq 'HASH') {
 5132:                 $order = $domcurrent{$role}{'order'};
 5133:                 $desc = $domcurrent{$role}{'desc'};
 5134:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5135:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5136:             }
 5137:             if ($order eq '') {
 5138:                 $order = $count;
 5139:             }
 5140:             $ordered{$order} = $role;
 5141:             if ($desc ne '') {
 5142:                 $description{$role} = $desc;
 5143:             } else {
 5144:                 $description{$role}= $role;
 5145:             }
 5146:             $count++;
 5147:         }
 5148:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5149:             push(@roles_by_num,$ordered{$item});
 5150:         }
 5151:     }
 5152:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5153: }
 5154: 
 5155: sub get_my_adhocroles {
 5156:     my ($cid,$checkreg) = @_;
 5157:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5158:     if ($env{'request.course.id'} eq $cid) {
 5159:         $cdom = $env{'course.'.$cid.'.domain'};
 5160:         $cnum = $env{'course.'.$cid.'.num'};
 5161:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5162:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5163:         $cdom = $1;
 5164:         $cnum = $2;
 5165:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5166:                                      $cdom,$cnum);
 5167:     }
 5168:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5169:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5170:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5171:         if ($rosterhash{$user} ne '') {
 5172:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5173:             return ([],{}) if ($type eq 'auto');
 5174:         }
 5175:     }
 5176:     if (($cdom ne '') && ($cnum ne ''))  {
 5177:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5178:             my $then=$env{'user.login.time'};
 5179:             my $update=$env{'user.update.time'};
 5180:             if (!$update) {
 5181:                 $update = $then;
 5182:             }
 5183:             my @liveroles;
 5184:             foreach my $role ('dh','da') {
 5185:                 if ($env{"user.role.$role./$cdom/"}) {
 5186:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5187:                     my $limit = $update;
 5188:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5189:                         $limit = $then;
 5190:                     }
 5191:                     my $activerole = 1;
 5192:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5193:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5194:                     if ($activerole) {
 5195:                         push(@liveroles,$role);
 5196:                     }
 5197:                 }
 5198:             }
 5199:             if (@liveroles) {
 5200:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5201:                     my ($accessref,$accessinfo,%access_in_dom);
 5202:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5203:                     if (ref($roles_by_num) eq 'ARRAY') {
 5204:                         if (@{$roles_by_num}) {
 5205:                             my %settings;
 5206:                             if ($env{'request.course.id'} eq $cid) {
 5207:                                 foreach my $envkey (keys(%env)) {
 5208:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5209:                                         $settings{$1} = $env{$envkey};
 5210:                                     }
 5211:                                 }
 5212:                             } else {
 5213:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5214:                             }
 5215:                             my %setincrs;
 5216:                             if ($settings{'internal.adhocaccess'}) {
 5217:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5218:                             }
 5219:                             my @statuses;
 5220:                             if ($env{'environment.inststatus'}) {
 5221:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5222:                             }
 5223:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5224:                             if (ref($accessref) eq 'HASH') {
 5225:                                 %access_in_dom = %{$accessref};
 5226:                             }
 5227:                             foreach my $role (@{$roles_by_num}) {
 5228:                                 my ($curraccess,@okstatus,@personnel);
 5229:                                 if ($setincrs{$role}) {
 5230:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5231:                                     if ($curraccess eq 'status') {
 5232:                                         @okstatus = split(/\&/,$rest);
 5233:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5234:                                         @personnel = split(/\&/,$rest);
 5235:                                     }
 5236:                                 } else {
 5237:                                     $curraccess = $access_in_dom{$role};
 5238:                                     if (ref($accessinfo) eq 'HASH') {
 5239:                                         if ($curraccess eq 'status') {
 5240:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5241:                                                 @okstatus = @{$accessinfo->{$role}};
 5242:                                             }
 5243:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5244:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5245:                                                 @personnel = @{$accessinfo->{$role}};
 5246:                                             }
 5247:                                         }
 5248:                                     }
 5249:                                 }
 5250:                                 if ($curraccess eq 'none') {
 5251:                                     next;
 5252:                                 } elsif ($curraccess eq 'all') {
 5253:                                     push(@possroles,$role);
 5254:                                 } elsif ($curraccess eq 'dh') {
 5255:                                     if (grep(/^dh$/,@liveroles)) {
 5256:                                         push(@possroles,$role);
 5257:                                     } else {
 5258:                                         next;
 5259:                                     }
 5260:                                 } elsif ($curraccess eq 'da') {
 5261:                                     if (grep(/^da$/,@liveroles)) {
 5262:                                         push(@possroles,$role);
 5263:                                     } else {
 5264:                                         next;
 5265:                                     }
 5266:                                 } elsif ($curraccess eq 'status') {
 5267:                                     if (@okstatus) {
 5268:                                         if (!@statuses) {
 5269:                                             if (grep(/^default$/,@okstatus)) {
 5270:                                                 push(@possroles,$role);
 5271:                                             }
 5272:                                         } else {
 5273:                                             foreach my $status (@okstatus) {
 5274:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5275:                                                     push(@possroles,$role);
 5276:                                                     last;
 5277:                                                 }
 5278:                                             }
 5279:                                         }
 5280:                                     }
 5281:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5282:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5283:                                         if ($curraccess eq 'exc') {
 5284:                                             push(@possroles,$role);
 5285:                                         }
 5286:                                     } elsif ($curraccess eq 'inc') {
 5287:                                         push(@possroles,$role);
 5288:                                     }
 5289:                                 }
 5290:                             }
 5291:                         }
 5292:                     }
 5293:                 }
 5294:             }
 5295:         }
 5296:     }
 5297:     unless (ref($description) eq 'HASH') {
 5298:         if (ref($roles_by_num) eq 'ARRAY') {
 5299:             my %desc;
 5300:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5301:             $description = \%desc;
 5302:         } else {
 5303:             $description = {};
 5304:         }
 5305:     }
 5306:     return (\@possroles,$description);
 5307: }
 5308: 
 5309: # ----------------------------------------------------- Frontpage Announcements
 5310: #
 5311: #
 5312: 
 5313: sub postannounce {
 5314:     my ($server,$text)=@_;
 5315:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5316:     unless ($text=~/\w/) { $text=''; }
 5317:     return &reply('setannounce:'.&escape($text),$server);
 5318: }
 5319: 
 5320: sub getannounce {
 5321: 
 5322:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5323: 	my $announcement='';
 5324: 	while (my $line = <$fh>) { $announcement .= $line; }
 5325: 	close($fh);
 5326: 	if ($announcement=~/\w/) { 
 5327: 	    return 
 5328:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5329:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5330: 	} else {
 5331: 	    return '';
 5332: 	}
 5333:     } else {
 5334: 	return '';
 5335:     }
 5336: }
 5337: 
 5338: # ---------------------------------------------------------- Course ID routines
 5339: # Deal with domain's nohist_courseid.db files
 5340: #
 5341: 
 5342: sub courseidput {
 5343:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5344:     return unless (ref($storehash) eq 'HASH');
 5345:     my $outcome;
 5346:     if ($caller eq 'timeonly') {
 5347:         my $cids = '';
 5348:         foreach my $item (keys(%$storehash)) {
 5349:             $cids.=&escape($item).'&';
 5350:         }
 5351:         $cids=~s/\&$//;
 5352:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5353:                           $coursehome);       
 5354:     } else {
 5355:         my $items = '';
 5356:         foreach my $item (keys(%$storehash)) {
 5357:             $items.= &escape($item).'='.
 5358:                      &freeze_escape($$storehash{$item}).'&';
 5359:         }
 5360:         $items=~s/\&$//;
 5361:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5362:                           $coursehome);
 5363:     }
 5364:     if ($outcome eq 'unknown_cmd') {
 5365:         my $what;
 5366:         foreach my $cid (keys(%$storehash)) {
 5367:             $what .= &escape($cid).'=';
 5368:             foreach my $item ('description','inst_code','owner','type') {
 5369:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5370:             }
 5371:             $what =~ s/\:$/&/;
 5372:         }
 5373:         $what =~ s/\&$//;  
 5374:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5375:     } else {
 5376:         return $outcome;
 5377:     }
 5378: }
 5379: 
 5380: sub courseiddump {
 5381:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5382:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5383:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5384:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5385:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5386:     my $as_hash = 1;
 5387:     my %returnhash;
 5388:     if (!$domfilter) { $domfilter=''; }
 5389:     my %libserv = &all_library();
 5390:     foreach my $tryserver (keys(%libserv)) {
 5391:         if ( (  $hostidflag == 1 
 5392: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5393: 	     || (!defined($hostidflag)) ) {
 5394: 
 5395: 	    if (($domfilter eq '') ||
 5396: 		(&host_domain($tryserver) eq $domfilter)) {
 5397:                 my $rep;
 5398:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
 5399:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
 5400:                         join(":", (&host_domain($tryserver), $sincefilter,
 5401:                                 &escape($descfilter), &escape($instcodefilter),
 5402:                                 &escape($ownerfilter), &escape($coursefilter),
 5403:                                 &escape($typefilter), &escape($regexp_ok),
 5404:                                 $as_hash, &escape($selfenrollonly),
 5405:                                 &escape($catfilter), $showhidden, $caller,
 5406:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
 5407:                                 &escape($createdbefore), &escape($createdafter),
 5408:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5409:                                 $reqcrsdom,&escape($reqinstcode))));
 5410:                 } else {
 5411:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5412:                              $sincefilter.':'.&escape($descfilter).':'.
 5413:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5414:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5415:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5416:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5417:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5418:                              &escape($cc_clone).':'.$cloneonly.':'.
 5419:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5420:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5421:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5422:                 }
 5423: 
 5424:                 my @pairs=split(/\&/,$rep);
 5425:                 foreach my $item (@pairs) {
 5426:                     my ($key,$value)=split(/\=/,$item,2);
 5427:                     $key = &unescape($key);
 5428:                     next if ($key =~ /^error: 2 /);
 5429:                     my $result = &thaw_unescape($value);
 5430:                     if (ref($result) eq 'HASH') {
 5431:                         $returnhash{$key}=$result;
 5432:                     } else {
 5433:                         my @responses = split(/:/,$value);
 5434:                         my @items = ('description','inst_code','owner','type');
 5435:                         for (my $i=0; $i<@responses; $i++) {
 5436:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5437:                         }
 5438:                     }
 5439:                 }
 5440:             }
 5441:         }
 5442:     }
 5443:     return %returnhash;
 5444: }
 5445: 
 5446: sub courselastaccess {
 5447:     my ($cdom,$cnum,$hostidref) = @_;
 5448:     my %returnhash;
 5449:     if ($cdom && $cnum) {
 5450:         my $chome = &homeserver($cnum,$cdom);
 5451:         if ($chome ne 'no_host') {
 5452:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5453:             &extract_lastaccess(\%returnhash,$rep);
 5454:         }
 5455:     } else {
 5456:         if (!$cdom) { $cdom=''; }
 5457:         my %libserv = &all_library();
 5458:         foreach my $tryserver (keys(%libserv)) {
 5459:             if (ref($hostidref) eq 'ARRAY') {
 5460:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5461:             } 
 5462:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5463:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5464:                 &extract_lastaccess(\%returnhash,$rep);
 5465:             }
 5466:         }
 5467:     }
 5468:     return %returnhash;
 5469: }
 5470: 
 5471: sub extract_lastaccess {
 5472:     my ($returnhash,$rep) = @_;
 5473:     if (ref($returnhash) eq 'HASH') {
 5474:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5475:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5476:                  $rep eq '') {
 5477:             my @pairs=split(/\&/,$rep);
 5478:             foreach my $item (@pairs) {
 5479:                 my ($key,$value)=split(/\=/,$item,2);
 5480:                 $key = &unescape($key);
 5481:                 next if ($key =~ /^error: 2 /);
 5482:                 $returnhash->{$key} = &thaw_unescape($value);
 5483:             }
 5484:         }
 5485:     }
 5486:     return;
 5487: }
 5488: 
 5489: # ---------------------------------------------------------- DC e-mail
 5490: 
 5491: sub dcmailput {
 5492:     my ($domain,$msgid,$message,$server)=@_;
 5493:     my $status = &Apache::lonnet::critical(
 5494:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5495:        &escape($message),$server);
 5496:     return $status;
 5497: }
 5498: 
 5499: sub dcmaildump {
 5500:     my ($dom,$startdate,$enddate,$senders) = @_;
 5501:     my %returnhash=();
 5502: 
 5503:     if (defined(&domain($dom,'primary'))) {
 5504:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5505:                                                          &escape($enddate).':';
 5506: 	my @esc_senders=map { &escape($_)} @$senders;
 5507: 	$cmd.=&escape(join('&',@esc_senders));
 5508: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5509:             my ($key,$value) = split(/\=/,$line,2);
 5510:             if (($key) && ($value)) {
 5511:                 $returnhash{&unescape($key)} = &unescape($value);
 5512:             }
 5513:         }
 5514:     }
 5515:     return %returnhash;
 5516: }
 5517: # ---------------------------------------------------------- Domain roles
 5518: 
 5519: sub get_domain_roles {
 5520:     my ($dom,$roles,$startdate,$enddate)=@_;
 5521:     if ((!defined($startdate)) || ($startdate eq '')) {
 5522:         $startdate = '.';
 5523:     }
 5524:     if ((!defined($enddate)) || ($enddate eq '')) {
 5525:         $enddate = '.';
 5526:     }
 5527:     my $rolelist;
 5528:     if (ref($roles) eq 'ARRAY') {
 5529:         $rolelist = join('&',@{$roles});
 5530:     }
 5531:     my %personnel = ();
 5532: 
 5533:     my %servers = &get_servers($dom,'library');
 5534:     foreach my $tryserver (keys(%servers)) {
 5535: 	%{$personnel{$tryserver}}=();
 5536: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5537: 					    &escape($startdate).':'.
 5538: 					    &escape($enddate).':'.
 5539: 					    &escape($rolelist), $tryserver))) {
 5540: 	    my ($key,$value) = split(/\=/,$line,2);
 5541: 	    if (($key) && ($value)) {
 5542: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5543: 	    }
 5544: 	}
 5545:     }
 5546:     return %personnel;
 5547: }
 5548: 
 5549: sub get_active_domroles {
 5550:     my ($dom,$roles) = @_;
 5551:     return () unless (ref($roles) eq 'ARRAY');
 5552:     my $now = time;
 5553:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5554:     my %domroles;
 5555:     foreach my $server (keys(%dompersonnel)) {
 5556:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5557:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5558:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5559:         }
 5560:     }
 5561:     return %domroles;
 5562: }
 5563: 
 5564: # ----------------------------------------------------------- Interval timing 
 5565: 
 5566: {
 5567: # Caches needed for speedup of navmaps
 5568: # We don't want to cache this for very long at all (5 seconds at most)
 5569: # 
 5570: # The user for whom we cache
 5571: my $cachedkey='';
 5572: # The cached times for this user
 5573: my %cachedtimes=();
 5574: # When this was last done
 5575: my $cachedtime='';
 5576: 
 5577: sub load_all_first_access {
 5578:     my ($uname,$udom,$ignorecache)=@_;
 5579:     if (($cachedkey eq $uname.':'.$udom) &&
 5580:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5581:         (!$ignorecache)) {
 5582:         return;
 5583:     }
 5584:     $cachedtime=time;
 5585:     $cachedkey=$uname.':'.$udom;
 5586:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5587: }
 5588: 
 5589: sub get_first_access {
 5590:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5591:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5592:     if ($argsymb) { $symb=$argsymb; }
 5593:     my ($map,$id,$res)=&decode_symb($symb);
 5594:     if ($argmap) { $map = $argmap; }
 5595:     if ($type eq 'course') {
 5596: 	$res='course';
 5597:     } elsif ($type eq 'map') {
 5598: 	$res=&symbread($map);
 5599:     } else {
 5600: 	$res=$symb;
 5601:     }
 5602:     &load_all_first_access($uname,$udom,$ignorecache);
 5603:     return $cachedtimes{"$courseid\0$res"};
 5604: }
 5605: 
 5606: sub set_first_access {
 5607:     my ($type,$interval)=@_;
 5608:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5609:     my ($map,$id,$res)=&decode_symb($symb);
 5610:     if ($type eq 'course') {
 5611: 	$res='course';
 5612:     } elsif ($type eq 'map') {
 5613: 	$res=&symbread($map);
 5614:     } else {
 5615: 	$res=$symb;
 5616:     }
 5617:     $cachedkey='';
 5618:     my $firstaccess=&get_first_access($type,$symb,$map);
 5619:     if ($firstaccess) {
 5620:         &logthis("First access time already set ($firstaccess) when attempting ".
 5621:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5622:                  "in $courseid");
 5623:         return 'already_set';
 5624:     } else {
 5625:         my $start = time;
 5626: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5627:                           $udom,$uname);
 5628:         if ($putres eq 'ok') {
 5629:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5630:                  $udom,$uname); 
 5631:             &appenv(
 5632:                      {
 5633:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5634:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5635:                      }
 5636:                   );
 5637:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5638:                 $cachedtimes{"$courseid\0$res"} = $start;
 5639:             }
 5640:         } elsif ($putres ne 'refused') {
 5641:             &logthis("Result: $putres when attempting to set first access time ".
 5642:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5643:         }
 5644:         return $putres;
 5645:     }
 5646:     return 'already_set';
 5647: }
 5648: }
 5649: 
 5650: sub checkout {
 5651:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 5652:     my $now=time;
 5653:     my $lonhost=$perlvar{'lonHostID'};
 5654:     my $ip = &get_requestor_ip();
 5655:     my $infostr=&escape(
 5656:                  'CHECKOUTTOKEN&'.
 5657:                  $tuname.'&'.
 5658:                  $tudom.'&'.
 5659:                  $tcrsid.'&'.
 5660:                  $symb.'&'.
 5661:                  $now.'&'.$ip);
 5662:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 5663:     if ($token=~/^error\:/) {
 5664:         &logthis("<font color=\"blue\">WARNING: ".
 5665:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 5666:                  "</font>");
 5667:         return '';
 5668:     }
 5669: 
 5670:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 5671:     $token=~tr/a-z/A-Z/;
 5672: 
 5673:     my %infohash=('resource.0.outtoken' => $token,
 5674:                   'resource.0.checkouttime' => $now,
 5675:                   'resource.0.outremote' => $ip);
 5676: 
 5677:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 5678:        return '';
 5679:     } else {
 5680:         &logthis("<font color=\"blue\">WARNING: ".
 5681:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 5682:                  "</font>");
 5683:     }
 5684: 
 5685:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 5686:                          &escape('Checkout '.$infostr.' - '.
 5687:                                                  $token)) ne 'ok') {
 5688:         return '';
 5689:     } else {
 5690:         &logthis("<font color=\"blue\">WARNING: ".
 5691:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 5692:                  "</font>");
 5693:     }
 5694:     return $token;
 5695: }
 5696: 
 5697: # ------------------------------------------------------------ Check in an item
 5698: 
 5699: sub checkin {
 5700:     my $token=shift;
 5701:     my $now=time;
 5702:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 5703:     $lonhost=~tr/A-Z/a-z/;
 5704:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 5705:     $dtoken=~s/\W/\_/g;
 5706:     my $ip = &get_requestor_ip();
 5707:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 5708:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 5709: 
 5710:     unless (($tuname) && ($tudom)) {
 5711:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 5712:         return '';
 5713:     }
 5714: 
 5715:     unless (&allowed('mgr',$tcrsid)) {
 5716:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 5717:                  $env{'user.name'}.' - '.$env{'user.domain'});
 5718:         return '';
 5719:     }
 5720: 
 5721:     my %infohash=('resource.0.intoken' => $token,
 5722:                   'resource.0.checkintime' => $now,
 5723:                   'resource.0.inremote' => $ip);
 5724: 
 5725:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 5726:        return '';
 5727:     }
 5728: 
 5729:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 5730:                          &escape('Checkin - '.$token)) ne 'ok') {
 5731:         return '';
 5732:     }
 5733: 
 5734:     return ($symb,$tuname,$tudom,$tcrsid);
 5735: }
 5736: 
 5737: # --------------------------------------------- Set Expire Date for Spreadsheet
 5738: 
 5739: sub expirespread {
 5740:     my ($uname,$udom,$stype,$usymb)=@_;
 5741:     my $cid=$env{'request.course.id'}; 
 5742:     if ($cid) {
 5743:        my $now=time;
 5744:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5745:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5746:                             $env{'course.'.$cid.'.num'}.
 5747: 	        	    ':nohist_expirationdates:'.
 5748:                             &escape($key).'='.$now,
 5749:                             $env{'course.'.$cid.'.home'})
 5750:     }
 5751:     return 'ok';
 5752: }
 5753: 
 5754: # ----------------------------------------------------- Devalidate Spreadsheets
 5755: 
 5756: sub devalidate {
 5757:     my ($symb,$uname,$udom)=@_;
 5758:     my $cid=$env{'request.course.id'}; 
 5759:     if ($cid) {
 5760:         # delete the stored spreadsheets for
 5761:         # - the student level sheet of this user in course's homespace
 5762:         # - the assessment level sheet for this resource 
 5763:         #   for this user in user's homespace
 5764: 	# - current conditional state info
 5765: 	my $key=$uname.':'.$udom.':';
 5766:         my $status=
 5767: 	    &del('nohist_calculatedsheets',
 5768: 		 [$key.'studentcalc:'],
 5769: 		 $env{'course.'.$cid.'.domain'},
 5770: 		 $env{'course.'.$cid.'.num'})
 5771: 		.' '.
 5772: 	    &del('nohist_calculatedsheets_'.$cid,
 5773: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5774:         unless ($status eq 'ok ok') {
 5775:            &logthis('Could not devalidate spreadsheet '.
 5776:                     $uname.' at '.$udom.' for '.
 5777: 		    $symb.': '.$status);
 5778:         }
 5779: 	&delenv('user.state.'.$cid);
 5780:     }
 5781: }
 5782: 
 5783: sub get_scalar {
 5784:     my ($string,$end) = @_;
 5785:     my $value;
 5786:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5787: 	$value = $1;
 5788:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5789: 	$value = $1;
 5790:     }
 5791:     return &unescape($value);
 5792: }
 5793: 
 5794: sub array2str {
 5795:   my (@array) = @_;
 5796:   my $result=&arrayref2str(\@array);
 5797:   $result=~s/^__ARRAY_REF__//;
 5798:   $result=~s/__END_ARRAY_REF__$//;
 5799:   return $result;
 5800: }
 5801: 
 5802: sub arrayref2str {
 5803:   my ($arrayref) = @_;
 5804:   my $result='__ARRAY_REF__';
 5805:   foreach my $elem (@$arrayref) {
 5806:     if(ref($elem) eq 'ARRAY') {
 5807:       $result.=&arrayref2str($elem).'&';
 5808:     } elsif(ref($elem) eq 'HASH') {
 5809:       $result.=&hashref2str($elem).'&';
 5810:     } elsif(ref($elem)) {
 5811:       #print("Got a ref of ".(ref($elem))." skipping.");
 5812:     } else {
 5813:       $result.=&escape($elem).'&';
 5814:     }
 5815:   }
 5816:   $result=~s/\&$//;
 5817:   $result .= '__END_ARRAY_REF__';
 5818:   return $result;
 5819: }
 5820: 
 5821: sub hash2str {
 5822:   my (%hash) = @_;
 5823:   my $result=&hashref2str(\%hash);
 5824:   $result=~s/^__HASH_REF__//;
 5825:   $result=~s/__END_HASH_REF__$//;
 5826:   return $result;
 5827: }
 5828: 
 5829: sub hashref2str {
 5830:   my ($hashref)=@_;
 5831:   my $result='__HASH_REF__';
 5832:   foreach my $key (sort(keys(%$hashref))) {
 5833:     if (ref($key) eq 'ARRAY') {
 5834:       $result.=&arrayref2str($key).'=';
 5835:     } elsif (ref($key) eq 'HASH') {
 5836:       $result.=&hashref2str($key).'=';
 5837:     } elsif (ref($key)) {
 5838:       $result.='=';
 5839:       #print("Got a ref of ".(ref($key))." skipping.");
 5840:     } else {
 5841: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5842:     }
 5843: 
 5844:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5845:       $result.=&arrayref2str($hashref->{$key}).'&';
 5846:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5847:       $result.=&hashref2str($hashref->{$key}).'&';
 5848:     } elsif(ref($hashref->{$key})) {
 5849:        $result.='&';
 5850:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5851:     } else {
 5852:       $result.=&escape($hashref->{$key}).'&';
 5853:     }
 5854:   }
 5855:   $result=~s/\&$//;
 5856:   $result .= '__END_HASH_REF__';
 5857:   return $result;
 5858: }
 5859: 
 5860: sub str2hash {
 5861:     my ($string)=@_;
 5862:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5863:     return %$hash;
 5864: }
 5865: 
 5866: sub str2hashref {
 5867:   my ($string) = @_;
 5868: 
 5869:   my %hash;
 5870: 
 5871:   if($string !~ /^__HASH_REF__/) {
 5872:       if (! ($string eq '' || !defined($string))) {
 5873: 	  $hash{'error'}='Not hash reference';
 5874:       }
 5875:       return (\%hash, $string);
 5876:   }
 5877: 
 5878:   $string =~ s/^__HASH_REF__//;
 5879: 
 5880:   while($string !~ /^__END_HASH_REF__/) {
 5881:       #key
 5882:       my $key='';
 5883:       if($string =~ /^__HASH_REF__/) {
 5884:           ($key, $string)=&str2hashref($string);
 5885:           if(defined($key->{'error'})) {
 5886:               $hash{'error'}='Bad data';
 5887:               return (\%hash, $string);
 5888:           }
 5889:       } elsif($string =~ /^__ARRAY_REF__/) {
 5890:           ($key, $string)=&str2arrayref($string);
 5891:           if($key->[0] eq 'Array reference error') {
 5892:               $hash{'error'}='Bad data';
 5893:               return (\%hash, $string);
 5894:           }
 5895:       } else {
 5896:           $string =~ s/^(.*?)=//;
 5897: 	  $key=&unescape($1);
 5898:       }
 5899:       $string =~ s/^=//;
 5900: 
 5901:       #value
 5902:       my $value='';
 5903:       if($string =~ /^__HASH_REF__/) {
 5904:           ($value, $string)=&str2hashref($string);
 5905:           if(defined($value->{'error'})) {
 5906:               $hash{'error'}='Bad data';
 5907:               return (\%hash, $string);
 5908:           }
 5909:       } elsif($string =~ /^__ARRAY_REF__/) {
 5910:           ($value, $string)=&str2arrayref($string);
 5911:           if($value->[0] eq 'Array reference error') {
 5912:               $hash{'error'}='Bad data';
 5913:               return (\%hash, $string);
 5914:           }
 5915:       } else {
 5916: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5917:       }
 5918:       $string =~ s/^&//;
 5919: 
 5920:       $hash{$key}=$value;
 5921:   }
 5922: 
 5923:   $string =~ s/^__END_HASH_REF__//;
 5924: 
 5925:   return (\%hash, $string);
 5926: }
 5927: 
 5928: sub str2array {
 5929:     my ($string)=@_;
 5930:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5931:     return @$array;
 5932: }
 5933: 
 5934: sub str2arrayref {
 5935:   my ($string) = @_;
 5936:   my @array;
 5937: 
 5938:   if($string !~ /^__ARRAY_REF__/) {
 5939:       if (! ($string eq '' || !defined($string))) {
 5940: 	  $array[0]='Array reference error';
 5941:       }
 5942:       return (\@array, $string);
 5943:   }
 5944: 
 5945:   $string =~ s/^__ARRAY_REF__//;
 5946: 
 5947:   while($string !~ /^__END_ARRAY_REF__/) {
 5948:       my $value='';
 5949:       if($string =~ /^__HASH_REF__/) {
 5950:           ($value, $string)=&str2hashref($string);
 5951:           if(defined($value->{'error'})) {
 5952:               $array[0] ='Array reference error';
 5953:               return (\@array, $string);
 5954:           }
 5955:       } elsif($string =~ /^__ARRAY_REF__/) {
 5956:           ($value, $string)=&str2arrayref($string);
 5957:           if($value->[0] eq 'Array reference error') {
 5958:               $array[0] ='Array reference error';
 5959:               return (\@array, $string);
 5960:           }
 5961:       } else {
 5962: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5963:       }
 5964:       $string =~ s/^&//;
 5965: 
 5966:       push(@array, $value);
 5967:   }
 5968: 
 5969:   $string =~ s/^__END_ARRAY_REF__//;
 5970: 
 5971:   return (\@array, $string);
 5972: }
 5973: 
 5974: # -------------------------------------------------------------------Temp Store
 5975: 
 5976: sub tmpreset {
 5977:   my ($symb,$namespace,$domain,$stuname) = @_;
 5978:   if (!$symb) {
 5979:     $symb=&symbread();
 5980:     if (!$symb) { $symb= $env{'request.url'}; }
 5981:   }
 5982:   $symb=escape($symb);
 5983: 
 5984:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5985:   $namespace=~s/\//\_/g;
 5986:   $namespace=~s/\W//g;
 5987: 
 5988:   if (!$domain) { $domain=$env{'user.domain'}; }
 5989:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5990:   if ($domain eq 'public' && $stuname eq 'public') {
 5991:       $stuname=&get_requestor_ip();
 5992:   }
 5993:   my $path=LONCAPA::tempdir();
 5994:   my %hash;
 5995:   if (tie(%hash,'GDBM_File',
 5996: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5997: 	  &GDBM_WRCREAT(),0640)) {
 5998:     foreach my $key (keys(%hash)) {
 5999:       if ($key=~ /:$symb/) {
 6000: 	delete($hash{$key});
 6001:       }
 6002:     }
 6003:   }
 6004: }
 6005: 
 6006: sub tmpstore {
 6007:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 6008: 
 6009:   if (!$symb) {
 6010:     $symb=&symbread();
 6011:     if (!$symb) { $symb= $env{'request.url'}; }
 6012:   }
 6013:   $symb=escape($symb);
 6014: 
 6015:   if (!$namespace) {
 6016:     # I don't think we would ever want to store this for a course.
 6017:     # it seems this will only be used if we don't have a course.
 6018:     #$namespace=$env{'request.course.id'};
 6019:     #if (!$namespace) {
 6020:       $namespace=$env{'request.state'};
 6021:     #}
 6022:   }
 6023:   $namespace=~s/\//\_/g;
 6024:   $namespace=~s/\W//g;
 6025:   if (!$domain) { $domain=$env{'user.domain'}; }
 6026:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6027:   if ($domain eq 'public' && $stuname eq 'public') {
 6028:       $stuname=&get_requestor_ip();
 6029:   }
 6030:   my $now=time;
 6031:   my %hash;
 6032:   my $path=LONCAPA::tempdir();
 6033:   if (tie(%hash,'GDBM_File',
 6034: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6035: 	  &GDBM_WRCREAT(),0640)) {
 6036:     $hash{"version:$symb"}++;
 6037:     my $version=$hash{"version:$symb"};
 6038:     my $allkeys=''; 
 6039:     foreach my $key (keys(%$storehash)) {
 6040:       $allkeys.=$key.':';
 6041:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6042:     }
 6043:     $hash{"$version:$symb:timestamp"}=$now;
 6044:     $allkeys.='timestamp';
 6045:     $hash{"$version:keys:$symb"}=$allkeys;
 6046:     if (untie(%hash)) {
 6047:       return 'ok';
 6048:     } else {
 6049:       return "error:$!";
 6050:     }
 6051:   } else {
 6052:     return "error:$!";
 6053:   }
 6054: }
 6055: 
 6056: # -----------------------------------------------------------------Temp Restore
 6057: 
 6058: sub tmprestore {
 6059:   my ($symb,$namespace,$domain,$stuname) = @_;
 6060: 
 6061:   if (!$symb) {
 6062:     $symb=&symbread();
 6063:     if (!$symb) { $symb= $env{'request.url'}; }
 6064:   }
 6065:   $symb=escape($symb);
 6066: 
 6067:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6068: 
 6069:   if (!$domain) { $domain=$env{'user.domain'}; }
 6070:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6071:   if ($domain eq 'public' && $stuname eq 'public') {
 6072:       $stuname=&get_requestor_ip();
 6073:   }
 6074:   my %returnhash;
 6075:   $namespace=~s/\//\_/g;
 6076:   $namespace=~s/\W//g;
 6077:   my %hash;
 6078:   my $path=LONCAPA::tempdir();
 6079:   if (tie(%hash,'GDBM_File',
 6080: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6081: 	  &GDBM_READER(),0640)) {
 6082:     my $version=$hash{"version:$symb"};
 6083:     $returnhash{'version'}=$version;
 6084:     my $scope;
 6085:     for ($scope=1;$scope<=$version;$scope++) {
 6086:       my $vkeys=$hash{"$scope:keys:$symb"};
 6087:       my @keys=split(/:/,$vkeys);
 6088:       my $key;
 6089:       $returnhash{"$scope:keys"}=$vkeys;
 6090:       foreach $key (@keys) {
 6091: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6092: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6093:       }
 6094:     }
 6095:     if (!(untie(%hash))) {
 6096:       return "error:$!";
 6097:     }
 6098:   } else {
 6099:     return "error:$!";
 6100:   }
 6101:   return %returnhash;
 6102: }
 6103: 
 6104: # ----------------------------------------------------------------------- Store
 6105: 
 6106: sub store {
 6107:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6108:     my $home='';
 6109: 
 6110:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6111: 
 6112:     $symb=&symbclean($symb);
 6113:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6114: 
 6115:     if (!$domain) { $domain=$env{'user.domain'}; }
 6116:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6117: 
 6118:     &devalidate($symb,$stuname,$domain);
 6119: 
 6120:     $symb=escape($symb);
 6121:     if (!$namespace) { 
 6122:        unless ($namespace=$env{'request.course.id'}) { 
 6123:           return ''; 
 6124:        } 
 6125:     }
 6126:     if (!$home) { $home=$env{'user.home'}; }
 6127: 
 6128:     $$storehash{'ip'}=&get_requestor_ip();
 6129:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6130: 
 6131:     my $namevalue='';
 6132:     foreach my $key (keys(%$storehash)) {
 6133:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6134:     }
 6135:     $namevalue=~s/\&$//;
 6136:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6137:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6138: }
 6139: 
 6140: # -------------------------------------------------------------- Critical Store
 6141: 
 6142: sub cstore {
 6143:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6144:     my $home='';
 6145: 
 6146:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6147: 
 6148:     $symb=&symbclean($symb);
 6149:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6150: 
 6151:     if (!$domain) { $domain=$env{'user.domain'}; }
 6152:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6153: 
 6154:     &devalidate($symb,$stuname,$domain);
 6155: 
 6156:     $symb=escape($symb);
 6157:     if (!$namespace) { 
 6158:        unless ($namespace=$env{'request.course.id'}) { 
 6159:           return ''; 
 6160:        } 
 6161:     }
 6162:     if (!$home) { $home=$env{'user.home'}; }
 6163: 
 6164:     $$storehash{'ip'}=&get_requestor_ip();
 6165:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6166: 
 6167:     my $namevalue='';
 6168:     foreach my $key (keys(%$storehash)) {
 6169:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6170:     }
 6171:     $namevalue=~s/\&$//;
 6172:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6173:     return critical
 6174:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6175: }
 6176: 
 6177: # --------------------------------------------------------------------- Restore
 6178: 
 6179: sub restore {
 6180:     my ($symb,$namespace,$domain,$stuname) = @_;
 6181:     my $home='';
 6182: 
 6183:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6184: 
 6185:     if (!$symb) {
 6186:         return if ($namespace eq 'courserequests');
 6187:         unless ($symb=escape(&symbread())) { return ''; }
 6188:     } else {
 6189:         unless ($namespace eq 'courserequests') {
 6190:             $symb=&escape(&symbclean($symb));
 6191:         }
 6192:     }
 6193:     if (!$namespace) { 
 6194:        unless ($namespace=$env{'request.course.id'}) { 
 6195:           return ''; 
 6196:        } 
 6197:     }
 6198:     if (!$domain) { $domain=$env{'user.domain'}; }
 6199:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6200:     if (!$home) { $home=$env{'user.home'}; }
 6201:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6202: 
 6203:     my %returnhash=();
 6204:     foreach my $line (split(/\&/,$answer)) {
 6205: 	my ($name,$value)=split(/\=/,$line);
 6206:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6207:     }
 6208:     my $version;
 6209:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6210:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6211:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6212:        }
 6213:     }
 6214:     return %returnhash;
 6215: }
 6216: 
 6217: # ---------------------------------------------------------- Course Description
 6218: #
 6219: #  
 6220: 
 6221: sub coursedescription {
 6222:     my ($courseid,$args)=@_;
 6223:     $courseid=~s/^\///;
 6224:     $courseid=~s/\_/\//g;
 6225:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6226:     my $chome=&homeserver($cnum,$cdomain);
 6227:     my $normalid=$cdomain.'_'.$cnum;
 6228:     # need to always cache even if we get errors otherwise we keep 
 6229:     # trying and trying and trying to get the course description.
 6230:     my %envhash=();
 6231:     my %returnhash=();
 6232:     
 6233:     my $expiretime=600;
 6234:     if ($env{'request.course.id'} eq $normalid) {
 6235: 	$expiretime=120;
 6236:     }
 6237: 
 6238:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6239:     if (!$args->{'freshen_cache'}
 6240: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6241: 	foreach my $key (keys(%env)) {
 6242: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6243: 	    my ($setting) = $1;
 6244: 	    $returnhash{$setting} = $env{$key};
 6245: 	}
 6246: 	return %returnhash;
 6247:     }
 6248: 
 6249:     # get the data again
 6250: 
 6251:     if (!$args->{'one_time'}) {
 6252: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6253:     }
 6254: 
 6255:     if ($chome ne 'no_host') {
 6256:        %returnhash=&dump('environment',$cdomain,$cnum);
 6257:        if (!exists($returnhash{'con_lost'})) {
 6258: 	   my $username = $env{'user.name'}; # Defult username
 6259: 	   if(defined $args->{'user'}) {
 6260: 	       $username = $args->{'user'};
 6261: 	   }
 6262:            $returnhash{'home'}= $chome;
 6263: 	   $returnhash{'domain'} = $cdomain;
 6264: 	   $returnhash{'num'} = $cnum;
 6265:            if (!defined($returnhash{'type'})) {
 6266:                $returnhash{'type'} = 'Course';
 6267:            }
 6268:            while (my ($name,$value) = each %returnhash) {
 6269:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6270:            }
 6271:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6272:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6273: 	       $username.'_'.$cdomain.'_'.$cnum;
 6274:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6275:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6276:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6277:        }
 6278:     }
 6279:     if (!$args->{'one_time'}) {
 6280: 	&appenv(\%envhash);
 6281:     }
 6282:     return %returnhash;
 6283: }
 6284: 
 6285: sub update_released_required {
 6286:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6287:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6288:         $cid = $env{'request.course.id'};
 6289:         $cdom = $env{'course.'.$cid.'.domain'};
 6290:         $cnum = $env{'course.'.$cid.'.num'};
 6291:         $chome = $env{'course.'.$cid.'.home'};
 6292:     }
 6293:     if ($needsrelease) {
 6294:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6295:         my $needsupdate;
 6296:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6297:             $needsupdate = 1;
 6298:         } else {
 6299:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6300:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6301:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6302:                 $needsupdate = 1;
 6303:             }
 6304:         }
 6305:         if ($needsupdate) {
 6306:             my %needshash = (
 6307:                              'internal.releaserequired' => $needsrelease,
 6308:                             );
 6309:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6310:             if ($putresult eq 'ok') {
 6311:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6312:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6313:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6314:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6315:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6316:                 }
 6317:             }
 6318:         }
 6319:     }
 6320:     return;
 6321: }
 6322: 
 6323: # -------------------------------------------------See if a user is privileged
 6324: 
 6325: sub privileged {
 6326:     my ($username,$domain,$possdomains,$possroles)=@_;
 6327:     my $now = time;
 6328:     my $roles;
 6329:     if (ref($possroles) eq 'ARRAY') {
 6330:         $roles = $possroles;
 6331:     } else {
 6332:         $roles = ['dc','su'];
 6333:     }
 6334:     if (ref($possdomains) eq 'ARRAY') {
 6335:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6336:         foreach my $dom (@{$possdomains}) {
 6337:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6338:                 (ref($privileged{$dom}) eq 'HASH')) {
 6339:                 foreach my $role (@{$roles}) {
 6340:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6341:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6342:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6343:                             return 1 unless (($end && $end < $now) ||
 6344:                                              ($start && $start > $now));
 6345:                         }
 6346:                     }
 6347:                 }
 6348:             }
 6349:         }
 6350:     } else {
 6351:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6352:         my $now = time;
 6353: 
 6354:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6355:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6356:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6357:                 return 1 unless ($tend && $tend < $now)
 6358:                         or ($tstart && $tstart > $now);
 6359:             }
 6360:         }
 6361:     }
 6362:     return 0;
 6363: }
 6364: 
 6365: sub privileged_by_domain {
 6366:     my ($domains,$roles) = @_;
 6367:     my %privileged = ();
 6368:     my $cachetime = 60*60*24;
 6369:     my $now = time;
 6370:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6371:         return %privileged;
 6372:     }
 6373:     foreach my $dom (@{$domains}) {
 6374:         next if (ref($privileged{$dom}) eq 'HASH');
 6375:         my $needroles;
 6376:         foreach my $role (@{$roles}) {
 6377:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6378:             if (defined($cached)) {
 6379:                 if (ref($result) eq 'HASH') {
 6380:                     $privileged{$dom}{$role} = $result;
 6381:                 }
 6382:             } else {
 6383:                 $needroles = 1;
 6384:             }
 6385:         }
 6386:         if ($needroles) {
 6387:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6388:             $privileged{$dom} = {};
 6389:             foreach my $server (keys(%dompersonnel)) {
 6390:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6391:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6392:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6393:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6394:                         next if ($end && $end < $now);
 6395:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
 6396:                             $dompersonnel{$server}{$item};
 6397:                     }
 6398:                 }
 6399:             }
 6400:             if (ref($privileged{$dom}) eq 'HASH') {
 6401:                 foreach my $role (@{$roles}) {
 6402:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6403:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6404:                     } else {
 6405:                         my %hash = ();
 6406:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6407:                     }
 6408:                 }
 6409:             }
 6410:         }
 6411:     }
 6412:     return %privileged;
 6413: }
 6414: 
 6415: # -------------------------------------------------------- Get user privileges
 6416: 
 6417: sub rolesinit {
 6418:     my ($domain, $username) = @_;
 6419:     my %userroles = ('user.login.time' => time);
 6420:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6421: 
 6422:     # firstaccess and timerinterval are related to timed maps/resources. 
 6423:     # also, blocking can be triggered by an activating timer
 6424:     # it's saved in the user's %env.
 6425:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6426:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6427:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6428:         %timerintchk, %timerintenv);
 6429: 
 6430:     foreach my $key (keys(%firstaccess)) {
 6431:         my ($cid, $rest) = split(/\0/, $key);
 6432:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6433:     }
 6434: 
 6435:     foreach my $key (keys(%timerinterval)) {
 6436:         my ($cid,$rest) = split(/\0/,$key);
 6437:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6438:     }
 6439: 
 6440:     my %allroles=();
 6441:     my %allgroups=();
 6442: 
 6443:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6444:         my $role = $rolesdump{$area};
 6445:         $area =~ s/\_\w\w$//;
 6446: 
 6447:         my ($trole, $tend, $tstart, $group_privs);
 6448: 
 6449:         if ($role =~ /^cr/) {
 6450:         # Custom role, defined by a user 
 6451:         # e.g., user.role.cr/msu/smith/mynewrole
 6452:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6453:                 $trole = $1;
 6454:                 ($tend, $tstart) = split('_', $2);
 6455:             } else {
 6456:                 $trole = $role;
 6457:             }
 6458:         } elsif ($role =~ m|^gr/|) {
 6459:         # Role of member in a group, defined within a course/community
 6460:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6461:             ($trole, $tend, $tstart) = split(/_/, $role);
 6462:             next if $tstart eq '-1';
 6463:             ($trole, $group_privs) = split(/\//, $trole);
 6464:             $group_privs = &unescape($group_privs);
 6465:         } else {
 6466:         # Just a normal role, defined in roles.tab
 6467:             ($trole, $tend, $tstart) = split(/_/,$role);
 6468:         }
 6469: 
 6470:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6471:                  $username);
 6472:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6473: 
 6474:         # role expired or not available yet?
 6475:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6476:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6477: 
 6478:         next if $area eq '' or $trole eq '';
 6479: 
 6480:         my $spec = "$trole.$area";
 6481:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6482: 
 6483:         if ($trole =~ /^cr\//) {
 6484:         # Custom role, defined by a user
 6485:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6486:         } elsif ($trole eq 'gr') {
 6487:         # Role of a member in a group, defined within a course/community
 6488:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6489:             next;
 6490:         } else {
 6491:         # Normal role, defined in roles.tab
 6492:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6493:         }
 6494: 
 6495:         my $cid = $tdomain.'_'.$trest;
 6496:         unless ($firstaccchk{$cid}) {
 6497:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6498:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6499:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6500:                         $coursetimerstarts{$cid}{$item}; 
 6501:                 }
 6502:             }
 6503:             $firstaccchk{$cid} = 1;
 6504:         }
 6505:         unless ($timerintchk{$cid}) {
 6506:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6507:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6508:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6509:                        $coursetimerintervals{$cid}{$item};
 6510:                 }
 6511:             }
 6512:             $timerintchk{$cid} = 1;
 6513:         }
 6514:     }
 6515: 
 6516:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6517:                                                           \%allroles, \%allgroups);
 6518:     $env{'user.adv'} = $userroles{'user.adv'};
 6519:     $env{'user.rar'} = $userroles{'user.rar'};
 6520: 
 6521:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6522: }
 6523: 
 6524: sub set_arearole {
 6525:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6526:     unless ($nolog) {
 6527: # log the associated role with the area
 6528:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6529:     }
 6530:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6531: }
 6532: 
 6533: sub custom_roleprivs {
 6534:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6535:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6536:     my $homsvr = &homeserver($rauthor,$rdomain);
 6537:     if (&hostname($homsvr) ne '') {
 6538:         my ($rdummy,$roledef)=
 6539:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6540:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6541:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6542:             if (defined($syspriv)) {
 6543:                 if ($trest =~ /^$match_community$/) {
 6544:                     $syspriv =~ s/bre\&S//; 
 6545:                 }
 6546:                 $$allroles{'cm./'}.=':'.$syspriv;
 6547:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6548:             }
 6549:             if ($tdomain ne '') {
 6550:                 if (defined($dompriv)) {
 6551:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6552:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6553:                 }
 6554:                 if (($trest ne '') && (defined($coursepriv))) {
 6555:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6556:                         my $rolename = $1;
 6557:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6558:                     }
 6559:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6560:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6561:                 }
 6562:             }
 6563:         }
 6564:     }
 6565: }
 6566: 
 6567: sub course_adhocrole_privs {
 6568:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6569:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6570:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6571:         my (%currprivs,%storeprivs);
 6572:         foreach my $item (split(/:/,$coursepriv)) {
 6573:             my ($priv,$restrict) = split(/\&/,$item);
 6574:             $currprivs{$priv} = $restrict;
 6575:         }
 6576:         my (%possadd,%possremove,%full);
 6577:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6578:             my ($priv,$restrict)=split(/\&/,$item);
 6579:             $full{$priv} = $restrict;
 6580:         }
 6581:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6582:              next if ($item eq '');
 6583:              my ($rule,$rest) = split(/=/,$item);
 6584:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6585:              foreach my $priv (split(/:/,$rest)) {
 6586:                  if ($priv ne '') {
 6587:                      if ($rule eq 'off') {
 6588:                          $possremove{$priv} = 1;
 6589:                      } else {
 6590:                          $possadd{$priv} = 1;
 6591:                      }
 6592:                  }
 6593:              }
 6594:          }
 6595:          foreach my $priv (sort(keys(%full))) {
 6596:              if (exists($currprivs{$priv})) {
 6597:                  unless (exists($possremove{$priv})) {
 6598:                      $storeprivs{$priv} = $currprivs{$priv};
 6599:                  }
 6600:              } elsif (exists($possadd{$priv})) {
 6601:                  $storeprivs{$priv} = $full{$priv};
 6602:              }
 6603:          }
 6604:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6605:      }
 6606:      return $coursepriv;
 6607: }
 6608: 
 6609: sub group_roleprivs {
 6610:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6611:     my $access = 1;
 6612:     my $now = time;
 6613:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6614:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6615:     if ($access) {
 6616:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6617:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6618:     }
 6619: }
 6620: 
 6621: sub standard_roleprivs {
 6622:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6623:     if (defined($pr{$trole.':s'})) {
 6624:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6625:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6626:     }
 6627:     if ($tdomain ne '') {
 6628:         if (defined($pr{$trole.':d'})) {
 6629:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6630:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6631:         }
 6632:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6633:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6634:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6635:         }
 6636:     }
 6637: }
 6638: 
 6639: sub set_userprivs {
 6640:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6641:     my $author=0;
 6642:     my $adv=0;
 6643:     my $rar=0;
 6644:     my %grouproles = ();
 6645:     if (keys(%{$allgroups}) > 0) {
 6646:         my @groupkeys; 
 6647:         foreach my $role (keys(%{$allroles})) {
 6648:             push(@groupkeys,$role);
 6649:         }
 6650:         if (ref($groups_roles) eq 'HASH') {
 6651:             foreach my $key (keys(%{$groups_roles})) {
 6652:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6653:                     push(@groupkeys,$key);
 6654:                 }
 6655:             }
 6656:         }
 6657:         if (@groupkeys > 0) {
 6658:             foreach my $role (@groupkeys) {
 6659:                 my ($trole,$area,$sec,$extendedarea);
 6660:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6661:                     $trole = $1;
 6662:                     $area = $2;
 6663:                     $sec = $3;
 6664:                     $extendedarea = $area.$sec;
 6665:                     if (exists($$allgroups{$area})) {
 6666:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6667:                             my $spec = $trole.'.'.$extendedarea;
 6668:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6669:                                                 $$allgroups{$area}{$group};
 6670:                         }
 6671:                     }
 6672:                 }
 6673:             }
 6674:         }
 6675:     }
 6676:     foreach my $group (keys(%grouproles)) {
 6677:         $$allroles{$group} = $grouproles{$group};
 6678:     }
 6679:     foreach my $role (keys(%{$allroles})) {
 6680:         my %thesepriv;
 6681:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6682:         foreach my $item (split(/:/,$$allroles{$role})) {
 6683:             if ($item ne '') {
 6684:                 my ($privilege,$restrictions)=split(/&/,$item);
 6685:                 if ($restrictions eq '') {
 6686:                     $thesepriv{$privilege}='F';
 6687:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6688:                     $thesepriv{$privilege}.=$restrictions;
 6689:                 }
 6690:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6691:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6692:             }
 6693:         }
 6694:         my $thesestr='';
 6695:         foreach my $priv (sort(keys(%thesepriv))) {
 6696: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6697: 	}
 6698:         $userroles->{'user.priv.'.$role} = $thesestr;
 6699:     }
 6700:     return ($author,$adv,$rar);
 6701: }
 6702: 
 6703: sub role_status {
 6704:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6705:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6706:         my ($one,$two) = split(m{\./},$rolekey,2);
 6707:         (undef,undef,$$role) = split(/\./,$one,3);
 6708:         unless (!defined($$role) || $$role eq '') {
 6709:             $$where = '/'.$two;
 6710:             $$trolecode=$$role.'.'.$$where;
 6711:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6712:             $$tstatus='is';
 6713:             if ($$tstart && $$tstart>$update) {
 6714:                 $$tstatus='future';
 6715:                 if ($$tstart<$now) {
 6716:                     if ($$tstart && $$tstart>$refresh) {
 6717:                         if (($$where ne '') && ($$role ne '')) {
 6718:                             my (%allroles,%allgroups,$group_privs,
 6719:                                 %groups_roles,@rolecodes);
 6720:                             my %userroles = (
 6721:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6722:                             );
 6723:                             @rolecodes = ('cm'); 
 6724:                             my $spec=$$role.'.'.$$where;
 6725:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6726:                             if ($$role =~ /^cr\//) {
 6727:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6728:                                 push(@rolecodes,'cr');
 6729:                             } elsif ($$role eq 'gr') {
 6730:                                 push(@rolecodes,$$role);
 6731:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6732:                                                     $env{'user.name'});
 6733:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6734:                                 (undef,my $group_privs) = split(/\//,$trole);
 6735:                                 $group_privs = &unescape($group_privs);
 6736:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6737:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6738:                                 &get_groups_roles($tdomain,$trest,
 6739:                                                   \%course_roles,\@rolecodes,
 6740:                                                   \%groups_roles);
 6741:                             } else {
 6742:                                 push(@rolecodes,$$role);
 6743:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6744:                             }
 6745:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6746:                                                                    \%groups_roles);
 6747:                             &appenv(\%userroles,\@rolecodes);
 6748:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6749:                         }
 6750:                     }
 6751:                     $$tstatus = 'is';
 6752:                 }
 6753:             }
 6754:             if ($$tend) {
 6755:                 if ($$tend<$update) {
 6756:                     $$tstatus='expired';
 6757:                 } elsif ($$tend<$now) {
 6758:                     $$tstatus='will_not';
 6759:                 }
 6760:             }
 6761:         }
 6762:     }
 6763: }
 6764: 
 6765: sub get_groups_roles {
 6766:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6767:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6768:                   (ref($rolecodes) eq 'ARRAY') && 
 6769:                   (ref($groups_roles) eq 'HASH')); 
 6770:     if (keys(%{$cdom_courseroles}) > 0) {
 6771:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6772:         if ($cdom ne '' && $cnum ne '') {
 6773:             foreach my $key (keys(%{$cdom_courseroles})) {
 6774:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6775:                     my $crsrole = $1;
 6776:                     my $crssec = $2;
 6777:                     if ($crsrole =~ /^cr/) {
 6778:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6779:                             push(@{$rolecodes},'cr');
 6780:                         }
 6781:                     } else {
 6782:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6783:                             push(@{$rolecodes},$crsrole);
 6784:                         }
 6785:                     }
 6786:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6787:                     if ($crssec ne '') {
 6788:                         $rolekey .= "/$crssec";
 6789:                     }
 6790:                     $rolekey .= './';
 6791:                     $groups_roles->{$rolekey} = $rolecodes;
 6792:                 }
 6793:             }
 6794:         }
 6795:     }
 6796:     return;
 6797: }
 6798: 
 6799: sub delete_env_groupprivs {
 6800:     my ($where,$courseroles,$possroles) = @_;
 6801:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6802:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6803:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6804:         %{$courseroles->{$udom}} =
 6805:             &get_my_roles('','','userroles',['active'],
 6806:                           $possroles,[$udom],1);
 6807:     }
 6808:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6809:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6810:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6811:             my $area = '/'.$cdom.'/'.$cnum;
 6812:             my $privkey = "user.priv.$crsrole.$area";
 6813:             if ($crssec ne '') {
 6814:                 $privkey .= '/'.$crssec;
 6815:             }
 6816:             $privkey .= ".$area/$group";
 6817:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6818:         }
 6819:     }
 6820:     return;
 6821: }
 6822: 
 6823: sub check_adhoc_privs {
 6824:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6825:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6826:     if ($sec) {
 6827:         $cckey .= '/'.$sec;
 6828:     }
 6829:     my $setprivs;
 6830:     if ($env{$cckey}) {
 6831:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6832:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6833:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6834:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6835:             $setprivs = 1;
 6836:         }
 6837:     } else {
 6838:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6839:         $setprivs = 1;
 6840:     }
 6841:     return $setprivs;
 6842: }
 6843: 
 6844: sub set_adhoc_privileges {
 6845: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6846:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6847:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6848:     if ($sec ne '') {
 6849:         $area .= '/'.$sec;
 6850:     }
 6851:     my $spec = $role.'.'.$area;
 6852:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6853:                                   $env{'user.name'},1);
 6854:     my %rolehash = ();
 6855:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6856:         my $rolename = $1;
 6857:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6858:         my %domdef = &get_domain_defaults($dcdom);
 6859:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6860:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6861:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6862:             }
 6863:         }
 6864:     } else {
 6865:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6866:     }
 6867:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6868:     &appenv(\%userroles,[$role,'cm']);
 6869:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6870:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 6871:             ($caller eq 'tiny')) {
 6872:         &appenv( {'request.role'        => $spec,
 6873:                   'request.role.domain' => $dcdom,
 6874:                   'request.course.sec'  => $sec, 
 6875:                  }
 6876:                );
 6877:         my $tadv=0;
 6878:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6879:         &appenv({'request.role.adv'    => $tadv});
 6880:     }
 6881: }
 6882: 
 6883: # --------------------------------------------------------------- get interface
 6884: 
 6885: sub get {
 6886:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6887:    my $items='';
 6888:    foreach my $item (@$storearr) {
 6889:        $items.=&escape($item).'&';
 6890:    }
 6891:    $items=~s/\&$//;
 6892:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6893:    if (!$uname) { $uname=$env{'user.name'}; }
 6894:    my $uhome=&homeserver($uname,$udomain);
 6895: 
 6896:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6897:    my @pairs=split(/\&/,$rep);
 6898:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6899:      return @pairs;
 6900:    }
 6901:    my %returnhash=();
 6902:    my $i=0;
 6903:    foreach my $item (@$storearr) {
 6904:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6905:       $i++;
 6906:    }
 6907:    return %returnhash;
 6908: }
 6909: 
 6910: # --------------------------------------------------------------- del interface
 6911: 
 6912: sub del {
 6913:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6914:    my $items='';
 6915:    foreach my $item (@$storearr) {
 6916:        $items.=&escape($item).'&';
 6917:    }
 6918: 
 6919:    $items=~s/\&$//;
 6920:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6921:    if (!$uname) { $uname=$env{'user.name'}; }
 6922:    my $uhome=&homeserver($uname,$udomain);
 6923:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6924: }
 6925: 
 6926: # -------------------------------------------------------------- dump interface
 6927: 
 6928: sub unserialize {
 6929:     my ($rep, $escapedkeys) = @_;
 6930: 
 6931:     return {} if $rep =~ /^error/;
 6932: 
 6933:     my %returnhash=();
 6934:     foreach my $item (split(/\&/,$rep)) {
 6935:         my ($key, $value) = split(/=/, $item, 2);
 6936:         $key = unescape($key) unless $escapedkeys;
 6937:         next if $key =~ /^error: 2 /;
 6938:         $returnhash{$key} = &thaw_unescape($value);
 6939:     }
 6940:     return \%returnhash;
 6941: }
 6942: 
 6943: # see Lond::dump_with_regexp
 6944: # if $escapedkeys hash keys won't get unescaped.
 6945: sub dump {
 6946:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
 6947:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6948:     if (!$uname) { $uname=$env{'user.name'}; }
 6949:     my $uhome=&homeserver($uname,$udomain);
 6950: 
 6951:     if ($regexp) {
 6952:         $regexp=&escape($regexp);
 6953:     } else {
 6954:         $regexp='.';
 6955:     }
 6956:     if (grep { $_ eq $uhome } &current_machine_ids()) {
 6957:         # user is hosted on this machine
 6958:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
 6959:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6960:         return %{&unserialize($reply, $escapedkeys)};
 6961:     }
 6962:     my $rep;
 6963:     if ($encrypt) {
 6964:         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6965:     } else {
 6966:         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6967:     }
 6968:     my @pairs=split(/\&/,$rep);
 6969:     my %returnhash=();
 6970:     if (!($rep =~ /^error/ )) {
 6971: 	foreach my $item (@pairs) {
 6972: 	    my ($key,$value)=split(/=/,$item,2);
 6973:             $key = &unescape($key) unless ($escapedkeys);
 6974: 	    next if ($key =~ /^error: 2 /);
 6975: 	    $returnhash{$key}=&thaw_unescape($value);
 6976: 	}
 6977:     }
 6978:     return %returnhash;
 6979: }
 6980: 
 6981: 
 6982: # --------------------------------------------------------- dumpstore interface
 6983: 
 6984: sub dumpstore {
 6985:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6986:    # same as dump but keys must be escaped. They may contain colon separated
 6987:    # lists of values that may themself contain colons (e.g. symbs).
 6988:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6989: }
 6990: 
 6991: # -------------------------------------------------------------- keys interface
 6992: 
 6993: sub getkeys {
 6994:    my ($namespace,$udomain,$uname)=@_;
 6995:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6996:    if (!$uname) { $uname=$env{'user.name'}; }
 6997:    my $uhome=&homeserver($uname,$udomain);
 6998:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6999:    my @keyarray=();
 7000:    foreach my $key (split(/\&/,$rep)) {
 7001:       next if ($key =~ /^error: 2 /);
 7002:       push(@keyarray,&unescape($key));
 7003:    }
 7004:    return @keyarray;
 7005: }
 7006: 
 7007: # --------------------------------------------------------------- currentdump
 7008: sub currentdump {
 7009:    my ($courseid,$sdom,$sname)=@_;
 7010:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 7011:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 7012:    $sname    = $env{'user.name'}         if (! defined($sname));
 7013:    my $uhome = &homeserver($sname,$sdom);
 7014:    my $rep;
 7015: 
 7016:    if (grep { $_ eq $uhome } current_machine_ids()) {
 7017:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
 7018:                    $courseid)));
 7019:    } else {
 7020:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 7021:    }
 7022: 
 7023:    return if ($rep =~ /^(error:|no_such_host)/);
 7024:    #
 7025:    my %returnhash=();
 7026:    #
 7027:    if ($rep eq "unknown_cmd") { 
 7028:        # an old lond will not know currentdump
 7029:        # Do a dump and make it look like a currentdump
 7030:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 7031:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 7032:        my %hash = @tmp;
 7033:        @tmp=();
 7034:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7035:    } else {
 7036:        my @pairs=split(/\&/,$rep);
 7037:        foreach my $pair (@pairs) {
 7038:            my ($key,$value)=split(/=/,$pair,2);
 7039:            my ($symb,$param) = split(/:/,$key);
 7040:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7041:                                                         &thaw_unescape($value);
 7042:        }
 7043:    }
 7044:    return %returnhash;
 7045: }
 7046: 
 7047: sub convert_dump_to_currentdump{
 7048:     my %hash = %{shift()};
 7049:     my %returnhash;
 7050:     # Code ripped from lond, essentially.  The only difference
 7051:     # here is the unescaping done by lonnet::dump().  Conceivably
 7052:     # we might run in to problems with parameter names =~ /^v\./
 7053:     while (my ($key,$value) = each(%hash)) {
 7054:         my ($v,$symb,$param) = split(/:/,$key);
 7055: 	$symb  = &unescape($symb);
 7056: 	$param = &unescape($param);
 7057:         next if ($v eq 'version' || $symb eq 'keys');
 7058:         next if (exists($returnhash{$symb}) &&
 7059:                  exists($returnhash{$symb}->{$param}) &&
 7060:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7061:         $returnhash{$symb}->{$param}=$value;
 7062:         $returnhash{$symb}->{'v.'.$param}=$v;
 7063:     }
 7064:     #
 7065:     # Remove all of the keys in the hashes which keep track of
 7066:     # the version of the parameter.
 7067:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7068:         # use a foreach because we are going to delete from the hash.
 7069:         foreach my $key (keys(%$param_hash)) {
 7070:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7071:         }
 7072:     }
 7073:     return \%returnhash;
 7074: }
 7075: 
 7076: # ------------------------------------------------------ critical inc interface
 7077: 
 7078: sub cinc {
 7079:     return &inc(@_,'critical');
 7080: }
 7081: 
 7082: # --------------------------------------------------------------- inc interface
 7083: 
 7084: sub inc {
 7085:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7086:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7087:     if (!$uname) { $uname=$env{'user.name'}; }
 7088:     my $uhome=&homeserver($uname,$udomain);
 7089:     my $items='';
 7090:     if (! ref($store)) {
 7091:         # got a single value, so use that instead
 7092:         $items = &escape($store).'=&';
 7093:     } elsif (ref($store) eq 'SCALAR') {
 7094:         $items = &escape($$store).'=&';        
 7095:     } elsif (ref($store) eq 'ARRAY') {
 7096:         $items = join('=&',map {&escape($_);} @{$store});
 7097:     } elsif (ref($store) eq 'HASH') {
 7098:         while (my($key,$value) = each(%{$store})) {
 7099:             $items.= &escape($key).'='.&escape($value).'&';
 7100:         }
 7101:     }
 7102:     $items=~s/\&$//;
 7103:     if ($critical) {
 7104: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7105:     } else {
 7106: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7107:     }
 7108: }
 7109: 
 7110: # --------------------------------------------------------------- put interface
 7111: 
 7112: sub put {
 7113:    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
 7114:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7115:    if (!$uname) { $uname=$env{'user.name'}; }
 7116:    my $uhome=&homeserver($uname,$udomain);
 7117:    my $items='';
 7118:    foreach my $item (keys(%$storehash)) {
 7119:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7120:    }
 7121:    $items=~s/\&$//;
 7122:    if ($encrypt) {
 7123:        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
 7124:    } else {
 7125:        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7126:    }
 7127: }
 7128: 
 7129: # ------------------------------------------------------------ newput interface
 7130: 
 7131: sub newput {
 7132:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7133:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7134:    if (!$uname) { $uname=$env{'user.name'}; }
 7135:    my $uhome=&homeserver($uname,$udomain);
 7136:    my $items='';
 7137:    foreach my $key (keys(%$storehash)) {
 7138:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7139:    }
 7140:    $items=~s/\&$//;
 7141:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7142: }
 7143: 
 7144: # ---------------------------------------------------------  putstore interface
 7145: 
 7146: sub putstore {
 7147:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7148:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7149:    if (!$uname) { $uname=$env{'user.name'}; }
 7150:    my $uhome=&homeserver($uname,$udomain);
 7151:    my $items='';
 7152:    foreach my $key (keys(%$storehash)) {
 7153:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7154:    }
 7155:    $items=~s/\&$//;
 7156:    my $esc_symb=&escape($symb);
 7157:    my $esc_v=&escape($version);
 7158:    my $reply =
 7159:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7160: 	      $uhome);
 7161:    if (($tolog) && ($reply eq 'ok')) {
 7162:        my $namevalue='';
 7163:        foreach my $key (keys(%{$storehash})) {
 7164:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7165:        }
 7166:        my $ip = &get_requestor_ip();
 7167:        $namevalue .= 'ip='.&escape($ip).
 7168:                      '&host='.&escape($perlvar{'lonHostID'}).
 7169:                      '&version='.$esc_v.
 7170:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7171:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7172:    }
 7173:    if ($reply eq 'unknown_cmd') {
 7174:        # gfall back to way things use to be done
 7175:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7176: 			    $uname);
 7177:    }
 7178:    return $reply;
 7179: }
 7180: 
 7181: sub old_putstore {
 7182:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7183:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7184:     if (!$uname) { $uname=$env{'user.name'}; }
 7185:     my $uhome=&homeserver($uname,$udomain);
 7186:     my %newstorehash;
 7187:     foreach my $item (keys(%$storehash)) {
 7188: 	my $key = $version.':'.&escape($symb).':'.$item;
 7189: 	$newstorehash{$key} = $storehash->{$item};
 7190:     }
 7191:     my $items='';
 7192:     my %allitems = ();
 7193:     foreach my $item (keys(%newstorehash)) {
 7194: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7195: 	    my $key = $1.':keys:'.$2;
 7196: 	    $allitems{$key} .= $3.':';
 7197: 	}
 7198: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7199:     }
 7200:     foreach my $item (keys(%allitems)) {
 7201: 	$allitems{$item} =~ s/\:$//;
 7202: 	$items.= $item.'='.$allitems{$item}.'&';
 7203:     }
 7204:     $items=~s/\&$//;
 7205:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7206: }
 7207: 
 7208: # ------------------------------------------------------ critical put interface
 7209: 
 7210: sub cput {
 7211:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7212:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7213:    if (!$uname) { $uname=$env{'user.name'}; }
 7214:    my $uhome=&homeserver($uname,$udomain);
 7215:    my $items='';
 7216:    foreach my $item (keys(%$storehash)) {
 7217:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7218:    }
 7219:    $items=~s/\&$//;
 7220:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7221: }
 7222: 
 7223: # -------------------------------------------------------------- eget interface
 7224: 
 7225: sub eget {
 7226:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7227:    my $items='';
 7228:    foreach my $item (@$storearr) {
 7229:        $items.=&escape($item).'&';
 7230:    }
 7231:    $items=~s/\&$//;
 7232:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7233:    if (!$uname) { $uname=$env{'user.name'}; }
 7234:    my $uhome=&homeserver($uname,$udomain);
 7235:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7236:    my @pairs=split(/\&/,$rep);
 7237:    my %returnhash=();
 7238:    my $i=0;
 7239:    foreach my $item (@$storearr) {
 7240:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7241:       $i++;
 7242:    }
 7243:    return %returnhash;
 7244: }
 7245: 
 7246: # ------------------------------------------------------------ tmpput interface
 7247: sub tmpput {
 7248:     my ($storehash,$server,$context)=@_;
 7249:     my $items='';
 7250:     foreach my $item (keys(%$storehash)) {
 7251: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7252:     }
 7253:     $items=~s/\&$//;
 7254:     if (defined($context)) {
 7255:         $items .= ':'.&escape($context);
 7256:     }
 7257:     return &reply("tmpput:$items",$server);
 7258: }
 7259: 
 7260: # ------------------------------------------------------------ tmpget interface
 7261: sub tmpget {
 7262:     my ($token,$server)=@_;
 7263:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7264:     my $rep=&reply("tmpget:$token",$server);
 7265:     my %returnhash;
 7266:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7267:         return %returnhash;
 7268:     }
 7269:     foreach my $item (split(/\&/,$rep)) {
 7270: 	my ($key,$value)=split(/=/,$item);
 7271: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7272:     }
 7273:     return %returnhash;
 7274: }
 7275: 
 7276: # ------------------------------------------------------------ tmpdel interface
 7277: sub tmpdel {
 7278:     my ($token,$server)=@_;
 7279:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7280:     return &reply("tmpdel:$token",$server);
 7281: }
 7282: 
 7283: # ------------------------------------------------------------ get_timebased_id
 7284: 
 7285: sub get_timebased_id {
 7286:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7287:         $maxtries) = @_;
 7288:     my ($newid,$error,$dellock);
 7289:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
 7290:         return ('','ok','invalid call to get suffix');
 7291:     }
 7292: 
 7293: # set defaults for any optional args for which values were not supplied
 7294:     if ($who eq '') {
 7295:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7296:     }
 7297:     if (!$locktries) {
 7298:         $locktries = 3;
 7299:     }
 7300:     if (!$maxtries) {
 7301:         $maxtries = 10;
 7302:     }
 7303: 
 7304:     if (($cdom eq '') || ($cnum eq '')) {
 7305:         if ($env{'request.course.id'}) {
 7306:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7307:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7308:         }
 7309:         if (($cdom eq '') || ($cnum eq '')) {
 7310:             return ('','ok','call to get suffix not in course context');
 7311:         }
 7312:     }
 7313: 
 7314: # construct locking item
 7315:     my $lockhash = {
 7316:                       $prefix."\0".'locked_'.$keyid => $who,
 7317:                    };
 7318:     my $tries = 0;
 7319: 
 7320: # attempt to get lock on nohist_$namespace file
 7321:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7322:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7323:         $tries ++;
 7324:         sleep 1;
 7325:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7326:     }
 7327: 
 7328: # attempt to get unique identifier, based on current timestamp
 7329:     if ($gotlock eq 'ok') {
 7330:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7331:         my $id = time;
 7332:         $newid = $id;
 7333:         if ($idtype eq 'addcode') {
 7334:             $newid .= &sixnum_code();
 7335:         }
 7336:         my $idtries = 0;
 7337:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7338:             if ($idtype eq 'concat') {
 7339:                 $newid = $id.$idtries;
 7340:             } elsif ($idtype eq 'addcode') {
 7341:                 $newid = $newid.&sixnum_code();
 7342:             } else {
 7343:                 $newid ++;
 7344:             }
 7345:             $idtries ++;
 7346:         }
 7347:         if (!exists($inuse{$prefix."\0".$newid})) {
 7348:             my %new_item =  (
 7349:                               $prefix."\0".$newid => $who,
 7350:                             );
 7351:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7352:                                                  $cdom,$cnum);
 7353:             if ($putresult ne 'ok') {
 7354:                 undef($newid);
 7355:                 $error = 'error saving new item: '.$putresult;
 7356:             }
 7357:         } else {
 7358:              undef($newid);
 7359:              $error = ('error: no unique suffix available for the new item ');
 7360:         }
 7361: #  remove lock
 7362:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7363:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7364:     } else {
 7365:         $error = "error: could not obtain lockfile\n";
 7366:         $dellock = 'ok';
 7367:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7368:             $dellock = 'nolock';
 7369:         }
 7370:     }
 7371:     return ($newid,$dellock,$error);
 7372: }
 7373: 
 7374: sub sixnum_code {
 7375:     my $code;
 7376:     for (0..6) {
 7377:         $code .= int( rand(9) );
 7378:     }
 7379:     return $code;
 7380: }
 7381: 
 7382: # -------------------------------------------------- portfolio access checking
 7383: 
 7384: sub portfolio_access {
 7385:     my ($requrl,$clientip) = @_;
 7386:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7387:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7388:     if ($result) {
 7389:         my %setters;
 7390:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7391:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7392:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
 7393:             if (($startblock && $endblock) || ($by_ip))  {
 7394:                 return 'B';
 7395:             }
 7396:         } else {
 7397:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdo) =
 7398:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 7399:             if (($startblock && $endblock) || ($by_ip)) {
 7400:                 return 'B';
 7401:             }
 7402:         }
 7403:     }
 7404:     if ($result eq 'ok') {
 7405:        return 'F';
 7406:     } elsif ($result =~ /^[^:]+:guest_/) {
 7407:        return 'A';
 7408:     }
 7409:     return '';
 7410: }
 7411: 
 7412: sub get_portfolio_access {
 7413:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7414: 
 7415:     if (!ref($access_hash)) {
 7416: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7417: 	my %access_controls = &get_access_controls($current_perms,$group,
 7418: 						   $file_name);
 7419: 	$access_hash = $access_controls{$file_name};
 7420:     }
 7421: 
 7422:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7423:     my $now = time;
 7424:     if (ref($access_hash) eq 'HASH') {
 7425:         foreach my $key (keys(%{$access_hash})) {
 7426:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7427:             if ($start > $now) {
 7428:                 next;
 7429:             }
 7430:             if ($end && $end<$now) {
 7431:                 next;
 7432:             }
 7433:             if ($scope eq 'public') {
 7434:                 $public = $key;
 7435:                 last;
 7436:             } elsif ($scope eq 'guest') {
 7437:                 $guest = $key;
 7438:             } elsif ($scope eq 'domains') {
 7439:                 push(@domains,$key);
 7440:             } elsif ($scope eq 'users') {
 7441:                 push(@users,$key);
 7442:             } elsif ($scope eq 'course') {
 7443:                 push(@courses,$key);
 7444:             } elsif ($scope eq 'group') {
 7445:                 push(@groups,$key);
 7446:             } elsif ($scope eq 'ip') {
 7447:                 push(@ips,$key);
 7448:             }
 7449:         }
 7450:         if ($public) {
 7451:             return 'ok';
 7452:         } elsif (@ips > 0) {
 7453:             my $allowed;
 7454:             foreach my $ipkey (@ips) {
 7455:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7456:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7457:                         $allowed = 1;
 7458:                         last;
 7459:                     }
 7460:                 }
 7461:             }
 7462:             if ($allowed) {
 7463:                 return 'ok';
 7464:             }
 7465:         }
 7466:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7467:             if ($guest) {
 7468:                 return $guest;
 7469:             }
 7470:         } else {
 7471:             if (@domains > 0) {
 7472:                 foreach my $domkey (@domains) {
 7473:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7474:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7475:                             return 'ok';
 7476:                         }
 7477:                     }
 7478:                 }
 7479:             }
 7480:             if (@users > 0) {
 7481:                 foreach my $userkey (@users) {
 7482:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7483:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7484:                             if (ref($item) eq 'HASH') {
 7485:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7486:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7487:                                     return 'ok';
 7488:                                 }
 7489:                             }
 7490:                         }
 7491:                     } 
 7492:                 }
 7493:             }
 7494:             my %roleshash;
 7495:             my @courses_and_groups = @courses;
 7496:             push(@courses_and_groups,@groups); 
 7497:             if (@courses_and_groups > 0) {
 7498:                 my (%allgroups,%allroles); 
 7499:                 my ($start,$end,$role,$sec,$group);
 7500:                 foreach my $envkey (%env) {
 7501:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7502:                         my $cid = $2.'_'.$3; 
 7503:                         if ($1 eq 'gr') {
 7504:                             $group = $4;
 7505:                             $allgroups{$cid}{$group} = $env{$envkey};
 7506:                         } else {
 7507:                             if ($4 eq '') {
 7508:                                 $sec = 'none';
 7509:                             } else {
 7510:                                 $sec = $4;
 7511:                             }
 7512:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7513:                         }
 7514:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7515:                         my $cid = $2.'_'.$3;
 7516:                         if ($4 eq '') {
 7517:                             $sec = 'none';
 7518:                         } else {
 7519:                             $sec = $4;
 7520:                         }
 7521:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7522:                     }
 7523:                 }
 7524:                 if (keys(%allroles) == 0) {
 7525:                     return;
 7526:                 }
 7527:                 foreach my $key (@courses_and_groups) {
 7528:                     my %content = %{$$access_hash{$key}};
 7529:                     my $cnum = $content{'number'};
 7530:                     my $cdom = $content{'domain'};
 7531:                     my $cid = $cdom.'_'.$cnum;
 7532:                     if (!exists($allroles{$cid})) {
 7533:                         next;
 7534:                     }    
 7535:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7536:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7537:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7538:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7539:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7540:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7541:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7542:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7543:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7544:                                         if (grep/^all$/,@sections) {
 7545:                                             return 'ok';
 7546:                                         } else {
 7547:                                             if (grep/^$sec$/,@sections) {
 7548:                                                 return 'ok';
 7549:                                             }
 7550:                                         }
 7551:                                     }
 7552:                                 }
 7553:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7554:                                     if (grep/^none$/,@groups) {
 7555:                                         return 'ok';
 7556:                                     }
 7557:                                 } else {
 7558:                                     if (grep/^all$/,@groups) {
 7559:                                         return 'ok';
 7560:                                     } 
 7561:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7562:                                         if (grep/^$group$/,@groups) {
 7563:                                             return 'ok';
 7564:                                         }
 7565:                                     }
 7566:                                 } 
 7567:                             }
 7568:                         }
 7569:                     }
 7570:                 }
 7571:             }
 7572:             if ($guest) {
 7573:                 return $guest;
 7574:             }
 7575:         }
 7576:     }
 7577:     return;
 7578: }
 7579: 
 7580: sub course_group_datechecker {
 7581:     my ($dates,$now,$status) = @_;
 7582:     my ($start,$end) = split(/\./,$dates);
 7583:     if (!$start && !$end) {
 7584:         return 'ok';
 7585:     }
 7586:     if (grep/^active$/,@{$status}) {
 7587:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7588:             return 'ok';
 7589:         }
 7590:     }
 7591:     if (grep/^previous$/,@{$status}) {
 7592:         if ($end > $now ) {
 7593:             return 'ok';
 7594:         }
 7595:     }
 7596:     if (grep/^future$/,@{$status}) {
 7597:         if ($start > $now) {
 7598:             return 'ok';
 7599:         }
 7600:     }
 7601:     return; 
 7602: }
 7603: 
 7604: sub parse_portfolio_url {
 7605:     my ($url) = @_;
 7606: 
 7607:     my ($type,$udom,$unum,$group,$file_name);
 7608:     
 7609:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7610: 	$type = 1;
 7611:         $udom = $1;
 7612:         $unum = $2;
 7613:         $file_name = $3;
 7614:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7615: 	$type = 2;
 7616:         $udom = $1;
 7617:         $unum = $2;
 7618:         $group = $3;
 7619:         $file_name = $3.'/'.$4;
 7620:     }
 7621:     if (wantarray) {
 7622: 	return ($type,$udom,$unum,$file_name,$group);
 7623:     }
 7624:     return $type;
 7625: }
 7626: 
 7627: sub is_portfolio_url {
 7628:     my ($url) = @_;
 7629:     return scalar(&parse_portfolio_url($url));
 7630: }
 7631: 
 7632: sub is_portfolio_file {
 7633:     my ($file) = @_;
 7634:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7635:         return 1;
 7636:     }
 7637:     return;
 7638: }
 7639: 
 7640: sub usertools_access {
 7641:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7642:     my ($access,%tools);
 7643:     if ($context eq '') {
 7644:         $context = 'tools';
 7645:     }
 7646:     if ($context eq 'requestcourses') {
 7647:         %tools = (
 7648:                       official   => 1,
 7649:                       unofficial => 1,
 7650:                       community  => 1,
 7651:                       textbook   => 1,
 7652:                  );
 7653:     } elsif ($context eq 'requestauthor') {
 7654:         %tools = (
 7655:                       requestauthor => 1,
 7656:                  );
 7657:     } else {
 7658:         %tools = (
 7659:                       aboutme   => 1,
 7660:                       blog      => 1,
 7661:                       webdav    => 1,
 7662:                       portfolio => 1,
 7663:                  );
 7664:     }
 7665:     return if (!defined($tools{$tool}));
 7666: 
 7667:     if (($udom eq '') || ($uname eq '')) {
 7668:         $udom = $env{'user.domain'};
 7669:         $uname = $env{'user.name'};
 7670:     }
 7671: 
 7672:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7673:         if ($action ne 'reload') {
 7674:             if ($context eq 'requestcourses') {
 7675:                 return $env{'environment.canrequest.'.$tool};
 7676:             } elsif ($context eq 'requestauthor') {
 7677:                 return $env{'environment.canrequest.author'};
 7678:             } else {
 7679:                 return $env{'environment.availabletools.'.$tool};
 7680:             }
 7681:         }
 7682:     }
 7683: 
 7684:     my ($toolstatus,$inststatus,$envkey);
 7685:     if ($context eq 'requestauthor') {
 7686:         $envkey = $context;
 7687:     } else {
 7688:         $envkey = $context.'.'.$tool;
 7689:     }
 7690: 
 7691:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7692:          ($action ne 'reload')) {
 7693:         $toolstatus = $env{'environment.'.$envkey};
 7694:         $inststatus = $env{'environment.inststatus'};
 7695:     } else {
 7696:         if (ref($userenvref) eq 'HASH') {
 7697:             $toolstatus = $userenvref->{$envkey};
 7698:             $inststatus = $userenvref->{'inststatus'};
 7699:         } else {
 7700:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7701:             $toolstatus = $userenv{$envkey};
 7702:             $inststatus = $userenv{'inststatus'};
 7703:         }
 7704:     }
 7705: 
 7706:     if ($toolstatus ne '') {
 7707:         if ($toolstatus) {
 7708:             $access = 1;
 7709:         } else {
 7710:             $access = 0;
 7711:         }
 7712:         return $access;
 7713:     }
 7714: 
 7715:     my ($is_adv,%domdef);
 7716:     if (ref($is_advref) eq 'HASH') {
 7717:         $is_adv = $is_advref->{'is_adv'};
 7718:     } else {
 7719:         $is_adv = &is_advanced_user($udom,$uname);
 7720:     }
 7721:     if (ref($domdefref) eq 'HASH') {
 7722:         %domdef = %{$domdefref};
 7723:     } else {
 7724:         %domdef = &get_domain_defaults($udom);
 7725:     }
 7726:     if (ref($domdef{$tool}) eq 'HASH') {
 7727:         if ($is_adv) {
 7728:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7729:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7730:                     $access = 1;
 7731:                 } else {
 7732:                     $access = 0;
 7733:                 }
 7734:                 return $access;
 7735:             }
 7736:         }
 7737:         if ($inststatus ne '') {
 7738:             my ($hasaccess,$hasnoaccess);
 7739:             foreach my $affiliation (split(/:/,$inststatus)) {
 7740:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7741:                     if ($domdef{$tool}{$affiliation}) {
 7742:                         $hasaccess = 1;
 7743:                     } else {
 7744:                         $hasnoaccess = 1;
 7745:                     }
 7746:                 }
 7747:             }
 7748:             if ($hasaccess || $hasnoaccess) {
 7749:                 if ($hasaccess) {
 7750:                     $access = 1;
 7751:                 } elsif ($hasnoaccess) {
 7752:                     $access = 0; 
 7753:                 }
 7754:                 return $access;
 7755:             }
 7756:         } else {
 7757:             if ($domdef{$tool}{'default'} ne '') {
 7758:                 if ($domdef{$tool}{'default'}) {
 7759:                     $access = 1;
 7760:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7761:                     $access = 0;
 7762:                 }
 7763:                 return $access;
 7764:             }
 7765:         }
 7766:     } else {
 7767:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7768:             $access = 1;
 7769:         } else {
 7770:             $access = 0;
 7771:         }
 7772:         return $access;
 7773:     }
 7774: }
 7775: 
 7776: sub is_course_owner {
 7777:     my ($cdom,$cnum,$udom,$uname) = @_;
 7778:     if (($udom eq '') || ($uname eq '')) {
 7779:         $udom = $env{'user.domain'};
 7780:         $uname = $env{'user.name'};
 7781:     }
 7782:     unless (($udom eq '') || ($uname eq '')) {
 7783:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7784:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7785:                 return 1;
 7786:             } else {
 7787:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7788:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7789:                     return 1;
 7790:                 }
 7791:             }
 7792:         }
 7793:     }
 7794:     return;
 7795: }
 7796: 
 7797: sub is_advanced_user {
 7798:     my ($udom,$uname) = @_;
 7799:     if ($udom ne '' && $uname ne '') {
 7800:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7801:             if (wantarray) {
 7802:                 return ($env{'user.adv'},$env{'user.author'});
 7803:             } else {
 7804:                 return $env{'user.adv'};
 7805:             }
 7806:         }
 7807:     }
 7808:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7809:     my %allroles;
 7810:     my ($is_adv,$is_author);
 7811:     foreach my $role (keys(%roleshash)) {
 7812:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7813:         my $area = '/'.$tdomain.'/'.$trest;
 7814:         if ($sec ne '') {
 7815:             $area .= '/'.$sec;
 7816:         }
 7817:         if (($area ne '') && ($trole ne '')) {
 7818:             my $spec=$trole.'.'.$area;
 7819:             if ($trole =~ /^cr\//) {
 7820:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7821:             } elsif ($trole ne 'gr') {
 7822:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7823:             }
 7824:             if ($trole eq 'au') {
 7825:                 $is_author = 1;
 7826:             }
 7827:         }
 7828:     }
 7829:     foreach my $role (keys(%allroles)) {
 7830:         last if ($is_adv);
 7831:         foreach my $item (split(/:/,$allroles{$role})) {
 7832:             if ($item ne '') {
 7833:                 my ($privilege,$restrictions)=split(/&/,$item);
 7834:                 if ($privilege eq 'adv') {
 7835:                     $is_adv = 1;
 7836:                     last;
 7837:                 }
 7838:             }
 7839:         }
 7840:     }
 7841:     if (wantarray) {
 7842:         return ($is_adv,$is_author);
 7843:     }
 7844:     return $is_adv;
 7845: }
 7846: 
 7847: sub check_can_request {
 7848:     my ($dom,$can_request,$request_domains) = @_;
 7849:     my $canreq = 0;
 7850:     my ($types,$typename) = &Apache::loncommon::course_types();
 7851:     my @options = ('approval','validate','autolimit');
 7852:     my $optregex = join('|',@options);
 7853:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7854:         foreach my $type (@{$types}) {
 7855:             if (&usertools_access($env{'user.name'},
 7856:                                   $env{'user.domain'},
 7857:                                   $type,undef,'requestcourses')) {
 7858:                 $canreq ++;
 7859:                 if (ref($request_domains) eq 'HASH') {
 7860:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 7861:                 }
 7862:                 if ($dom eq $env{'user.domain'}) {
 7863:                     $can_request->{$type} = 1;
 7864:                 }
 7865:             }
 7866:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 7867:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7868:                 if (@curr > 0) {
 7869:                     foreach my $item (@curr) {
 7870:                         if (ref($request_domains) eq 'HASH') {
 7871:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7872:                             if ($otherdom ne '') {
 7873:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7874:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7875:                                         push(@{$request_domains->{$type}},$otherdom);
 7876:                                     }
 7877:                                 } else {
 7878:                                     push(@{$request_domains->{$type}},$otherdom);
 7879:                                 }
 7880:                             }
 7881:                         }
 7882:                     }
 7883:                     unless($dom eq $env{'user.domain'}) {
 7884:                         $canreq ++;
 7885:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7886:                             $can_request->{$type} = 1;
 7887:                         }
 7888:                     }
 7889:                 }
 7890:             }
 7891:         }
 7892:     }
 7893:     return $canreq;
 7894: }
 7895: 
 7896: # ---------------------------------------------- Custom access rule evaluation
 7897: 
 7898: sub customaccess {
 7899:     my ($priv,$uri)=@_;
 7900:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7901:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7902:     $udom = &LONCAPA::clean_domain($udom);
 7903:     $ucrs = &LONCAPA::clean_username($ucrs);
 7904:     my $access=0;
 7905:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7906: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7907: 	if ($type eq 'user') {
 7908: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7909: 		my ($tdom,$tuname)=split(m{/},$scope);
 7910: 		if ($tdom) {
 7911: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7912: 		}
 7913: 		if ($tuname) {
 7914: 		    if ($tuname ne $env{'user.name'}) { next; }
 7915: 		}
 7916: 		$access=($effect eq 'allow');
 7917: 		last;
 7918: 	    }
 7919: 	} else {
 7920: 	    if ($role) {
 7921: 		if ($role ne $urole) { next; }
 7922: 	    }
 7923: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7924: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7925: 		if ($tdom) {
 7926: 		    if ($tdom ne $udom) { next; }
 7927: 		}
 7928: 		if ($tcrs) {
 7929: 		    if ($tcrs ne $ucrs) { next; }
 7930: 		}
 7931: 		if ($tsec) {
 7932: 		    if ($tsec ne $usec) { next; }
 7933: 		}
 7934: 		$access=($effect eq 'allow');
 7935: 		last;
 7936: 	    }
 7937: 	    if ($realm eq '' && $role eq '') {
 7938: 		$access=($effect eq 'allow');
 7939: 	    }
 7940: 	}
 7941:     }
 7942:     return $access;
 7943: }
 7944: 
 7945: # ------------------------------------------------- Check for a user privilege
 7946: 
 7947: sub allowed {
 7948:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
 7949:     my $ver_orguri=$uri;
 7950:     $uri=&deversion($uri);
 7951:     my $orguri=$uri;
 7952:     $uri=&declutter($uri);
 7953: 
 7954:     if ($priv eq 'evb') {
 7955: # Evade communication block restrictions for specified role in a course
 7956:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7957:             return $1;
 7958:         } else {
 7959:             return;
 7960:         }
 7961:     }
 7962: 
 7963:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7964: # Free bre access to adm and meta resources
 7965:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
 7966: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7967: 	&& ($priv eq 'bre')) {
 7968: 	return 'F';
 7969:     }
 7970: 
 7971: # Free bre access to user's own portfolio contents
 7972:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7973:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7974: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7975:         my %setters;
 7976:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 7977:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 7978:         if (($startblock && $endblock) || ($by_ip)) {
 7979:             return 'B';
 7980:         } else {
 7981:             return 'F';
 7982:         }
 7983:     }
 7984: 
 7985: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7986:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7987:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7988:         if (exists($env{'request.course.id'})) {
 7989:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7990:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7991:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7992:                 my $courseprivid=$env{'request.course.id'};
 7993:                 $courseprivid=~s/\_/\//;
 7994:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7995:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7996:                     return $1; 
 7997:                 } else {
 7998:                     if ($env{'request.course.sec'}) {
 7999:                         $courseprivid.='/'.$env{'request.course.sec'};
 8000:                     }
 8001:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8002:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8003:                         return $2;
 8004:                     }
 8005:                 }
 8006:             }
 8007:         }
 8008:     }
 8009: 
 8010: # Free bre to public access
 8011: 
 8012:     if ($priv eq 'bre') {
 8013:         my $copyright;
 8014:         unless ($uri =~ /ext\.tool/) {
 8015:             $copyright=&metadata($uri,'copyright');
 8016:         }
 8017: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8018:            return 'F'; 
 8019:         }
 8020:         if ($copyright eq 'priv') {
 8021:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8022: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8023: 		return '';
 8024:             }
 8025:         }
 8026:         if ($copyright eq 'domain') {
 8027:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8028: 	    unless (($env{'user.domain'} eq $1) ||
 8029:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8030: 		return '';
 8031:             }
 8032:         }
 8033:         if ($env{'request.role'}=~ /li\.\//) {
 8034:             # Library role, so allow browsing of resources in this domain.
 8035:             return 'F';
 8036:         }
 8037:         if ($copyright eq 'custom') {
 8038: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8039:         }
 8040:     }
 8041:     # Domain coordinator is trying to create a course
 8042:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8043:         # uri is the requested domain in this case.
 8044:         # comparison to 'request.role.domain' shows if the user has selected
 8045:         # a role of dc for the domain in question.
 8046:         return 'F' if ($uri eq $env{'request.role.domain'});
 8047:     }
 8048: 
 8049:     my $thisallowed='';
 8050:     my $statecond=0;
 8051:     my $courseprivid='';
 8052: 
 8053:     my $ownaccess;
 8054:     # Community Coordinator or Assistant Co-author browsing resource space.
 8055:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8056:         if ($uri eq '') {
 8057:             $ownaccess = 1;
 8058:         } else {
 8059:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8060:                 my $udom = $env{'user.domain'};
 8061:                 my $uname = $env{'user.name'};
 8062:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8063:                     $ownaccess = 1;
 8064:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8065:                     unless ($uri =~ m{\.\./}) {
 8066:                         $ownaccess = 1;
 8067:                     }
 8068:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8069:                     my $now = time;
 8070:                     if ($uri =~ m{^([^/]+)/?$}) {
 8071:                         my $adom = $1;
 8072:                         foreach my $key (keys(%env)) {
 8073:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8074:                                 my ($start,$end) = split(/\./,$env{$key});
 8075:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8076:                                     $ownaccess = 1;
 8077:                                     last;
 8078:                                 }
 8079:                             }
 8080:                         }
 8081:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8082:                         my $adom = $1;
 8083:                         my $aname = $2;
 8084:                         foreach my $role ('ca','aa') { 
 8085:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8086:                                 my ($start,$end) =
 8087:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
 8088:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8089:                                     $ownaccess = 1;
 8090:                                     last;
 8091:                                 }
 8092:                             }
 8093:                         }
 8094:                     }
 8095:                 }
 8096:             }
 8097:         }
 8098:     }
 8099: 
 8100: # Course
 8101: 
 8102:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8103:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8104:             $thisallowed.=$1;
 8105:         }
 8106:     }
 8107: 
 8108: # Domain
 8109: 
 8110:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8111:        =~/\Q$priv\E\&([^\:]*)/) {
 8112:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8113:             $thisallowed.=$1;
 8114:         }
 8115:     }
 8116: 
 8117: # User who is not author or co-author might still be able to edit
 8118: # resource of an author in the domain (e.g., if Domain Coordinator).
 8119:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8120:         (&allowed('mdc',$env{'request.course.id'}))) {
 8121:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8122:             $thisallowed.=$1;
 8123:         }
 8124:     }
 8125: 
 8126: # Course: uri itself is a course
 8127:     my $courseuri=$uri;
 8128:     $courseuri=~s/\_(\d)/\/$1/;
 8129:     $courseuri=~s/^([^\/])/\/$1/;
 8130: 
 8131:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8132:        =~/\Q$priv\E\&([^\:]*)/) {
 8133:         if ($priv eq 'mip') {
 8134:             my $rem = $1;
 8135:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8136:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8137:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8138:                 if ($cdom ne '') {
 8139:                     my %passwdconf = &get_passwdconf($cdom);
 8140:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8141:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8142:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8143:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8144:                                 unless (@inststatuses) {
 8145:                                     @inststatuses = ('default');
 8146:                                 }
 8147:                                 foreach my $status (@inststatuses) {
 8148:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8149:                                         $thisallowed.=$rem;
 8150:                                     }
 8151:                                 }
 8152:                             }
 8153:                         }
 8154:                     }
 8155:                 }
 8156:             }
 8157:         } else {
 8158:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8159:                 $thisallowed.=$1;
 8160:             }
 8161:         }
 8162:     }
 8163: 
 8164: # URI is an uploaded document for this course, default permissions don't matter
 8165: # not allowing 'edit' access (editupload) to uploaded course docs
 8166:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8167: 	$thisallowed='';
 8168:         my ($match)=&is_on_map($uri);
 8169:         if ($match) {
 8170:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8171:                   =~/\Q$priv\E\&([^\:]*)/) {
 8172:                 my $value = $1;
 8173:                 my $deeplinkblock;
 8174:                 unless ($nodeeplinkcheck) {
 8175:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8176:                 }
 8177:                 if ($deeplinkblock) {
 8178:                     $thisallowed='D';
 8179:                 } elsif ($noblockcheck) {
 8180:                     $thisallowed.=$value;
 8181:                 } else {
 8182:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8183:                     if (@blockers > 0) {
 8184:                         $thisallowed = 'B';
 8185:                     } else {
 8186:                         $thisallowed.=$value;
 8187:                     }
 8188:                 }
 8189:             }
 8190:         } else {
 8191:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8192:             if ($refuri) {
 8193:                 if ($refuri =~ m|^/adm/|) {
 8194:                     $thisallowed='F';
 8195:                 } else {
 8196:                     $refuri=&declutter($refuri);
 8197:                     my ($match) = &is_on_map($refuri);
 8198:                     if ($match) {
 8199:                         my $deeplinkblock;
 8200:                         unless ($nodeeplinkcheck) {
 8201:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8202:                         }
 8203:                         if ($deeplinkblock) {
 8204:                             $thisallowed='D';
 8205:                         } elsif ($noblockcheck) {
 8206:                             $thisallowed='F';
 8207:                         } else {
 8208:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8209:                             if (@blockers > 0) {
 8210:                                 $thisallowed = 'B';
 8211:                             } else {
 8212:                                 $thisallowed='F';
 8213:                             }
 8214:                         }
 8215:                     }
 8216:                 }
 8217:             }
 8218:         }
 8219:     }
 8220: 
 8221:     if ($priv eq 'bre'
 8222: 	&& $thisallowed ne 'F' 
 8223: 	&& $thisallowed ne '2'
 8224: 	&& &is_portfolio_url($uri)) {
 8225: 	$thisallowed = &portfolio_access($uri,$clientip);
 8226:     }
 8227:     
 8228: # Full access at system, domain or course-wide level? Exit.
 8229:     if ($thisallowed=~/F/) {
 8230: 	return 'F';
 8231:     }
 8232: 
 8233: # If this is generating or modifying users, exit with special codes
 8234: 
 8235:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8236: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8237: 	    my ($audom,$auname)=split('/',$uri);
 8238: # no author name given, so this just checks on the general right to make a co-author in this domain
 8239: 	    unless ($auname) { return $thisallowed; }
 8240: # an author name is given, so we are about to actually make a co-author for a certain account
 8241: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8242: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8243: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8244: 	}
 8245: 	return $thisallowed;
 8246:     }
 8247: #
 8248: # Gathered so far: system, domain and course wide privileges
 8249: #
 8250: # Course: See if uri or referer is an individual resource that is part of 
 8251: # the course
 8252: 
 8253:     if ($env{'request.course.id'}) {
 8254: 
 8255: # If this is modifying password (internal auth) domains must match for user and user's role.
 8256: 
 8257:         if ($priv eq 'mip') {
 8258:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8259:                 return $thisallowed;
 8260:             } else {
 8261:                 return '';
 8262:             }
 8263:         }
 8264: 
 8265:        $courseprivid=$env{'request.course.id'};
 8266:        if ($env{'request.course.sec'}) {
 8267:           $courseprivid.='/'.$env{'request.course.sec'};
 8268:        }
 8269:        $courseprivid=~s/\_/\//;
 8270:        my $checkreferer=1;
 8271:        my ($match,$cond)=&is_on_map($uri);
 8272:        if ($match) {
 8273:            $statecond=$cond;
 8274:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8275:                =~/\Q$priv\E\&([^\:]*)/) {
 8276:                my $value = $1;
 8277:                if ($priv eq 'bre') {
 8278:                    my $deeplinkblock;
 8279:                    unless ($nodeeplinkcheck) {
 8280:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8281:                    }
 8282:                    if ($deeplinkblock) {
 8283:                        $thisallowed = 'D';
 8284:                    } elsif ($noblockcheck) {
 8285:                        $thisallowed.=$value;
 8286:                    } else {
 8287:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8288:                        if (@blockers > 0) {
 8289:                            $thisallowed = 'B';
 8290:                        } else {
 8291:                            $thisallowed.=$value;
 8292:                        }
 8293:                    }
 8294:                } else {
 8295:                    $thisallowed.=$value;
 8296:                }
 8297:                $checkreferer=0;
 8298:            }
 8299:        }
 8300: 
 8301:        if ($checkreferer) {
 8302: 	  my $refuri=$env{'httpref.'.$orguri};
 8303:             unless ($refuri) {
 8304:                 foreach my $key (keys(%env)) {
 8305: 		    if ($key=~/^httpref\..*\*/) {
 8306: 			my $pattern=$key;
 8307:                         $pattern=~s/^httpref\.\/res\///;
 8308:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8309:                         $pattern=~s/\//\\\//g;
 8310:                         if ($orguri=~/$pattern/) {
 8311: 			    $refuri=$env{$key};
 8312:                         }
 8313:                     }
 8314:                 }
 8315:             }
 8316: 
 8317:          if ($refuri) { 
 8318: 	  $refuri=&declutter($refuri);
 8319:           my ($match,$cond)=&is_on_map($refuri);
 8320:             if ($match) {
 8321:               my $refstatecond=$cond;
 8322:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8323:                   =~/\Q$priv\E\&([^\:]*)/) {
 8324:                   my $value = $1;
 8325:                   if ($priv eq 'bre') {
 8326:                       my $deeplinkblock;
 8327:                       unless ($nodeeplinkcheck) {
 8328:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8329:                       }
 8330:                       if ($deeplinkblock) {
 8331:                           $thisallowed = 'D';
 8332:                       } elsif ($noblockcheck) {
 8333:                           $thisallowed.=$value;
 8334:                       } else {
 8335:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8336:                           if (@blockers > 0) {
 8337:                               $thisallowed = 'B';
 8338:                           } else {
 8339:                               $thisallowed.=$value;
 8340:                           }
 8341:                       }
 8342:                   } else {
 8343:                       $thisallowed.=$value;
 8344:                   }
 8345:                   $uri=$refuri;
 8346:                   $statecond=$refstatecond;
 8347:               }
 8348:           }
 8349:         }
 8350:        }
 8351:    }
 8352: 
 8353: #
 8354: # Gathered now: all privileges that could apply, and condition number
 8355: # 
 8356: #
 8357: # Full or no access?
 8358: #
 8359: 
 8360:     if ($thisallowed=~/F/) {
 8361: 	return 'F';
 8362:     }
 8363: 
 8364:     unless ($thisallowed) {
 8365:         return '';
 8366:     }
 8367: 
 8368: # Restrictions exist, deal with them
 8369: #
 8370: #   C:according to course preferences
 8371: #   R:according to resource settings
 8372: #   L:unless locked
 8373: #   X:according to user session state
 8374: #
 8375: 
 8376: # Possibly locked functionality, check all courses
 8377: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
 8378: # Locks might take effect only after 10 minutes cache expiration for other
 8379: # courses, and 2 minutes for current course, in which user has st or ta role
 8380: # which is neither expired nor a future role (unless current course).
 8381: 
 8382:     my ($needlockcheck,$now,$crsonly);
 8383:     if ($thisallowed=~/L/) {
 8384:         $now = time;
 8385:         if ($priv eq 'bre') {
 8386:             if ($uri ne '') {
 8387:                 if ($orguri =~ m{^/+res/}) {
 8388:                     if ($uri =~ m{^lib/templates/}) {
 8389:                         if ($env{'request.course.id'}) {
 8390:                             $crsonly = 1;
 8391:                             $needlockcheck = 1;
 8392:                         }
 8393:                     } else {
 8394:                         $needlockcheck = 1;
 8395:                     }
 8396:                 } elsif ($env{'request.course.id'}) {
 8397:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
 8398:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
 8399:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
 8400:                         $crsonly = 1;
 8401:                     }
 8402:                     $needlockcheck = 1;
 8403:                 }
 8404:             }
 8405:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
 8406:             $needlockcheck = 1;
 8407:         }
 8408:     }
 8409:     if ($needlockcheck) {
 8410:         foreach my $envkey (keys(%env)) {
 8411:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8412:                my $courseid=$2;
 8413:                my $roleid=$1.'.'.$2;
 8414:                $courseid=~s/^\///;
 8415:                unless ($env{'request.role'} eq $roleid) {
 8416:                    my ($start,$end) = split(/\./,$env{$envkey});
 8417:                    next unless (($now >= $start) && (!$end || $end > $now));
 8418:                }
 8419:                my $expiretime=600;
 8420:                if ($env{'request.role'} eq $roleid) {
 8421: 		  $expiretime=120;
 8422:                }
 8423: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8424:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8425:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8426: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8427:                }
 8428:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8429:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8430: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8431:                        &log($env{'user.domain'},$env{'user.name'},
 8432:                             $env{'user.home'},
 8433:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8434:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8435:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8436: 		       return '';
 8437:                    }
 8438:                }
 8439:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8440:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8441: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
 8442:                        &log($env{'user.domain'},$env{'user.name'},
 8443:                             $env{'user.home'},
 8444:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8445:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8446:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8447: 		       return '';
 8448:                    }
 8449:                }
 8450: 	   }
 8451:        }
 8452:     }
 8453: 
 8454: #
 8455: # Rest of the restrictions depend on selected course
 8456: #
 8457: 
 8458:     unless ($env{'request.course.id'}) {
 8459: 	if ($thisallowed eq 'A') {
 8460: 	    return 'A';
 8461:         } elsif ($thisallowed eq 'B') {
 8462:             return 'B';
 8463: 	} else {
 8464: 	    return '1';
 8465: 	}
 8466:     }
 8467: 
 8468: #
 8469: # Now user is definitely in a course
 8470: #
 8471: 
 8472: 
 8473: # Course preferences
 8474: 
 8475:    if ($thisallowed=~/C/) {
 8476:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8477:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8478:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8479: 	   =~/\Q$rolecode\E/) {
 8480: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8481: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8482: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8483: 			$env{'request.course.id'});
 8484: 	   }
 8485:            return '';
 8486:        }
 8487: 
 8488:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8489: 	   =~/\Q$unamedom\E/) {
 8490: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8491: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8492: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8493: 			$env{'request.course.id'});
 8494: 	   }
 8495:            return '';
 8496:        }
 8497:    }
 8498: 
 8499: # Resource preferences
 8500: 
 8501:    if ($thisallowed=~/R/) {
 8502:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8503:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8504: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8505: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8506: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8507: 	   }
 8508: 	   return '';
 8509:        }
 8510:    }
 8511: 
 8512: # Restricted for deeplinked session?
 8513: 
 8514:     if ($env{'request.deeplink.login'}) {
 8515:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
 8516:             if (!$symb) { $symb=&symbread($uri,1); }
 8517:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
 8518:                 return '';
 8519:             }
 8520:         }
 8521:     }
 8522: 
 8523: # Restricted by state or randomout?
 8524: 
 8525:    if ($thisallowed=~/X/) {
 8526:       if ($env{'acc.randomout'}) {
 8527: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8528:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8529:             return ''; 
 8530:          }
 8531:       }
 8532:       if (&condval($statecond)) {
 8533: 	 return '2';
 8534:       } else {
 8535:          return '';
 8536:       }
 8537:    }
 8538: 
 8539:     if ($thisallowed eq 'A') {
 8540: 	return 'A';
 8541:     } elsif ($thisallowed eq 'B') {
 8542:         return 'B';
 8543:     } elsif ($thisallowed eq 'D') {
 8544:         return 'D';
 8545:     }
 8546:    return 'F';
 8547: }
 8548: 
 8549: # ------------------------------------------- Check construction space access
 8550: 
 8551: sub constructaccess {
 8552:     my ($url,$setpriv)=@_;
 8553: 
 8554: # We do not allow editing of previous versions of files
 8555:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8556: 
 8557: # Get username and domain from URL
 8558:     my ($ownername,$ownerdomain,$ownerhome);
 8559: 
 8560:     ($ownerdomain,$ownername) =
 8561:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
 8562: 
 8563: # The URL does not really point to any authorspace, forget it
 8564:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8565: 
 8566: # Now we need to see if the user has access to the authorspace of
 8567: # $ownername at $ownerdomain
 8568: 
 8569:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8570: # Real author for this?
 8571:        $ownerhome = $env{'user.home'};
 8572:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8573:           return ($ownername,$ownerdomain,$ownerhome);
 8574:        }
 8575:     } else {
 8576: # Co-author for this?
 8577:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8578:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8579:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8580:             return ($ownername,$ownerdomain,$ownerhome);
 8581:         }
 8582:     }
 8583: 
 8584: # We don't have any access right now. If we are not possibly going to do anything about this,
 8585: # we might as well leave
 8586:    unless ($setpriv) { return ''; }
 8587: 
 8588: # Backdoor access?
 8589:     my $allowed=&allowed('eco',$ownerdomain);
 8590: # Nope
 8591:     unless ($allowed) { return ''; }
 8592: # Looks like we may have access, but could be locked by the owner of the construction space
 8593:     if ($allowed eq 'U') {
 8594:         my %blocked=&get('environment',['domcoord.author'],
 8595:                          $ownerdomain,$ownername);
 8596: # Is blocked by owner
 8597:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8598:     }
 8599:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8600: # Grant temporary access
 8601:         my $then=$env{'user.login.time'};
 8602:         my $update=$env{'user.update.time'};
 8603:         if (!$update) { $update = $then; }
 8604:         my $refresh=$env{'user.refresh.time'};
 8605:         if (!$refresh) { $refresh = $update; }
 8606:         my $now = time;
 8607:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8608:                            $now,'ca','constructaccess');
 8609:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8610:         return($ownername,$ownerdomain,$ownerhome);
 8611:     }
 8612: # No business here
 8613:     return '';
 8614: }
 8615: 
 8616: # ----------------------------------------------------------- Content Blocking
 8617: 
 8618: {
 8619: # Caches for faster Course Contents display where content blocking
 8620: # is in operation (i.e., interval param set) for timed quiz.
 8621: #
 8622: # User for whom data are being temporarily cached.
 8623: my $cacheduser='';
 8624: # Course for which data are being temporarily cached.
 8625: my $cachedcid='';
 8626: # Cached blockers for this user (a hash of blocking items).
 8627: my %cachedblockers=();
 8628: # When the data were last cached.
 8629: my $cachedlast='';
 8630: 
 8631: sub load_all_blockers {
 8632:     my ($uname,$udom)=@_;
 8633:     if (($uname ne '') && ($udom ne '')) {
 8634:         if (($cacheduser eq $uname.':'.$udom) &&
 8635:             ($cachedcid eq $env{'request.course.id'}) &&
 8636:             (abs($cachedlast-time)<5)) {
 8637:             return;
 8638:         }
 8639:     }
 8640:     $cachedlast=time;
 8641:     $cacheduser=$uname.':'.$udom;
 8642:     $cachedcid=$env{'request.course.id'};
 8643:     %cachedblockers = &get_commblock_resources();
 8644:     return;
 8645: }
 8646: 
 8647: sub get_comm_blocks {
 8648:     my ($cdom,$cnum) = @_;
 8649:     if ($cdom eq '' || $cnum eq '') {
 8650:         return unless ($env{'request.course.id'});
 8651:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8652:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8653:     }
 8654:     my %commblocks;
 8655:     my $hashid=$cdom.'_'.$cnum;
 8656:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8657:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8658:         %commblocks = %{$blocksref};
 8659:     } else {
 8660:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8661:         my $cachetime = 600;
 8662:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8663:     }
 8664:     return %commblocks;
 8665: }
 8666: 
 8667: sub get_commblock_resources {
 8668:     my ($blocks) = @_;
 8669:     my %blockers = ();
 8670:     return %blockers unless ($env{'request.course.id'});
 8671:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 8672:     if ($env{'request.course.sec'}) {
 8673:         $courseurl .= '/'.$env{'request.course.sec'};
 8674:     }
 8675:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 8676:     my %commblocks;
 8677:     if (ref($blocks) eq 'HASH') {
 8678:         %commblocks = %{$blocks};
 8679:     } else {
 8680:         %commblocks = &get_comm_blocks();
 8681:     }
 8682:     return %blockers unless (keys(%commblocks) > 0);
 8683:     my $navmap = Apache::lonnavmaps::navmap->new();
 8684:     return %blockers unless (ref($navmap));
 8685:     my $now = time;
 8686:     foreach my $block (keys(%commblocks)) {
 8687:         if ($block =~ /^(\d+)____(\d+)$/) {
 8688:             my ($start,$end) = ($1,$2);
 8689:             if ($start <= $now && $end >= $now) {
 8690:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8691:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8692:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8693:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8694:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8695:                             }
 8696:                         }
 8697:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8698:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8699:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8700:                             }
 8701:                         }
 8702:                     }
 8703:                 }
 8704:             }
 8705:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8706:             my $item = $1;
 8707:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8708:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8709:                     my (@interval,$mapname);
 8710:                     my $type = 'map';
 8711:                     if ($item eq 'course') {
 8712:                         $type = 'course';
 8713:                         @interval=&EXT("resource.0.interval");
 8714:                     } else {
 8715:                         if ($item =~ /___\d+___/) {
 8716:                             $type = 'resource';
 8717:                             @interval=&EXT("resource.0.interval",$item);
 8718:                         } else {
 8719:                             $mapname = &deversion($item);
 8720:                             if (ref($navmap)) {
 8721:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
 8722:                                 @interval = ($timelimit,'map');
 8723:                             }
 8724:                         }
 8725:                     }
 8726:                     if ($interval[0] =~ /^(\d+)/) {
 8727:                         my $timelimit = $1;
 8728:                         my $first_access;
 8729:                         if ($type eq 'resource') {
 8730:                             $first_access=&get_first_access($interval[1],$item);
 8731:                         } elsif ($type eq 'map') {
 8732:                             $first_access=&get_first_access($interval[1],undef,$item);
 8733:                         } else {
 8734:                             $first_access=&get_first_access($interval[1]);
 8735:                         }
 8736:                         if ($first_access) {
 8737:                             my $timesup = $first_access+$timelimit;
 8738:                             if ($timesup > $now) {
 8739:                                 my $activeblock;
 8740:                                 if ($type eq 'resource') {
 8741:                                     if (ref($navmap)) {
 8742:                                         my $res = $navmap->getBySymb($item);
 8743:                                         if ($res->answerable()) {
 8744:                                             $activeblock = 1;
 8745:                                         }
 8746:                                     }
 8747:                                 } elsif ($type eq 'map') {
 8748:                                     my $mapsymb = &symbread($mapname,1);
 8749:                                     if (($mapsymb) && (ref($navmap))) {
 8750:                                         my $mapres = $navmap->getBySymb($mapsymb);
 8751:                                         if (ref($mapres)) {
 8752:                                             my $first = $mapres->map_start();
 8753:                                             my $finish = $mapres->map_finish();
 8754:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
 8755:                                             if (ref($it)) {
 8756:                                                 my $res;
 8757:                                                 while ($res = $it->next(undef,1)) {
 8758:                                                     next unless (ref($res));
 8759:                                                     my $symb = $res->symb();
 8760:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
 8761:                                                     @interval=&EXT("resource.0.interval",$symb);
 8762:                                                     if ($interval[1] eq 'map') {
 8763:                                                         if ($res->answerable()) {
 8764:                                                             $activeblock = 1;
 8765:                                                             last;
 8766:                                                         }
 8767:                                                     }
 8768:                                                 }
 8769:                                             }
 8770:                                         }
 8771:                                     }
 8772:                                 }
 8773:                                 if ($activeblock) {
 8774:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8775:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8776:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8777:                                          }
 8778:                                     }
 8779:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8780:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8781:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8782:                                         }
 8783:                                     }
 8784:                                 }
 8785:                             }
 8786:                         }
 8787:                     }
 8788:                 }
 8789:             }
 8790:         }
 8791:     }
 8792:     return %blockers;
 8793: }
 8794: 
 8795: sub has_comm_blocking {
 8796:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 8797:     my @blockers;
 8798:     return unless ($env{'request.course.id'});
 8799:     return unless ($priv eq 'bre');
 8800:     return if ($env{'request.state'} eq 'construct');
 8801:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 8802:     if ($env{'request.course.sec'}) {
 8803:         $courseurl .= '/'.$env{'request.course.sec'};
 8804:     }
 8805:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 8806:     my %blockinfo;
 8807:     if (ref($blocks) eq 'HASH') {
 8808:         %blockinfo = &get_commblock_resources($blocks);
 8809:     } else {
 8810:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 8811:         %blockinfo = %cachedblockers;
 8812:     }
 8813:     return unless (keys(%blockinfo) > 0);
 8814:     my (%possibles,@symbs);
 8815:     if (!$symb) {
 8816:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 8817:     }
 8818:     if ($symb) {
 8819:         @symbs = ($symb);
 8820:     } elsif (keys(%possibles)) {
 8821:         @symbs = keys(%possibles);
 8822:     }
 8823:     my $noblock;
 8824:     foreach my $symb (@symbs) {
 8825:         last if ($noblock);
 8826:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8827:         foreach my $block (keys(%blockinfo)) {
 8828:             if ($block =~ /^firstaccess____(.+)$/) {
 8829:                 my $item = $1;
 8830:                 unless ($blocked) {
 8831:                     if (($item eq $map) || ($item eq $symb)) {
 8832:                         $noblock = 1;
 8833:                         last;
 8834:                     }
 8835:                 }
 8836:             }
 8837:             if (ref($blockinfo{$block}) eq 'HASH') {
 8838:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 8839:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 8840:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8841:                             push(@blockers,$block);
 8842:                         }
 8843:                     }
 8844:                 }
 8845:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 8846:                     if ($blockinfo{$block}{'maps'}{$map}) {
 8847:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8848:                             push(@blockers,$block);
 8849:                         }
 8850:                     }
 8851:                 }
 8852:             }
 8853:         }
 8854:     }
 8855:     unless ($noblock) {
 8856:         return @blockers;
 8857:     }
 8858:     return;
 8859: }
 8860: }
 8861: 
 8862: sub deeplink_check {
 8863:     my ($priv,$symb,$uri) = @_;
 8864:     return unless ($env{'request.course.id'});
 8865:     return unless ($priv eq 'bre');
 8866:     return if ($env{'request.state'} eq 'construct');
 8867:     return if ($env{'request.role.adv'});
 8868:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8869:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8870:     my (%possibles,@symbs);
 8871:     if (!$symb) {
 8872:         $symb = &symbread($uri,1,1,1,\%possibles);
 8873:     }
 8874:     if ($symb) {
 8875:         @symbs = ($symb);
 8876:     } elsif (keys(%possibles)) {
 8877:         @symbs = keys(%possibles);
 8878:     }
 8879: 
 8880:     my ($deeplink_symb,$allow);
 8881:     if ($env{'request.deeplink.login'}) {
 8882:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
 8883:     }
 8884:     foreach my $symb (@symbs) {
 8885:         last if ($allow);
 8886:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 8887:         if ($deeplink eq '') {
 8888:             $allow = 1;
 8889:         } else {
 8890:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
 8891:             if ($state ne 'only') {
 8892:                 $allow = 1;
 8893:             } else {
 8894:                 my $check_deeplink_entry;
 8895:                 if ($protect ne 'none') {
 8896:                     my ($acctype,$item) = split(/:/,$protect);
 8897:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
 8898:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
 8899:                             $check_deeplink_entry = 1
 8900:                         }
 8901:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
 8902:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
 8903:                             $check_deeplink_entry = 1;
 8904:                         }
 8905:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 8906:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 8907:                             $check_deeplink_entry = 1;
 8908:                         }
 8909:                     }
 8910:                 }
 8911:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
 8912:                     if ($scope eq 'res') {
 8913:                         if ($symb eq $deeplink_symb) {
 8914:                             $allow = 1;
 8915:                         }
 8916:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
 8917:                         my ($map_from_symb,$map_from_login);
 8918:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
 8919:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
 8920:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
 8921:                         } else {
 8922:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
 8923:                         }
 8924:                         if (($map_from_symb) && ($map_from_login)) {
 8925:                             if ($map_from_symb eq $map_from_login) {
 8926:                                 $allow = 1;
 8927:                             } elsif ($scope eq 'rec') {
 8928:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
 8929:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
 8930:                                     $allow = 1;
 8931:                                 }
 8932:                             }
 8933:                         }
 8934:                     }
 8935:                 }
 8936:             }
 8937:         }
 8938:     }
 8939:     return if ($allow);
 8940:     return 1;
 8941: }
 8942: 
 8943: # -------------------------------- Deversion and split uri into path an filename
 8944: 
 8945: #
 8946: #   Removes the version from a URI and
 8947: #   splits it in to its filename and path to the filename.
 8948: #   Seems like File::Basename could have done this more clearly.
 8949: #   Parameters:
 8950: #      $uri   - input URI
 8951: #   Returns:
 8952: #     Two element list consisting of 
 8953: #     $pathname  - the URI up to and excluding the trailing /
 8954: #     $filename  - The part of the URI following the last /
 8955: #  NOTE:
 8956: #    Another realization of this is simply:
 8957: #    use File::Basename;
 8958: #    ...
 8959: #    $uri = shift;
 8960: #    $filename = basename($uri);
 8961: #    $path     = dirname($uri);
 8962: #    return ($filename, $path);
 8963: #
 8964: #     The implementation below is probably faster however.
 8965: #
 8966: sub split_uri_for_cond {
 8967:     my $uri=&deversion(&declutter(shift));
 8968:     my @uriparts=split(/\//,$uri);
 8969:     my $filename=pop(@uriparts);
 8970:     my $pathname=join('/',@uriparts);
 8971:     return ($pathname,$filename);
 8972: }
 8973: # --------------------------------------------------- Is a resource on the map?
 8974: 
 8975: sub is_on_map {
 8976:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8977:     #Trying to find the conditional for the file
 8978:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8979: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8980:     if ($match) {
 8981: 	return (1,$1);
 8982:     } else {
 8983: 	return (0,0);
 8984:     }
 8985: }
 8986: 
 8987: # --------------------------------------------------------- Get symb from alias
 8988: 
 8989: sub get_symb_from_alias {
 8990:     my $symb=shift;
 8991:     my ($map,$resid,$url)=&decode_symb($symb);
 8992: # Already is a symb
 8993:     if ($url) { return $symb; }
 8994: # Must be an alias
 8995:     my $aliassymb='';
 8996:     my %bighash;
 8997:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8998:                             &GDBM_READER(),0640)) {
 8999:         my $rid=$bighash{'mapalias_'.$symb};
 9000: 	if ($rid) {
 9001: 	    my ($mapid,$resid)=split(/\./,$rid);
 9002: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 9003: 				    $resid,$bighash{'src_'.$rid});
 9004: 	}
 9005:         untie %bighash;
 9006:     }
 9007:     return $aliassymb;
 9008: }
 9009: 
 9010: # ----------------------------------------------------------------- Define Role
 9011: 
 9012: sub definerole {
 9013:   if (allowed('mcr','/')) {
 9014:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 9015:     foreach my $role (split(':',$sysrole)) {
 9016: 	my ($crole,$cqual)=split(/\&/,$role);
 9017:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9018:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9019: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9020:                return "refused:s:$crole&$cqual"; 
 9021:             }
 9022:         }
 9023:     }
 9024:     foreach my $role (split(':',$domrole)) {
 9025: 	my ($crole,$cqual)=split(/\&/,$role);
 9026:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9027:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9028: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9029:                return "refused:d:$crole&$cqual"; 
 9030:             }
 9031:         }
 9032:     }
 9033:     foreach my $role (split(':',$courole)) {
 9034: 	my ($crole,$cqual)=split(/\&/,$role);
 9035:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9036:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9037: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9038:                return "refused:c:$crole&$cqual"; 
 9039:             }
 9040:         }
 9041:     }
 9042:     my $uhome;
 9043:     if (($uname ne '') && ($udom ne '')) {
 9044:         $uhome = &homeserver($uname,$udom);
 9045:         return $uhome if ($uhome eq 'no_host');
 9046:     } else {
 9047:         $uname = $env{'user.name'};
 9048:         $udom = $env{'user.domain'};
 9049:         $uhome = $env{'user.home'};
 9050:     }
 9051:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9052:                 "$udom:$uname:rolesdef_$rolename=".
 9053:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9054:     return reply($command,$uhome);
 9055:   } else {
 9056:     return 'refused';
 9057:   }
 9058: }
 9059: 
 9060: # ---------------- Make a metadata query against the network of library servers
 9061: 
 9062: sub metadata_query {
 9063:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9064:     my %rhash;
 9065:     my %libserv = &all_library();
 9066:     my @server_list = (defined($server_array) ? @$server_array
 9067:                                               : keys(%libserv) );
 9068:     for my $server (@server_list) {
 9069:         my $domains = '';
 9070:         if (ref($domains_hash) eq 'HASH') {
 9071:             $domains = $domains_hash->{$server};    
 9072:         }
 9073: 	unless ($custom or $customshow) {
 9074: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9075: 	    $rhash{$server}=$reply;
 9076: 	}
 9077: 	else {
 9078: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9079: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9080: 			     $server);
 9081: 	    $rhash{$server}=$reply;
 9082: 	}
 9083:     }
 9084:     return \%rhash;
 9085: }
 9086: 
 9087: # ----------------------------------------- Send log queries and wait for reply
 9088: 
 9089: sub log_query {
 9090:     my ($uname,$udom,$query,%filters)=@_;
 9091:     my $uhome=&homeserver($uname,$udom);
 9092:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9093:     my $uhost=&hostname($uhome);
 9094:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9095:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9096:                        $uhome);
 9097:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9098:     return get_query_reply($queryid);
 9099: }
 9100: 
 9101: # -------------------------- Update MySQL table for portfolio file
 9102: 
 9103: sub update_portfolio_table {
 9104:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9105:     if ($group ne '') {
 9106:         $file_name =~s /^\Q$group\E//;
 9107:     }
 9108:     my $homeserver = &homeserver($uname,$udom);
 9109:     my $queryid=
 9110:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9111:                ':'.&escape($file_name).':'.$action,$homeserver);
 9112:     my $reply = &get_query_reply($queryid);
 9113:     return $reply;
 9114: }
 9115: 
 9116: # -------------------------- Update MySQL allusers table
 9117: 
 9118: sub update_allusers_table {
 9119:     my ($uname,$udom,$names) = @_;
 9120:     my $homeserver = &homeserver($uname,$udom);
 9121:     my $queryid=
 9122:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9123:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9124:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9125:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9126:                'generation='.&escape($names->{'generation'}).'%%'.
 9127:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9128:                'id='.&escape($names->{'id'}),$homeserver);
 9129:     return;
 9130: }
 9131: 
 9132: # ------- Request retrieval of institutional classlists for course(s)
 9133: 
 9134: sub fetch_enrollment_query {
 9135:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9136:     my ($homeserver,$sleep,$loopmax);
 9137:     my $maxtries = 1;
 9138:     if ($context eq 'automated') {
 9139:         $homeserver = $perlvar{'lonHostID'};
 9140:         $sleep = 2;
 9141:         $loopmax = 100;
 9142:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9143:     } else {
 9144:         $homeserver = &homeserver($cnum,$dom);
 9145:     }
 9146:     my $host=&hostname($homeserver);
 9147:     my $cmd = '';
 9148:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9149:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9150:     }
 9151:     $cmd =~ s/%%$//;
 9152:     $cmd = &escape($cmd);
 9153:     my $query = 'fetchenrollment';
 9154:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9155:     unless ($queryid=~/^\Q$host\E\_/) { 
 9156:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9157:         return 'error: '.$queryid;
 9158:     }
 9159:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9160:     my $tries = 1;
 9161:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9162:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9163:         $tries ++;
 9164:     }
 9165:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9166:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9167:     } else {
 9168:         my @responses = split(/:/,$reply);
 9169:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9170:             foreach my $line (@responses) {
 9171:                 my ($key,$value) = split(/=/,$line,2);
 9172:                 $$replyref{$key} = $value;
 9173:             }
 9174:         } else {
 9175:             my $pathname = LONCAPA::tempdir();
 9176:             foreach my $line (@responses) {
 9177:                 my ($key,$value) = split(/=/,$line);
 9178:                 $$replyref{$key} = $value;
 9179:                 if ($value > 0) {
 9180:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9181:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9182:                         my $destname = $pathname.'/'.$filename;
 9183:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9184:                         if ($xml_classlist =~ /^error/) {
 9185:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9186:                         } else {
 9187:                             if ( open(FILE,">",$destname) ) {
 9188:                                 print FILE &unescape($xml_classlist);
 9189:                                 close(FILE);
 9190:                             } else {
 9191:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9192:                             }
 9193:                         }
 9194:                     }
 9195:                 }
 9196:             }
 9197:         }
 9198:         return 'ok';
 9199:     }
 9200:     return 'error';
 9201: }
 9202: 
 9203: sub get_query_reply {
 9204:     my ($queryid,$sleep,$loopmax) = @_;
 9205:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9206:         $sleep = 0.2;
 9207:     }
 9208:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9209:         $loopmax = 100;
 9210:     }
 9211:     my $replyfile=LONCAPA::tempdir().$queryid;
 9212:     my $reply='';
 9213:     for (1..$loopmax) {
 9214: 	sleep($sleep);
 9215:         if (-e $replyfile.'.end') {
 9216: 	    if (open(my $fh,"<",$replyfile)) {
 9217: 		$reply = join('',<$fh>);
 9218: 		close($fh);
 9219: 	   } else { return 'error: reply_file_error'; }
 9220:            return &unescape($reply);
 9221: 	}
 9222:     }
 9223:     return 'timeout:'.$queryid;
 9224: }
 9225: 
 9226: sub courselog_query {
 9227: #
 9228: # possible filters:
 9229: # url: url or symb
 9230: # username
 9231: # domain
 9232: # action: view, submit, grade
 9233: # start: timestamp
 9234: # end: timestamp
 9235: #
 9236:     my (%filters)=@_;
 9237:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9238:     if ($filters{'url'}) {
 9239: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9240:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9241:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9242:     }
 9243:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9244:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9245:     return &log_query($cname,$cdom,'courselog',%filters);
 9246: }
 9247: 
 9248: sub userlog_query {
 9249: #
 9250: # possible filters:
 9251: # action: log check role
 9252: # start: timestamp
 9253: # end: timestamp
 9254: #
 9255:     my ($uname,$udom,%filters)=@_;
 9256:     return &log_query($uname,$udom,'userlog',%filters);
 9257: }
 9258: 
 9259: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9260: 
 9261: sub auto_run {
 9262:     my ($cnum,$cdom) = @_;
 9263:     my $response = 0;
 9264:     my $settings;
 9265:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9266:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9267:         $settings = $domconfig{'autoenroll'};
 9268:         if ($settings->{'run'} eq '1') {
 9269:             $response = 1;
 9270:         }
 9271:     } else {
 9272:         my $homeserver;
 9273:         if (&is_course($cdom,$cnum)) {
 9274:             $homeserver = &homeserver($cnum,$cdom);
 9275:         } else {
 9276:             $homeserver = &domain($cdom,'primary');
 9277:         }
 9278:         if ($homeserver ne 'no_host') {
 9279:             $response = &reply('autorun:'.$cdom,$homeserver);
 9280:         }
 9281:     }
 9282:     return $response;
 9283: }
 9284: 
 9285: sub auto_get_sections {
 9286:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9287:     my $homeserver;
 9288:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9289:         $homeserver = &homeserver($cnum,$cdom);
 9290:     }
 9291:     if (!defined($homeserver)) { 
 9292:         if ($cdom =~ /^$match_domain$/) {
 9293:             $homeserver = &domain($cdom,'primary');
 9294:         }
 9295:     }
 9296:     my @secs;
 9297:     if (defined($homeserver)) {
 9298:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9299:         unless ($response eq 'refused') {
 9300:             @secs = split(/:/,$response);
 9301:         }
 9302:     }
 9303:     return @secs;
 9304: }
 9305: 
 9306: sub auto_new_course {
 9307:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9308:     my $homeserver = &homeserver($cnum,$cdom);
 9309:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9310:     return $response;
 9311: }
 9312: 
 9313: sub auto_validate_courseID {
 9314:     my ($cnum,$cdom,$inst_course_id) = @_;
 9315:     my $homeserver = &homeserver($cnum,$cdom);
 9316:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9317:     return $response;
 9318: }
 9319: 
 9320: sub auto_validate_instcode {
 9321:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9322:     my ($homeserver,$response);
 9323:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9324:         $homeserver = &homeserver($cnum,$cdom);
 9325:     }
 9326:     if (!defined($homeserver)) {
 9327:         if ($cdom =~ /^$match_domain$/) {
 9328:             $homeserver = &domain($cdom,'primary');
 9329:         }
 9330:     }
 9331:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9332:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9333:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9334:     return ($outcome,$description,$defaultcredits);
 9335: }
 9336: 
 9337: sub auto_validate_inst_crosslist {
 9338:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
 9339:     my ($homeserver,$response);
 9340:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9341:         $homeserver = &homeserver($cnum,$cdom);
 9342:     }
 9343:     if (!defined($homeserver)) {
 9344:         if ($cdom =~ /^$match_domain$/) {
 9345:             $homeserver = &domain($cdom,'primary');
 9346:         }
 9347:     }
 9348:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
 9349:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
 9350:                          &escape($instcode).':'.&escape($inst_xlist).':'.
 9351:                          &escape($coowner),$homeserver);
 9352:     }
 9353:     return $response;
 9354: }
 9355: 
 9356: sub auto_create_password {
 9357:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9358:     my ($homeserver,$response);
 9359:     my $create_passwd = 0;
 9360:     my $authchk = '';
 9361:     if ($udom =~ /^$match_domain$/) {
 9362:         $homeserver = &domain($udom,'primary');
 9363:     }
 9364:     if ($homeserver eq '') {
 9365:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9366:             $homeserver = &homeserver($cnum,$cdom);
 9367:         }
 9368:     }
 9369:     if ($homeserver eq '') {
 9370:         $authchk = 'nodomain';
 9371:     } else {
 9372:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9373:         if ($response eq 'refused') {
 9374:             $authchk = 'refused';
 9375:         } else {
 9376:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9377:         }
 9378:     }
 9379:     return ($authparam,$create_passwd,$authchk);
 9380: }
 9381: 
 9382: sub auto_photo_permission {
 9383:     my ($cnum,$cdom,$students) = @_;
 9384:     my $homeserver = &homeserver($cnum,$cdom);
 9385:     my ($outcome,$perm_reqd,$conditions) = 
 9386: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9387:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9388: 	return (undef,undef);
 9389:     }
 9390:     return ($outcome,$perm_reqd,$conditions);
 9391: }
 9392: 
 9393: sub auto_checkphotos {
 9394:     my ($uname,$udom,$pid) = @_;
 9395:     my $homeserver = &homeserver($uname,$udom);
 9396:     my ($result,$resulttype);
 9397:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9398: 				   &escape($uname).':'.&escape($pid),
 9399: 				   $homeserver));
 9400:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9401: 	return (undef,undef);
 9402:     }
 9403:     if ($outcome) {
 9404:         ($result,$resulttype) = split(/:/,$outcome);
 9405:     } 
 9406:     return ($result,$resulttype);
 9407: }
 9408: 
 9409: sub auto_photochoice {
 9410:     my ($cnum,$cdom) = @_;
 9411:     my $homeserver = &homeserver($cnum,$cdom);
 9412:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9413: 						       &escape($cdom),
 9414: 						       $homeserver)));
 9415:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9416: 	return (undef,undef);
 9417:     }
 9418:     return ($update,$comment);
 9419: }
 9420: 
 9421: sub auto_photoupdate {
 9422:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9423:     my $homeserver = &homeserver($cnum,$dom);
 9424:     my $host=&hostname($homeserver);
 9425:     my $cmd = '';
 9426:     my $maxtries = 1;
 9427:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9428:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9429:     }
 9430:     $cmd =~ s/%%$//;
 9431:     $cmd = &escape($cmd);
 9432:     my $query = 'institutionalphotos';
 9433:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9434:     unless ($queryid=~/^\Q$host\E\_/) {
 9435:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9436:         return 'error: '.$queryid;
 9437:     }
 9438:     my $reply = &get_query_reply($queryid);
 9439:     my $tries = 1;
 9440:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9441:         $reply = &get_query_reply($queryid);
 9442:         $tries ++;
 9443:     }
 9444:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9445:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9446:     } else {
 9447:         my @responses = split(/:/,$reply);
 9448:         my $outcome = shift(@responses); 
 9449:         foreach my $item (@responses) {
 9450:             my ($key,$value) = split(/=/,$item);
 9451:             $$photo{$key} = $value;
 9452:         }
 9453:         return $outcome;
 9454:     }
 9455:     return 'error';
 9456: }
 9457: 
 9458: sub auto_instcode_format {
 9459:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9460: 	$cat_order) = @_;
 9461:     my $courses = '';
 9462:     my @homeservers;
 9463:     if ($caller eq 'global') {
 9464: 	my %servers = &get_servers($codedom,'library');
 9465: 	foreach my $tryserver (keys(%servers)) {
 9466: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9467: 		push(@homeservers,$tryserver);
 9468: 	    }
 9469:         }
 9470:     } elsif ($caller eq 'requests') {
 9471:         if ($codedom =~ /^$match_domain$/) {
 9472:             my $chome = &domain($codedom,'primary');
 9473:             unless ($chome eq 'no_host') {
 9474:                 push(@homeservers,$chome);
 9475:             }
 9476:         }
 9477:     } else {
 9478:         push(@homeservers,&homeserver($caller,$codedom));
 9479:     }
 9480:     foreach my $code (keys(%{$instcodes})) {
 9481:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9482:     }
 9483:     chop($courses);
 9484:     my $ok_response = 0;
 9485:     my $response;
 9486:     while (@homeservers > 0 && $ok_response == 0) {
 9487:         my $server = shift(@homeservers); 
 9488:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9489:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9490:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9491: 		split(/:/,$response);
 9492:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9493:             push(@{$codetitles},&str2array($codetitles_str));
 9494:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9495:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9496:             $ok_response = 1;
 9497:         }
 9498:     }
 9499:     if ($ok_response) {
 9500:         return 'ok';
 9501:     } else {
 9502:         return $response;
 9503:     }
 9504: }
 9505: 
 9506: sub auto_instcode_defaults {
 9507:     my ($domain,$returnhash,$code_order) = @_;
 9508:     my @homeservers;
 9509: 
 9510:     my %servers = &get_servers($domain,'library');
 9511:     foreach my $tryserver (keys(%servers)) {
 9512: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9513: 	    push(@homeservers,$tryserver);
 9514: 	}
 9515:     }
 9516: 
 9517:     my $response;
 9518:     foreach my $server (@homeservers) {
 9519:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9520:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9521: 	
 9522: 	foreach my $pair (split(/\&/,$response)) {
 9523: 	    my ($name,$value)=split(/\=/,$pair);
 9524: 	    if ($name eq 'code_order') {
 9525: 		@{$code_order} = split(/\&/,&unescape($value));
 9526: 	    } else {
 9527: 		$returnhash->{&unescape($name)}=&unescape($value);
 9528: 	    }
 9529: 	}
 9530: 	return 'ok';
 9531:     }
 9532: 
 9533:     return $response;
 9534: }
 9535: 
 9536: sub auto_possible_instcodes {
 9537:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9538:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9539:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9540:         return;
 9541:     }
 9542:     my (@homeservers,$uhome);
 9543:     if (defined(&domain($domain,'primary'))) {
 9544:         $uhome=&domain($domain,'primary');
 9545:         push(@homeservers,&domain($domain,'primary'));
 9546:     } else {
 9547:         my %servers = &get_servers($domain,'library');
 9548:         foreach my $tryserver (keys(%servers)) {
 9549:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9550:                 push(@homeservers,$tryserver);
 9551:             }
 9552:         }
 9553:     }
 9554:     my $response;
 9555:     foreach my $server (@homeservers) {
 9556:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9557:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9558:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9559:             split(':',$response);
 9560:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9561:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9562:         foreach my $item (split('&',$cat_title)) {   
 9563:             my ($name,$value)=split('=',$item);
 9564:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9565:         }
 9566:         foreach my $item (split('&',$cat_order)) {
 9567:             my ($name,$value)=split('=',$item);
 9568:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9569:         }
 9570:         return 'ok';
 9571:     }
 9572:     return $response;
 9573: }
 9574: 
 9575: sub auto_courserequest_checks {
 9576:     my ($dom) = @_;
 9577:     my ($homeserver,%validations);
 9578:     if ($dom =~ /^$match_domain$/) {
 9579:         $homeserver = &domain($dom,'primary');
 9580:     }
 9581:     unless ($homeserver eq 'no_host') {
 9582:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9583:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9584:             my @items = split(/&/,$response);
 9585:             foreach my $item (@items) {
 9586:                 my ($key,$value) = split('=',$item);
 9587:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9588:             }
 9589:         }
 9590:     }
 9591:     return %validations; 
 9592: }
 9593: 
 9594: sub auto_courserequest_validation {
 9595:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9596:     my ($homeserver,$response);
 9597:     if ($dom =~ /^$match_domain$/) {
 9598:         $homeserver = &domain($dom,'primary');
 9599:     }
 9600:     unless ($homeserver eq 'no_host') {
 9601:         my $customdata;
 9602:         if (ref($custominfo) eq 'HASH') {
 9603:             $customdata = &freeze_escape($custominfo);
 9604:         }
 9605:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9606:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9607:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9608:                                     $customdata,$homeserver));
 9609:     }
 9610:     return $response;
 9611: }
 9612: 
 9613: sub auto_validate_class_sec {
 9614:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9615:     my $homeserver = &homeserver($cnum,$cdom);
 9616:     my $ownerlist;
 9617:     if (ref($owners) eq 'ARRAY') {
 9618:         $ownerlist = join(',',@{$owners});
 9619:     } else {
 9620:         $ownerlist = $owners;
 9621:     }
 9622:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9623:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9624:     return $response;
 9625: }
 9626: 
 9627: sub auto_instsec_reformat {
 9628:     my ($cdom,$action,$instsecref) = @_;
 9629:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
 9630:     my @homeservers;
 9631:     if (defined(&domain($cdom,'primary'))) {
 9632:         push(@homeservers,&domain($cdom,'primary'));
 9633:     } else {
 9634:         my %servers = &get_servers($cdom,'library');
 9635:         foreach my $tryserver (keys(%servers)) {
 9636:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9637:                 push(@homeservers,$tryserver);
 9638:             }
 9639:         }
 9640:     }
 9641:     my $response;
 9642:     my %reformatted = %{$instsecref};
 9643:     foreach my $server (@homeservers) {
 9644:         if (ref($instsecref) eq 'HASH') {
 9645:             my $info = &freeze_escape($instsecref);
 9646:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
 9647:                                 $action.':'.$info,$server);
 9648:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
 9649:             my @items = split(/&/,$response);
 9650:             foreach my $item (@items) {
 9651:                 my ($key,$value) = split(/=/,$item);
 9652:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
 9653:             }
 9654:         }
 9655:     }
 9656:     return %reformatted;
 9657: }
 9658: 
 9659: sub auto_validate_instclasses {
 9660:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9661:     my ($homeserver,%validations);
 9662:     $homeserver = &homeserver($cnum,$cdom);
 9663:     unless ($homeserver eq 'no_host') {
 9664:         my $ownerlist;
 9665:         if (ref($owners) eq 'ARRAY') {
 9666:             $ownerlist = join(',',@{$owners});
 9667:         } else {
 9668:             $ownerlist = $owners;
 9669:         }
 9670:         if (ref($classesref) eq 'HASH') {
 9671:             my $classes = &freeze_escape($classesref);
 9672:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9673:                                 ':'.$cdom.':'.$classes,$homeserver);
 9674:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9675:                 my @items = split(/&/,$response);
 9676:                 foreach my $item (@items) {
 9677:                     my ($key,$value) = split('=',$item);
 9678:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9679:                 }
 9680:             }
 9681:         }
 9682:     }
 9683:     return %validations;
 9684: }
 9685: 
 9686: sub auto_crsreq_update {
 9687:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9688:         $code,$accessstart,$accessend,$inbound) = @_;
 9689:     my ($homeserver,%crsreqresponse);
 9690:     if ($cdom =~ /^$match_domain$/) {
 9691:         $homeserver = &domain($cdom,'primary');
 9692:     }
 9693:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9694:         my $info;
 9695:         if (ref($inbound) eq 'HASH') {
 9696:             $info = &freeze_escape($inbound);
 9697:         }
 9698:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9699:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9700:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9701:                             &escape($title).':'.&escape($code).':'.
 9702:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
 9703:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9704:             my @items = split(/&/,$response);
 9705:             foreach my $item (@items) {
 9706:                 my ($key,$value) = split('=',$item);
 9707:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9708:             }
 9709:         }
 9710:     }
 9711:     return \%crsreqresponse;
 9712: }
 9713: 
 9714: sub auto_export_grades {
 9715:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9716:     my ($homeserver,%exportresponse);
 9717:     if ($cdom =~ /^$match_domain$/) {
 9718:         $homeserver = &domain($cdom,'primary');
 9719:     }
 9720:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9721:         my $info;
 9722:         if (ref($inforef) eq 'HASH') {
 9723:             $info = &freeze_escape($inforef);
 9724:         }
 9725:         if (ref($gradesref) eq 'HASH') {
 9726:             my $grades = &freeze_escape($gradesref);
 9727:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9728:                                 $info.':'.$grades,$homeserver);
 9729:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9730:                 my @items = split(/&/,$response);
 9731:                 foreach my $item (@items) {
 9732:                     my ($key,$value) = split('=',$item);
 9733:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9734:                 }
 9735:             }
 9736:         }
 9737:     }
 9738:     return \%exportresponse;
 9739: }
 9740: 
 9741: sub check_instcode_cloning {
 9742:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9743:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9744:         return;
 9745:     }
 9746:     my $canclone;
 9747:     if (@{$code_order} > 0) {
 9748:         my $instcoderegexp ='^';
 9749:         my @clonecodes = split(/\&/,$cloner);
 9750:         foreach my $item (@{$code_order}) {
 9751:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9752:                 foreach my $pair (@clonecodes) {
 9753:                     my ($key,$val) = split(/\=/,$pair,2);
 9754:                     $val = &unescape($val);
 9755:                     if ($key eq $item) {
 9756:                         $instcoderegexp .= '('.$val.')';
 9757:                         last;
 9758:                     }
 9759:                 }
 9760:             } else {
 9761:                 $instcoderegexp .= $codedefaults->{$item};
 9762:             }
 9763:         }
 9764:         $instcoderegexp .= '$';
 9765:         my (@from,@to);
 9766:         eval {
 9767:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9768:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9769:         };
 9770:         if ((@from > 0) && (@to > 0)) {
 9771:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9772:             if (!@diffs) {
 9773:                 $canclone = 1;
 9774:             }
 9775:         }
 9776:     }
 9777:     return $canclone;
 9778: }
 9779: 
 9780: sub default_instcode_cloning {
 9781:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9782:     my (%codedefaults,@code_order,$canclone);
 9783:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9784:         %codedefaults = %{$codedefaultsref};
 9785:         @code_order = @{$codeorderref};
 9786:     } elsif ($clonedom) {
 9787:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9788:     }
 9789:     if (($domdefclone) && (@code_order)) {
 9790:         my @clonecodes = split(/\+/,$domdefclone);
 9791:         my $instcoderegexp ='^';
 9792:         foreach my $item (@code_order) {
 9793:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9794:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9795:             } else {
 9796:                 $instcoderegexp .= $codedefaults{$item};
 9797:             }
 9798:         }
 9799:         $instcoderegexp .= '$';
 9800:         my (@from,@to);
 9801:         eval {
 9802:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9803:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9804:         };
 9805:         if ((@from > 0) && (@to > 0)) {
 9806:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9807:             if (!@diffs) {
 9808:                 $canclone = 1;
 9809:             }
 9810:         }
 9811:     }
 9812:     return $canclone;
 9813: }
 9814: 
 9815: # ------------------------------------------------------- Course Group routines
 9816: 
 9817: sub get_coursegroups {
 9818:     my ($cdom,$cnum,$group,$namespace) = @_;
 9819:     return(&dump($namespace,$cdom,$cnum,$group));
 9820: }
 9821: 
 9822: sub modify_coursegroup {
 9823:     my ($cdom,$cnum,$groupsettings) = @_;
 9824:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9825: }
 9826: 
 9827: sub toggle_coursegroup_status {
 9828:     my ($cdom,$cnum,$group,$action) = @_;
 9829:     my ($from_namespace,$to_namespace);
 9830:     if ($action eq 'delete') {
 9831:         $from_namespace = 'coursegroups';
 9832:         $to_namespace = 'deleted_groups';
 9833:     } else {
 9834:         $from_namespace = 'deleted_groups';
 9835:         $to_namespace = 'coursegroups';
 9836:     }
 9837:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9838:     if (my $tmp = &error(%curr_group)) {
 9839:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9840:         return ('read error',$tmp);
 9841:     } else {
 9842:         my %savedsettings = %curr_group; 
 9843:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9844:         my $deloutcome;
 9845:         if ($result eq 'ok') {
 9846:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9847:         } else {
 9848:             return ('write error',$result);
 9849:         }
 9850:         if ($deloutcome eq 'ok') {
 9851:             return 'ok';
 9852:         } else {
 9853:             return ('delete error',$deloutcome);
 9854:         }
 9855:     }
 9856: }
 9857: 
 9858: sub modify_group_roles {
 9859:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9860:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9861:     my $role = 'gr/'.&escape($userprivs);
 9862:     my ($uname,$udom) = split(/:/,$user);
 9863:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9864:     if ($result eq 'ok') {
 9865:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9866:     }
 9867:     return $result;
 9868: }
 9869: 
 9870: sub modify_coursegroup_membership {
 9871:     my ($cdom,$cnum,$membership) = @_;
 9872:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9873:     return $result;
 9874: }
 9875: 
 9876: sub get_active_groups {
 9877:     my ($udom,$uname,$cdom,$cnum) = @_;
 9878:     my $now = time;
 9879:     my %groups = ();
 9880:     foreach my $key (keys(%env)) {
 9881:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9882:             my ($start,$end) = split(/\./,$env{$key});
 9883:             if (($end!=0) && ($end<$now)) { next; }
 9884:             if (($start!=0) && ($start>$now)) { next; }
 9885:             if ($1 eq $cdom && $2 eq $cnum) {
 9886:                 $groups{$3} = $env{$key} ;
 9887:             }
 9888:         }
 9889:     }
 9890:     return %groups;
 9891: }
 9892: 
 9893: sub get_group_membership {
 9894:     my ($cdom,$cnum,$group) = @_;
 9895:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9896: }
 9897: 
 9898: sub get_users_groups {
 9899:     my ($udom,$uname,$courseid) = @_;
 9900:     my @usersgroups;
 9901:     my $cachetime=1800;
 9902: 
 9903:     my $hashid="$udom:$uname:$courseid";
 9904:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9905:     if (defined($cached)) {
 9906:         @usersgroups = split(/:/,$grouplist);
 9907:     } else {  
 9908:         $grouplist = '';
 9909:         my $courseurl = &courseid_to_courseurl($courseid);
 9910:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9911:         my $access_end = $env{'course.'.$courseid.
 9912:                               '.default_enrollment_end_date'};
 9913:         my $now = time;
 9914:         foreach my $key (keys(%roleshash)) {
 9915:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9916:                 my $group = $1;
 9917:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9918:                     my $start = $2;
 9919:                     my $end = $1;
 9920:                     if ($start == -1) { next; } # deleted from group
 9921:                     if (($start!=0) && ($start>$now)) { next; }
 9922:                     if (($end!=0) && ($end<$now)) {
 9923:                         if ($access_end && $access_end < $now) {
 9924:                             if ($access_end - $end < 86400) {
 9925:                                 push(@usersgroups,$group);
 9926:                             }
 9927:                         }
 9928:                         next;
 9929:                     }
 9930:                     push(@usersgroups,$group);
 9931:                 }
 9932:             }
 9933:         }
 9934:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9935:         $grouplist = join(':',@usersgroups);
 9936:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9937:     }
 9938:     return @usersgroups;
 9939: }
 9940: 
 9941: sub devalidate_getgroups_cache {
 9942:     my ($udom,$uname,$cdom,$cnum)=@_;
 9943:     my $courseid = $cdom.'_'.$cnum;
 9944: 
 9945:     my $hashid="$udom:$uname:$courseid";
 9946:     &devalidate_cache_new('getgroups',$hashid);
 9947: }
 9948: 
 9949: # ------------------------------------------------------------------ Plain Text
 9950: 
 9951: sub plaintext {
 9952:     my ($short,$type,$cid,$forcedefault) = @_;
 9953:     if ($short =~ m{^cr/}) {
 9954: 	return (split('/',$short))[-1];
 9955:     }
 9956:     if (!defined($cid)) {
 9957:         $cid = $env{'request.course.id'};
 9958:     }
 9959:     my %rolenames = (
 9960:                       Course    => 'std',
 9961:                       Community => 'alt1',
 9962:                     );
 9963:     if ($cid ne '') {
 9964:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9965:             unless ($forcedefault) {
 9966:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9967:                 &Apache::lonlocal::mt_escape(\$roletext);
 9968:                 return &Apache::lonlocal::mt($roletext);
 9969:             }
 9970:         }
 9971:     }
 9972:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9973:         (defined($rolenames{$type})) && 
 9974:         (defined($prp{$short}{$rolenames{$type}}))) {
 9975:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9976:     } elsif ($cid ne '') {
 9977:         my $crstype = $env{'course.'.$cid.'.type'};
 9978:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9979:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9980:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9981:         }
 9982:     }
 9983:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9984: }
 9985: 
 9986: # ----------------------------------------------------------------- Assign Role
 9987: 
 9988: sub assignrole {
 9989:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9990:         $context)=@_;
 9991:     my $mrole;
 9992:     if ($role =~ /^cr\//) {
 9993:         my $cwosec=$url;
 9994:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9995: 	unless (&allowed('ccr',$cwosec)) {
 9996:            my $refused = 1;
 9997:            if ($context eq 'requestcourses') {
 9998:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9999:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10000:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10001:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10002:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10003:                            if ($crsenv{'internal.courseowner'} eq
10004:                                $env{'user.name'}.':'.$env{'user.domain'}) {
10005:                                $refused = '';
10006:                            }
10007:                        }
10008:                    }
10009:                }
10010:            }
10011:            if ($refused) {
10012:                &logthis('Refused custom assignrole: '.
10013:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10014:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10015:                return 'refused';
10016:            }
10017:         }
10018:         $mrole='cr';
10019:     } elsif ($role =~ /^gr\//) {
10020:         my $cwogrp=$url;
10021:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10022:         unless (&allowed('mdg',$cwogrp)) {
10023:             &logthis('Refused group assignrole: '.
10024:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10025:                     $env{'user.name'}.' at '.$env{'user.domain'});
10026:             return 'refused';
10027:         }
10028:         $mrole='gr';
10029:     } else {
10030:         my $cwosec=$url;
10031:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10032:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10033:             my $refused;
10034:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
10035:                 if (!(&allowed('c'.$role,$url))) {
10036:                     $refused = 1;
10037:                 }
10038:             } else {
10039:                 $refused = 1;
10040:             }
10041:             if ($refused) {
10042:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10043:                 if (!$selfenroll && $context eq 'course') {
10044:                     my %crsenv;
10045:                     if ($role eq 'cc' || $role eq 'co') {
10046:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10047:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10048:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10049:                                 if ($crsenv{'internal.courseowner'} eq 
10050:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10051:                                     $refused = '';
10052:                                 }
10053:                             }
10054:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
10055:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10056:                                 if ($crsenv{'internal.courseowner'} eq 
10057:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10058:                                     $refused = '';
10059:                                 }
10060:                             }
10061:                         }
10062:                     }
10063:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10064:                     $refused = '';
10065:                 } elsif ($context eq 'requestcourses') {
10066:                     my @possroles = ('st','ta','ep','in','cc','co');
10067:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10068:                         my $wrongcc;
10069:                         if ($cnum =~ /^$match_community$/) {
10070:                             $wrongcc = 1 if ($role eq 'cc');
10071:                         } else {
10072:                             $wrongcc = 1 if ($role eq 'co');
10073:                         }
10074:                         unless ($wrongcc) {
10075:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10076:                             if ($crsenv{'internal.courseowner'} eq 
10077:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10078:                                 $refused = '';
10079:                             }
10080:                         }
10081:                     }
10082:                 } elsif ($context eq 'requestauthor') {
10083:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
10084:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10085:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10086:                             $refused = '';
10087:                         } else {
10088:                             my %domdefaults = &get_domain_defaults($udom);
10089:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10090:                                 my $checkbystatus;
10091:                                 if ($env{'user.adv'}) {
10092:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10093:                                     if ($disposition eq 'automatic') {
10094:                                         $refused = '';
10095:                                     } elsif ($disposition eq '') {
10096:                                         $checkbystatus = 1;
10097:                                     }
10098:                                 } else {
10099:                                     $checkbystatus = 1;
10100:                                 }
10101:                                 if ($checkbystatus) {
10102:                                     if ($env{'environment.inststatus'}) {
10103:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10104:                                         foreach my $type (@inststatuses) {
10105:                                             if (($type ne '') &&
10106:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10107:                                                 $refused = '';
10108:                                             }
10109:                                         }
10110:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10111:                                         $refused = '';
10112:                                     }
10113:                                 }
10114:                             }
10115:                         }
10116:                     }
10117:                 }
10118:                 if ($refused) {
10119:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10120:                              ' '.$role.' '.$end.' '.$start.' by '.
10121: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10122:                     return 'refused';
10123:                 }
10124:             }
10125:         } elsif ($role eq 'au') {
10126:             if ($url ne '/'.$udom.'/') {
10127:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10128:                          ' to assign author role for '.$uname.':'.$udom.
10129:                          ' in domain: '.$url.' refused (wrong domain).');
10130:                 return 'refused';
10131:             }
10132:         }
10133:         $mrole=$role;
10134:     }
10135:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10136:                 "$udom:$uname:$url".'_'."$mrole=$role";
10137:     if ($end) { $command.='_'.$end; }
10138:     if ($start) {
10139: 	if ($end) { 
10140:            $command.='_'.$start; 
10141:         } else {
10142:            $command.='_0_'.$start;
10143:         }
10144:     }
10145:     my $origstart = $start;
10146:     my $origend = $end;
10147:     my $delflag;
10148: # actually delete
10149:     if ($deleteflag) {
10150: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10151: # modify command to delete the role
10152:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10153:                 "$udom:$uname:$url".'_'."$mrole";
10154: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10155: # set start and finish to negative values for userrolelog
10156:            $start=-1;
10157:            $end=-1;
10158:            $delflag = 1;
10159:         }
10160:     }
10161: # send command
10162:     my $answer=&reply($command,&homeserver($uname,$udom));
10163: # log new user role if status is ok
10164:     if ($answer eq 'ok') {
10165: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10166:         if (($role eq 'cc') || ($role eq 'in') ||
10167:             ($role eq 'ep') || ($role eq 'ad') ||
10168:             ($role eq 'ta') || ($role eq 'st') ||
10169:             ($role=~/^cr/) || ($role eq 'gr') ||
10170:             ($role eq 'co')) {
10171: # for course roles, perform group memberships changes triggered by role change.
10172:             unless ($role =~ /^gr/) {
10173:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10174:                                                  $origstart,$selfenroll,$context);
10175:             }
10176:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10177:                            $selfenroll,$context);
10178:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10179:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10180:                  ($role eq 'da')) {
10181:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10182:                            $context);
10183:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10184:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10185:                              $context);
10186:         }
10187:         if ($role eq 'cc') {
10188:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10189:         }
10190:     }
10191:     return $answer;
10192: }
10193: 
10194: sub autoupdate_coowners {
10195:     my ($url,$end,$start,$uname,$udom) = @_;
10196:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10197:     if (($cdom ne '') && ($cnum ne '')) {
10198:         my $now = time;
10199:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10200:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10201:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10202:             my $instcode = $coursehash{'internal.coursecode'};
10203:             my $xlists = $coursehash{'internal.crosslistings'};
10204:             if ($instcode ne '') {
10205:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10206:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10207:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10208:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10209:                         unless ($result eq 'valid') {
10210:                             if ($xlists ne '') {
10211:                                 foreach my $xlist (split(',',$xlists)) {
10212:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
10213:                                     $result =
10214:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10215:                                                                       $inst_crosslist,$uname.':'.$udom);
10216:                                     last if ($result eq 'valid');
10217:                                 }
10218:                             }
10219:                         }
10220:                         if ($result eq 'valid') {
10221:                             if ($coursehash{'internal.co-owners'}) {
10222:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10223:                                     push(@newcoowners,$coowner);
10224:                                 }
10225:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10226:                                     push(@newcoowners,$uname.':'.$udom);
10227:                                 }
10228:                                 @newcoowners = sort(@newcoowners);
10229:                             } else {
10230:                                 push(@newcoowners,$uname.':'.$udom);
10231:                             }
10232:                         } elsif ($coursehash{'internal.co-owners'}) {
10233:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10234:                                 unless ($coowner eq $uname.':'.$udom) {
10235:                                     push(@newcoowners,$coowner);
10236:                                 }
10237:                             }
10238:                             unless (@newcoowners > 0) {
10239:                                 $delcoowners = 1;
10240:                                 $coowners = '';
10241:                             }
10242:                         }
10243:                         if (@newcoowners || $delcoowners) {
10244:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
10245:                                             $delcoowners,@newcoowners);
10246:                         }
10247:                     }
10248:                 }
10249:             }
10250:         }
10251:     }
10252: }
10253: 
10254: sub store_coowners {
10255:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10256:     my $cid = $cdom.'_'.$cnum;
10257:     my ($coowners,$delresult,$putresult);
10258:     if (@newcoowners) {
10259:         $coowners = join(',',@newcoowners);
10260:         my %coownershash = (
10261:                             'internal.co-owners' => $coowners,
10262:                            );
10263:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10264:         if ($putresult eq 'ok') {
10265:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
10266:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10267:             }
10268:         }
10269:     }
10270:     if ($delcoowners) {
10271:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10272:         if ($delresult eq 'ok') {
10273:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
10274:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10275:             }
10276:         }
10277:     }
10278:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10279:         my %crsinfo =
10280:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10281:         if (ref($crsinfo{$cid}) eq 'HASH') {
10282:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10283:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10284:         }
10285:     }
10286: }
10287: 
10288: # -------------------------------------------------- Modify user authentication
10289: # Overrides without validation
10290: 
10291: sub modifyuserauth {
10292:     my ($udom,$uname,$umode,$upass)=@_;
10293:     my $uhome=&homeserver($uname,$udom);
10294:     my $allowed;
10295:     if (&allowed('mau',$udom)) {
10296:         $allowed = 1;
10297:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10298:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10299:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10300:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10301:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10302:         if (($cdom ne '') && ($cnum ne '')) {
10303:             my $is_owner = &is_course_owner($cdom,$cnum);
10304:             if ($is_owner) {
10305:                 $allowed = 1;
10306:             }
10307:         }
10308:     }
10309:     unless ($allowed) { return 'refused'; }
10310:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10311:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10312:              ' in domain '.$env{'request.role.domain'});  
10313:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10314: 		     &escape($upass),$uhome);
10315:     my $ip = &get_requestor_ip();
10316:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10317:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10318:          '(Remote '.$ip.'): '.$reply);
10319:     &log($udom,,$uname,$uhome,
10320:         'Authentication changed by '.$env{'user.domain'}.', '.
10321:                                      $env{'user.name'}.', '.$umode.
10322:          '(Remote '.$ip.'): '.$reply);
10323:     unless ($reply eq 'ok') {
10324:         &logthis('Authentication mode error: '.$reply);
10325: 	return 'error: '.$reply;
10326:     }   
10327:     return 'ok';
10328: }
10329: 
10330: # --------------------------------------------------------------- Modify a user
10331: 
10332: sub modifyuser {
10333:     my ($udom,    $uname, $uid,
10334:         $umode,   $upass, $first,
10335:         $middle,  $last,  $gene,
10336:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10337:     $udom= &LONCAPA::clean_domain($udom);
10338:     $uname=&LONCAPA::clean_username($uname);
10339:     my $showcandelete = 'none';
10340:     if (ref($candelete) eq 'ARRAY') {
10341:         if (@{$candelete} > 0) {
10342:             $showcandelete = join(', ',@{$candelete});
10343:         }
10344:     }
10345:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10346:              $umode.', '.$first.', '.$middle.', '.
10347: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10348:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10349:                                      ' desiredhome not specified'). 
10350:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10351:              ' in domain '.$env{'request.role.domain'});
10352:     my $uhome=&homeserver($uname,$udom,'true');
10353:     my $newuser;
10354:     if ($uhome eq 'no_host') {
10355:         $newuser = 1;
10356:     }
10357: # ----------------------------------------------------------------- Create User
10358:     if (($uhome eq 'no_host') && 
10359: 	(($umode && $upass) || ($umode eq 'localauth'))) {
10360:         my $unhome='';
10361:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10362:             $unhome = $desiredhome;
10363: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10364: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10365:         } else { # load balancing routine for determining $unhome
10366:             my $loadm=10000000;
10367: 	    my %servers = &get_servers($udom,'library');
10368: 	    foreach my $tryserver (keys(%servers)) {
10369: 		my $answer=reply('load',$tryserver);
10370: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10371: 		    $loadm=$answer;
10372: 		    $unhome=$tryserver;
10373: 		}
10374: 	    }
10375:         }
10376:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10377: 	    return 'error: unable to find a home server for '.$uname.
10378:                    ' in domain '.$udom;
10379:         }
10380:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10381:                          &escape($upass),$unhome);
10382: 	unless ($reply eq 'ok') {
10383:             return 'error: '.$reply;
10384:         }   
10385:         $uhome=&homeserver($uname,$udom,'true');
10386:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10387: 	    return 'error: unable verify users home machine.';
10388:         }
10389:     }   # End of creation of new user
10390: # ---------------------------------------------------------------------- Add ID
10391:     if ($uid) {
10392:        $uid=~tr/A-Z/a-z/;
10393:        my %uidhash=&idrget($udom,$uname);
10394:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10395:          && (!$forceid)) {
10396: 	  unless ($uid eq $uidhash{$uname}) {
10397: 	      return 'error: user id "'.$uid.'" does not match '.
10398:                   'current user id "'.$uidhash{$uname}.'".';
10399:           }
10400:        } else {
10401: 	  &idput($udom,($uname => $uid));
10402:        }
10403:     }
10404: # -------------------------------------------------------------- Add names, etc
10405:     my @tmp=&get('environment',
10406: 		   ['firstname','middlename','lastname','generation','id',
10407:                     'permanentemail','inststatus'],
10408: 		   $udom,$uname);
10409:     my (%names,%oldnames);
10410:     if ($tmp[0] =~ m/^error:.*/) { 
10411:         %names=(); 
10412:     } else {
10413:         %names = @tmp;
10414:         %oldnames = %names;
10415:     }
10416: #
10417: # If name, email and/or uid are blank (e.g., because an uploaded file
10418: # of users did not contain them), do not overwrite existing values
10419: # unless field is in $candelete array ref.  
10420: #
10421: 
10422:     my @fields = ('firstname','middlename','lastname','generation',
10423:                   'permanentemail','id');
10424:     my %newvalues;
10425:     if (ref($candelete) eq 'ARRAY') {
10426:         foreach my $field (@fields) {
10427:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10428:                 if ($field eq 'firstname') {
10429:                     $names{$field} = $first;
10430:                 } elsif ($field eq 'middlename') {
10431:                     $names{$field} = $middle;
10432:                 } elsif ($field eq 'lastname') {
10433:                     $names{$field} = $last;
10434:                 } elsif ($field eq 'generation') { 
10435:                     $names{$field} = $gene;
10436:                 } elsif ($field eq 'permanentemail') {
10437:                     $names{$field} = $email;
10438:                 } elsif ($field eq 'id') {
10439:                     $names{$field}  = $uid;
10440:                 }
10441:             }
10442:         }
10443:     }
10444:     if ($first)  { $names{'firstname'}  = $first; }
10445:     if (defined($middle)) { $names{'middlename'} = $middle; }
10446:     if ($last)   { $names{'lastname'}   = $last; }
10447:     if (defined($gene))   { $names{'generation'} = $gene; }
10448:     if ($email) {
10449:        $email=~s/[^\w\@\.\-\,]//gs;
10450:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10451:     }
10452:     if ($uid) { $names{'id'}  = $uid; }
10453:     if (defined($inststatus)) {
10454:         $names{'inststatus'} = '';
10455:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10456:         if (ref($usertypes) eq 'HASH') {
10457:             my @okstatuses; 
10458:             foreach my $item (split(/:/,$inststatus)) {
10459:                 if (defined($usertypes->{$item})) {
10460:                     push(@okstatuses,$item);  
10461:                 }
10462:             }
10463:             if (@okstatuses) {
10464:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10465:             }
10466:         }
10467:     }
10468:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10469:                  $umode.', '.$first.', '.$middle.', '.
10470:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10471:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10472:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10473:     } else {
10474:         $logmsg .= ' during self creation';
10475:     }
10476:     my $changed;
10477:     if ($newuser) {
10478:         $changed = 1;
10479:     } else {
10480:         foreach my $field (@fields) {
10481:             if ($names{$field} ne $oldnames{$field}) {
10482:                 $changed = 1;
10483:                 last;
10484:             }
10485:         }
10486:     }
10487:     unless ($changed) {
10488:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10489:         &logthis($logmsg);
10490:         return 'ok';
10491:     }
10492:     my $reply = &put('environment', \%names, $udom,$uname);
10493:     if ($reply ne 'ok') { 
10494:         return 'error: '.$reply;
10495:     }
10496:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10497:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10498:     }
10499:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10500:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10501:     $logmsg = 'Success modifying user '.$logmsg;
10502:     &logthis($logmsg);
10503:     return 'ok';
10504: }
10505: 
10506: # -------------------------------------------------------------- Modify student
10507: 
10508: sub modifystudent {
10509:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10510:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10511:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10512:     if (!$cid) {
10513: 	unless ($cid=$env{'request.course.id'}) {
10514: 	    return 'not_in_class';
10515: 	}
10516:     }
10517: # --------------------------------------------------------------- Make the user
10518:     my $reply=&modifyuser
10519: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10520:          $desiredhome,$email,$inststatus);
10521:     unless ($reply eq 'ok') { return $reply; }
10522:     # This will cause &modify_student_enrollment to get the uid from the
10523:     # student's environment
10524:     $uid = undef if (!$forceid);
10525:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10526: 					$gene,$usec,$end,$start,$type,$locktype,
10527:                                         $cid,$selfenroll,$context,$credits,$instsec);
10528:     return $reply;
10529: }
10530: 
10531: sub modify_student_enrollment {
10532:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10533:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10534:     my ($cdom,$cnum,$chome);
10535:     if (!$cid) {
10536: 	unless ($cid=$env{'request.course.id'}) {
10537: 	    return 'not_in_class';
10538: 	}
10539: 	$cdom=$env{'course.'.$cid.'.domain'};
10540: 	$cnum=$env{'course.'.$cid.'.num'};
10541:     } else {
10542: 	($cdom,$cnum)=split(/_/,$cid);
10543:     }
10544:     $chome=$env{'course.'.$cid.'.home'};
10545:     if (!$chome) {
10546: 	$chome=&homeserver($cnum,$cdom);
10547:     }
10548:     if (!$chome) { return 'unknown_course'; }
10549:     # Make sure the user exists
10550:     my $uhome=&homeserver($uname,$udom);
10551:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10552: 	return 'error: no such user';
10553:     }
10554:     # Get student data if we were not given enough information
10555:     if (!defined($first)  || $first  eq '' || 
10556:         !defined($last)   || $last   eq '' || 
10557:         !defined($uid)    || $uid    eq '' || 
10558:         !defined($middle) || $middle eq '' || 
10559:         !defined($gene)   || $gene   eq '') {
10560:         # They did not supply us with enough data to enroll the student, so
10561:         # we need to pick up more information.
10562:         my %tmp = &get('environment',
10563:                        ['firstname','middlename','lastname', 'generation','id']
10564:                        ,$udom,$uname);
10565: 
10566:         #foreach my $key (keys(%tmp)) {
10567:         #    &logthis("key $key = ".$tmp{$key});
10568:         #}
10569:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10570:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10571:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10572:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10573:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10574:     }
10575:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10576:     my $user = "$uname:$udom";
10577:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10578:     my $reply=cput('classlist',
10579: 		   {$user => 
10580: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10581: 		   $cdom,$cnum);
10582:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10583:         &devalidate_getsection_cache($udom,$uname,$cid);
10584:     } else { 
10585: 	return 'error: '.$reply;
10586:     }
10587:     # Add student role to user
10588:     my $uurl='/'.$cid;
10589:     $uurl=~s/\_/\//g;
10590:     if ($usec) {
10591: 	$uurl.='/'.$usec;
10592:     }
10593:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10594:                              $selfenroll,$context);
10595:     if ($result ne 'ok') {
10596:         if ($old_entry{$user} ne '') {
10597:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10598:         } else {
10599:             $reply = &del('classlist',[$user],$cdom,$cnum);
10600:         }
10601:     }
10602:     return $result; 
10603: }
10604: 
10605: sub format_name {
10606:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10607:     my $name;
10608:     if ($first ne 'lastname') {
10609: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10610:     } else {
10611: 	if ($lastname=~/\S/) {
10612: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10613: 	    $name=~s/\s+,/,/;
10614: 	} else {
10615: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10616: 	}
10617:     }
10618:     $name=~s/^\s+//;
10619:     $name=~s/\s+$//;
10620:     $name=~s/\s+/ /g;
10621:     return $name;
10622: }
10623: 
10624: # ------------------------------------------------- Write to course preferences
10625: 
10626: sub writecoursepref {
10627:     my ($courseid,%prefs)=@_;
10628:     $courseid=~s/^\///;
10629:     $courseid=~s/\_/\//g;
10630:     my ($cdomain,$cnum)=split(/\//,$courseid);
10631:     my $chome=homeserver($cnum,$cdomain);
10632:     if (($chome eq '') || ($chome eq 'no_host')) { 
10633: 	return 'error: no such course';
10634:     }
10635:     my $cstring='';
10636:     foreach my $pref (keys(%prefs)) {
10637: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10638:     }
10639:     $cstring=~s/\&$//;
10640:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10641: }
10642: 
10643: # ---------------------------------------------------------- Make/modify course
10644: 
10645: sub createcourse {
10646:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10647:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
10648:     $url=&declutter($url);
10649:     my $cid='';
10650:     if ($context eq 'requestcourses') {
10651:         my $can_create = 0;
10652:         my ($ownername,$ownerdom) = split(':',$course_owner);
10653:         if ($udom eq $ownerdom) {
10654:             my $reload;
10655:             if (($callercontext eq 'auto') &&
10656:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
10657:                 $reload = 'reload';
10658:             }
10659:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
10660:                                   $context)) {
10661:                 $can_create = 1;
10662:             }
10663:         } else {
10664:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10665:                                            $category);
10666:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10667:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10668:                 if (@curr > 0) {
10669:                     my @options = qw(approval validate autolimit);
10670:                     my $optregex = join('|',@options);
10671:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10672:                         $can_create = 1;
10673:                     }
10674:                 }
10675:             }
10676:         }
10677:         if ($can_create) {
10678:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10679:                 unless (&allowed('ccc',$udom)) {
10680:                     return 'refused'; 
10681:                 }
10682:             }
10683:         } else {
10684:             return 'refused';
10685:         }
10686:     } elsif (!&allowed('ccc',$udom)) {
10687:         return 'refused';
10688:     }
10689: # --------------------------------------------------------------- Get Unique ID
10690:     my $uname;
10691:     if ($cnum =~ /^$match_courseid$/) {
10692:         my $chome=&homeserver($cnum,$udom,'true');
10693:         if (($chome eq '') || ($chome eq 'no_host')) {
10694:             $uname = $cnum;
10695:         } else {
10696:             $uname = &generate_coursenum($udom,$crstype);
10697:         }
10698:     } else {
10699:         $uname = &generate_coursenum($udom,$crstype);
10700:     }
10701:     return $uname if ($uname =~ /^error/);
10702: # -------------------------------------------------- Check supplied server name
10703:     if (!defined($course_server)) {
10704:         if (defined(&domain($udom,'primary'))) {
10705:             $course_server = &domain($udom,'primary');
10706:         } else {
10707:             $course_server = $env{'user.home'}; 
10708:         }
10709:     }
10710:     my %host_servers =
10711:         &Apache::lonnet::get_servers($udom,'library');
10712:     unless ($host_servers{$course_server}) {
10713:         return 'error: invalid home server for course: '.$course_server;
10714:     }
10715: # ------------------------------------------------------------- Make the course
10716:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10717:                       $course_server);
10718:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10719:     my $uhome=&homeserver($uname,$udom,'true');
10720:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10721: 	return 'error: no such course';
10722:     }
10723: # ----------------------------------------------------------------- Course made
10724: # log existence
10725:     my $now = time;
10726:     my $newcourse = {
10727:                     $udom.'_'.$uname => {
10728:                                      description => $description,
10729:                                      inst_code   => $inst_code,
10730:                                      owner       => $course_owner,
10731:                                      type        => $crstype,
10732:                                      creator     => $env{'user.name'}.':'.
10733:                                                     $env{'user.domain'},
10734:                                      created     => $now,
10735:                                      context     => $context,
10736:                                                 },
10737:                     };
10738:     &courseidput($udom,$newcourse,$uhome,'notime');
10739: # set toplevel url
10740:     my $topurl=$url;
10741:     unless ($nonstandard) {
10742: # ------------------------------------------ For standard courses, make top url
10743:         my $mapurl=&clutter($url);
10744:         if ($mapurl eq '/res/') { $mapurl=''; }
10745:         $env{'form.initmap'}=(<<ENDINITMAP);
10746: <map>
10747: <resource id="1" type="start"></resource>
10748: <resource id="2" src="$mapurl"></resource>
10749: <resource id="3" type="finish"></resource>
10750: <link index="1" from="1" to="2"></link>
10751: <link index="2" from="2" to="3"></link>
10752: </map>
10753: ENDINITMAP
10754:         $topurl=&declutter(
10755:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10756:                           );
10757:     }
10758: # ----------------------------------------------------------- Write preferences
10759:     &writecoursepref($udom.'_'.$uname,
10760:                      ('description'              => $description,
10761:                       'url'                      => $topurl,
10762:                       'internal.creator'         => $env{'user.name'}.':'.
10763:                                                     $env{'user.domain'},
10764:                       'internal.created'         => $now,
10765:                       'internal.creationcontext' => $context)
10766:                     );
10767:     return '/'.$udom.'/'.$uname;
10768: }
10769: 
10770: # ------------------------------------------------------------------- Create ID
10771: sub generate_coursenum {
10772:     my ($udom,$crstype) = @_;
10773:     my $domdesc = &domain($udom);
10774:     return 'error: invalid domain' if ($domdesc eq '');
10775:     my $first;
10776:     if ($crstype eq 'Community') {
10777:         $first = '0';
10778:     } else {
10779:         $first = int(1+rand(9)); 
10780:     } 
10781:     my $uname=$first.
10782:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10783:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10784:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10785: # ----------------------------------------------- Make sure that does not exist
10786:     my $uhome=&homeserver($uname,$udom,'true');
10787:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10788:         if ($crstype eq 'Community') {
10789:             $first = '0';
10790:         } else {
10791:             $first = int(1+rand(9));
10792:         }
10793:         $uname=$first.
10794:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10795:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10796:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10797:         $uhome=&homeserver($uname,$udom,'true');
10798:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10799:             return 'error: unable to generate unique course-ID';
10800:         }
10801:     }
10802:     return $uname;
10803: }
10804: 
10805: sub is_course {
10806:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10807:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10808:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10809:     my $uhome=&homeserver($cnum,$cdom);
10810:     my $iscourse;
10811:     if (grep { $_ eq $uhome } current_machine_ids()) {
10812:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10813:     } else {
10814:         my $hashid = $cdom.':'.$cnum;
10815:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10816:         unless (defined($cached)) {
10817:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10818:                                         $cnum,undef,undef,'.');
10819:             $iscourse = 0;
10820:             if (exists($courses{$cdom.'_'.$cnum})) {
10821:                 $iscourse = 1;
10822:             }
10823:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10824:         }
10825:     }
10826:     return unless($iscourse);
10827:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10828: }
10829: 
10830: sub store_userdata {
10831:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10832:     my $result;
10833:     if ($datakey ne '') {
10834:         if (ref($storehash) eq 'HASH') {
10835:             if ($udom eq '' || $uname eq '') {
10836:                 $udom = $env{'user.domain'};
10837:                 $uname = $env{'user.name'};
10838:             }
10839:             my $uhome=&homeserver($uname,$udom);
10840:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10841:                 $result = 'error: no_host';
10842:             } else {
10843:                 $storehash->{'ip'} = &get_requestor_ip();
10844:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10845: 
10846:                 my $namevalue='';
10847:                 foreach my $key (keys(%{$storehash})) {
10848:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10849:                 }
10850:                 $namevalue=~s/\&$//;
10851:                 unless ($namespace eq 'courserequests') {
10852:                     $datakey = &escape($datakey);
10853:                 }
10854:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10855:                                   $namevalue,$uhome);
10856:             }
10857:         } else {
10858:             $result = 'error: data to store was not a hash reference'; 
10859:         }
10860:     } else {
10861:         $result= 'error: invalid requestkey'; 
10862:     }
10863:     return $result;
10864: }
10865: 
10866: # ---------------------------------------------------------- Assign Custom Role
10867: 
10868: sub assigncustomrole {
10869:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10870:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10871:                        $end,$start,$deleteflag,$selfenroll,$context);
10872: }
10873: 
10874: # ----------------------------------------------------------------- Revoke Role
10875: 
10876: sub revokerole {
10877:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10878:     my $now=time;
10879:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10880: }
10881: 
10882: # ---------------------------------------------------------- Revoke Custom Role
10883: 
10884: sub revokecustomrole {
10885:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10886:     my $now=time;
10887:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10888:            $deleteflag,$selfenroll,$context);
10889: }
10890: 
10891: # ------------------------------------------------------------ Disk usage
10892: sub diskusage {
10893:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10894:     $directorypath =~ s/\/$//;
10895:     my $listing=&reply('du2:'.&escape($directorypath).':'
10896:                        .&escape($getpropath).':'.&escape($uname).':'
10897:                        .&escape($udom),homeserver($uname,$udom));
10898:     if ($listing eq 'unknown_cmd') {
10899:         if ($getpropath) {
10900:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10901:         }
10902:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10903:     }
10904:     return $listing;
10905: }
10906: 
10907: sub is_locked {
10908:     my ($file_name, $domain, $user, $which) = @_;
10909:     my @check;
10910:     my $is_locked;
10911:     push (@check,$file_name);
10912:     my %locked = &get('file_permissions',\@check,
10913: 		      $env{'user.domain'},$env{'user.name'});
10914:     my ($tmp)=keys(%locked);
10915:     if ($tmp=~/^error:/) { undef(%locked); }
10916:     
10917:     if (ref($locked{$file_name}) eq 'ARRAY') {
10918:         $is_locked = 'false';
10919:         foreach my $entry (@{$locked{$file_name}}) {
10920:            if (ref($entry) eq 'ARRAY') {
10921:                $is_locked = 'true';
10922:                if (ref($which) eq 'ARRAY') {
10923:                    push(@{$which},$entry);
10924:                } else {
10925:                    last;
10926:                }
10927:            }
10928:        }
10929:     } else {
10930:         $is_locked = 'false';
10931:     }
10932:     return $is_locked;
10933: }
10934: 
10935: sub declutter_portfile {
10936:     my ($file) = @_;
10937:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10938:     return $file;
10939: }
10940: 
10941: # ------------------------------------------------------------- Mark as Read Only
10942: 
10943: sub mark_as_readonly {
10944:     my ($domain,$user,$files,$what) = @_;
10945:     my %current_permissions = &dump('file_permissions',$domain,$user);
10946:     my ($tmp)=keys(%current_permissions);
10947:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10948:     foreach my $file (@{$files}) {
10949: 	$file = &declutter_portfile($file);
10950:         push(@{$current_permissions{$file}},$what);
10951:     }
10952:     &put('file_permissions',\%current_permissions,$domain,$user);
10953:     return;
10954: }
10955: 
10956: # ------------------------------------------------------------Save Selected Files
10957: 
10958: sub save_selected_files {
10959:     my ($user, $path, @files) = @_;
10960:     my $filename = $user."savedfiles";
10961:     my @other_files = &files_not_in_path($user, $path);
10962:     open (OUT,'>',LONCAPA::tempdir().$filename);
10963:     foreach my $file (@files) {
10964:         print (OUT $env{'form.currentpath'}.$file."\n");
10965:     }
10966:     foreach my $file (@other_files) {
10967:         print (OUT $file."\n");
10968:     }
10969:     close (OUT);
10970:     return 'ok';
10971: }
10972: 
10973: sub clear_selected_files {
10974:     my ($user) = @_;
10975:     my $filename = $user."savedfiles";
10976:     open (OUT,'>',LONCAPA::tempdir().$filename);
10977:     print (OUT undef);
10978:     close (OUT);
10979:     return ("ok");    
10980: }
10981: 
10982: sub files_in_path {
10983:     my ($user, $path) = @_;
10984:     my $filename = $user."savedfiles";
10985:     my %return_files;
10986:     open (IN,'<',LONCAPA::tempdir().$filename);
10987:     while (my $line_in = <IN>) {
10988:         chomp ($line_in);
10989:         my @paths_and_file = split (m!/!, $line_in);
10990:         my $file_part = pop (@paths_and_file);
10991:         my $path_part = join ('/', @paths_and_file);
10992:         $path_part.='/';
10993:         my $path_and_file = $path_part.$file_part;
10994:         if ($path_part eq $path) {
10995:             $return_files{$file_part}= 'selected';
10996:         }
10997:     }
10998:     close (IN);
10999:     return (\%return_files);
11000: }
11001: 
11002: # called in portfolio select mode, to show files selected NOT in current directory
11003: sub files_not_in_path {
11004:     my ($user, $path) = @_;
11005:     my $filename = $user."savedfiles";
11006:     my @return_files;
11007:     my $path_part;
11008:     open(IN, '<',LONCAPA::tempdir().$filename);
11009:     while (my $line = <IN>) {
11010:         #ok, I know it's clunky, but I want it to work
11011:         my @paths_and_file = split(m|/|, $line);
11012:         my $file_part = pop(@paths_and_file);
11013:         chomp($file_part);
11014:         my $path_part = join('/', @paths_and_file);
11015:         $path_part .= '/';
11016:         my $path_and_file = $path_part.$file_part;
11017:         if ($path_part ne $path) {
11018:             push(@return_files, ($path_and_file));
11019:         }
11020:     }
11021:     close(OUT);
11022:     return (@return_files);
11023: }
11024: 
11025: #----------------------------------------------Get portfolio file permissions
11026: 
11027: sub get_portfile_permissions {
11028:     my ($domain,$user) = @_;
11029:     my %current_permissions = &dump('file_permissions',$domain,$user);
11030:     my ($tmp)=keys(%current_permissions);
11031:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11032:     return \%current_permissions;
11033: }
11034: 
11035: #---------------------------------------------Get portfolio file access controls
11036: 
11037: sub get_access_controls {
11038:     my ($current_permissions,$group,$file) = @_;
11039:     my %access;
11040:     my $real_file = $file;
11041:     $file =~ s/\.meta$//;
11042:     if (defined($file)) {
11043:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11044:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11045:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11046:             }
11047:         }
11048:     } else {
11049:         foreach my $key (keys(%{$current_permissions})) {
11050:             if ($key =~ /\0accesscontrol$/) {
11051:                 if (defined($group)) {
11052:                     if ($key !~ m-^\Q$group\E/-) {
11053:                         next;
11054:                     }
11055:                 }
11056:                 my ($fullpath) = split(/\0/,$key);
11057:                 if (ref($$current_permissions{$key}) eq 'HASH') {
11058:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
11059:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11060:                     }
11061:                 }
11062:             }
11063:         }
11064:     }
11065:     return %access;
11066: }
11067: 
11068: sub modify_access_controls {
11069:     my ($file_name,$changes,$domain,$user)=@_;
11070:     my ($outcome,$deloutcome);
11071:     my %store_permissions;
11072:     my %new_values;
11073:     my %new_control;
11074:     my %translation;
11075:     my @deletions = ();
11076:     my $now = time;
11077:     if (exists($$changes{'activate'})) {
11078:         if (ref($$changes{'activate'}) eq 'HASH') {
11079:             my @newitems = sort(keys(%{$$changes{'activate'}}));
11080:             my $numnew = scalar(@newitems);
11081:             for (my $i=0; $i<$numnew; $i++) {
11082:                 my $newkey = $newitems[$i];
11083:                 my $newid = &Apache::loncommon::get_cgi_id();
11084:                 if ($newkey =~ /^\d+:/) { 
11085:                     $newkey =~ s/^(\d+)/$newid/;
11086:                     $translation{$1} = $newid;
11087:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11088:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11089:                     $translation{$1} = $newid;
11090:                 }
11091:                 $new_values{$file_name."\0".$newkey} = 
11092:                                           $$changes{'activate'}{$newitems[$i]};
11093:                 $new_control{$newkey} = $now;
11094:             }
11095:         }
11096:     }
11097:     my %todelete;
11098:     my %changed_items;
11099:     foreach my $action ('delete','update') {
11100:         if (exists($$changes{$action})) {
11101:             if (ref($$changes{$action}) eq 'HASH') {
11102:                 foreach my $key (keys(%{$$changes{$action}})) {
11103:                     my ($itemnum) = ($key =~ /^([^:]+):/);
11104:                     if ($action eq 'delete') { 
11105:                         $todelete{$itemnum} = 1;
11106:                     } else {
11107:                         $changed_items{$itemnum} = $key;
11108:                     }
11109:                 }
11110:             }
11111:         }
11112:     }
11113:     # get lock on access controls for file.
11114:     my $lockhash = {
11115:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11116:                                                        ':'.$env{'user.domain'},
11117:                    }; 
11118:     my $tries = 0;
11119:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11120:    
11121:     while (($gotlock ne 'ok') && $tries < 10) {
11122:         $tries ++;
11123:         sleep(0.1);
11124:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11125:     }
11126:     if ($gotlock eq 'ok') {
11127:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11128:         my ($tmp)=keys(%curr_permissions);
11129:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
11130:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11131:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11132:             if (ref($curr_controls) eq 'HASH') {
11133:                 foreach my $control_item (keys(%{$curr_controls})) {
11134:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
11135:                     if (defined($todelete{$itemnum})) {
11136:                         push(@deletions,$file_name."\0".$control_item);
11137:                     } else {
11138:                         if (defined($changed_items{$itemnum})) {
11139:                             $new_control{$changed_items{$itemnum}} = $now;
11140:                             push(@deletions,$file_name."\0".$control_item);
11141:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11142:                         } else {
11143:                             $new_control{$control_item} = $$curr_controls{$control_item};
11144:                         }
11145:                     }
11146:                 }
11147:             }
11148:         }
11149:         my ($group);
11150:         if (&is_course($domain,$user)) {
11151:             ($group,my $file) = split(/\//,$file_name,2);
11152:         }
11153:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11154:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11155:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
11156:         #  remove lock
11157:         my @del_lock = ($file_name."\0".'locked_access_records');
11158:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11159:         my $sqlresult =
11160:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11161:                                     $group);
11162:     } else {
11163:         $outcome = "error: could not obtain lockfile\n";  
11164:     }
11165:     return ($outcome,$deloutcome,\%new_values,\%translation);
11166: }
11167: 
11168: sub make_public_indefinitely {
11169:     my ($requrl) = @_;
11170:     my $now = time;
11171:     my $action = 'activate';
11172:     my $aclnum = 0;
11173:     if (&is_portfolio_url($requrl)) {
11174:         my (undef,$udom,$unum,$file_name,$group) =
11175:             &parse_portfolio_url($requrl);
11176:         my $current_perms = &get_portfile_permissions($udom,$unum);
11177:         my %access_controls = &get_access_controls($current_perms,
11178:                                                    $group,$file_name);
11179:         foreach my $key (keys(%{$access_controls{$file_name}})) {
11180:             my ($num,$scope,$end,$start) = 
11181:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11182:             if ($scope eq 'public') {
11183:                 if ($start <= $now && $end == 0) {
11184:                     $action = 'none';
11185:                 } else {
11186:                     $action = 'update';
11187:                     $aclnum = $num;
11188:                 }
11189:                 last;
11190:             }
11191:         }
11192:         if ($action eq 'none') {
11193:              return 'ok';
11194:         } else {
11195:             my %changes;
11196:             my $newend = 0;
11197:             my $newstart = $now;
11198:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
11199:             $changes{$action}{$newkey} = {
11200:                 type => 'public',
11201:                 time => {
11202:                     start => $newstart,
11203:                     end   => $newend,
11204:                 },
11205:             };
11206:             my ($outcome,$deloutcome,$new_values,$translation) =
11207:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
11208:             return $outcome;
11209:         }
11210:     } else {
11211:         return 'invalid';
11212:     }
11213: }
11214: 
11215: #------------------------------------------------------Get Marked as Read Only
11216: 
11217: sub get_marked_as_readonly {
11218:     my ($domain,$user,$what,$group) = @_;
11219:     my $current_permissions = &get_portfile_permissions($domain,$user);
11220:     my @readonly_files;
11221:     my $cmp1=$what;
11222:     if (ref($what)) { $cmp1=join('',@{$what}) };
11223:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11224:         if (defined($group)) {
11225:             if ($file_name !~ m-^\Q$group\E/-) {
11226:                 next;
11227:             }
11228:         }
11229:         if (ref($value) eq "ARRAY"){
11230:             foreach my $stored_what (@{$value}) {
11231:                 my $cmp2=$stored_what;
11232:                 if (ref($stored_what) eq 'ARRAY') {
11233:                     $cmp2=join('',@{$stored_what});
11234:                 }
11235:                 if ($cmp1 eq $cmp2) {
11236:                     push(@readonly_files, $file_name);
11237:                     last;
11238:                 } elsif (!defined($what)) {
11239:                     push(@readonly_files, $file_name);
11240:                     last;
11241:                 }
11242:             }
11243:         }
11244:     }
11245:     return @readonly_files;
11246: }
11247: #-----------------------------------------------------------Get Marked as Read Only Hash
11248: 
11249: sub get_marked_as_readonly_hash {
11250:     my ($current_permissions,$group,$what) = @_;
11251:     my %readonly_files;
11252:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11253:         if (defined($group)) {
11254:             if ($file_name !~ m-^\Q$group\E/-) {
11255:                 next;
11256:             }
11257:         }
11258:         if (ref($value) eq "ARRAY"){
11259:             foreach my $stored_what (@{$value}) {
11260:                 if (ref($stored_what) eq 'ARRAY') {
11261:                     foreach my $lock_descriptor(@{$stored_what}) {
11262:                         if ($lock_descriptor eq 'graded') {
11263:                             $readonly_files{$file_name} = 'graded';
11264:                         } elsif ($lock_descriptor eq 'handback') {
11265:                             $readonly_files{$file_name} = 'handback';
11266:                         } else {
11267:                             if (!exists($readonly_files{$file_name})) {
11268:                                 $readonly_files{$file_name} = 'locked';
11269:                             }
11270:                         }
11271:                     }
11272:                 } 
11273:             }
11274:         } 
11275:     }
11276:     return %readonly_files;
11277: }
11278: # ------------------------------------------------------------ Unmark as Read Only
11279: 
11280: sub unmark_as_readonly {
11281:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
11282:     # for portfolio submissions, $what contains [$symb,$crsid] 
11283:     my ($domain,$user,$what,$file_name,$group) = @_;
11284:     $file_name = &declutter_portfile($file_name);
11285:     my $symb_crs = $what;
11286:     if (ref($what)) { $symb_crs=join('',@$what); }
11287:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11288:     my ($tmp)=keys(%current_permissions);
11289:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11290:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11291:     foreach my $file (@readonly_files) {
11292: 	my $clean_file = &declutter_portfile($file);
11293: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11294: 	my $current_locks = $current_permissions{$file};
11295:         my @new_locks;
11296:         my @del_keys;
11297:         if (ref($current_locks) eq "ARRAY"){
11298:             foreach my $locker (@{$current_locks}) {
11299:                 my $compare=$locker;
11300:                 if (ref($locker) eq 'ARRAY') {
11301:                     $compare=join('',@{$locker});
11302:                     if ($compare ne $symb_crs) {
11303:                         push(@new_locks, $locker);
11304:                     }
11305:                 }
11306:             }
11307:             if (scalar(@new_locks) > 0) {
11308:                 $current_permissions{$file} = \@new_locks;
11309:             } else {
11310:                 push(@del_keys, $file);
11311:                 &del('file_permissions',\@del_keys, $domain, $user);
11312:                 delete($current_permissions{$file});
11313:             }
11314:         }
11315:     }
11316:     &put('file_permissions',\%current_permissions,$domain,$user);
11317:     return;
11318: }
11319: 
11320: # ------------------------------------------------------------ Directory lister
11321: 
11322: sub dirlist {
11323:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11324:     $uri=~s/^\///;
11325:     $uri=~s/\/$//;
11326:     my ($udom, $uname);
11327:     if ($getuserdir) {
11328:         $udom = $userdomain;
11329:         $uname = $username;
11330:     } else {
11331:         (undef,$udom,$uname)=split(/\//,$uri);
11332:         if(defined($userdomain)) {
11333:             $udom = $userdomain;
11334:         }
11335:         if(defined($username)) {
11336:             $uname = $username;
11337:         }
11338:     }
11339:     my ($dirRoot,$listing,@listing_results);
11340: 
11341:     $dirRoot = $perlvar{'lonDocRoot'};
11342:     if (defined($getpropath)) {
11343:         $dirRoot = &propath($udom,$uname);
11344:         $dirRoot =~ s/\/$//;
11345:     } elsif (defined($getuserdir)) {
11346:         my $subdir=$uname.'__';
11347:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11348:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11349:                    ."/$udom/$subdir/$uname";
11350:     } elsif (defined($alternateRoot)) {
11351:         $dirRoot = $alternateRoot;
11352:     }
11353: 
11354:     if($udom) {
11355:         if($uname) {
11356:             my $uhome = &homeserver($uname,$udom);
11357:             if ($uhome eq 'no_host') {
11358:                 return ([],'no_host');
11359:             }
11360:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11361:                               .$getuserdir.':'.&escape($dirRoot)
11362:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11363:             if ($listing eq 'unknown_cmd') {
11364:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11365:             } else {
11366:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11367:             }
11368:             if ($listing eq 'unknown_cmd') {
11369:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11370:                 @listing_results = split(/:/,$listing);
11371:             } else {
11372:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11373:             }
11374:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11375:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11376:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11377:                 return ([],$listing);
11378:             } else {
11379:                 return (\@listing_results);
11380:             }
11381:         } elsif(!$alternateRoot) {
11382:             my (%allusers,%listerror);
11383: 	    my %servers = &get_servers($udom,'library');
11384:  	    foreach my $tryserver (keys(%servers)) {
11385:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11386:                                   &escape($udom),$tryserver);
11387:                 if ($listing eq 'unknown_cmd') {
11388: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11389: 				      $udom, $tryserver);
11390:                 } else {
11391:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11392:                 }
11393: 		if ($listing eq 'unknown_cmd') {
11394: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11395: 				      $udom, $tryserver);
11396: 		    @listing_results = split(/:/,$listing);
11397: 		} else {
11398: 		    @listing_results =
11399: 			map { &unescape($_); } split(/:/,$listing);
11400: 		}
11401:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11402:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11403:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11404:                     $listerror{$tryserver} = $listing;
11405:                 } else {
11406: 		    foreach my $line (@listing_results) {
11407: 			my ($entry) = split(/&/,$line,2);
11408: 			$allusers{$entry} = 1;
11409: 		    }
11410: 		}
11411:             }
11412:             my @alluserslist=();
11413:             foreach my $user (sort(keys(%allusers))) {
11414:                 push(@alluserslist,$user.'&user');
11415:             }
11416:             if (!%listerror) {
11417:                 # no errors
11418:                 return (\@alluserslist);
11419:             } elsif (scalar(keys(%servers)) == 1) {
11420:                 # one library server, one error
11421:                 my ($key) = keys(%listerror);
11422:                 return (\@alluserslist, $listerror{$key});
11423:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11424:                 # con_lost indicates that we might miss data from at least one
11425:                 # library server
11426:                 return (\@alluserslist, 'con_lost');
11427:             } else {
11428:                 # multiple library servers and no con_lost -> data should be
11429:                 # complete.
11430:                 return (\@alluserslist);
11431:             }
11432: 
11433:         } else {
11434:             return ([],'missing username');
11435:         }
11436:     } elsif(!defined($getpropath)) {
11437:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11438:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11439:         return (\@all_domains);
11440:     } else {
11441:         return ([],'missing domain');
11442:     }
11443: }
11444: 
11445: # --------------------------------------------- GetFileTimestamp
11446: # This function utilizes dirlist and returns the date stamp for
11447: # when it was last modified.  It will also return an error of -1
11448: # if an error occurs
11449: 
11450: sub GetFileTimestamp {
11451:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11452:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11453:     $studentName   = &LONCAPA::clean_username($studentName);
11454:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11455:                                     undef,$getuserdir);
11456:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11457:         return -1;
11458:     }
11459:     if (ref($fileref) eq 'ARRAY') {
11460:         my @stats = split('&',$fileref->[0]);
11461:         # @stats contains first the filename, then the stat output
11462:         return $stats[10]; # so this is 10 instead of 9.
11463:     } else {
11464:         return -1;
11465:     }
11466: }
11467: 
11468: sub stat_file {
11469:     my ($uri) = @_;
11470:     $uri = &clutter_with_no_wrapper($uri);
11471: 
11472:     my ($udom,$uname,$file);
11473:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11474: 	($udom,$uname,$file) =
11475: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11476: 	$file = 'userfiles/'.$file;
11477:     }
11478:     if ($uri =~ m-^/res/-) {
11479: 	($udom,$uname) = 
11480: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11481: 	$file = $uri;
11482:     }
11483: 
11484:     if (!$udom || !$uname || !$file) {
11485: 	# unable to handle the uri
11486: 	return ();
11487:     }
11488:     my $getpropath;
11489:     if ($file =~ /^userfiles\//) {
11490:         $getpropath = 1;
11491:     }
11492:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11493:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11494:         return ();
11495:     } else {
11496:         if (ref($listref) eq 'ARRAY') {
11497:             my @stats = split('&',$listref->[0]);
11498: 	    shift(@stats); #filename is first
11499: 	    return @stats;
11500:         }
11501:     }
11502:     return ();
11503: }
11504: 
11505: # -------------------------------------------------------- Value of a Condition
11506: 
11507: # gets the value of a specific preevaluated condition
11508: #    stored in the string  $env{user.state.<cid>}
11509: # or looks up a condition reference in the bighash and if if hasn't
11510: # already been evaluated recurses into docondval to get the value of
11511: # the condition, then memoizing it to 
11512: #   $env{user.state.<cid>.<condition>}
11513: sub directcondval {
11514:     my $number=shift;
11515:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11516: 	&Apache::lonuserstate::evalstate();
11517:     }
11518:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11519: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11520:     } elsif ($number =~ /^_/) {
11521: 	my $sub_condition;
11522: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11523: 		&GDBM_READER(),0640)) {
11524: 	    $sub_condition=$bighash{'conditions'.$number};
11525: 	    untie(%bighash);
11526: 	}
11527: 	my $value = &docondval($sub_condition);
11528: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11529: 	return $value;
11530:     }
11531:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11532:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11533:     } else {
11534:        return 2;
11535:     }
11536: }
11537: 
11538: # get the collection of conditions for this resource
11539: sub condval {
11540:     my $condidx=shift;
11541:     my $allpathcond='';
11542:     foreach my $cond (split(/\|/,$condidx)) {
11543: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11544: 	    $allpathcond.=
11545: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11546: 	}
11547:     }
11548:     $allpathcond=~s/\|$//;
11549:     return &docondval($allpathcond);
11550: }
11551: 
11552: #evaluates an expression of conditions
11553: sub docondval {
11554:     my ($allpathcond) = @_;
11555:     my $result=0;
11556:     if ($env{'request.course.id'}
11557: 	&& defined($allpathcond)) {
11558: 	my $operand='|';
11559: 	my @stack;
11560: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11561: 	    if ($chunk eq '(') {
11562: 		push @stack,($operand,$result);
11563: 	    } elsif ($chunk eq ')') {
11564: 		my $before=pop @stack;
11565: 		if (pop @stack eq '&') {
11566: 		    $result=$result>$before?$before:$result;
11567: 		} else {
11568: 		    $result=$result>$before?$result:$before;
11569: 		}
11570: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11571: 		$operand=$chunk;
11572: 	    } else {
11573: 		my $new=directcondval($chunk);
11574: 		if ($operand eq '&') {
11575: 		    $result=$result>$new?$new:$result;
11576: 		} else {
11577: 		    $result=$result>$new?$result:$new;
11578: 		}
11579: 	    }
11580: 	}
11581:     }
11582:     return $result;
11583: }
11584: 
11585: # ---------------------------------------------------- Devalidate courseresdata
11586: 
11587: sub devalidatecourseresdata {
11588:     my ($coursenum,$coursedomain)=@_;
11589:     my $hashid=$coursenum.':'.$coursedomain;
11590:     &devalidate_cache_new('courseres',$hashid);
11591: }
11592: 
11593: 
11594: # --------------------------------------------------- Course Resourcedata Query
11595: #
11596: #  Parameters:
11597: #      $coursenum    - Number of the course.
11598: #      $coursedomain - Domain at which the course was created.
11599: #  Returns:
11600: #     A hash of the course parameters along (I think) with timestamps
11601: #     and version info.
11602: 
11603: sub get_courseresdata {
11604:     my ($coursenum,$coursedomain)=@_;
11605:     my $coursehom=&homeserver($coursenum,$coursedomain);
11606:     my $hashid=$coursenum.':'.$coursedomain;
11607:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11608:     my %dumpreply;
11609:     unless (defined($cached)) {
11610: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11611: 	$result=\%dumpreply;
11612: 	my ($tmp) = keys(%dumpreply);
11613: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11614: 	    &do_cache_new('courseres',$hashid,$result,600);
11615: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11616: 	    return $tmp;
11617: 	} elsif ($tmp =~ /^(error)/) {
11618: 	    $result=undef;
11619: 	    &do_cache_new('courseres',$hashid,$result,600);
11620: 	}
11621:     }
11622:     return $result;
11623: }
11624: 
11625: sub devalidateuserresdata {
11626:     my ($uname,$udom)=@_;
11627:     my $hashid="$udom:$uname";
11628:     &devalidate_cache_new('userres',$hashid);
11629: }
11630: 
11631: sub get_userresdata {
11632:     my ($uname,$udom)=@_;
11633:     #most student don\'t have any data set, check if there is some data
11634:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11635: 
11636:     my $hashid="$udom:$uname";
11637:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11638:     if (!defined($cached)) {
11639: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11640: 	$result=\%resourcedata;
11641: 	&do_cache_new('userres',$hashid,$result,600);
11642:     }
11643:     my ($tmp)=keys(%$result);
11644:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11645: 	return $result;
11646:     }
11647:     #error 2 occurs when the .db doesn't exist
11648:     if ($tmp!~/error: 2 /) {
11649:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11650: 	    &logthis("<font color=\"blue\">WARNING:".
11651: 		     " Trying to get resource data for ".
11652: 		     $uname." at ".$udom.": ".
11653: 		     $tmp."</font>");
11654:         }
11655:     } elsif ($tmp=~/error: 2 /) {
11656: 	#&EXT_cache_set($udom,$uname);
11657: 	&do_cache_new('userres',$hashid,undef,600);
11658: 	undef($tmp); # not really an error so don't send it back
11659:     }
11660:     return $tmp;
11661: }
11662: #----------------------------------------------- resdata - return resource data
11663: #  Purpose:
11664: #    Return resource data for either users or for a course.
11665: #  Parameters:
11666: #     $name      - Course/user name.
11667: #     $domain    - Name of the domain the user/course is registered on.
11668: #     $type      - Type of thing $name is (must be 'course' or 'user'
11669: #     @which     - Array of names of resources desired.
11670: #  Returns:
11671: #     The value of the first reasource in @which that is found in the
11672: #     resource hash.
11673: #  Exceptional Conditions:
11674: #     If the $type passed in is not valid (not the string 'course' or 
11675: #     'user', an undefined  reference is returned.
11676: #     If none of the resources are found, an undef is returned
11677: sub resdata {
11678:     my ($name,$domain,$type,@which)=@_;
11679:     my $result;
11680:     if ($type eq 'course') {
11681: 	$result=&get_courseresdata($name,$domain);
11682:     } elsif ($type eq 'user') {
11683: 	$result=&get_userresdata($name,$domain);
11684:     }
11685:     if (!ref($result)) { return $result; }    
11686:     foreach my $item (@which) {
11687: 	if (defined($result->{$item->[0]})) {
11688: 	    return [$result->{$item->[0]},$item->[1]];
11689: 	}
11690:     }
11691:     return undef;
11692: }
11693: 
11694: sub get_domain_lti {
11695:     my ($cdom,$context) = @_;
11696:     my ($name,%lti);
11697:     if ($context eq 'consumer') {
11698:         $name = 'ltitools';
11699:     } elsif ($context eq 'provider') {
11700:         $name = 'lti';
11701:     } else {
11702:         return %lti;
11703:     }
11704:     my ($result,$cached)=&is_cached_new($name,$cdom);
11705:     if (defined($cached)) {
11706:         if (ref($result) eq 'HASH') {
11707:             %lti = %{$result};
11708:         }
11709:     } else {
11710:         my %domconfig = &get_dom('configuration',[$name],$cdom);
11711:         if (ref($domconfig{$name}) eq 'HASH') {
11712:             %lti = %{$domconfig{$name}};
11713:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
11714:             if (ref($encdomconfig{$name}) eq 'HASH') {
11715:                 foreach my $id (keys(%lti)) {
11716:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
11717:                         foreach my $item ('key','secret') {
11718:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
11719:                         }
11720:                     }
11721:                 }
11722:             }
11723:         }
11724:         my $cachetime = 24*60*60;
11725:         &do_cache_new($name,$cdom,\%lti,$cachetime);
11726:     }
11727:     return %lti;
11728: }
11729: 
11730: sub get_course_lti {
11731:     my ($cnum,$cdom) = @_;
11732:     my $hashid=$cdom.'_'.$cnum;
11733:     my %courselti;
11734:     my ($result,$cached)=&is_cached_new('courselti',$hashid);
11735:     if (defined($cached)) {
11736:         if (ref($result) eq 'HASH') {
11737:             %courselti = %{$result};
11738:         }
11739:     } else {
11740:         %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
11741:         my $cachetime = 24*60*60;
11742:         &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
11743:     }
11744:     return %courselti;
11745: }
11746: 
11747: sub get_numsuppfiles {
11748:     my ($cnum,$cdom,$ignorecache)=@_;
11749:     my $hashid=$cnum.':'.$cdom;
11750:     my ($suppcount,$cached);
11751:     unless ($ignorecache) {
11752:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11753:     }
11754:     unless (defined($cached)) {
11755:         my $chome=&homeserver($cnum,$cdom);
11756:         unless ($chome eq 'no_host') {
11757:             ($suppcount,my $errors) = (0,0);
11758:             my $suppmap = 'supplemental.sequence';
11759:             ($suppcount,$errors) =
11760:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11761:         }
11762:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11763:     }
11764:     return $suppcount;
11765: }
11766: 
11767: #
11768: # EXT resource caching routines
11769: #
11770: 
11771: {
11772: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11773: #
11774: # The course for which we cache
11775: my $cachedmapkey='';
11776: # The cached recursive maps for this course
11777: my %cachedmaps=();
11778: # When this was last done
11779: my $cachedmaptime='';
11780: 
11781: sub clear_EXT_cache_status {
11782:     &delenv('cache.EXT.');
11783: }
11784: 
11785: sub EXT_cache_status {
11786:     my ($target_domain,$target_user) = @_;
11787:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11788:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11789:         # We know already the user has no data
11790:         return 1;
11791:     } else {
11792:         return 0;
11793:     }
11794: }
11795: 
11796: sub EXT_cache_set {
11797:     my ($target_domain,$target_user) = @_;
11798:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11799:     #&appenv({$cachename => time});
11800: }
11801: 
11802: # --------------------------------------------------------- Value of a Variable
11803: sub EXT {
11804: 
11805:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11806:     unless ($varname) { return ''; }
11807:     #get real user name/domain, courseid and symb
11808:     my $courseid;
11809:     my $publicuser;
11810:     if ($symbparm) {
11811: 	$symbparm=&get_symb_from_alias($symbparm);
11812:     }
11813:     if (!($uname && $udom)) {
11814:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11815:       if (!$symbparm) {	$symbparm=$cursymb; }
11816:     } else {
11817: 	$courseid=$env{'request.course.id'};
11818:     }
11819:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11820:     my $rest;
11821:     if (defined($therest[0])) {
11822:        $rest=join('.',@therest);
11823:     } else {
11824:        $rest='';
11825:     }
11826: 
11827:     my $qualifierrest=$qualifier;
11828:     if ($rest) { $qualifierrest.='.'.$rest; }
11829:     my $spacequalifierrest=$space;
11830:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11831:     if ($realm eq 'user') {
11832: # --------------------------------------------------------------- user.resource
11833: 	if ($space eq 'resource') {
11834: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11835: 		  || defined($Apache::lonhomework::parsing_a_task))
11836: 		 &&
11837: 		 ($symbparm eq &symbread()) ) {
11838: 		# if we are in the middle of processing the resource the
11839: 		# get the value we are planning on committing
11840:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11841:                     return $Apache::lonhomework::results{$qualifierrest};
11842:                 } else {
11843:                     return $Apache::lonhomework::history{$qualifierrest};
11844:                 }
11845: 	    } else {
11846: 		my %restored;
11847: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11848: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11849: 		} else {
11850: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11851: 		}
11852: 		return $restored{$qualifierrest};
11853: 	    }
11854: # ----------------------------------------------------------------- user.access
11855:         } elsif ($space eq 'access') {
11856: 	    # FIXME - not supporting calls for a specific user
11857:             return &allowed($qualifier,$rest);
11858: # ------------------------------------------ user.preferences, user.environment
11859:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11860: 	    if (($uname eq $env{'user.name'}) &&
11861: 		($udom eq $env{'user.domain'})) {
11862: 		return $env{join('.',('environment',$qualifierrest))};
11863: 	    } else {
11864: 		my %returnhash;
11865: 		if (!$publicuser) {
11866: 		    %returnhash=&userenvironment($udom,$uname,
11867: 						 $qualifierrest);
11868: 		}
11869: 		return $returnhash{$qualifierrest};
11870: 	    }
11871: # ----------------------------------------------------------------- user.course
11872:         } elsif ($space eq 'course') {
11873: 	    # FIXME - not supporting calls for a specific user
11874:             return $env{join('.',('request.course',$qualifier))};
11875: # ------------------------------------------------------------------- user.role
11876:         } elsif ($space eq 'role') {
11877: 	    # FIXME - not supporting calls for a specific user
11878:             my ($role,$where)=split(/\./,$env{'request.role'});
11879:             if ($qualifier eq 'value') {
11880: 		return $role;
11881:             } elsif ($qualifier eq 'extent') {
11882:                 return $where;
11883:             }
11884: # ----------------------------------------------------------------- user.domain
11885:         } elsif ($space eq 'domain') {
11886:             return $udom;
11887: # ------------------------------------------------------------------- user.name
11888:         } elsif ($space eq 'name') {
11889:             return $uname;
11890: # ---------------------------------------------------- Any other user namespace
11891:         } else {
11892: 	    my %reply;
11893: 	    if (!$publicuser) {
11894: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11895: 	    }
11896: 	    return $reply{$qualifierrest};
11897:         }
11898:     } elsif ($realm eq 'query') {
11899: # ---------------------------------------------- pull stuff out of query string
11900:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11901: 						[$spacequalifierrest]);
11902: 	return $env{'form.'.$spacequalifierrest}; 
11903:    } elsif ($realm eq 'request') {
11904: # ------------------------------------------------------------- request.browser
11905:         if ($space eq 'browser') {
11906:             return $env{'browser.'.$qualifier};
11907: # ------------------------------------------------------------ request.filename
11908:         } else {
11909:             return $env{'request.'.$spacequalifierrest};
11910:         }
11911:     } elsif ($realm eq 'course') {
11912: # ---------------------------------------------------------- course.description
11913:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11914:     } elsif ($realm eq 'resource') {
11915: 
11916: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11917: 	    if (!$symbparm) { $symbparm=&symbread(); }
11918: 	}
11919: 
11920:         if ($qualifier eq '') {
11921: 	    if ($space eq 'title') {
11922: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11923: 	        return &gettitle($symbparm);
11924: 	    }
11925: 	
11926: 	    if ($space eq 'map') {
11927: 	        my ($map) = &decode_symb($symbparm);
11928: 	        return &symbread($map);
11929: 	    }
11930:             if ($space eq 'maptitle') {
11931:                 my ($map) = &decode_symb($symbparm);
11932:                 return &gettitle($map);
11933:             }
11934: 	    if ($space eq 'filename') {
11935: 	        if ($symbparm) {
11936: 		    return &clutter((&decode_symb($symbparm))[2]);
11937: 	        }
11938: 	        return &hreflocation('',$env{'request.filename'});
11939: 	    }
11940: 
11941:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11942:                 if ($space eq 'visibleparts') {
11943:                     my $navmap = Apache::lonnavmaps::navmap->new();
11944:                     my $item;
11945:                     if (ref($navmap)) {
11946:                         my $res = $navmap->getBySymb($symbparm);
11947:                         my $parts = $res->parts();
11948:                         if (ref($parts) eq 'ARRAY') {
11949:                             $item = join(',',@{$parts});
11950:                         }
11951:                         undef($navmap);
11952:                     }
11953:                     return $item;
11954:                 }
11955:             }
11956:         }
11957: 
11958: 	my ($section, $group, @groups);
11959: 	my ($courselevelm,$courselevel);
11960:         if (($courseid eq '') && ($cid)) {
11961:             $courseid = $cid;
11962:         }
11963: 	if (($symbparm && $courseid) && 
11964: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
11965: 
11966: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11967: 
11968: # ----------------------------------------------------- Cascading lookup scheme
11969: 	    my $symbp=$symbparm;
11970: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
11971: 
11972: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
11973: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11974: 
11975: 	    if (($env{'user.name'} eq $uname) &&
11976: 		($env{'user.domain'} eq $udom)) {
11977: 		$section=$env{'request.course.sec'};
11978:                 @groups = split(/:/,$env{'request.course.groups'});  
11979:                 @groups=&sort_course_groups($courseid,@groups); 
11980: 	    } else {
11981: 		if (! defined($usection)) {
11982: 		    $section=&getsection($udom,$uname,$courseid);
11983: 		} else {
11984: 		    $section = $usection;
11985: 		}
11986:                 @groups = &get_users_groups($udom,$uname,$courseid);
11987: 	    }
11988: 
11989: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11990: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11991: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11992: 
11993: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
11994: 	    my $courselevelr=$courseid.'.'.$symbparm;
11995: 	    $courselevelm=$courseid.'.'.$mapparm;
11996: 
11997: # ----------------------------------------------------------- first, check user
11998: 
11999: 	    my $userreply=&resdata($uname,$udom,'user',
12000: 				       ([$courselevelr,'resource'],
12001: 					[$courselevelm,'map'     ],
12002: 					[$courselevel, 'course'  ]));
12003: 	    if (defined($userreply)) { return &get_reply($userreply); }
12004: 
12005: # ------------------------------------------------ second, check some of course
12006:             my $coursereply;
12007:             if (@groups > 0) {
12008:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12009:                                        $mapparm,$spacequalifierrest);
12010:                 if (defined($coursereply)) { return &get_reply($coursereply); }
12011:             }
12012: 
12013: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12014: 				  $env{'course.'.$courseid.'.domain'},
12015: 				  'course',
12016: 				  ([$seclevelr,   'resource'],
12017: 				   [$seclevelm,   'map'     ],
12018: 				   [$seclevel,    'course'  ],
12019: 				   [$courselevelr,'resource']));
12020: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12021: 
12022: # ------------------------------------------------------ third, check map parms
12023: 	    my %parmhash=();
12024: 	    my $thisparm='';
12025: 	    if (tie(%parmhash,'GDBM_File',
12026: 		    $env{'request.course.fn'}.'_parms.db',
12027: 		    &GDBM_READER(),0640)) {
12028: 		$thisparm=$parmhash{$symbparm};
12029: 		untie(%parmhash);
12030: 	    }
12031: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12032: 	}
12033: # ------------------------------------------ fourth, look in resource metadata
12034: 
12035: 	$spacequalifierrest=~s/\./\_/;
12036: 	my $filename;
12037: 	if (!$symbparm) { $symbparm=&symbread(); }
12038: 	if ($symbparm) {
12039: 	    $filename=(&decode_symb($symbparm))[2];
12040: 	} else {
12041: 	    $filename=$env{'request.filename'};
12042: 	}
12043: 	my $metadata=&metadata($filename,$spacequalifierrest);
12044: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12045: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
12046: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12047: 
12048: # ---------------------------------------------- fourth, look in rest of course
12049: 	if ($symbparm && defined($courseid) && 
12050: 	    $courseid eq $env{'request.course.id'}) {
12051: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12052: 				     $env{'course.'.$courseid.'.domain'},
12053: 				     'course',
12054: 				     ([$courselevelm,'map'   ],
12055: 				      [$courselevel, 'course']));
12056: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12057: 	}
12058: # ------------------------------------------------------------------ Cascade up
12059: 	unless ($space eq '0') {
12060: 	    my @parts=split(/_/,$space);
12061: 	    my $id=pop(@parts);
12062: 	    my $part=join('_',@parts);
12063: 	    if ($part eq '') { $part='0'; }
12064: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12065: 				 $symbparm,$udom,$uname,$section,1);
12066: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12067: 	}
12068: 	if ($recurse) { return undef; }
12069: 	my $pack_def=&packages_tab_default($filename,$varname);
12070: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12071: # ---------------------------------------------------- Any other user namespace
12072:     } elsif ($realm eq 'environment') {
12073: # ----------------------------------------------------------------- environment
12074: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12075: 	    return $env{'environment.'.$spacequalifierrest};
12076: 	} else {
12077: 	    if ($uname eq 'anonymous' && $udom eq '') {
12078: 		return '';
12079: 	    }
12080: 	    my %returnhash=&userenvironment($udom,$uname,
12081: 					    $spacequalifierrest);
12082: 	    return $returnhash{$spacequalifierrest};
12083: 	}
12084:     } elsif ($realm eq 'system') {
12085: # ----------------------------------------------------------------- system.time
12086: 	if ($space eq 'time') {
12087: 	    return time;
12088:         }
12089:     } elsif ($realm eq 'server') {
12090: # ----------------------------------------------------------------- system.time
12091: 	if ($space eq 'name') {
12092: 	    return $ENV{'SERVER_NAME'};
12093:         }
12094:     } elsif ($realm eq 'client') {
12095:         if ($space eq 'remote_addr') {
12096:             return &get_requestor_ip();
12097:         }
12098:     }
12099:     return '';
12100: }
12101: 
12102: sub get_reply {
12103:     my ($reply_value) = @_;
12104:     if (ref($reply_value) eq 'ARRAY') {
12105:         if (wantarray) {
12106: 	    return @$reply_value;
12107:         }
12108:         return $reply_value->[0];
12109:     } else {
12110:         return $reply_value;
12111:     }
12112: }
12113: 
12114: sub check_group_parms {
12115:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
12116:     my @groupitems = ();
12117:     my $resultitem;
12118:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
12119:     foreach my $group (@{$groups}) {
12120:         foreach my $level (@levels) {
12121:              my $item = $courseid.'.['.$group.'].'.$level->[0];
12122:              push(@groupitems,[$item,$level->[1]]);
12123:         }
12124:     }
12125:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12126:                             $env{'course.'.$courseid.'.domain'},
12127:                                      'course',@groupitems);
12128:     return $coursereply;
12129: }
12130: 
12131: sub get_map_hierarchy {
12132:     my ($mapname,$courseid) = @_;
12133:     my @recurseup = ();
12134:     if ($mapname) {
12135:         if (($cachedmapkey eq $courseid) &&
12136:             (abs($cachedmaptime-time)<5)) {
12137:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12138:                 return @{$cachedmaps{$mapname}};
12139:             }
12140:         }
12141:         my $navmap = Apache::lonnavmaps::navmap->new();
12142:         if (ref($navmap)) {
12143:             @recurseup = $navmap->recurseup_maps($mapname);
12144:             undef($navmap);
12145:             $cachedmaps{$mapname} = \@recurseup;
12146:             $cachedmaptime=time;
12147:             $cachedmapkey=$courseid;
12148:         }
12149:     }
12150:     return @recurseup;
12151: }
12152: 
12153: }
12154: 
12155: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12156:     my ($courseid,@groups) = @_;
12157:     @groups = sort(@groups);
12158:     return @groups;
12159: }
12160: 
12161: sub packages_tab_default {
12162:     my ($uri,$varname)=@_;
12163:     my (undef,$part,$name)=split(/\./,$varname);
12164: 
12165:     my (@extension,@specifics,$do_default);
12166:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
12167: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
12168: 	if ($pack_type eq 'default') {
12169: 	    $do_default=1;
12170: 	} elsif ($pack_type eq 'extension') {
12171: 	    push(@extension,[$package,$pack_type,$pack_part]);
12172: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
12173: 	    # only look at packages defaults for packages that this id is
12174: 	    push(@specifics,[$package,$pack_type,$pack_part]);
12175: 	}
12176:     }
12177:     # first look for a package that matches the requested part id
12178:     foreach my $package (@specifics) {
12179: 	my (undef,$pack_type,$pack_part)=@{$package};
12180: 	next if ($pack_part ne $part);
12181: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12182: 	    return $packagetab{"$pack_type&$name&default"};
12183: 	}
12184:     }
12185:     # look for any possible matching non extension_ package
12186:     foreach my $package (@specifics) {
12187: 	my (undef,$pack_type,$pack_part)=@{$package};
12188: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12189: 	    return $packagetab{"$pack_type&$name&default"};
12190: 	}
12191: 	if ($pack_type eq 'part') { $pack_part='0'; }
12192: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12193: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12194: 	}
12195:     }
12196:     # look for any posible extension_ match
12197:     foreach my $package (@extension) {
12198: 	my ($package,$pack_type)=@{$package};
12199: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12200: 	    return $packagetab{"$pack_type&$name&default"};
12201: 	}
12202: 	if (defined($packagetab{$package."&$name&default"})) {
12203: 	    return $packagetab{$package."&$name&default"};
12204: 	}
12205:     }
12206:     # look for a global default setting
12207:     if ($do_default && defined($packagetab{"default&$name&default"})) {
12208: 	return $packagetab{"default&$name&default"};
12209:     }
12210:     return undef;
12211: }
12212: 
12213: sub add_prefix_and_part {
12214:     my ($prefix,$part)=@_;
12215:     my $keyroot;
12216:     if (defined($prefix) && $prefix !~ /^__/) {
12217: 	# prefix that has a part already
12218: 	$keyroot=$prefix;
12219:     } elsif (defined($prefix)) {
12220: 	# prefix that is missing a part
12221: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12222:     } else {
12223: 	# no prefix at all
12224: 	if (defined($part)) { $keyroot='_'.$part; }
12225:     }
12226:     return $keyroot;
12227: }
12228: 
12229: # ---------------------------------------------------------------- Get metadata
12230: 
12231: my %metaentry;
12232: my %importedpartids;
12233: my %importedrespids;
12234: sub metadata {
12235:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
12236:     $uri=&declutter($uri);
12237:     # if it is a non metadata possible uri return quickly
12238:     if (($uri eq '') || 
12239: 	(($uri =~ m|^/*adm/|) && 
12240: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12241:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12242: 	return undef;
12243:     }
12244:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
12245: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12246: 	return undef;
12247:     }
12248:     my $filename=$uri;
12249:     $uri=~s/\.meta$//;
12250: #
12251: # Is the metadata already cached?
12252: # Look at timestamp of caching
12253: # Everything is cached by the main uri, libraries are never directly cached
12254: #
12255:     if (!defined($liburi)) {
12256: 	my ($result,$cached)=&is_cached_new('meta',$uri);
12257: 	if (defined($cached)) { return $result->{':'.$what}; }
12258:     }
12259:     {
12260: # Imported parts would go here
12261:         my @origfiletagids=();
12262:         my $importedparts=0;
12263: 
12264: # Imported responseids would go here
12265:         my $importedresponses=0;
12266: #
12267: # Is this a recursive call for a library?
12268: #
12269: #	if (! exists($metacache{$uri})) {
12270: #	    $metacache{$uri}={};
12271: #	}
12272: 	my $cachetime = 60*60;
12273:         if ($liburi) {
12274: 	    $liburi=&declutter($liburi);
12275:             $filename=$liburi;
12276:         } else {
12277: 	    &devalidate_cache_new('meta',$uri);
12278: 	    undef(%metaentry);
12279: 	}
12280:         my %metathesekeys=();
12281:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12282: 	my $metastring;
12283: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12284: 	    my $which = &hreflocation('','/'.($liburi || $uri));
12285: 	    $metastring = 
12286: 		&Apache::lonnet::ssi_body($which,
12287: 					  ('grade_target' => 'meta'));
12288: 	    $cachetime = 1; # only want this cached in the child not long term
12289: 	} elsif (($uri !~ m -^(editupload)/-) && 
12290:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12291: 	    my $file=&filelocation('',&clutter($filename));
12292: 	    #push(@{$metaentry{$uri.'.file'}},$file);
12293: 	    $metastring=&getfile($file);
12294: 	}
12295:         my $parser=HTML::LCParser->new(\$metastring);
12296:         my $token;
12297:         undef %metathesekeys;
12298:         while ($token=$parser->get_token) {
12299: 	    if ($token->[0] eq 'S') {
12300: 		if (defined($token->[2]->{'package'})) {
12301: #
12302: # This is a package - get package info
12303: #
12304: 		    my $package=$token->[2]->{'package'};
12305: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12306: 		    if (defined($token->[2]->{'id'})) { 
12307: 			$keyroot.='_'.$token->[2]->{'id'}; 
12308: 		    }
12309: 		    if ($metaentry{':packages'}) {
12310: 			$metaentry{':packages'}.=','.$package.$keyroot;
12311: 		    } else {
12312: 			$metaentry{':packages'}=$package.$keyroot;
12313: 		    }
12314: 		    foreach my $pack_entry (keys(%packagetab)) {
12315: 			my $part=$keyroot;
12316: 			$part=~s/^\_//;
12317: 			if ($pack_entry=~/^\Q$package\E\&/ || 
12318: 			    $pack_entry=~/^\Q$package\E_0\&/) {
12319: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12320: 			    # ignore package.tab specified default values
12321:                             # here &package_tab_default() will fetch those
12322: 			    if ($subp eq 'default') { next; }
12323: 			    my $value=$packagetab{$pack_entry};
12324: 			    my $unikey;
12325: 			    if ($pack =~ /_0$/) {
12326: 				$unikey='parameter_0_'.$name;
12327: 				$part=0;
12328: 			    } else {
12329: 				$unikey='parameter'.$keyroot.'_'.$name;
12330: 			    }
12331: 			    if ($subp eq 'display') {
12332: 				$value.=' [Part: '.$part.']';
12333: 			    }
12334: 			    $metaentry{':'.$unikey.'.part'}=$part;
12335: 			    $metathesekeys{$unikey}=1;
12336: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12337: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
12338: 			    }
12339: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
12340: 				$metaentry{':'.$unikey}=
12341: 				    $metaentry{':'.$unikey.'.default'};
12342: 			    }
12343: 			}
12344: 		    }
12345: 		} else {
12346: #
12347: # This is not a package - some other kind of start tag
12348: #
12349: 		    my $entry=$token->[1];
12350: 		    my $unikey='';
12351: 
12352: 		    if ($entry eq 'import') {
12353: #
12354: # Importing a library here
12355: #
12356:                         my $location=$parser->get_text('/import');
12357:                         my $dir=$filename;
12358:                         $dir=~s|[^/]*$||;
12359:                         $location=&filelocation($dir,$location);
12360: 
12361:                         my $importid=$token->[2]->{'id'};
12362:                         my $importmode=$token->[2]->{'importmode'};
12363: #
12364: # Check metadata for imported file to
12365: # see if it contained response items
12366: #
12367:                         my %currmetaentry = %metaentry;
12368:                         my $libresponseorder = &metadata($location,'responseorder');
12369:                         my $origfile;
12370:                         if ($libresponseorder ne '') {
12371:                             if ($#origfiletagids<0) {
12372:                                 undef(%importedrespids);
12373:                                 undef(%importedpartids);
12374:                             }
12375:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
12376:                             if (@{$importedrespids{$importid}} > 0) {
12377:                                 $importedresponses = 1;
12378: # We need to get the original file and the imported file to get the response order correct
12379: # Load and inspect original file
12380:                                 if ($#origfiletagids<0) {
12381:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12382:                                     $origfile=&getfile($origfilelocation);
12383:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12384:                                 }
12385:                             }
12386:                         }
12387: # Do not overwrite contents of %metaentry hash for resource itself with 
12388: # hash populated for imported library file
12389:                         %metaentry = %currmetaentry;
12390:                         undef(%currmetaentry);
12391:                         if ($importmode eq 'problem') {
12392: # Import as problem/response
12393:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12394:                         } elsif ($importmode eq 'part') {
12395: # Import as part(s)
12396:                            $importedparts=1;
12397: # We need to get the original file and the imported file to get the part order correct
12398: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12399: # Load and inspect original file if we didn't do that already
12400:                            if ($#origfiletagids<0) {
12401:                                undef(%importedrespids);
12402:                                undef(%importedpartids);
12403:                                if ($origfile eq '') {
12404:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12405:                                    $origfile=&getfile($origfilelocation);
12406:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12407:                                }
12408:                            }
12409: 
12410: # Load and inspect imported file
12411:                            my $impfile=&getfile($location);
12412:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12413:                            if ($#impfilepartids>=0) {
12414: # This problem had parts
12415:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12416:                            } else {
12417: # Importing by turning a single problem into a problem part
12418: # It gets the import-tags ID as part-ID
12419:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12420:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12421:                            }
12422:                         } else {
12423: # Normal import
12424:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12425:                            if (defined($token->[2]->{'id'})) {
12426:                               $unikey.='_'.$token->[2]->{'id'};
12427:                            }
12428:                         }
12429: 
12430: 			if ($depthcount<20) {
12431: 			    my $metadata = 
12432: 				&metadata($uri,'keys', $location,$unikey,
12433: 					  $depthcount+1);
12434: 			    foreach my $meta (split(',',$metadata)) {
12435: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12436: 				$metathesekeys{$meta}=1;
12437: 			    }
12438: 			
12439:                         }
12440: 		    } else {
12441: #
12442: # Not importing, some other kind of non-package, non-library start tag
12443: # 
12444:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12445:                         if (defined($token->[2]->{'id'})) {
12446:                             $unikey.='_'.$token->[2]->{'id'};
12447:                         }
12448: 			if (defined($token->[2]->{'name'})) { 
12449: 			    $unikey.='_'.$token->[2]->{'name'}; 
12450: 			}
12451: 			$metathesekeys{$unikey}=1;
12452: 			foreach my $param (@{$token->[3]}) {
12453: 			    $metaentry{':'.$unikey.'.'.$param} =
12454: 				$token->[2]->{$param};
12455: 			}
12456: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12457: 			my $default=$metaentry{':'.$unikey.'.default'};
12458: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12459: 		 # only ws inside the tag, and not in default, so use default
12460: 		 # as value
12461: 			    $metaentry{':'.$unikey}=$default;
12462: 			} elsif ( $internaltext =~ /\S/ ) {
12463: 		  # something interesting inside the tag
12464: 			    $metaentry{':'.$unikey}=$internaltext;
12465: 			} else {
12466: 		  # no interesting values, don't set a default
12467: 			}
12468: # end of not-a-package not-a-library import
12469: 		    }
12470: # end of not-a-package start tag
12471: 		}
12472: # the next is the end of "start tag"
12473: 	    }
12474: 	}
12475: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12476: 	$extension = lc($extension);
12477: 	if ($extension eq 'htm') { $extension='html'; }
12478: 
12479: 	foreach my $key (keys(%packagetab)) {
12480: 	    #no specific packages #how's our extension
12481: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12482: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12483: 					 \%metathesekeys);
12484: 	}
12485: 
12486: 	if (!exists($metaentry{':packages'})
12487: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12488: 	    foreach my $key (keys(%packagetab)) {
12489: 		#no specific packages well let's get default then
12490: 		if ($key!~/^default&/) { next; }
12491: 		&metadata_create_package_def($uri,$key,'default',
12492: 					     \%metathesekeys);
12493: 	    }
12494: 	}
12495: # are there custom rights to evaluate
12496: 	if ($metaentry{':copyright'} eq 'custom') {
12497: 
12498:     #
12499:     # Importing a rights file here
12500:     #
12501: 	    unless ($depthcount) {
12502: 		my $location=$metaentry{':customdistributionfile'};
12503: 		my $dir=$filename;
12504: 		$dir=~s|[^/]*$||;
12505: 		$location=&filelocation($dir,$location);
12506: 		my $rights_metadata =
12507: 		    &metadata($uri,'keys',$location,'_rights',
12508: 			      $depthcount+1);
12509: 		foreach my $rights (split(',',$rights_metadata)) {
12510: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12511: 		    $metathesekeys{$rights}=1;
12512: 		}
12513: 	    }
12514: 	}
12515: 	# uniqifiy package listing
12516: 	my %seen;
12517: 	my @uniq_packages =
12518: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12519: 	$metaentry{':packages'} = join(',',@uniq_packages);
12520: 
12521:         if (($importedresponses) || ($importedparts)) {
12522:             if ($importedparts) {
12523: # We had imported parts and need to rebuild partorder
12524:                 $metaentry{':partorder'}='';
12525:                 $metathesekeys{'partorder'}=1;
12526:             }
12527:             if ($importedresponses) {
12528: # We had imported responses and need to rebuild responseorder
12529:                 $metaentry{':responseorder'}='';
12530:                 $metathesekeys{'responseorder'}=1;
12531:             }
12532:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12533:                 my $origid = $origfiletagids[$index+1];
12534:                 if ($origfiletagids[$index] eq 'part') {
12535: # Original part, part of the problem
12536:                     if ($importedparts) {
12537:                         $metaentry{':partorder'}.=','.$origid;
12538:                     }
12539:                 } elsif ($origfiletagids[$index] eq 'import') {
12540:                     if ($importedparts) {
12541: # We have imported parts at this position
12542:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
12543:                     }
12544:                     if ($importedresponses) {
12545: # We have imported responses at this position
12546:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
12547:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
12548:                         }
12549:                     }
12550:                 } else {
12551: # Original response item, part of the problem
12552:                     if ($importedresponses) {
12553:                         $metaentry{':responseorder'}.=','.$origid;
12554:                     }
12555:                 }
12556:             }
12557:             if ($importedparts) {
12558:                 $metaentry{':partorder'}=~s/^\,//;
12559:             }
12560:             if ($importedresponses) {
12561:                 $metaentry{':responseorder'}=~s/^\,//;
12562:             }
12563:         }
12564: 
12565: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12566: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12567: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12568: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
12569: # this is the end of "was not already recently cached
12570:     }
12571:     return $metaentry{':'.$what};
12572: }
12573: 
12574: sub metadata_create_package_def {
12575:     my ($uri,$key,$package,$metathesekeys)=@_;
12576:     my ($pack,$name,$subp)=split(/\&/,$key);
12577:     if ($subp eq 'default') { next; }
12578:     
12579:     if (defined($metaentry{':packages'})) {
12580: 	$metaentry{':packages'}.=','.$package;
12581:     } else {
12582: 	$metaentry{':packages'}=$package;
12583:     }
12584:     my $value=$packagetab{$key};
12585:     my $unikey;
12586:     $unikey='parameter_0_'.$name;
12587:     $metaentry{':'.$unikey.'.part'}=0;
12588:     $$metathesekeys{$unikey}=1;
12589:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12590: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12591:     }
12592:     if (defined($metaentry{':'.$unikey.'.default'})) {
12593: 	$metaentry{':'.$unikey}=
12594: 	    $metaentry{':'.$unikey.'.default'};
12595:     }
12596: }
12597: 
12598: sub metadata_generate_part0 {
12599:     my ($metadata,$metacache,$uri) = @_;
12600:     my %allnames;
12601:     foreach my $metakey (keys(%$metadata)) {
12602: 	if ($metakey=~/^parameter\_(.*)/) {
12603: 	  my $part=$$metacache{':'.$metakey.'.part'};
12604: 	  my $name=$$metacache{':'.$metakey.'.name'};
12605: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12606: 	    $allnames{$name}=$part;
12607: 	  }
12608: 	}
12609:     }
12610:     foreach my $name (keys(%allnames)) {
12611:       $$metadata{"parameter_0_$name"}=1;
12612:       my $key=":parameter_0_$name";
12613:       $$metacache{"$key.part"}='0';
12614:       $$metacache{"$key.name"}=$name;
12615:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12616: 					   $allnames{$name}.'_'.$name.
12617: 					   '.type'};
12618:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12619: 			     '.display'};
12620:       my $expr='[Part: '.$allnames{$name}.']';
12621:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12622:       $$metacache{"$key.display"}=$olddis;
12623:     }
12624: }
12625: 
12626: # ------------------------------------------------------ Devalidate title cache
12627: 
12628: sub devalidate_title_cache {
12629:     my ($url)=@_;
12630:     if (!$env{'request.course.id'}) { return; }
12631:     my $symb=&symbread($url);
12632:     if (!$symb) { return; }
12633:     my $key=$env{'request.course.id'}."\0".$symb;
12634:     &devalidate_cache_new('title',$key);
12635: }
12636: 
12637: # ------------------------------------------------- Get the title of a course
12638: 
12639: sub current_course_title {
12640:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12641: }
12642: # ------------------------------------------------- Get the title of a resource
12643: 
12644: sub gettitle {
12645:     my $urlsymb=shift;
12646:     my $symb=&symbread($urlsymb);
12647:     if ($symb) {
12648: 	my $key=$env{'request.course.id'}."\0".$symb;
12649: 	my ($result,$cached)=&is_cached_new('title',$key);
12650: 	if (defined($cached)) { 
12651: 	    return $result;
12652: 	}
12653: 	my ($map,$resid,$url)=&decode_symb($symb);
12654: 	my $title='';
12655: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12656: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12657: 	} else {
12658: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12659: 		    &GDBM_READER(),0640)) {
12660: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12661: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12662: 		untie(%bighash);
12663: 	    }
12664: 	}
12665: 	$title=~s/\&colon\;/\:/gs;
12666: 	if ($title) {
12667: # Remember both $symb and $title for dynamic metadata
12668:             $accesshash{$symb.'___crstitle'}=$title;
12669:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12670: # Cache this title and then return it
12671: 	    return &do_cache_new('title',$key,$title,600);
12672: 	}
12673: 	$urlsymb=$url;
12674:     }
12675:     my $title=&metadata($urlsymb,'title');
12676:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12677:     return $title;
12678: }
12679: 
12680: sub get_slot {
12681:     my ($which,$cnum,$cdom)=@_;
12682:     if (!$cnum || !$cdom) {
12683: 	(undef,my $courseid)=&whichuser();
12684: 	$cdom=$env{'course.'.$courseid.'.domain'};
12685: 	$cnum=$env{'course.'.$courseid.'.num'};
12686:     }
12687:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12688:     my %slotinfo;
12689:     if (exists($remembered{$key})) {
12690: 	$slotinfo{$which} = $remembered{$key};
12691:     } else {
12692: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12693: 	&Apache::lonhomework::showhash(%slotinfo);
12694: 	my ($tmp)=keys(%slotinfo);
12695: 	if ($tmp=~/^error:/) { return (); }
12696: 	$remembered{$key} = $slotinfo{$which};
12697:     }
12698:     if (ref($slotinfo{$which}) eq 'HASH') {
12699: 	return %{$slotinfo{$which}};
12700:     }
12701:     return $slotinfo{$which};
12702: }
12703: 
12704: sub get_reservable_slots {
12705:     my ($cnum,$cdom,$uname,$udom) = @_;
12706:     my $now = time;
12707:     my $reservable_info;
12708:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12709:     if (exists($remembered{$key})) {
12710:         $reservable_info = $remembered{$key};
12711:     } else {
12712:         my %resv;
12713:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12714:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12715:         $reservable_info = \%resv;
12716:         $remembered{$key} = $reservable_info;
12717:     }
12718:     return $reservable_info;
12719: }
12720: 
12721: sub get_course_slots {
12722:     my ($cnum,$cdom) = @_;
12723:     my $hashid=$cnum.':'.$cdom;
12724:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12725:     if (defined($cached)) {
12726:         if (ref($result) eq 'HASH') {
12727:             return %{$result};
12728:         }
12729:     } else {
12730:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12731:         my ($tmp) = keys(%slots);
12732:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12733:             &do_cache_new('allslots',$hashid,\%slots,600);
12734:             return %slots;
12735:         }
12736:     }
12737:     return;
12738: }
12739: 
12740: sub devalidate_slots_cache {
12741:     my ($cnum,$cdom)=@_;
12742:     my $hashid=$cnum.':'.$cdom;
12743:     &devalidate_cache_new('allslots',$hashid);
12744: }
12745: 
12746: sub get_coursechange {
12747:     my ($cdom,$cnum) = @_;
12748:     if ($cdom eq '' || $cnum eq '') {
12749:         return unless ($env{'request.course.id'});
12750:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12751:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12752:     }
12753:     my $hashid=$cdom.'_'.$cnum;
12754:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12755:     if ((defined($cached)) && ($change ne '')) {
12756:         return $change;
12757:     } else {
12758:         my %crshash;
12759:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12760:         if ($crshash{'internal.contentchange'} eq '') {
12761:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12762:             if ($change eq '') {
12763:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12764:                 $change = $crshash{'internal.created'};
12765:             }
12766:         } else {
12767:             $change = $crshash{'internal.contentchange'};
12768:         }
12769:         my $cachetime = 600;
12770:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12771:     }
12772:     return $change;
12773: }
12774: 
12775: sub devalidate_coursechange_cache {
12776:     my ($cnum,$cdom)=@_;
12777:     my $hashid=$cnum.':'.$cdom;
12778:     &devalidate_cache_new('crschange',$hashid);
12779: }
12780: 
12781: # ------------------------------------------------- Update symbolic store links
12782: 
12783: sub symblist {
12784:     my ($mapname,%newhash)=@_;
12785:     $mapname=&deversion(&declutter($mapname));
12786:     my %hash;
12787:     if (($env{'request.course.fn'}) && (%newhash)) {
12788:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12789:                       &GDBM_WRCREAT(),0640)) {
12790: 	    foreach my $url (keys(%newhash)) {
12791: 		next if ($url eq 'last_known'
12792: 			 && $env{'form.no_update_last_known'});
12793: 		$hash{declutter($url)}=&encode_symb($mapname,
12794: 						    $newhash{$url}->[1],
12795: 						    $newhash{$url}->[0]);
12796:             }
12797:             if (untie(%hash)) {
12798: 		return 'ok';
12799:             }
12800:         }
12801:     }
12802:     return 'error';
12803: }
12804: 
12805: # --------------------------------------------------------------- Verify a symb
12806: 
12807: sub symbverify {
12808:     my ($symb,$thisurl,$encstate)=@_;
12809:     my $thisfn=$thisurl;
12810:     $thisfn=&declutter($thisfn);
12811: # direct jump to resource in page or to a sequence - will construct own symbs
12812:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12813: # check URL part
12814:     my ($map,$resid,$url)=&decode_symb($symb);
12815: 
12816:     unless ($url eq $thisfn) { return 0; }
12817: 
12818:     $symb=&symbclean($symb);
12819:     $thisurl=&deversion($thisurl);
12820:     $thisfn=&deversion($thisfn);
12821: 
12822:     my %bighash;
12823:     my $okay=0;
12824: 
12825:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12826:                             &GDBM_READER(),0640)) {
12827:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12828:             $thisurl =~ s/\?.+$//;
12829:             if ($map =~ m{^uploaded/.+\.page$}) {
12830:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12831:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12832:             }
12833:         }
12834:         my $ids;
12835:         if ($map =~ m{^uploaded/.+\.page$}) {
12836:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
12837:         } else {
12838:             $ids=$bighash{'ids_'.&clutter($thisurl)};
12839:         }
12840:         unless ($ids) {
12841:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
12842:             $ids=$bighash{$idkey};
12843:         }
12844:         if ($ids) {
12845: # ------------------------------------------------------------------- Has ID(s)
12846:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12847:                 $symb =~ s/\?.+$//;
12848:             }
12849: 	    foreach my $id (split(/\,/,$ids)) {
12850: 	       my ($mapid,$resid)=split(/\./,$id);
12851:                if (
12852:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12853:    eq $symb) {
12854:                    if (ref($encstate)) {
12855:                        $$encstate = $bighash{'encrypted_'.$id};
12856:                    }
12857:                    if (($env{'request.role.adv'}) ||
12858:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12859:                        ($thisurl eq '/adm/navmaps')) {
12860:                        $okay=1;
12861:                        last;
12862:                    }
12863:                }
12864:            }
12865:         }
12866: 	untie(%bighash);
12867:     }
12868:     return $okay;
12869: }
12870: 
12871: # --------------------------------------------------------------- Clean-up symb
12872: 
12873: sub symbclean {
12874:     my $symb=shift;
12875:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12876: # remove version from map
12877:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12878: 
12879: # remove version from URL
12880:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12881: 
12882: # remove wrapper
12883: 
12884:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12885:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12886:     return $symb;
12887: }
12888: 
12889: # ---------------------------------------------- Split symb to find map and url
12890: 
12891: sub encode_symb {
12892:     my ($map,$resid,$url)=@_;
12893:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12894: }
12895: 
12896: sub decode_symb {
12897:     my $symb=shift;
12898:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12899:     my ($map,$resid,$url)=split(/___/,$symb);
12900:     return (&fixversion($map),$resid,&fixversion($url));
12901: }
12902: 
12903: sub fixversion {
12904:     my $fn=shift;
12905:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12906:     my %bighash;
12907:     my $uri=&clutter($fn);
12908:     my $key=$env{'request.course.id'}.'_'.$uri;
12909: # is this cached?
12910:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
12911:     if (defined($cached)) { return $result; }
12912: # unfortunately not cached, or expired
12913:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12914: 	    &GDBM_READER(),0640)) {
12915:  	if ($bighash{'version_'.$uri}) {
12916:  	    my $version=$bighash{'version_'.$uri};
12917:  	    unless (($version eq 'mostrecent') || 
12918: 		    ($version==&getversion($uri))) {
12919:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
12920:  	    }
12921:  	}
12922:  	untie %bighash;
12923:     }
12924:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12925: }
12926: 
12927: sub deversion {
12928:     my $url=shift;
12929:     $url=~s/\.\d+\.(\w+)$/\.$1/;
12930:     return $url;
12931: }
12932: 
12933: # ------------------------------------------------------ Return symb list entry
12934: 
12935: sub symbread {
12936:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
12937:         $ignoresymbdb,$noenccheck)=@_;
12938:     my $cache_str='request.symbread.cached.'.$thisfn;
12939:     if (defined($env{$cache_str})) {
12940:         unless (ref($possibles) eq 'HASH') {
12941:             if ($ignorecachednull) {
12942:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
12943:             } else {
12944:                 return $env{$cache_str};
12945:             }
12946:         }
12947:     }
12948: # no filename provided? try from environment
12949:     unless ($thisfn) {
12950:         if ($env{'request.symb'}) {
12951:             return $env{$cache_str}=&symbclean($env{'request.symb'});
12952:         }
12953:         $thisfn=$env{'request.filename'};
12954:     }
12955:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12956: # is that filename actually a symb? Verify, clean, and return
12957:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12958: 	if (&symbverify($thisfn,$1)) {
12959: 	    return $env{$cache_str}=&symbclean($thisfn);
12960: 	}
12961:     }
12962:     $thisfn=declutter($thisfn);
12963:     my %hash;
12964:     my %bighash;
12965:     my $syval='';
12966:     if (($env{'request.course.fn'}) && ($thisfn)) {
12967:         my $targetfn = $thisfn;
12968:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12969:             $targetfn = 'adm/wrapper/'.$thisfn;
12970:         }
12971: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12972: 	    $targetfn=$1;
12973: 	}
12974:         unless ($ignoresymbdb) {
12975:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12976:                           &GDBM_READER(),0640)) {
12977: 	        $syval=$hash{$targetfn};
12978:                 untie(%hash);
12979:             }
12980:             if ($syval && $checkforblock) {
12981:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
12982:                 if (@blockers) {
12983:                     $syval='';
12984:                 }
12985:             }
12986:         }
12987: # ---------------------------------------------------------- There was an entry
12988:         if ($syval) {
12989: 	    #unless ($syval=~/\_\d+$/) {
12990: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12991: 		    #&appenv({'request.ambiguous' => $thisfn});
12992: 		    #return $env{$cache_str}='';
12993: 		#}    
12994: 		#$syval.=$1;
12995: 	    #}
12996:         } else {
12997: # ------------------------------------------------------- Was not in symb table
12998:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12999:                             &GDBM_READER(),0640)) {
13000: # ---------------------------------------------- Get ID(s) for current resource
13001:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
13002:               unless ($ids) { 
13003:                  $ids=$bighash{'ids_/'.$thisfn};
13004:               }
13005:               unless ($ids) {
13006: # alias?
13007: 		  $ids=$bighash{'mapalias_'.$thisfn};
13008:               }
13009:               if ($ids) {
13010: # ------------------------------------------------------------------- Has ID(s)
13011:                  my @possibilities=split(/\,/,$ids);
13012:                  if ($#possibilities==0) {
13013: # ----------------------------------------------- There is only one possibility
13014: 		     my ($mapid,$resid)=split(/\./,$ids);
13015: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
13016: 						    $resid,$thisfn);
13017:                      if (ref($possibles) eq 'HASH') {
13018:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13019:                              $possibles->{$syval} = 1;
13020:                          }
13021:                      }
13022:                      if ($checkforblock) {
13023:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13024:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
13025:                              if (@blockers) {
13026:                                  $syval = '';
13027:                                  untie(%bighash);
13028:                                  return $env{$cache_str}='';
13029:                              }
13030:                          }
13031:                      }
13032:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13033: # ------------------------------------------ There is more than one possibility
13034:                      my $realpossible=0;
13035:                      foreach my $id (@possibilities) {
13036: 			 my $file=$bighash{'src_'.$id};
13037:                          my $canaccess;
13038:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13039:                              $canaccess = 1;
13040:                          } else {
13041:                              $canaccess = &allowed('bre',$file);
13042:                          }
13043:                          if ($canaccess) {
13044:          		     my ($mapid,$resid)=split(/\./,$id);
13045:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
13046:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13047:                                                              $resid,$thisfn);
13048:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
13049:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
13050:                                  if ($checkforblock) {
13051:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
13052:                                      if (@blockers > 0) {
13053:                                          $syval = '';
13054:                                      } else {
13055:                                          $syval = $poss_syval;
13056:                                          $realpossible++;
13057:                                      }
13058:                                  } else {
13059:                                      $syval = $poss_syval;
13060:                                      $realpossible++;
13061:                                  }
13062:                                  if ($syval) {
13063:                                      if (ref($possibles) eq 'HASH') {
13064:                                          $possibles->{$syval} = 1;
13065:                                      }
13066:                                  }
13067:                              }
13068: 			 }
13069:                      }
13070: 		     if ($realpossible!=1) { $syval=''; }
13071:                  } else {
13072:                      $syval='';
13073:                  }
13074: 	      }
13075:               untie(%bighash);
13076:            }
13077:         }
13078:         if ($syval) {
13079: 	    return $env{$cache_str}=$syval;
13080:         }
13081:     }
13082:     &appenv({'request.ambiguous' => $thisfn});
13083:     return $env{$cache_str}='';
13084: }
13085: 
13086: # ---------------------------------------------------------- Return random seed
13087: 
13088: sub numval {
13089:     my $txt=shift;
13090:     $txt=~tr/A-J/0-9/;
13091:     $txt=~tr/a-j/0-9/;
13092:     $txt=~tr/K-T/0-9/;
13093:     $txt=~tr/k-t/0-9/;
13094:     $txt=~tr/U-Z/0-5/;
13095:     $txt=~tr/u-z/0-5/;
13096:     $txt=~s/\D//g;
13097:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
13098:     return int($txt);
13099: }
13100: 
13101: sub numval2 {
13102:     my $txt=shift;
13103:     $txt=~tr/A-J/0-9/;
13104:     $txt=~tr/a-j/0-9/;
13105:     $txt=~tr/K-T/0-9/;
13106:     $txt=~tr/k-t/0-9/;
13107:     $txt=~tr/U-Z/0-5/;
13108:     $txt=~tr/u-z/0-5/;
13109:     $txt=~s/\D//g;
13110:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13111:     my $total;
13112:     foreach my $val (@txts) { $total+=$val; }
13113:     if ($_64bit) { if ($total > 2**32) { return -1; } }
13114:     return int($total);
13115: }
13116: 
13117: sub numval3 {
13118:     use integer;
13119:     my $txt=shift;
13120:     $txt=~tr/A-J/0-9/;
13121:     $txt=~tr/a-j/0-9/;
13122:     $txt=~tr/K-T/0-9/;
13123:     $txt=~tr/k-t/0-9/;
13124:     $txt=~tr/U-Z/0-5/;
13125:     $txt=~tr/u-z/0-5/;
13126:     $txt=~s/\D//g;
13127:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13128:     my $total;
13129:     foreach my $val (@txts) { $total+=$val; }
13130:     if ($_64bit) { $total=(($total<<32)>>32); }
13131:     return $total;
13132: }
13133: 
13134: sub digest {
13135:     my ($data)=@_;
13136:     my $digest=&Digest::MD5::md5($data);
13137:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
13138:     my ($e,$f);
13139:     {
13140:         use integer;
13141:         $e=($a+$b);
13142:         $f=($c+$d);
13143:         if ($_64bit) {
13144:             $e=(($e<<32)>>32);
13145:             $f=(($f<<32)>>32);
13146:         }
13147:     }
13148:     if (wantarray) {
13149: 	return ($e,$f);
13150:     } else {
13151: 	my $g;
13152: 	{
13153: 	    use integer;
13154: 	    $g=($e+$f);
13155: 	    if ($_64bit) {
13156: 		$g=(($g<<32)>>32);
13157: 	    }
13158: 	}
13159: 	return $g;
13160:     }
13161: }
13162: 
13163: sub latest_rnd_algorithm_id {
13164:     return '64bit5';
13165: }
13166: 
13167: sub get_rand_alg {
13168:     my ($courseid)=@_;
13169:     if (!$courseid) { $courseid=(&whichuser())[1]; }
13170:     if ($courseid) {
13171: 	return $env{"course.$courseid.rndseed"};
13172:     }
13173:     return &latest_rnd_algorithm_id();
13174: }
13175: 
13176: sub validCODE {
13177:     my ($CODE)=@_;
13178:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13179:     return 0;
13180: }
13181: 
13182: sub getCODE {
13183:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13184:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13185: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
13186: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13187: 	return $Apache::lonhomework::history{'resource.CODE'};
13188:     }
13189:     return undef;
13190: }
13191: #
13192: #  Determines the random seed for a specific context:
13193: #
13194: # parameters:
13195: #   symb      - in course context the symb for the seed.
13196: #   course_id - The course id of the form domain_coursenum.
13197: #   domain    - Domain for the user.
13198: #   course    - Course for the user.
13199: #   cenv      - environment of the course.
13200: #
13201: # NOTE:
13202: #   All parameters are picked out of the environment if missing
13203: #   or not defined.
13204: #   If a symb cannot be determined the current time is used instead.
13205: #
13206: #  For a given well defined symb, courside, domain, username,
13207: #  and course environment, the seed is reproducible.
13208: #
13209: sub rndseed {
13210:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
13211:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
13212:     if (!defined($symb)) {
13213: 	unless ($symb=$wsymb) { return time; }
13214:     }
13215:     if (!defined $courseid) { 
13216: 	$courseid=$wcourseid; 
13217:     }
13218:     if (!defined $domain) { $domain=$wdomain; }
13219:     if (!defined $username) { $username=$wusername }
13220: 
13221:     my $which;
13222:     if (defined($cenv->{'rndseed'})) {
13223: 	$which = $cenv->{'rndseed'};
13224:     } else {
13225: 	$which =&get_rand_alg($courseid);
13226:     }
13227:     if (defined(&getCODE())) {
13228: 	if ($which eq '64bit5') {
13229: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13230: 	} elsif ($which eq '64bit4') {
13231: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13232: 	} else {
13233: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13234: 	}
13235:     } elsif ($which eq '64bit5') {
13236: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
13237:     } elsif ($which eq '64bit4') {
13238: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
13239:     } elsif ($which eq '64bit3') {
13240: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
13241:     } elsif ($which eq '64bit2') {
13242: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
13243:     } elsif ($which eq '64bit') {
13244: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
13245:     }
13246:     return &rndseed_32bit($symb,$courseid,$domain,$username);
13247: }
13248: 
13249: sub rndseed_32bit {
13250:     my ($symb,$courseid,$domain,$username)=@_;
13251:     {
13252: 	use integer;
13253: 	my $symbchck=unpack("%32C*",$symb) << 27;
13254: 	my $symbseed=numval($symb) << 22;
13255: 	my $namechck=unpack("%32C*",$username) << 17;
13256: 	my $nameseed=numval($username) << 12;
13257: 	my $domainseed=unpack("%32C*",$domain) << 7;
13258: 	my $courseseed=unpack("%32C*",$courseid);
13259: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
13260: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13261: 	#&logthis("rndseed :$num:$symb");
13262: 	if ($_64bit) { $num=(($num<<32)>>32); }
13263: 	return $num;
13264:     }
13265: }
13266: 
13267: sub rndseed_64bit {
13268:     my ($symb,$courseid,$domain,$username)=@_;
13269:     {
13270: 	use integer;
13271: 	my $symbchck=unpack("%32S*",$symb) << 21;
13272: 	my $symbseed=numval($symb) << 10;
13273: 	my $namechck=unpack("%32S*",$username);
13274: 	
13275: 	my $nameseed=numval($username) << 21;
13276: 	my $domainseed=unpack("%32S*",$domain) << 10;
13277: 	my $courseseed=unpack("%32S*",$courseid);
13278: 	
13279: 	my $num1=$symbchck+$symbseed+$namechck;
13280: 	my $num2=$nameseed+$domainseed+$courseseed;
13281: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13282: 	#&logthis("rndseed :$num:$symb");
13283: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13284: 	return "$num1,$num2";
13285:     }
13286: }
13287: 
13288: sub rndseed_64bit2 {
13289:     my ($symb,$courseid,$domain,$username)=@_;
13290:     {
13291: 	use integer;
13292: 	# strings need to be an even # of cahracters long, it it is odd the
13293:         # last characters gets thrown away
13294: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13295: 	my $symbseed=numval($symb) << 10;
13296: 	my $namechck=unpack("%32S*",$username.' ');
13297: 	
13298: 	my $nameseed=numval($username) << 21;
13299: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13300: 	my $courseseed=unpack("%32S*",$courseid.' ');
13301: 	
13302: 	my $num1=$symbchck+$symbseed+$namechck;
13303: 	my $num2=$nameseed+$domainseed+$courseseed;
13304: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13305: 	#&logthis("rndseed :$num:$symb");
13306: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13307: 	return "$num1,$num2";
13308:     }
13309: }
13310: 
13311: sub rndseed_64bit3 {
13312:     my ($symb,$courseid,$domain,$username)=@_;
13313:     {
13314: 	use integer;
13315: 	# strings need to be an even # of cahracters long, it it is odd the
13316:         # last characters gets thrown away
13317: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13318: 	my $symbseed=numval2($symb) << 10;
13319: 	my $namechck=unpack("%32S*",$username.' ');
13320: 	
13321: 	my $nameseed=numval2($username) << 21;
13322: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13323: 	my $courseseed=unpack("%32S*",$courseid.' ');
13324: 	
13325: 	my $num1=$symbchck+$symbseed+$namechck;
13326: 	my $num2=$nameseed+$domainseed+$courseseed;
13327: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13328: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13329: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13330: 	
13331: 	return "$num1:$num2";
13332:     }
13333: }
13334: 
13335: sub rndseed_64bit4 {
13336:     my ($symb,$courseid,$domain,$username)=@_;
13337:     {
13338: 	use integer;
13339: 	# strings need to be an even # of cahracters long, it it is odd the
13340:         # last characters gets thrown away
13341: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13342: 	my $symbseed=numval3($symb) << 10;
13343: 	my $namechck=unpack("%32S*",$username.' ');
13344: 	
13345: 	my $nameseed=numval3($username) << 21;
13346: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13347: 	my $courseseed=unpack("%32S*",$courseid.' ');
13348: 	
13349: 	my $num1=$symbchck+$symbseed+$namechck;
13350: 	my $num2=$nameseed+$domainseed+$courseseed;
13351: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13352: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13353: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13354: 	
13355: 	return "$num1:$num2";
13356:     }
13357: }
13358: 
13359: sub rndseed_64bit5 {
13360:     my ($symb,$courseid,$domain,$username)=@_;
13361:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13362:     return "$num1:$num2";
13363: }
13364: 
13365: sub rndseed_CODE_64bit {
13366:     my ($symb,$courseid,$domain,$username)=@_;
13367:     {
13368: 	use integer;
13369: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13370: 	my $symbseed=numval2($symb);
13371: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13372: 	my $CODEseed=numval(&getCODE());
13373: 	my $courseseed=unpack("%32S*",$courseid.' ');
13374: 	my $num1=$symbseed+$CODEchck;
13375: 	my $num2=$CODEseed+$courseseed+$symbchck;
13376: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13377: 	#&logthis("rndseed :$num1:$num2:$symb");
13378: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13379: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13380: 	return "$num1:$num2";
13381:     }
13382: }
13383: 
13384: sub rndseed_CODE_64bit4 {
13385:     my ($symb,$courseid,$domain,$username)=@_;
13386:     {
13387: 	use integer;
13388: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13389: 	my $symbseed=numval3($symb);
13390: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13391: 	my $CODEseed=numval3(&getCODE());
13392: 	my $courseseed=unpack("%32S*",$courseid.' ');
13393: 	my $num1=$symbseed+$CODEchck;
13394: 	my $num2=$CODEseed+$courseseed+$symbchck;
13395: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13396: 	#&logthis("rndseed :$num1:$num2:$symb");
13397: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13398: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13399: 	return "$num1:$num2";
13400:     }
13401: }
13402: 
13403: sub rndseed_CODE_64bit5 {
13404:     my ($symb,$courseid,$domain,$username)=@_;
13405:     my $code = &getCODE();
13406:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13407:     return "$num1:$num2";
13408: }
13409: 
13410: sub setup_random_from_rndseed {
13411:     my ($rndseed)=@_;
13412:     if ($rndseed =~/([,:])/) {
13413: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13414:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13415:             &Math::Random::random_set_seed_from_phrase($rndseed);
13416:         } else {
13417:             &Math::Random::random_set_seed($num1,$num2);
13418:         }
13419:     } else {
13420: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13421:     }
13422: }
13423: 
13424: sub latest_receipt_algorithm_id {
13425:     return 'receipt3';
13426: }
13427: 
13428: sub recunique {
13429:     my $fucourseid=shift;
13430:     my $unique;
13431:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13432: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13433: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13434:     } else {
13435: 	$unique=$perlvar{'lonReceipt'};
13436:     }
13437:     return unpack("%32C*",$unique);
13438: }
13439: 
13440: sub recprefix {
13441:     my $fucourseid=shift;
13442:     my $prefix;
13443:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13444: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13445: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13446:     } else {
13447: 	$prefix=$perlvar{'lonHostID'};
13448:     }
13449:     return unpack("%32C*",$prefix);
13450: }
13451: 
13452: sub ireceipt {
13453:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13454: 
13455:     my $return =&recprefix($fucourseid).'-';
13456: 
13457:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13458: 	$env{'request.state'} eq 'construct') {
13459: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13460: 	return $return;
13461:     }
13462: 
13463:     my $cuname=unpack("%32C*",$funame);
13464:     my $cudom=unpack("%32C*",$fudom);
13465:     my $cucourseid=unpack("%32C*",$fucourseid);
13466:     my $cusymb=unpack("%32C*",$fusymb);
13467:     my $cunique=&recunique($fucourseid);
13468:     my $cpart=unpack("%32S*",$part);
13469:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13470: 
13471: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13472: 			       
13473: 	$return.= ($cunique%$cuname+
13474: 		   $cunique%$cudom+
13475: 		   $cusymb%$cuname+
13476: 		   $cusymb%$cudom+
13477: 		   $cucourseid%$cuname+
13478: 		   $cucourseid%$cudom+
13479: 		   $cpart%$cuname+
13480: 		   $cpart%$cudom);
13481:     } else {
13482: 	$return.= ($cunique%$cuname+
13483: 		   $cunique%$cudom+
13484: 		   $cusymb%$cuname+
13485: 		   $cusymb%$cudom+
13486: 		   $cucourseid%$cuname+
13487: 		   $cucourseid%$cudom);
13488:     }
13489:     return $return;
13490: }
13491: 
13492: sub receipt {
13493:     my ($part)=@_;
13494:     my ($symb,$courseid,$domain,$name) = &whichuser();
13495:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13496: }
13497: 
13498: sub whichuser {
13499:     my ($passedsymb)=@_;
13500:     my ($symb,$courseid,$domain,$name,$publicuser);
13501:     if (defined($env{'form.grade_symb'})) {
13502: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13503: 	my $allowed=&allowed('vgr',$tmp_courseid);
13504: 	if (!$allowed &&
13505: 	    exists($env{'request.course.sec'}) &&
13506: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13507: 	    $allowed=&allowed('vgr',$tmp_courseid.
13508: 			      '/'.$env{'request.course.sec'});
13509: 	}
13510: 	if ($allowed) {
13511: 	    ($symb)=&get_env_multiple('form.grade_symb');
13512: 	    $courseid=$tmp_courseid;
13513: 	    ($domain)=&get_env_multiple('form.grade_domain');
13514: 	    ($name)=&get_env_multiple('form.grade_username');
13515: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13516: 	}
13517:     }
13518:     if (!$passedsymb) {
13519: 	$symb=&symbread();
13520:     } else {
13521: 	$symb=$passedsymb;
13522:     }
13523:     $courseid=$env{'request.course.id'};
13524:     $domain=$env{'user.domain'};
13525:     $name=$env{'user.name'};
13526:     if ($name eq 'public' && $domain eq 'public') {
13527: 	if (!defined($env{'form.username'})) {
13528: 	    $env{'form.username'}.=time.rand(10000000);
13529: 	}
13530: 	$name.=$env{'form.username'};
13531:     }
13532:     return ($symb,$courseid,$domain,$name,$publicuser);
13533: 
13534: }
13535: 
13536: # ------------------------------------------------------------ Serves up a file
13537: # returns either the contents of the file or 
13538: # -1 if the file doesn't exist
13539: #
13540: # if the target is a file that was uploaded via DOCS, 
13541: # a check will be made to see if a current copy exists on the local server,
13542: # if it does this will be served, otherwise a copy will be retrieved from
13543: # the home server for the course and stored in /home/httpd/html/userfiles on
13544: # the local server.   
13545: 
13546: sub getfile {
13547:     my ($file) = @_;
13548:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13549:     &repcopy($file);
13550:     return &readfile($file);
13551: }
13552: 
13553: sub repcopy_userfile {
13554:     my ($file)=@_;
13555:     my $londocroot = $perlvar{'lonDocRoot'};
13556:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13557:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13558:     my ($cdom,$cnum,$filename) = 
13559: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13560:     my $uri="/uploaded/$cdom/$cnum/$filename";
13561:     if (-e "$file") {
13562: # we already have a local copy, check it out
13563: 	my @fileinfo = stat($file);
13564: 	my $rtncode;
13565: 	my $info;
13566: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13567: 	if ($lwpresp ne 'ok') {
13568: # there is no such file anymore, even though we had a local copy
13569: 	    if ($rtncode eq '404') {
13570: 		unlink($file);
13571: 	    }
13572: 	    return -1;
13573: 	}
13574: 	if ($info < $fileinfo[9]) {
13575: # nice, the file we have is up-to-date, just say okay
13576: 	    return 'ok';
13577: 	} else {
13578: # the file is outdated, get rid of it
13579: 	    unlink($file);
13580: 	}
13581:     }
13582: # one way or the other, at this point, we don't have the file
13583: # construct the correct path for the file
13584:     my @parts = ($cdom,$cnum); 
13585:     if ($filename =~ m|^(.+)/[^/]+$|) {
13586: 	push @parts, split(/\//,$1);
13587:     }
13588:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13589:     foreach my $part (@parts) {
13590: 	$path .= '/'.$part;
13591: 	if (!-e $path) {
13592: 	    mkdir($path,0770);
13593: 	}
13594:     }
13595: # now the path exists for sure
13596: # get a user agent
13597:     my $ua=new LWP::UserAgent;
13598:     my $transferfile=$file.'.in.transfer';
13599: # FIXME: this should flock
13600:     if (-e $transferfile) { return 'ok'; }
13601:     my $request;
13602:     $uri=~s/^\///;
13603:     my $homeserver = &homeserver($cnum,$cdom);
13604:     my $hostname = &hostname($homeserver);
13605:     my $protocol = $protocol{$homeserver};
13606:     $protocol = 'http' if ($protocol ne 'https');
13607:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
13608:     my $response=$ua->request($request,$transferfile);
13609: # did it work?
13610:     if ($response->is_error()) {
13611: 	unlink($transferfile);
13612: 	&logthis("Userfile repcopy failed for $uri");
13613: 	return -1;
13614:     }
13615: # worked, rename the transfer file
13616:     rename($transferfile,$file);
13617:     return 'ok';
13618: }
13619: 
13620: sub tokenwrapper {
13621:     my $uri=shift;
13622:     $uri=~s|^https?\://([^/]+)||;
13623:     $uri=~s|^/||;
13624:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13625:     my $token=$1;
13626:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13627:     if ($udom && $uname && $file) {
13628: 	$file=~s|(\?\.*)*$||;
13629:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13630:         my $homeserver = &homeserver($uname,$udom);
13631:         my $hostname = &hostname($homeserver);
13632:         my $protocol = $protocol{$homeserver};
13633:         $protocol = 'http' if ($protocol ne 'https');
13634:         return $protocol.'://'.$hostname.'/'.$uri.
13635:                (($uri=~/\?/)?'&':'?').'token='.$token.
13636:                                '&tokenissued='.$perlvar{'lonHostID'};
13637:     } else {
13638:         return '/adm/notfound.html';
13639:     }
13640: }
13641: 
13642: # call with reqtype HEAD: get last modification time
13643: # call with reqtype GET: get the file contents
13644: # Do not call this with reqtype GET for large files! It loads everything into memory
13645: #
13646: sub getuploaded {
13647:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13648:     $uri=~s/^\///;
13649:     my $homeserver = &homeserver($cnum,$cdom);
13650:     my $hostname = &hostname($homeserver);
13651:     my $protocol = $protocol{$homeserver};
13652:     $protocol = 'http' if ($protocol ne 'https');
13653:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
13654:     my $ua=new LWP::UserAgent;
13655:     my $request=new HTTP::Request($reqtype,$uri);
13656:     my $response=$ua->request($request);
13657:     $$rtncode = $response->code;
13658:     if (! $response->is_success()) {
13659: 	return 'failed';
13660:     }      
13661:     if ($reqtype eq 'HEAD') {
13662: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13663:     } elsif ($reqtype eq 'GET') {
13664: 	$$info = $response->content;
13665:     }
13666:     return 'ok';
13667: }
13668: 
13669: sub readfile {
13670:     my $file = shift;
13671:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13672:     my $fh;
13673:     open($fh,"<",$file);
13674:     my $a='';
13675:     while (my $line = <$fh>) { $a .= $line; }
13676:     return $a;
13677: }
13678: 
13679: sub filelocation {
13680:     my ($dir,$file) = @_;
13681:     my $location;
13682:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13683: 
13684:     if ($file =~ m-^/adm/-) {
13685: 	$file=~s-^/adm/wrapper/-/-;
13686: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13687:     }
13688: 
13689:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13690:         $location = $file;
13691:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13692:         my ($udom,$uname,$filename)=
13693:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13694:         my $home=&homeserver($uname,$udom);
13695:         my $is_me=0;
13696:         my @ids=&current_machine_ids();
13697:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13698:         if ($is_me) {
13699:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13700:         } else {
13701:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13702:   	      $udom.'/'.$uname.'/'.$filename;
13703:         }
13704:     } elsif ($file =~ m-^/adm/-) {
13705: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13706:     } else {
13707:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13708:         $file=~s:^/(res|priv)/:/:;
13709:         my $space=$1;
13710:         if ( !( $file =~ m:^/:) ) {
13711:             $location = $dir. '/'.$file;
13712:         } else {
13713:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13714:         }
13715:     }
13716:     $location=~s://+:/:g; # remove duplicate /
13717:     while ($location=~m{/\.\./}) {
13718: 	if ($location =~ m{/[^/]+/\.\./}) {
13719: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13720: 	} else {
13721: 	    $location=~ s{/\.\./}{/}g;
13722: 	}
13723:     } #remove dir/..
13724:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13725:     return $location;
13726: }
13727: 
13728: sub hreflocation {
13729:     my ($dir,$file)=@_;
13730:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13731: 	$file=filelocation($dir,$file);
13732:     } elsif ($file=~m-^/adm/-) {
13733: 	$file=~s-^/adm/wrapper/-/-;
13734: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13735:     }
13736:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13737: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13738:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13739: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13740: 	        {/uploaded/$1/$2/}x;
13741:     }
13742:     if ($file=~ m{^/userfiles/}) {
13743: 	$file =~ s{^/userfiles/}{/uploaded/};
13744:     }
13745:     return $file;
13746: }
13747: 
13748: 
13749: 
13750: 
13751: 
13752: sub current_machine_domains {
13753:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13754: }
13755: 
13756: sub machine_domains {
13757:     my ($hostname) = @_;
13758:     my @domains;
13759:     my %hostname = &all_hostnames();
13760:     while( my($id, $name) = each(%hostname)) {
13761: #	&logthis("-$id-$name-$hostname-");
13762: 	if ($hostname eq $name) {
13763: 	    push(@domains,&host_domain($id));
13764: 	}
13765:     }
13766:     return @domains;
13767: }
13768: 
13769: sub current_machine_ids {
13770:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13771: }
13772: 
13773: sub machine_ids {
13774:     my ($hostname) = @_;
13775:     $hostname ||= &hostname($perlvar{'lonHostID'});
13776:     my @ids;
13777:     my %name_to_host = &all_names();
13778:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13779: 	return @{ $name_to_host{$hostname} };
13780:     }
13781:     return;
13782: }
13783: 
13784: sub additional_machine_domains {
13785:     my @domains;
13786:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
13787:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
13788:             while( my $line = <$fh>) {
13789:                 chomp($line);
13790:                 $line =~ s/\s//g;
13791:                 push(@domains,$line);
13792:             }
13793:             close($fh);
13794:         }
13795:     }
13796:     return @domains;
13797: }
13798: 
13799: sub default_login_domain {
13800:     my $domain = $perlvar{'lonDefDomain'};
13801:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13802:     foreach my $posdom (&current_machine_domains(),
13803:                         &additional_machine_domains()) {
13804:         if (lc($posdom) eq lc($testdomain)) {
13805:             $domain=$posdom;
13806:             last;
13807:         }
13808:     }
13809:     return $domain;
13810: }
13811: 
13812: sub shared_institution {
13813:     my ($dom,$lonhost) = @_;
13814:     if ($lonhost eq '') {
13815:         $lonhost = $perlvar{'lonHostID'};
13816:     }
13817:     my $same_intdom;
13818:     my $hostintdom = &internet_dom($lonhost);
13819:     if ($hostintdom ne '') {
13820:         my %iphost = &get_iphost();
13821:         my $primary_id = &domain($dom,'primary');
13822:         my $primary_ip = &get_host_ip($primary_id);
13823:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
13824:             foreach my $id (@{$iphost{$primary_ip}}) {
13825:                 my $intdom = &internet_dom($id);
13826:                 if ($intdom eq $hostintdom) {
13827:                     $same_intdom = 1;
13828:                     last;
13829:                 }
13830:             }
13831:         }
13832:     }
13833:     return $same_intdom;
13834: }
13835: 
13836: sub uses_sts {
13837:     my ($ignore_cache) = @_;
13838:     my $lonhost = $perlvar{'lonHostID'};
13839:     my $hostname = &hostname($lonhost);
13840:     my $sts_on;
13841:     if ($protocol{$lonhost} eq 'https') {
13842:         my $cachetime = 12*3600;
13843:         if (!$ignore_cache) {
13844:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13845:             if (defined($cached)) {
13846:                 return $sts_on;
13847:             }
13848:         }
13849:         my $ua=new LWP::UserAgent;
13850:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13851:         my $request=new HTTP::Request('HEAD',$url);
13852:         my $response=$ua->request($request);
13853:         if ($response->is_success) {
13854:             my $has_sts = $response->header('Strict-Transport-Security');
13855:             if ($has_sts eq '') {
13856:                 $sts_on = 0;
13857:             } else {
13858:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13859:                     my $maxage = $1;
13860:                     if ($maxage) {
13861:                         $sts_on = 1;
13862:                     } else {
13863:                         $sts_on = 0;
13864:                     }
13865:                 } else {
13866:                     $sts_on = 0;
13867:                 }
13868:             }
13869:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13870:         }
13871:     }
13872:     return;
13873: }
13874: 
13875: sub waf_allssl {
13876:     my ($host_name) = @_;
13877:     my $alias = &get_proxy_alias();
13878:     if ($host_name eq '') {
13879:         $host_name = $ENV{'SERVER_NAME'};
13880:     }
13881:     if (($host_name ne '') && ($alias eq $host_name)) {
13882:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
13883:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
13884:         if ($defdomdefaults{'waf_sslopt'}) {
13885:             return $defdomdefaults{'waf_sslopt'};
13886:         }
13887:     }
13888:     return;
13889: }
13890: 
13891: sub get_requestor_ip {
13892:     my ($r,$nolookup,$noproxy) = @_;
13893:     my $from_ip;
13894:     if (ref($r)) {
13895:         if ($r->can('useragent_ip')) {
13896:             if ($noproxy && $r->can('client_ip')) {
13897:                 $from_ip = $r->client_ip();
13898:             } else {
13899:                 $from_ip = $r->useragent_ip();
13900:             }
13901:         } elsif ($r->connection->can('remote_ip')) {
13902:             $from_ip = $r->connection->remote_ip();
13903:         } else {
13904:             $from_ip = $r->get_remote_host($nolookup);
13905:         }
13906:     } else {
13907:         $from_ip = $ENV{'REMOTE_ADDR'};
13908:     }
13909:     return $from_ip if ($noproxy);
13910:    # Who controls proxy settings for server
13911:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
13912:     my $proxyinfo = &get_proxy_settings($dom_in_use);
13913:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
13914:         if ($proxyinfo->{'vpnint'}) {
13915:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
13916:                 return $from_ip;
13917:             }
13918:         }
13919:         if ($proxyinfo->{'trusted'}) {
13920:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
13921:                 my $ipheader = $proxyinfo->{'ipheader'};
13922:                 my ($ip,$xfor);
13923:                 if (ref($r)) {
13924:                     if ($ipheader) {
13925:                         $ip = $r->headers_in->{$ipheader};
13926:                     }
13927:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
13928:                 } else {
13929:                     if ($ipheader) {
13930:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
13931:                     }
13932:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
13933:                 }
13934:                 if (($ip eq '') && ($xfor ne '')) {
13935:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
13936:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
13937:                             $ip = $poss_ip;
13938:                             last;
13939:                         }
13940:                     }
13941:                 }
13942:                 if ($ip ne '') {
13943:                     return $ip;
13944:                 }
13945:             }
13946:         }
13947:     }
13948:     return $from_ip;
13949: }
13950: 
13951: sub get_proxy_settings {
13952:     my ($dom_in_use) = @_;
13953:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
13954:     my $proxyinfo = {
13955:                        ipheader => $domdefaults{'waf_ipheader'},
13956:                        trusted  => $domdefaults{'waf_trusted'},
13957:                        vpnint   => $domdefaults{'waf_vpnint'},
13958:                        vpnext   => $domdefaults{'waf_vpnext'},
13959:                        sslopt   => $domdefaults{'waf_sslopt'},
13960:                     };
13961:     return $proxyinfo;
13962: }
13963: 
13964: sub ip_match {
13965:     my ($ip,$pattern_str) = @_;
13966:     $ip=Net::CIDR::cidrvalidate($ip);
13967:     if ($ip) {
13968:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
13969:     }
13970:     return;
13971: }
13972: 
13973: sub get_proxy_alias {
13974:     my ($lonid) = @_;
13975:     if ($lonid eq '') {
13976:         $lonid = $perlvar{'lonHostID'};
13977:     }
13978:     if (!defined(&hostname($lonid))) {
13979:         return;
13980:     }
13981:     if ($lonid ne '') {
13982:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
13983:         if ($cached) {
13984:             return $alias;
13985:         }
13986:         my $dom = &Apache::lonnet::host_domain($lonid);
13987:         if ($dom ne '') {
13988:             my $cachetime = 60*60*24;
13989:             my %domconfig =
13990:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
13991:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
13992:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
13993:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
13994:                 }
13995:             }
13996:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
13997:         }
13998:     }
13999:     return;
14000: }
14001: 
14002: sub use_proxy_alias {
14003:     my ($r,$lonid) = @_;
14004:     my $alias = &get_proxy_alias($lonid);
14005:     if ($alias) {
14006:         my $dom = &host_domain($lonid);
14007:         if ($dom ne '') {
14008:             my $proxyinfo = &get_proxy_settings($dom);
14009:             my ($vpnint,$remote_ip);
14010:             if (ref($proxyinfo) eq 'HASH') {
14011:                 $vpnint = $proxyinfo->{'vpnint'};
14012:                 if ($vpnint) {
14013:                     $remote_ip = &get_requestor_ip($r,1,1);
14014:                 }
14015:             }
14016:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
14017:                 return $alias;
14018:             }
14019:         }
14020:     }
14021:     return;
14022: }
14023: 
14024: sub alias_sso {
14025:     my ($lonid) = @_;
14026:     if ($lonid eq '') {
14027:         $lonid = $perlvar{'lonHostID'};
14028:     }
14029:     if (!defined(&hostname($lonid))) {
14030:         return;
14031:     }
14032:     if ($lonid ne '') {
14033:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
14034:         if ($cached) {
14035:             return $use_alias;
14036:         }
14037:         my $dom = &Apache::lonnet::host_domain($lonid);
14038:         if ($dom ne '') {
14039:             my $cachetime = 60*60*24;
14040:             my %domconfig =
14041:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14042:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14043:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
14044:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
14045:                 }
14046:             }
14047:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
14048:         }
14049:     }
14050:     return;
14051: }
14052: 
14053: sub get_saml_landing {
14054:     my ($lonid) = @_;
14055:     if ($lonid eq '') {
14056:         my $defdom = &default_login_domain();
14057:         my @hosts = &current_machine_ids();
14058:         if (@hosts > 1) {
14059:             foreach my $hostid (@hosts) {
14060:                 if (&host_domain($hostid) eq $defdom) {
14061:                     $lonid = $hostid;
14062:                     last;
14063:                 }
14064:             }
14065:         } else {
14066:             $lonid = $perlvar{'lonHostID'};
14067:         }
14068:         if ($lonid) {
14069:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
14070:                 return;
14071:             }
14072:         } else {
14073:             return;
14074:         }
14075:     } elsif (!defined(&hostname($lonid))) {
14076:         return;
14077:     }
14078:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
14079:     if ($cached) {
14080:         return $landing;
14081:     }
14082:     my $dom = &Apache::lonnet::host_domain($lonid);
14083:     if ($dom ne '') {
14084:         my $cachetime = 60*60*24;
14085:         my %domconfig =
14086:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
14087:         if (ref($domconfig{'login'}) eq 'HASH') {
14088:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
14089:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
14090:                     $landing = 1;
14091:                 }
14092:             }
14093:         }
14094:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
14095:     }
14096:     return;
14097: }
14098: 
14099: # ------------------------------------------------------------- Declutters URLs
14100: 
14101: sub declutter {
14102:     my $thisfn=shift;
14103:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14104:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14105:         $thisfn=~s{^/home/httpd/html}{};
14106:     }
14107:     $thisfn=~s/^\///;
14108:     $thisfn=~s|^adm/wrapper/||;
14109:     $thisfn=~s|^adm/coursedocs/showdoc/||;
14110:     $thisfn=~s/^res\///;
14111:     $thisfn=~s/^priv\///;
14112:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14113:         $thisfn=~s/\?.+$//;
14114:     }
14115:     return $thisfn;
14116: }
14117: 
14118: # ------------------------------------------------------------- Clutter up URLs
14119: 
14120: sub clutter {
14121:     my $thisfn='/'.&declutter(shift);
14122:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
14123: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
14124:        $thisfn='/res'.$thisfn; 
14125:     }
14126:     if ($thisfn !~m|^/adm|) {
14127: 	if ($thisfn =~ m|^/ext/|) {
14128: 	    $thisfn='/adm/wrapper'.$thisfn;
14129: 	} else {
14130: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
14131: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
14132: 	    if ($embstyle eq 'ssi'
14133: 		|| ($embstyle eq 'hdn')
14134: 		|| ($embstyle eq 'rat')
14135: 		|| ($embstyle eq 'prv')
14136: 		|| ($embstyle eq 'ign')) {
14137: 		#do nothing with these
14138: 	    } elsif (($embstyle eq 'img') 
14139: 		|| ($embstyle eq 'emb')
14140: 		|| ($embstyle eq 'wrp')) {
14141: 		$thisfn='/adm/wrapper'.$thisfn;
14142: 	    } elsif ($embstyle eq 'unk'
14143: 		     && $thisfn!~/\.(sequence|page)$/) {
14144: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
14145: 	    } else {
14146: #		&logthis("Got a blank emb style");
14147: 	    }
14148: 	}
14149:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14150:         $thisfn='/adm/wrapper'.$thisfn;
14151:     }
14152:     return $thisfn;
14153: }
14154: 
14155: sub clutter_with_no_wrapper {
14156:     my $uri = &clutter(shift);
14157:     if ($uri =~ m-^/adm/-) {
14158: 	$uri =~ s-^/adm/wrapper/-/-;
14159: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
14160:     }
14161:     return $uri;
14162: }
14163: 
14164: sub freeze_escape {
14165:     my ($value)=@_;
14166:     if (ref($value)) {
14167: 	$value=&nfreeze($value);
14168: 	return '__FROZEN__'.&escape($value);
14169:     }
14170:     return &escape($value);
14171: }
14172: 
14173: 
14174: sub thaw_unescape {
14175:     my ($value)=@_;
14176:     if ($value =~ /^__FROZEN__/) {
14177: 	substr($value,0,10,undef);
14178: 	$value=&unescape($value);
14179: 	return &thaw($value);
14180:     }
14181:     return &unescape($value);
14182: }
14183: 
14184: sub correct_line_ends {
14185:     my ($result)=@_;
14186:     $$result =~s/\r\n/\n/mg;
14187:     $$result =~s/\r/\n/mg;
14188: }
14189: # ================================================================ Main Program
14190: 
14191: sub goodbye {
14192:    &logthis("Starting Shut down");
14193: #not converted to using infrastruture and probably shouldn't be
14194:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
14195: #converted
14196: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
14197:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14198: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14199: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
14200: #1.1 only
14201: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14202: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14203: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14204: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14205:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
14206:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14207:    &logthis(sprintf("%-20s is %s",'hits',$hits));
14208:    &flushcourselogs();
14209:    &logthis("Shutting down");
14210: }
14211: 
14212: sub get_dns {
14213:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
14214:     if (!$ignore_cache) {
14215: 	my ($content,$cached)=
14216: 	    &Apache::lonnet::is_cached_new('dns',$url);
14217: 	if ($cached) {
14218: 	    &$func($content,$hashref);
14219: 	    return;
14220: 	}
14221:     }
14222: 
14223:     my %alldns;
14224:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14225:         foreach my $dns (<$config>) {
14226: 	    next if ($dns !~ /^\^(\S*)/x);
14227:             my $line = $1;
14228:             my ($host,$protocol) = split(/:/,$line);
14229:             if ($protocol ne 'https') {
14230:                 $protocol = 'http';
14231:             }
14232: 	    $alldns{$host} = $protocol;
14233:         }
14234:         close($config);
14235:     }
14236:     while (%alldns) {
14237: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
14238:         my @content;
14239:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
14240:             my $command = (split('/',$url))[3];
14241:             my ($dir,$file) = &parse_getdns_url($command,$url);
14242:             delete($alldns{$dns});
14243:             next if (($dir eq '') || ($file eq ''));
14244:             if (open(my $config,'<',"$dir/$file")) {
14245:                 @content = <$config>;
14246:                 close($config);
14247:             }
14248:         } else {
14249: 	    my $ua=new LWP::UserAgent;
14250:             $ua->timeout(30);
14251: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14252: 	    my $response=$ua->request($request);
14253:             delete($alldns{$dns});
14254: 	    next if ($response->is_error());
14255: 	    @content = split("\n",$response->content);
14256:         }
14257:         unless ($nocache) {
14258: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
14259:         }
14260: 	&$func(\@content,$hashref);
14261: 	return;
14262:     }
14263:     my $which = (split('/',$url))[3];
14264:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14265:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14266:         my @content = <$config>;
14267:         &$func(\@content,$hashref);
14268:     }
14269:     return;
14270: }
14271: 
14272: # ------------------------------------------------------Get DNS checksums file
14273: sub parse_dns_checksums_tab {
14274:     my ($lines,$hashref) = @_;
14275:     my $lonhost = $perlvar{'lonHostID'};
14276:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
14277:     my $loncaparev = &get_server_loncaparev($machine_dom);
14278:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14279:     my $webconfdir = '/etc/httpd/conf';
14280:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14281:         $webconfdir = '/etc/apache2';
14282:     } elsif ($distro =~ /^sles(\d+)$/) {
14283:         if ($1 >= 10) {
14284:             $webconfdir = '/etc/apache2';
14285:         }
14286:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14287:         if ($1 >= 10.0) {
14288:             $webconfdir = '/etc/apache2';
14289:         }
14290:     }
14291:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14292:     my (%chksum,%revnum);
14293:     if (ref($lines) eq 'ARRAY') {
14294:         chomp(@{$lines});
14295:         my $version = shift(@{$lines});
14296:         if ($version eq $release) {
14297:             foreach my $line (@{$lines}) {
14298:                 my ($file,$version,$shasum) = split(/,/,$line);
14299:                 if ($file =~ m{^/etc/httpd/conf}) {
14300:                     if ($webconfdir eq '/etc/apache2') {
14301:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14302:                     }
14303:                 }
14304:                 $chksum{$file} = $shasum;
14305:                 $revnum{$file} = $version;
14306:             }
14307:             if (ref($hashref) eq 'HASH') {
14308:                 %{$hashref} = (
14309:                                 sums     => \%chksum,
14310:                                 versions => \%revnum,
14311:                               );
14312:             }
14313:         }
14314:     }
14315:     return;
14316: }
14317: 
14318: sub fetch_dns_checksums {
14319:     my %checksums;
14320:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
14321:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
14322:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14323:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
14324:              \%checksums);
14325:     return \%checksums;
14326: }
14327: 
14328: sub parse_getdns_url {
14329:     my ($command,$url) = @_;
14330:     my $dir = $perlvar{'lonTabDir'};
14331:     my $file;
14332:     if ($command eq 'hosts') {
14333:         $file = 'dns_hosts.tab';
14334:     } elsif ($command eq 'domain') {
14335:         $file = 'dns_domain.tab';
14336:     } elsif ($command eq 'checksums') {
14337:         my $version = (split('/',$url))[4];
14338:         $file = "dns_checksums/$version.tab",
14339:     }
14340:     return ($dir,$file);
14341: }
14342: 
14343: # ------------------------------------------------------------ Read domain file
14344: {
14345:     my $loaded;
14346:     my %domain;
14347: 
14348:     sub parse_domain_tab {
14349: 	my ($lines) = @_;
14350: 	foreach my $line (@$lines) {
14351: 	    next if ($line =~ /^(\#|\s*$ )/x);
14352: 
14353: 	    chomp($line);
14354: 	    my ($name,@elements) = split(/:/,$line,9);
14355: 	    my %this_domain;
14356: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
14357: 			       'lang_def', 'city', 'longi', 'lati',
14358: 			       'primary') {
14359: 		$this_domain{$field} = shift(@elements);
14360: 	    }
14361: 	    $domain{$name} = \%this_domain;
14362: 	}
14363:     }
14364: 
14365:     sub reset_domain_info {
14366: 	undef($loaded);
14367: 	undef(%domain);
14368:     }
14369: 
14370:     sub load_domain_tab {
14371: 	my ($ignore_cache,$nocache) = @_;
14372: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
14373: 	my $fh;
14374: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
14375: 	    my @lines = <$fh>;
14376: 	    &parse_domain_tab(\@lines);
14377: 	}
14378: 	close($fh);
14379: 	$loaded = 1;
14380:     }
14381: 
14382:     sub domain {
14383: 	&load_domain_tab() if (!$loaded);
14384: 
14385: 	my ($name,$what) = @_;
14386: 	return if ( !exists($domain{$name}) );
14387: 
14388: 	if (!$what) {
14389: 	    return $domain{$name}{'description'};
14390: 	}
14391: 	return $domain{$name}{$what};
14392:     }
14393: 
14394:     sub domain_info {
14395:         &load_domain_tab() if (!$loaded);
14396:         return %domain;
14397:     }
14398: 
14399: }
14400: 
14401: 
14402: # ------------------------------------------------------------- Read hosts file
14403: {
14404:     my %hostname;
14405:     my %hostdom;
14406:     my %libserv;
14407:     my $loaded;
14408:     my %name_to_host;
14409:     my %internetdom;
14410:     my %LC_dns_serv;
14411: 
14412:     sub parse_hosts_tab {
14413: 	my ($file) = @_;
14414: 	foreach my $configline (@$file) {
14415: 	    next if ($configline =~ /^(\#|\s*$ )/x);
14416:             chomp($configline);
14417: 	    if ($configline =~ /^\^/) {
14418:                 if ($configline =~ /^\^([\w.\-]+)/) {
14419:                     $LC_dns_serv{$1} = 1;
14420:                 }
14421:                 next;
14422:             }
14423: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
14424: 	    $name=~s/\s//g;
14425: 	    if ($id && $domain && $role && $name) {
14426:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14427:                     my $curr = $hostname{$id};
14428:                     my $skip;
14429:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
14430:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14431:                             $skip = 1;
14432:                         } else {
14433:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14434:                         }
14435:                     }
14436:                     unless ($skip) {
14437:                         push(@{$name_to_host{$name}},$id);
14438:                     }
14439:                 } else {
14440:                     push(@{$name_to_host{$name}},$id);
14441:                 }
14442: 		$hostname{$id}=$name;
14443: 		$hostdom{$id}=$domain;
14444: 		if ($role eq 'library') { $libserv{$id}=$name; }
14445:                 if (defined($protocol)) {
14446:                     if ($protocol eq 'https') {
14447:                         $protocol{$id} = $protocol;
14448:                     } else {
14449:                         $protocol{$id} = 'http'; 
14450:                     }
14451:                 } else {
14452:                     $protocol{$id} = 'http';
14453:                 }
14454:                 if (defined($intdom)) {
14455:                     $internetdom{$id} = $intdom;
14456:                 }
14457: 	    }
14458: 	}
14459:     }
14460:     
14461:     sub reset_hosts_info {
14462: 	&purge_remembered();
14463: 	&reset_domain_info();
14464: 	&reset_hosts_ip_info();
14465: 	undef(%name_to_host);
14466: 	undef(%hostname);
14467: 	undef(%hostdom);
14468: 	undef(%libserv);
14469: 	undef($loaded);
14470:     }
14471: 
14472:     sub load_hosts_tab {
14473: 	my ($ignore_cache,$nocache) = @_;
14474: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
14475: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
14476: 	my @config = <$config>;
14477: 	&parse_hosts_tab(\@config);
14478: 	close($config);
14479: 	$loaded=1;
14480:     }
14481: 
14482:     sub hostname {
14483: 	&load_hosts_tab() if (!$loaded);
14484: 
14485: 	my ($lonid) = @_;
14486: 	return $hostname{$lonid};
14487:     }
14488: 
14489:     sub all_hostnames {
14490: 	&load_hosts_tab() if (!$loaded);
14491: 
14492: 	return %hostname;
14493:     }
14494: 
14495:     sub all_names {
14496:         my ($ignore_cache,$nocache) = @_;
14497: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
14498: 
14499: 	return %name_to_host;
14500:     }
14501: 
14502:     sub all_host_domain {
14503:         &load_hosts_tab() if (!$loaded);
14504:         return %hostdom;
14505:     }
14506: 
14507:     sub is_library {
14508: 	&load_hosts_tab() if (!$loaded);
14509: 
14510: 	return exists($libserv{$_[0]});
14511:     }
14512: 
14513:     sub all_library {
14514: 	&load_hosts_tab() if (!$loaded);
14515: 
14516: 	return %libserv;
14517:     }
14518: 
14519:     sub unique_library {
14520: 	#2x reverse removes all hostnames that appear more than once
14521:         my %unique = reverse &all_library();
14522:         return reverse %unique;
14523:     }
14524: 
14525:     sub get_servers {
14526: 	&load_hosts_tab() if (!$loaded);
14527: 
14528: 	my ($domain,$type) = @_;
14529: 	my %possible_hosts = ($type eq 'library') ? %libserv
14530: 	                                          : %hostname;
14531: 	my %result;
14532: 	if (ref($domain) eq 'ARRAY') {
14533: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14534: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
14535: 		    $result{$host} = $hostname;
14536: 		}
14537: 	    }
14538: 	} else {
14539: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14540: 		if ($hostdom{$host} eq $domain) {
14541: 		    $result{$host} = $hostname;
14542: 		}
14543: 	    }
14544: 	}
14545: 	return %result;
14546:     }
14547: 
14548:     sub get_unique_servers {
14549:         my %unique = reverse &get_servers(@_);
14550: 	return reverse %unique;
14551:     }
14552: 
14553:     sub host_domain {
14554: 	&load_hosts_tab() if (!$loaded);
14555: 
14556: 	my ($lonid) = @_;
14557: 	return $hostdom{$lonid};
14558:     }
14559: 
14560:     sub all_domains {
14561: 	&load_hosts_tab() if (!$loaded);
14562: 
14563: 	my %seen;
14564: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
14565: 	return @uniq;
14566:     }
14567: 
14568:     sub internet_dom {
14569:         &load_hosts_tab() if (!$loaded);
14570: 
14571:         my ($lonid) = @_;
14572:         return $internetdom{$lonid};
14573:     }
14574: 
14575:     sub is_LC_dns {
14576:         &load_hosts_tab() if (!$loaded);
14577: 
14578:         my ($hostname) = @_;
14579:         return exists($LC_dns_serv{$hostname});
14580:     }
14581: 
14582: }
14583: 
14584: { 
14585:     my %iphost;
14586:     my %name_to_ip;
14587:     my %lonid_to_ip;
14588: 
14589:     sub get_hosts_from_ip {
14590: 	my ($ip) = @_;
14591: 	my %iphosts = &get_iphost();
14592: 	if (ref($iphosts{$ip})) {
14593: 	    return @{$iphosts{$ip}};
14594: 	}
14595: 	return;
14596:     }
14597:     
14598:     sub reset_hosts_ip_info {
14599: 	undef(%iphost);
14600: 	undef(%name_to_ip);
14601: 	undef(%lonid_to_ip);
14602:     }
14603: 
14604:     sub get_host_ip {
14605: 	my ($lonid) = @_;
14606: 	if (exists($lonid_to_ip{$lonid})) {
14607: 	    return $lonid_to_ip{$lonid};
14608: 	}
14609: 	my $name=&hostname($lonid);
14610:    	my $ip = gethostbyname($name);
14611: 	return if (!$ip || length($ip) ne 4);
14612: 	$ip=inet_ntoa($ip);
14613: 	$name_to_ip{$name}   = $ip;
14614: 	$lonid_to_ip{$lonid} = $ip;
14615: 	return $ip;
14616:     }
14617:     
14618:     sub get_iphost {
14619: 	my ($ignore_cache,$nocache) = @_;
14620: 
14621: 	if (!$ignore_cache) {
14622: 	    if (%iphost) {
14623: 		return %iphost;
14624: 	    }
14625: 	    my ($ip_info,$cached)=
14626: 		&Apache::lonnet::is_cached_new('iphost','iphost');
14627: 	    if ($cached) {
14628: 		%iphost      = %{$ip_info->[0]};
14629: 		%name_to_ip  = %{$ip_info->[1]};
14630: 		%lonid_to_ip = %{$ip_info->[2]};
14631: 		return %iphost;
14632: 	    }
14633: 	}
14634: 
14635: 	# get yesterday's info for fallback
14636: 	my %old_name_to_ip;
14637: 	my ($ip_info,$cached)=
14638: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
14639: 	if ($cached) {
14640: 	    %old_name_to_ip = %{$ip_info->[1]};
14641: 	}
14642: 
14643: 	my %name_to_host = &all_names($ignore_cache,$nocache);
14644: 	foreach my $name (keys(%name_to_host)) {
14645: 	    my $ip;
14646: 	    if (!exists($name_to_ip{$name})) {
14647: 		$ip = gethostbyname($name);
14648: 		if (!$ip || length($ip) ne 4) {
14649: 		    if (defined($old_name_to_ip{$name})) {
14650: 			$ip = $old_name_to_ip{$name};
14651: 			&logthis("Can't find $name defaulting to old $ip");
14652: 		    } else {
14653: 			&logthis("Name $name no IP found");
14654: 			next;
14655: 		    }
14656: 		} else {
14657: 		    $ip=inet_ntoa($ip);
14658: 		}
14659: 		$name_to_ip{$name} = $ip;
14660: 	    } else {
14661: 		$ip = $name_to_ip{$name};
14662: 	    }
14663: 	    foreach my $id (@{ $name_to_host{$name} }) {
14664: 		$lonid_to_ip{$id} = $ip;
14665: 	    }
14666: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
14667: 	}
14668:         unless ($nocache) {
14669: 	    &do_cache_new('iphost','iphost',
14670: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
14671: 		          48*60*60);
14672:         }
14673: 
14674: 	return %iphost;
14675:     }
14676: 
14677:     #
14678:     #  Given a DNS returns the loncapa host name for that DNS 
14679:     # 
14680:     sub host_from_dns {
14681:         my ($dns) = @_;
14682:         my @hosts;
14683:         my $ip;
14684: 
14685:         if (exists($name_to_ip{$dns})) {
14686:             $ip = $name_to_ip{$dns};
14687:         }
14688:         if (!$ip) {
14689:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14690:             if (length($ip) == 4) { 
14691: 	        $ip   = &IO::Socket::inet_ntoa($ip);
14692:             }
14693:         }
14694:         if ($ip) {
14695: 	    @hosts = get_hosts_from_ip($ip);
14696: 	    return $hosts[0];
14697:         }
14698:         return undef;
14699:     }
14700: 
14701:     sub get_internet_names {
14702:         my ($lonid) = @_;
14703:         return if ($lonid eq '');
14704:         my ($idnref,$cached)=
14705:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14706:         if ($cached) {
14707:             return $idnref;
14708:         }
14709:         my $ip = &get_host_ip($lonid);
14710:         my @hosts = &get_hosts_from_ip($ip);
14711:         my %iphost = &get_iphost();
14712:         my (@idns,%seen);
14713:         foreach my $id (@hosts) {
14714:             my $dom = &host_domain($id);
14715:             my $prim_id = &domain($dom,'primary');
14716:             my $prim_ip = &get_host_ip($prim_id);
14717:             next if ($seen{$prim_ip});
14718:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14719:                 foreach my $id (@{$iphost{$prim_ip}}) {
14720:                     my $intdom = &internet_dom($id);
14721:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14722:                         push(@idns,$intdom);
14723:                     }
14724:                 }
14725:             }
14726:             $seen{$prim_ip} = 1;
14727:         }
14728:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14729:     }
14730: 
14731: }
14732: 
14733: sub all_loncaparevs {
14734:     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);
14735: }
14736: 
14737: # ------------------------------------------------------- Read loncaparev table
14738: {
14739:     sub load_loncaparevs {
14740:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14741:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14742:                 while (my $configline=<$config>) {
14743:                     chomp($configline);
14744:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14745:                     $loncaparevs{$hostid}=$loncaparev;
14746:                 }
14747:                 close($config);
14748:             }
14749:         }
14750:     }
14751: }
14752: 
14753: # ----------------------------------------------------- Read serverhostID table
14754: {
14755:     sub load_serverhomeIDs {
14756:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14757:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14758:                 while (my $configline=<$config>) {
14759:                     chomp($configline);
14760:                     my ($name,$id)=split(/:/,$configline);
14761:                     $serverhomeIDs{$name}=$id;
14762:                 }
14763:                 close($config);
14764:             }
14765:         }
14766:     }
14767: }
14768: 
14769: 
14770: BEGIN {
14771: 
14772: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14773:     unless ($readit) {
14774: {
14775:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14776:     %perlvar = (%perlvar,%{$configvars});
14777: }
14778: 
14779: 
14780: # ------------------------------------------------------ Read spare server file
14781: {
14782:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14783: 
14784:     while (my $configline=<$config>) {
14785:        chomp($configline);
14786:        if ($configline) {
14787: 	   my ($host,$type) = split(':',$configline,2);
14788: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14789: 	   push(@{ $spareid{$type} }, $host);
14790:        }
14791:     }
14792:     close($config);
14793: }
14794: # ------------------------------------------------------------ Read permissions
14795: {
14796:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14797: 
14798:     while (my $configline=<$config>) {
14799: 	chomp($configline);
14800: 	if ($configline) {
14801: 	    my ($role,$perm)=split(/ /,$configline);
14802: 	    if ($perm ne '') { $pr{$role}=$perm; }
14803: 	}
14804:     }
14805:     close($config);
14806: }
14807: 
14808: # -------------------------------------------- Read plain texts for permissions
14809: {
14810:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14811: 
14812:     while (my $configline=<$config>) {
14813: 	chomp($configline);
14814: 	if ($configline) {
14815: 	    my ($short,@plain)=split(/:/,$configline);
14816:             %{$prp{$short}} = ();
14817: 	    if (@plain > 0) {
14818:                 $prp{$short}{'std'} = $plain[0];
14819:                 for (my $i=1; $i<@plain; $i++) {
14820:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14821:                 }
14822:             }
14823: 	}
14824:     }
14825:     close($config);
14826: }
14827: 
14828: # ---------------------------------------------------------- Read package table
14829: {
14830:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14831: 
14832:     while (my $configline=<$config>) {
14833: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14834: 	chomp($configline);
14835: 	my ($short,$plain)=split(/:/,$configline);
14836: 	my ($pack,$name)=split(/\&/,$short);
14837: 	if ($plain ne '') {
14838: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14839: 	    $packagetab{$short}=$plain; 
14840: 	}
14841:     }
14842:     close($config);
14843: }
14844: 
14845: # --------------------------------------------------------- Read loncaparev table
14846: 
14847: &load_loncaparevs();
14848: 
14849: # ------------------------------------------------------- Read serverhostID table
14850: 
14851: &load_serverhomeIDs();
14852: 
14853: # ---------------------------------------------------------- Read releaseslist XML
14854: {
14855:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14856:     if (-e $file) {
14857:         my $parser = HTML::LCParser->new($file);
14858:         while (my $token = $parser->get_token()) {
14859:             if ($token->[0] eq 'S') {
14860:                 my $item = $token->[1];
14861:                 my $name = $token->[2]{'name'};
14862:                 my $value = $token->[2]{'value'};
14863:                 if ($item ne '' && $name ne '' && $value ne '') {
14864:                     my $release = $parser->get_text();
14865:                     $release =~ s/(^\s*|\s*$ )//gx;
14866:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
14867:                 }
14868:             }
14869:         }
14870:     }
14871: }
14872: 
14873: # ---------------------------------------------------------- Read managers table
14874: {
14875:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14876:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14877:             while (my $configline=<$config>) {
14878:                 chomp($configline);
14879:                 next if ($configline =~ /^\#/);
14880:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14881:                     $managerstab{$configline} = 1;
14882:                 }
14883:             }
14884:             close($config);
14885:         }
14886:     }
14887: }
14888: 
14889: # ------------- set up temporary directory
14890: {
14891:     $tmpdir = LONCAPA::tempdir();
14892: 
14893: }
14894: 
14895: # ------------- set default texengine (domain default overrides this)
14896: {
14897:     $deftex = LONCAPA::texengine();
14898: }
14899: 
14900: # ------------- set default minimum length for passwords for internal auth users
14901: {
14902:     $passwdmin = LONCAPA::passwd_min();
14903: }
14904: 
14905: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
14906: 				'compress_threshold'=> 20_000,
14907:  			        });
14908: 
14909: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14910: $dumpcount=0;
14911: $locknum=0;
14912: 
14913: &logtouch();
14914: &logthis('<font color="yellow">INFO: Read configuration</font>');
14915: $readit=1;
14916:     {
14917: 	use integer;
14918: 	my $test=(2**32)+1;
14919: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14920: 	&logthis(" Detected 64bit platform ($_64bit)");
14921:     }
14922: }
14923: }
14924: 
14925: 1;
14926: __END__
14927: 
14928: =pod
14929: 
14930: =head1 NAME
14931: 
14932: Apache::lonnet - Subroutines to ask questions about things in the network.
14933: 
14934: =head1 SYNOPSIS
14935: 
14936: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14937: 
14938:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14939: 
14940: Common parameters:
14941: 
14942: =over 4
14943: 
14944: =item *
14945: 
14946: $uname : an internal username (if $cname expecting a course Id specifically)
14947: 
14948: =item *
14949: 
14950: $udom : a domain (if $cdom expecting a course's domain specifically)
14951: 
14952: =item *
14953: 
14954: $symb : a resource instance identifier
14955: 
14956: =item *
14957: 
14958: $namespace : the name of a .db file that contains the data needed or
14959: being set.
14960: 
14961: =back
14962: 
14963: =head1 OVERVIEW
14964: 
14965: lonnet provides subroutines which interact with the
14966: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14967: about classes, users, and resources.
14968: 
14969: For many of these objects you can also use this to store data about
14970: them or modify them in various ways.
14971: 
14972: =head2 Symbs
14973: 
14974: To identify a specific instance of a resource, LON-CAPA uses symbols
14975: or "symbs"X<symb>. These identifiers are built from the URL of the
14976: map, the resource number of the resource in the map, and the URL of
14977: the resource itself. The latter is somewhat redundant, but might help
14978: if maps change.
14979: 
14980: An example is
14981: 
14982:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14983: 
14984: The respective map entry is
14985: 
14986:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14987:   title="Problem 2">
14988:  </resource>
14989: 
14990: Symbs are used by the random number generator, as well as to store and
14991: restore data specific to a certain instance of for example a problem.
14992: 
14993: =head2 Storing And Retrieving Data
14994: 
14995: X<store()>X<cstore()>X<restore()>Three of the most important functions
14996: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14997: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14998: is is the non-critical message twin of cstore. These functions are for
14999: handlers to store a perl hash to a user's permanent data space in an
15000: easy manner, and to retrieve it again on another call. It is expected
15001: that a handler would use this once at the beginning to retrieve data,
15002: and then again once at the end to send only the new data back.
15003: 
15004: The data is stored in the user's data directory on the user's
15005: homeserver under the ID of the course.
15006: 
15007: The hash that is returned by restore will have all of the previous
15008: value for all of the elements of the hash.
15009: 
15010: Example:
15011: 
15012:  #creating a hash
15013:  my %hash;
15014:  $hash{'foo'}='bar';
15015: 
15016:  #storing it
15017:  &Apache::lonnet::cstore(\%hash);
15018: 
15019:  #changing a value
15020:  $hash{'foo'}='notbar';
15021: 
15022:  #adding a new value
15023:  $hash{'bar'}='foo';
15024:  &Apache::lonnet::cstore(\%hash);
15025: 
15026:  #retrieving the hash
15027:  my %history=&Apache::lonnet::restore();
15028: 
15029:  #print the hash
15030:  foreach my $key (sort(keys(%history))) {
15031:    print("\%history{$key} = $history{$key}");
15032:  }
15033: 
15034: Will print out:
15035: 
15036:  %history{1:foo} = bar
15037:  %history{1:keys} = foo:timestamp
15038:  %history{1:timestamp} = 990455579
15039:  %history{2:bar} = foo
15040:  %history{2:foo} = notbar
15041:  %history{2:keys} = foo:bar:timestamp
15042:  %history{2:timestamp} = 990455580
15043:  %history{bar} = foo
15044:  %history{foo} = notbar
15045:  %history{timestamp} = 990455580
15046:  %history{version} = 2
15047: 
15048: Note that the special hash entries C<keys>, C<version> and
15049: C<timestamp> were added to the hash. C<version> will be equal to the
15050: total number of versions of the data that have been stored. The
15051: C<timestamp> attribute will be the UNIX time the hash was
15052: stored. C<keys> is available in every historical section to list which
15053: keys were added or changed at a specific historical revision of a
15054: hash.
15055: 
15056: B<Warning>: do not store the hash that restore returns directly. This
15057: will cause a mess since it will restore the historical keys as if the
15058: were new keys. I.E. 1:foo will become 1:1:foo etc.
15059: 
15060: Calling convention:
15061: 
15062:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
15063:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
15064: 
15065: For more detailed information, see lonnet specific documentation.
15066: 
15067: =head1 RETURN MESSAGES
15068: 
15069: =over 4
15070: 
15071: =item * B<con_lost>: unable to contact remote host
15072: 
15073: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15074: when the connection is brought back up
15075: 
15076: =item * B<con_failed>: unable to contact remote host and unable to save message
15077: for later delivery
15078: 
15079: =item * B<error:>: an error a occurred, a description of the error follows the :
15080: 
15081: =item * B<no_such_host>: unable to fund a host associated with the user/domain
15082: that was requested
15083: 
15084: =back
15085: 
15086: =head1 PUBLIC SUBROUTINES
15087: 
15088: =head2 Session Environment Functions
15089: 
15090: =over 4
15091: 
15092: =item * 
15093: X<appenv()>
15094: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
15095: the user envirnoment file, and will be restored for each access this
15096: user makes during this session, also modifies the %env for the current
15097: process. Optional rolesarrayref - if defined contains a reference to an array
15098: of roles which are exempt from the restriction on modifying user.role entries 
15099: in the user's environment.db and in %env.    
15100: 
15101: =item *
15102: X<delenv()>
15103: B<delenv($delthis,$regexp)>: removes all items from the session
15104: environment file that begin with $delthis. If the 
15105: optional second arg - $regexp - is true, $delthis is treated as a 
15106: regular expression, otherwise \Q$delthis\E is used. 
15107: The values are also deleted from the current processes %env.
15108: 
15109: =item * get_env_multiple($name) 
15110: 
15111: gets $name from the %env hash, it seemlessly handles the cases where multiple
15112: values may be defined and end up as an array ref.
15113: 
15114: returns an array of values
15115: 
15116: =back
15117: 
15118: =head2 User Information
15119: 
15120: =over 4
15121: 
15122: =item *
15123: X<queryauthenticate()>
15124: B<queryauthenticate($uname,$udom)>: try to determine user's current 
15125: authentication scheme
15126: 
15127: =item *
15128: X<authenticate()>
15129: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
15130: authenticate user from domain's lib servers (first use the current
15131: one). C<$upass> should be the users password.
15132: $checkdefauth is optional (value is 1 if a check should be made to
15133:    authenticate user using default authentication method, and allow
15134:    account creation if username does not have account in the domain).
15135: $clientcancheckhost is optional (value is 1 if checking whether the
15136:    server can host will occur on the client side in lonauth.pm).   
15137: 
15138: =item *
15139: X<homeserver()>
15140: B<homeserver($uname,$udom)>: find the server which has
15141: the user's directory and files (there must be only one), this caches
15142: the answer, and also caches if there is a borken connection.
15143: 
15144: =item *
15145: X<idget()>
15146: B<idget($udom,@ids)>: find the usernames behind a list of IDs
15147: (IDs are a unique resource in a domain, there must be only 1 ID per
15148: username, and only 1 username per ID in a specific domain) (returns
15149: hash: id=>name,id=>name)
15150: 
15151: =item *
15152: X<idrget()>
15153: B<idrget($udom,@unames)>: find the IDs behind a list of
15154: usernames (returns hash: name=>id,name=>id)
15155: 
15156: =item *
15157: X<idput()>
15158: B<idput($udom,%ids)>: store away a list of names and associated IDs
15159: 
15160: =item *
15161: X<rolesinit()>
15162: B<rolesinit($udom,$username)>: get user privileges.
15163: returns user role, first access and timer interval hashes
15164: 
15165: =item *
15166: X<privileged()>
15167: B<privileged($username,$domain)>: returns a true if user has a
15168: privileged and active role (i.e. su or dc), false otherwise.
15169: 
15170: =item *
15171: X<getsection()>
15172: B<getsection($udom,$uname,$cname)>: finds the section of student in the
15173: course $cname, return section name/number or '' for "not in course"
15174: and '-1' for "no section"
15175: 
15176: =item *
15177: X<userenvironment()>
15178: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
15179: passed in @what from the requested user's environment, returns a hash
15180: 
15181: =item * 
15182: X<userlog_query()>
15183: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15184: activity.log file. %filters defines filters applied when parsing the
15185: log file. These can be start or end timestamps, or the type of action
15186: - log to look for Login or Logout events, check for Checkin or
15187: Checkout, role for role selection. The response is in the form
15188: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
15189: escaped strings of the action recorded in the activity.log file.
15190: 
15191: =back
15192: 
15193: =head2 User Roles
15194: 
15195: =over 4
15196: 
15197: =item *
15198: 
15199: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
15200: returns codes for allowed actions.
15201: 
15202: The first argument is required, all others are optional.
15203: 
15204: $priv is the privilege being checked.
15205: $uri contains additional information about what is being checked for access (e.g.,
15206: URL, course ID etc.).
15207: $symb is the unique resource instance identifier in a course; if needed,
15208: but not provided, it will be retrieved via a call to &symbread().
15209: $role is the role for which a priv is being checked (only used if priv is evb).
15210: $clientip is the user's IP address (only used when checking for access to portfolio
15211: files).
15212: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
15213: prevents recursive calls to &allowed.
15214: 
15215:  F: full access
15216:  U,I,K: authentication modes (cxx only)
15217:  '': forbidden
15218:  1: user needs to choose course
15219:  2: browse allowed
15220:  A: passphrase authentication needed
15221:  B: access temporarily blocked because of a blocking event in a course.
15222:  D: access blocked because access is required via session initiated via deep-link
15223: 
15224: =item *
15225: 
15226: constructaccess($url,$setpriv) : check for access to construction space URL
15227: 
15228: See if the owner domain and name in the URL match those in the
15229: expected environment.  If so, return three element list
15230: ($ownername,$ownerdomain,$ownerhome).
15231: 
15232: Otherwise return the null string.
15233: 
15234: If second argument 'setpriv' is true, it assigns the privileges,
15235: and returns the same three element list, unless the owner has
15236: blocked "ad hoc" Domain Coordinator access to the Author Space,
15237: in which case the null string is returned.
15238: 
15239: =item *
15240: 
15241: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
15242: define a custom role rolename set privileges in format of lonTabs/roles.tab
15243: for system, domain, and course level. $uname and $udom are optional (current
15244: user's username and domain will be used when either of $uname or $udom are absent.
15245: 
15246: =item *
15247: 
15248: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
15249: (rolesplain.tab); plain text explanation of a user role term.
15250: $type is Course (default) or Community.
15251: If $forcedefault evaluates to true, text returned will be default 
15252: text for $type. Otherwise, if this is a course, the text returned 
15253: will be a custom name for the role (if defined in the course's 
15254: environment).  If no custom name is defined the default is returned.
15255:    
15256: =item *
15257: 
15258: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
15259: All arguments are optional. Returns a hash of a roles, either for
15260: co-author/assistant author roles for a user's Construction Space
15261: (default), or if $context is 'userroles', roles for the user himself,
15262: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15263: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15264: For each key, value is set to colon-separated start and end times for
15265: the role.  If no username and domain are specified, will default to
15266: current user/domain. Types, roles, and roledoms are references to arrays
15267: of role statuses (active, future or previous), roles 
15268: (e.g., cc,in, st etc.) and domains of the roles which can be used
15269: to restrict the list of roles reported. If no array ref is 
15270: provided for types, will default to return only active roles.
15271: 
15272: =item *
15273: 
15274: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
15275: user: $uname:$udom has a role in the course: $cdom_$cnum.
15276: 
15277: Additional optional arguments are: $type (if role checking is to be restricted
15278: to certain user status types -- previous (expired roles), active (currently
15279: available roles) or future (roles available in the future), and
15280: $hideprivileged -- if true will not report course roles for users who
15281: have active Domain Coordinator role in course's domain or in additional
15282: domains (specified in 'Domains to check for privileged users' in course
15283: environment -- set via:  Course Settings -> Classlists and staff listing).
15284: 
15285: =item *
15286: 
15287: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15288: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15289: $possdomains and $possroles are optional array refs -- to domains to check and
15290: roles to check.  If $possdomains is not specified, a dump will be done of the
15291: users' roles.db to check for a dc or su role in any domain. This can be
15292: time consuming if &privileged is called repeatedly (e.g., when displaying a
15293: classlist), so in such cases, supplying a $possdomains array is preferred, as
15294: this then allows &privileged_by_domain() to be used, which caches the identity
15295: of privileged users, eliminating the need for repeated calls to &dump().
15296: 
15297: =item *
15298: 
15299: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15300: where the outer hash keys are domains specified in the $possdomains array ref,
15301: next inner hash keys are privileged roles specified in the $roles array ref,
15302: and the innermost hash contains key = value pairs for username:domain = end:start
15303: for active or future "privileged" users with that role in that domain. To avoid
15304: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15305: innerhash are cached using priv_$role and $dom as the identifiers.
15306: 
15307: =back
15308: 
15309: =head2 User Modification
15310: 
15311: =over 4
15312: 
15313: =item *
15314: 
15315: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
15316: user for the level given by URL.  Optional start and end dates (leave empty
15317: string or zero for "no date")
15318: 
15319: =item *
15320: 
15321: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15322: change a users, password, possible return values are: ok,
15323: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15324: refused
15325: 
15326: =item *
15327: 
15328: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
15329: 
15330: =item *
15331: 
15332: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15333:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
15334: 
15335: will update user information (firstname,middlename,lastname,generation,
15336: permanentemail), and if forceid is true, student/employee ID also.
15337: A user's institutional affiliation(s) can also be updated.
15338: User information fields will not be overwritten with empty entries 
15339: unless the field is included in the $candelete array reference.
15340: This array is included when a single user is modified via "Manage Users",
15341: or when Autoupdate.pl is run by cron in a domain.
15342: 
15343: =item *
15344: 
15345: modifystudent
15346: 
15347: modify a student's enrollment and identification information.
15348: The course id is resolved based on the current user's environment.  
15349: This means the invoking user must be a course coordinator or otherwise
15350: associated with a course.
15351: 
15352: This call is essentially a wrapper for lonnet::modifyuser and
15353: lonnet::modify_student_enrollment
15354: 
15355: Inputs: 
15356: 
15357: =over 4
15358: 
15359: =item B<$udom> Student's loncapa domain
15360: 
15361: =item B<$uname> Student's loncapa login name
15362: 
15363: =item B<$uid> Student/Employee ID
15364: 
15365: =item B<$umode> Student's authentication mode
15366: 
15367: =item B<$upass> Student's password
15368: 
15369: =item B<$first> Student's first name
15370: 
15371: =item B<$middle> Student's middle name
15372: 
15373: =item B<$last> Student's last name
15374: 
15375: =item B<$gene> Student's generation
15376: 
15377: =item B<$usec> Student's section in course
15378: 
15379: =item B<$end> Unix time of the roles expiration
15380: 
15381: =item B<$start> Unix time of the roles start date
15382: 
15383: =item B<$forceid> If defined, allow $uid to be changed
15384: 
15385: =item B<$desiredhome> server to use as home server for student
15386: 
15387: =item B<$email> Student's permanent e-mail address
15388: 
15389: =item B<$type> Type of enrollment (auto or manual)
15390: 
15391: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
15392: 
15393: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
15394: 
15395: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
15396: 
15397: =item B<$context> role change context (shown in User Management Logs display in a course)
15398: 
15399: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15400: 
15401: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
15402: 
15403: =back
15404: 
15405: =item *
15406: 
15407: modify_student_enrollment
15408: 
15409: Change a student's enrollment status in a class.  The environment variable
15410: 'role.request.course' must be defined for this function to proceed.
15411: 
15412: Inputs:
15413: 
15414: =over 4
15415: 
15416: =item $udom, student's domain
15417: 
15418: =item $uname, student's name
15419: 
15420: =item $uid, student's user id
15421: 
15422: =item $first, student's first name
15423: 
15424: =item $middle
15425: 
15426: =item $last
15427: 
15428: =item $gene
15429: 
15430: =item $usec
15431: 
15432: =item $end
15433: 
15434: =item $start
15435: 
15436: =item $type
15437: 
15438: =item $locktype
15439: 
15440: =item $cid
15441: 
15442: =item $selfenroll
15443: 
15444: =item $context
15445: 
15446: =item $credits, number of credits student will earn from this class
15447: 
15448: =item $instsec, institutional course section code for student
15449: 
15450: =back
15451: 
15452: 
15453: =item *
15454: 
15455: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15456: custom role; give a custom role to a user for the level given by URL.  Specify
15457: name and domain of role author, and role name
15458: 
15459: =item *
15460: 
15461: revokerole($udom,$uname,$url,$role) : revoke a role for url
15462: 
15463: =item *
15464: 
15465: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15466: 
15467: =back
15468: 
15469: =head2 Course Infomation
15470: 
15471: =over 4
15472: 
15473: =item *
15474: 
15475: coursedescription($courseid,$options) : returns a hash of information about the
15476: specified course id, including all environment settings for the
15477: course, the description of the course will be in the hash under the
15478: key 'description'
15479: 
15480: $options is an optional parameter that if supplied is a hash reference that controls
15481: what how this function works.  It has the following key/values:
15482: 
15483: =over 4
15484: 
15485: =item freshen_cache
15486: 
15487: If defined, and the environment cache for the course is valid, it is 
15488: returned in the returned hash.
15489: 
15490: =item one_time
15491: 
15492: If defined, the last cache time is set to _now_
15493: 
15494: =item user
15495: 
15496: If defined, the supplied username is used instead of the current user.
15497: 
15498: 
15499: =back
15500: 
15501: =item *
15502: 
15503: resdata($name,$domain,$type,@which) : request for current parameter
15504: setting for a specific $type, where $type is either 'course' or 'user',
15505: @what should be a list of parameters to ask about. This routine caches
15506: answers for 10 minutes.
15507: 
15508: =item *
15509: 
15510: get_courseresdata($courseid, $domain) : dump the entire course resource
15511: data base, returning a hash that is keyed by the resource name and has
15512: values that are the resource value.  I believe that the timestamps and
15513: versions are also returned.
15514: 
15515: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15516: supplemental content area. This routine caches the number of files for
15517: 10 minutes.
15518: 
15519: =back
15520: 
15521: =head2 Course Modification
15522: 
15523: =over 4
15524: 
15525: =item *
15526: 
15527: writecoursepref($courseid,%prefs) : write preferences (environment
15528: database) for a course
15529: 
15530: =item *
15531: 
15532: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15533: 
15534: =item *
15535: 
15536: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
15537: 
15538: =item *
15539: 
15540: is_course($courseid), is_course($cdom, $cnum)
15541: 
15542: Accepts either a combined $courseid (in the form of domain_courseid) or the
15543: two component version $cdom, $cnum. It checks if the specified course exists.
15544: 
15545: Returns:
15546:     undef if the course doesn't exist, otherwise
15547:     in scalar context the combined courseid.
15548:     in list context the two components of the course identifier, domain and 
15549:     courseid.    
15550: 
15551: =back
15552: 
15553: =head2 Bubblesheet Configuration
15554: 
15555: =over 4
15556: 
15557: =item *
15558: 
15559: get_scantron_config($which)
15560: 
15561: $which - the name of the configuration to parse from the file.
15562: 
15563: Parses and returns the bubblesheet configuration line selected as a
15564: hash of configuration file fields.
15565: 
15566: 
15567: Returns:
15568:     If the named configuration is not in the file, an empty
15569:     hash is returned.
15570: 
15571:     a hash with the fields
15572:       name         - internal name for the this configuration setup
15573:       description  - text to display to operator that describes this config
15574:       CODElocation - if 0 or the string 'none'
15575:                           - no CODE exists for this config
15576:                      if -1 || the string 'letter'
15577:                           - a CODE exists for this config and is
15578:                             a string of letters
15579:                      Unsupported value (but planned for future support)
15580:                           if a positive integer
15581:                                - The CODE exists as the first n items from
15582:                                  the question section of the form
15583:                           if the string 'number'
15584:                                - The CODE exists for this config and is
15585:                                  a string of numbers
15586:       CODEstart   - (only matter if a CODE exists) column in the line where
15587:                      the CODE starts
15588:       CODElength  - length of the CODE
15589:       IDstart     - column where the student/employee ID starts
15590:       IDlength    - length of the student/employee ID info
15591:       Qstart      - column where the information from the bubbled
15592:                     'questions' start
15593:       Qlength     - number of columns comprising a single bubble line from
15594:                     the sheet. (usually either 1 or 10)
15595:       Qon         - either a single character representing the character used
15596:                     to signal a bubble was chosen in the positional setup, or
15597:                     the string 'letter' if the letter of the chosen bubble is
15598:                     in the final, or 'number' if a number representing the
15599:                     chosen bubble is in the file (1->A 0->J)
15600:       Qoff        - the character used to represent that a bubble was
15601:                     left blank
15602:       PaperID     - if the scanning process generates a unique number for each
15603:                     sheet scanned the column that this ID number starts in
15604:       PaperIDlength - number of columns that comprise the unique ID number
15605:                       for the sheet of paper
15606:       FirstName   - column that the first name starts in
15607:       FirstNameLength - number of columns that the first name spans
15608:       LastName    - column that the last name starts in
15609:       LastNameLength - number of columns that the last name spans
15610:       BubblesPerRow - number of bubbles available in each row used to
15611:                       bubble an answer. (If not specified, 10 assumed).
15612: 
15613: 
15614: =item *
15615: 
15616: get_scantronformat_file($cdom)
15617: 
15618: $cdom - the course's domain (optional); if not supplied, uses
15619: domain for current $env{'request.course.id'}.
15620: 
15621: Returns an array containing lines from the scantron format file for
15622: the domain of the course.
15623: 
15624: If a url for a custom.tab file is listed in domain's configuration.db,
15625: lines are from this file.
15626: 
15627: Otherwise, if a default.tab has been published in RES space by the
15628: domainconfig user, lines are from this file.
15629: 
15630: Otherwise, fall back to getting lines from the legacy file on the
15631: local server:  /home/httpd/lonTabs/default_scantronformat.tab
15632: 
15633: =back
15634: 
15635: =head2 Resource Subroutines
15636: 
15637: =over 4
15638: 
15639: =item *
15640: 
15641: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
15642: 
15643: =item *
15644: 
15645: repcopy($filename) : subscribes to the requested file, and attempts to
15646: replicate from the owning library server, Might return
15647: 'unavailable', 'not_found', 'forbidden', 'ok', or
15648: 'bad_request', also attempts to grab the metadata for the
15649: resource. Expects the local filesystem pathname
15650: (/home/httpd/html/res/....)
15651: 
15652: =back
15653: 
15654: =head2 Resource Information
15655: 
15656: =over 4
15657: 
15658: =item *
15659: 
15660: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
15661: and returns the value of a variety of different possible values,
15662: $varname should be a request string, and the other parameters can be
15663: used to specify who and what one is asking about. Ordinarily, $cid 
15664: does not need to be specified, as it is retrived from 
15665: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15666: within lonuserstate::loadmap() when initializing a course, before
15667: $env{'request.course.id'} has been set, so it needs to be provided
15668: in that one case.
15669: 
15670: Possible values for $varname are environment.lastname (or other item
15671: from the envirnment hash), user.name (or someother aspect about the
15672: user), resource.0.maxtries (or some other part and parameter of a
15673: resource)
15674: 
15675: =item *
15676: 
15677: directcondval($number) : get current value of a condition; reads from a state
15678: string
15679: 
15680: =item *
15681: 
15682: condval($condidx) : value of condition index based on state
15683: 
15684: =item *
15685: 
15686: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
15687: resource's metadata, $what should be either a specific key, or either
15688: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15689: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
15690: 
15691: this function automatically caches all requests
15692: 
15693: =item *
15694: 
15695: metadata_query($query,$custom,$customshow) : make a metadata query against the
15696: network of library servers; returns file handle of where SQL and regex results
15697: will be stored for query
15698: 
15699: =item *
15700: 
15701: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
15702: return symbolic list entry (all arguments optional).
15703: 
15704: Args: filename is the filename (including path) for the file for which a symb
15705: is required; donotrecurse, if true will prevent calls to allowed() being made
15706: to check access status if more than one resource was found in the bighash
15707: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
15708: a randompick); ignorecachednull, if true will prevent a symb of '' being
15709: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15710: cause possible symbs to be checked to determine if they are subject to content
15711: blocking, if so they will not be included as possible symbs; possibles is a
15712: ref to a hash, which, as a side effect, will be populated with all possible
15713: symbs (content blocking not tested).
15714: 
15715: returns the data handle
15716: 
15717: =item *
15718: 
15719: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15720: and is a possible symb for the URL in $thisfn, and if is an encrypted
15721: resource that the user accessed using /enc/ returns a 1 on success, 0
15722: on failure, user must be in a course, as it assumes the existence of
15723: the course initial hash, and uses $env('request.course.id'}.  The third
15724: arg is an optional reference to a scalar.  If this arg is passed in the
15725: call to symbverify, it will be set to 1 if the symb has been set to be 
15726: encrypted; otherwise it will be null.
15727: 
15728: =item *
15729: 
15730: symbclean($symb) : removes versions numbers from a symb, returns the
15731: cleaned symb
15732: 
15733: =item *
15734: 
15735: is_on_map($uri) : checks if the $uri is somewhere on the current
15736: course map, user must be in a course for it to work.
15737: 
15738: =item *
15739: 
15740: numval($salt) : return random seed value (addend for rndseed)
15741: 
15742: =item *
15743: 
15744: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15745: a random seed, all arguments are optional, if they aren't sent it uses the
15746: environment to derive them. Note: if symb isn't sent and it can't get one
15747: from &symbread it will use the current time as its return value
15748: 
15749: =item *
15750: 
15751: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15752: unfakeable, receipt
15753: 
15754: =item *
15755: 
15756: receipt() : API to ireceipt working off of env values; given out to users
15757: 
15758: =item *
15759: 
15760: countacc($url) : count the number of accesses to a given URL
15761: 
15762: =item *
15763: 
15764: checkout($symb,$tuname,$tudom,$tcrsid) :  creates a record of a user having looked at an item, most likely printed out or otherwise using a resource
15765: 
15766: =item *
15767: 
15768: checkin($token) : updates that a resource has beeen returned (a hard copy version for instance) and returns the data that $token was Checkout with ($symb, $tuname, $tudom, and $tcrsid)
15769: 
15770: =item *
15771: 
15772: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15773: 
15774: =item *
15775: 
15776: devalidate($symb) : devalidate temporary spreadsheet calculations,
15777: forcing spreadsheet to reevaluate the resource scores next time.
15778: 
15779: =item *
15780: 
15781: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15782: when viewing in course context.
15783: 
15784:  input: six args -- filename (decluttered), course number, course domain,
15785:                     url, symb (if registered) and group (if this is a
15786:                     group item -- e.g., bulletin board, group page etc.).
15787: 
15788:  output: array of five scalars --
15789:          $cfile -- url for file editing if editable on current server
15790:          $home -- homeserver of resource (i.e., for author if published,
15791:                                           or course if uploaded.).
15792:          $switchserver --  1 if server switch will be needed.
15793:          $forceedit -- 1 if icon/link should be to go to edit mode
15794:          $forceview -- 1 if icon/link should be to go to view mode
15795: 
15796: =item *
15797: 
15798: is_course_upload($file,$cnum,$cdom)
15799: 
15800: Used in course context to determine if current file was uploaded to
15801: the course (i.e., would be found in /userfiles/docs on the course's
15802: homeserver.
15803: 
15804:   input: 3 args -- filename (decluttered), course number and course domain.
15805:   output: boolean -- 1 if file was uploaded.
15806: 
15807: =back
15808: 
15809: =head2 Storing/Retreiving Data
15810: 
15811: =over 4
15812: 
15813: =item *
15814: 
15815: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
15816: permanently for this url; hashref needs to be given and should be a \%hashname;
15817: the remaining args aren't required and if they aren't passed or are '' they will
15818: be derived from the env (with the exception of $laststore, which is an
15819: optional arg used when a user's submission is stored in grading).
15820: $laststore is $version=$timestamp, where $version is the most recent version
15821: number retrieved for the corresponding $symb in the $namespace db file, and
15822: $timestamp is the timestamp for that transaction (UNIX time).
15823: $laststore is currently only passed when cstore() is called by
15824: structuretags::finalize_storage().
15825: 
15826: =item *
15827: 
15828: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
15829: but uses critical subroutine
15830: 
15831: =item *
15832: 
15833: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15834: all args are optional
15835: 
15836: =item *
15837: 
15838: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
15839: dumps the complete (or key matching regexp) namespace into a hash
15840: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15841: normally &store()ed into
15842: 
15843: $range should be either an integer '100' (give me the first 100
15844:                                            matching records)
15845:               or be  two integers sperated by a - with no spaces
15846:                  '30-50' (give me the 30th through the 50th matching
15847:                           records)
15848: 
15849: 
15850: =item *
15851: 
15852: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15853: replaces a &store() version of data with a replacement set of data
15854: for a particular resource in a namespace passed in the $storehash hash 
15855: reference. If $tolog is true, the transaction is logged in the courselog
15856: with an action=PUTSTORE.
15857: 
15858: =item *
15859: 
15860: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15861: works very similar to store/cstore, but all data is stored in a
15862: temporary location and can be reset using tmpreset, $storehash should
15863: be a hash reference, returns nothing on success
15864: 
15865: =item *
15866: 
15867: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15868: similar to restore, but all data is stored in a temporary location and
15869: can be reset using tmpreset. Returns a hash of values on success,
15870: error string otherwise.
15871: 
15872: =item *
15873: 
15874: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15875: deltes all keys for $symb form the temporary storage hash.
15876: 
15877: =item *
15878: 
15879: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15880: reference filled in from namesp ($udom and $uname are optional)
15881: 
15882: =item *
15883: 
15884: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15885: namesp ($udom and $uname are optional)
15886: 
15887: =item *
15888: 
15889: dump($namespace,$udom,$uname,$regexp,$range) : 
15890: dumps the complete (or key matching regexp) namespace into a hash
15891: ($udom, $uname, $regexp, $range are optional)
15892: 
15893: $range should be either an integer '100' (give me the first 100
15894:                                            matching records)
15895:               or be  two integers sperated by a - with no spaces
15896:                  '30-50' (give me the 30th through the 50th matching
15897:                           records)
15898: =item *
15899: 
15900: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15901: $store can be a scalar, an array reference, or if the amount to be 
15902: incremented is > 1, a hash reference.
15903: 
15904: ($udom and $uname are optional)
15905: 
15906: =item *
15907: 
15908: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15909: ($udom and $uname are optional)
15910: 
15911: =item *
15912: 
15913: cput($namespace,$storehash,$udom,$uname) : critical put
15914: ($udom and $uname are optional)
15915: 
15916: =item *
15917: 
15918: newput($namespace,$storehash,$udom,$uname) :
15919: 
15920: Attempts to store the items in the $storehash, but only if they don't
15921: currently exist, if this succeeds you can be certain that you have 
15922: successfully created a new key value pair in the $namespace db.
15923: 
15924: 
15925: Args:
15926:  $namespace: name of database to store values to
15927:  $storehash: hashref to store to the db
15928:  $udom: (optional) domain of user containing the db
15929:  $uname: (optional) name of user caontaining the db
15930: 
15931: Returns:
15932:  'ok' -> succeeded in storing all keys of $storehash
15933:  'key_exists: <key>' -> failed to anything out of $storehash, as at
15934:                         least <key> already existed in the db (other
15935:                         requested keys may also already exist)
15936:  'error: <msg>' -> unable to tie the DB or other error occurred
15937:  'con_lost' -> unable to contact request server
15938:  'refused' -> action was not allowed by remote machine
15939: 
15940: 
15941: =item *
15942: 
15943: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15944: reference filled in from namesp (encrypts the return communication)
15945: ($udom and $uname are optional)
15946: 
15947: =item *
15948: 
15949: log($udom,$name,$home,$message) : write to permanent log for user; use
15950: critical subroutine
15951: 
15952: =item *
15953: 
15954: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15955: array reference filled in from namespace found in domain level on either
15956: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15957: 
15958: =item *
15959: 
15960: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
15961: domain level either on specified domain server ($uhome) or primary domain 
15962: server ($udom and $uhome are optional)
15963: 
15964: =item * 
15965: 
15966: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
15967: for: authentication, language, quotas, timezone, date locale, and portal URL in
15968: the target domain.
15969: 
15970: May also include additional key => value pairs for the following groups:
15971: 
15972: =over
15973: 
15974: =item
15975: disk quotas (MB allocated by default to portfolios and authoring spaces).
15976: 
15977: =over
15978: 
15979: =item defaultquota, authorquota
15980: 
15981: =back
15982: 
15983: =item
15984: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15985: portfolio for users).
15986: 
15987: =over
15988: 
15989: =item
15990: aboutme, blog, webdav, portfolio
15991: 
15992: =back
15993: 
15994: =item
15995: requestcourses: ability to request courses, and how requests are processed.
15996: 
15997: =over
15998: 
15999: =item
16000: official, unofficial, community, textbook
16001: 
16002: =back
16003: 
16004: =item
16005: inststatus: types of institutional affiliation, and order in which they are displayed.
16006: 
16007: =over
16008: 
16009: =item
16010: inststatustypes, inststatusorder, inststatusguest
16011: 
16012: =back
16013: 
16014: =item
16015: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16016: for course's uploaded content.
16017: 
16018: =over
16019: 
16020: =item
16021: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
16022: communityquota, textbookquota
16023: 
16024: =back
16025: 
16026: =item
16027: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16028: on your servers.
16029: 
16030: =over
16031: 
16032: =item
16033: remotesessions, hostedsessions
16034: 
16035: =back
16036: 
16037: =back
16038: 
16039: In cases where a domain coordinator has never used the "Set Domain Configuration"
16040: utility to create a configuration.db file on a domain's primary library server
16041: only the following domain defaults: auth_def, auth_arg_def, lang_def
16042: -- corresponding values are authentication type (internal, krb4, krb5,
16043: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
16044: will be available. Values are retrieved from cache (if current), unless the
16045: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16046: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16047: 
16048: Typical usage:
16049: 
16050: %domdefaults = &get_domain_defaults($target_domain);
16051: 
16052: =back
16053: 
16054: =head2 Network Status Functions
16055: 
16056: =over 4
16057: 
16058: =item *
16059: 
16060: dirlist() : return directory list based on URI (first arg).
16061: 
16062: Inputs: 1 required, 5 optional.
16063: 
16064: =over
16065: 
16066: =item 
16067: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16068: 
16069: =item
16070: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
16071: 
16072: =item
16073: $username -  username of user/course to be listed. Extracted from $uri if absent. 
16074: 
16075: =item
16076: $getpropath - boolean: 1 if prepend path using &propath(). 
16077: 
16078: =item
16079: $getuserdir - boolean: 1 if prepend path for "userfiles".
16080: 
16081: =item 
16082: $alternateRoot - path to prepend in place of path from $uri.
16083: 
16084: =back
16085: 
16086: Returns: Array of up to two items.
16087: 
16088: =over
16089: 
16090: a reference to an array of files/subdirectories
16091: 
16092: =over
16093: 
16094: Each element in the array of files/subdirectories is a & separated list of
16095: item name and the result of running stat on the item.  If dirlist was requested
16096: for a file instead of a directory, the item name will be ''. For a directory 
16097: listing, if the item is a metadata file, the element will end &N&M 
16098: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16099: default copyright set (1).  
16100: 
16101: =back
16102: 
16103: a scalar containing error condition (if encountered).
16104: 
16105: =over
16106: 
16107: =item 
16108: no_host (no homeserver identified for $username:$domain).
16109: 
16110: =item 
16111: no_such_host (server contacted for listing not identified as valid host).
16112: 
16113: =item 
16114: con_lost (connection to remote server failed).
16115: 
16116: =item 
16117: refused (invalid $username:$domain received on lond side).
16118: 
16119: =item 
16120: no_such_dir (directory at specified path on lond side does not exist). 
16121: 
16122: =item 
16123: empty (directory at specified path on lond side is empty).
16124: 
16125: =over
16126: 
16127: This is currently not encountered because the &ls3, &ls2, 
16128: &ls (_handler) routines on the lond side do not filter out
16129: . and .. from a directory listing. 
16130: 
16131: =back
16132: 
16133: =back
16134: 
16135: =back
16136: 
16137: =item *
16138: 
16139: spareserver() : find server with least workload from spare.tab
16140: 
16141: 
16142: =item *
16143: 
16144: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16145: if there is no corresponding loncapa host.
16146: 
16147: =back
16148: 
16149: 
16150: =head2 Apache Request
16151: 
16152: =over 4
16153: 
16154: =item *
16155: 
16156: ssi($url,%hash) : server side include, does a complete request cycle on url to
16157: localhost, posts hash
16158: 
16159: =back
16160: 
16161: =head2 Data to String to Data
16162: 
16163: =over 4
16164: 
16165: =item *
16166: 
16167: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16168: and '&' separators, supports elements that are arrayrefs and hashrefs
16169: 
16170: =item *
16171: 
16172: hashref2str($hashref) : convert a hashref into a string complete with
16173: escaping and '=' and '&' separators, supports elements that are
16174: arrayrefs and hashrefs
16175: 
16176: =item *
16177: 
16178: arrayref2str($arrayref) : convert an arrayref into a string complete
16179: with escaping and '&' separators, supports elements that are arrayrefs
16180: and hashrefs
16181: 
16182: =item *
16183: 
16184: str2hash($string) : convert string to hash using unescaping and
16185: splitting on '=' and '&', supports elements that are arrayrefs and
16186: hashrefs
16187: 
16188: =item *
16189: 
16190: str2array($string) : convert string to hash using unescaping and
16191: splitting on '&', supports elements that are arrayrefs and hashrefs
16192: 
16193: =back
16194: 
16195: =head2 Logging Routines
16196: 
16197: 
16198: These routines allow one to make log messages in the lonnet.log and
16199: lonnet.perm logfiles.
16200: 
16201: =over 4
16202: 
16203: =item *
16204: 
16205: logtouch() : make sure the logfile, lonnet.log, exists
16206: 
16207: =item *
16208: 
16209: logthis() : append message to the normal lonnet.log file, it gets
16210: preiodically rolled over and deleted.
16211: 
16212: =item *
16213: 
16214: logperm() : append a permanent message to lonnet.perm.log, this log
16215: file never gets deleted by any automated portion of the system, only
16216: messages of critical importance should go in here.
16217: 
16218: 
16219: =back
16220: 
16221: =head2 General File Helper Routines
16222: 
16223: =over 4
16224: 
16225: =item *
16226: 
16227: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
16228: (a) files in /uploaded
16229:   (i) If a local copy of the file exists - 
16230:       compares modification date of local copy with last-modified date for 
16231:       definitive version stored on home server for course. If local copy is 
16232:       stale, requests a new version from the home server and stores it. 
16233:       If the original has been removed from the home server, then local copy 
16234:       is unlinked.
16235:   (ii) If local copy does not exist -
16236:       requests the file from the home server and stores it. 
16237:   
16238:   If $caller is 'uploadrep':  
16239:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16240:     for request for files originally uploaded via DOCS. 
16241:      - returns 'ok' if fresh local copy now available, -1 otherwise.
16242:   
16243:   Otherwise:
16244:      This indicates a call from the content generation phase of the request.
16245:      -  returns the entire contents of the file or -1.
16246:      
16247: (b) files in /res
16248:    - returns the entire contents of a file or -1; 
16249:    it properly subscribes to and replicates the file if neccessary.
16250: 
16251: 
16252: =item *
16253: 
16254: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16255:                   reference
16256: 
16257: returns either a stat() list of data about the file or an empty list
16258: if the file doesn't exist or couldn't find out about it (connection
16259: problems or user unknown)
16260: 
16261: =item *
16262: 
16263: filelocation($dir,$file) : returns file system location of a file
16264: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16265: directory that relative $file lookups are to looked in ($dir of /a/dir
16266: and a file of ../bob will become /a/bob)
16267: 
16268: =item *
16269: 
16270: hreflocation($dir,$file) : returns file system location or a URL; same as
16271: filelocation except for hrefs
16272: 
16273: =item *
16274: 
16275: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16276: also removes beginning /home/httpd/html unless /priv/ follows it.
16277: 
16278: =back
16279: 
16280: =head2 Usererfile file routines (/uploaded*)
16281: 
16282: =over 4
16283: 
16284: =item *
16285: 
16286: userfileupload(): main rotine for putting a file in a user or course's
16287:                   filespace, arguments are,
16288: 
16289:  formname - required - this is the name of the element in $env where the
16290:            filename, and the contents of the file to create/modifed exist
16291:            the filename is in $env{'form.'.$formname.'.filename'} and the
16292:            contents of the file is located in $env{'form.'.$formname}
16293:  context - if coursedoc, store the file in the course of the active role
16294:              of the current user; 
16295:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16296:            if 'canceloverwrite': delete file in tmp/overwrites directory
16297:  subdir - required - subdirectory to put the file in under ../userfiles/
16298:          if undefined, it will be placed in "unknown"
16299: 
16300:  (This routine calls clean_filename() to remove any dangerous
16301:  characters from the filename, and then calls finuserfileupload() to
16302:  complete the transaction)
16303: 
16304:  returns either the url of the uploaded file (/uploaded/....) if successful
16305:  and /adm/notfound.html if unsuccessful
16306: 
16307: =item *
16308: 
16309: clean_filename(): routine for cleaing a filename up for storage in
16310:                  userfile space, argument is:
16311: 
16312:  filename - proposed filename
16313: 
16314: returns: the new clean filename
16315: 
16316: =item *
16317: 
16318: finishuserfileupload(): routine that creates and sends the file to
16319: userspace, probably shouldn't be called directly
16320: 
16321:   docuname: username or courseid of destination for the file
16322:   docudom: domain of user/course of destination for the file
16323:   formname: same as for userfileupload()
16324:   fname: filename (including subdirectories) for the file
16325:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
16326:           if hashref, and context is scantron, will convert csv format to standard format
16327:   allfiles: reference to hash used to store objects found by parser
16328:   codebase: reference to hash used for codebases of java objects found by parser
16329:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16330:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
16331:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
16332:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
16333:   context: if 'overwrite', will move the uploaded file from its temporary location to
16334:             userfiles to facilitate overwriting a previously uploaded file with same name.
16335:   mimetype: reference to scalar to accommodate mime type determined
16336:             from File::MMagic if $parser = parse.
16337: 
16338:  returns either the url of the uploaded file (/uploaded/....) if successful
16339:  and /adm/notfound.html if unsuccessful (or an error message if context 
16340:  was 'overwrite').
16341:  
16342: 
16343: =item *
16344: 
16345: renameuserfile(): renames an existing userfile to a new name
16346: 
16347:   Args:
16348:    docuname: username or courseid of destination for the file
16349:    docudom: domain of user/course of destination for the file
16350:    old: current file name (including any subdirs under userfiles)
16351:    new: desired file name (including any subdirs under userfiles)
16352: 
16353: =item *
16354: 
16355: mkdiruserfile(): creates a directory is a userfiles dir
16356: 
16357:   Args:
16358:    docuname: username or courseid of destination for the file
16359:    docudom: domain of user/course of destination for the file
16360:    dir: dir to create (including any subdirs under userfiles)
16361: 
16362: =item *
16363: 
16364: removeuserfile(): removes a file that exists in userfiles
16365: 
16366:   Args:
16367:    docuname: username or courseid of destination for the file
16368:    docudom: domain of user/course of destination for the file
16369:    fname: filname to delete (including any subdirs under userfiles)
16370: 
16371: =item *
16372: 
16373: removeuploadedurl(): convience function for removeuserfile()
16374: 
16375:   Args:
16376:    url:  a full /uploaded/... url to delete
16377: 
16378: =item * 
16379: 
16380: get_portfile_permissions():
16381:   Args:
16382:     domain: domain of user or course contain the portfolio files
16383:     user: name of user or num of course contain the portfolio files
16384:   Returns:
16385:     hashref of a dump of the proper file_permissions.db
16386:    
16387: 
16388: =item * 
16389: 
16390: get_access_controls():
16391: 
16392: Args:
16393:   current_permissions: the hash ref returned from get_portfile_permissions()
16394:   group: (optional) the group you want the files associated with
16395:   file: (optional) the file you want access info on
16396: 
16397: Returns:
16398:     a hash (keys are file names) of hashes containing
16399:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16400:         values are XML containing access control settings (see below) 
16401: 
16402: Internal notes:
16403: 
16404:  access controls are stored in file_permissions.db as key=value pairs.
16405:     key -> path to file/file_name\0uniqueID:scope_end_start
16406:         where scope -> public,guest,course,group,domains or users.
16407:               end -> UNIX time for end of access (0 -> no end date)
16408:               start -> UNIX time for start of access
16409: 
16410:     value -> XML description of access control
16411:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16412:             <start></start>
16413:             <end></end>
16414: 
16415:             <password></password>  for scope type = guest
16416: 
16417:             <domain></domain>     for scope type = course or group
16418:             <number></number>
16419:             <roles id="">
16420:              <role></role>
16421:              <access></access>
16422:              <section></section>
16423:              <group></group>
16424:             </roles>
16425: 
16426:             <dom></dom>         for scope type = domains
16427: 
16428:             <users>             for scope type = users
16429:              <user>
16430:               <uname></uname>
16431:               <udom></udom>
16432:              </user>
16433:             </users>
16434:            </scope> 
16435:               
16436:  Access data is also aggregated for each file in an additional key=value pair:
16437:  key -> path to file/file_name\0accesscontrol 
16438:  value -> reference to hash
16439:           hash contains key = value pairs
16440:           where key = uniqueID:scope_end_start
16441:                 value = UNIX time record was last updated
16442: 
16443:           Used to improve speed of look-ups of access controls for each file.  
16444:  
16445:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16446: 
16447: =item *
16448: 
16449: modify_access_controls():
16450: 
16451: Modifies access controls for a portfolio file
16452: Args
16453: 1. file name
16454: 2. reference to hash of required changes,
16455: 3. domain
16456: 4. username
16457:   where domain,username are the domain of the portfolio owner 
16458:   (either a user or a course) 
16459: 
16460: Returns:
16461: 1. result of additions or updates ('ok' or 'error', with error message). 
16462: 2. result of deletions ('ok' or 'error', with error message).
16463: 3. reference to hash of any new or updated access controls.
16464: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16465:    key = integer (inbound ID)
16466:    value = uniqueID
16467: 
16468: =item *
16469: 
16470: get_timebased_id():
16471: 
16472: Attempts to get a unique timestamp-based suffix for use with items added to a
16473: course via the Course Editor (e.g., folders, composite pages,
16474: group bulletin boards).
16475: 
16476: Args: (first three required; six others optional)
16477: 
16478: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16479:    docssequence, or name of group
16480: 
16481: 2. keyid (alphanumeric): name of temporary locking key in hash,
16482:    e.g., num, boardids
16483: 
16484: 3. namespace: name of gdbm file used to store suffixes already assigned;
16485:    file will be named nohist_namespace.db
16486: 
16487: 4. cdom: domain of course; default is current course domain from %env
16488: 
16489: 5. cnum: course number; default is current course number from %env
16490: 
16491: 6. idtype: set to concat if an additional digit is to be appended to the
16492:    unix timestamp to form the suffix, if the plain timestamp is already
16493:    in use.  Default is to not do this, but simply increment the unix
16494:    timestamp by 1 until a unique key is obtained.
16495: 
16496: 7. who: holder of locking key; defaults to user:domain for user.
16497: 
16498: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
16499:    retrying); default is 3.
16500: 
16501: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
16502: 
16503: Returns:
16504: 
16505: 1. suffix obtained (numeric)
16506: 
16507: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16508: 
16509: 3. error: contains (localized) error message if an error occurred.
16510: 
16511: 
16512: =back
16513: 
16514: =head2 HTTP Helper Routines
16515: 
16516: =over 4
16517: 
16518: =item *
16519: 
16520: escape() : unpack non-word characters into CGI-compatible hex codes
16521: 
16522: =item *
16523: 
16524: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16525: 
16526: =back
16527: 
16528: =head1 PRIVATE SUBROUTINES
16529: 
16530: =head2 Underlying communication routines (Shouldn't call)
16531: 
16532: =over 4
16533: 
16534: =item *
16535: 
16536: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16537: 
16538: =item *
16539: 
16540: reply() : uses subreply to send a message to remote machine, logs all failures
16541: 
16542: =item *
16543: 
16544: critical() : passes a critical message to another server; if cannot
16545: get through then place message in connection buffer directory and
16546: returns con_delayed, if incapable of saving message, returns
16547: con_failed
16548: 
16549: =item *
16550: 
16551: reconlonc() : tries to reconnect lonc client processes.
16552: 
16553: =back
16554: 
16555: =head2 Resource Access Logging
16556: 
16557: =over 4
16558: 
16559: =item *
16560: 
16561: flushcourselogs() : flush (save) buffer logs and access logs
16562: 
16563: =item *
16564: 
16565: courselog($what) : save message for course in hash
16566: 
16567: =item *
16568: 
16569: courseacclog($what) : save message for course using &courselog().  Perform
16570: special processing for specific resource types (problems, exams, quizzes, etc).
16571: 
16572: =item *
16573: 
16574: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16575: as a PerlChildExitHandler
16576: 
16577: =back
16578: 
16579: =head2 Other
16580: 
16581: =over 4
16582: 
16583: =item *
16584: 
16585: symblist($mapname,%newhash) : update symbolic storage links
16586: 
16587: =back
16588: 
16589: =cut
16590: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>